import os os.environ['MPLCONFIGDIR'] = '/tmp/matplotlib' os.makedirs(os.environ['MPLCONFIGDIR'], exist_ok=True) import pandas as pd import panel as pn import holoviews as hv from holoviews import dim, opts import numpy as np import param import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import seaborn as sns import matplotlib.patheffects as path_effects import matplotlib.colors as mcolors import matplotlib.colors as plt_colors import pickle import hvplot.pandas pn.extension(design="bootstrap", sizing_mode="stretch_width", throttled=True) order_division = ['Isocortex', 'OLF', 'HPF', 'CTXsp', 'STR', 'PAL', 'TH', 'HY', 'MB', 'P', 'MY', 'CB',] threshold_expression = 3.5 # for RNAseq threshold_expression_MERFISH = .5 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'] def percentage_above_threshold(series): return (series > threshold_expression).sum() / len(series) * 100 threshold_expression_MERFISH = .5 def percentage_above_threshold_MER(series): return (series > threshold_expression_MERFISH).sum() / len(series) * 100 datasets = ['Zhuang-ABCA-1','Zhuang-ABCA-2','Zhuang-ABCA-3','Zhuang-ABCA-4'] with open("./Data/sub_cell_expression.pickle", "rb") as f: merfish_data = pickle.load(f) transcriptomic_data_sub = pd.read_csv("./Data/joined_with_membership_sub.csv") joined_sub = pd.read_csv("./Data/joined_sub.csv") gene_filtered = pd.read_csv("Data/selected_genes_RNAseq.csv") selected_genes_cl = np.sort(gene_filtered["gene_symbol"].values) gene_filtered = pd.read_csv("Data/selected_genes_MERFISH.csv") selected_genes = np.sort(gene_filtered["gene_symbol"].values) dataset = datasets[0] print(joined_sub.columns) #df_pane = pn.pane.DataFrame(joined_sub, width=400) classification_cmap = joined_sub.drop_duplicates(subset='subclass').set_index('subclass')['subclass_color'].to_dict() classification_cmap.update(joined_sub.drop_duplicates(subset='supertype').set_index('supertype')['subclass_color'].to_dict()) classification_cmap.update(joined_sub.drop_duplicates(subset='cluster').set_index('cluster')['subclass_color'].to_dict()) classification_cmap.update(joined_sub.drop_duplicates(subset='class').set_index('class')['class_color'].to_dict()) class MERFISH_viz(param.Parameterized): dataset_selector = param.Selector(objects=datasets) brain_section_index = param.Integer(default=0, bounds=( 0, merfish_data[datasets[0]]["brain_section_label"].unique().shape[0])) gene_selector = param.ObjectSelector(default=selected_genes[0], objects=selected_genes.tolist()) class_selector = param.ListSelector(default=sorted(merfish_data[dataset]['class'].unique()), objects=sorted(merfish_data[dataset]['class'].unique())) subclass_selector = param.ListSelector(default=sorted(merfish_data[dataset]['subclass'].unique()), objects=sorted(merfish_data[dataset]['subclass'].unique())) section_updated = param.Event() filtered_data_updated = param.Event() dataset_updated = param.Event() # Naming the keyword arguments `**params` is purely a convention. def __init__(self, merfish_data, sel_dataset, sel_class, sel_subclass, brain_section_index, **params): super().__init__(**params) self.merfish_data = merfish_data self.current_data = self.merfish_data[sel_dataset] self.filtered_data = self.current_data[ self.current_data['class'].isin(sel_class) & self.current_data['subclass'].isin(sel_subclass)] brain_section = self.current_data['brain_section_label'].unique()[brain_section_index] section = self.filtered_data[self.filtered_data['brain_section_label'] == brain_section] self.section = section[section['parcellation_division'] != "unassigned"] self.control_panel = pn.Row( pn.Param(self.param['dataset_selector']), pn.Param(self.param['brain_section_index']), pn.Param(self.param['gene_selector']), pn.Param(self.param['class_selector']), pn.Param(self.param['subclass_selector']) ) @pn.depends("filtered_data_updated", "gene_selector", "brain_section_index") def plot_expr_across_slices(self): curve_data = self.filtered_data[self.filtered_data[self.gene_selector] > 0].groupby('brain_section_label')[ self.gene_selector].mean() curve_data.rename(f"Expression {self.gene_selector}", inplace=True) curve = hv.Curve(curve_data, label=f'Log(CPM) {self.gene_selector}').opts(xaxis=None, height=140, responsive=True, active_tools=[]) grouped_data = self.filtered_data.groupby('brain_section_label')[self.gene_selector].apply( percentage_above_threshold_MER).reset_index() grouped_data.rename(columns={self.gene_selector: f"% expressing {self.gene_selector}"}, inplace=True) percentage_curve = hv.Curve(grouped_data, 'brain_section_label', f"% expressing {self.gene_selector}", label=f'Percentage expressing {self.gene_selector}').opts(xaxis=None, height=140, responsive=True, active_tools=[]) vline = hv.VLine(self.brain_section_index).opts(line_color='red', line_width=2) percentage_of_all_cells = ((self.filtered_data.groupby( 'brain_section_label').size() / self.current_data.groupby('brain_section_label').size()) * 100).fillna(0) percentage_of_all_cells.name = "% of all cells" ratio_cells = hv.Curve(percentage_of_all_cells, 'brain_section_label', "% of all cells", label='Percentage of all cells').opts(xaxis=None, height=100, responsive=True, active_tools=[]) return hv.Layout([(ratio_cells * vline), (curve * vline), (percentage_curve * vline)]).cols(1) @pn.depends("section_updated", "gene_selector") def plot_bar(self): color_map = self.section.groupby('parcellation_structure')['parcellation_structure_color'].first().to_dict() hv_ds = hv.Dataset(self.section.groupby(['parcellation_structure'])[self.gene_selector].apply( percentage_above_threshold_MER).sort_values(ascending=False).head(20).reset_index(), kdims=['parcellation_structure'], vdims=[self.gene_selector]) # Create the vertical Bar chart with rotated xticklabels bar_plot = hv.Bars(hv_ds).opts( color=dim('parcellation_structure').categorize(color_map, 'gray'), active_tools=[], tools=["hover"], responsive=True, frame_height=100, invert_axes=False, xrotation=90 # Rotate xticklabels by 90 degrees ) grouped_data = self.section.groupby(['parcellation_structure'])[self.gene_selector].apply( percentage_above_threshold_MER).sort_values( ascending=False).head(30).reset_index() counts = self.section['parcellation_structure'].value_counts().reindex( grouped_data['parcellation_structure']).fillna(0) labels = hv.Labels( {'x': grouped_data['parcellation_structure'], 'y': grouped_data[self.gene_selector], 'text': counts}, ['x', 'y'], 'text').opts(text_font_size='8pt', text_color="black", yoffset=-5) return bar_plot * labels @pn.depends("section_updated", "gene_selector") def plot_section(self): plot1 = hv.Points(data=self.section, kdims=['x', 'y'], vdims=[self.gene_selector, 'parcellation_structure', 'parcellation_substructure']).opts( width=550, colorbar=True, cmap='rocket_r', size=2, color=self.gene_selector, clabel='RNA expression') plot2 = hv.NdOverlay({division: hv.Points(self.section[self.section['parcellation_division'] == division], ['x', 'y'], ['parcellation_division_color', 'parcellation_structure', 'parcellation_substructure']).opts( color='parcellation_division_color', size=2) for division in self.section[self.section['parcellation_category'] == "grey"][ 'parcellation_division'].unique()}, kdims='parcellation_division').opts( legend_position='right', width=650, show_legend=True, xlim=(0,6), ylim=(0,6)) common_opts = opts.Points(height=500, invert_yaxis=True, xaxis=None, yaxis=None, show_grid=False, active_tools=[], tools=["hover"]) return (plot1 + plot2).opts(common_opts) @pn.depends("brain_section_index", "filtered_data_updated", watch=True) def get_section(self): brain_section = self.current_data['brain_section_label'].unique()[self.brain_section_index] section = self.filtered_data[self.filtered_data['brain_section_label'] == brain_section] self.section = section[section['parcellation_division'] != "unassigned"] self.section_updated = True @pn.depends("dataset_selector", watch=True) def update_current_data(self): self.current_data = self.merfish_data[self.dataset_selector] self.brain_section_index = 0 self.param.brain_section_index.bounds = (0, self.current_data["brain_section_label"].unique().shape[0]) self.dataset_updated = True @pn.depends("class_selector", "subclass_selector", "dataset_updated", watch=True) def filter_by_class_subclass(self): self.filtered_data = self.current_data[ self.current_data['class'].isin(self.class_selector) & self.current_data['subclass'].isin( self.subclass_selector)] self.filtered_data_updated = True @pn.depends("class_selector", watch=True) def update_subclasses(self): self.param.subclass_selector.objects = sorted( self.current_data[self.current_data['class'].isin(self.class_selector)]['subclass'].unique()) self.subclass_selector = sorted( self.current_data[(self.current_data['class'].isin(self.class_selector))]['subclass'].unique()) viz = MERFISH_viz(merfish_data, datasets[0], merfish_data[datasets[0]]["class"].unique(), merfish_data[dataset]["subclass"].unique(), 0) dashboard_spatial = pn.Column( viz.control_panel, viz.plot_expr_across_slices, viz.plot_bar, viz.plot_section) def plot_class_expression_split_by_categories(subfig, cls, df_subset, gene): axs = subfig.subplots(4, 1) subfig.subplots_adjust(left=0.05, right=.95) sns.violinplot(data=df_subset, y=f'{gene} prevalence (%)', x='subclass', hue='subclass', ax=axs[0], palette=classification_cmap, fill=False) # Set the title with desired modifications title = axs[0].set_title(cls, color=classification_cmap[cls], fontweight='bold', fontsize=20) title.set_path_effects([path_effects.withStroke(linewidth=3, foreground='black')]) subfig.set_facecolor(mcolors.to_rgba(classification_cmap[cls], alpha=0.15)) axs[0].set_ylim(0, 100) # Set y-axis limit to 1 axs[0].xaxis.set_ticks_position('top') axs[0].tick_params(axis='x', length=0) sns.violinplot(data=df_subset, y=f'{gene} prevalence (%)', x='supertype', hue='supertype', ax=axs[1], palette=classification_cmap, fill=False) axs[1].set_title(cls) axs[1].set_ylim(0, 100) # Set y-axis limit to 1 sns.barplot(data=df_subset, y=f'{gene} prevalence (%)', x='cluster', hue='cluster', ax=axs[2], palette=classification_cmap) axs[2].set_title(cls) axs[2].set_ylim(0, 100) # Set y-axis limit to 1 axs[2].set(ylabel='') axs[0].set(ylabel='') axs[2].set(xticks=[], xlabel='') axs[1].set(xticks=[], xlabel='') axs[0].set(xticks=[], xlabel='') axs[0].set(xlabel='') axs[2].set(xticks=[], xlabel='') axs[2].set(xticks=[], xlabel='') axs[1].set_title('') axs[2].set_title('') plt.draw() for tick in axs[0].get_xticklabels(): tick.set_color(classification_cmap[tick.get_text()]) # Identify positions for subclass delimiters in the cluster graph subclass_ends = df_subset.groupby('subclass').size().cumsum() subclass_positions = subclass_ends - 1 # For the third plot (clusters): for pos in subclass_positions[:-1]: axs[2].axvline(pos + 0.5, color='gray', linestyle='--') # For the first plot (subclass), simply draw lines between unique subclasses for i in range(1, len(df_subset['subclass'].unique())): axs[0].axvline(i - 0.5, color='gray', linestyle='--') # For the second plot (supertype), the position will be based on unique supertypes per subclass supertype_ends = df_subset.groupby('subclass')['supertype'].nunique().cumsum() supertype_positions = supertype_ends - 1 for pos in supertype_positions[:-1]: axs[1].axvline(pos + 0.5, color='gray', linestyle='--') # For the first plot (subclass): subclasses = df_subset['subclass'].unique() start = -.5 for i, subclass in enumerate(subclasses): end = i + 0.5 color = classification_cmap[subclass] axs[0].axvspan(start + .05, end - .05, facecolor=color, alpha=0.15) start = end # For the second plot (supertype), determine filling areas based on unique supertypes per subclass supertype_ends = df_subset.groupby('subclass')['supertype'].nunique().cumsum() supertype_positions = supertype_ends - 1 previous_position = -0.5 # initialize to start from the first entry for idx, pos in enumerate(supertype_positions): current_position = pos + 0.5 # Retrieve the subclass name for the current supertype subclass_name = df_subset['subclass'].unique()[idx] color = classification_cmap[subclass_name] axs[1].axvspan(previous_position + 0.2, current_position - .2, facecolor=color, alpha=0.15) previous_position = current_position # set for the next iteration ####third plot filling # Get a mapping of subclasses to their dominant cluster subclass_to_cluster = df_subset.groupby('subclass')['cluster'].apply(lambda x: x.value_counts().idxmax()) # Define previous position to help us fill areas between borders prev_pos = 0 # Iterate over the subclass positions and the corresponding subclasses for idx, (subclass, cluster) in enumerate(subclass_to_cluster.items()): # Get the color for this subclass's dominant cluster from your cmap color_value = classification_cmap[cluster] # End position is either the next border position or the end of the plot end_pos = subclass_positions.iloc[idx] if idx < len(subclass_positions) else len(df_subset['cluster']) - 1 # Fill the area with the given color axs[2].fill_between([prev_pos, end_pos], 0, 100, color=color_value, alpha=0.15) # Update the previous position to the current position prev_pos = end_pos + 1 # Adjust the xlim of each axis axs[0].set_xlim(-0.5, len(df_subset['subclass'].unique()) - 0.5) axs[1].set_xlim(-0.5, len(df_subset['supertype'].unique()) - 0.5) axs[2].set_xlim(-.8, len(df_subset['cluster'].unique())) # Now, add legend in the fourth axis: patches = [plt.Line2D([0], [0], color=classification_cmap[c], lw=8) for c in df_subset["subclass"].unique()] labels = list(df_subset["subclass"].unique()) axs[3].legend(patches, labels, loc='center', ncol=6, handlelength=1.8, handleheight=1) axs[3].axis('off') # Hide axis sns.despine(bottom=True) group_selector = pn.widgets.Select(name='Group', options=neuron_cluster_groups_order, value=neuron_cluster_groups_order[0]) gene_selector = pn.widgets.Select(name='Gene', options=list(selected_genes_cl), value=selected_genes_cl[0]) @pn.depends(group_selector, gene_selector) def interactive_plot(group, gene): global global_saved_fig, group_g, gene_g data = transcriptomic_data_sub[transcriptomic_data_sub["cluster_group_name"] == group] data = data.groupby(["cluster_group_name", "class", "subclass", "supertype", "cluster"])[gene].apply( percentage_above_threshold).reset_index() data = data[data["cluster_group_name"] != "WholeBrain"] data["cluster_group_name"] = pd.Categorical(data["cluster_group_name"], categories=neuron_cluster_groups_order, ordered=True) data = data.sort_values(by=["cluster_group_name", "class"]) data.rename(columns={gene: f'{gene} prevalence (%)'}, inplace=True) fig = plt.figure(figsize=(25, 5 * data['class'].nunique())) gs = gridspec.GridSpec(data['class'].nunique(), 1) for n, cls in enumerate(data['class'].unique()): df_subset = data[data['class'] == cls] subfig = fig.add_subfigure(gs[n, :]) subfig.subplots_adjust(left=0.05, right=.95, bottom=0.01) plot_class_expression_split_by_categories(subfig, cls, df_subset, gene) global_saved_fig = fig group_g = group gene_g = gene fig.suptitle(group, y=1.04, fontweight='bold', fontsize=20); return fig dashboard_cluster_centric = pn.Column( pn.Row(group_selector, gene_selector), pn.pane.Matplotlib(interactive_plot, sizing_mode = 'stretch_width') ) def update_subclass_selector(event): selected_classes = event.new if "None" in selected_classes or not selected_classes: all_subclasses = sorted(joined_sub["subclass"].unique().tolist()) else: all_subclasses = sorted(joined_sub[joined_sub["class"].isin(selected_classes)]["subclass"].unique().tolist()) subclass_selector.options = ["None"] + all_subclasses subclass_selector.value = ["None"] class_selector = pn.widgets.MultiSelect(name='Class selector', options=["None"] + sorted(joined_sub["class"].unique().tolist()), value=[joined_sub["class"].unique()[0]]) subclass_selector = pn.widgets.MultiSelect(name='Subclass selector', options=["None"] + sorted(joined_sub["subclass"].unique().tolist()), value=["None"]) groupby_selector = pn.widgets.Select(name='Group by', options=["class", "subclass", "supertype", "cluster"], value="class") sortby_selector = pn.widgets.Select(name='Sort by', options=["class"] + list(selected_genes_cl), value="class") class_selector.param.watch(update_subclass_selector, 'value') @pn.depends(class_selector, subclass_selector, groupby_selector, sortby_selector) def heatmap_cell_centric(class_, subclass, groupby, sortby): if class_ != ["None"] or subclass != ["None"]: filtered_data = joined_sub if "None" not in class_: filtered_data = filtered_data[filtered_data["class"].isin(class_)] if "None" not in subclass: filtered_data = filtered_data[filtered_data["subclass"].isin(subclass)] if sortby == "class": sortby = groupby ascending = False else: ascending = True heatmap_data = filtered_data.groupby(groupby)[selected_genes_cl].apply(percentage_above_threshold).sort_values( sortby, ascending=ascending).reset_index() # Convert to a format suitable for Holoviews HeatMap heatmap_data = pd.melt(heatmap_data, id_vars=[groupby], value_vars=selected_genes_cl) # Calculate the height of the heatmap unique_groups = heatmap_data[groupby].nunique() fig_height = max(200, unique_groups * 20) # 20 pixels per group, adjust as needed # Create HeatMap heatmap = hv.HeatMap(heatmap_data, kdims=['variable', groupby], vdims=['value']).opts( cmap='RdYlBu_r', width=600, height=fig_height, tools=['hover'], active_tools=[], colorbar=True, xlabel='Gene', ylabel=groupby, clim=(0, 100), clabel='Prevalence (%)' ) # Customizing the plot # Note: Custom color for each gene and classification like in the original function might require more complex handling return heatmap else: # Return an empty plot with a message if no data return hv.Text(0.5, 0.5, 'No data to display').opts(xaxis=None, yaxis=None) dashboard_cell_centric = pn.Column(pn.Row(class_selector, subclass_selector, groupby_selector, sortby_selector), heatmap_cell_centric) division_selector = pn.widgets.MultiSelect(name='Division selector', options=["Whole brain"] + order_division , value=[( ["Whole brain"] + order_division )[0]]) type_selector = pn.widgets.MultiSelect(name='Neurotransmitter selector', options=["Tot", 'Glut', 'GABA', 'Glut-GABA', 'Dopa', '', 'GABA-Glyc', 'Chol', 'Hist', 'Sero', 'Nora'], value=["Tot"]) with open('./Data/expr_by_region.pkl', 'rb') as pickle_file: dict_expr_by_reg = pickle.load(pickle_file) with open('./Data/expr_by_region_only_MERFISH.pkl', 'rb') as pickle_file: dict_expr_by_reg_only_MERFISH = pickle.load(pickle_file) division_selector = pn.widgets.MultiSelect(name='Division selector', options=["Whole brain"] + order_division, value=[(["Whole brain"] + order_division)[0]]) type_selector = pn.widgets.MultiSelect(name='Neurotransmitter selector', options=["Tot", 'Glut', 'GABA', 'Glut-GABA', 'Dopa', '', 'GABA-Glyc', 'Chol', 'Hist', 'Sero', 'Nora'], value=["Tot"]) data_source_selector = pn.widgets.Select(name='Data Source selector', options=['scRNAseq + MERFISH', 'MERFISH only'], value='scRNAseq + MERFISH') sortby_selector = pn.widgets.Select(name='Sort by', options=["region"] + list(selected_genes), value="region") @pn.depends(division_selector, type_selector, data_source_selector, sortby_selector) def heatmap_region_centric(division, type_selector, data_source, sortby): if data_source == 'scRNAseq + MERFISH': data_dict = dict_expr_by_reg elif data_source == "MERFISH only": data_dict = dict_expr_by_reg_only_MERFISH if sortby == "region": heatmap_data = data_dict[type_selector[0]].loc[division[0]].sort_values("parcellation_structure") else: heatmap_data = data_dict[type_selector[0]].loc[division[0]].sort_values(sortby, ascending=False) fig_height = max(200, heatmap_data.shape[0] * 20) # Create HeatMap heatmap = heatmap_data.hvplot.heatmap().opts( cmap='RdYlBu_r', width=600, height=fig_height, tools=['hover'], active_tools=[], colorbar=True, xlabel='Gene', ylabel='Structure', invert_yaxis=True, clabel='Prevalence (%)' ) return heatmap dashboard_region_centric_dashboard = pn.Column( pn.Row(data_source_selector, division_selector, type_selector, sortby_selector), heatmap_region_centric ) # Title of the paper and authors # Custom HTML for the title custom_title_html = """