RDeF654875678597657 commited on
Commit
d0f36ec
·
1 Parent(s): 0468c1c

add app + requirements.txt

Browse files
Files changed (2) hide show
  1. app.py +469 -133
  2. requirements.txt +6 -4
app.py CHANGED
@@ -1,147 +1,483 @@
1
- import io
2
- import random
3
- from typing import List, Tuple
4
-
5
- import aiohttp
6
  import panel as pn
7
- from PIL import Image
8
- from transformers import CLIPModel, CLIPProcessor
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  pn.extension(design="bootstrap", sizing_mode="stretch_width")
11
 
12
- ICON_URLS = {
13
- "brand-github": "https://github.com/holoviz/panel",
14
- "brand-twitter": "https://twitter.com/Panel_Org",
15
- "brand-linkedin": "https://www.linkedin.com/company/panel-org",
16
- "message-circle": "https://discourse.holoviz.org/",
17
- "brand-discord": "https://discord.gg/AXRHnJU6sP",
18
- }
19
 
 
20
 
21
- async def random_url(_):
22
- pet = random.choice(["cat", "dog"])
23
- api_url = f"https://api.the{pet}api.com/v1/images/search"
24
- async with aiohttp.ClientSession() as session:
25
- async with session.get(api_url) as resp:
26
- return (await resp.json())[0]["url"]
27
 
 
28
 
29
- @pn.cache
30
- def load_processor_model(
31
- processor_name: str, model_name: str
32
- ) -> Tuple[CLIPProcessor, CLIPModel]:
33
- processor = CLIPProcessor.from_pretrained(processor_name)
34
- model = CLIPModel.from_pretrained(model_name)
35
- return processor, model
36
 
 
 
37
 
38
- async def open_image_url(image_url: str) -> Image:
39
- async with aiohttp.ClientSession() as session:
40
- async with session.get(image_url) as resp:
41
- return Image.open(io.BytesIO(await resp.read()))
42
 
43
 
44
- def get_similarity_scores(class_items: List[str], image: Image) -> List[float]:
45
- processor, model = load_processor_model(
46
- "openai/clip-vit-base-patch32", "openai/clip-vit-base-patch32"
47
- )
48
- inputs = processor(
49
- text=class_items,
50
- images=[image],
51
- return_tensors="pt", # pytorch tensors
52
- )
53
- outputs = model(**inputs)
54
- logits_per_image = outputs.logits_per_image
55
- class_likelihoods = logits_per_image.softmax(dim=1).detach().numpy()
56
- return class_likelihoods[0]
57
-
58
-
59
- async def process_inputs(class_names: List[str], image_url: str):
60
- """
61
- High level function that takes in the user inputs and returns the
62
- classification results as panel objects.
63
- """
64
- try:
65
- main.disabled = True
66
- if not image_url:
67
- yield "##### ⚠️ Provide an image URL"
68
- return
69
-
70
- yield "##### ⚙ Fetching image and running model..."
71
- try:
72
- pil_img = await open_image_url(image_url)
73
- img = pn.pane.Image(pil_img, height=400, align="center")
74
- except Exception as e:
75
- yield f"##### 😔 Something went wrong, please try a different URL!"
76
- return
77
-
78
- class_items = class_names.split(",")
79
- class_likelihoods = get_similarity_scores(class_items, pil_img)
80
-
81
- # build the results column
82
- results = pn.Column("##### 🎉 Here are the results!", img)
83
-
84
- for class_item, class_likelihood in zip(class_items, class_likelihoods):
85
- row_label = pn.widgets.StaticText(
86
- name=class_item.strip(), value=f"{class_likelihood:.2%}", align="center"
87
- )
88
- row_bar = pn.indicators.Progress(
89
- value=int(class_likelihood * 100),
90
- sizing_mode="stretch_width",
91
- bar_color="secondary",
92
- margin=(0, 10),
93
- design=pn.theme.Material,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  )
95
- results.append(pn.Column(row_label, row_bar))
96
- yield results
97
- finally:
98
- main.disabled = False
99
-
100
-
101
- # create widgets
102
- randomize_url = pn.widgets.Button(name="Randomize URL", align="end")
103
-
104
- image_url = pn.widgets.TextInput(
105
- name="Image URL to classify",
106
- value=pn.bind(random_url, randomize_url),
107
- )
108
- class_names = pn.widgets.TextInput(
109
- name="Comma separated class names",
110
- placeholder="Enter possible class names, e.g. cat, dog",
111
- value="cat, dog, parrot",
112
- )
113
-
114
- input_widgets = pn.Column(
115
- "##### 😊 Click randomize or paste a URL to start classifying!",
116
- pn.Row(image_url, randomize_url),
117
- class_names,
118
- )
119
-
120
- # add interactivity
121
- interactive_result = pn.panel(
122
- pn.bind(process_inputs, image_url=image_url, class_names=class_names),
123
- height=600,
124
- )
125
-
126
- # add footer
127
- footer_row = pn.Row(pn.Spacer(), align="center")
128
- for icon, url in ICON_URLS.items():
129
- href_button = pn.widgets.Button(icon=icon, width=35, height=35)
130
- href_button.js_on_click(code=f"window.open('{url}')")
131
- footer_row.append(href_button)
132
- footer_row.append(pn.Spacer())
133
-
134
- # create dashboard
135
- main = pn.WidgetBox(
136
- input_widgets,
137
- interactive_result,
138
- footer_row,
139
- )
140
-
141
- title = "Panel Demo - Image Classification"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  pn.template.BootstrapTemplate(
143
- title=title,
144
- main=main,
145
- main_max_width="min(50%, 698px)",
146
- header_background="#F08080",
147
- ).servable(title=title)
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
 
 
 
 
2
  import panel as pn
3
+ import holoviews as hv
4
+ from holoviews import dim, opts
5
+ import numpy as np
6
+ import param
7
+ import matplotlib.pyplot as plt
8
+ import matplotlib.gridspec as gridspec
9
+ import seaborn as sns
10
+ import matplotlib.patheffects as path_effects
11
+ import matplotlib.colors as mcolors
12
+ import matplotlib.colors as plt_colors
13
+
14
+ genes_families = {
15
+ 'Htr1': ['Htr1a', 'Htr1b', 'Htr1d', 'Htr1f'],
16
+ 'Htr2': ['Htr2a', 'Htr2b', 'Htr2c'],
17
+ 'Htr3': ['Htr3a', 'Htr3b'],
18
+ 'Htr4': ['Htr4'],
19
+ 'Htr5': ['Htr5a', 'Htr5b'],
20
+ 'Htr6': ['Htr6'],
21
+ 'Htr7': ['Htr7']
22
+ }
23
+ base_colors = sns.color_palette("husl", n_colors=len(genes_families))
24
+ genes_cmap = {}
25
+
26
+
27
+ for idx, (family, members) in enumerate(genes_families.items()):
28
+ shades = sns.light_palette(base_colors[idx], n_colors=len(members) + 1)[1:]
29
+ for receptor, shade in zip(members, shades):
30
+ genes_cmap[receptor] = shade
31
+
32
+ # Convert RGB to HEX
33
+
34
+ genes_cmap_rgb = {k: plt_colors.rgb2hex(v) for k, v in genes_cmap.items()}
35
+
36
+ threshold_expression = 3.5 # for RNAseq
37
+ threshold_expression_MERFISH = .5
38
+ neuron_cluster_groups_order = ['Pallium-Glut', 'Subpallium-GABA', 'MB-HB-CB-GABA','MB-HB-Glut-Sero-Dopa', 'HY-EA-Glut-GABA','TH-EPI-Glut','NN-IMN-GC']
39
+
40
+
41
+ def percentage_above_threshold(series):
42
+ return (series > threshold_expression).sum() / len(series) * 100
43
+
44
+ threshold_expression_MERFISH = .5
45
+ def percentage_above_threshold_MER(series):
46
+ return (series > threshold_expression_MERFISH).sum() / len(series) * 100
47
 
48
  pn.extension(design="bootstrap", sizing_mode="stretch_width")
49
 
 
 
 
 
 
 
 
50
 
51
+ datasets = ['Zhuang-ABCA-1','Zhuang-ABCA-2','Zhuang-ABCA-3','Zhuang-ABCA-4']
52
 
53
+ sub_cell_expression = pd.read_csv("./Data/sub_cell_expression")
54
+ joined_with_membership_sub = pd.read_csv("./Data/joined_with_membership_sub.csv")
 
 
 
 
55
 
56
+ joined_sub = pd.read_csv("./Data/joined_sub.csv")
57
 
58
+ gene_filtered = pd.read_csv( "./Data/selected_genes_RNAseq.csv")
59
+ selected_genes_cl = np.sort(gene_filtered["gene_symbol"].values)
 
 
 
 
 
60
 
61
+ gene_filtered = pd.read_csv("./Data/selected_genes_MERFISH.csv")
62
+ selected_genes = np.sort(gene_filtered["gene_symbol"].values)
63
 
64
+ dataset = datasets[0]
 
 
 
65
 
66
 
67
+ class MERFISH_viz(param.Parameterized):
68
+ dataset_selector = param.Selector(objects=datasets)
69
+ brain_section_index = param.Integer(default=0, bounds=(
70
+ 0, sub_cell_expression[datasets[0]]["brain_section_label"].unique().shape[0]))
71
+ gene_selector = param.ObjectSelector(default=selected_genes[0], objects=selected_genes.tolist())
72
+ class_selector = param.ListSelector(default=sorted(sub_cell_expression[dataset]['class'].unique()),
73
+ objects=sorted(sub_cell_expression[dataset]['class'].unique()))
74
+ subclass_selector = param.ListSelector(default=sorted(sub_cell_expression[dataset]['subclass'].unique()),
75
+ objects=sorted(sub_cell_expression[dataset]['subclass'].unique()))
76
+
77
+ # Naming the keyword arguments `**params` is purely a convention.
78
+ def __init__(self, sub_cell_expression, sel_dataset, sel_class, sel_subclass, brain_section_index, **params):
79
+ super().__init__(**params)
80
+ self.sub_cell_expression = sub_cell_expression
81
+ self.current_data = self.sub_cell_expression[sel_dataset]
82
+ self.filtered_data = self.current_data[
83
+ self.current_data['class'].isin(sel_class) & self.current_data['subclass'].isin(sel_subclass)]
84
+
85
+ brain_section = self.current_data['brain_section_label'].unique()[brain_section_index]
86
+ section = self.filtered_data[self.filtered_data['brain_section_label'] == brain_section]
87
+
88
+ self.section = section[section['parcellation_division'] != "unassigned"]
89
+
90
+ self.control_panel = pn.Row(
91
+ pn.Param(self.param['dataset_selector']),
92
+ pn.Param(self.param['brain_section_index']),
93
+ pn.Param(self.param['gene_selector']),
94
+ pn.Param(self.param['class_selector']),
95
+ pn.Param(self.param['subclass_selector'])
96
+ )
97
+
98
+ @param.depends('dataset_selector', 'brain_section_index', 'gene_selector', 'class_selector', 'subclass_selector')
99
+ def view(self):
100
+ return pn.Column(
101
+ f'Selected dataset: {self.dataset_selector}',
102
+ f'Brain Section Index: {self.brain_section_index}',
103
+ f'Selected Gene: {self.gene_selector}',
104
+ f'Selected Classes: {self.class_selector}, {self.subclass_selector}')
105
+
106
+ @pn.depends("filter_by_class_subclass", "gene_selector", "brain_section_index")
107
+ def plot_expr_across_slices(self):
108
+ curve_data = self.filtered_data[self.filtered_data[self.gene_selector] > 0].groupby('brain_section_label')[
109
+ self.gene_selector].mean()
110
+ curve_data.rename(f"Expression {self.gene_selector}", inplace=True)
111
+ curve = hv.Curve(curve_data, label=f'Log(CPM) {self.gene_selector}').opts(xaxis=None, height=140,
112
+ responsive=True, active_tools=[])
113
+
114
+ grouped_data = self.filtered_data.groupby('brain_section_label')[self.gene_selector].apply(
115
+ percentage_above_threshold_MER).reset_index()
116
+ grouped_data.rename(columns={self.gene_selector: f"% expressing {self.gene_selector}"}, inplace=True)
117
+ percentage_curve = hv.Curve(grouped_data, 'brain_section_label', f"% expressing {self.gene_selector}",
118
+ label=f'Percentage expressing {self.gene_selector}').opts(xaxis=None,
119
+ height=140,
120
+ responsive=True,
121
+ active_tools=[])
122
+
123
+ vline = hv.VLine(self.brain_section_index).opts(line_color='red', line_width=2)
124
+ percentage_of_all_cells = ((self.filtered_data.groupby(
125
+ 'brain_section_label').size() / self.current_data.groupby('brain_section_label').size()) * 100).fillna(0)
126
+ percentage_of_all_cells.name = "% of all cells"
127
+ ratio_cells = hv.Curve(percentage_of_all_cells, 'brain_section_label', "% of all cells",
128
+ label='Percentage of all cells').opts(xaxis=None,
129
+ height=100,
130
+ responsive=True,
131
+ active_tools=[])
132
+
133
+ return hv.Layout([(ratio_cells * vline), (curve * vline), (percentage_curve * vline)]).cols(1)
134
+
135
+ @pn.depends("filter_by_class_subclass", "gene_selector", "brain_section_index")
136
+ def plot_bar(self):
137
+ color_map = self.section.groupby('parcellation_structure')['parcellation_structure_color'].first().to_dict()
138
+
139
+ hv_ds = hv.Dataset(self.section.groupby(['parcellation_structure'])[self.gene_selector].apply(
140
+ percentage_above_threshold_MER).sort_values(ascending=False).head(20).reset_index(),
141
+ kdims=['parcellation_structure'], vdims=[self.gene_selector])
142
+
143
+ # Create the vertical Bar chart with rotated xticklabels
144
+ bar_plot = hv.Bars(hv_ds).opts(
145
+ color=dim('parcellation_structure').categorize(color_map, 'gray'),
146
+ active_tools=[],
147
+ tools=["hover"],
148
+ responsive=True,
149
+ frame_height=100,
150
+ invert_axes=False,
151
+ xrotation=90 # Rotate xticklabels by 90 degrees
152
+ )
153
+ return bar_plot
154
+
155
+ @pn.depends("filter_by_class_subclass", "gene_selector", "get_section")
156
+ def plot_section(self):
157
+ plot1 = hv.Points(data=self.section, kdims=['x', 'y'],
158
+ vdims=[self.gene_selector, 'parcellation_structure', 'parcellation_substructure']).opts(
159
+ width=550, colorbar=True, cmap='rocket_r', size=2, color=self.gene_selector)
160
+ plot2 = hv.NdOverlay({division: hv.Points(self.section[self.section['parcellation_division'] == division],
161
+ ['x', 'y'], ['parcellation_division_color', 'parcellation_structure',
162
+ 'parcellation_substructure']).opts(
163
+ color='parcellation_division_color', size=2) for division in
164
+ self.section[self.section['parcellation_category'] == "grey"][
165
+ 'parcellation_division'].unique()}, kdims='parcellation_division').opts(
166
+ legend_position='right', width=650, show_legend=True)
167
+
168
+ common_opts = opts.Points(height=500, invert_yaxis=True, xaxis=None, yaxis=None, show_grid=False,
169
+ active_tools=[], tools=["hover"])
170
+
171
+ return (plot1 + plot2).opts(common_opts)
172
+
173
+ @param.depends("brain_section_index", watch=True)
174
+ def get_section(self):
175
+ brain_section = self.current_data['brain_section_label'].unique()[self.brain_section_index]
176
+ section = self.filtered_data[self.filtered_data['brain_section_label'] == brain_section]
177
+ self.section = section[section['parcellation_division'] != "unassigned"]
178
+
179
+ @param.depends('dataset_selector', watch=True)
180
+ def update_current_data(self):
181
+ self.current_data = self.sub_cell_expression[self.dataset_selector]
182
+ self.brain_section_index = 0
183
+ self.brain_section_index.bounds = (0, self.current_data["brain_section_label"].unique().shape[0])
184
+
185
+ @param.depends("update_current_data", 'class_selector', 'subclass_selector', watch=True)
186
+ def filter_by_class_subclass(self):
187
+ self.filtered_data = self.current_data[
188
+ self.current_data['class'].isin(self.class_selector) & self.current_data['subclass'].isin(
189
+ self.subclass_selector)]
190
+
191
+ @param.depends("update_current_data", 'class_selector', watch=True)
192
+ def update_subclasses(self):
193
+ self.param.subclass_selector.objects = sorted(
194
+ self.current_data[self.current_data['class'].isin(self.class_selector)]['subclass'].unique())
195
+ self.subclass_selector = sorted(
196
+ self.current_data[(self.current_data['class'].isin(self.class_selector))]['subclass'].unique())
197
+
198
+
199
+ viz = MERFISH_viz(sub_cell_expression, datasets[0], sub_cell_expression[datasets[0]]["class"].unique(),
200
+ sub_cell_expression[dataset]["subclass"].unique(), 0)
201
+
202
+ # Title of the paper and authors
203
+ # Custom HTML for the title
204
+ custom_title_html = """
205
+ <div style="text-align: center; max-width: 1200px; margin: 20px auto;">
206
+ <h1 style="font-weight: 900; font-size: 3rem; margin: 0rem">
207
+ Transcriptomic Mapping of the 5-HT Receptor Landscape
208
+ </h1>
209
+ <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
210
+ Roberto De Filippo<sup>#</sup>, Dietmar Schmitz
211
+ </h2>
212
+ <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
213
+ <sup>#</sup>Corresponding author
214
+ </h2>
215
+ <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
216
+ [<a href="https://github.com/RobertoDF/5-HT2A-MERFISH" style="color:blue;">Article</a>]
217
+ [<a href="https://github.com/RobertoDF/5-HT2A-MERFISH" style="color:blue;">Github</a>]
218
+ </h2>
219
+ <h2 style="font-weight: 450; font-size: 1rem;">
220
+ 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>
221
+ <h2 style="font-weight: 450; font-size: 1rem;">
222
+ By <b>Roberto De Filippo</b>
223
+ </h2>
224
+ </div>
225
+ """
226
+
227
+ # Create a Panel HTML pane with the custom title
228
+ custom_title_pane = pn.pane.HTML(custom_title_html, sizing_mode='stretch_width')
229
+
230
+ dashboard_spatial = pn.Column(custom_title_pane, viz.control_panel, viz.plot_expr_across_slices, viz.plot_bar, viz.plot_section)
231
+
232
+
233
+ def plot_class_expression_split_by_categories(subfig, cls, df_subset, gene):
234
+ axs = subfig.subplots(4, 1)
235
+ subfig.subplots_adjust(left=0.05, right=.95)
236
+
237
+ sns.violinplot(data=df_subset, y=f'{gene} prevalence (%)', x='subclass', hue='subclass', ax=axs[0],
238
+ palette=classification_cmap, fill=False)
239
+
240
+ # Set the title with desired modifications
241
+ title = axs[0].set_title(cls, color=classification_cmap[cls], fontweight='bold', fontsize=20)
242
+ title.set_path_effects([path_effects.withStroke(linewidth=3, foreground='black')])
243
+
244
+ subfig.set_facecolor(mcolors.to_rgba(classification_cmap[cls], alpha=0.15))
245
+
246
+ axs[0].set_ylim(0, 100) # Set y-axis limit to 1
247
+ axs[0].xaxis.set_ticks_position('top')
248
+ axs[0].tick_params(axis='x', length=0)
249
+
250
+ sns.violinplot(data=df_subset, y=f'{gene} prevalence (%)', x='supertype', hue='supertype', ax=axs[1],
251
+ palette=classification_cmap, fill=False)
252
+ axs[1].set_title(cls)
253
+ axs[1].set_ylim(0, 100) # Set y-axis limit to 1
254
+
255
+ sns.barplot(data=df_subset, y=f'{gene} prevalence (%)', x='cluster', hue='cluster', ax=axs[2],
256
+ palette=classification_cmap)
257
+ axs[2].set_title(cls)
258
+ axs[2].set_ylim(0, 100) # Set y-axis limit to 1
259
+
260
+ axs[2].set(ylabel='')
261
+ axs[0].set(ylabel='')
262
+ axs[2].set(xticks=[], xlabel='')
263
+ axs[1].set(xticks=[], xlabel='')
264
+ axs[0].set(xticks=[], xlabel='')
265
+ axs[0].set(xlabel='')
266
+ axs[2].set(xticks=[], xlabel='')
267
+ axs[2].set(xticks=[], xlabel='')
268
+ axs[1].set_title('')
269
+ axs[2].set_title('')
270
+ plt.draw()
271
+ for tick in axs[0].get_xticklabels():
272
+ tick.set_color(classification_cmap[tick.get_text()])
273
+
274
+ # Identify positions for subclass delimiters in the cluster graph
275
+ subclass_ends = df_subset.groupby('subclass').size().cumsum()
276
+ subclass_positions = subclass_ends - 1
277
+
278
+ # For the third plot (clusters):
279
+ for pos in subclass_positions[:-1]:
280
+ axs[2].axvline(pos + 0.5, color='gray', linestyle='--')
281
+
282
+ # For the first plot (subclass), simply draw lines between unique subclasses
283
+ for i in range(1, len(df_subset['subclass'].unique())):
284
+ axs[0].axvline(i - 0.5, color='gray', linestyle='--')
285
+
286
+ # For the second plot (supertype), the position will be based on unique supertypes per subclass
287
+ supertype_ends = df_subset.groupby('subclass')['supertype'].nunique().cumsum()
288
+ supertype_positions = supertype_ends - 1
289
+ for pos in supertype_positions[:-1]:
290
+ axs[1].axvline(pos + 0.5, color='gray', linestyle='--')
291
+
292
+ # For the first plot (subclass):
293
+ subclasses = df_subset['subclass'].unique()
294
+ start = -.5
295
+ for i, subclass in enumerate(subclasses):
296
+ end = i + 0.5
297
+ color = classification_cmap[subclass]
298
+ axs[0].axvspan(start + .05, end - .05, facecolor=color, alpha=0.15)
299
+ start = end
300
+
301
+ # For the second plot (supertype), determine filling areas based on unique supertypes per subclass
302
+ supertype_ends = df_subset.groupby('subclass')['supertype'].nunique().cumsum()
303
+ supertype_positions = supertype_ends - 1
304
+
305
+ previous_position = -0.5 # initialize to start from the first entry
306
+ for idx, pos in enumerate(supertype_positions):
307
+ current_position = pos + 0.5
308
+ # Retrieve the subclass name for the current supertype
309
+ subclass_name = df_subset['subclass'].unique()[idx]
310
+ color = classification_cmap[subclass_name]
311
+
312
+ axs[1].axvspan(previous_position + 0.2, current_position - .2, facecolor=color, alpha=0.15)
313
+
314
+ previous_position = current_position # set for the next iteration
315
+
316
+ ####third plot filling
317
+ # Get a mapping of subclasses to their dominant cluster
318
+ subclass_to_cluster = df_subset.groupby('subclass')['cluster'].apply(lambda x: x.value_counts().idxmax())
319
+
320
+ # Define previous position to help us fill areas between borders
321
+ prev_pos = 0
322
+
323
+ # Iterate over the subclass positions and the corresponding subclasses
324
+ for idx, (subclass, cluster) in enumerate(subclass_to_cluster.items()):
325
+ # Get the color for this subclass's dominant cluster from your cmap
326
+ color_value = classification_cmap[cluster]
327
+
328
+ # End position is either the next border position or the end of the plot
329
+ end_pos = subclass_positions.iloc[idx] if idx < len(subclass_positions) else len(df_subset['cluster']) - 1
330
+
331
+ # Fill the area with the given color
332
+ axs[2].fill_between([prev_pos, end_pos], 0, 100, color=color_value, alpha=0.15)
333
+
334
+ # Update the previous position to the current position
335
+ prev_pos = end_pos + 1
336
+
337
+ # Adjust the xlim of each axis
338
+ axs[0].set_xlim(-0.5, len(df_subset['subclass'].unique()) - 0.5)
339
+ axs[1].set_xlim(-0.5, len(df_subset['supertype'].unique()) - 0.5)
340
+ axs[2].set_xlim(-.8, len(df_subset['cluster'].unique()))
341
+
342
+ # Now, add legend in the fourth axis:
343
+ patches = [plt.Line2D([0], [0], color=classification_cmap[c], lw=8) for c in df_subset["subclass"].unique()]
344
+ labels = list(df_subset["subclass"].unique())
345
+
346
+ axs[3].legend(patches, labels, loc='center', ncol=6, handlelength=1.8, handleheight=1)
347
+ axs[3].axis('off') # Hide axis
348
+
349
+ sns.despine(bottom=True)
350
+
351
+
352
+ group_selector = pn.widgets.Select(name='Group', options=neuron_cluster_groups_order, value=neuron_cluster_groups_order[0])
353
+ gene_selector = pn.widgets.Select(name='Gene', options=list(selected_genes_cl), value=selected_genes_cl[0])
354
+
355
+
356
+ @pn.depends(group_selector, gene_selector)
357
+ def interactive_plot(group, gene):
358
+ global global_saved_fig, group_g, gene_g
359
+ data = joined_with_membership_sub[joined_with_membership_sub["cluster_group_name"] == group]
360
+ data = data.groupby(["cluster_group_name", "class", "subclass", "supertype", "cluster"])[gene].apply(
361
+ percentage_above_threshold).reset_index()
362
+ data = data[data["cluster_group_name"] != "WholeBrain"]
363
+ data["cluster_group_name"] = pd.Categorical(data["cluster_group_name"], categories=neuron_cluster_groups_order,
364
+ ordered=True)
365
+ data = data.sort_values(by=["cluster_group_name", "class"])
366
+
367
+ data.rename(columns={gene: f'{gene} prevalence (%)'}, inplace=True)
368
+
369
+ fig = plt.figure(figsize=(25, 5 * data['class'].nunique()))
370
+ gs = gridspec.GridSpec(data['class'].nunique(), 1)
371
+
372
+ for n, cls in enumerate(data['class'].unique()):
373
+ df_subset = data[data['class'] == cls]
374
+ subfig = fig.add_subfigure(gs[n, :])
375
+ subfig.subplots_adjust(left=0.05, right=.95, bottom=0.01)
376
+ plot_class_expression_split_by_categories(subfig, cls, df_subset, gene)
377
+
378
+ global_saved_fig = fig
379
+ group_g = group
380
+ gene_g = gene
381
+
382
+ fig.suptitle(group, y=1.04, fontweight='bold', fontsize=20);
383
+ print(group, gene)
384
+
385
+ return fig
386
+
387
+ classification_cmap = joined_sub.drop_duplicates(subset='subclass').set_index('subclass')['subclass_color'].to_dict()
388
+ classification_cmap.update(joined_sub.drop_duplicates(subset='supertype').set_index('supertype')['subclass_color'].to_dict())
389
+ classification_cmap.update(joined_sub.drop_duplicates(subset='cluster').set_index('cluster')['subclass_color'].to_dict())
390
+ classification_cmap.update(joined_sub.drop_duplicates(subset='class').set_index('class')['class_color'].to_dict())
391
+
392
+
393
+
394
+ save_button = pn.widgets.Button(name="Save Figure", button_type='primary')
395
+
396
+
397
+
398
+ dashboard_receptor_centric = pn.Column(
399
+ pn.Row(group_selector, gene_selector, save_button),
400
+ pn.pane.Matplotlib(interactive_plot, sizing_mode = 'stretch_width')
401
  )
402
+
403
+
404
+ def update_subclass_selector(event):
405
+ selected_classes = event.new
406
+ if "None" in selected_classes or not selected_classes:
407
+ all_subclasses = sorted(joined_sub["subclass"].unique().tolist())
408
+ else:
409
+ all_subclasses = sorted(joined_sub[joined_sub["class"].isin(selected_classes)]["subclass"].unique().tolist())
410
+ subclass_selector.options = ["None"] + all_subclasses
411
+ subclass_selector.value = ["None"]
412
+
413
+
414
+ class_selector = pn.widgets.MultiSelect(name='Class selector',
415
+ options=["None"] + sorted(joined_sub["class"].unique().tolist()),
416
+ value=[joined_sub["class"].unique()[0]])
417
+ subclass_selector = pn.widgets.MultiSelect(name='Subclass selector',
418
+ options=["None"] + sorted(joined_sub["subclass"].unique().tolist()),
419
+ value=["None"])
420
+ groupby_selector = pn.widgets.Select(name='Group by', options=["class", "subclass", "supertype", "cluster"],
421
+ value="class")
422
+ sortby_selector = pn.widgets.Select(name='Sort by', options=["class"] + list(selected_genes_cl), value="class")
423
+
424
+ class_selector.param.watch(update_subclass_selector, 'value')
425
+
426
+
427
+ @pn.depends(class_selector, subclass_selector, groupby_selector, sortby_selector)
428
+ def heatmap_cell_centric(class_, subclass, groupby, sortby):
429
+ if class_ != ["None"] or subclass != ["None"]:
430
+
431
+ filtered_data = joined_sub
432
+ if "None" not in class_:
433
+ filtered_data = filtered_data[filtered_data["class"].isin(class_)]
434
+ if "None" not in subclass:
435
+ filtered_data = filtered_data[filtered_data["subclass"].isin(subclass)]
436
+
437
+ if sortby == "class":
438
+ sortby = groupby
439
+ ascending = True
440
+ else:
441
+ ascending = False
442
+
443
+ num_rows = len(filtered_data.groupby(groupby))
444
+ fig_height = max(5, num_rows * 0.2) # Set a minimum height and scale per row
445
+
446
+ fig, ax = plt.subplots(figsize=(10, fig_height))
447
+ sns.heatmap(
448
+ filtered_data.groupby(groupby)[selected_genes_cl].apply(percentage_above_threshold).sort_values(sortby,
449
+ ascending=ascending),
450
+ yticklabels=True, cmap=sns.light_palette("#CC5656", as_cmap=True), ax=ax, cbar=False, vmax=90)
451
+
452
+ for ytick in ax.get_xticklabels():
453
+ ytick.set_color(genes_cmap_rgb[ytick.get_text()])
454
+ for ytick in ax.get_yticklabels():
455
+ ytick.set_color(classification_cmap[ytick.get_text()])
456
+
457
+ plt.tight_layout()
458
+ else:
459
+ fig = plt.figure(figsize=(10, 5)) # Default size if no data
460
+ plt.text(0.5, 0.5, 'No data to display', horizontalalignment='center', verticalalignment='center')
461
+
462
+ return fig
463
+
464
+
465
+ dashboard_cell_centric = pn.Column(pn.Row(class_selector, subclass_selector, groupby_selector, sortby_selector),
466
+ pn.pane.Matplotlib(heatmap_cell_centric, sizing_mode='stretch_width'))
467
+
468
+ title = "5-HT Transcriptomic"
469
  pn.template.BootstrapTemplate(
470
+ header_background="#F9B9B7",
471
+ logo="https://upload.wikimedia.org/wikipedia/commons/5/51/Logo_Charite.svg",
472
+ title="5-HT Transcriptomics",
473
+ main=pn.Column(
474
+ pn.Tabs(
475
+ ("Spatial", dashboard_spatial), # Add your spatial content here
476
+ ("Receptor-centric", dashboard_receptor_centric),
477
+ ("Cell-centric", dashboard_cell_centric),
478
+ dynamic=True
479
+ )
480
+ )
481
+ ).servable(title=title)
482
+
483
+
requirements.txt CHANGED
@@ -1,6 +1,8 @@
1
  panel
2
- jupyter
3
- transformers
 
4
  numpy
5
- torch
6
- aiohttp
 
 
1
  panel
2
+ pandas
3
+ holoviews
4
+ python==3.11.7
5
  numpy
6
+ matplotlib
7
+ seaborn
8
+