import streamlit as st import pandas as pd import re import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as mcolors import matplotlib.gridspec as gridspec import matplotlib matplotlib.use('Agg') # Configure matplotlib for Docker environment plt.ioff() # Turn off interactive plotting # Set matplotlib to use memory-efficient settings plt.rcParams['figure.max_open_warning'] = 0 # Disable warnings about too many figures plt.rcParams['agg.path.chunksize'] = 15360 # Reduce memory usage for complex plots from bokeh.embed import file_html from bokeh.plotting import figure, output_file, save from bokeh.models import BasicTicker, BoxSelectTool, CheckboxGroup, ColumnDataSource, ColorBar, CustomJS, CustomJSTickFormatter, DataTable, Div, HoverTool, Legend, LinearAxis, LinearColorMapper, MultiSelect, Paragraph, Range1d, RangeSlider, Span, TableColumn, TapTool from bokeh.models.widgets import TextInput, Button from bokeh.layouts import column, gridplot, row, Spacer from bokeh.palettes import Category10, Category20 from bokeh.resources import CDN, INLINE from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from scipy.stats import gaussian_kde, linregress from scipy.stats import f as f_distribution import scipy.cluster.hierarchy as sch import logging import os import io import sys import base64 from datetime import datetime, date from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed import math import tracemalloc import warnings warnings.simplefilter(action='ignore', category=pd.errors.SettingWithCopyWarning) today_str = datetime.today().strftime('%Y.%m.%d') import psutil import gc import shutil import uuid import tempfile # Set the page config: title, favicon, layout, etc. st.set_page_config( page_title="MQ, Moka, QC, Shanti Report", page_icon="🧬", layout="centered", initial_sidebar_state="expanded" ) # Inject custom CSS to hide Streamlit's top-right menu hide_streamlit_style = """ """ st.markdown(hide_streamlit_style, unsafe_allow_html=True) def log(msg): timestamp = datetime.now().strftime('%H:%M:%S') full_msg = f"[{timestamp}] {msg}" st.session_state.log_messages.append(full_msg) # Keep only last 15 log messages to avoid memory issues if len(st.session_state.log_messages) > 200: st.session_state.log_messages = st.session_state.log_messages[-200:] log_placeholder.text('\n'.join(st.session_state.log_messages)) def setup_safe_directories(): """Setup writable directories for Docker environment""" # Use environment variables if set by Dockerfile, otherwise fall back to temp streamlit_config_dir = os.environ.get("STREAMLIT_CONFIG_DIR", "/tmp/streamlit_config") mpl_config_dir = os.environ.get("MPLCONFIGDIR", "/tmp/matplotlib_config") # Ensure directories exist for directory in [streamlit_config_dir, mpl_config_dir]: try: os.makedirs(directory, exist_ok=True) except PermissionError: # If we can't create in the specified location, try system temp temp_dir = tempfile.gettempdir() directory = os.path.join(temp_dir, os.path.basename(directory)) os.makedirs(directory, exist_ok=True) # Set environment variables os.environ["STREAMLIT_CONFIG_DIR"] = streamlit_config_dir os.environ["MPLCONFIGDIR"] = mpl_config_dir return streamlit_config_dir, mpl_config_dir # Setup directories at import time try: streamlit_config_dir, mpl_config_dir = setup_safe_directories() except Exception as e: st.error(f"Failed to setup config directories: {e}") # Continue anyway - matplotlib will handle its own temp directory hidden_container = st.empty() # To hide "Attach the callback to the selection event" message from bokeh report creation function # --------------------------- # Main functions # --------------------------- # Remove rows where Proteins only contain CON_ entries def filter_proteins(protein_str): proteins = [p.strip() for p in protein_str.split(';')] has_non_con = any(not p.startswith('CON_') for p in proteins) return has_non_con def merge_large_files_swifter(file_a, file_b, custom_sample_names, output_path, chunk_size=50000): log("memory-efficient two-pass strategy...") # Step 1: First Pass - Load Key Columns and Find Matches log("πŸ”Ή Pass 1: Extracting keys and finding matches...") df_a_keys = pd.read_csv(file_a, sep='\t', usecols=['MS/MS scan numbers', 'Raw file']) df_b_keys = pd.read_csv(file_b, sep='\t', usecols=['ScanNr', 'filename']) # Rename for consistency df_a_keys.rename(columns={'Raw file': 'filename'}, inplace=True) # Expand 'MS/MS scan numbers' in file_a df_a_keys['ScanNr_list'] = df_a_keys['MS/MS scan numbers'].astype(str).str.split(';') df_a_keys = df_a_keys.explode('ScanNr_list') df_a_keys['ScanNr_list'] = df_a_keys['ScanNr_list'].str.strip() # Create merge keys df_a_keys['merge_key'] = df_a_keys['ScanNr_list'] + '||' + df_a_keys['filename'].astype(str) df_b_keys['merge_key'] = df_b_keys['ScanNr'].astype(str) + '||' + df_b_keys['filename'].astype(str) # Add index for lookup df_a_keys['index_a'] = df_a_keys.index df_b_keys['index_b'] = df_b_keys.index # Merge on combined key merged_keys = pd.merge(df_a_keys[['merge_key', 'index_a']], df_b_keys[['merge_key', 'index_b']], on='merge_key', how='inner') if merged_keys.empty: log("❌ No matches found. Exiting.\n") return FALSE # Matched/unmatched stats index_a = merged_keys['index_a'].unique() index_b = merged_keys['index_b'].unique() num_total_a = len(df_a_keys) num_total_b = len(df_b_keys) log(f"βœ… Matches from file A: {len(index_a)} rows out of {num_total_a}") log(f"βœ… Matches from file B: {len(index_b)} rows out of {num_total_b}") log(f"❌ Unmatched rows in file A: {num_total_a - len(index_a)}") log(f"❌ Unmatched rows in file B: {num_total_b - len(index_b)}") # Count how often merge_keys from file_a appear in file_b b_key_counts = df_b_keys['merge_key'].value_counts() df_a_keys['match_count_in_b'] = df_a_keys['merge_key'].map(b_key_counts).fillna(0).astype(int) # Count how often merge_keys from file_b appear in file_a a_key_counts = df_a_keys['merge_key'].value_counts() df_b_keys['match_count_in_a'] = df_b_keys['merge_key'].map(a_key_counts).fillna(0).astype(int) # Summary statistics log("πŸ” Merge key mapping stats:") log(f"πŸ”Ή merge_keys in file_a with multiple matches in file_b: {(df_a_keys['match_count_in_b'] > 1).sum()}") log(f"πŸ”Ή merge_keys in file_b with multiple matches in file_a: {(df_b_keys['match_count_in_a'] > 1).sum()}") # Debugging: show top worst offenders # log("\nπŸ”Ž Top merge_keys in file_a with highest match counts in file_b:") # log(df_a_keys[df_a_keys['match_count_in_b'] > 1][['merge_key', 'match_count_in_b']].drop_duplicates().sort_values(by='match_count_in_b', ascending=False).head(10)) # log("\nπŸ”Ž Top merge_keys in file_b with highest match counts in file_a:") # log(df_b_keys[df_b_keys['match_count_in_a'] > 1][['merge_key', 'match_count_in_a']].drop_duplicates().sort_values(by='match_count_in_a', ascending=False).head(10)) # Filter file_b df_b_full = pd.read_csv(file_b, sep='\t') df_b_filtered = df_b_full.loc[index_b].copy() df_b_filtered = df_b_filtered[df_b_filtered['Proteins'].apply(filter_proteins)] df_b_filtered = df_b_filtered[df_b_filtered['mokapot q-value'] < 0.01] # Rename and reduce columns df_b_filtered = df_b_filtered.rename(columns={ 'ScanNr': 'ScanNrMoka', 'Peptide': 'PeptideMoka', 'filename': 'FileMoka', 'mokapot q-value': 'QvalMoka', 'Proteins': 'UniProtID' })[['ScanNrMoka', 'FileMoka', 'QvalMoka', 'UniProtID']] # Create merge key df_b_filtered['ScanNrMoka'] = df_b_filtered['ScanNrMoka'].astype(str) df_b_filtered['merge_key'] = df_b_filtered['ScanNrMoka'] + '||' + df_b_filtered['FileMoka'] # Read file_a in chunks and process a_reader = pd.read_csv(file_a, sep='\t', chunksize=chunk_size, low_memory=False) log("πŸ”„ Merging in chunks...") header_written = False for i, chunk in enumerate(a_reader): chunk.rename(columns={'Raw file': 'filename'}, inplace=True) # Create merge key chunk['chunk_index'] = chunk.index chunk['ScanNr_list'] = chunk['MS/MS scan numbers'].astype(str).str.split(';') chunk = chunk.explode('ScanNr_list') chunk['ScanNr_list'] = chunk['ScanNr_list'].str.strip() chunk['merge_key'] = chunk['ScanNr_list'] + '||' + chunk['filename'].astype(str) # Keep only matching rows chunk = chunk[chunk['merge_key'].isin(df_b_filtered['merge_key'])] if chunk.empty: continue # Rename required columns from file_a rename_dict = { 'Modified sequence': 'SequenceM', # 'Proteins': 'UniProtID', 'Charge': 'Charge', 'Missed cleavages': 'Missed cleavages', 'Number of data points': 'NrDataPoints' } # Find and rename Reporter intensity corrected columns rep_int_cols = [col for col in chunk.columns if re.match(r'Reporter intensity corrected \d+', col)] custom_labels = {} if custom_sample_names: for i, (col_name, sample_short) in enumerate(custom_sample_names.items(), 1): custom_labels[i] = col_name # or sample_short, depending on what you want else: # Fallback: create generic labels if no custom mapping provided st.warning("No custom mappings provided - will use generic column names") # You might want to set some default labels here based on expected columns custom_labels = {int(k): v for k, v in custom_labels.items()} custom_labels_type = type(custom_labels) # log(f"Inside function: custom_labels type: {custom_labels_type}") # rep_int_rename = {col: 'RepIntCorr_' + re.search(r'\d+', col).group() for col in rep_int_cols} # Assign new names based on order using custom_labels rep_int_rename = {} for idx, col in enumerate(rep_int_cols, start=1): label = custom_labels.get(idx, f'Unknown{idx}') #new_col_name = f'{label}_ReporterIntensityCorrected{idx}' new_col_name = f'{label}' rep_int_rename[col] = new_col_name rename_dict.update(rep_int_rename) # Apply renaming chunk.rename(columns=rename_dict, inplace=True) # Merge merged_chunk = pd.merge(chunk, df_b_filtered, on='merge_key', how='inner', suffixes=('_A', '_B')) if merged_chunk.empty: continue # Fill NaNs fill_value = '' # Or change to your desired default # merged_chunk[list(rep_int_rename.values())] = merged_chunk[list(rep_int_rename.values())].fillna(fill_value) # Step 1: Replace 0 with empty string cols = list(rep_int_rename.values()) merged_chunk[cols] = merged_chunk[cols].apply(pd.to_numeric, errors='coerce') merged_chunk[cols] = merged_chunk[cols].map( lambda x: '' if isinstance(x, (int, float, np.float64)) and abs(x) < 1e-8 else x ).fillna('') # Step 2: Fill NaN with empty string (or other default value) merged_chunk[list(rep_int_rename.values())] = merged_chunk[list(rep_int_rename.values())].fillna('') merged_chunk['Missed cleavages'] = merged_chunk['Missed cleavages'].fillna(fill_value) # Final column selection final_columns = [ 'ScanNrMoka', 'FileMoka', 'QvalMoka', 'UniProtID', 'SequenceM', 'Charge', 'Missed cleavages', 'NrDataPoints' ] + list(rep_int_rename.values()) existing_cols = [col for col in final_columns if col in merged_chunk.columns] # Write output with open(output_path, 'a', encoding='utf-8') as f: if not header_written: f.write('\t'.join(existing_cols) + '\n') header_written = True for row in merged_chunk[existing_cols].itertuples(index=False, name=None): f.write('\t'.join(map(str, row)) + '\n') log(f"Chunk {i+1}: wrote {len(merged_chunk)} merged rows.") # log(f"output file: {output_path}\n") return True # Add this at the end # Basic memory monitoring function def monitor_memory(label=""): """Print current memory usage with optional label""" process = psutil.Process() memory_mb = process.memory_info().rss / 1024 / 1024 log(f"... memory usage {label}: {memory_mb:.1f} MB") return memory_mb # Memory usage alerts def check_memory_usage(threshold_mb=15360, label=""): """Alert if memory usage exceeds threshold""" current_memory = monitor_memory(label) if current_memory > threshold_mb: log(f"⚠️ WARNING: Memory usage ({current_memory:.1f} MB) exceeds threshold ({threshold_mb} MB)") return True return False def get_palette_for_groups(group_list): n = len(group_list) palette = Category10[3][:2] if n == 2 else Category10[n] if 3 <= n <= 10 else Category20[n] if n <= 20 else None if palette is None: raise ValueError("Supports up to 20 groups only") return {group: color for group, color in zip(group_list, palette)} def apply_sci_axis_formatter(axis): axis.formatter = CustomJSTickFormatter(code=""" var n = tick; if (n === 0) return "0"; var exp = Math.floor(Math.log10(Math.abs(n))); var base = n / Math.pow(10, exp); if (base === 1) return "1e" + exp; if (base % 1 === 0) return base.toFixed(0) + "e" + exp; return base.toFixed(1) + "e" + exp; """) def _load_and_preprocess_data(df, sample_group_map, custom_sample_names): filter_cols = [col for col in custom_sample_names if 'PepQuant' in col] df = df[filter_cols] df.rename(columns=custom_sample_names, inplace=True) return df[[col for col in df.columns if sample_group_map.get(col, '').lower() != 'blank']] def compute_missed_cleavages(df_chunk, sample_group_map, custom_sample_names): filter_cols = ['Missed cleavages'] + [col for col in custom_sample_names.keys() if 'PepQuant' in col] df_chunk = df_chunk[filter_cols] sample_cols = [col for col in df_chunk.columns if 'PepQuant' in col] renamed_cols = {col: custom_sample_names.get(col, col) for col in sample_cols} df_chunk.rename(columns=renamed_cols, inplace=True) included_samples = [s for s in list(renamed_cols.values()) if sample_group_map.get(s, '').lower() != 'blank'] mc_counts = {} for sample in included_samples: detected = df_chunk[df_chunk[sample] > 0] counts = detected['Missed cleavages'].value_counts().sort_index() mc_counts[sample] = counts mc_df = pd.DataFrame(mc_counts).fillna(0).astype(int).sort_index() del df_chunk return mc_df, included_samples def plot_missed_cleavages(mc_df, included_samples): mc_levels = mc_df.index.astype(str).tolist() colors = Category10[10] abs_source = ColumnDataSource(data={'Sample': included_samples}) rel_source = ColumnDataSource(data={'Sample': included_samples}) for mc in mc_levels: abs_source.data[mc] = [mc_df.get(sample, {}).get(int(float(mc)), 0) for sample in included_samples] rel_source.data[mc] = [(mc_df.loc[int(float(mc)), sample] / mc_df[sample].sum()) * 100 if sample in mc_df.columns else 0 for sample in included_samples] p1 = figure(x_range=included_samples, height=400, width=400, title="Peptide Missed Cleavages (Absolute)", toolbar_location=None, tools="") p1.vbar_stack(mc_levels, x='Sample', width=0.9, color=colors[:len(mc_levels)], source=abs_source) p1.add_tools(HoverTool(tooltips=[("Sample", "@Sample"), ("Missed Cleavages", "$name"), ("Count", "@$name")], mode='mouse')) p1.yaxis.axis_label = "Peptides" p1.xaxis.major_label_orientation = 1 apply_sci_axis_formatter(p1.yaxis) p2 = figure(x_range=included_samples, height=400, width=400, title="Peptide Missed Cleavages (Relative %)", toolbar_location=None, tools="") p2.vbar_stack(mc_levels, x='Sample', width=0.9, color=colors[:len(mc_levels)], source=rel_source) p2.add_tools(HoverTool(tooltips=[("Sample", "@Sample"), ("Missed Cleavages", "$name"), ("Percentage", "@$name{0.2f}%")], mode='mouse')) p2.yaxis.axis_label = "Percentage" p2.xaxis.major_label_orientation = 1 return p1, p2 def compute_peptide_classification(df_chunk, sample_group_map, custom_sample_names): filter_cols = [col for col in custom_sample_names.keys() if 'PepQuant' in col] df_chunk = df_chunk[filter_cols] sample_cols = [col for col in df_chunk.columns if 'PepQuant' in col] renamed_cols = {col: custom_sample_names.get(col, col) for col in sample_cols} df_chunk.rename(columns=renamed_cols, inplace=True) included_samples = [s for s in list(renamed_cols.values()) if sample_group_map.get(s, '').lower() != 'blank'] presence = df_chunk[included_samples] > 0 sample_peptide_counts = presence.sum(axis=1) unique_mask = sample_peptide_counts == 1 shared_mask = sample_peptide_counts > 1 total_peptides = presence.sum() shared_peptides = presence[shared_mask].sum() unique_peptides = presence[unique_mask].sum() del df_chunk return total_peptides, shared_peptides, unique_peptides, included_samples, presence def plot_peptide_counts(total_peptides, shared_peptides, unique_peptides, included_samples): p3_source = ColumnDataSource(data=dict( Sample=included_samples, Total=total_peptides[included_samples].tolist(), Unique=unique_peptides[included_samples].tolist(), )) y_min = total_peptides.min() # Minimum value of Total y_max = total_peptides.max() # Maximum value of Total p3 = figure( x_range=included_samples, height=400, width=400, title="Peptides per Sample", toolbar_location=None, tools="", y_range=(y_min, y_max) # Set Y-axis range from min to max of Total ) # Left Y-axis: Total peptides p3.scatter(x='Sample', y='Total', source=p3_source, color=Category10[10][1], marker='circle', size=8) p3.line(x='Sample', y='Total', source=p3_source, color=Category10[10][1], line_dash='dotted', line_width=2) # Secondary Y-axis for Unique peptides p3.extra_y_ranges = { "unique": Range1d(start=0, end=max(unique_peptides[included_samples]) * 1.1) } p3.add_layout(LinearAxis(y_range_name="unique", axis_label="Unique Peptides"), 'right') p3.scatter(x='Sample', y='Unique', source=p3_source, color=Category10[10][0], marker='square', size=8, y_range_name="unique") p3.line(x='Sample', y='Unique', source=p3_source, color=Category10[10][0], line_dash='dotted', line_width=2, y_range_name="unique") # Hover tool with details p3.add_tools(HoverTool(tooltips=[ ("Sample", "@Sample"), ("Total Peptides", "@Total"), ("Unique Peptides", "@Unique") ], mode='mouse')) p3.yaxis[0].axis_label = "Total Peptides" p3.xaxis.major_label_orientation = 1 return p3 def plot_cumulative_peptides(total_peptides, presence, included_samples): sorted_samples = total_peptides.sort_values(ascending=True).index.tolist() peptide_sets = {sample: set(presence.index[presence[sample]]) for sample in sorted_samples} cumulative_union_counts = [] cumulative_set = set() for sample in sorted_samples: cumulative_set |= peptide_sets[sample] cumulative_union_counts.append(len(cumulative_set)) cumulative_increment = [] prev_val = 0 for val in cumulative_union_counts: cumulative_increment.append(val - prev_val) prev_val = val # Calculate percentage for cumulative shared peptides and shared increment total_unique = cumulative_union_counts[-1] cumulative_percent = [count / total_unique * 100 for count in cumulative_union_counts] cumulative_increment_percent = [inc / total_unique * 100 for inc in cumulative_increment] # Calculate shared peptides incrementally across samples shared_cumulative_list = [] shared_decrement_list = [] intersection_set = None for i, sample in enumerate(sorted_samples): if intersection_set is None: intersection_set = peptide_sets[sample] else: intersection_set = intersection_set & peptide_sets[sample] shared_cumulative_list.append(len(intersection_set)) if i == 0: shared_decrement_list.append(0) # No decrement on first sample else: shared_decrement_list.append(shared_cumulative_list[-2] - shared_cumulative_list[-1]) shared_percent = [v / total_unique * 100 for v in shared_cumulative_list] shared_decrement_percent = [v / total_unique * 100 for v in shared_decrement_list] trimmed_source = ColumnDataSource(data=dict( samples=sorted_samples[1:], cumulative=cumulative_union_counts[1:], cumulative_percent=cumulative_percent[1:], cumulative_increment=cumulative_increment[1:], cumulative_increment_percent=cumulative_increment_percent[1:], shared_cumulative=shared_cumulative_list[1:], shared_percent=shared_percent[1:], shared_decrement=shared_decrement_list[1:], shared_decrement_percent=shared_decrement_percent[1:] )) # Plot adjustments (same structure) p4 = figure(x_range=sorted_samples[1:], height=400, width=400, title=f"Cumulative Plot excluding {sorted_samples[0]}", toolbar_location=None, tools="") p4.y_range = Range1d(start=min(cumulative_percent[1:]), end=max(cumulative_percent[1:])) p4.extra_y_ranges = { "shared_dec": Range1d(start=min(shared_decrement_percent[1:]), end=max(shared_decrement_percent[1:])) } p4.add_layout(LinearAxis(y_range_name="shared_dec", axis_label="Shared Decrement (%)"), 'right') # Add the lines and scatter for both cumulative and shared data line1 = p4.line(x='samples', y='cumulative_percent', source=trimmed_source, line_width=2, color=Category10[10][0], legend_label="Cumulative") scatter1 = p4.scatter(x='samples', y='cumulative_percent', source=trimmed_source, size=6, color=Category10[10][0], marker='square') line2 = p4.line(x='samples', y='shared_decrement_percent', source=trimmed_source, y_range_name="shared_dec", line_width=2, color=Category10[10][1], legend_label="Shared") scatter2 = p4.scatter(x='samples', y='shared_decrement_percent', source=trimmed_source, y_range_name="shared_dec", size=6, color=Category10[10][1], marker='square') # Hover tool configuration hover = HoverTool(renderers=[line1, scatter1, line2, scatter2], tooltips=[ ("Sample", "@samples"), ("Cumulative Peptides", "@cumulative"), ("Cumulative Peptides %", "@cumulative_percent{0.0}%"), ("Cumulative Peptides Increment", "@cumulative_increment"), ("Cumulative Peptides Increment %", "@cumulative_increment_percent"), ("Shared Peptides", "@shared_cumulative"), ("Shared Peptides %", "@shared_percent{0.0}%"), ("Shared Peptide Decrement", "@shared_decrement"), ("Shared Peptide Decrement %", "@shared_decrement_percent{0.0}%") ]) p4.add_tools(hover) p4.yaxis[0].axis_label = "Cumulative Increment (%)" p4.xaxis.major_label_orientation = 1.2 p4.legend.location = "center_right" return p4 def plot_PCA(df_chunk, sample_group_map, custom_sample_names): tracemalloc.start() filter_cols = [col for col in custom_sample_names.keys() if 'PepQuant' in col] df_chunk = df_chunk[filter_cols] renamed_cols = {col: custom_sample_names.get(col, col) for col in df_chunk.columns} df_chunk.rename(columns=renamed_cols, inplace=True) sample_names = list(renamed_cols.values()) sample_groups = [sample_group_map[s] for s in sample_names] group_list = sorted(set(sample_groups)) group_colors = get_palette_for_groups(group_list) has_blanks = any(sample_group_map.get(s, '').lower() == 'blank' for s in sample_names) has_nans = df_chunk[sample_names].isnull().any().any() def create_pca_plot(data, samples, title, add_peptide_count=False): colors = [group_colors[sample_group_map[s]] for s in samples] pca_data = data.transpose() pca_scaled = StandardScaler().fit_transform(pca_data) pca = PCA(n_components=2) pca_result = pca.fit_transform(pca_scaled) if add_peptide_count: n_peptides = data.shape[0] title = f"{title} (n={n_peptides})" del data, pca_data, pca_scaled gc.collect() source = ColumnDataSource(data={'x': pca_result[:, 0], 'y': pca_result[:, 1], 'Sample': samples, 'Color': colors}) plot = figure(title=title, width=400, height=400, toolbar_location=None, tools="") plot.scatter('x', 'y', source=source, fill_color='Color', size=10, line_color='black', alpha=0.8) plot.add_tools(HoverTool(tooltips=[("Sample", "@Sample")])) plot.xaxis.axis_label = f"PC1 ({pca.explained_variance_ratio_[0]*100:.1f}%)" plot.yaxis.axis_label = f"PC2 ({pca.explained_variance_ratio_[1]*100:.1f}%)" current, peak = tracemalloc.get_traced_memory() log(f"... Current memory usage: {current / 1024**2:.2f} MB") log(f"... Peak memory usage: {peak / 1024**2:.2f} MB") return plot non_blank_samples = [s for s in sample_names if sample_group_map.get(s, '').lower() != 'blank'] plots = [] if not has_blanks and not has_nans: plots.append(create_pca_plot(df_chunk[sample_names], sample_names, "PCA")) elif not has_blanks and has_nans: plots.append(create_pca_plot(df_chunk[sample_names].dropna(), sample_names, "PCA (Drop NaNs)", add_peptide_count=True)) plots.append(create_pca_plot(df_chunk[sample_names].fillna(df_chunk[sample_names].mean()), sample_names, "PCA (Mean Imputation)", add_peptide_count=True)) elif has_blanks and not has_nans: plots.append(create_pca_plot(df_chunk[sample_names], sample_names, "PCA (with Blanks)")) plots.append(create_pca_plot(df_chunk[non_blank_samples], non_blank_samples, "PCA (without Blanks)")) else: plots.append(create_pca_plot(df_chunk[sample_names].dropna(), sample_names, "PCA (with Blanks, Drop NaNs)", add_peptide_count=True)) plots.append(create_pca_plot(df_chunk[sample_names].fillna(df_chunk[sample_names].mean()), sample_names, "PCA (with Blanks, Mean Imputation)", add_peptide_count=True)) plots.append(create_pca_plot(df_chunk[non_blank_samples].dropna(), non_blank_samples, "PCA (without Blanks, Drop NaNs)", add_peptide_count=True)) plots.append(create_pca_plot(df_chunk[non_blank_samples].fillna(df_chunk[non_blank_samples].mean()), non_blank_samples, "PCA (without Blanks, Mean Imputation)", add_peptide_count=True)) del df_chunk, sample_names, non_blank_samples, group_list, group_colors, sample_groups, renamed_cols current, peak = tracemalloc.get_traced_memory() log(f"... Current memory usage: {current / 1024**2:.2f} MB") log(f"... Peak memory usage: {peak / 1024**2:.2f} MB") tracemalloc.stop() gc.collect() return tuple(plots) """ Optimized plotting functions with shared preprocessing to eliminate redundant calculations. All function signatures and outputs remain unchanged. """ def preprocess_shared_data(df_chunk, sample_group_map, custom_sample_names): """ Performs common preprocessing once for all plotting functions. Returns: dict with preprocessed data or None if no valid data """ # Filter PepQuant columns filter_cols = [col for col in custom_sample_names.keys() if 'PepQuant' in col] if not filter_cols: return None df_filtered = df_chunk[filter_cols].copy() # Rename columns renamed_cols = {col: custom_sample_names.get(col, col) for col in df_filtered.columns} df_filtered.rename(columns=renamed_cols, inplace=True) # Filter out blanks sample_names = df_filtered.columns.tolist() non_blank_cols = [col for col in sample_names if sample_group_map.get(col, '').lower() != 'blank'] if not non_blank_cols: return None df_filtered = df_filtered[non_blank_cols] # CRITICAL OPTIMIZATION: Compute log2 transformation ONCE log2_data = np.log2(df_filtered.fillna(0).values + 1) # Group information computed once sample_names = df_filtered.columns.tolist() sample_groups = [sample_group_map[s] for s in sample_names] group_list = sorted(list(set(sample_groups))) group_colors = get_palette_for_groups(group_list) return { 'df_filtered': df_filtered, # For CV (needs original values) 'log2_data': log2_data, # For distributions and heatmap 'sample_names': sample_names, 'sample_groups': sample_groups, 'group_list': group_list, 'group_colors': group_colors, 'sample_group_map': sample_group_map # Pass through for convenience } def plot_sample_distributions(df_chunk, sample_group_map, custom_sample_names, preprocessed=None): """ Accepts optional preprocessed data to avoid redundant calculations. Original signature preserved - preprocessed is optional parameter. """ # Use preprocessed data if available, otherwise compute if preprocessed is None: preprocessed = preprocess_shared_data(df_chunk, sample_group_map, custom_sample_names) if preprocessed is None: return figure(title="Sample Intensity Distributions (Log2)", width=400, height=400, x_axis_label="Log2(Intensity)", y_axis_label="Density") # Extract preprocessed data (already filtered, renamed, log2-transformed) transformed_data = preprocessed['log2_data'] sample_names = preprocessed['sample_names'] sample_groups = preprocessed['sample_groups'] group_list = preprocessed['group_list'] group_colors = preprocessed['group_colors'] sample_group_map = preprocessed['sample_group_map'] # OPTIMIZATION: Use ravel() all_values = transformed_data.ravel() # Check if all_values is empty or all-NaN after filtering if all_values.size == 0 or np.all(np.isnan(all_values)): return figure(title="Sample Intensity Distributions (Log2)", width=400, height=400, x_axis_label="Log2(Intensity)", y_axis_label="Density") # OPTIMIZATION: Reduce number of evaluation points for KDE x_vals = np.linspace(np.nanmin(all_values), np.nanmax(all_values), 200) p = figure(title="Sample Intensity Distributions (Log2)", width=400, height=400, x_axis_label="Log2(Intensity)", y_axis_label="Density", toolbar_location=None, tools="") group_samples = {group: [] for group in group_list} # OPTIMIZATION: Populate group_samples *only* with valid samples for idx, sample in enumerate(sample_names): values = transformed_data[:, idx] group = sample_group_map[sample] # Only include samples with at least 2 non-zero points for KDE if np.count_nonzero(values) >= 2: group_samples[group].append(values) # Per-group average KDE (solid thick line) for group in group_list: # OPTIMIZATION: Concatenate once if not group_samples[group]: log(f"No valid samples for group {group}, skipping KDE.") continue group_data = np.concatenate(group_samples[group]) if np.count_nonzero(group_data) < 2: continue try: # OPTIMIZATION: Subsample if too many data points if len(group_data) > 5000: subsample_idx = np.random.choice(len(group_data), 5000, replace=False) group_data_kde = group_data[subsample_idx] else: group_data_kde = group_data kde_group = gaussian_kde(group_data_kde, bw_method='scott') y_group = kde_group(x_vals) p.line(x_vals, y_group, line_color=group_colors[group], line_width=3, legend_label=f"{group} (avg)") # OPTIMIZATION: Use nanpercentile and compute only median q50 = np.nanpercentile(group_data, 50) vline = Span(location=q50, dimension='height', line_dash='dashed', line_color=group_colors[group], line_width=1.5) p.add_layout(vline) except Exception as e: log(f"Group KDE failed for {group}: {e}") continue # FIX: Reduce padding and adjust for legend space x_min, x_max = np.nanmin(all_values), np.nanmax(all_values) x_range_padding = (x_max - x_min) * 0.05 p.x_range.start = x_min - x_range_padding p.x_range.end = x_max + x_range_padding # Dynamically choose the legend location based on where most data points lie # If data points are more on the left, place the legend on the right, and vice versa mean_x = np.mean(all_values) # Mean of the data plot_center = (p.x_range.start + p.x_range.end) / 2 # Center of the plot # Decide legend position based on the mean of all_values if mean_x < plot_center: p.legend.location = "top_right" # More data on the left, so place legend on the right else: p.legend.location = "top_left" # More data on the right, so place legend on the left # Legend settings p.legend.click_policy = "hide" p.legend.title = "Groups" # Cleanup (only cleanup local data, not preprocessed) del all_values, group_samples gc.collect() return p def plot_cv_distributions(df_chunk, sample_group_map, custom_sample_names, preprocessed=None): """ Accepts optional preprocessed data to avoid redundant calculations. Original signature preserved - preprocessed is optional parameter. """ # Use preprocessed data if available, otherwise compute if preprocessed is None: preprocessed = preprocess_shared_data(df_chunk, sample_group_map, custom_sample_names) if preprocessed is None: # Return empty figure return figure(title="Group CV Distributions", width=400, height=400, x_axis_label="Coefficient of Variation (CV%)", y_axis_label="Density", toolbar_location=None, tools="") # Extract preprocessed data df_filtered = preprocessed['df_filtered'] # Need original values for CV sample_names = preprocessed['sample_names'] group_list = preprocessed['group_list'] group_colors = preprocessed['group_colors'] sample_group_map = preprocessed['sample_group_map'] # Calculate CV per peptide (across all samples in the group) cv_values_by_group = {group: [] for group in group_list} for group in group_list: group_samples_in_group = [sample for sample in sample_names if sample_group_map[sample] == group] # For each peptide, calculate the CV across all samples in that group for peptide in df_filtered.index: intensities = df_filtered.loc[peptide, group_samples_in_group].values if np.count_nonzero(intensities) < 2: continue # Calculate CV for this peptide across all samples in the group mean = np.mean(intensities) std = np.std(intensities) if mean == 0: continue cv = std / mean # Ensure CV is a valid number and not inf or NaN if np.isfinite(cv): cv_values_by_group[group].append(cv * 100) # Create a figure for the plot all_cv_values = [cv for group_vals in cv_values_by_group.values() for cv in group_vals] max_cv = min(200, np.max(all_cv_values)) x_vals = np.linspace(0, max_cv, 500) p = figure( title="Group CV Distributions", width=400, height=400, x_axis_label="Coefficient of Variation (CV%)", y_axis_label="Density", toolbar_location=None, tools="" ) # Plot per-group CV distributions for group in group_list: cv_values = cv_values_by_group[group] if len(cv_values) < 2: continue kde_group = gaussian_kde(cv_values) y_group = kde_group(x_vals) # Plot the KDE for this group p.line(x_vals, y_group, line_color=group_colors[group], line_width=3, legend_label=group) # Vertical line only for median q50 = np.percentile(cv_values, 50) vline = Span(location=q50, dimension='height', line_dash='dashed', line_color=group_colors[group], line_width=1.5) p.add_layout(vline) p.legend.title = "Groups" p.legend.click_policy = "hide" p.legend.location = "right" return p def create_dendrogram(col_linkage, sample_labels): """ Optimized function for creating dendrogram image. Plots the dendrogram and returns both the base64-encoded image and the ordering of the leaves (col_order). """ fig = None buf = None try: plt.ioff() # Adjust figure size based on sample count fig_width = min(10, max(6, len(sample_labels) / 10)) fig, ax = plt.subplots(figsize=(fig_width, 2.5)) dendro_plot = None # Simplify dendrogram for many samples if len(sample_labels) > 100: dendro_plot = sch.dendrogram( col_linkage, ax=ax, orientation='top', color_threshold=None, truncate_mode='lastp', p=30, show_contracted=True, leaf_rotation=90, leaf_font_size=7 ) else: dendro_plot = sch.dendrogram( col_linkage, ax=ax, labels=sample_labels, orientation='top', color_threshold=None, leaf_rotation=90, leaf_font_size=8 ) # Subsample labels if there are too many if 50 < len(sample_labels) <= 100: labels = ax.get_xticklabels() step = max(1, len(labels) // 50) for i, label in enumerate(labels): if i % step != 0: label.set_visible(False) col_order = dendro_plot['leaves'] ax.set_yticks([]) fig.tight_layout() buf = io.BytesIO() fig.savefig(buf, format='png', bbox_inches='tight', dpi=150) buf.seek(0) img_base64 = base64.b64encode(buf.read()).decode('utf-8') return img_base64, col_order except Exception as e: log(f"Error creating dendrogram: {e}") return None, None finally: if buf: buf.close() if fig: plt.close(fig) plt.ion() def plot_heatmap(df_chunk, sample_group_map, custom_sample_names, preprocessed=None): """ Optimized version with preprocessed data support. CRITICAL FIX: Log2 transformation now computed only ONCE. """ try: # Use preprocessed data if available, otherwise compute if preprocessed is None: preprocessed = preprocess_shared_data(df_chunk, sample_group_map, custom_sample_names) if preprocessed is None: empty_div = Div(text='

No PepQuant columns found for heatmap

') return column(empty_div) # Extract preprocessed data - log2_data already computed! df_work = preprocessed['df_filtered'].copy() heatmap_data = preprocessed['log2_data'].copy() # Already log2-transformed! # Store original labels BEFORE subsampling original_sample_labels = df_work.columns.tolist() # Subsample rows for large datasets max_rows_for_heatmap = 2000 max_cols_for_heatmap = 500 # OPTIMIZATION: Use already-computed log2 data for variance if heatmap_data.shape[0] > max_rows_for_heatmap: row_variances = np.var(heatmap_data, axis=1) # No recomputation! top_indices = np.argsort(row_variances)[-max_rows_for_heatmap:] df_work = df_work.iloc[top_indices] heatmap_data = heatmap_data[top_indices] # Slice, not recompute! # Subsample columns if heatmap_data.shape[1] > max_cols_for_heatmap: col_variances = np.var(heatmap_data, axis=0) # No recomputation! top_col_indices = np.argsort(col_variances)[-max_cols_for_heatmap:] df_work = df_work.iloc[:, top_col_indices] heatmap_data = heatmap_data[:, top_col_indices] # Slice, not recompute! original_sample_labels = [original_sample_labels[i] for i in top_col_indices] # Skip clustering if too few samples or features if heatmap_data.shape[1] < 2 or heatmap_data.shape[0] < 2: col_order = list(range(heatmap_data.shape[1])) row_order = list(range(heatmap_data.shape[0])) heatmap_data_clustered = heatmap_data clustered_sample_labels = original_sample_labels dendro_img_base64 = None else: # Perform hierarchical clustering try: # Compute linkages row_linkage = sch.linkage(heatmap_data, method='average') col_linkage = sch.linkage(heatmap_data.T, method='average') # Create dendrogram and get column order in ONE step dendro_img_base64, col_order = create_dendrogram(col_linkage, original_sample_labels) if col_order is None: col_order = list(range(heatmap_data.shape[1])) # Get row order row_dendro = sch.dendrogram(row_linkage, no_plot=True) row_order = row_dendro['leaves'] # Apply ordering heatmap_data_clustered = heatmap_data[np.ix_(row_order, col_order)] clustered_sample_labels = [original_sample_labels[i] for i in col_order] except Exception as e: log(f"Clustering failed: {e}") col_order = list(range(heatmap_data.shape[1])) row_order = list(range(heatmap_data.shape[0])) heatmap_data_clustered = heatmap_data clustered_sample_labels = original_sample_labels dendro_img_base64 = None # Create heatmap image heatmap_img_base64 = create_heatmap_image(heatmap_data_clustered, clustered_sample_labels) # Create HTML for display if dendro_img_base64 and heatmap_img_base64: img_html = f"""
""" elif heatmap_img_base64: img_html = f"""
""" else: img_html = '

Failed to generate heatmap

' heatmap_div = Div(text=img_html) heatmap_title = Div(text='

Peptide Quan Heatmap (Log2)

') heatmap_with_title = column(heatmap_title, heatmap_div) # Cleanup del df_work, heatmap_data, heatmap_data_clustered gc.collect() return heatmap_with_title except Exception as e: log(f"Error in plot_heatmap: {e}") error_div = Div(text=f'

Error generating heatmap: {str(e)}

') return column(error_div) def create_heatmap_image(heatmap_data, sample_labels): """ Create heatmap image with proper resource management (This function is unchanged as its inputs are still valid) """ fig = None buf = None try: # Early return for empty data if heatmap_data.size == 0: return None # Create quantiles for color mapping num_bins = 10 # OPTIMIZATION 1: Use ravel() instead of flatten() to avoid copy flat_data = heatmap_data.ravel() # OPTIMIZATION 2: Calculate quantiles more efficiently quantiles = np.quantile(flat_data, np.linspace(0, 1, num_bins + 1)) # Fix quantiles if they're too close for i in range(1, len(quantiles)): if quantiles[i] <= quantiles[i-1]: quantiles[i] = quantiles[i-1] + 1e-8 # Create figure with explicit cleanup plt.ioff() # Turn off interactive mode # OPTIMIZATION 3: Adjust figure size based on data dimensions # Smaller figures for large datasets fig_height = min(8, max(4, heatmap_data.shape[0] / 250)) fig_width = min(8, max(4, heatmap_data.shape[1] / 50)) fig, ax = plt.subplots(figsize=(fig_width, fig_height)) cmap = plt.get_cmap('tab20', num_bins) norm = mcolors.BoundaryNorm(quantiles, ncolors=num_bins) # OPTIMIZATION 4: Use interpolation for large datasets to speed up rendering if heatmap_data.shape[0] > 1000 or heatmap_data.shape[1] > 500: im = ax.imshow(heatmap_data, aspect='auto', cmap=cmap, norm=norm, interpolation='nearest') # Faster rendering else: im = ax.imshow(heatmap_data, aspect='auto', cmap=cmap, norm=norm) # OPTIMIZATION 5: Limit number of x-axis labels for readability if len(sample_labels) > 50: # Show only every nth label step = max(1, len(sample_labels) // 50) indices = np.arange(0, len(sample_labels), step) ax.set_xticks(indices) ax.set_xticklabels([sample_labels[i] for i in indices], rotation=90, fontsize=8) else: ax.set_xticks(np.arange(len(sample_labels))) ax.set_xticklabels(sample_labels, rotation=90, fontsize=8) ax.set_yticks([]) # Add colorbar bin_mids = (quantiles[:-1] + quantiles[1:]) / 2 cbar = plt.colorbar(im, ax=ax, boundaries=quantiles) cbar.set_ticks(bin_mids) cbar.set_ticklabels([f"{quantiles[i]:.2f} - {quantiles[i+1]:.2f}" for i in range(len(quantiles)-1)], fontsize=7) fig.tight_layout() buf = io.BytesIO() fig.savefig(buf, format='png', bbox_inches='tight', dpi=150) buf.seek(0) img_base64 = base64.b64encode(buf.read()).decode('utf-8') return img_base64 except Exception as e: log(f"Error creating heatmap image: {e}") return None finally: # Explicit cleanup if buf: buf.close() if fig: plt.close(fig) plt.ion() # Turn interactive mode back on gc.collect() def _load_and_preprocess_data(df, sample_group_map, custom_sample_names): """ Load and preprocess data with better error handling """ try: filter_cols = [col for col in custom_sample_names if 'PepQuant' in col] if not filter_cols: raise ValueError("No PepQuant columns found") # Work with a copy to avoid modifying original df_work = df[filter_cols].copy() df_work.rename(columns=custom_sample_names, inplace=True) # Filter out blank samples non_blank_cols = [col for col in df_work.columns if sample_group_map.get(col, '').lower() != 'blank'] if not non_blank_cols: raise ValueError("No non-blank samples found") return df_work[non_blank_cols] except Exception as e: log(f"Error in _load_and_preprocess_data: {e}") # Return empty dataframe if processing fails return pd.DataFrame() def _create_single_plot(task_data, fig_size_inch=2, dpi=150): """ Create a single scatter plot with improved memory management. No changes needed - already optimized. """ fig = None buf = None try: *identifiers, x_data, y_data = task_data # OPTIMIZATION: Use numpy's optimized nan checking mask = np.isfinite(x_data) & np.isfinite(y_data) x_clean = x_data[mask] y_clean = y_data[mask] if len(x_clean) < 2: return tuple(identifiers), None plt.ioff() fig, ax = plt.subplots(figsize=(fig_size_inch, fig_size_inch), dpi=150) fig.subplots_adjust(left=0.05, right=0.95, top=0.85, bottom=0.15) # OPTIMIZATION: Simplify scatter plot logic if len(x_clean) > 500 and (np.std(x_clean) > 1e-10) and (np.std(y_clean) > 1e-10): try: # OPTIMIZATION: Subsample for KDE if too many points if len(x_clean) > 2000: step = len(x_clean) // 2000 x_kde = x_clean[::step] y_kde = y_clean[::step] else: x_kde = x_clean y_kde = y_clean xy = np.vstack([x_kde, y_kde]) kde = gaussian_kde(xy) xy_full = np.vstack([x_clean, y_clean]) z = kde(xy_full) idx = z.argsort() ax.scatter(x_clean[idx], y_clean[idx], c=z[idx], cmap='viridis', s=5, alpha=0.6, edgecolors='none', rasterized=True) except Exception: ax.scatter(x_clean, y_clean, s=5, alpha=0.6, color='darkblue', rasterized=True) else: ax.scatter(x_clean, y_clean, s=5, alpha=0.6, color='darkblue', rasterized=True) # Add regression line and identity line try: # OPTIMIZATION: Subsample for regression if very large if len(x_clean) > 5000: indices = np.random.choice(len(x_clean), 5000, replace=False) x_reg = x_clean[indices] y_reg = y_clean[indices] else: x_reg = x_clean y_reg = y_clean slope, intercept, r, _, _ = linregress(x_reg, y_reg) r2 = r**2 # Use only 2 points for line plotting x_min, x_max = x_clean.min(), x_clean.max() xlim = np.array([x_min, x_max]) ax.plot(xlim, slope * xlim + intercept, color='orange', linewidth=1.2) ax.plot(xlim, xlim, linestyle='--', color='red', linewidth=1.0, alpha=0.7) ax.set_title(f"RΒ² = {r2:.3f}", fontsize=6, pad=2) except Exception as e: ax.set_title("Regression failed", fontsize=6, pad=2) ax.set_xticks([]) ax.set_yticks([]) save_dpi = min(dpi, 150) buf = io.BytesIO() fig.savefig(buf, format='png', bbox_inches='tight', pad_inches=0.02, dpi=save_dpi) buf.seek(0) img_b64 = base64.b64encode(buf.read()).decode() return tuple(identifiers), img_b64 except Exception as e: log(f"Error in _create_single_plot: {e}") return tuple(identifiers), None finally: if buf: buf.close() if fig: plt.close(fig) gc.collect() def _build_matrix_html(title, results, labels, is_triangular=False): """ Build HTML matrix with better structure and error handling """ try: if not labels or not results: return f'

{title}

No data available for matrix

' html_parts = [ f'
', f'

{title}

', f'
', f'', '' ] # Add column headers for label in labels: html_parts.append( f'' ) html_parts.append("") # Add rows for i, row_label in enumerate(labels): html_parts.append( f'' ) for j, col_label in enumerate(labels): if is_triangular and j <= i: html_parts.append('') else: key = (row_label, col_label) if not is_triangular else (labels[i], labels[j]) img = results.get(key, '') if img: html_parts.append( f'' ) else: html_parts.append('') html_parts.append("") html_parts.extend(["
{label}
' f'
{row_label}
", "
", "
"]) return ''.join(html_parts) except Exception as e: log(f"Error in _build_matrix_html: {e}") return f'

{title}

Error building matrix: {str(e)}

' def plot_across_group_pairwise_matrix(df, sample_group_map, custom_sample_names, num_cpu_workers): """ Plot pairwise comparisons across groups with improved error handling and memory management """ try: # Preprocess data df_processed = _load_and_preprocess_data(df, sample_group_map, custom_sample_names) if df_processed.empty: return [Div(text="

No data available for across-group comparison.

")] # Group columns by their groups group_to_cols = {} for col in df_processed.columns: if col in sample_group_map: group = sample_group_map[col] group_to_cols.setdefault(group, []).append(col) # Compute log2-transformed mean expression for each group group_avg = {} for group, cols in group_to_cols.items(): if cols: try: group_data = df_processed[cols].fillna(0) group_avg[group] = np.log2(group_data.mean(axis=1).values + 1) # Use median instead of mean for more robust statistics # group_avg[group] = np.log2(group_data.median(axis=1).values + 1) except Exception as e: log(f"Error computing group average for {group}: {e}") continue group_names = list(group_avg.keys()) if len(group_names) < 2: return [Div(text="

Not enough groups for pairwise comparisons.

")] log(f"... processing {len(group_names)} groups: {group_names}") # Create tasks for pairwise comparisons tasks = [] for j in range(len(group_names)-1, 0, -1): for i in range(j): g1, g2 = group_names[i], group_names[j] tasks.append((g1, g2, group_avg[g1], group_avg[g2])) # Process tasks with limited workers to avoid memory issues max_workers = min(num_cpu_workers, 2, len(tasks)) # Limit concurrent processes results = {} # Use ThreadPoolExecutor instead of ProcessPoolExecutor to reduce memory overhead # Use ProcessPoolExectuor for hf space 2 vCPU 16 GB RAM with ProcessPoolExecutor(max_workers=max_workers) as executor: futures = { executor.submit(_create_single_plot, task, fig_size_inch=2, dpi=150): (task[0], task[1]) for task in tasks } for future in as_completed(futures): try: # result = future.result(timeout=300) # Add timeout result = future.result() # No timeout if result[1]: # If plot was successfully created results[result[0]] = result[1] except Exception as e: log(f"Error processing {futures[future]}: {e}") # Build matrix HTML matrix_html = f"""

Between-Group Linear Regression (mean.Log2)

""" # Header (columns) for col_index in range(len(group_names) - 1): group_name = group_names[len(group_names) - 1 - col_index] matrix_html += f'' matrix_html += "" # Matrix rows for row_index in range(len(group_names) - 1): row_group = group_names[row_index] matrix_html += f""" """ for col_index in range(len(group_names) - 1 - row_index): col_group = group_names[len(group_names) - 1 - col_index] key = (row_group, col_group) img_base64 = results.get(key, '') if img_base64: matrix_html += f'' else: matrix_html += '' matrix_html += "" matrix_html += """
{group_name}
{row_group}
""" # Cleanup del df_processed, group_avg, results, tasks gc.collect() return [Div(text=matrix_html)] except Exception as e: log(f"Error in plot_across_group_pairwise_matrix: {e}") return [Div(text=f"

Error generating across-group matrix: {str(e)}

")] def plot_within_group_pairwise_matrix(df, sample_group_map, custom_sample_names, num_cpu_workers): """ Plot pairwise comparisons within groups with improved error handling and memory management """ try: # Preprocess data df_processed = _load_and_preprocess_data(df, sample_group_map, custom_sample_names) if df_processed.empty: log("No data available for within-group comparison\n") return # Transform data once transformed_array = np.log2(df_processed.fillna(0).values + 1) sample_to_index = {col: i for i, col in enumerate(df_processed.columns)} # Group samples by their groups group_samples = {} for sample, group in sample_group_map.items(): if sample in df_processed.columns: group_samples.setdefault(group, []).append(sample) # Remove groups with less than 2 samples group_samples = {k: v for k, v in group_samples.items() if len(v) >= 2} if not group_samples: log("No groups with enough samples for within-group comparison\n") # Create tasks for all pairwise comparisons all_tasks = [] for group_name, samples in group_samples.items(): log(f"creating task for Group: {group_name} and Samples: {samples}\n") pairs = [(samples[i], samples[j]) for j in range(len(samples)-1, 0, -1) for i in range(j)] for s1, s2 in pairs: try: idx1, idx2 = sample_to_index[s1], sample_to_index[s2] all_tasks.append((group_name, s1, s2, transformed_array[:, idx1], transformed_array[:, idx2])) except KeyError as e: log(f"Sample {e} not found in data") continue if not all_tasks: log("No valid sample pairs found for comparison") return log(f"..processing {len(all_tasks)} within-group comparisons across {len(group_samples)} groups") # Process all tasks with limited workers max_workers = min(num_cpu_workers, 2, len(all_tasks)) # Limit concurrent processes all_results = {} # Use ThreadPoolExecutor for better memory management # Use ProcessPoolExecutor for hf 2 vCPU 16 GB RAM with ProcessPoolExecutor(max_workers=max_workers) as executor: futures = { executor.submit(_create_single_plot, task, fig_size_inch=2, dpi=150): task[:3] for task in all_tasks } for future in as_completed(futures): try: # result = future.result(timeout=30) # Add timeout result = future.result() # No timeout if result[1]: # If plot was successfully created all_results[result[0]] = result[1] except Exception as e: log(f"Error processing {futures[future]}: {e}") # Build matrices for each group all_group_layouts = [] for group_name, samples in group_samples.items(): try: # Get results for this group group_results = {} for j in range(len(samples)-1, 0, -1): for i in range(j): s1, s2 = samples[i], samples[j] key = (group_name, s1, s2) if key in all_results: group_results[(s1, s2)] = all_results[key] if not group_results: continue # Skip groups with no successful plots # Build HTML matrix for this group matrix_html = f"""

Within-Group Linear Regression (Log2): {group_name}

""" # Column headers for col_index in range(len(samples) - 1): sample_name = samples[len(samples) - 1 - col_index] matrix_html += f'' matrix_html += "" # Matrix rows for row_index in range(len(samples) - 1): row_sample = samples[row_index] matrix_html += f""" """ for col_index in range(len(samples) - 1 - row_index): col_sample = samples[len(samples) - 1 - col_index] img_base64 = group_results.get((row_sample, col_sample), '') if img_base64: matrix_html += f'' else: matrix_html += '' matrix_html += "" matrix_html += """
{sample_name}
{row_sample}
""" all_group_layouts.append(Div(text=matrix_html)) except Exception as e: log(f"Error building matrix for group {group_name}: {e}") continue # Cleanup del df_processed, transformed_array, all_results, all_tasks gc.collect() return all_group_layouts if all_group_layouts else [Div(text="

No matrices could be generated.

")] except Exception as e: log(f"Error in plot_within_group_pairwise_matrix: {e}") return [Div(text=f"

Error generating within-group matrices: {str(e)}

")] def process_protein_data(tsv_file_path, custom_sample_names, sample_group_map): """ Process MQ protein (containing pVal) file with TMT reporter intensities and transform according to specifications. Args: tsv_file_path: MQ protein file uploaded and saved in temp directory custom_sample_names: Dict mapping column names to sample short names sample_group_map: Dict mapping sample short names to group names Returns: Processed DataFrame with transformed columns """ # Read the TSV file df = pd.read_csv(tsv_file_path, sep='\t') # Initialize the result DataFrame result_df = pd.DataFrame() # 1. Calculate group mean Reporter Intensities sample_short_names = list(custom_sample_names.values()) # Get TMT reporter intensity columns (assuming they start from "Reporter intensity 1 TMT1") tmt_columns = [col for col in df.columns if col.startswith("Reporter intensity")] if len(tmt_columns) != len(sample_short_names): raise ValueError(f"Number of TMT columns ({len(tmt_columns)}) does not match number of sample names ({len(sample_short_names)})") # Map tmt_columns to sample_short names based on position column_to_sample_short = { tmt_col: sample_short for tmt_col, sample_short in zip(tmt_columns, sample_short_names) } # Group columns by group_name group_to_columns = {} for tmt_col, sample_short in column_to_sample_short.items(): group_name = sample_group_map.get(sample_short) if group_name: group_to_columns.setdefault(group_name, []).append(tmt_col) # Compute and add group averages for group_name, cols in group_to_columns.items(): mean_col_name = f"{group_name}_MeanL2" result_df[mean_col_name] = df[cols].mean(axis=1, skipna=True) # 2. Create Description column from Fasta headers def extract_description(fasta_header): if pd.isna(fasta_header): return "" descriptions = [] # Split by semicolon for multiple proteins proteins = fasta_header.split(';') for protein in proteins: protein = protein.strip() if protein: # Extract UniProt ID and description # Pattern: sp|Q16222|UAP1_HUMAN UDP-N-acetylhexosamine pyrophosphorylase match = re.search(r'sp\|([A-Z0-9]+)\|[A-Z0-9_]+\s+(.+?)(?:\s+OS=|$)', protein) if match: uniprot_id = match.group(1) description = match.group(2).strip() descriptions.append(f"{uniprot_id} {description}") return ", ".join(descriptions) result_df['Description'] = df['Fasta headers'].apply(extract_description) # 3. Create UniProtID column (first UniProt ID from Description) def extract_first_uniprot_id(description): if not description: return "" # Extract first UniProt ID match = re.search(r'^([A-Z0-9]+)', description) return match.group(1) if match else "" def remove_first_uniprot_from_description(description): if not description: return "" # Remove the first "UniProtID " pattern match = re.search(r'^[A-Z0-9]+\s+(.+)', description) return match.group(1) if match else description result_df['UniProtID'] = result_df['Description'].apply(extract_first_uniprot_id) result_df['Description'] = result_df['Description'].apply(remove_first_uniprot_from_description) # 4. Genes column (rename "Gene names") if 'Gene names' in df.columns: result_df['Genes'] = df['Gene names'] # 5. SequenceCoverage column if 'Sequence coverage [%]' in df.columns: result_df['SequenceCoverage'] = df['Sequence coverage [%]'] # 6. L2FC columns (from "Difference" columns) difference_columns = [col for col in df.columns if 'Difference' in col] for col in difference_columns: # Extract prefix before "Difference" (e.g., "S: Difference" -> "S") prefix = col.split(':')[0].strip() if ':' in col else col.replace(' Difference', '') new_col_name = f"{prefix}_L2FC" result_df[new_col_name] = df[col] # 7. PValue columns (from "-Log(P-value)" columns) pvalue_columns = [col for col in df.columns if '-Log(P-value)' in col] for col in pvalue_columns: # Extract prefix before "-Log(P-value)" (e.g., "SC7: -Log(P-value)" -> "SC7") prefix = col.split(':')[0].strip() if ':' in col else col.replace(' -Log(P-value)', '') new_col_name = f"{prefix}_PValue" result_df[new_col_name] = df[col] return result_df # Bokeh Report File containing Volcano Plots, Histograms, Tables, Search Button class DataProcessor: """Internal class for processing data and performing statistical calculations""" def __init__(self): """Initialize the data processor""" pass def get_s0(self, fc_lim=0.5, alpha=0.05, dfn=10, dfd=10, loc=0, scale=1, two_sided=False, **kwargs): """ Calculates the s0 value given a log2 fold change limit and an alpha value. This is based on the two-tailed SAM test analysis transferred two F-test. Parameters ---------- fc_lim : float or array of floats fold-change limit asymptote (x) in log2. Controls how far the threshold curve extends on x-axis. alpha : float or array of floats alpha threshold limit asymptote (y). Between 0 and 1. Controls significance threshold. dfn : float or array of floats degrees of freedom of nominator for the f-distribution. Higher values make curve steeper. dfd : float or array of floats degrees of freedom of denominator for the f-distribution. Higher values make curve steeper. loc : float or array of floats location parameter for the f-distribution. Controls horizontal shift of curve. scale : float or array of floats scaling parameter for the f-distribution. Controls vertical scaling of curve. two_sided : bool, optional if a two-sided test is performed. Default is False. When True, uses alpha/2 for threshold. **kwargs : dict, optional Additional keyword arguments not used directly but passed through function calls. Returns ------- s0 : float fudge factor s0 that determines curvature of significance threshold """ # Convert to vectorized form and check input fc_lim, alpha = np.asarray(fc_lim), np.asarray(alpha) if np.any((alpha < 0) | (alpha > 1)): raise ValueError(f'alpha value(s) must be between 0 and 1.') # Using the F = T**2 equality for 2 groups (max vs. min plateau), SAM analysis can be performed with f-distribution if two_sided: alpha_lim = np.sqrt(f_distribution.ppf(1 - (alpha / 2), dfn=dfn, dfd=dfd, loc=loc, scale=scale)) else: alpha_lim = np.sqrt(f_distribution.ppf(1 - alpha, dfn=dfn, dfd=dfd, loc=loc, scale=scale)) # Calculate S0 in vectorized form alpha_lim = np.asarray(alpha_lim) alpha_lim[alpha_lim < 0] = 0.0 # Guard against negative values s0 = abs(fc_lim) / alpha_lim return s0 def map_fc_to_pvalue_cutoff(self, x, alpha=0.05, s0=1.45, dfn=10, dfd=10, loc=0, scale=1, two_sided=False, **kwargs): """ This function maps input fold changes to the respective p-values given statistic type, chosen alpha value, fudge factor s0, and degrees of freedom. It is based on the SAM test with some modifications (see comments). Parameters ---------- x : pd.Series log2 fold change values to map to p-value thresholds alpha : float alpha threshold limit asymptote (y). Between 0 and 1. Controls overall significance level. s0 : float fudge factor, which determines the transition between both fold-change and p-value asymptotes. Higher values create more curved threshold lines. dfn : int degrees of freedom of nominator for the f-distribution. Controls shape of threshold curve. dfd : int degrees of freedom of denominator for the f-distribution. Controls shape of threshold curve. loc : float location parameter for the f-distribution. Shifts threshold curve horizontally. scale : float scaling parameter for the f-distribution. Scales threshold curve vertically. two_sided : bool, optional if a two-sided test is performed. By default False. When True, results in symmetrical thresholds. **kwargs : dict, optional Additional keyword arguments not used directly. Returns ------- y : pd.Series p-value cutoffs for each input log2-fold change x-value. Comments -------- Adapted from: https://analyticalsciencejournals.onlinelibrary.wiley.com/doi/10.1002/pmic.201600132 R Code in the supplement FPB addition: use the f_distribution for calculation of a f-statistic under assumption F = T**2 for two group analysis """ # Added on 2025.04.17 if not isinstance(x, pd.Series): x = pd.Series(x) # Convert to pandas Series if not already if (len(x) == 0) or type(pd.Series([0])) is not pd.Series: raise ValueError(f'Fold change array needs to be a pd.Series object with at least 1 value.') if not 0 <= alpha <= 1: raise ValueError(f'Alpha value must be between 0 and 1, but it was {alpha}.') # Using the F = T**2 equality for 2 groups (max vs. min plateau infinity argument), SAM analysis can be performed with f-distribution if two_sided: alpha_lim = np.sqrt(f_distribution.ppf(1 - (alpha / 2), dfn=dfn, dfd=dfd, loc=loc, scale=scale)) else: alpha_lim = np.sqrt(f_distribution.ppf(1 - alpha, dfn=dfn, dfd=dfd, loc=loc, scale=scale)) # New positional limits with s0 pos_lim = alpha_lim * s0 # Positive threshold limit neg_lim = -alpha_lim * s0 # Negative threshold limit # Mask with 0 edge case pos = x > pos_lim # Mask for values above positive threshold neg = x < neg_lim # Mask for values below negative threshold if pos_lim == neg_lim: pos = x >= pos_lim # Special case when thresholds are equal # Calculate the fudge-modified values x_pos = x[pos] # Values above positive threshold x_neg = x[neg] # Values below negative threshold x_none = x[(~pos) & (~neg)] # Values between thresholds (not significant) # Calculate modified statistics for positive threshold d_pos = x_pos / alpha_lim - s0 d_pos = (s0 / d_pos) d_pos = alpha_lim * (1 + d_pos) # Calculate modified statistics for negative threshold d_neg = x_neg / (-alpha_lim) - s0 d_neg = (s0 / d_neg) d_neg = alpha_lim * (1 + d_neg) # Calculate to p-values. # Revert to F-test with F = T**2 # Log survival function to have more accurate p value calculations: - np.log10[(1 - dist.cdf(x, dfn, dfd))] y_pos = - f_distribution.logsf(d_pos**2, dfn=dfn, dfd=dfd, loc=loc, scale=scale) * np.log10(np.e) y_neg = - f_distribution.logsf(d_neg**2, dfn=dfn, dfd=dfd, loc=loc, scale=scale) * np.log10(np.e) if two_sided: # Two sided p values are multiplied by two: - np.log10[(1 - dist.cdf(x, deg)) * 2] y_pos -= np.log10(2) y_neg -= np.log10(2) # Combine arrays for output and ensure non-negative values and convert nan to max_prob as its the least likely (for the 0 edge case for d_p/n) y_none = np.full(shape=len(x_none), fill_value=np.inf) # Non-significant values get inf y = pd.concat([pd.Series(y_neg, index=x_neg.index), pd.Series(y_none, index=x_none.index), pd.Series(y_pos, index=x_pos.index)]) y = y.clip(lower=0, upper=None) # Ensure no negative values y = y.replace(np.nan, max(y)) # Replace NaN with maximum value return y[x.index] # Return in original order # Function to classify points based on p-value cutoff and fold-change def classify_point(self, row, l2fc_col, pAdj_col, fc_lim, **kwargs): """ Classify and color data points based on significance thresholds Parameters ---------- row : pandas.Series A row from the dataframe containing fold-change and p-value data l2fc_col : str Column name containing log2 fold change values pAdj_col : str Column name containing adjusted p-values (as -log10 values) fc_lim : float Fold-change limit threshold for significance **kwargs : dict, optional Additional keyword arguments not used directly Returns ------- str Color code for the data point: 'lightgrey' for non-significant, 'orange' for significantly downregulated, 'blue' for significantly upregulated """ x = row[l2fc_col] # Get log2 fold change value y = row[pAdj_col] # Get -log10 adjusted p-value y_thresh = row["y_thresh"] # Get threshold value for this point # Protect against invalid values if pd.isna(x) or pd.isna(y): return "lightgrey" if y < y_thresh: return "lightgrey" # below threshold (not significant) elif x < -fc_lim: return "orange" # significant downregulation else: return "blue" # significant upregulation def load_data(protein_df, alpha = 0.05, dfn = 10, dfd = 10, loc = 0, scale = 1, two_sided=False, fc_lim = 0.5, l2fc_col = '', pAdj_col = ''): """ Load data from Excel file and return a ColumnDataSource with processed data. Parameters: ----------- protein_df : pandas dataframe dataframe containing protein data obtained by processing 20250805_DataAnalysis_norm_pvalue.txt file with function process_protein_data(tsv_file_path, custom_sample_names, sample_group_map) NOT rescore.proteinGroups.fdr1.txt file sheet_name : int or str, default 0 Sheet to read from the Excel file, can be sheet number or name alpha : float or array of floats alpha threshold limit asymptote (y). Between 0 and 1. Controls significance cutoff. dfn : float or array of floats degrees of freedom of nominator for the f-distribution. Controls shape of threshold curve. dfd : float or array of floats degrees of freedom of denominator for the f-distribution. Controls shape of threshold curve. loc : float or array of floats location parameter for the f-distribution. Shifts threshold curve horizontally. scale : float or array of floats scaling parameter for the f-distribution. Scales threshold curve vertically. two_sided : bool, optional if a two-sided test is performed. Default is False. When True, uses alpha/2 for threshold. fc_lim : float or array of floats fold-change limit asymptote (x) in log2. Controls how far the threshold extends on x-axis. l2fc_col : str column name containing log2 fold change values, required for volcano plot x-axis pAdj_col : str column name containing adjusted P values, required for volcano plot y-axis Returns: -------- ColumnDataSource Bokeh ColumnDataSource object containing the processed data with additional columns for visualization """ # Initialize the data processor dp = DataProcessor() # subset only the columns required for html report df = protein_df.copy() # adjusted p-values with a minimum clip to avoid infinity df.loc[:, "mlog10pAdj"] = df[pAdj_col].clip(lower=1e-300) # Perform Data Processing # 1. Calculate s0 for the threshold curve - controls curvature of significance threshold s0 = dp.get_s0(fc_lim=fc_lim, alpha=alpha, dfn=dfn, dfd=dfd, two_sided=two_sided) # 2. Calculate y_thresh values for the threshold curve - these define the significance boundary df["y_thresh"] = dp.map_fc_to_pvalue_cutoff(x=df[l2fc_col], alpha=alpha, s0=s0, dfn=dfn, dfd=dfd, loc=loc, scale=scale, two_sided=two_sided) # 3. create color column based on threshold curve - colors points by significance and direction df["color"] = df.apply(lambda row: dp.classify_point(row, l2fc_col, "mlog10pAdj", fc_lim), axis=1) # Convert to ColumnDataSource for Bokeh visualization source = ColumnDataSource(df) return source def make_histogram(source=None, hist_col='', width=200, height=800, visible=True, tools="", toolbar_location=None, title="", x_axis_label='', y_axis_label='', min_border=0, **kwargs): """ Create a horizontal histogram visualization for protein abundance data. Parameters: ----------- source : ColumnDataSource Bokeh data source containing the protein data hist_col : str Column name containing the abundance values to plot in histogram width : int, default 200 Width of the histogram plot in pixels height : int, default 800 Height of the histogram plot in pixels visible : bool, default False Whether the histogram should be initially visible tools : str, default "" Bokeh tools to include with the plot (e.g., "pan,zoom") toolbar_location : str or None, default None Location of the toolbar (None, "above", "below", "left", "right") title : str, default "" Title for the histogram plot x_axis_label : str, default '' Label for the x-axis (horizontal axis showing count) y_axis_label : str, default '' Label for the y-axis (vertical axis showing bins) min_border : int, default 0 Minimum border size around the plot in pixels **kwargs : dict Additional keyword arguments passed to the figure function Returns: -------- tuple (figure, filtered_data, bin_edges, bottoms, bar_height) containing: - Bokeh figure object of the histogram - Filtered data used for histogram - bin edges for binning - Bottom positions for bars - Height of each bar """ # Convert source data to DataFrame df = pd.DataFrame(source.data) data = df[hist_col].dropna() # Remove NaN values # Return early if no valid data if len(data) == 0: return None, None, None, None, None, None # Create bins for better visualization of abundance data bin_edges = np.linspace(data.min(), data.max(), 21) # 20 bins in raw scale hist, _ = np.histogram(data, bins=bin_edges) # Set up spacing for horizontal bars n_bins = len(hist) bar_height = 1 # Height of each bar bar_spacing = 0.2 # Space between bars # Calculate positions for bars bottoms = np.arange(n_bins) * (bar_height + bar_spacing) # Bottom position of each bar tops = bottoms + bar_height # Top position of each bar # Create figure with basic settings p = figure(width=width, height=height, visible=visible, tools=tools, toolbar_location=toolbar_location, title=title, x_axis_label=x_axis_label, y_axis_label=y_axis_label, min_border=min_border) # Create empty figure if no column selected if hist_col == "": log(hist_col, "is empty") return p, None, None, None, None if data is None: log("data is empty") return p, None, None, None, None # Configure figure visibility p.visible = True p.xaxis.visible = True p.yaxis.visible = True p.grid.visible = False p.outline_line_color = None # Create histogram data source source_hist = ColumnDataSource(data=dict( left=[0] * len(hist), # All bars start at 0 right=hist, # Width of each bar is the count bottom=bottoms, # Bottom position for each bar top=tops # Top position for each bar )) # Add bars to the plot p.quad(left='left', right='right', bottom='bottom', top='top', source=source_hist, fill_color='lightgrey', line_color='white', alpha=0.4) # Configure plot ranges p.y_range.start = 0 p.y_range.end = tops[-1] + (tops[0] - bottoms[0]) * 0.2 # Add headroom at the top # Set x-axis range x_max = max(hist) if len(hist) > 0 else 1 p.x_range.start = 0 p.x_range.end = x_max * 1.2 # Add padding for appearance # Calculate midpoints of bins for tick positions midpoints = bottoms + (bar_height / 2) # Create tick formatter for y-axis using bin values bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2 # Centers of bins bin_labels = [f"{value:.2g}" for value in bin_centers] # Format as text # Set custom y-axis ticks p.yaxis.ticker = midpoints # Position ticks at bin midpoints p.yaxis.major_label_overrides = {midpoints[i]: bin_labels[i] for i in range(len(midpoints))} # Custom labels # Optional: Adjust y-axis appearance p.yaxis.major_label_text_font_size = "8pt" return p, data, bin_edges, bottoms, bar_height def create_interactive_dashboard(source, peptides_df=None, l2fc_col='', pAdj_col='', html_title="Shanti Tool", color_column="color", table_columns=None, peptide_columns=None, volcano_title='', volcano_tools="pan, box_zoom, wheel_zoom, tap, box_select, reset, save", output_path="dashboard.html", plot2=None, plot3=None, hist1_data_filtered=None, hist2_data_filtered=None, hist1_bin_edges=None, hist2_bin_edges=None, hist1_bottoms=None, hist2_bottoms=None, hist1_bar_height=None, hist2_bar_height=None, hist1_col='', hist2_col=''): """ Create an interactive Bokeh dashboard with multiple linked plots and filters. Parameters: ----------- source : ColumnDataSource Data source for the plots, containing processed proteomics data peptides_df : pandas dataframe subset of dataframe returned by merge_large_files_swifter(evidence_path, mokapot_path, custom_sample_names, output_path) where evidence_path is evidence.txt generated by MaxQuant, mokapot_path is peptides file generated by Mokapot tool l2fc_col : str Column name for x-axis in main volcano plot (log2 fold change) pAdj_col : str Column name for y-axis in main volcano plot (adjusted p-value) html_title : str, default "Shanti Tool" Title for the HTML page color_column : str, default "color" Column name to use for point colors in volcano plot table_columns : list, default None List of column names to display in the protein data table peptide_columns : list, default None List of column names to display in the peptide data table volcano_title : str, default '' Title for the volcano plot volcano_tools : str, default "pan, box_zoom, wheel_zoom, tap, box_select, reset, save" Tools to include with the volcano plot output_path : str, default "dashboard.html" Path to save the HTML dashboard plot2 : Bokeh figure, optional First histogram plot (treatment/KO condition) plot3 : Bokeh figure, optional Second histogram plot (control/WT condition) hist1_data_filtered : array-like, optional Filtered data for first histogram hist2_data_filtered : array-like, optional Filtered data for second histogram hist1_bin_edges : array-like, optional bin edges for first histogram hist2_bin_edges : array-like, optional bin edges for second histogram hist1_bottoms : array-like, optional Bottom positions for bars in first histogram hist2_bottoms : array-like, optional Bottom positions for bars in second histogram hist1_bar_height : float, optional Height of each bar in first histogram hist2_bar_height : float, optional Height of each bar in second histogram hist1_col : str, default '' Column name for first histogram data hist2_col : str, default '' Column name for second histogram data Returns: -------- str Path to the created HTML file """ # Create a filtered copy of the source data for interactive filtering filtered_source = ColumnDataSource(data=source.data) df = pd.DataFrame(source.data) # df.to_csv('output.tsv', sep='\t', index=False) # Commented out data export # Ensure UniProtID column exists if 'UniProtID' not in peptides_df.columns: raise ValueError("Peptides file must contain a 'UniProtID' column") # Create peptides source if available peptides_source = None peptides_source_all = None peptides_table = None if peptides_df is not None: # Store the full peptides data peptides_source_all = ColumnDataSource(peptides_df) # log(f"Peptides DataFrame loaded with {len(peptides_df)} rows") # log(f"Peptides columns: {peptides_df.columns.tolist()}") # Check if UniProtID column exists and has valid data if 'UniProtID' in peptides_df.columns: # log(f"UniProtID column exists with {peptides_df['UniProtID'].count()} non-null values") # log(f"Sample UniProtID values: {peptides_df['UniProtID'].iloc[:3].tolist()}") # Check for semicolon-separated values has_semicolons = peptides_df['UniProtID'].str.contains(';').any() # log(f"UniProtID column contains semicolon-separated values: {has_semicolons}") else: log("WARNING: UniProtID column not found in peptides data!") # Use all columns if not specified if peptide_columns is None: peptide_columns = list(peptides_df.columns) # Default to all columns if not specified else: # Define column widths in order (first column = 80px, second = 120px, etc.) peptide_column_widths = [160, 360, 100, 40, 70, 70] default_width = 50 # Create table columns with specified widths peptide_table_columns = [] for i, col in enumerate(peptide_columns): # Get width from the list or use default if index exceeds list length width = peptide_column_widths[i] if i < len(peptide_column_widths) else default_width peptide_table_columns.append(TableColumn(field=col, title=col, width=width)) # Create empty source with only selected columns for filtered peptides empty_peptides_data = {col: [] for col in peptide_columns} peptides_source = ColumnDataSource(empty_peptides_data) # Create the peptides table with the prepared columns peptides_table = DataTable(source=peptides_source, columns=peptide_table_columns, width=900, height=400, index_position=None) # Define hover tooltips for volcano plot tooltips = [ ("UniProtID", "@UniProtID"), ("Gene", "@Genes"), ("Log2 Fold Change", f"@{l2fc_col}"), ("p Adjusted", f"@{pAdj_col}"), ("-log10pAdj", "@mlog10pAdj"), (f"{hist1_col}", f"@{hist1_col}"), (f"{hist2_col}", f"@{hist2_col}") ] # Create the main volcano plot plot1 = figure( height=800, width=400, title=volcano_title, x_axis_label="log2 fold change values", y_axis_label="-log10 adjusted p-values", tools=volcano_tools, toolbar_location="below", visible=True) # Add hover tool with tooltips plot1.add_tools(HoverTool(tooltips=tooltips)) # Add scatter points to volcano plot plot1.scatter(x=l2fc_col, y="mlog10pAdj", source=filtered_source, color="color", size=8, selection_color="green", nonselection_alpha=0.5) # Add threshold curve lines to the volcano plot ylim = df["mlog10pAdj"].max() + 0.25 # Maximum y-value with padding # Split curve data into left and right sides for smooth rendering curve_left = df[(df[l2fc_col] < 0) & (df["y_thresh"] <= ylim)].sort_values(by=l2fc_col) curve_right = df[(df[l2fc_col] > 0) & (df["y_thresh"] <= ylim)].sort_values(by=l2fc_col) # Draw the significance threshold curves plot1.line(curve_left[l2fc_col], curve_left["y_thresh"], line_width=1, color="black") plot1.line(curve_right[l2fc_col], curve_right["y_thresh"], line_width=1, color="black") # Create data sources for horizontal lines in histograms (for showing selected proteins) lines_source_plot2 = ColumnDataSource(data=dict(x0=[], x1=[], y=[], color=[])) lines_source_plot3 = ColumnDataSource(data=dict(x0=[], x1=[], y=[], color=[])) # Add segment renderers to histogram plots for selected proteins if plot2 is not None: plot2.segment(x0='x0', y0='y', x1='x1', y1='y', line_color='color', line_width=1, source=lines_source_plot2) if plot3 is not None: plot3.segment(x0='x0', y0='y', x1='x1', y1='y', line_color='color', line_width=1, source=lines_source_plot3) # Set up slider filters for data filtering sliders = [] slider_titles = ["Filter X-axis (log2 fold change)", "Filter y-axis (-log10 adjusted p-value)"] i = 0 # Create sliders for both X and Y axes for volcano_slider in [l2fc_col, pAdj_col]: # Calculate min/max values for slider range min_val = min(source.data[volcano_slider]) max_val = max(source.data[volcano_slider]) # Create RangeSlider with appropriate settings slider = RangeSlider( title=f"{slider_titles[i]}", start=min_val, end=max_val, value=(min_val, max_val), # Initial value is full range step=(max_val - min_val) / 100, # 100 steps across the range width=300 ) i = i + 1 # Create a JavaScript callback for the slider to filter data based on slider values # This callback filters the data source based on the current slider range and updates the filtered source slider_callback = CustomJS( # Pass required data sources and controls to the callback args=dict(source=source, filtered=filtered_source, slider=slider, column=volcano_slider), code=""" // Get the current slider values const min_val = slider.value[0]; const max_val = slider.value[1]; // Get the original data const data = source.data; const column_data = data[column]; // Create new filtered data object const new_data = {}; for (const key in data) { new_data[key] = []; } // Filter the data for (let i = 0; i < column_data.length; i++) { if (column_data[i] >= min_val && column_data[i] <= max_val) { for (const key in data) { new_data[key].push(data[key][i]); } } } // Update the filtered source filtered.data = new_data; filtered.change.emit(); """ ) # Connect the callback to the slider's value change event slider.js_on_change('value', slider_callback) # Add spacing between sliders for better UI layout sliders.append(Spacer(width=60)) # Add the slider to the sliders collection sliders.append(slider) # Set up search functionality with text input and button # TextInput widget allows users to search by specified fields search_input = TextInput(title="Search by UniProtID, Description, Gene", width=370) # Button to trigger the search search_button = Button(label="Go", button_type="primary", width=100) # Create a JavaScript callback for the search functionality # This callback filters data based on search text across all fields search_callback = CustomJS( # Pass required data sources and controls to the callback args=dict(source=source, filtered=filtered_source, search_input=search_input), code=""" // Get the search text const search_text = search_input.value.toLowerCase(); // Get the original data const data = source.data; // If search is empty, restore all data if (search_text.trim() === '') { filtered.data = data; filtered.change.emit(); return; } // Create new filtered data object const new_data = {}; for (const key in data) { new_data[key] = []; } // Search across all string columns const columns = Object.keys(data); for (let i = 0; i < data[columns[0]].length; i++) { let match = false; // Check each column for a match for (const col of columns) { const val = String(data[col][i]).toLowerCase(); if (val.includes(search_text)) { match = true; break; } } // If a match is found, add all data for this row if (match) { for (const key in data) { new_data[key].push(data[key][i]); } } } // Update the filtered source filtered.data = new_data; filtered.change.emit(); """ ) # Connect the search callback to the button's click event search_button.js_on_click(search_callback) # Create a data source for the table that will display only the selected points # This source will be populated when user selects data points selected_source = ColumnDataSource({col: [] for col in table_columns}) # Initialize data table to None data_table = None # Create a data table only if table columns are provided if table_columns: # Define column widths to customize the table appearance # Each number represents width in pixels for the corresponding column column_widths = [75, 100, 150, 875] # Default width for columns that exceed the defined widths list default_width = 100 # Create table columns with appropriate widths columns = [] for i, col in enumerate(table_columns): # Get width from the list or use default if index exceeds list length width = column_widths[i] if i < len(column_widths) else default_width columns.append(TableColumn(field=col, title=col, width=width)) # Create the data table with the configured columns # Parameters: # source: The data source for the table # columns: List of table columns # width/height: Dimensions of the table in pixels # index_position: Set to None to hide the index column data_table = DataTable(source=selected_source, columns=columns, width=900, height=400, index_position=None) # This CustomJS callback processes user selections in the filtered data source # and updates related visualizations and tables selection_callback = CustomJS( # Pass all required data sources and variables to the JS callback args=dict( # Data sources filtered_source=filtered_source, # Contains filtered protein data selected_source=selected_source, # Will hold data for selected items peptides_source=peptides_source, # Contains peptide data for selected proteins peptides_source_all=peptides_source_all, # Contains all peptide data # Column definitions table_columns=table_columns, # Columns for the protein data table peptide_columns=peptide_columns, # Columns for the peptide data table # Plot references plot2=plot2, # Histogram plot 1 plot3=plot3, # Histogram plot 2 # Line sources for visual indicators on plots lines_source_plot2=lines_source_plot2, # Lines to highlight selected items on plot2 lines_source_plot3=lines_source_plot3, # Lines to highlight selected items on plot3 # Histogram 1 data hist1_data=hist1_data_filtered, # Data for histogram 1 hist1_bin_edges=hist1_bin_edges, # Bin edges for histogram 1 hist1_bottoms=hist1_bottoms, # Bottom positions for histogram 1 bars hist1_bar_height=hist1_bar_height, # Height of bars in histogram 1 hist1_col=hist1_col, # Column name for histogram 1 data # Histogram 2 data hist2_data=hist2_data_filtered, # Data for histogram 2 hist2_bin_edges=hist2_bin_edges, # Bin edges for histogram 2 hist2_bottoms=hist2_bottoms, # Bottom positions for histogram 2 bars hist2_bar_height=hist2_bar_height, # Height of bars in histogram 2 hist2_col=hist2_col # Column name for histogram 2 data ), code=""" (function() { console.log("Selection callback triggered"); var indices = filtered_source.selected.indices; console.log("Selected indices:", indices); var lines_data_plot2 = {x0: [], x1: [], y: [], color: []}; var plot2_max_x = plot2.x_range.end; var lines_data_plot3 = {x0: [], x1: [], y: [], color: []}; var plot3_max_x = plot3.x_range.end; var new_data = {}; for (var i = 0; i < table_columns.length; i++) { new_data[table_columns[i]] = []; } var selected_uniprotids = []; for (var i = 0; i < indices.length; i++) { var idx = indices[i]; for (var j = 0; j < table_columns.length; j++) { var key = table_columns[j]; new_data[key].push(filtered_source.data[key][idx]); } if ('UniProtID' in filtered_source.data) { var uid = filtered_source.data['UniProtID'][idx]; if (selected_uniprotids.indexOf(uid) === -1) { selected_uniprotids.push(uid); } } if (filtered_source.data[hist1_col] && filtered_source.data[hist1_col][idx] != null) { var val1 = filtered_source.data[hist1_col][idx]; for (var k = 0; k < hist1_bin_edges.length - 1; k++) { if (val1 >= hist1_bin_edges[k] && val1 < hist1_bin_edges[k + 1]) { var bin_bottom1 = hist1_bottoms[k]; var rand_offset1 = Math.random() * hist1_bar_height; var y_pos1 = bin_bottom1 + rand_offset1; lines_data_plot2.x0.push(0); lines_data_plot2.x1.push(plot2_max_x); lines_data_plot2.y.push(y_pos1); lines_data_plot2.color.push('green'); break; } } } if (filtered_source.data[hist2_col] && filtered_source.data[hist2_col][idx] != null) { var val2 = filtered_source.data[hist2_col][idx]; for (var k2 = 0; k2 < hist2_bin_edges.length - 1; k2++) { if (val2 >= hist2_bin_edges[k2] && val2 < hist2_bin_edges[k2 + 1]) { var bin_bottom2 = hist2_bottoms[k2]; var rand_offset2 = Math.random() * hist2_bar_height; var y_pos2 = bin_bottom2 + rand_offset2; lines_data_plot3.x0.push(0); lines_data_plot3.x1.push(plot3_max_x); lines_data_plot3.y.push(y_pos2); lines_data_plot3.color.push('green'); break; } } } } lines_source_plot2.data = lines_data_plot2; lines_source_plot2.change.emit(); lines_source_plot3.data = lines_data_plot3; lines_source_plot3.change.emit(); selected_source.data = new_data; selected_source.change.emit(); console.log("Updating peptides table"); if (!peptides_source_all || !peptides_source || !peptide_columns || !Array.isArray(peptide_columns)) { console.error("Missing required peptides data sources or columns"); return; } if (!('UniProtID' in peptides_source_all.data)) { console.error("UniProtID column not found in peptides data"); return; } var filtered_peptides = {}; for (var i = 0; i < peptide_columns.length; i++) { filtered_peptides[peptide_columns[i]] = []; } var matchCount = 0; var peptidesLength = peptides_source_all.data['UniProtID'].length; console.log("Total peptides rows to check:", peptidesLength); for (var i = 0; i < peptidesLength; i++) { var peptide_uniprotid = peptides_source_all.data['UniProtID'][i]; if (typeof peptide_uniprotid !== 'string') { continue; } var peptide_uniprotids = peptide_uniprotid.split(';'); var found = false; for (var s = 0; s < selected_uniprotids.length; s++) { var sel_uid = selected_uniprotids[s]; for (var p = 0; p < peptide_uniprotids.length; p++) { if (peptide_uniprotids[p] === sel_uid) { found = true; break; } } if (found) break; } if (found) { matchCount++; for (var j = 0; j < peptide_columns.length; j++) { var key = peptide_columns[j]; if (key in peptides_source_all.data) { filtered_peptides[key].push(peptides_source_all.data[key][i]); } else { filtered_peptides[key].push(null); console.error("Column '" + key + "' not found in peptides_source_all.data"); } } } } console.log("Total peptide matches found: " + matchCount); var maxLength = 0; for (var i = 0; i < peptide_columns.length; i++) { var key = peptide_columns[i]; if (filtered_peptides[key].length > maxLength) { maxLength = filtered_peptides[key].length; } } for (var i = 0; i < peptide_columns.length; i++) { var key = peptide_columns[i]; while (filtered_peptides[key].length < maxLength) { filtered_peptides[key].push(null); } } peptides_source.data = filtered_peptides; peptides_source.change.emit(); console.log("Peptides table update complete"); })(); """ ) """Attach the callback to the selection event""" # Connect the selection callback to the filtered_source's selection change event filtered_source.selected.js_on_change('indices', selection_callback); # Create the layout for the visualization # Add titles for the data tables data_table_title = Paragraph(text="Selected Protein(s)") peptides_table_title = Paragraph(text="Peptides of selected protein(s)") # Arrange sliders in a 2x2 grid sliders_col = column(row(sliders[0], sliders[1]), row(sliders[2], sliders[3]) ) # Arrange search elements with spacers for layout filter_col = column(row(Spacer(width=20), search_input), row(Spacer(width=20), search_button)) # Create column layout for plot1 and sliders plot1_col = column(plot1, Spacer(height=20), sliders_col) # Place histogram plots side by side hist_plots = row(plot2, plot3) # Create column layout for histogram plots and filter components hist_plots_col = column(hist_plots, Spacer(height=20), filter_col) # Arrange data tables and their titles in a column tables_col = column(data_table_title, data_table, Spacer(height=20), peptides_table_title, peptides_table) # Create a hyperlink using Div footer = Div(text=f'

File generated on {today_str} by Nara Marella

', width=800, height=30) # Combine all elements into the final layout # The layout is organized as: plots and histograms on the left, tables on the right layout = column( row(plot1_col, hist_plots_col, Spacer(width=20), tables_col), Spacer(height=50), footer) # Output to standalone HTML file # Parameters: # output_path: Path where the HTML file will be saved # html_title: Title for the HTML page # mode='inline': Embeds all resources in the HTML file # Save the layout to the HTML file # INLINE resources parameter ensures all JavaScript and CSS is embedded in the HTML output_file(output_path, title=html_title, mode='inline') save(layout, resources=INLINE) log(f"βœ…{output_path} created succesfully!") return output_path def generate_download_buttons_from_paths(paths, mime="text/html"): for item in paths: path = item["filepath"] label = item["label"] if os.path.exists(st.session_state[path]): with open(st.session_state[path], "rb") as f: st.download_button( label=label, data=f, file_name= re.sub(r'\s+', '_', re.sub(r'[^\w\s]', '', label.strip())) + ".html", mime=mime ) def get_group_sample_columns(df, group_name): """ Get all sample columns belonging to a specific group. Pattern: {GroupName}_{replicate_number} Parameters: df : pd.DataFrame, Input dataframe group_name : str, Name of the group (e.g., 'WT', 'KI') Returns: list, List of column names matching the pattern """ pattern = f'{group_name}_\d+' sample_cols = [col for col in df.columns if re.match(pattern, col)] return sample_cols def calculate_avg_quan(df, group_name): """ Calculate average quantification for a group by averaging all its replicates. Parameters: df : pd.DataFrame, Input dataframe group_name : str, Name of the group Returns: pd.Series, Average quantification values """ sample_cols = get_group_sample_columns(df, group_name) if not sample_cols: raise ValueError(f"No sample columns found for group '{group_name}' with pattern '{group_name}_*'") print(f" Found {len(sample_cols)} replicates for {group_name}: {sample_cols}") # Calculate mean across replicates avg_quan = df[sample_cols].mean(axis=1) return avg_quan # --------------------------- # Streamlit UI # --------------------------- st.title("MQ, Moka, QC, Shanti Report") # Create a safe, writable temp directory session_id = str(uuid.uuid4()) temp_base = tempfile.gettempdir() temp_dir = os.path.join(temp_base, session_id) # Setup log storage if "log_messages" not in st.session_state: st.session_state.log_messages = [] with st.sidebar: st.subheader("πŸ“ Log") log_placeholder = st.empty() log_placeholder.text('\n'.join(st.session_state.log_messages)) try: os.makedirs(temp_dir, exist_ok=True) log(f"βœ… Created session dir: {temp_dir}") except Exception as e: st.error(f"Could not create temp directory: {e}") st.stop() # File paths inside temp dir evidence_path = os.path.join(temp_dir, "evidence.txt") mokapot_path = os.path.join(temp_dir, "mokapot_pepides.txt") mq_proteinfile_path = os.path.join(temp_dir, "mq_protein.txt") output_path = os.path.join(temp_dir, "evidence_moka_merged_peptides.tsv") html_output = os.path.join(temp_dir, "Peptide_QC_Report.html") report_file_paths = [] # will be used to collect comparison reports # File upload section st.header("πŸ“ Files Upload") col1, col2, col3 = st.columns(3) with col1: evidence_file = st.file_uploader("MQ Evidence File", type=["txt", "tsv"]) with col2: mokapot_file = st.file_uploader("Mokapot Peptides File", type=["txt", "tsv"]) with col3: mq_protein_file = st.file_uploader("MQ pVal File", type=["txt", "tsv"]) # Sample mapping section st.header("🏷️ Samples, Groups, Comparisons") col1, col2 = st.columns(2) with col1: example_mapping = """IC61, IC6 I1, I DMSO3, DMSO """ mapping_input = st.text_area( "Paste your sample, group labels below (comma or tab separated, one entry per line):", value=example_mapping, height=200, help="""Format: sample_name, group_name First element (example, IC61, I1, DMSO3) are short sample names, will be used in QC report plots. Any name longer than 5 characters, is not good for plots because of limted pixel space. Second element is the (IC6, I..) are Group labels that each sample belongs example, if DMSO1, DMSO2, DMSO3 are three replicates of group DMSO * The sequence of samples are taken as the sequence of TMT channels. example, IC61 = 1 TMT, I1 = 2 TMT, DMSO3 = 3 TMT """ ) with col2: example_mapping = """BlahBlah1, I, DMSO BlahBlah2, IC6, DMSO BlahBlah3, IC7, DMSO BlahBlah4, S, DMSO BlahBlah5, SC7, DMSO """ reporting_input = st.text_area( "Paste your comparisons below (comma or tab separated, one entry per line):", value=example_mapping, height=200, help="""format L2FC (name used in protein file), Hist1 (Group Name), Hist2 (Group Name) """ ) custom_sample_names = {} sample_group_map = {} # Processing section st.header("πŸ”„ Data Processing") st.text("Click πŸš€ button πŸ‘‡ to start. It will take ~ 1 hour to process 1 TMT 18plex batch") # Button to process if st.button("πŸš€ Merge Files and Generate QC Report", type="secondary"): if "processing_done" not in st.session_state: if not evidence_file or not mokapot_file: log("❌ Please upload both Evidence and Mokapot files") else: with st.spinner("working... (see logs in side bar)"): peptides_file_name = mokapot_file.name # Extract the filename evidence_file_name = evidence_file.name if mapping_input: valid_mappings = 0 for line_num, line in enumerate(mapping_input.strip().split('\n'), 1): parts = [p.strip() for p in line.replace('\t', ',').split(',')] if len(parts) == 2: sample_short, group_name = parts custom_sample_names["PepQuant_" + sample_short] = sample_short sample_group_map[sample_short] = group_name valid_mappings += 1 else: log(f"⚠️ Line {line_num}: Could not parse '{line}' (expected 3 comma-separated values)") log(f"βœ… Parsed {valid_mappings} valid samples") elif not custom_sample_names: log("❌ Please provide valid sample mappings") try: # Save uploaded files log("Saving uploaded files...") with open(evidence_path, "wb") as f: f.write(evidence_file.read()) with open(mokapot_path, "wb") as f: f.write(mokapot_file.read()) with open(mq_proteinfile_path, "wb") as f: f.write(mq_protein_file.read()) # Processing protein file if mq_proteinfile_path is not None: # Save uploaded file temporarily or read directly proteins_df = process_protein_data(mq_proteinfile_path, custom_sample_names, sample_group_map) # st.dataframe(proteins_df) else: log("❌ Please upload mokapot protein file") # Run merging function log("Starting file merge...") success = merge_large_files_swifter(evidence_path, mokapot_path, custom_sample_names, output_path) if success: log("βœ… File merge complete.") else: log("❌ File merge Error. See logs") # Load merged file log("Loading merged data...") df = pd.read_csv(output_path, sep='\t', low_memory=False) peptides_df = df[["QvalMoka", "UniProtID", "SequenceM", "Charge", "Missed cleavages", "NrDataPoints"]] log(f"Loaded {len(df)} rows and {len(df.columns)} columns") # Convert column types log("Converting data types...") cols_to_exclude = ['FileMoka', 'UniProtID', 'Sequence'] cols_to_convert = df.columns.difference(cols_to_exclude) # Convert numeric columns safely for col in cols_to_convert: if col in df.columns: df[col] = pd.to_numeric(df[col], errors='coerce') # Memory monitoring MEMORY_THRESHOLD = 10000 # Reduced for Docker environment num_cpu_workers = min(8, os.cpu_count() or 1) # Reduced for stability monitor_memory(label="after data loading") check_memory_usage(MEMORY_THRESHOLD, label="initial check") log("πŸ“ˆWorking on QC Reports...") # Generate plots log("Computing missed cleavages...") mc_df, included_samples = compute_missed_cleavages(df, sample_group_map, custom_sample_names) gc.collect() p1, p2 = plot_missed_cleavages(mc_df, included_samples) gc.collect() log("βœ… Plotted missed cleavages") log("Computing peptide classification...") total_peptides, shared_peptides, unique_peptides, included_samples, presence = compute_peptide_classification(df, sample_group_map, custom_sample_names) gc.collect() p3 = plot_peptide_counts(total_peptides, shared_peptides, unique_peptides, included_samples) gc.collect() log("βœ… Plotted peptide counts") p4 = plot_cumulative_peptides(total_peptides, presence, included_samples) gc.collect() log("βœ… Plotted cumulative peptides") log("calculating principal components...") pca_plots = plot_PCA(df, sample_group_map, custom_sample_names) gc.collect() log("βœ… Plotted PCA") # Preprocess ONCE for Instensity Plot, CV Plot, Heatmap and Pairwise Scatter plots preprocessed = preprocess_shared_data(df, sample_group_map, custom_sample_names) # Call all plotting functions with shared data # p5 = plot_sample_distributions(df, sample_group_map, custom_sample_names) p5 = plot_sample_distributions(df, sample_group_map, custom_sample_names, preprocessed=preprocessed) # gc.collect() log("βœ… Plotted intensity distributions") # p6 = plot_cv_distributions(df, sample_group_map, custom_sample_names) p6 = plot_cv_distributions(df, sample_group_map, custom_sample_names, preprocessed=preprocessed) # gc.collect() log("βœ… Plotted CV distributions") # heatmap_with_title = plot_heatmap(df, sample_group_map, custom_sample_names) p7 = plot_heatmap(df, sample_group_map, custom_sample_names, preprocessed=preprocessed) gc.collect() log("βœ… Created heatmap") log("performing across-group linear regression...") log("... this will take very long time") group_average_scatter = plot_across_group_pairwise_matrix(df, sample_group_map, custom_sample_names, num_cpu_workers) gc.collect() log("βœ… Created across-group scatter plots") log("performing within-group linear regression") log("... this will take very long time") within_group_scatter = plot_within_group_pairwise_matrix(df, sample_group_map, custom_sample_names, num_cpu_workers) gc.collect() log("βœ… Created within-group scatter plots") # Organize plots num_plots = len(within_group_scatter) plots_per_row = 3 if num_plots == 6 else 2 within_group_scatter_layout = [ row(*within_group_scatter[i:i + plots_per_row]) for i in range(0, num_plots, plots_per_row) ] # Create report today_str = str(date.today()) footer = Div(text=f'

Peptide QC Report file generated on {today_str}

with {peptides_file_name} and {evidence_file_name} as input by Nara Marella', width=800, height=30) log("generating QC report...") output_file(html_output, title="Proteomics QC Report") layout = column( row(p1, p2, p3, p4), row(*pca_plots, p5, p6), row(column(p7), Spacer(width=20), column(group_average_scatter)), column(*within_group_scatter_layout), column(footer) ) save(layout) log("πŸ“ˆ QC Report generated successfully!") valid_mappings = 0 log("generating comparision reports...") with hidden_container: # Common to all repots (not-specific) protein_table_columns=["UniProtID", "Genes", "SequenceCoverage", "Description"] peptides_df["QvalMoka"] = peptides_df["QvalMoka"].round(6) peptide_columns=["UniProtID", "SequenceM", "Missed cleavages", "Charge", "NrDataPoints", "QvalMoka"] hist_x_axis_label="protein count" for line_num, line in enumerate(reporting_input.strip().split('\n'), 1): parts = [p.strip() for p in line.replace('\t', ',').split(',')] if len(parts) == 3: l2fc_string, hist1, hist2 = parts l2fc_col = l2fc_string + "_L2FC" pAdj_col = l2fc_string + "_PValue" hist1_col = hist1 + "_MeanL2" hist1_title = l2fc_string hist2_col = hist2 + "_MeanL2" hist2_title = hist2 html_title = l2fc_string volcano_title = l2fc_string + " vs " + hist2 + " Comparison" report_file_name = l2fc_string + ".html" report_file_path = os.path.join(temp_dir, report_file_name) report_file_paths.append({ "filepath": report_file_path, "label": f"⬇️ {volcano_title} Report" }) valid_mappings += 1 source = load_data( protein_df = proteins_df[[l2fc_col, pAdj_col, hist1_col, hist2_col] + list(protein_table_columns)], # proteins_df is returned by process_protein_data(tsv_file_path, custom_sample_names, sample_group_map), where tsv_file_path is 20250805_DataAnalysis_norm_pvalue.txt file, not rescore.proteinGroups.fdr1.txt file alpha = 0.05, dfn = 10, dfd = 10, loc = 0, scale = 1, two_sided=False, fc_lim = 0.25, l2fc_col = l2fc_col, pAdj_col = pAdj_col ) hist1, hist1_data_filtered, hist1_bin_edges, hist1_bottoms, hist1_bar_height = make_histogram(source=source, hist_col= hist1_col, title= hist1_title, visible=True, x_axis_label= hist_x_axis_label) hist2, hist2_data_filtered, hist2_bin_edges, hist2_bottoms, hist2_bar_height = make_histogram(source, hist_col= hist2_col, title= hist2_title, visible=True, x_axis_label= hist_x_axis_label) create_interactive_dashboard( source = source, l2fc_col = l2fc_col, pAdj_col = pAdj_col, html_title = html_title, color_column="color", volcano_title = volcano_title, volcano_tools="pan, box_zoom, wheel_zoom, tap, box_select, reset, save", plot2=hist1, plot3=hist2, hist1_data_filtered=hist1_data_filtered, hist2_data_filtered=hist2_data_filtered, hist1_bin_edges=hist1_bin_edges, hist2_bin_edges=hist2_bin_edges, hist1_bottoms=hist1_bottoms, hist2_bottoms=hist2_bottoms, hist1_bar_height = hist1_bar_height, hist2_bar_height = hist2_bar_height, hist1_col = hist1_col, hist2_col = hist2_col, table_columns = protein_table_columns, peptides_df = peptides_df, peptide_columns = peptide_columns, output_path = report_file_path ) # Adding the newly created report file to session state st.session_state[report_file_path] = report_file_path else: log(f"⚠️ Line {line_num}: Could not parse '{line}' (expected 3 comma-separated values)") # log(f"βœ… Parsed {valid_mappings} valid reporting inputs\n") hidden_container.empty() # Final memory check final_memory = check_memory_usage(MEMORY_THRESHOLD, label="final") log(f"Processing completed. Final memory: {final_memory:.1f} MB") st.session_state["processing_done"] = True st.session_state["output_path"] = output_path st.session_state["html_output"] = html_output st.session_state["temp_dir"] = temp_dir st.session_state["report_file_paths"] = report_file_paths st.success("πŸŽ‰ All processing completed successfully!") except Exception as e: st.error(f"❌ An error occurred: {e}") import traceback st.error("Full traceback:") st.code(traceback.format_exc()) else: log(f"Not Processing because, st.session_state[processing_done] is {st.session_state['processing_done']}") # --------------------------- # Download buttons (Session-safe) # --------------------------- # πŸ”½ This runs regardless of button state if st.session_state.get("processing_done"): if st.session_state.get("report_file_paths"): st.header("πŸ“₯ Download Results") generate_download_buttons_from_paths(st.session_state.get("report_file_paths")) # col1, col2 = st.columns(2) # with col1: if os.path.exists(st.session_state["output_path"]): with open(st.session_state["output_path"], "rb") as f: st.download_button( label="πŸ“Š Download MQ evidence, Mokapot merged Peptide data", data=f, file_name="mq_evidence_moka_merged_peptides.tsv", mime="text/tab-separated-values" ) # with col2: if os.path.exists(st.session_state["html_output"]): with open(st.session_state["html_output"], "rb") as f: st.download_button( label="πŸ“ˆ Download QC Report", data=f, file_name=f"Peptide_QC_Report.html", mime="text/html" ) # --------------------------- # Optional cleanup step # --------------------------- if st.session_state.get("processing_done"): if st.button("🧹 Clean up temporary files (after downloading)", type="secondary"): try: if os.path.exists(st.session_state["temp_dir"]): shutil.rmtree(st.session_state["temp_dir"]) log("βœ… Cleaned up temporary files") # Remove session keys to avoid errors on rerun for k in ["output_path", "html_output", "temp_dir"]: st.session_state.pop(k, None) st.success("🧼 Cleanup complete. Reload the page to start again.") except Exception as e: st.warning(f"Could not clean up temp directory: {e}")