-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteractivehuman1
More file actions
766 lines (655 loc) · 24.3 KB
/
interactivehuman1
File metadata and controls
766 lines (655 loc) · 24.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
import dash
import matplotlib
from dash import html, dcc, Input, Output
import plotly.graph_objects as go
from PIL import Image
import base64
import io
import matplotlib.pyplot as plt
import pyanatomogram
import pandas as pd
import numpy as np
from plotly.subplots import make_subplots
import math
import matplotlib.patches as mpatches
import matplotlib.colors as mpcolor
import matplotlib.cm as cm
from matplotlib.lines import Line2D
import plotly.express as px
import plotly.io as pio
import dash_bootstrap_components as dbc
from dash import Dash, dash_table
matplotlib.use('Agg')
#Needed Functions
#This function creates a merged dictonary which can be later called as a data frame
#Useful for both creating a anatomy figure and the swimmers plot
#BUT, does not include every single variable in these two data sets, if another variable is needed must add it here
def treatment_process_centered(filename, filename2, filename3):
df = pd.read_csv(filename, sep=',')
df2=pd.read_csv(filename2, sep='\t')
df3=pd.read_csv(filename3, sep='\t')
df=pd.merge(df,df2, on='participant_id', how='inner', suffixes=('', '_df2'))
df=pd.merge(df,df3, on='participant_id', how='inner', suffixes=('', '_df3'))
patient_val = df['participant_id'].tolist()
treatment_val = df['categories'].tolist()
tx_start = df['start_date_dfd'].tolist()
tx_end = df['stop_date_dfd'].tolist()
stop_reason=df['stop_reason'].tolist()
tumor_morph=df['tumor_morphology'].tolist()
drug_type=df['drugs'].tolist()
bio_count = pd.to_numeric(df['biospecimen_total_count'], errors='coerce').tolist()
treat_count = pd.to_numeric(df['treatment_count'], errors='coerce').tolist()
prim_site=df['tumor_primary_site'].tolist()
gender_value=df['gender'].tolist()
tumorornormal=df['tumor_normal'].tolist()
analytetype=df['analyte_type'].tolist()
experimentalstrategy=df['experimental_strategy'].tolist()
ulpfrac=df['ulp_tumor_fraction'].tolist()
df = df.drop_duplicates()
new_dict = {'patient': patient_val,
'treatment': treatment_val,
'tx_start': tx_start,
'tx_end': tx_end,
'stop':stop_reason,
'morph':tumor_morph,
'drug':drug_type,
'biocount':bio_count,
'treatcount':treat_count,
'site':prim_site,
'gender':gender_value,
'tum_nor':tumorornormal,
'analyte':analytetype,
'strategy':experimentalstrategy,
'ulp_tumor':ulpfrac
}
return new_dict
def tableprocess(filename):
df=pd.read_csv(filename, sep='\t')
patient_val = df['participant_id'].tolist()
collectiondate=df['collection_date_dfd'].tolist()
sub_material_type=df['submitted_material_type'].tolist()
og_material_type=df['original_material_type'].tolist()
prim_site=df['primary_site'].tolist()
tiss_site=df['tissue_site'].tolist()
new_dict = {'patient': patient_val,
'site':prim_site,
'collection':collectiondate,
'submaterial':sub_material_type,
'ogmaterial':og_material_type,
'tissue_site':tiss_site}
return new_dict
#generate the y position needed for the swimmer plot
def generate_patientYpos(patient_DF):
"""
Return a dictionary with unique patients as keys, and
y positions as values, for plotting. Assumes the column with
the patient names is called "patient"
"""
patient_ids=list(patient_DF['patient'])
y_pos={}
new_pos=0000
for patient_name in patient_ids:
if patient_name not in y_pos:
new_pos=new_pos+1
y_pos[patient_name]=new_pos
return y_pos
#this function makes the background imaging
def make_figure_with_background(base64_img):
fig = go.Figure()
fig.add_layout_image(
dict(
source=f"data:image/png;base64,{base64_img}",
xref="x",
yref="y",
x=0,
y=600,
sizex=400,
sizey=600,
sizing="stretch",
layer="below"
)
)
fig.update_layout(
width=400,
height=600,
xaxis=dict(visible=False, range=[0, 400]),
yaxis=dict(visible=False, range=[0, 600]),
margin=dict(l=0, r=0, t=0, b=0),
dragmode=False,
clickmode='event+select',
showlegend=False
)
return fig
#Loading in the Data Set
tumordata=pd.DataFrame(treatment_process_centered('Juric_Rapid_Autopsy_MASTER-treatments1.csv', 'Juric_Rapid_Autopsy_MASTER-participants.txt', 'samples.6i2fn.tsv'))
biospecdata=pd.DataFrame(tableprocess('Juric_Rapid_Autopsy_MASTER-biospecimens.txt'))
tumordata['tx_end'] = pd.to_numeric(tumordata['tx_end'], errors='coerce')
xmax = math.ceil(tumordata['tx_end'].max())
patient_pos=generate_patientYpos(tumordata)
drugtype = tumordata['drug'].unique()
patients = tumordata['patient'].unique()
#Data managmenet to get the tumor primary site to be in a workable form in order to automatically plot using pyanatomogram package
site_to_organ = {
'BREAST (C50)': 'breast',
'COLON (C18)': 'colon',
'BRONCHUS AND LUNG (C34)': 'lung',
'CORPUS UTERI (C54)': 'uterus',
'ESOPHAGUS (C15)': 'esophagus',
'GALLBLADDER (C23)': 'gall bladder',
'KIDNEY (C64)': 'kidney',
'LIVER AND INTRAHEPATIC BILE DUCTS (C22)': 'liver',
'LYMPH NODES (C77)': 'lymph node',
'OVARY (C56)': 'ovary',
'PANCREAS (C25)': 'pancreas',
'SKIN (C44)': 'skin',
'STOMACH (C16)': 'stomach',
'THYROID GLAND (C73)': 'thyroid gland',
'PROSTATE GLAND (C61)': 'prostate gland'
}
tumordata['organs'] = tumordata['site'].map(site_to_organ).fillna('Fail')
#DICTONARIES
#these two dictonarys hold the organs and a possible color number for the different organs in the study
#Note-there are more organs in the package
allfemaleorgans = {
'heart': 3, 'lung': 2, 'brain': 18, 'colon': 1, 'liver': 4, 'breast': 5,
'stomach': 6, 'esophagus': 7, 'ovary': 8, 'uterus': 9, 'pancreas': 10,
'lymph node': 11, 'gall bladder': 12, 'thyroid gland': 13, 'kidney': 14,
'uterine cervix': 15, 'bronchus': 16, 'skin': 17
}
allmaleorgans={'heart': 3, 'lung': 2, 'brain': 18, 'colon': 1, 'liver': 4, 'breast': 5,
'stomach': 6, 'esophagus': 7, 'pancreas': 8,
'lymph node': 11, 'gall bladder': 12, 'thyroid gland': 13, 'kidney': 14,
'uterine cervix': 15, 'bronchus': 16, 'skin': 10, 'prostate gland':9
}
#These two dictonarys hold a textbubble and arrow location for each gland
annotationsfemale = {
'lung': ((0, 0), (48, 44)),
'heart': ((0, 10), (52, 48)),
'brain': ((25, 0), (50, 5)),
'colon': ((0,95), (43, 85)),
'liver': ((0, 53), (43, 65)),
'breast': ((100, 30), (62, 50)),
'pancreas': ((100, 62), (51, 70)),
'esophagus': ((80, 20), (51, 40)),
'uterus': ((95, 78), (50.5, 88.5)),
'ovary': ((90, 88), (58, 90.75)),
'stomach': ((93, 50), (62, 64)),
'lymph node': ((75, 0), (56, 27)),
'gall bladder':((0,62),(49,70)),
'thyroid gland':((22,10),(52,31)),
'kidney':((0,85),(45,72)),
'skin':((0,100),(40,110))
}
annotationsmale = {
'lung': ((0, 0), (48, 44)),
'heart': ((0, 10), (52, 48)),
'brain': ((25, 0), (50, 5)),
'colon': ((0,95), (43, 85)),
'liver': ((0, 53), (43, 65)),
'breast': ((100, 30), (62, 50)),
'pancreas': ((100, 62), (51, 70)),
'esophagus': ((80, 20), (51, 40)),
'stomach': ((93, 50), (62, 64)),
'lymph node': ((75, 0), (56, 27)),
'gall bladder':((0,62),(49,70)),
'thyroid gland':((22,10),(52,31)),
'kidney':((0,85),(45,72)),
'skin':((0,100),(40,110)),
'prostate gland':((0,50),(0,10))
}
#These two dictonaries have just a dot, no arrows, best for plotly interactive steps since it is not a tuple
annotationsfemale2 = {
'thyroid gland': (299, 240),
'esophagus': (308, 275),
'lymph node': (325, 222),
'lung': (285, 290),
'heart': (300, 304),
'colon': (270, 465),
'liver': (266, 375),
'breast': (345, 315),
'stomach': (315, 390),
'uterus': (305, 470),
'ovary': (332, 480),
'pancreas': (347, 372),
'gall bladder': (290, 395),
'kidney': (273, 405),
'skin': (255, 553),
'other':(0,0)
}
annotationsmale2={
'thyroid gland': (299, 240),
'esophagus': (308, 275),
'lymph node': (325, 222),
'lung': (285, 290),
'heart': (300, 304),
'colon': (270, 465),
'liver': (266, 375),
'breast': (345, 315),
'stomach': (312, 395),
'pancreas': (347, 372),
'gall bladder': (290, 395),
'kidney': (273, 405),
'skin': (255, 553),
'other':(0,0),
'prostate gland':(304,495)
}
#this creates the original background image before a person has chosen a patient, defaults to female but could simply change to male if that is a need
fig,ax=plt.subplots(figsize=(6,10))
scatter_fig = go.Figure()
anatomogram2 = pyanatomogram.Anatomogram('homo_sapiens.female')
anatomogram2.highlight_tissues(allfemaleorgans, cmap='gist_heat_r')
anatomogram2.to_matplotlib(ax=ax)
for organ, ((x_text, y_text), (x_arrow, y_arrow)) in annotationsfemale.items():
ax.annotate(
organ.capitalize(),
xy=(x_arrow, y_arrow),
xytext=(x_text, y_text),
arrowprops=dict(facecolor='black', arrowstyle='->'),
bbox=dict(boxstyle='round,pad=0.3', fc='white', ec='black', lw=1),
fontsize=8
)
buf = io.BytesIO()
plt.tight_layout()
plt.savefig(buf, format="png")
plt.close(fig)
buf.seek(0)
img = Image.open(buf)
w, h = img.size
buffer = io.BytesIO()
img.save(buffer, format="PNG")
encoded_image = base64.b64encode(buffer.getvalue()).decode()
scatter_fig = go.Figure()
scatter_fig.add_layout_image(
dict(
source=f"data:image/png;base64,{encoded_image}",
xref='x',
yref='y',
x=0,
y=h,
sizex=w,
sizey=h,
sizing="stretch",
layer="below"
)
)
for organ, (x, y) in annotationsfemale2.items():
scatter_fig.add_trace(go.Scatter(
x=[x],
y=[h - y],
mode="markers",
marker=dict(size=5, color="black"),
name=organ,
text=organ,
hoverinfo="text",
customdata=[organ]
))
scatter_fig.update_layout(
showlegend=False,
xaxis=dict(visible=False, range=[0, w]),
yaxis=dict(visible=False, range=[0, h]),
margin=dict(l=0, r=0, t=0, b=0),
clickmode='event+select'
)
#Dash App Creationg occurs here
app = dash.Dash(external_stylesheets=[dbc.themes.CYBORG])
app.title = "Interactive Organ Data"
app.layout = dbc.Container([
dbc.Row([
dbc.Col(html.H1("Cohort and Patient Specific Autopsy Data", className="text-center text-primary mb-4"))
]),
dbc.Row([
dbc.Col(html.H2("Select a Patient to View Information", className="text-secondary mb-3"))
]),
dbc.Row([
dbc.Col(
dcc.Dropdown(
id='patient-dropdown',
options=[{'label': pid, 'value': pid} for pid in sorted(tumordata['patient'].unique())],
placeholder="Select a patient",
style={'backgroundColor': 'transparent','color': 'blue', 'border': '1px solid white',}
),
width=6,
style={'backgroundColor': 'transparent'}
)
]),
dbc.Row([
dbc.Col(dcc.Graph(id='swimmer-plot'), width=12)
], className="mb-4"),
dbc.Row([
dbc.Col(
dash_table.DataTable(
id='tableinfo',
columns=[],
data=[],
style_table={'overflowX': 'auto'},
style_cell={'textAlign': 'left', 'minWidth': '100px', 'width': '150px', 'maxWidth': '200px'},
page_size=10
),
width=12,
style={'backgroundColor': 'transparent'}
)
], className="mb-4"),
dbc.Row([
dbc.Col(
dcc.Graph(id='anatomy-plot', figure=scatter_fig),
width=6,
style={'backgroundColor': 'transparent'}
),
dbc.Col(
dcc.Graph(id='organ-data-plot'),
width=6,
style={'backgroundColor': 'transparent'}
)
])
], fluid=True, style={'backgroundColor': 'transparent'})
@app.callback(
Output('anatomy-plot', 'figure'),
Input('patient-dropdown', 'value')
)
def update_anatomy_figure(selected_patient):
if not selected_patient:
return make_figure_with_background(encoded_image)
buf = io.BytesIO()
patient_info=tumordata[tumordata['patient']==selected_patient]
if patient_info.empty:
return make_figure_with_background(encoded_image)
gender = patient_info.iloc[0]['gender'].lower()
fig, ax = plt.subplots(figsize=(6, 10))
if gender == 'female':
anatomogram = pyanatomogram.Anatomogram('homo_sapiens.female')
patient_organs = tumordata[tumordata['patient'] == selected_patient]['organs'].unique().tolist()
highlight_organs = {organ: allfemaleorgans[organ] for organ in patient_organs if organ in allfemaleorgans}
anatomogram.highlight_tissues(highlight_organs, cmap='spring')
anatomogram.to_matplotlib(ax=ax)
else:
anatomogram = pyanatomogram.Anatomogram('homo_sapiens.male')
patient_organs = tumordata[tumordata['patient'] == selected_patient]['organs'].unique().tolist()
highlight_organs = {organ: allmaleorgans[organ] for organ in patient_organs if organ in allmaleorgans}
anatomogram.highlight_tissues(highlight_organs, cmap='spring')
anatomogram.to_matplotlib(ax=ax)
plt.savefig(buf, format='png')
plt.close(fig)
buf.seek(0)
img = Image.open(buf)
w, h = img.size
img_str = base64.b64encode(buf.getvalue()).decode()
fig_out = go.Figure()
fig_out.add_layout_image(
dict(
source=f"data:image/png;base64,{img_str}",
xref="x", yref="y",
x=0, y=h,
sizex=w, sizey=h,
sizing="stretch",
layer="below"
)
)
if gender == 'female':
for organ, (x, y_pixel) in annotationsfemale2.items():
if organ in highlight_organs:
fig_out.add_trace(go.Scatter(
x=[x],
y=[h - y_pixel],
mode='markers',
marker=dict(size=8, color='black'),
name=organ,
text=organ,
hoverinfo='text',
customdata=[organ]
))
else:
for organ, (x, y_pixel) in annotationsmale2.items():
if organ in highlight_organs:
fig_out.add_trace(go.Scatter(
x=[x],
y=[h - y_pixel],
mode='markers',
marker=dict(size=8, color='black'),
name=organ,
text=organ,
hoverinfo='text',
customdata=[organ]
))
fig_out.update_layout(
width=w,
height=h,
xaxis=dict(visible=False, range=[0, w]),
yaxis=dict(visible=False, range=[0, h]),
margin=dict(l=0, r=0, t=0, b=0),
dragmode=False,
clickmode='event+select',
showlegend=False,
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
font=dict(color='white')
)
return fig_out
@app.callback(
Output('organ-data-plot', 'figure'),
[Input('anatomy-plot', 'clickData'),
Input('patient-dropdown', 'value')]
)
def display_organ_data(clickData, selected_patient):
if clickData is None or selected_patient is None:
return go.Figure(layout=go.Layout(title="Click on an organ to view tumor information"))
try:
organ = clickData['points'][0].get('customdata')
if organ is None:
raise ValueError("No valid organ selected.")
except (IndexError, KeyError, TypeError, ValueError):
return go.Figure(layout=go.Layout(title="Invalid click. Please click on an organ marker."))
# Patient data
patient_data = tumordata[tumordata['patient'] == selected_patient]
if patient_data.empty:
return go.Figure(layout=go.Layout(title=f"No data for patient {selected_patient}"))
# Cohort data for the selected organ
filtered_df = tumordata[tumordata['organs'] == organ].copy()
# Ensure numeric
filtered_df['biocount'] = pd.to_numeric(filtered_df['biocount'], errors='coerce')
filtered_df['treatcount'] = pd.to_numeric(filtered_df['treatcount'], errors='coerce')
filtered_df = filtered_df.dropna(subset=['biocount', 'treatcount'])
if filtered_df.empty:
return go.Figure(layout=go.Layout(title=f"No tumor data available for {organ.capitalize()}"))
tumor_counts = filtered_df['tum_nor'].value_counts()
tumorspec = patient_data['tum_nor'].value_counts()
analyte_counts = filtered_df['analyte'].value_counts()
analytespec = patient_data['analyte'].value_counts()
exper_counts=filtered_df['strategy'].value_counts()
experspec=patient_data['strategy'].value_counts()
if tumor_counts.empty and tumorspec.empty:
return go.Figure(layout=go.Layout(title=f"No tumor categories found for {organ.capitalize()}"))
fig = make_subplots(
rows=3, cols=2,
subplot_titles=("Patient Tumor vs Normal", "Cohort Tumor vs Normal", "Patient Analyte Types", "Cohort Analyte Types", "Patient Strategies", "Cohort Strategies"),
specs=[[{"type": "domain"}, {"type": "domain"}], [{"type": "domain"}, {"type": "domain"}],[{"type": "domain"}, {"type": "domain"}]]
)
#tumor pie chart
if not tumorspec.empty:
fig.add_trace(
go.Pie(
labels=[label.capitalize() for label in tumorspec.index],
values=tumorspec.values,
name='Patient Tumor vs Normal',
marker=dict(colors=['lavender', 'mediumslateblue'])
),
row=1, col=1
)
if not tumor_counts.empty:
fig.add_trace(
go.Pie(
labels=[label.capitalize() for label in tumor_counts.index],
values=tumor_counts.values,
name='Cohort Tumor vs Normal',
marker=dict(colors=['lavender', 'mediumslateblue'])
),
row=1, col=2
)
if not analyte_counts.empty:
fig.add_trace(
go.Pie(
labels=analyte_counts.index,
values=analyte_counts.values,
name='Cohort Analyte Types',
marker=dict(colors=['lightblue', 'blue'])
),
row=2, col=2
)
if not analytespec.empty:
fig.add_trace(
go.Pie(
labels=analytespec.index,
values=analytespec.values,
name='Patient Analyte Types',
marker=dict(colors=['lightblue', 'blue'])
),
row=2, col=1
)
if not exper_counts.empty:
fig.add_trace(
go.Pie(
labels=exper_counts.index,
values=exper_counts.values,
name='Cohort Strategies',
marker=dict(colors=['lightpink', 'palevioletred'])
),
row=3, col=2
)
if not experspec.empty:
fig.add_trace(
go.Pie(
labels=experspec.index,
values=experspec.values,
name='Patient Strategies',
marker=dict(colors=['lightpink', 'palevioletred'])
),
row=3, col=1
)
fig.update_layout(
title_text=f"Tumor Data for {organ.capitalize()}",
title_pad=dict(t=60),
height=500,
width=1000,
showlegend=False,
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
font=dict(color='white')
)
return fig
# Fallback (default empty plot)
return go.Figure(layout=go.Layout(title="Click on an organ to view tumor information"))
@app.callback(
Output('swimmer-plot', 'figure'),
Input('patient-dropdown', 'value')
)
def update_swimmer_figure(selected_patient):
if not selected_patient:
return go.Figure(layout=go.Layout(title="Select a patient to view treatment timeline"))
plt.rcParams.update({'font.size': 14})
plt.rcParams['svg.fonttype'] = 'none'
pio.templates.default = "seaborn"
fig = go.Figure()
patient_data = tumordata[tumordata['patient'] == selected_patient]
if patient_data.empty:
return go.Figure(layout=go.Layout(title="No data found for selected patient"))
unique_drugs = sorted(patient_data['drug'].dropna().astype(str).unique())
color_list = px.colors.qualitative.Alphabet
while len(color_list) < len(unique_drugs):
color_list += color_list
drug_color_map = {drug: color_list[i % len(color_list)] for i, drug in enumerate(unique_drugs)}
added_drug_legends = set()
for idx, row in patient_data.iterrows():
drug = row['drug']
color = drug_color_map.get(drug, 'lightgray')
show_legend = drug not in added_drug_legends
if show_legend:
added_drug_legends.add(drug)
fig.add_trace(go.Scatter(
x=[row['tx_start'], row['tx_end']],
y=[row['patient'], row['patient']],
mode='lines',
line=dict(color=color, width=10),
hoverinfo='text',
name=drug,
text=f"Patient: {row['patient']}<br>Drug: {row['drug']}<br>Start: {row['tx_start']}<br>End: {row['tx_end']}<br>Stop: {row['stop']}, <br>Morph: {row['morph']}",
showlegend=show_legend
))
stop_marker_styles = {
'Progression and relapse': dict(color='red', symbol='circle', size=10),
'Completion of standard course': dict(color='black', symbol='triangle-down', size=10),
'Toxicity': dict(color='green', symbol='triangle-down', size=10),
'Other': dict(color='gray', symbol='circle', size=10)
}
for idx, row in patient_data.iterrows():
stop = row['stop']
if stop in stop_marker_styles:
style = stop_marker_styles[stop]
fig.add_trace(go.Scatter(
x=[row['tx_end']],
y=[row['patient']],
mode='markers',
marker=dict(color=style['color'], symbol=style['symbol'], size=style['size']),
name=stop,
hoverinfo='text',
text=f"Stop Reason: {row['stop']}<br>Morph: {row['morph']}",
showlegend=False
))
morph_options = patient_data['morph'].dropna().unique()
buttons = []
for morph in morph_options:
visibility = [morph.lower() in str(trace.text).lower() for trace in fig.data]
buttons.append(dict(
label=morph,
method='update',
args=[{'visible': visibility},
{'title': f'Drug Progression in {selected_patient} for {morph}'}]
))
fig.update_layout(
title=dict(
text=f'Drug Progression in {selected_patient}',
x=0.5,
xanchor='center',
font=dict(size=20)
),
xaxis_title='Time (Days)',
yaxis_title='Patient',
yaxis=dict(type='category'),
legend_title='Drug / Stop Reason',
height=400,
hovermode='closest',
updatemenus=[dict(
active=0,
buttons=buttons,
direction="down",
showactive=True,
x=0.0,
y=1,
xanchor="left",
yanchor="top"
)] if buttons else []
)
return fig
@app.callback(
Output('tableinfo', 'columns'),
Output('tableinfo', 'data'),
Input('patient-dropdown', 'value')
)
def createtable(selected_patient):
if selected_patient is None:
return [],[]
patient_data = biospecdata[biospecdata['patient'] == selected_patient]
if patient_data.empty:
return [],[]
displaycolumns=['patient', 'ogmaterial', 'submaterial', 'collection', 'tissue_site']
patient_data=patient_data[displaycolumns]
custom_column={
'patient':'Patient ID',
'ogmaterial':'Orignal Material Type',
'submaterial':'Submitted Material Type',
'collection':'Collection Date',
'tissue_site':'Sample Location'
}
columns=[{'name':custom_column[col],'id':col} for col in patient_data.columns]
data=patient_data.to_dict('records')
return columns,data
if __name__ == '__main__':
app.run(debug=True)