RDeF654875678597657 commited on
Commit
252f6a0
·
1 Parent(s): 9d164f1
Files changed (1) hide show
  1. app.py +421 -421
app.py CHANGED
@@ -77,424 +77,424 @@ try:
77
  # Add similar checks and dict updates for 'supertype', 'cluster', and 'class'
78
  except Exception as e:
79
  print(f"An error occurred: {e}")
80
-
81
- #classification_cmap = joined_sub.drop_duplicates(subset='subclass').set_index('subclass')['subclass_color'].to_dict()
82
- #classification_cmap.update(joined_sub.drop_duplicates(subset='supertype').set_index('supertype')['subclass_color'].to_dict())
83
- #classification_cmap.update(joined_sub.drop_duplicates(subset='cluster').set_index('cluster')['subclass_color'].to_dict())
84
- #classification_cmap.update(joined_sub.drop_duplicates(subset='class').set_index('class')['class_color'].to_dict())
85
-
86
-
87
- class MERFISH_viz(param.Parameterized):
88
- dataset_selector = param.Selector(objects=datasets)
89
- brain_section_index = param.Integer(default=0, bounds=(
90
- 0, sub_cell_expression[datasets[0]]["brain_section_label"].unique().shape[0]))
91
- gene_selector = param.ObjectSelector(default=selected_genes[0], objects=selected_genes.tolist())
92
- class_selector = param.ListSelector(default=sorted(sub_cell_expression[dataset]['class'].unique()),
93
- objects=sorted(sub_cell_expression[dataset]['class'].unique()))
94
- subclass_selector = param.ListSelector(default=sorted(sub_cell_expression[dataset]['subclass'].unique()),
95
- objects=sorted(sub_cell_expression[dataset]['subclass'].unique()))
96
-
97
- # Naming the keyword arguments `**params` is purely a convention.
98
- def __init__(self, sub_cell_expression, sel_dataset, sel_class, sel_subclass, brain_section_index, **params):
99
- super().__init__(**params)
100
- self.sub_cell_expression = sub_cell_expression
101
- self.current_data = self.sub_cell_expression[sel_dataset]
102
- self.filtered_data = self.current_data[
103
- self.current_data['class'].isin(sel_class) & self.current_data['subclass'].isin(sel_subclass)]
104
-
105
- brain_section = self.current_data['brain_section_label'].unique()[brain_section_index]
106
- section = self.filtered_data[self.filtered_data['brain_section_label'] == brain_section]
107
-
108
- self.section = section[section['parcellation_division'] != "unassigned"]
109
-
110
- self.control_panel = pn.Row(
111
- pn.Param(self.param['dataset_selector']),
112
- pn.Param(self.param['brain_section_index']),
113
- pn.Param(self.param['gene_selector']),
114
- pn.Param(self.param['class_selector']),
115
- pn.Param(self.param['subclass_selector'])
116
- )
117
-
118
- @param.depends('dataset_selector', 'brain_section_index', 'gene_selector', 'class_selector', 'subclass_selector')
119
- def view(self):
120
- return pn.Column(
121
- f'Selected dataset: {self.dataset_selector}',
122
- f'Brain Section Index: {self.brain_section_index}',
123
- f'Selected Gene: {self.gene_selector}',
124
- f'Selected Classes: {self.class_selector}, {self.subclass_selector}')
125
-
126
- @pn.depends("filter_by_class_subclass", "gene_selector", "brain_section_index")
127
- def plot_expr_across_slices(self):
128
- curve_data = self.filtered_data[self.filtered_data[self.gene_selector] > 0].groupby('brain_section_label')[
129
- self.gene_selector].mean()
130
- curve_data.rename(f"Expression {self.gene_selector}", inplace=True)
131
- curve = hv.Curve(curve_data, label=f'Log(CPM) {self.gene_selector}').opts(xaxis=None, height=140,
132
- responsive=True, active_tools=[])
133
-
134
- grouped_data = self.filtered_data.groupby('brain_section_label')[self.gene_selector].apply(
135
- percentage_above_threshold_MER).reset_index()
136
- grouped_data.rename(columns={self.gene_selector: f"% expressing {self.gene_selector}"}, inplace=True)
137
- percentage_curve = hv.Curve(grouped_data, 'brain_section_label', f"% expressing {self.gene_selector}",
138
- label=f'Percentage expressing {self.gene_selector}').opts(xaxis=None,
139
- height=140,
140
- responsive=True,
141
- active_tools=[])
142
-
143
- vline = hv.VLine(self.brain_section_index).opts(line_color='red', line_width=2)
144
- percentage_of_all_cells = ((self.filtered_data.groupby(
145
- 'brain_section_label').size() / self.current_data.groupby('brain_section_label').size()) * 100).fillna(0)
146
- percentage_of_all_cells.name = "% of all cells"
147
- ratio_cells = hv.Curve(percentage_of_all_cells, 'brain_section_label', "% of all cells",
148
- label='Percentage of all cells').opts(xaxis=None,
149
- height=100,
150
- responsive=True,
151
- active_tools=[])
152
-
153
- return hv.Layout([(ratio_cells * vline), (curve * vline), (percentage_curve * vline)]).cols(1)
154
-
155
- @pn.depends("filter_by_class_subclass", "gene_selector", "brain_section_index")
156
- def plot_bar(self):
157
- color_map = self.section.groupby('parcellation_structure')['parcellation_structure_color'].first().to_dict()
158
-
159
- hv_ds = hv.Dataset(self.section.groupby(['parcellation_structure'])[self.gene_selector].apply(
160
- percentage_above_threshold_MER).sort_values(ascending=False).head(20).reset_index(),
161
- kdims=['parcellation_structure'], vdims=[self.gene_selector])
162
-
163
- # Create the vertical Bar chart with rotated xticklabels
164
- bar_plot = hv.Bars(hv_ds).opts(
165
- color=dim('parcellation_structure').categorize(color_map, 'gray'),
166
- active_tools=[],
167
- tools=["hover"],
168
- responsive=True,
169
- frame_height=100,
170
- invert_axes=False,
171
- xrotation=90 # Rotate xticklabels by 90 degrees
172
- )
173
-
174
- grouped_data = self.section.groupby(['parcellation_structure'])[self.gene_selector].apply(
175
- percentage_above_threshold_MER).sort_values(
176
- ascending=False).head(30).reset_index()
177
- counts = self.section['parcellation_structure'].value_counts().reindex(
178
- grouped_data['parcellation_structure']).fillna(0)
179
-
180
- labels = hv.Labels({'x': grouped_data['parcellation_structure'], 'y': grouped_data[self.gene_selector], 'text': counts},
181
- ['x', 'y'], 'text').opts(text_font_size='8pt', text_color="black", yoffset=-5)
182
-
183
- return bar_plot * labels
184
-
185
- @pn.depends("filter_by_class_subclass", "gene_selector", "get_section")
186
- def plot_section(self):
187
- plot1 = hv.Points(data=self.section, kdims=['x', 'y'],
188
- vdims=[self.gene_selector, 'parcellation_structure', 'parcellation_substructure']).opts(
189
- width=550, colorbar=True, cmap='rocket_r', size=2, color=self.gene_selector)
190
- plot2 = hv.NdOverlay({division: hv.Points(self.section[self.section['parcellation_division'] == division],
191
- ['x', 'y'], ['parcellation_division_color', 'parcellation_structure',
192
- 'parcellation_substructure']).opts(
193
- color='parcellation_division_color', size=2) for division in
194
- self.section[self.section['parcellation_category'] == "grey"][
195
- 'parcellation_division'].unique()}, kdims='parcellation_division').opts(
196
- legend_position='right', width=650, show_legend=True)
197
-
198
- common_opts = opts.Points(height=500, invert_yaxis=True, xaxis=None, yaxis=None, show_grid=False,
199
- active_tools=[], tools=["hover"])
200
-
201
- return (plot1 + plot2).opts(common_opts)
202
-
203
- @param.depends("brain_section_index", watch=True)
204
- def get_section(self):
205
- brain_section = self.current_data['brain_section_label'].unique()[self.brain_section_index]
206
- section = self.filtered_data[self.filtered_data['brain_section_label'] == brain_section]
207
- self.section = section[section['parcellation_division'] != "unassigned"]
208
-
209
- @param.depends('dataset_selector', watch=True)
210
- def update_current_data(self):
211
- self.current_data = self.sub_cell_expression[self.dataset_selector]
212
- self.brain_section_index = 0
213
- self.brain_section_index.bounds = (0, self.current_data["brain_section_label"].unique().shape[0])
214
-
215
- @param.depends("update_current_data", 'class_selector', 'subclass_selector', watch=True)
216
- def filter_by_class_subclass(self):
217
- self.filtered_data = self.current_data[
218
- self.current_data['class'].isin(self.class_selector) & self.current_data['subclass'].isin(
219
- self.subclass_selector)]
220
-
221
- @param.depends("update_current_data", 'class_selector', watch=True)
222
- def update_subclasses(self):
223
- self.param.subclass_selector.objects = sorted(
224
- self.current_data[self.current_data['class'].isin(self.class_selector)]['subclass'].unique())
225
- self.subclass_selector = sorted(
226
- self.current_data[(self.current_data['class'].isin(self.class_selector))]['subclass'].unique())
227
-
228
-
229
- viz = MERFISH_viz(sub_cell_expression, datasets[0], sub_cell_expression[datasets[0]]["class"].unique(),
230
- sub_cell_expression[dataset]["subclass"].unique(), 0)
231
-
232
- # Title of the paper and authors
233
- # Custom HTML for the title
234
- custom_title_html = """
235
- <div style="text-align: center; max-width: 1200px; margin: 20px auto;">
236
- <h1 style="font-weight: 900; font-size: 3rem; margin: 0rem">
237
- Transcriptomic Mapping of the 5-HT Receptor Landscape
238
- </h1>
239
- <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
240
- Roberto De Filippo<sup>#</sup>, Dietmar Schmitz
241
- </h2>
242
- <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
243
- <sup>#</sup>Corresponding author
244
- </h2>
245
- <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
246
- [<a href="https://github.com/RobertoDF/5-HT2A-MERFISH" style="color:blue;">Article</a>]
247
- [<a href="https://github.com/RobertoDF/5-HT2A-MERFISH" style="color:blue;">Github</a>]
248
- </h2>
249
- <h2 style="font-weight: 450; font-size: 1rem;">
250
- Custom visualizer for MERFISH dataset provided by [<a href="https://www.nature.com/articles/s41586-023-06808-9" style="color:blue;">Zhang et al., 2023</a>] </h2>
251
- <h2 style="font-weight: 450; font-size: 1rem;">
252
- By <b>Roberto De Filippo</b>
253
- </h2>
254
- </div>
255
- """
256
-
257
- # Create a Panel HTML pane with the custom title
258
- custom_title_pane = pn.pane.HTML(custom_title_html, sizing_mode='stretch_width')
259
-
260
- dashboard_spatial = pn.Column(custom_title_pane, viz.control_panel, viz.plot_expr_across_slices, viz.plot_bar, viz.plot_section)
261
-
262
-
263
- def plot_class_expression_split_by_categories(subfig, cls, df_subset, gene):
264
- axs = subfig.subplots(4, 1)
265
- subfig.subplots_adjust(left=0.05, right=.95)
266
-
267
- sns.violinplot(data=df_subset, y=f'{gene} prevalence (%)', x='subclass', hue='subclass', ax=axs[0],
268
- palette=classification_cmap, fill=False)
269
-
270
- # Set the title with desired modifications
271
- title = axs[0].set_title(cls, color=classification_cmap[cls], fontweight='bold', fontsize=20)
272
- title.set_path_effects([path_effects.withStroke(linewidth=3, foreground='black')])
273
-
274
- subfig.set_facecolor(mcolors.to_rgba(classification_cmap[cls], alpha=0.15))
275
-
276
- axs[0].set_ylim(0, 100) # Set y-axis limit to 1
277
- axs[0].xaxis.set_ticks_position('top')
278
- axs[0].tick_params(axis='x', length=0)
279
-
280
- sns.violinplot(data=df_subset, y=f'{gene} prevalence (%)', x='supertype', hue='supertype', ax=axs[1],
281
- palette=classification_cmap, fill=False)
282
- axs[1].set_title(cls)
283
- axs[1].set_ylim(0, 100) # Set y-axis limit to 1
284
-
285
- sns.barplot(data=df_subset, y=f'{gene} prevalence (%)', x='cluster', hue='cluster', ax=axs[2],
286
- palette=classification_cmap)
287
- axs[2].set_title(cls)
288
- axs[2].set_ylim(0, 100) # Set y-axis limit to 1
289
-
290
- axs[2].set(ylabel='')
291
- axs[0].set(ylabel='')
292
- axs[2].set(xticks=[], xlabel='')
293
- axs[1].set(xticks=[], xlabel='')
294
- axs[0].set(xticks=[], xlabel='')
295
- axs[0].set(xlabel='')
296
- axs[2].set(xticks=[], xlabel='')
297
- axs[2].set(xticks=[], xlabel='')
298
- axs[1].set_title('')
299
- axs[2].set_title('')
300
- plt.draw()
301
- for tick in axs[0].get_xticklabels():
302
- tick.set_color(classification_cmap[tick.get_text()])
303
-
304
- # Identify positions for subclass delimiters in the cluster graph
305
- subclass_ends = df_subset.groupby('subclass').size().cumsum()
306
- subclass_positions = subclass_ends - 1
307
-
308
- # For the third plot (clusters):
309
- for pos in subclass_positions[:-1]:
310
- axs[2].axvline(pos + 0.5, color='gray', linestyle='--')
311
-
312
- # For the first plot (subclass), simply draw lines between unique subclasses
313
- for i in range(1, len(df_subset['subclass'].unique())):
314
- axs[0].axvline(i - 0.5, color='gray', linestyle='--')
315
-
316
- # For the second plot (supertype), the position will be based on unique supertypes per subclass
317
- supertype_ends = df_subset.groupby('subclass')['supertype'].nunique().cumsum()
318
- supertype_positions = supertype_ends - 1
319
- for pos in supertype_positions[:-1]:
320
- axs[1].axvline(pos + 0.5, color='gray', linestyle='--')
321
-
322
- # For the first plot (subclass):
323
- subclasses = df_subset['subclass'].unique()
324
- start = -.5
325
- for i, subclass in enumerate(subclasses):
326
- end = i + 0.5
327
- color = classification_cmap[subclass]
328
- axs[0].axvspan(start + .05, end - .05, facecolor=color, alpha=0.15)
329
- start = end
330
-
331
- # For the second plot (supertype), determine filling areas based on unique supertypes per subclass
332
- supertype_ends = df_subset.groupby('subclass')['supertype'].nunique().cumsum()
333
- supertype_positions = supertype_ends - 1
334
-
335
- previous_position = -0.5 # initialize to start from the first entry
336
- for idx, pos in enumerate(supertype_positions):
337
- current_position = pos + 0.5
338
- # Retrieve the subclass name for the current supertype
339
- subclass_name = df_subset['subclass'].unique()[idx]
340
- color = classification_cmap[subclass_name]
341
-
342
- axs[1].axvspan(previous_position + 0.2, current_position - .2, facecolor=color, alpha=0.15)
343
-
344
- previous_position = current_position # set for the next iteration
345
-
346
- ####third plot filling
347
- # Get a mapping of subclasses to their dominant cluster
348
- subclass_to_cluster = df_subset.groupby('subclass')['cluster'].apply(lambda x: x.value_counts().idxmax())
349
-
350
- # Define previous position to help us fill areas between borders
351
- prev_pos = 0
352
-
353
- # Iterate over the subclass positions and the corresponding subclasses
354
- for idx, (subclass, cluster) in enumerate(subclass_to_cluster.items()):
355
- # Get the color for this subclass's dominant cluster from your cmap
356
- color_value = classification_cmap[cluster]
357
-
358
- # End position is either the next border position or the end of the plot
359
- end_pos = subclass_positions.iloc[idx] if idx < len(subclass_positions) else len(df_subset['cluster']) - 1
360
-
361
- # Fill the area with the given color
362
- axs[2].fill_between([prev_pos, end_pos], 0, 100, color=color_value, alpha=0.15)
363
-
364
- # Update the previous position to the current position
365
- prev_pos = end_pos + 1
366
-
367
- # Adjust the xlim of each axis
368
- axs[0].set_xlim(-0.5, len(df_subset['subclass'].unique()) - 0.5)
369
- axs[1].set_xlim(-0.5, len(df_subset['supertype'].unique()) - 0.5)
370
- axs[2].set_xlim(-.8, len(df_subset['cluster'].unique()))
371
-
372
- # Now, add legend in the fourth axis:
373
- patches = [plt.Line2D([0], [0], color=classification_cmap[c], lw=8) for c in df_subset["subclass"].unique()]
374
- labels = list(df_subset["subclass"].unique())
375
-
376
- axs[3].legend(patches, labels, loc='center', ncol=6, handlelength=1.8, handleheight=1)
377
- axs[3].axis('off') # Hide axis
378
-
379
- sns.despine(bottom=True)
380
-
381
-
382
- group_selector = pn.widgets.Select(name='Group', options=neuron_cluster_groups_order, value=neuron_cluster_groups_order[0])
383
- gene_selector = pn.widgets.Select(name='Gene', options=list(selected_genes_cl), value=selected_genes_cl[0])
384
-
385
-
386
- @pn.depends(group_selector, gene_selector)
387
- def interactive_plot(group, gene):
388
- global global_saved_fig, group_g, gene_g
389
- data = joined_with_membership_sub[joined_with_membership_sub["cluster_group_name"] == group]
390
- data = data.groupby(["cluster_group_name", "class", "subclass", "supertype", "cluster"])[gene].apply(
391
- percentage_above_threshold).reset_index()
392
- data = data[data["cluster_group_name"] != "WholeBrain"]
393
- data["cluster_group_name"] = pd.Categorical(data["cluster_group_name"], categories=neuron_cluster_groups_order,
394
- ordered=True)
395
- data = data.sort_values(by=["cluster_group_name", "class"])
396
-
397
- data.rename(columns={gene: f'{gene} prevalence (%)'}, inplace=True)
398
-
399
- fig = plt.figure(figsize=(25, 5 * data['class'].nunique()))
400
- gs = gridspec.GridSpec(data['class'].nunique(), 1)
401
-
402
- for n, cls in enumerate(data['class'].unique()):
403
- df_subset = data[data['class'] == cls]
404
- subfig = fig.add_subfigure(gs[n, :])
405
- subfig.subplots_adjust(left=0.05, right=.95, bottom=0.01)
406
- plot_class_expression_split_by_categories(subfig, cls, df_subset, gene)
407
-
408
- global_saved_fig = fig
409
- group_g = group
410
- gene_g = gene
411
-
412
- fig.suptitle(group, y=1.04, fontweight='bold', fontsize=20);
413
- #print(group, gene)
414
-
415
- return fig
416
-
417
- dashboard_receptor_centric = pn.Column(
418
- pn.Row(group_selector, gene_selector),
419
- pn.pane.Matplotlib(interactive_plot, sizing_mode = 'stretch_width')
420
- )
421
-
422
-
423
- def update_subclass_selector(event):
424
- selected_classes = event.new
425
- if "None" in selected_classes or not selected_classes:
426
- all_subclasses = sorted(joined_sub["subclass"].unique().tolist())
427
- else:
428
- all_subclasses = sorted(joined_sub[joined_sub["class"].isin(selected_classes)]["subclass"].unique().tolist())
429
- subclass_selector.options = ["None"] + all_subclasses
430
- subclass_selector.value = ["None"]
431
-
432
-
433
- class_selector = pn.widgets.MultiSelect(name='Class selector',
434
- options=["None"] + sorted(joined_sub["class"].unique().tolist()),
435
- value=[joined_sub["class"].unique()[0]])
436
- subclass_selector = pn.widgets.MultiSelect(name='Subclass selector',
437
- options=["None"] + sorted(joined_sub["subclass"].unique().tolist()),
438
- value=["None"])
439
- groupby_selector = pn.widgets.Select(name='Group by', options=["class", "subclass", "supertype", "cluster"],
440
- value="class")
441
- sortby_selector = pn.widgets.Select(name='Sort by', options=["class"] + list(selected_genes_cl), value="class")
442
-
443
- class_selector.param.watch(update_subclass_selector, 'value')
444
-
445
-
446
- @pn.depends(class_selector, subclass_selector, groupby_selector, sortby_selector)
447
- def heatmap_cell_centric(class_, subclass, groupby, sortby):
448
- if class_ != ["None"] or subclass != ["None"]:
449
-
450
- filtered_data = joined_sub
451
- if "None" not in class_:
452
- filtered_data = filtered_data[filtered_data["class"].isin(class_)]
453
- if "None" not in subclass:
454
- filtered_data = filtered_data[filtered_data["subclass"].isin(subclass)]
455
-
456
- if sortby == "class":
457
- sortby = groupby
458
- ascending = True
459
- else:
460
- ascending = False
461
-
462
- num_rows = len(filtered_data.groupby(groupby))
463
- fig_height = max(5, num_rows * 0.2) # Set a minimum height and scale per row
464
-
465
- fig, ax = plt.subplots(figsize=(10, fig_height))
466
- sns.heatmap(
467
- filtered_data.groupby(groupby)[selected_genes_cl].apply(percentage_above_threshold).sort_values(sortby,
468
- ascending=ascending),
469
- yticklabels=True, cmap=sns.light_palette("#CC5656", as_cmap=True), ax=ax, cbar=False, vmax=90)
470
-
471
- for ytick in ax.get_xticklabels():
472
- ytick.set_color(genes_cmap_rgb[ytick.get_text()])
473
- for ytick in ax.get_yticklabels():
474
- ytick.set_color(classification_cmap[ytick.get_text()])
475
-
476
- plt.tight_layout()
477
- else:
478
- fig = plt.figure(figsize=(10, 5)) # Default size if no data
479
- plt.text(0.5, 0.5, 'No data to display', horizontalalignment='center', verticalalignment='center')
480
-
481
- return fig
482
-
483
-
484
- dashboard_cell_centric = pn.Column(pn.Row(class_selector, subclass_selector, groupby_selector, sortby_selector),
485
- pn.pane.Matplotlib(heatmap_cell_centric, sizing_mode='stretch_width'))
486
-
487
- title = "5-HT Transcriptomic"
488
- pn.template.BootstrapTemplate(
489
- header_background="#F9B9B7",
490
- logo="https://upload.wikimedia.org/wikipedia/commons/5/51/Logo_Charite.svg",
491
- title="5-HT Transcriptomics",
492
- main=pn.Column(
493
- pn.Tabs(
494
- ("Spatial", dashboard_spatial), # Add your spatial content here
495
- ("Receptor-centric", dashboard_receptor_centric),
496
- ("Cell-centric", dashboard_cell_centric),
497
- dynamic=True
498
- )
499
- )
500
- ).servable(title=title)
 
77
  # Add similar checks and dict updates for 'supertype', 'cluster', and 'class'
78
  except Exception as e:
79
  print(f"An error occurred: {e}")
80
+ #
81
+ # classification_cmap = joined_sub.drop_duplicates(subset='subclass').set_index('subclass')['subclass_color'].to_dict()
82
+ # classification_cmap.update(joined_sub.drop_duplicates(subset='supertype').set_index('supertype')['subclass_color'].to_dict())
83
+ # classification_cmap.update(joined_sub.drop_duplicates(subset='cluster').set_index('cluster')['subclass_color'].to_dict())
84
+ # classification_cmap.update(joined_sub.drop_duplicates(subset='class').set_index('class')['class_color'].to_dict())
85
+ #
86
+ #
87
+ # class MERFISH_viz(param.Parameterized):
88
+ # dataset_selector = param.Selector(objects=datasets)
89
+ # brain_section_index = param.Integer(default=0, bounds=(
90
+ # 0, sub_cell_expression[datasets[0]]["brain_section_label"].unique().shape[0]))
91
+ # gene_selector = param.ObjectSelector(default=selected_genes[0], objects=selected_genes.tolist())
92
+ # class_selector = param.ListSelector(default=sorted(sub_cell_expression[dataset]['class'].unique()),
93
+ # objects=sorted(sub_cell_expression[dataset]['class'].unique()))
94
+ # subclass_selector = param.ListSelector(default=sorted(sub_cell_expression[dataset]['subclass'].unique()),
95
+ # objects=sorted(sub_cell_expression[dataset]['subclass'].unique()))
96
+ #
97
+ # # Naming the keyword arguments `**params` is purely a convention.
98
+ # def __init__(self, sub_cell_expression, sel_dataset, sel_class, sel_subclass, brain_section_index, **params):
99
+ # super().__init__(**params)
100
+ # self.sub_cell_expression = sub_cell_expression
101
+ # self.current_data = self.sub_cell_expression[sel_dataset]
102
+ # self.filtered_data = self.current_data[
103
+ # self.current_data['class'].isin(sel_class) & self.current_data['subclass'].isin(sel_subclass)]
104
+ #
105
+ # brain_section = self.current_data['brain_section_label'].unique()[brain_section_index]
106
+ # section = self.filtered_data[self.filtered_data['brain_section_label'] == brain_section]
107
+ #
108
+ # self.section = section[section['parcellation_division'] != "unassigned"]
109
+ #
110
+ # self.control_panel = pn.Row(
111
+ # pn.Param(self.param['dataset_selector']),
112
+ # pn.Param(self.param['brain_section_index']),
113
+ # pn.Param(self.param['gene_selector']),
114
+ # pn.Param(self.param['class_selector']),
115
+ # pn.Param(self.param['subclass_selector'])
116
+ # )
117
+ #
118
+ # @param.depends('dataset_selector', 'brain_section_index', 'gene_selector', 'class_selector', 'subclass_selector')
119
+ # def view(self):
120
+ # return pn.Column(
121
+ # f'Selected dataset: {self.dataset_selector}',
122
+ # f'Brain Section Index: {self.brain_section_index}',
123
+ # f'Selected Gene: {self.gene_selector}',
124
+ # f'Selected Classes: {self.class_selector}, {self.subclass_selector}')
125
+ #
126
+ # @pn.depends("filter_by_class_subclass", "gene_selector", "brain_section_index")
127
+ # def plot_expr_across_slices(self):
128
+ # curve_data = self.filtered_data[self.filtered_data[self.gene_selector] > 0].groupby('brain_section_label')[
129
+ # self.gene_selector].mean()
130
+ # curve_data.rename(f"Expression {self.gene_selector}", inplace=True)
131
+ # curve = hv.Curve(curve_data, label=f'Log(CPM) {self.gene_selector}').opts(xaxis=None, height=140,
132
+ # responsive=True, active_tools=[])
133
+ #
134
+ # grouped_data = self.filtered_data.groupby('brain_section_label')[self.gene_selector].apply(
135
+ # percentage_above_threshold_MER).reset_index()
136
+ # grouped_data.rename(columns={self.gene_selector: f"% expressing {self.gene_selector}"}, inplace=True)
137
+ # percentage_curve = hv.Curve(grouped_data, 'brain_section_label', f"% expressing {self.gene_selector}",
138
+ # label=f'Percentage expressing {self.gene_selector}').opts(xaxis=None,
139
+ # height=140,
140
+ # responsive=True,
141
+ # active_tools=[])
142
+ #
143
+ # vline = hv.VLine(self.brain_section_index).opts(line_color='red', line_width=2)
144
+ # percentage_of_all_cells = ((self.filtered_data.groupby(
145
+ # 'brain_section_label').size() / self.current_data.groupby('brain_section_label').size()) * 100).fillna(0)
146
+ # percentage_of_all_cells.name = "% of all cells"
147
+ # ratio_cells = hv.Curve(percentage_of_all_cells, 'brain_section_label', "% of all cells",
148
+ # label='Percentage of all cells').opts(xaxis=None,
149
+ # height=100,
150
+ # responsive=True,
151
+ # active_tools=[])
152
+ #
153
+ # return hv.Layout([(ratio_cells * vline), (curve * vline), (percentage_curve * vline)]).cols(1)
154
+ #
155
+ # @pn.depends("filter_by_class_subclass", "gene_selector", "brain_section_index")
156
+ # def plot_bar(self):
157
+ # color_map = self.section.groupby('parcellation_structure')['parcellation_structure_color'].first().to_dict()
158
+ #
159
+ # hv_ds = hv.Dataset(self.section.groupby(['parcellation_structure'])[self.gene_selector].apply(
160
+ # percentage_above_threshold_MER).sort_values(ascending=False).head(20).reset_index(),
161
+ # kdims=['parcellation_structure'], vdims=[self.gene_selector])
162
+ #
163
+ # # Create the vertical Bar chart with rotated xticklabels
164
+ # bar_plot = hv.Bars(hv_ds).opts(
165
+ # color=dim('parcellation_structure').categorize(color_map, 'gray'),
166
+ # active_tools=[],
167
+ # tools=["hover"],
168
+ # responsive=True,
169
+ # frame_height=100,
170
+ # invert_axes=False,
171
+ # xrotation=90 # Rotate xticklabels by 90 degrees
172
+ # )
173
+ #
174
+ # grouped_data = self.section.groupby(['parcellation_structure'])[self.gene_selector].apply(
175
+ # percentage_above_threshold_MER).sort_values(
176
+ # ascending=False).head(30).reset_index()
177
+ # counts = self.section['parcellation_structure'].value_counts().reindex(
178
+ # grouped_data['parcellation_structure']).fillna(0)
179
+ #
180
+ # labels = hv.Labels({'x': grouped_data['parcellation_structure'], 'y': grouped_data[self.gene_selector], 'text': counts},
181
+ # ['x', 'y'], 'text').opts(text_font_size='8pt', text_color="black", yoffset=-5)
182
+ #
183
+ # return bar_plot * labels
184
+ #
185
+ # @pn.depends("filter_by_class_subclass", "gene_selector", "get_section")
186
+ # def plot_section(self):
187
+ # plot1 = hv.Points(data=self.section, kdims=['x', 'y'],
188
+ # vdims=[self.gene_selector, 'parcellation_structure', 'parcellation_substructure']).opts(
189
+ # width=550, colorbar=True, cmap='rocket_r', size=2, color=self.gene_selector)
190
+ # plot2 = hv.NdOverlay({division: hv.Points(self.section[self.section['parcellation_division'] == division],
191
+ # ['x', 'y'], ['parcellation_division_color', 'parcellation_structure',
192
+ # 'parcellation_substructure']).opts(
193
+ # color='parcellation_division_color', size=2) for division in
194
+ # self.section[self.section['parcellation_category'] == "grey"][
195
+ # 'parcellation_division'].unique()}, kdims='parcellation_division').opts(
196
+ # legend_position='right', width=650, show_legend=True)
197
+ #
198
+ # common_opts = opts.Points(height=500, invert_yaxis=True, xaxis=None, yaxis=None, show_grid=False,
199
+ # active_tools=[], tools=["hover"])
200
+ #
201
+ # return (plot1 + plot2).opts(common_opts)
202
+ #
203
+ # @param.depends("brain_section_index", watch=True)
204
+ # def get_section(self):
205
+ # brain_section = self.current_data['brain_section_label'].unique()[self.brain_section_index]
206
+ # section = self.filtered_data[self.filtered_data['brain_section_label'] == brain_section]
207
+ # self.section = section[section['parcellation_division'] != "unassigned"]
208
+ #
209
+ # @param.depends('dataset_selector', watch=True)
210
+ # def update_current_data(self):
211
+ # self.current_data = self.sub_cell_expression[self.dataset_selector]
212
+ # self.brain_section_index = 0
213
+ # self.brain_section_index.bounds = (0, self.current_data["brain_section_label"].unique().shape[0])
214
+ #
215
+ # @param.depends("update_current_data", 'class_selector', 'subclass_selector', watch=True)
216
+ # def filter_by_class_subclass(self):
217
+ # self.filtered_data = self.current_data[
218
+ # self.current_data['class'].isin(self.class_selector) & self.current_data['subclass'].isin(
219
+ # self.subclass_selector)]
220
+ #
221
+ # @param.depends("update_current_data", 'class_selector', watch=True)
222
+ # def update_subclasses(self):
223
+ # self.param.subclass_selector.objects = sorted(
224
+ # self.current_data[self.current_data['class'].isin(self.class_selector)]['subclass'].unique())
225
+ # self.subclass_selector = sorted(
226
+ # self.current_data[(self.current_data['class'].isin(self.class_selector))]['subclass'].unique())
227
+ #
228
+ #
229
+ # viz = MERFISH_viz(sub_cell_expression, datasets[0], sub_cell_expression[datasets[0]]["class"].unique(),
230
+ # sub_cell_expression[dataset]["subclass"].unique(), 0)
231
+ #
232
+ # # Title of the paper and authors
233
+ # # Custom HTML for the title
234
+ # custom_title_html = """
235
+ # <div style="text-align: center; max-width: 1200px; margin: 20px auto;">
236
+ # <h1 style="font-weight: 900; font-size: 3rem; margin: 0rem">
237
+ # Transcriptomic Mapping of the 5-HT Receptor Landscape
238
+ # </h1>
239
+ # <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
240
+ # Roberto De Filippo<sup>#</sup>, Dietmar Schmitz
241
+ # </h2>
242
+ # <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
243
+ # <sup>#</sup>Corresponding author
244
+ # </h2>
245
+ # <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
246
+ # [<a href="https://github.com/RobertoDF/5-HT2A-MERFISH" style="color:blue;">Article</a>]
247
+ # [<a href="https://github.com/RobertoDF/5-HT2A-MERFISH" style="color:blue;">Github</a>]
248
+ # </h2>
249
+ # <h2 style="font-weight: 450; font-size: 1rem;">
250
+ # Custom visualizer for MERFISH dataset provided by [<a href="https://www.nature.com/articles/s41586-023-06808-9" style="color:blue;">Zhang et al., 2023</a>] </h2>
251
+ # <h2 style="font-weight: 450; font-size: 1rem;">
252
+ # By <b>Roberto De Filippo</b>
253
+ # </h2>
254
+ # </div>
255
+ # """
256
+ #
257
+ # # Create a Panel HTML pane with the custom title
258
+ # custom_title_pane = pn.pane.HTML(custom_title_html, sizing_mode='stretch_width')
259
+ #
260
+ # dashboard_spatial = pn.Column(custom_title_pane, viz.control_panel, viz.plot_expr_across_slices, viz.plot_bar, viz.plot_section)
261
+ #
262
+ #
263
+ # def plot_class_expression_split_by_categories(subfig, cls, df_subset, gene):
264
+ # axs = subfig.subplots(4, 1)
265
+ # subfig.subplots_adjust(left=0.05, right=.95)
266
+ #
267
+ # sns.violinplot(data=df_subset, y=f'{gene} prevalence (%)', x='subclass', hue='subclass', ax=axs[0],
268
+ # palette=classification_cmap, fill=False)
269
+ #
270
+ # # Set the title with desired modifications
271
+ # title = axs[0].set_title(cls, color=classification_cmap[cls], fontweight='bold', fontsize=20)
272
+ # title.set_path_effects([path_effects.withStroke(linewidth=3, foreground='black')])
273
+ #
274
+ # subfig.set_facecolor(mcolors.to_rgba(classification_cmap[cls], alpha=0.15))
275
+ #
276
+ # axs[0].set_ylim(0, 100) # Set y-axis limit to 1
277
+ # axs[0].xaxis.set_ticks_position('top')
278
+ # axs[0].tick_params(axis='x', length=0)
279
+ #
280
+ # sns.violinplot(data=df_subset, y=f'{gene} prevalence (%)', x='supertype', hue='supertype', ax=axs[1],
281
+ # palette=classification_cmap, fill=False)
282
+ # axs[1].set_title(cls)
283
+ # axs[1].set_ylim(0, 100) # Set y-axis limit to 1
284
+ #
285
+ # sns.barplot(data=df_subset, y=f'{gene} prevalence (%)', x='cluster', hue='cluster', ax=axs[2],
286
+ # palette=classification_cmap)
287
+ # axs[2].set_title(cls)
288
+ # axs[2].set_ylim(0, 100) # Set y-axis limit to 1
289
+ #
290
+ # axs[2].set(ylabel='')
291
+ # axs[0].set(ylabel='')
292
+ # axs[2].set(xticks=[], xlabel='')
293
+ # axs[1].set(xticks=[], xlabel='')
294
+ # axs[0].set(xticks=[], xlabel='')
295
+ # axs[0].set(xlabel='')
296
+ # axs[2].set(xticks=[], xlabel='')
297
+ # axs[2].set(xticks=[], xlabel='')
298
+ # axs[1].set_title('')
299
+ # axs[2].set_title('')
300
+ # plt.draw()
301
+ # for tick in axs[0].get_xticklabels():
302
+ # tick.set_color(classification_cmap[tick.get_text()])
303
+ #
304
+ # # Identify positions for subclass delimiters in the cluster graph
305
+ # subclass_ends = df_subset.groupby('subclass').size().cumsum()
306
+ # subclass_positions = subclass_ends - 1
307
+ #
308
+ # # For the third plot (clusters):
309
+ # for pos in subclass_positions[:-1]:
310
+ # axs[2].axvline(pos + 0.5, color='gray', linestyle='--')
311
+ #
312
+ # # For the first plot (subclass), simply draw lines between unique subclasses
313
+ # for i in range(1, len(df_subset['subclass'].unique())):
314
+ # axs[0].axvline(i - 0.5, color='gray', linestyle='--')
315
+ #
316
+ # # For the second plot (supertype), the position will be based on unique supertypes per subclass
317
+ # supertype_ends = df_subset.groupby('subclass')['supertype'].nunique().cumsum()
318
+ # supertype_positions = supertype_ends - 1
319
+ # for pos in supertype_positions[:-1]:
320
+ # axs[1].axvline(pos + 0.5, color='gray', linestyle='--')
321
+ #
322
+ # # For the first plot (subclass):
323
+ # subclasses = df_subset['subclass'].unique()
324
+ # start = -.5
325
+ # for i, subclass in enumerate(subclasses):
326
+ # end = i + 0.5
327
+ # color = classification_cmap[subclass]
328
+ # axs[0].axvspan(start + .05, end - .05, facecolor=color, alpha=0.15)
329
+ # start = end
330
+ #
331
+ # # For the second plot (supertype), determine filling areas based on unique supertypes per subclass
332
+ # supertype_ends = df_subset.groupby('subclass')['supertype'].nunique().cumsum()
333
+ # supertype_positions = supertype_ends - 1
334
+ #
335
+ # previous_position = -0.5 # initialize to start from the first entry
336
+ # for idx, pos in enumerate(supertype_positions):
337
+ # current_position = pos + 0.5
338
+ # # Retrieve the subclass name for the current supertype
339
+ # subclass_name = df_subset['subclass'].unique()[idx]
340
+ # color = classification_cmap[subclass_name]
341
+ #
342
+ # axs[1].axvspan(previous_position + 0.2, current_position - .2, facecolor=color, alpha=0.15)
343
+ #
344
+ # previous_position = current_position # set for the next iteration
345
+ #
346
+ # ####third plot filling
347
+ # # Get a mapping of subclasses to their dominant cluster
348
+ # subclass_to_cluster = df_subset.groupby('subclass')['cluster'].apply(lambda x: x.value_counts().idxmax())
349
+ #
350
+ # # Define previous position to help us fill areas between borders
351
+ # prev_pos = 0
352
+ #
353
+ # # Iterate over the subclass positions and the corresponding subclasses
354
+ # for idx, (subclass, cluster) in enumerate(subclass_to_cluster.items()):
355
+ # # Get the color for this subclass's dominant cluster from your cmap
356
+ # color_value = classification_cmap[cluster]
357
+ #
358
+ # # End position is either the next border position or the end of the plot
359
+ # end_pos = subclass_positions.iloc[idx] if idx < len(subclass_positions) else len(df_subset['cluster']) - 1
360
+ #
361
+ # # Fill the area with the given color
362
+ # axs[2].fill_between([prev_pos, end_pos], 0, 100, color=color_value, alpha=0.15)
363
+ #
364
+ # # Update the previous position to the current position
365
+ # prev_pos = end_pos + 1
366
+ #
367
+ # # Adjust the xlim of each axis
368
+ # axs[0].set_xlim(-0.5, len(df_subset['subclass'].unique()) - 0.5)
369
+ # axs[1].set_xlim(-0.5, len(df_subset['supertype'].unique()) - 0.5)
370
+ # axs[2].set_xlim(-.8, len(df_subset['cluster'].unique()))
371
+ #
372
+ # # Now, add legend in the fourth axis:
373
+ # patches = [plt.Line2D([0], [0], color=classification_cmap[c], lw=8) for c in df_subset["subclass"].unique()]
374
+ # labels = list(df_subset["subclass"].unique())
375
+ #
376
+ # axs[3].legend(patches, labels, loc='center', ncol=6, handlelength=1.8, handleheight=1)
377
+ # axs[3].axis('off') # Hide axis
378
+ #
379
+ # sns.despine(bottom=True)
380
+ #
381
+ #
382
+ # group_selector = pn.widgets.Select(name='Group', options=neuron_cluster_groups_order, value=neuron_cluster_groups_order[0])
383
+ # gene_selector = pn.widgets.Select(name='Gene', options=list(selected_genes_cl), value=selected_genes_cl[0])
384
+ #
385
+ #
386
+ # @pn.depends(group_selector, gene_selector)
387
+ # def interactive_plot(group, gene):
388
+ # global global_saved_fig, group_g, gene_g
389
+ # data = joined_with_membership_sub[joined_with_membership_sub["cluster_group_name"] == group]
390
+ # data = data.groupby(["cluster_group_name", "class", "subclass", "supertype", "cluster"])[gene].apply(
391
+ # percentage_above_threshold).reset_index()
392
+ # data = data[data["cluster_group_name"] != "WholeBrain"]
393
+ # data["cluster_group_name"] = pd.Categorical(data["cluster_group_name"], categories=neuron_cluster_groups_order,
394
+ # ordered=True)
395
+ # data = data.sort_values(by=["cluster_group_name", "class"])
396
+ #
397
+ # data.rename(columns={gene: f'{gene} prevalence (%)'}, inplace=True)
398
+ #
399
+ # fig = plt.figure(figsize=(25, 5 * data['class'].nunique()))
400
+ # gs = gridspec.GridSpec(data['class'].nunique(), 1)
401
+ #
402
+ # for n, cls in enumerate(data['class'].unique()):
403
+ # df_subset = data[data['class'] == cls]
404
+ # subfig = fig.add_subfigure(gs[n, :])
405
+ # subfig.subplots_adjust(left=0.05, right=.95, bottom=0.01)
406
+ # plot_class_expression_split_by_categories(subfig, cls, df_subset, gene)
407
+ #
408
+ # global_saved_fig = fig
409
+ # group_g = group
410
+ # gene_g = gene
411
+ #
412
+ # fig.suptitle(group, y=1.04, fontweight='bold', fontsize=20);
413
+ # #print(group, gene)
414
+ #
415
+ # return fig
416
+ #
417
+ # dashboard_receptor_centric = pn.Column(
418
+ # pn.Row(group_selector, gene_selector),
419
+ # pn.pane.Matplotlib(interactive_plot, sizing_mode = 'stretch_width')
420
+ # )
421
+ #
422
+ #
423
+ # def update_subclass_selector(event):
424
+ # selected_classes = event.new
425
+ # if "None" in selected_classes or not selected_classes:
426
+ # all_subclasses = sorted(joined_sub["subclass"].unique().tolist())
427
+ # else:
428
+ # all_subclasses = sorted(joined_sub[joined_sub["class"].isin(selected_classes)]["subclass"].unique().tolist())
429
+ # subclass_selector.options = ["None"] + all_subclasses
430
+ # subclass_selector.value = ["None"]
431
+ #
432
+ #
433
+ # class_selector = pn.widgets.MultiSelect(name='Class selector',
434
+ # options=["None"] + sorted(joined_sub["class"].unique().tolist()),
435
+ # value=[joined_sub["class"].unique()[0]])
436
+ # subclass_selector = pn.widgets.MultiSelect(name='Subclass selector',
437
+ # options=["None"] + sorted(joined_sub["subclass"].unique().tolist()),
438
+ # value=["None"])
439
+ # groupby_selector = pn.widgets.Select(name='Group by', options=["class", "subclass", "supertype", "cluster"],
440
+ # value="class")
441
+ # sortby_selector = pn.widgets.Select(name='Sort by', options=["class"] + list(selected_genes_cl), value="class")
442
+ #
443
+ # class_selector.param.watch(update_subclass_selector, 'value')
444
+ #
445
+ #
446
+ # @pn.depends(class_selector, subclass_selector, groupby_selector, sortby_selector)
447
+ # def heatmap_cell_centric(class_, subclass, groupby, sortby):
448
+ # if class_ != ["None"] or subclass != ["None"]:
449
+ #
450
+ # filtered_data = joined_sub
451
+ # if "None" not in class_:
452
+ # filtered_data = filtered_data[filtered_data["class"].isin(class_)]
453
+ # if "None" not in subclass:
454
+ # filtered_data = filtered_data[filtered_data["subclass"].isin(subclass)]
455
+ #
456
+ # if sortby == "class":
457
+ # sortby = groupby
458
+ # ascending = True
459
+ # else:
460
+ # ascending = False
461
+ #
462
+ # num_rows = len(filtered_data.groupby(groupby))
463
+ # fig_height = max(5, num_rows * 0.2) # Set a minimum height and scale per row
464
+ #
465
+ # fig, ax = plt.subplots(figsize=(10, fig_height))
466
+ # sns.heatmap(
467
+ # filtered_data.groupby(groupby)[selected_genes_cl].apply(percentage_above_threshold).sort_values(sortby,
468
+ # ascending=ascending),
469
+ # yticklabels=True, cmap=sns.light_palette("#CC5656", as_cmap=True), ax=ax, cbar=False, vmax=90)
470
+ #
471
+ # for ytick in ax.get_xticklabels():
472
+ # ytick.set_color(genes_cmap_rgb[ytick.get_text()])
473
+ # for ytick in ax.get_yticklabels():
474
+ # ytick.set_color(classification_cmap[ytick.get_text()])
475
+ #
476
+ # plt.tight_layout()
477
+ # else:
478
+ # fig = plt.figure(figsize=(10, 5)) # Default size if no data
479
+ # plt.text(0.5, 0.5, 'No data to display', horizontalalignment='center', verticalalignment='center')
480
+ #
481
+ # return fig
482
+ #
483
+ #
484
+ # dashboard_cell_centric = pn.Column(pn.Row(class_selector, subclass_selector, groupby_selector, sortby_selector),
485
+ # pn.pane.Matplotlib(heatmap_cell_centric, sizing_mode='stretch_width'))
486
+ #
487
+ # title = "5-HT Transcriptomic"
488
+ # pn.template.BootstrapTemplate(
489
+ # header_background="#F9B9B7",
490
+ # logo="https://upload.wikimedia.org/wikipedia/commons/5/51/Logo_Charite.svg",
491
+ # title="5-HT Transcriptomics",
492
+ # main=pn.Column(
493
+ # pn.Tabs(
494
+ # ("Spatial", dashboard_spatial), # Add your spatial content here
495
+ # ("Receptor-centric", dashboard_receptor_centric),
496
+ # ("Cell-centric", dashboard_cell_centric),
497
+ # dynamic=True
498
+ # )
499
+ # )
500
+ # ).servable(title=title)