Arts-of-coding commited on
Commit
d46f929
1 Parent(s): 75649f8

Delete dash_plotly_QC_scRNA.py

Browse files
Files changed (1) hide show
  1. dash_plotly_QC_scRNA.py +0 -482
dash_plotly_QC_scRNA.py DELETED
@@ -1,482 +0,0 @@
1
- # Dash app to visualize scRNA-seq data quality control metrics from scanpy objects
2
- # Shoutout to Coding-with-Adam for the initial template of the project:
3
- # https://github.com/Coding-with-Adam/Dash-by-Plotly/blob/master/Dash%20Components/Graph/dash-graph.py
4
-
5
- import dash
6
- from dash import dcc, html, Output, Input
7
- import plotly.express as px
8
- import dash_callback_chain
9
- import yaml
10
- import polars as pl
11
- import os
12
- pl.enable_string_cache(False)
13
-
14
- # Set custom resolution for plots:
15
- config_fig = {
16
- 'toImageButtonOptions': {
17
- 'format': 'svg',
18
- 'filename': 'custom_image',
19
- 'height': 600,
20
- 'width': 700,
21
- 'scale': 1,
22
- }
23
- }
24
- from adlfs import AzureBlobFileSystem
25
- mountpount=os.environ['AZURE_MOUNT_POINT'],
26
- AZURE_STORAGE_ACCESS_KEY=os.getenv('AZURE_STORAGE_ACCESS_KEY')
27
- AZURE_STORAGE_ACCOUNT=os.getenv('AZURE_STORAGE_ACCOUNT')
28
-
29
- # Load in config file
30
- config_path = "./data/config.yaml"
31
-
32
- # Add the read-in data from the yaml file
33
- def read_config(filename):
34
- with open(filename, 'r') as yaml_file:
35
- config = yaml.safe_load(yaml_file)
36
- return config
37
-
38
- config = read_config(config_path)
39
- path_parquet = config.get("path_parquet")
40
- col_batch = config.get("col_batch")
41
- col_features = config.get("col_features")
42
- col_counts = config.get("col_counts")
43
- col_mt = config.get("col_mt")
44
-
45
- filepath = f"az://{path_parquet}"
46
-
47
- storage_options={'account_name': AZURE_STORAGE_ACCOUNT, 'account_key': AZURE_STORAGE_ACCESS_KEY,'anon': False}
48
- #azfs = AzureBlobFileSystem(**storage_options )
49
-
50
- # Load in multiple dataframes
51
- df = pl.read_parquet(filepath, storage_options=storage_options)
52
-
53
- # Setup the app
54
- external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
55
- app = dash.Dash(__name__, external_stylesheets=external_stylesheets) #, requests_pathname_prefix='/dashboard1/'
56
-
57
- #df = pl.read_parquet(filepath,storage_options=storage_options)
58
- #df = pl.DataFrame()
59
- #abfs = AzureBlobFileSystem(account_name=accountname,account_key=accountkey)
60
- #df = df.rename({"__index_level_0__": "Unnamed: 0"})
61
-
62
- #df1 = pl.read_parquet(filepath, storage_options=storage_options)
63
-
64
- #df2 = pl.read_parquet(f"az://data10xflex/{dataset_chosen}.parquet", storage_options=storage_options)
65
-
66
- #tab0_content = html.Div([
67
- # html.Label("Dataset chosen"),
68
- # dcc.Dropdown(id='dpdn1', value="corg/10xflexcorg_umap_clusres", multi=False,
69
- # options=["corg/10xflexcorg_umap_clusres","d1011/10xflexd1011_umap_clusres"])
70
- #])
71
-
72
- #@app.callback(
73
- # Input(component_id='dpdn1', component_property='value')
74
- #)
75
-
76
- #def update_filepath(dpdn1):
77
- # global df
78
- # if str(f"az://data10xflex/{dpdn1}.parquet") != str(filepath):
79
- # print("not identical filepath, chosing other")
80
- # df2 = pl.read_parquet(f"az://data10xflex/{dpdn1}.parquet", storage_options=storage_options)
81
- # df = df2
82
- # return
83
-
84
- #df = pl.read_parquet(filepath, storage_options=storage_options)
85
- min_value = df[col_features].min()
86
- max_value = df[col_features].max()
87
-
88
- min_value_2 = df[col_counts].min()
89
- min_value_2 = round(min_value_2)
90
- max_value_2 = df[col_counts].max()
91
- max_value_2 = round(max_value_2)
92
-
93
- min_value_3 = df[col_mt].min()
94
- min_value_3 = round(min_value_3, 1)
95
- max_value_3 = df[col_mt].max()
96
- max_value_3 = round(max_value_3, 1)
97
-
98
- # Loads in the conditions specified in the yaml file
99
-
100
- # Note: Future version perhaps all values from a column in the dataframe of the parquet file
101
- # Note 2: This could also be a tsv of the categories and own specified colors
102
- #conditions = df[col_batch].unique().to_list()
103
- # Create the first tab content
104
- # Add Sliders for three QC params: N genes by counts, total amount of reads and pct MT reads
105
-
106
- tab1_content = html.Div([
107
- html.Label("Column chosen"),
108
- dcc.Dropdown(id='dpdn2', value="batch", multi=False,
109
- options=df.columns),
110
- html.Label("N Genes by Counts"),
111
- dcc.RangeSlider(
112
- id='range-slider-1',
113
- step=250,
114
- value=[min_value, max_value],
115
- marks={i: str(i) for i in range(min_value, max_value + 1, 250)},
116
- ),
117
- dcc.Input(id='min-slider-1', type='number', value=min_value, debounce=True),
118
- dcc.Input(id='max-slider-1', type='number', value=max_value, debounce=True),
119
- html.Label("Total Counts"),
120
- dcc.RangeSlider(
121
- id='range-slider-2',
122
- step=7500,
123
- value=[min_value_2, max_value_2],
124
- marks={i: str(i) for i in range(min_value_2, max_value_2 + 1, 7500)},
125
- ),
126
- dcc.Input(id='min-slider-2', type='number', value=min_value_2, debounce=True),
127
- dcc.Input(id='max-slider-2', type='number', value=max_value_2, debounce=True),
128
- html.Label("Percent Mitochondrial Genes"),
129
- dcc.RangeSlider(
130
- id='range-slider-3',
131
- step=5,
132
- min=0,
133
- max=100,
134
- value=[min_value_3, max_value_3],
135
- ),
136
- dcc.Input(id='min-slider-3', type='number', value=min_value_3, debounce=True),
137
- dcc.Input(id='max-slider-3', type='number', value=max_value_3, debounce=True),
138
- html.Div([
139
- dcc.Graph(id='pie-graph', figure={}, className='four columns',config=config_fig),
140
- dcc.Graph(id='my-graph', figure={}, clickData=None, hoverData=None,
141
- className='four columns',config=config_fig
142
- ),
143
- dcc.Graph(id='scatter-plot', figure={}, className='four columns',config=config_fig)
144
- ]),
145
- html.Div([
146
- dcc.Graph(id='scatter-plot-2', figure={}, className='four columns',config=config_fig)
147
- ]),
148
- html.Div([
149
- dcc.Graph(id='scatter-plot-3', figure={}, className='four columns',config=config_fig)
150
- ]),
151
- html.Div([
152
- dcc.Graph(id='scatter-plot-4', figure={}, className='four columns',config=config_fig)
153
- ]),
154
- ])
155
-
156
- # Create the second tab content with scatter-plot-5 and scatter-plot-6
157
- tab2_content = html.Div([
158
- html.Div([
159
- html.Label("S-cycle genes"),
160
- dcc.Dropdown(id='dpdn3', value="MCM5", multi=False,
161
- options=[
162
- "MCM5",
163
- "PCNA",
164
- "TYMS",
165
- "FEN1",
166
- "MCM2",
167
- "MCM4",
168
- "RRM1",
169
- "UNG",
170
- "GINS2",
171
- "MCM6",
172
- "CDCA7",
173
- "DTL",
174
- "PRIM1",
175
- "UHRF1",
176
- "MLF1IP",
177
- "HELLS",
178
- "RFC2",
179
- "RPA2",
180
- "NASP",
181
- "RAD51AP1",
182
- "GMNN",
183
- "WDR76",
184
- "SLBP",
185
- "CCNE2",
186
- "UBR7",
187
- "POLD3",
188
- "MSH2",
189
- "ATAD2",
190
- "RAD51",
191
- "RRM2",
192
- "CDC45",
193
- "CDC6",
194
- "EXO1",
195
- "TIPIN",
196
- "DSCC1",
197
- "BLM",
198
- "CASP8AP2",
199
- "USP1",
200
- "CLSPN",
201
- "POLA1",
202
- "CHAF1B",
203
- "BRIP1",
204
- "E2F8"
205
- ]),
206
- html.Label("G2M-cycle genes"),
207
- dcc.Dropdown(id='dpdn4', value="TOP2A", multi=False,
208
- options=[
209
- 'HMGB2', 'CDK1', 'NUSAP1', 'UBE2C', 'BIRC5', 'TPX2', 'TOP2A', 'NDC80', 'CKS2', 'NUF2', 'CKS1B', 'MKI67', 'TMPO', 'CENPF', 'TACC3', 'FAM64A', 'SMC4', 'CCNB2', 'CKAP2L', 'CKAP2', 'AURKB', 'BUB1', 'KIF11', 'ANP32E', 'TUBB4B', 'GTSE1', 'KIF20B', 'HJURP', 'CDCA3', 'HN1', 'CDC20', 'TTK', 'CDC25C', 'KIF2C', 'RANGAP1', 'NCAPD2', 'DLGAP5', 'CDCA2', 'CDCA8', 'ECT2', 'KIF23', 'HMMR', 'AURKA', 'PSRC1', 'ANLN', 'LBR', 'CKAP5',
210
- 'CENPE', 'CTCF', 'NEK2', 'G2E3', 'GAS2L3', 'CBX5', 'CENPA'
211
- ]),
212
- ]),
213
- html.Div([
214
- dcc.Graph(id='scatter-plot-5', figure={}, className='three columns',config=config_fig)
215
- ]),
216
- html.Div([
217
- dcc.Graph(id='scatter-plot-6', figure={}, className='three columns',config=config_fig)
218
- ]),
219
- html.Div([
220
- dcc.Graph(id='scatter-plot-7', figure={}, className='three columns',config=config_fig)
221
- ]),
222
- html.Div([
223
- dcc.Graph(id='scatter-plot-8', figure={}, className='three columns',config=config_fig)
224
- ]),
225
- ])
226
-
227
- # Create the second tab content with scatter-plot-5 and scatter-plot-6
228
- tab3_content = html.Div([
229
- html.Div([
230
- html.Label("UMAP condition 1"),
231
- dcc.Dropdown(id='dpdn5', value="batch", multi=False,
232
- options=df.columns),
233
- html.Label("UMAP condition 2"),
234
- dcc.Dropdown(id='dpdn6', value="n_genes_by_counts", multi=False,
235
- options=df.columns),
236
- html.Div([
237
- dcc.Graph(id='scatter-plot-9', figure={}, className='four columns',config=config_fig)
238
- ]),
239
- html.Div([
240
- dcc.Graph(id='scatter-plot-10', figure={}, className='four columns',config=config_fig)
241
- ]),
242
- html.Div([
243
- dcc.Graph(id='scatter-plot-11', figure={}, className='four columns',config=config_fig)
244
- ]),
245
- html.Div([
246
- dcc.Graph(id='my-graph2', figure={}, clickData=None, hoverData=None,
247
- className='four columns',config=config_fig
248
- )
249
- ]),
250
- ]),
251
- ])
252
- # html.Div([
253
- # dcc.Graph(id='scatter-plot-12', figure={}, className='four columns',config=config_fig)
254
- # ]),
255
-
256
-
257
- tab4_content = html.Div([
258
- html.Div([
259
- html.Label("Multi gene"),
260
- dcc.Dropdown(id='dpdn7', value=["PAX6","TP63","S100A9"], multi=True,
261
- options=df.columns),
262
- ]),
263
- html.Div([
264
- dcc.Graph(id='scatter-plot-12', figure={}, className='four columns',config=config_fig)
265
- ]),
266
- ])
267
-
268
- # Define the tabs layout
269
- app.layout = html.Div([
270
- dcc.Tabs(id='tabs', style= {'width': 600,
271
- 'font-size': '100%',
272
- 'height': 50}, value='tab1',children=[
273
- #dcc.Tab(label='Dataset', value='tab0', children=tab0_content),
274
- dcc.Tab(label='QC', value='tab1', children=tab1_content),
275
- dcc.Tab(label='Cell cycle', value='tab2', children=tab2_content),
276
- dcc.Tab(label='Custom', value='tab3', children=tab3_content),
277
- dcc.Tab(label='Multi dot', value='tab4', children=tab4_content),
278
- ]),
279
- ])
280
-
281
- # Define the circular callback
282
- @app.callback(
283
- Output("min-slider-1", "value"),
284
- Output("max-slider-1", "value"),
285
- Output("min-slider-2", "value"),
286
- Output("max-slider-2", "value"),
287
- Output("min-slider-3", "value"),
288
- Output("max-slider-3", "value"),
289
- Input("min-slider-1", "value"),
290
- Input("max-slider-1", "value"),
291
- Input("min-slider-2", "value"),
292
- Input("max-slider-2", "value"),
293
- Input("min-slider-3", "value"),
294
- Input("max-slider-3", "value"),
295
- )
296
- def circular_callback(min_1, max_1, min_2, max_2, min_3, max_3):
297
- return min_1, max_1, min_2, max_2, min_3, max_3
298
-
299
- @app.callback(
300
- Output('range-slider-1', 'value'),
301
- Output('range-slider-2', 'value'),
302
- Output('range-slider-3', 'value'),
303
- Input('min-slider-1', 'value'),
304
- Input('max-slider-1', 'value'),
305
- Input('min-slider-2', 'value'),
306
- Input('max-slider-2', 'value'),
307
- Input('min-slider-3', 'value'),
308
- Input('max-slider-3', 'value'),
309
- )
310
- def update_slider_values(min_1, max_1, min_2, max_2, min_3, max_3):
311
- return [min_1, max_1], [min_2, max_2], [min_3, max_3]
312
-
313
- @app.callback(
314
- Output(component_id='my-graph', component_property='figure'),
315
- Output(component_id='pie-graph', component_property='figure'),
316
- Output(component_id='scatter-plot', component_property='figure'),
317
- Output(component_id='scatter-plot-2', component_property='figure'),
318
- Output(component_id='scatter-plot-3', component_property='figure'),
319
- Output(component_id='scatter-plot-4', component_property='figure'), # Add this new scatter plot
320
- Output(component_id='scatter-plot-5', component_property='figure'),
321
- Output(component_id='scatter-plot-6', component_property='figure'),
322
- Output(component_id='scatter-plot-7', component_property='figure'),
323
- Output(component_id='scatter-plot-8', component_property='figure'),
324
- Output(component_id='scatter-plot-9', component_property='figure'),
325
- Output(component_id='scatter-plot-10', component_property='figure'),
326
- Output(component_id='scatter-plot-11', component_property='figure'),
327
- Output(component_id='scatter-plot-12', component_property='figure'),
328
- Output(component_id='my-graph2', component_property='figure'),
329
- Input(component_id='dpdn2', component_property='value'),
330
- Input(component_id='dpdn3', component_property='value'),
331
- Input(component_id='dpdn4', component_property='value'),
332
- Input(component_id='dpdn5', component_property='value'),
333
- Input(component_id='dpdn6', component_property='value'),
334
- Input(component_id='dpdn7', component_property='value'),
335
- Input(component_id='range-slider-1', component_property='value'),
336
- Input(component_id='range-slider-2', component_property='value'),
337
- Input(component_id='range-slider-3', component_property='value')
338
- )
339
-
340
- def update_graph_and_pie_chart(col_chosen, s_chosen, g2m_chosen, condition1_chosen, condition2_chosen, condition3_chosen, range_value_1, range_value_2, range_value_3): #batch_chosen,
341
- batch_chosen = df[col_chosen].unique().to_list()
342
- dff = df.filter(
343
- (pl.col(col_chosen).cast(str).is_in(batch_chosen)) &
344
- (pl.col(col_features) >= range_value_1[0]) &
345
- (pl.col(col_features) <= range_value_1[1]) &
346
- (pl.col(col_counts) >= range_value_2[0]) &
347
- (pl.col(col_counts) <= range_value_2[1]) &
348
- (pl.col(col_mt) >= range_value_3[0]) &
349
- (pl.col(col_mt) <= range_value_3[1])
350
- )
351
-
352
- #Drop categories that are not in the filtered data
353
- dff = dff.with_columns(dff[col_chosen].cast(pl.Categorical))
354
-
355
- dff = dff.sort(col_chosen)
356
-
357
- # Plot figures
358
- fig_violin = px.violin(data_frame=dff, x=col_chosen, y=col_features, box=True, points="all",
359
- color=col_chosen, hover_name=col_chosen,template="seaborn")
360
-
361
- # Cache commonly used subexpressions
362
- total_count = pl.lit(len(dff))
363
- category_counts = dff.group_by(col_chosen).agg(pl.col(col_chosen).count().alias("count"))
364
- category_counts = category_counts.with_columns(((pl.col("count") / total_count * 100).round(decimals=2)).alias("normalized_count"))
365
-
366
- # Sort the dataframe
367
- #category_counts = category_counts.sort(col_chosen) does not work check if the names are different ...
368
-
369
- # Display the result
370
- total_cells = total_count # Calculate total number of cells
371
- pie_title = f'Percentage of Total Cells: {total_cells}' # Include total cells in the title
372
-
373
- # Calculate the mean expression
374
-
375
- # Melt wide format DataFrame into long format
376
- # Specify batch column as string type and gene columns as float type
377
- list_conds = condition3_chosen
378
- list_conds += [col_chosen]
379
- dff_pre = dff.select(list_conds)
380
-
381
- # Melt wide format DataFrame into long format
382
- dff_long = dff_pre.melt(id_vars=col_chosen, variable_name="Gene", value_name="Mean expression")
383
-
384
- # Calculate the mean expression levels for each gene in each region
385
- expression_means = dff_long.lazy().group_by([col_chosen, "Gene"]).agg(pl.mean("Mean expression")).collect()
386
-
387
- # Calculate the percentage total expressed
388
- dff_long1 = dff_pre.melt(id_vars=col_chosen, variable_name="Gene")#.group_by(pl.all()).agg(pl.len())
389
- count = 1
390
- dff_long2 = dff_long1.with_columns(pl.lit(count).alias("len"))
391
- dff_long3 = dff_long2.filter(pl.col("value") > 0).group_by([col_chosen, "Gene"]).agg(pl.sum("len").alias("len"))
392
- dff_long4 = dff_long2.group_by([col_chosen, "Gene"]).agg(pl.sum("len").alias("total"))
393
- dff_5 = dff_long4.join(dff_long3, on=[col_chosen,"Gene"], how="outer")
394
- result = dff_5.select([
395
- pl.when((pl.col('len').is_not_null()) & (pl.col('total').is_not_null()))
396
- .then(pl.col('len') / pl.col('total')*100)
397
- .otherwise(None).alias("%"),
398
- ])
399
- result = result.with_columns(pl.col("%").fill_null(100))
400
- dff_5[["percentage"]] = result[["%"]]
401
- dff_5 = dff_5.select(pl.col(col_chosen,"Gene","percentage"))
402
-
403
- # Final part to join the percentage expressed and mean expression levels
404
- # TO DO
405
- expression_means = expression_means.join(dff_5, on=[col_chosen,"Gene"], how="inner")
406
-
407
- # Order the dataframe on ascending categories
408
- expression_means = expression_means.sort(col_chosen, descending=True)
409
-
410
- #expression_means = expression_means.select(["batch", "Gene", "Expression"] + condition3_chosen)
411
- category_counts = category_counts.sort(col_chosen)
412
-
413
- fig_pie = px.pie(category_counts, values="normalized_count", names=col_chosen, labels=col_chosen, hole=.3, title=pie_title, template="seaborn")
414
-
415
- #labels = category_counts[col_chosen].to_list()
416
- #values = category_counts["normalized_count"].to_list()
417
-
418
- # Create the scatter plots
419
- fig_scatter = px.scatter(data_frame=dff, x='X_umap-0', y='X_umap-1', color=col_chosen,
420
- labels={'X_umap-0': 'umap1' , 'X_umap-1': 'umap2'},
421
- hover_name='batch',template="seaborn")
422
-
423
- fig_scatter_2 = px.scatter(data_frame=dff, x='X_umap-0', y='X_umap-1', color=col_mt,
424
- labels={'X_umap-0': 'umap1' , 'X_umap-1': 'umap2'},
425
- hover_name='batch',template="seaborn")
426
-
427
- fig_scatter_3 = px.scatter(data_frame=dff, x='X_umap-0', y='X_umap-1', color=col_features,
428
- labels={'X_umap-0': 'umap1' , 'X_umap-1': 'umap2'},
429
- hover_name='batch',template="seaborn")
430
-
431
-
432
- fig_scatter_4 = px.scatter(data_frame=dff, x='X_umap-0', y='X_umap-1', color=col_counts,
433
- labels={'X_umap-0': 'umap1' , 'X_umap-1': 'umap2'},
434
- hover_name='batch',template="seaborn")
435
-
436
- fig_scatter_5 = px.scatter(data_frame=dff, x='X_umap-0', y='X_umap-1', color=s_chosen,
437
- labels={'X_umap-0': 'umap1' , 'X_umap-1': 'umap2'},
438
- hover_name='batch', title="S-cycle gene:",template="seaborn")
439
-
440
- fig_scatter_6 = px.scatter(data_frame=dff, x='X_umap-0', y='X_umap-1', color=g2m_chosen,
441
- labels={'X_umap-0': 'umap1' , 'X_umap-1': 'umap2'},
442
- hover_name='batch', title="G2M-cycle gene:",template="seaborn")
443
-
444
- fig_scatter_7 = px.scatter(data_frame=dff, x='X_umap-0', y='X_umap-1', color="S_score",
445
- labels={'X_umap-0': 'umap1' , 'X_umap-1': 'umap2'},
446
- hover_name='batch', title="S score:",template="seaborn")
447
-
448
- fig_scatter_8 = px.scatter(data_frame=dff, x='X_umap-0', y='X_umap-1', color="G2M_score",
449
- labels={'X_umap-0': 'umap1' , 'X_umap-1': 'umap2'},
450
- hover_name='batch', title="G2M score:",template="seaborn")
451
-
452
- # Sort values of custom in-between
453
- dff = dff.sort(condition1_chosen)
454
-
455
- fig_scatter_9 = px.scatter(data_frame=dff, x='X_umap-0', y='X_umap-1', color=condition1_chosen,
456
- labels={'X_umap-0': 'umap1' , 'X_umap-1': 'umap2'},
457
- hover_name='batch',template="seaborn")
458
-
459
- fig_scatter_10 = px.scatter(data_frame=dff, x='X_umap-0', y='X_umap-1', color=condition2_chosen,
460
- labels={'X_umap-0': 'umap1' , 'X_umap-1': 'umap2'},
461
- hover_name='batch',template="seaborn")
462
-
463
- fig_scatter_11 = px.scatter(data_frame=dff, x=condition1_chosen, y=condition2_chosen, color=condition1_chosen,
464
- #labels={'X_umap-0': 'umap1' , 'X_umap-1': 'umap2'},
465
- hover_name='batch',template="seaborn")
466
-
467
- fig_scatter_12 = px.scatter(data_frame=expression_means, x="Gene", y=col_chosen, color="Mean expression",
468
- size="percentage", size_max = 20,
469
- #labels={'X_umap-0': 'umap1' , 'X_umap-1': 'umap2'},
470
- hover_name=col_chosen,template="seaborn")
471
-
472
- fig_violin2 = px.violin(data_frame=dff, x=condition1_chosen, y=condition2_chosen, box=True, points="all",
473
- color=condition1_chosen, hover_name=condition1_chosen,template="seaborn")
474
-
475
-
476
- return fig_violin, fig_pie, fig_scatter, fig_scatter_2, fig_scatter_3, fig_scatter_4, fig_scatter_5, fig_scatter_6, fig_scatter_7, fig_scatter_8, fig_scatter_9, fig_scatter_10, fig_scatter_11, fig_scatter_12, fig_violin2
477
-
478
- # Set http://localhost:5000/ in web browser
479
- # Now create your regular FASTAPI application
480
-
481
- if __name__ == '__main__':
482
- app.run_server(debug=False, use_reloader=False, host='0.0.0.0', port=5000) #