gelpredict / app /batch_creation_lab.py
awolter's picture
Upload folder using huggingface_hub
266eda8 verified
Raw History Blame Contribute Delete
79.8 kB
""" Lab ECM Batch Creation Form - Document ECM processing (decell, wash, lyoph, reconstitute, etc.) - Characterize batch (protein, pH, conductivity, UV, etc.) - Output: batch_id for use in gelation experiments - No plates, no wells (batch exists independently) """ import streamlit as st import sqlite3 import pandas as pd from datetime import datetime, date from pathlib import Path import json import os # Import shared utilities # Define fallback constants first COMMON_DILUENTS = ["PBS", "Water", "Tris", "HEPES", "Acetic acid", "Other"] COMMON_BUFFERS = [ "PBS", "Tris-HCl", "HEPES", "MOPS", "MES", "Sodium phosphate", "Potassium phosphate", "Other" ] COMMON_ENZYMES = [ "Trypsin", "Collagenase", "Dispase", "Accutase", "Proteinase K", "Papain", "Elastase", "Other" ] DECELL_AGENTS = [ "SDS (Sodium dodecyl sulfate)", "Triton X-100", "Tween-20", "Sodium deoxycholate", "CHAPS", "N-lauroylsarcosine sodium salt", "Peracetic acid", "Acetic acid", "Freeze-thaw (physical)", "Hypotonic/hypertonic", "Trypsin", "Collagenase", "Dispase", "Accutase", "Other" ] DELIPID_SOLVENTS = [ "Isopropanol", "Ethanol", "Acetone", "Chloroform/methanol", "Petroleum ether", "Chloroform", "Methanol", "Other" ] COMMON_BASES = ["NaOH", "KOH", "NH4OH", "Other"] COMMON_ACIDS = ["HCl", "H2SO4", "HNO3", "Other"] COMMON_SALTS = ["NaCl", "KCl", "CaCl2", "MgCl2", "Other"] REAGENT_PURPOSES = ["neutralization", "ionic_adjust", "pH_adjust", "other"] # Try to import from shared_parameters and override fallbacks try: from shared_parameters import * except ImportError: # Fallback for cloud deployment import sys import os sys.path.append(os.path.dirname(os.path.abspath(__file__))) try: from shared_parameters import * except ImportError: # Keep the fallback constants defined above pass # ============================================================================ # DATABASE CONNECTION # ============================================================================ ROOT = Path(__file__).resolve().parents[1] DB_PATH = Path(os.getenv("GELPREDICT_DB", str(ROOT / "gelpredict.db"))).resolve() def get_connection(): con = sqlite3.connect(str(DB_PATH)) con.row_factory = sqlite3.Row con.execute("PRAGMA foreign_keys=ON;") con.execute("PRAGMA journal_mode=WAL;") return con def _connect(): """Consistent connection function following app pattern""" return get_connection() def tx(): """Context manager for transactions""" from contextlib import contextmanager @contextmanager def _tx(): con = get_connection() try: con.execute("BEGIN IMMEDIATE;") yield con con.execute("COMMIT;") except Exception as e: con.execute("ROLLBACK;") raise e finally: con.close() return _tx() # ============================================================================ # BATCH ID GENERATION # ============================================================================ def generate_batch_id(family: str, species: str = None, tissue: str = None, date_obj=None, is_commercial: bool = False) -> str: """ Auto-generate batch_id from ECM metadata. Format: {family_abbrev}-{species_abbrev}{tissue_abbrev}-{YYMMDD} """ if is_commercial: return "" # Commercial uses lot number parts = [] # Family abbreviation family_map = { "decECM": "dECM", "collagen": "COL", "fibrin": "FIB", "alginate": "ALG", "gelMA": "gMA", "gelatin": "GEL", "hyaluronan": "HA", "PEG_DA": "PEG", "composite": "COMP", "other": "OTH" } parts.append(family_map.get(family, family[:4].upper())) # Species-tissue for decECM if family == "decECM" and species and tissue: species_map = {"human": "Hu", "porcine": "Por", "bovine": "Bov", "rat": "Rat", "mouse": "Mou", "avian": "Avi"} tissue_map = {"mammary": "Mam", "dermis": "Der", "small_intestine_submucosa": "SIS", "myocardium": "Myo", "liver": "Liv", "lung": "Lun"} sp = species_map.get(species, species[:3].title()) ts = tissue_map.get(tissue, tissue[:3].title()) parts.append(f"{sp}{ts}") # Date if date_obj: if isinstance(date_obj, str): dt = datetime.fromisoformat(date_obj) else: dt = date_obj parts.append(dt.strftime("%y%m%d")) else: parts.append(datetime.now().strftime("%y%m%d")) return "-".join(parts) # ============================================================================ # UI # ============================================================================ def _show_edit_batch_form(batch_id, conn): """Show form to edit an existing batch.""" st.header(f"✏️ Edit Batch: {batch_id}") # Get current batch data batch_data = pd.read_sql_query(""" SELECT * FROM ecm_batches_lab WHERE batch_id = ? """, conn, params=(batch_id,)).iloc[0] st.info("⚠️ **Edit Mode**: Modifying an existing batch. Changes will be saved immediately.") # Pre-populate form with existing data col1, col2 = st.columns(2) with col1: new_batch_id = st.text_input("Batch ID", value=batch_data['batch_id'], key=f"edit_batch_id_{batch_id}") operator_id = st.text_input("Operator ID", value=batch_data['operator_id'], key=f"edit_operator_{batch_id}") family = st.selectbox("ECM Family", ["collagen", "decECM", "fibrin", "alginate", "gelMA", "gelatin", "hyaluronan", "PEG_DA", "composite", "other"], index=["collagen", "decECM", "fibrin", "alginate", "gelMA", "gelatin", "hyaluronan", "PEG_DA", "composite", "other"].index(batch_data['family']), key=f"edit_family_{batch_id}") with col2: species = st.text_input("Species", value=batch_data['species'] or "", key=f"edit_species_{batch_id}") tissue = st.text_input("Tissue", value=batch_data['tissue'] or "", key=f"edit_tissue_{batch_id}") source_description = st.text_area("Source Description", value=batch_data['source_description'] or "", key=f"edit_source_{batch_id}") # Processing steps and characterization (read-only for now) if batch_data['processing_steps']: st.subheader("🧪 Processing Steps") processing_steps = json.loads(batch_data['processing_steps']) if processing_steps: for i, step in enumerate(processing_steps, 1): with st.expander(f"Step {i}: {step.get('type', 'Unknown').title()}", expanded=False): for key, value in step.items(): if key != 'type' and value is not None: st.write(f"**{key.replace('_', ' ').title()}:** {value}") else: st.info("No processing steps recorded") if batch_data['characterization']: st.subheader("🔬 Characterization Data") characterization = json.loads(batch_data['characterization']) if characterization: char_cols = st.columns(2) for i, (key, value) in enumerate(characterization.items()): if value is not None: with char_cols[i % 2]: st.write(f"**{key.replace('_', ' ').title()}:** {value}") else: st.info("No characterization data recorded") # Save/Cancel buttons col1, col2 = st.columns(2) with col1: if st.button("💾 Save Changes", key=f"save_edit_{batch_id}", type="primary"): try: # Update batch record conn.execute(""" UPDATE ecm_batches_lab SET batch_id = ?, operator_id = ?, family = ?, species = ?, tissue = ?, source_description = ?, updated_at = ? WHERE batch_id = ? """, (new_batch_id, operator_id, family, species, tissue, source_description, datetime.now().isoformat(), batch_id)) conn.commit() st.success(f"✅ Batch **{new_batch_id}** updated successfully!") st.rerun() except Exception as e: st.error(f"❌ Error updating batch: {e}") with col2: if st.button("❌ Cancel", key=f"cancel_edit_{batch_id}"): st.rerun() def _show_delete_batch_confirmation(batch_id, conn): """Show confirmation dialog for deleting a batch.""" st.header(f"🗑️ Delete Batch: {batch_id}") # Get batch data to show what will be deleted batch_data = pd.read_sql_query(""" SELECT * FROM ecm_batches_lab WHERE batch_id = ? """, conn, params=(batch_id,)).iloc[0] st.warning("⚠️ **This action cannot be undone!**") st.write("**Batch to be deleted:**") st.write(f"- **Batch ID:** {batch_data['batch_id']}") st.write(f"- **Family:** {batch_data['family']}") st.write(f"- **Species:** {batch_data['species'] or 'N/A'}") st.write(f"- **Tissue:** {batch_data['tissue'] or 'N/A'}") st.write(f"- **Operator:** {batch_data['operator_id']}") st.write(f"- **Created:** {batch_data['created_at']}") if batch_data['processing_steps']: processing_steps = json.loads(batch_data['processing_steps']) st.write(f"- **Processing Steps:** {len(processing_steps)} steps") col1, col2 = st.columns(2) with col1: if st.button("🗑️ Delete Permanently", key=f"confirm_delete_{batch_id}", type="primary"): try: # Use a fresh connection for the delete operation with sqlite3.connect(DB_PATH) as delete_conn: cursor = delete_conn.execute("DELETE FROM ecm_batches_lab WHERE batch_id = ?", (batch_id,)) delete_conn.commit() if cursor.rowcount > 0: st.success(f"✅ Batch **{batch_id}** deleted successfully!") st.rerun() else: st.error(f"❌ Batch **{batch_id}** not found or already deleted.") except Exception as e: st.error(f"❌ Error deleting batch: {e}") st.error(f"Details: {str(e)}") with col2: if st.button("❌ Cancel", key=f"cancel_delete_{batch_id}"): st.rerun() def _show_duplicate_batch_form(batch_id, conn): """Show form to duplicate an existing batch.""" st.header(f"📋 Duplicate Batch: {batch_id}") # Get current batch data batch_data = pd.read_sql_query(""" SELECT * FROM ecm_batches_lab WHERE batch_id = ? """, conn, params=(batch_id,)).iloc[0] st.info("📋 **Duplicate Mode**: Creating a copy of an existing batch with a new ID.") # Form for new batch col1, col2 = st.columns(2) with col1: new_batch_id = st.text_input("New Batch ID", value=f"{batch_id}_copy", key=f"dup_batch_id_{batch_id}") operator_id = st.text_input("Operator ID", value=batch_data['operator_id'], key=f"dup_operator_{batch_id}") family = st.selectbox("ECM Family", ["collagen", "decECM", "fibrin", "alginate", "gelMA", "gelatin", "hyaluronan", "PEG_DA", "composite", "other"], index=["collagen", "decECM", "fibrin", "alginate", "gelMA", "gelatin", "hyaluronan", "PEG_DA", "composite", "other"].index(batch_data['family']), key=f"dup_family_{batch_id}") with col2: species = st.text_input("Species", value=batch_data['species'] or "", key=f"dup_species_{batch_id}") tissue = st.text_input("Tissue", value=batch_data['tissue'] or "", key=f"dup_tissue_{batch_id}") source_description = st.text_area("Source Description", value=batch_data['source_description'] or "", key=f"dup_source_{batch_id}") # Show what will be copied st.subheader("📋 What will be copied:") if batch_data['processing_steps']: processing_steps = json.loads(batch_data['processing_steps']) st.write(f"**Processing Steps:** {len(processing_steps)} steps") for i, step in enumerate(processing_steps, 1): with st.expander(f"Step {i}: {step.get('type', 'Unknown').title()}", expanded=False): for key, value in step.items(): if key != 'type' and value is not None: st.write(f"**{key.replace('_', ' ').title()}:** {value}") if batch_data['characterization']: characterization = json.loads(batch_data['characterization']) st.write("**Characterization Data:** Available") char_cols = st.columns(2) for i, (key, value) in enumerate(characterization.items()): if value is not None: with char_cols[i % 2]: st.write(f"**{key.replace('_', ' ').title()}:** {value}") # Save/Cancel buttons col1, col2 = st.columns(2) with col1: if st.button("📋 Create Duplicate", key=f"save_duplicate_{batch_id}", type="primary"): try: # Check if batch ID already exists existing = conn.execute("SELECT COUNT(*) FROM ecm_batches_lab WHERE batch_id = ?", (new_batch_id,)).fetchone()[0] if existing > 0: st.error(f"❌ Batch ID **{new_batch_id}** already exists. Please choose a different ID.") return # Create new batch record with copied data conn.execute(""" INSERT INTO ecm_batches_lab (batch_id, operator_id, family, species, tissue, source_description, commercial_product, processing_steps, characterization, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, (new_batch_id, operator_id, family, species, tissue, source_description, batch_data['commercial_product'], batch_data['processing_steps'], batch_data['characterization'], datetime.now().isoformat(), datetime.now().isoformat())) conn.commit() st.success(f"✅ Batch **{new_batch_id}** created successfully!") st.success(f"📋 Duplicated from: **{batch_id}**") st.rerun() except Exception as e: st.error(f"❌ Error creating duplicate: {e}") with col2: if st.button("❌ Cancel", key=f"cancel_duplicate_{batch_id}"): st.rerun() def show_batch_library(): """Display all created ECM batches with their processing steps and characterization data.""" st.header("📚 ECM Batch Library") # Connect to database try: conn = sqlite3.connect(DB_PATH) # Check if table exists cursor = conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='ecm_batches_lab'") if not cursor.fetchone(): st.info("No batches created yet. Create your first ECM batch to see it here!") conn.close() return # Get all batches df = pd.read_sql_query(""" SELECT batch_id, operator_id, family, species, tissue, source_description, commercial_product, created_at, updated_at FROM ecm_batches_lab ORDER BY created_at DESC """, conn) if df.empty: st.info("No batches created yet. Create your first ECM batch to see it here!") conn.close() return st.write(f"**Total batches created:** {len(df)}") # Filters with st.expander("🔍 Filter Batches", expanded=False): col1, col2, col3 = st.columns(3) with col1: filter_family = st.selectbox("ECM Family", ["All"] + df['family'].dropna().unique().tolist()) filter_operator = st.text_input("Operator ID") with col2: filter_species = st.selectbox("Species", ["All"] + df['species'].dropna().unique().tolist()) filter_tissue = st.selectbox("Tissue", ["All"] + df['tissue'].dropna().unique().tolist()) with col3: filter_batch_id = st.text_input("Batch ID (partial match)") # Apply filters filtered_df = df.copy() if filter_family != "All": filtered_df = filtered_df[filtered_df['family'] == filter_family] if filter_operator: filtered_df = filtered_df[filtered_df['operator_id'].str.contains(filter_operator, case=False, na=False)] if filter_species != "All": filtered_df = filtered_df[filtered_df['species'] == filter_species] if filter_tissue != "All": filtered_df = filtered_df[filtered_df['tissue'] == filter_tissue] if filter_batch_id: filtered_df = filtered_df[filtered_df['batch_id'].str.contains(filter_batch_id, case=False, na=False)] if filtered_df.empty: st.warning("No batches match your filters.") conn.close() return # Display batch list st.write(f"**Showing {len(filtered_df)} batches:**") # Show batch summary table with action buttons display_cols = ['batch_id', 'family', 'species', 'tissue', 'operator_id', 'created_at'] for idx, row in filtered_df.iterrows(): with st.container(): col1, col2, col3, col4, col5, col6, col7 = st.columns([3, 2, 2, 2, 2, 2, 3]) with col1: st.write(f"**{row['batch_id']}**") with col2: st.write(row['family']) with col3: st.write(row['species'] or 'N/A') with col4: st.write(row['tissue'] or 'N/A') with col5: st.write(row['operator_id']) with col6: st.write(row['created_at'][:10]) # Just the date with col7: # Action buttons btn_col1, btn_col2, btn_col3 = st.columns(3) with btn_col1: if st.button("✏️", key=f"edit_{row['batch_id']}", help="Edit batch"): st.session_state[f"edit_batch_{row['batch_id']}"] = True st.rerun() with btn_col2: if st.button("🗑️", key=f"delete_{row['batch_id']}", help="Delete batch"): st.session_state[f"delete_batch_{row['batch_id']}"] = True st.rerun() with btn_col3: if st.button("📋", key=f"duplicate_{row['batch_id']}", help="Duplicate batch"): st.session_state[f"duplicate_batch_{row['batch_id']}"] = True st.rerun() st.divider() # Handle edit action for batch_id in filtered_df['batch_id']: if st.session_state.get(f"edit_batch_{batch_id}"): st.session_state[f"edit_batch_{batch_id}"] = False _show_edit_batch_form(batch_id, conn) return # Handle delete action for batch_id in filtered_df['batch_id']: if st.session_state.get(f"delete_batch_{batch_id}"): st.session_state[f"delete_batch_{batch_id}"] = False _show_delete_batch_confirmation(batch_id, conn) return # Handle duplicate action for batch_id in filtered_df['batch_id']: if st.session_state.get(f"duplicate_batch_{batch_id}"): st.session_state[f"duplicate_batch_{batch_id}"] = False _show_duplicate_batch_form(batch_id, conn) return # Batch detail viewer st.subheader("📋 Batch Details") selected_batch = st.selectbox( "Select batch to view details:", options=[""] + filtered_df['batch_id'].tolist(), format_func=lambda x: f"{x}" if x else "Choose a batch..." ) if selected_batch: # Get full batch data batch_data = pd.read_sql_query(""" SELECT * FROM ecm_batches_lab WHERE batch_id = ? """, conn, params=(selected_batch,)).iloc[0] # Display batch info col1, col2 = st.columns(2) with col1: st.write(f"**Batch ID:** {batch_data['batch_id']}") st.write(f"**ECM Family:** {batch_data['family']}") st.write(f"**Species:** {batch_data['species'] or 'N/A'}") st.write(f"**Tissue:** {batch_data['tissue'] or 'N/A'}") with col2: st.write(f"**Operator:** {batch_data['operator_id']}") st.write(f"**Created:** {batch_data['created_at']}") st.write(f"**Updated:** {batch_data['updated_at']}") if batch_data['source_description']: st.write(f"**Source Description:** {batch_data['source_description']}") if batch_data['commercial_product']: st.write(f"**Commercial Product:** {batch_data['commercial_product']}") # Processing Steps if batch_data['processing_steps']: st.subheader("🧪 Processing Steps") processing_steps = json.loads(batch_data['processing_steps']) if processing_steps: for i, step in enumerate(processing_steps, 1): with st.expander(f"Step {i}: {step.get('type', 'Unknown').title()}", expanded=False): for key, value in step.items(): if key != 'type' and value is not None: st.write(f"**{key.replace('_', ' ').title()}:** {value}") else: st.info("No processing steps recorded") # Characterization if batch_data['characterization']: st.subheader("🔬 Characterization Data") characterization = json.loads(batch_data['characterization']) if characterization: char_cols = st.columns(2) for i, (key, value) in enumerate(characterization.items()): if value is not None: with char_cols[i % 2]: st.write(f"**{key.replace('_', ' ').title()}:** {value}") else: st.info("No characterization data recorded") conn.close() except Exception as e: st.error(f"Error loading batch library: {e}") st.info("This feature requires the batch creation system to be properly set up.") def show_batch_creation_form(codebook): """Main form for creating ECM batches.""" st.header("🧬 Create ECM Batch") st.caption("Document ECM processing to create a reusable batch_id") st.info("💡 This form creates an **ECM batch** (the material). Use the **Gelation Experiment** form to test it on plates.") # Initialize session state for protocol builder if "batch_proc_steps" not in st.session_state: st.session_state.batch_proc_steps = [] # ========== BATCH IDENTITY ========== st.subheader("📋 Batch Identity") m1, m2, m3 = st.columns(3) with m1: date_input = st.date_input("Date*", value=date.today()) with m2: operator_id = st.text_input("Operator ID*", help="Your initials") with m3: # Commercial product checkbox (needs to come before family selection) is_commercial = st.checkbox( "🏭 Commercial Product", value=False, help="Check if this is a commercial product (e.g., Matrigel, Cultrex)" ) # Commercial details if is_commercial: st.markdown("**🏷️ Commercial Product Details**") COMMERCIAL_PRODUCTS = { "Matrigel": {"vendor": "Corning", "family": "composite"}, "Matrigel GFR": {"vendor": "Corning", "family": "composite"}, "Cultrex": {"vendor": "R&D Systems", "family": "collagen"}, "Cultrex BME": {"vendor": "R&D Systems", "family": "composite"}, "Geltrex": {"vendor": "Thermo Fisher", "family": "composite"}, "PureCol": {"vendor": "Advanced BioMatrix", "family": "collagen"}, "VitroCol": {"vendor": "Advanced BioMatrix", "family": "collagen"}, "Rat Tail Collagen I": {"vendor": "Corning", "family": "collagen"}, "Bovine Collagen I": {"vendor": "Sigma-Aldrich", "family": "collagen"}, "Porcine Collagen I": {"vendor": "Sigma-Aldrich", "family": "collagen"}, "Collagen I (Human)": {"vendor": "Corning", "family": "collagen"}, "Type I Collagen": {"vendor": "Various", "family": "collagen"}, "Gelatin (Porcine)": {"vendor": "Sigma-Aldrich", "family": "gelatin"}, "Gelatin (Bovine)": {"vendor": "Sigma-Aldrich", "family": "gelatin"}, "Gelatin (Fish)": {"vendor": "Sigma-Aldrich", "family": "gelatin"}, "Custom/Other": {"vendor": "", "family": ""} } c1, c2 = st.columns(2) with c1: product_name = st.selectbox("Product Name*", [""] + list(COMMERCIAL_PRODUCTS.keys())) if product_name and product_name != "Custom/Other": vendor = COMMERCIAL_PRODUCTS[product_name]["vendor"] family_hint = COMMERCIAL_PRODUCTS[product_name]["family"] else: vendor = st.text_input("Vendor Name*") family_hint = None with c2: catalog_num = st.text_input("Catalog Number") lot_num = st.text_input("Lot Number", help="Optional - used as Batch ID if provided") website = st.text_input("Company Website", placeholder="https://www.corning.com", help="Company website URL") if product_name == "Custom/Other": custom_product = st.text_input("Custom Product Name*") else: custom_product = None else: product_name = vendor = catalog_num = lot_num = custom_product = website = family_hint = None # ECM Family selection (after commercial checkbox, so we can auto-fill) if is_commercial and family_hint: # Auto-fill from product family_idx = codebook['family'].index(family_hint) + 1 if family_hint in codebook['family'] else 0 family = st.selectbox( "ECM Family (auto-filled from product)", options=[""] + codebook['family'], index=family_idx, help="Auto-detected from product. Can override if needed." ) elif is_commercial: # Commercial but no hint (Custom/Other) family = st.selectbox( "ECM Family (optional for commercial)", options=[""] + codebook['family'], help="Optional - select if known" ) else: # Lab-made (required) family = st.selectbox( "ECM Family*", options=[""] + codebook['family'], index=2 if "decECM" in codebook['family'] else 0 ) # ECM Provenance st.markdown("**🧬 ECM Provenance**") if is_commercial: st.caption("⚠️ For commercial: Species/tissue often not disclosed by vendor (optional)") prov1, prov2 = st.columns(2) with prov1: # Label changes based on whether it's required if family == "decECM" and not is_commercial: label_species = "Origin Species*" else: label_species = "Origin Species (optional)" if is_commercial else "Origin Species" dec_species = st.selectbox( label_species, [""] + codebook['species'], index=1 if "human" in codebook['species'] else 0 ) with prov2: # Label changes based on whether it's required if family == "decECM" and not is_commercial: label_tissue = "Source Tissue*" else: label_tissue = "Source Tissue (optional)" if is_commercial else "Source Tissue" dec_tissue = st.selectbox( label_tissue, [""] + codebook['tissues'], index=1 if "mammary" in codebook['tissues'] else 0 ) collagen_type = st.text_input("Collagen Type (if collagen family)", placeholder="Type I, Type II, etc.") # Generate Batch ID st.markdown("**🏷️ Batch ID**") if is_commercial and lot_num: batch_id = f"{product_name or 'Commercial'}-{lot_num}" st.success(f"✅ Batch ID: **{batch_id}**") elif family and not is_commercial: batch_id = generate_batch_id(family, dec_species, dec_tissue, date_input) st.success(f"✅ Auto-generated Batch ID: **{batch_id}**") else: batch_id = "" st.warning("⚠️ Fill in Family (and Species/Tissue for decECM) to generate Batch ID") st.markdown("---") # ========== PRE-STORAGE ========== st.subheader("🧊 Pre-Processing Tissue Storage") st.caption("⚠️ BEFORE any decellularization began (raw tissue storage)") with st.expander("Pre-Storage Details", expanded=False): # Fresh storage c1a, c1b = st.columns(2) with c1a: unk_days_4c = st.checkbox("Unknown", key="batch_unk_pre_days_4c") pre_storage_days_4C = st.number_input("Days at 4°C", min_value=0, value=0, disabled=unk_days_4c) if unk_days_4c: pre_storage_days_4C = None with c1b: pre_storage_fresh_notes = st.text_input("Fresh storage notes", placeholder="e.g., in PBS") # Frozen storage st.markdown("**Frozen Storage:**") c2, c3, c4 = st.columns(3) with c2: unk_frozen_mo = st.checkbox("Unknown", key="batch_unk_frozen_mo") pre_storage_duration_months = st.number_input("Frozen (months)", 0.0, 120.0, 0.0, 0.5, disabled=unk_frozen_mo) if unk_frozen_mo: pre_storage_duration_months = None with c3: unk_freezer_temp = st.checkbox("Unknown", key="batch_unk_frz_temp") pre_storage_temp_freezer = st.number_input("Freezer temp (°C)", -200.0, 0.0, -80.0, 10.0, disabled=unk_freezer_temp) if unk_freezer_temp: pre_storage_temp_freezer = None with c4: pre_storage_frozen_in = st.text_input("Frozen in", placeholder="dry, buffer, cryoprotectant") # Freeze-thaw cycles st.markdown("**Freeze-Thaw During Storage:**") ft1, ft2, ft3, ft4 = st.columns(4) with ft1: unk_ft_cyc = st.checkbox("Unknown", key="batch_unk_ft_cyc") pre_storage_freeze_cycles = st.number_input("# Cycles", min_value=0, value=0, disabled=unk_ft_cyc) if unk_ft_cyc: pre_storage_freeze_cycles = None with ft2: pre_storage_thaw_method = st.selectbox("Thaw method", ["","passive_room_temp","37C_water_bath","4C_fridge", "buffer_wash_series","PBS_series","gradual_temp_ramp","other"]) with ft3: unk_thaw_dur = st.checkbox("Unk", key="batch_unk_thaw_dur") pre_storage_thaw_duration_min = st.number_input("Thaw duration (min)", 0.0, 1000.0, 30.0, 5.0, disabled=unk_thaw_dur) if unk_thaw_dur: pre_storage_thaw_duration_min = None with ft4: pre_storage_ft_notes = st.text_input("FT notes", placeholder="e.g., 3× PBS washes") st.markdown("---") # ========== ECM PROCESSING PROTOCOL ========== if not is_commercial: st.subheader("🔬 ECM Processing Protocol") st.caption("Build your ECM preparation protocol step-by-step") # Protocol builder buttons st.caption("**Add Processing Steps:**") row1 = st.columns(6) step_types = [ ("Decell", "decell"), ("Wash", "wash"), ("Delipid", "delipid"), ("Enzyme", "enzyme"), ("Homogenize", "homogenize"), ("Grind", "grind") ] for i, (label, stype) in enumerate(step_types): with row1[i]: if st.button(f"➕ {label}", key=f"add_{stype}_batch"): st.session_state.batch_proc_steps.append({ "type": stype, "id": len(st.session_state.batch_proc_steps) }) st.rerun() row2 = st.columns(6) step_types2 = [ ("Freeze-Thaw", "freeze_thaw"), ("Lyophilize", "lyophilize"), ("Reconstitute", "reconstitute"), ("pH Adjust", "ph_adjust"), ("Dialysis", "dialysis"), ("Filtration", "filtration") ] for i, (label, stype) in enumerate(step_types2): with row2[i]: if st.button(f"➕ {label}", key=f"add_{stype}_batch"): st.session_state.batch_proc_steps.append({ "type": stype, "id": len(st.session_state.batch_proc_steps) }) st.rerun() row3 = st.columns(6) with row3[0]: if st.button("➕ Centrifuge", key="add_centrifuge_batch"): st.session_state.batch_proc_steps.append({ "type": "centrifuge", "id": len(st.session_state.batch_proc_steps) }) st.rerun() with row3[1]: if st.button("➕ Storage", key="add_storage_batch"): st.session_state.batch_proc_steps.append({ "type": "storage", "id": len(st.session_state.batch_proc_steps) }) st.rerun() with row3[2]: if st.button("➕ Other", key="add_other_batch"): st.session_state.batch_proc_steps.append({ "type": "other", "id": len(st.session_state.batch_proc_steps) }) st.rerun() with row3[5]: if st.button("🗑️ Clear All", key="clear_batch_steps"): st.session_state.batch_proc_steps = [] st.rerun() if st.session_state.batch_proc_steps: st.caption(f"**{len(st.session_state.batch_proc_steps)} step(s) added**") # Display steps (simplified - full implementation would include all step types) processing_steps = [] for i, step in enumerate(st.session_state.batch_proc_steps): with st.expander(f"Step {i+1}: {step['type'].title()}", expanded=True): if step["type"] == "reconstitute": st.caption("💡 Critical: Enter lyoph weight + recon volume to calculate stock concentration") recol1, recol2, recol3, recol4 = st.columns(4) with recol1: solvent_sel = st.selectbox("Solvent", COMMON_DILUENTS, key=f"recon_solv_{step['id']}") if solvent_sel == "Other": solvent = st.text_input("Specify", key=f"recon_solv_other_{step['id']}") elif solvent_sel == "Acetic acid": solvent = "Acetic acid" conc_val = st.number_input("Conc (% v/v)", 0.0, 100.0, 0.1, 0.01, key=f"recon_aa_conc_{step['id']}") solvent = f"{conc_val}% Acetic acid" else: solvent = solvent_sel with recol2: unk_wt = st.checkbox("Unk", key=f"unk_recon_wt_{step['id']}") lyoph_wt = st.number_input("Lyoph weight (mg)", 0.0, 10000.0, 100.0, 1.0, disabled=unk_wt, key=f"recon_wt_{step['id']}") if unk_wt: lyoph_wt = None with recol3: unk_vol = st.checkbox("Unk", key=f"unk_recon_vol_{step['id']}") recon_vol = st.number_input("Recon volume (mL)", 0.0, 1000.0, 10.0, 0.1, disabled=unk_vol, key=f"recon_vol_{step['id']}") if unk_vol: recon_vol = None with recol4: unk_temp = st.checkbox("Unk", key=f"unk_recon_temp_{step['id']}") recon_temp = st.number_input("Temp (°C)", 0.0, 50.0, 4.0, 1.0, disabled=unk_temp, key=f"recon_temp_{step['id']}") if unk_temp: recon_temp = None # Auto-calculate concentration final_conc = None if lyoph_wt and recon_vol and lyoph_wt > 0 and recon_vol > 0: final_conc = lyoph_wt / recon_vol st.success(f"✅ **Stock concentration: {final_conc:.2f} mg/mL**") notes = st.text_input("Notes", placeholder="e.g., with pepsin 0.1 mg/mL, stirred overnight", key=f"recon_notes_{step['id']}") processing_steps.append({ "type": "reconstitute", "solvent": solvent, "lyoph_weight_mg": lyoph_wt, "recon_volume_mL": recon_vol, "final_conc_mgml": final_conc, "temp_C": recon_temp, "notes": notes or None }) elif step["type"] == "decell": st.caption("💡 Decellularization: Remove cells while preserving ECM structure") dcol1, dcol2, dcol3, dcol4 = st.columns(4) with dcol1: reagent_sel = st.selectbox("Reagent", DECELL_AGENTS, key=f"decell_reag_sel_batch_{step['id']}") if reagent_sel == "Other": reagent = st.text_input("Specify reagent", placeholder="e.g., custom detergent", key=f"decell_reag_other_batch_{step['id']}") else: reagent = reagent_sel with dcol2: unk_conc = st.checkbox("Unk", key=f"unk_decell_conc_batch_{step['id']}", help="Unknown/not reported") conc_val = st.number_input("Concentration", 0.0, 100.0, 1.0, 0.1, disabled=unk_conc, key=f"decell_conc_batch_{step['id']}") conc_unit = st.selectbox("Units", ["%","M","mM","mg/mL","v/v"], disabled=unk_conc, key=f"decell_unit_batch_{step['id']}") if unk_conc: conc_val, conc_unit = None, None with dcol3: unk_dur = st.checkbox("Unk", key=f"unk_decell_dur_batch_{step['id']}", help="Unknown/not reported") duration = st.number_input("Duration (hours)", 0.0, 1000.0, 24.0, 0.5, disabled=unk_dur, key=f"decell_dur_batch_{step['id']}") if unk_dur: duration = None unk_temp = st.checkbox("Unk", key=f"unk_decell_temp_batch_{step['id']}", help="Unknown/not reported") temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, disabled=unk_temp, key=f"decell_temp_batch_{step['id']}", help="e.g., 4°C (fridge), 22°C (room temp), 37°C") if unk_temp: temp = None with dcol4: unk_chg = st.checkbox("Unk", key=f"unk_decell_chg_batch_{step['id']}", help="Unknown/not reported") changes = st.number_input("# Changes", 1, 100, 3, 1, disabled=unk_chg, key=f"decell_chg_batch_{step['id']}", help="Solution changes") if unk_chg: changes = None notes = st.text_input("Notes (optional)", placeholder="e.g., gentle agitation, sterile conditions", key=f"decell_notes_batch_{step['id']}") processing_steps.append({ "type": "decell", "reagent": reagent, "concentration": conc_val, "conc_units": conc_unit, "duration_hours": duration, "temp_C": temp, "changes": changes, "notes": notes or None }) # Remove button for this specific step if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"): st.session_state.batch_proc_steps.pop(i) st.rerun() elif step["type"] == "wash": st.caption("💡 Washing: Remove decellularization agents and cellular debris") wcol1, wcol2, wcol3, wcol4 = st.columns(4) with wcol1: solution_sel = st.selectbox("Solution", COMMON_BUFFERS + ["DI water"], key=f"wash_sol_sel_batch_{step['id']}") if solution_sel == "Other": solution = st.text_input("Specify solution", placeholder="e.g., custom buffer", key=f"wash_sol_other_batch_{step['id']}") else: solution = solution_sel with wcol2: conc_val = st.number_input("Conc", 0.0, 100.0, 1.0, 0.1, key=f"wash_conc_batch_{step['id']}") conc_unit = st.selectbox("Units", ["x","M","mM","%","n/a"], key=f"wash_unit_batch_{step['id']}") with wcol3: washes = st.number_input("# Washes", 1, 20, 3, 1, key=f"wash_num_batch_{step['id']}") duration = st.number_input("Duration each (min)", 0.0, 500.0, 15.0, 5.0, key=f"wash_dur_batch_{step['id']}") with wcol4: temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"wash_temp_batch_{step['id']}", help="Wash temperature") notes = st.text_input("Notes (optional)", placeholder="e.g., shaking, flow rate", key=f"wash_notes_batch_{step['id']}") processing_steps.append({ "type": "wash", "solution": solution, "concentration": conc_val, "conc_units": conc_unit, "n_washes": washes, "duration_min": duration, "temp_C": temp, "notes": notes or None }) # Remove button for this specific step if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"): st.session_state.batch_proc_steps.pop(i) st.rerun() elif step["type"] == "delipid": st.caption("💡 Delipidation: Remove lipids and fat content") dlcol1, dlcol2, dlcol3, dlcol4 = st.columns(4) with dlcol1: solvent_sel = st.selectbox("Solvent", DELIPID_SOLVENTS, key=f"delip_solv_sel_batch_{step['id']}") if solvent_sel == "Other": solvent = st.text_input("Specify solvent", placeholder="e.g., custom solvent", key=f"delip_solv_other_batch_{step['id']}") else: solvent = solvent_sel with dlcol2: conc_val = st.number_input("Concentration", 0.0, 100.0, 100.0, 1.0, key=f"delip_conc_batch_{step['id']}") conc_unit = st.selectbox("Units", ["%","v/v"], key=f"delip_unit_batch_{step['id']}") with dlcol3: duration = st.number_input("Duration (hours)", 0.0, 100.0, 2.0, 0.25, key=f"delip_dur_batch_{step['id']}") temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"delip_temp_batch_{step['id']}", help="Room temp, fridge, etc.") with dlcol4: times = st.number_input("# Times", 1, 20, 3, 1, key=f"delip_times_batch_{step['id']}", help="Number of repetitions") notes = st.text_input("Notes (optional)", placeholder="e.g., vortex, solvent grade", key=f"delip_notes_batch_{step['id']}") processing_steps.append({ "type": "delipid", "solvent": solvent, "concentration": conc_val, "conc_units": conc_unit, "duration_hours": duration, "temp_C": temp, "n_times": times, "notes": notes or None }) # Remove button for this specific step if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"): st.session_state.batch_proc_steps.pop(i) st.rerun() elif step["type"] == "enzyme": st.caption("💡 Enzyme treatment: Digest specific ECM components") ecol1, ecol2, ecol3, ecol4 = st.columns(4) with ecol1: enzyme_sel = st.selectbox("Enzyme", COMMON_ENZYMES, key=f"enz_name_sel_batch_{step['id']}") if enzyme_sel == "Other": enzyme = st.text_input("Specify enzyme", placeholder="e.g., custom enzyme", key=f"enz_name_other_batch_{step['id']}") else: enzyme = enzyme_sel with ecol2: conc = st.number_input("Conc.", 0.0, 100.0, 1.0, 0.1, key=f"enz_conc_batch_{step['id']}") units = st.selectbox("Units", ["mg/mL", "U/mL", "mg/g"], key=f"enz_units_batch_{step['id']}") with ecol3: duration = st.number_input("Duration (hrs)", 0.0, 100.0, 2.0, 0.25, key=f"enz_dur_batch_{step['id']}") temp = st.number_input("Temp (°C)", 4.0, 60.0, 37.0, 1.0, key=f"enz_temp_batch_{step['id']}") with ecol4: ph_val = st.number_input("pH", 1.0, 14.0, 7.4, 0.1, key=f"enz_ph_batch_{step['id']}") buffer = st.text_input("Buffer", placeholder="e.g., PBS, Tris", key=f"enz_buffer_batch_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., gentle agitation, sterile conditions", key=f"enz_notes_batch_{step['id']}") processing_steps.append({ "type": "enzyme", "enzyme": enzyme, "concentration": conc, "units": units, "duration_hours": duration, "temp_C": temp, "pH": ph_val, "buffer": buffer, "notes": notes or None }) # Remove button for this specific step if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"): st.session_state.batch_proc_steps.pop(i) st.rerun() elif step["type"] == "homogenize": st.caption("💡 Homogenization: Mechanical tissue disruption") hcol1, hcol2, hcol3, hcol4 = st.columns(4) with hcol1: medium = st.selectbox("Medium/Liquid", COMMON_BUFFERS + COMMON_DILUENTS + ["PBS", "Saline", "DI water", "Other"], key=f"homog_medium_batch_{step['id']}") if medium == "Other": medium = st.text_input("Specify medium", placeholder="e.g., 0.1M HCl", key=f"homog_medium_other_batch_{step['id']}") with hcol2: rpm = st.number_input("RPM", 0, 50000, 10000, 1000, key=f"homog_rpm_batch_{step['id']}") duration = st.number_input("Duration (min)", 0.0, 500.0, 5.0, 1.0, key=f"homog_dur_batch_{step['id']}") with hcol3: temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"homog_temp_batch_{step['id']}") passes = st.number_input("# Passes", 1, 20, 1, 1, key=f"homog_passes_batch_{step['id']}") with hcol4: volume = st.number_input("Volume (mL)", 0.0, 1000.0, 10.0, 1.0, key=f"homog_vol_batch_{step['id']}") ratio = st.text_input("Tissue:Medium ratio", placeholder="e.g., 1:10, 1:20", key=f"homog_ratio_batch_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., sterile conditions, ice bath", key=f"homog_notes_batch_{step['id']}") processing_steps.append({"type": "homogenize", "medium": medium, "rpm": rpm, "duration_min": duration, "temp_C": temp, "passes": passes, "volume_mL": volume, "tissue_medium_ratio": ratio, "notes": notes or None}) # Remove button for this specific step if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"): st.session_state.batch_proc_steps.pop(i) st.rerun() elif step["type"] == "grind": st.caption("💡 Grinding/Milling: Mechanical particle size reduction") gcol1, gcol2, gcol3, gcol4 = st.columns(4) with gcol1: method = st.selectbox("Method", ["mortar_pestle", "ball_mill", "cryomill", "other"], key=f"grind_method_batch_{step['id']}") if method == "other": method = st.text_input("Specify method", key=f"grind_method_other_batch_{step['id']}") with gcol2: duration = st.number_input("Duration (min)", 0.0, 500.0, 5.0, 1.0, key=f"grind_dur_batch_{step['id']}") with gcol3: temp = st.number_input("Temp (°C)", -200.0, 50.0, 4.0, 1.0, key=f"grind_temp_batch_{step['id']}") with gcol4: cycles = st.number_input("# Cycles", 1, 50, 1, 1, key=f"grind_cycles_batch_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., liquid nitrogen, sterile", key=f"grind_notes_batch_{step['id']}") processing_steps.append({"type": "grind", "method": method, "duration_min": duration, "temp_C": temp, "cycles": cycles, "notes": notes or None}) # Remove button for this specific step if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"): st.session_state.batch_proc_steps.pop(i) st.rerun() elif step["type"] == "freeze_thaw": st.caption("💡 Freeze-Thaw: Cell lysis and ECM disruption") ftcol1, ftcol2, ftcol3, ftcol4 = st.columns(4) with ftcol1: cycles = st.number_input("# Cycles", 1, 50, 3, 1, key=f"ft_cycles_batch_{step['id']}") with ftcol2: freeze_temp = st.number_input("Freeze temp (°C)", -200.0, 0.0, -80.0, 10.0, key=f"ft_ftemp_batch_{step['id']}") with ftcol3: thaw_temp = st.number_input("Thaw temp (°C)", 0.0, 50.0, 37.0, 1.0, key=f"ft_ttemp_batch_{step['id']}") with ftcol4: duration_cycle = st.number_input("Duration/cycle (min)", 0.0, 1000.0, 60.0, 5.0, key=f"ft_dur_batch_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., liquid nitrogen, water bath", key=f"ft_notes_batch_{step['id']}") processing_steps.append({"type": "freeze_thaw", "cycles": cycles, "freeze_temp_C": freeze_temp, "thaw_temp_C": thaw_temp, "duration_min": duration_cycle, "notes": notes or None}) # Remove button for this specific step if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"): st.session_state.batch_proc_steps.pop(i) st.rerun() elif step["type"] == "lyophilize": st.caption("💡 Lyophilization: Freeze-drying for storage") lycol1, lycol2, lycol3, lycol4 = st.columns(4) with lycol1: unk_lyoph_dur = st.checkbox("Unk", key=f"unk_lyoph_dur_batch_{step['id']}", help="Unknown/not reported") duration = st.number_input("Duration (hours)", 0.0, 200.0, 48.0, 1.0, disabled=unk_lyoph_dur, key=f"lyoph_dur_batch_{step['id']}") if unk_lyoph_dur: duration = None with lycol2: temp = st.number_input("Temp (°C)", -100.0, 0.0, -50.0, 5.0, key=f"lyoph_temp_batch_{step['id']}") with lycol3: unk_press = st.checkbox("Unk", key=f"unk_lyoph_press_batch_{step['id']}", help="Unknown/not reported") pressure = st.number_input("Pressure (mTorr)", 0.0, 1000.0, 100.0, 10.0, disabled=unk_press, key=f"lyoph_press_batch_{step['id']}") if unk_press: pressure = None with lycol4: shelf_temp = st.number_input("Shelf temp (°C)", -100.0, 50.0, 20.0, 5.0, key=f"lyoph_shelf_batch_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., pre-freeze rate, condenser temp", key=f"lyoph_notes_batch_{step['id']}") processing_steps.append({"type": "lyophilize", "duration_hours": duration, "temp_C": temp, "pressure_mtorr": pressure, "shelf_temp_C": shelf_temp, "notes": notes or None}) # Remove button for this specific step if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"): st.session_state.batch_proc_steps.pop(i) st.rerun() elif step["type"] == "ph_adjust": st.caption("💡 pH Adjustment: Neutralization and buffering") phcol1, phcol2, phcol3, phcol4 = st.columns(4) with phcol1: direction = st.radio("Direction", ["Raise pH (base)", "Lower pH (acid)"], key=f"ph_dir_batch_{step['id']}", horizontal=True) if "base" in direction.lower(): reagent_sel = st.selectbox("Base", COMMON_BASES, key=f"ph_base_sel_batch_{step['id']}") else: reagent_sel = st.selectbox("Acid", COMMON_ACIDS, key=f"ph_acid_sel_batch_{step['id']}") if reagent_sel == "Other": reagent = st.text_input("Specify reagent", key=f"ph_reag_other_batch_{step['id']}") else: reagent = reagent_sel with phcol2: conc_val = st.number_input("Concentration", 0.0, 10.0, 1.0, 0.1, key=f"ph_conc_batch_{step['id']}") conc_unit = st.selectbox("Units", ["M", "mM", "%"], key=f"ph_unit_batch_{step['id']}") with phcol3: target_ph = st.number_input("Target pH", 1.0, 14.0, 7.4, 0.1, key=f"ph_target_batch_{step['id']}") final_ph = st.number_input("Final pH", 1.0, 14.0, 7.4, 0.1, key=f"ph_final_batch_{step['id']}") with phcol4: temp = st.number_input("Temp (°C)", 0.0, 50.0, 22.0, 1.0, key=f"ph_temp_batch_{step['id']}") duration = st.number_input("Duration (min)", 0.0, 300.0, 15.0, 5.0, key=f"ph_dur_batch_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., dropwise addition, monitoring", key=f"ph_notes_batch_{step['id']}") processing_steps.append({"type": "ph_adjust", "direction": direction, "reagent": reagent, "concentration": conc_val, "conc_units": conc_unit, "target_pH": target_ph, "final_pH": final_ph, "temp_C": temp, "duration_min": duration, "notes": notes or None}) # Remove button for this specific step if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"): st.session_state.batch_proc_steps.pop(i) st.rerun() elif step["type"] == "dialysis": st.caption("💡 Dialysis: Buffer exchange and purification") diacol1, diacol2, diacol3, diacol4 = st.columns(4) with diacol1: buffer_sel = st.selectbox("Buffer/Solution", COMMON_BUFFERS + COMMON_ACIDS, key=f"dial_buf_sel_batch_{step['id']}") if buffer_sel == "Other": buffer = st.text_input("Specify buffer", key=f"dial_buf_other_batch_{step['id']}") else: buffer = buffer_sel with diacol2: conc_val = st.number_input("Concentration", 0.0, 100.0, 1.0, 0.1, key=f"dial_conc_batch_{step['id']}") conc_unit = st.selectbox("Units", ["x", "M", "mM"], key=f"dial_unit_batch_{step['id']}") with diacol3: duration = st.number_input("Duration (hours)", 0.0, 168.0, 24.0, 1.0, key=f"dial_dur_batch_{step['id']}") changes = st.number_input("# Changes", 1, 20, 3, 1, key=f"dial_changes_batch_{step['id']}") with diacol4: temp = st.number_input("Temp (°C)", 0.0, 50.0, 4.0, 1.0, key=f"dial_temp_batch_{step['id']}") mwco = st.number_input("MWCO (kDa)", 1.0, 100.0, 10.0, 1.0, key=f"dial_mwco_batch_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., stirring, sterile conditions", key=f"dial_notes_batch_{step['id']}") processing_steps.append({"type": "dialysis", "buffer": buffer, "concentration": conc_val, "conc_units": conc_unit, "duration_hours": duration, "changes": changes, "temp_C": temp, "mwco_kda": mwco, "notes": notes or None}) # Remove button for this specific step if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"): st.session_state.batch_proc_steps.pop(i) st.rerun() elif step["type"] == "storage": st.caption("💡 Storage: Preservation conditions") scol1, scol2, scol3, scol4 = st.columns(4) with scol1: temp = st.number_input("Temp (°C)", -200.0, 50.0, -80.0, 1.0, key=f"stor_temp_batch_{step['id']}") with scol2: duration = st.text_input("Duration", placeholder="e.g., 7 days, 3 months", key=f"stor_dur_batch_{step['id']}") with scol3: container = st.selectbox("Container", ["tube", "vial", "bag", "plate", "other"], key=f"stor_container_batch_{step['id']}") with scol4: atmosphere = st.selectbox("Atmosphere", ["air", "nitrogen", "vacuum", "argon"], key=f"stor_atmo_batch_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., sterile, labeled", key=f"stor_notes_batch_{step['id']}") processing_steps.append({"type": "storage", "temp_C": temp, "duration": duration, "container": container, "atmosphere": atmosphere, "notes": notes or None}) # Remove button for this specific step if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"): st.session_state.batch_proc_steps.pop(i) st.rerun() elif step["type"] == "filtration": st.caption("💡 Filtration: Size-based separation") fcol1, fcol2, fcol3, fcol4 = st.columns(4) with fcol1: filter_type = st.selectbox("Filter type", ["spin_filter", "syringe_filter", "vacuum_filter", "gravity_filter", "other"], key=f"filt_type_batch_{step['id']}") if filter_type == "other": filter_type = st.text_input("Specify type", key=f"filt_type_other_batch_{step['id']}") with fcol2: pore_size = st.number_input("Pore size (µm)", 0.1, 100.0, 0.22, 0.01, key=f"filt_pore_batch_{step['id']}") material = st.selectbox("Material", ["PES", "PVDF", "cellulose", "nylon", "other"], key=f"filt_material_batch_{step['id']}") with fcol3: pressure = st.number_input("Pressure (psi)", 0.0, 100.0, 5.0, 0.5, key=f"filt_press_batch_{step['id']}") duration = st.number_input("Duration (min)", 0.0, 300.0, 10.0, 1.0, key=f"filt_dur_batch_{step['id']}") with fcol4: temp = st.number_input("Temp (°C)", 0.0, 50.0, 22.0, 1.0, key=f"filt_temp_batch_{step['id']}") volume = st.number_input("Volume (mL)", 0.0, 1000.0, 10.0, 1.0, key=f"filt_vol_batch_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., pre-wet, sterile", key=f"filt_notes_batch_{step['id']}") processing_steps.append({"type": "filtration", "filter_type": filter_type, "pore_size_um": pore_size, "material": material, "pressure_psi": pressure, "duration_min": duration, "temp_C": temp, "volume_mL": volume, "notes": notes or None}) # Remove button for this specific step if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"): st.session_state.batch_proc_steps.pop(i) st.rerun() elif step["type"] == "centrifuge": st.caption("💡 Centrifugation: Density-based separation") ccol1, ccol2, ccol3, ccol4 = st.columns(4) with ccol1: purpose = st.selectbox("Purpose", ["clarification", "concentration", "pellet_removal", "debris_removal", "other"], key=f"cent_purp_batch_{step['id']}") if purpose == "other": purpose = st.text_input("Specify purpose", key=f"cent_purp_other_batch_{step['id']}") with ccol2: speed = st.number_input("Speed (RCF)", 0, 50000, 3000, 100, key=f"cent_speed_batch_{step['id']}") duration = st.number_input("Duration (min)", 0.0, 300.0, 10.0, 1.0, key=f"cent_dur_batch_{step['id']}") with ccol3: temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"cent_temp_batch_{step['id']}") cycles = st.number_input("# Cycles", 1, 10, 1, 1, key=f"cent_cycles_batch_{step['id']}") with ccol4: volume = st.number_input("Volume (mL)", 0.0, 1000.0, 50.0, 5.0, key=f"cent_vol_batch_{step['id']}") tube_type = st.selectbox("Tube type", ["microcentrifuge", "conical", "round_bottom", "other"], key=f"cent_tube_batch_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., brake on/off, sterile", key=f"cent_notes_batch_{step['id']}") processing_steps.append({"type": "centrifuge", "purpose": purpose, "speed_rcf": speed, "duration_min": duration, "temp_C": temp, "cycles": cycles, "volume_mL": volume, "tube_type": tube_type, "notes": notes or None}) # Remove button for this specific step if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"): st.session_state.batch_proc_steps.pop(i) st.rerun() # For other step types, provide basic form else: notes = st.text_input("Notes", placeholder=f"Describe {step['type']} process", key=f"step_notes_{step['id']}") processing_steps.append({ "type": step["type"], "notes": notes or None }) # Remove button for this specific step if st.button("🗑️ Remove", key=f"remove_step_batch_{step['id']}"): st.session_state.batch_proc_steps.pop(i) st.rerun() else: st.info("ℹ️ Commercial products: Processing protocol N/A") processing_steps = [] st.markdown("---") # ========== BATCH CHARACTERIZATION ========== st.subheader("📊 Batch Characterization") st.caption("Measure ECM batch properties (can add later)") with st.expander("Characterization Measurements", expanded=False): char1, char2, char3 = st.columns(3) with char1: unk_protein = st.checkbox("Unk", key="batch_unk_protein", help="Unknown/not measured") ecm_total_protein_mgml = st.number_input("Protein (mg/mL)", 0.0, 100.0, 0.0, 0.1, disabled=unk_protein) if unk_protein: ecm_total_protein_mgml = None protein_assay_method = st.selectbox("Assay Method", ["","BCA","Bradford","Lowry","DC_assay","A280","other"], disabled=unk_protein) with char2: unk_ph = st.checkbox("Unk", key="batch_unk_ph", help="Unknown/not measured") pre_pH = st.number_input("Pre-pH", 0.0, 14.0, 0.0, 0.1, disabled=unk_ph, help="pH before neutralization") if unk_ph: pre_pH = None unk_cond = st.checkbox("Unk", key="batch_unk_cond", help="Unknown/not measured") pre_conductivity_mS = st.number_input("Pre-Conductivity (mS/cm)", 0.0, 100.0, 0.0, 0.1, disabled=unk_cond) if unk_cond: pre_conductivity_mS = None with char3: unk_uv = st.checkbox("Unk", key="batch_unk_uv", help="Unknown/not measured") uv_A220 = st.number_input("UV A220", 0.0, 1e6, 0.0, 0.01, disabled=unk_uv) uv_A280 = st.number_input("UV A280", 0.0, 1e6, 0.0, 0.01, disabled=unk_uv) if unk_uv: uv_A220 = None uv_A280 = None # Auto-calculate UV ratio uv_ratio = None if uv_A220 and uv_A280 and uv_A220 > 0 and uv_A280 > 0: uv_ratio = uv_A220 / uv_A280 st.info(f"📊 UV ratio A220/A280: **{uv_ratio:.3f}**") st.markdown("---") # ========== NOTES ========== notes_ecm_processing = st.text_area( "📝 ECM Processing Notes", placeholder="e.g., Tissue was slightly fibrous, decell took longer than usual, final solution clear", help="Notes about ECM preparation and characterization", height=100 ) st.markdown("---") # ========== SAVE BUTTON ========== if st.button("💾 Save ECM Batch", type="primary", use_container_width=True): # Validation errors = [] if not operator_id: errors.append("Operator ID required") # Family required for lab-made, optional for commercial if not is_commercial and not family: errors.append("ECM Family required (or check Commercial Product)") if not batch_id: errors.append("Batch ID required (fill in required fields)") # Species/tissue only required for lab-made decECM (commercial may not disclose) if family == "decECM" and not is_commercial: if not dec_species: errors.append("Species required for lab-made decECM") if not dec_tissue: errors.append("Tissue required for lab-made decECM") if errors: for e in errors: st.error(f"❌ {e}") return # Prepare payload payload = { 'batch_id': batch_id, 'date': date_input.isoformat(), 'operator_id': operator_id, 'family': family, 'is_commercial_product': int(is_commercial) if is_commercial else 0, 'commercial_vendor': vendor if is_commercial else None, 'commercial_product_name': (custom_product or product_name) if is_commercial else None, 'commercial_catalog_number': catalog_num if is_commercial else None, 'commercial_lot_number': lot_num if is_commercial else None, 'commercial_website': website if is_commercial else None, 'ecm_origin_species': dec_species or None, 'ecm_source_tissue': dec_tissue or None, 'collagen_type': collagen_type or None, 'pre_storage_days_4C': pre_storage_days_4C, 'pre_storage_fresh_notes': pre_storage_fresh_notes or None, 'pre_storage_freeze_cycles': pre_storage_freeze_cycles if 'pre_storage_freeze_cycles' in locals() else None, 'pre_storage_temp_freezer': pre_storage_temp_freezer, 'pre_storage_duration_months': pre_storage_duration_months, 'pre_storage_frozen_in': pre_storage_frozen_in or None, 'pre_storage_thaw_method': pre_storage_thaw_method if 'pre_storage_thaw_method' in locals() else None, 'pre_storage_thaw_duration_min': pre_storage_thaw_duration_min if 'pre_storage_thaw_duration_min' in locals() else None, 'pre_storage_ft_notes': pre_storage_ft_notes if 'pre_storage_ft_notes' in locals() else None, 'processing_protocol': json.dumps(processing_steps) if processing_steps else None, 'ecm_total_protein_mgml': ecm_total_protein_mgml if ecm_total_protein_mgml > 0 else None, 'protein_assay_method': protein_assay_method or None, 'pre_pH': pre_pH if pre_pH > 0 else None, 'pre_conductivity_mS': pre_conductivity_mS if pre_conductivity_mS > 0 else None, 'uv_A220': uv_A220 if uv_A220 > 0 else None, 'uv_A280': uv_A280 if uv_A280 > 0 else None, 'uv_ratio_A220_A280': uv_ratio, 'notes_pre': notes_ecm_processing or None, # Using notes_pre for ECM processing 'created_at': datetime.now().isoformat(), 'updated_at': datetime.now().isoformat() } # Save to database try: # Create batches table if it doesn't exist conn = sqlite3.connect(DB_PATH) conn.execute(""" CREATE TABLE IF NOT EXISTS ecm_batches_lab ( batch_id TEXT PRIMARY KEY, operator_id TEXT, family TEXT, species TEXT, tissue TEXT, source_description TEXT, commercial_product TEXT, processing_steps TEXT, -- JSON string characterization TEXT, -- JSON string created_at TEXT, updated_at TEXT ) """) # Prepare characterization data characterization = { 'ecm_total_protein_mgml': payload.get('ecm_total_protein_mgml'), 'protein_assay_method': payload.get('protein_assay_method'), 'pre_pH': payload.get('pre_pH'), 'pre_conductivity_mS': payload.get('pre_conductivity_mS'), 'uv_A220': payload.get('uv_A220'), 'uv_A280': payload.get('uv_A280'), 'uv_ratio_A220_A280': payload.get('uv_ratio_A220_A280'), 'pre_storage_days_4C': payload.get('pre_storage_days_4C'), 'pre_storage_temp_freezer': payload.get('pre_storage_temp_freezer'), 'pre_storage_duration_months': payload.get('pre_storage_duration_months'), 'pre_storage_fresh_notes': payload.get('pre_storage_fresh_notes'), 'pre_storage_frozen_in': payload.get('pre_storage_frozen_in'), 'pre_storage_thaw_method': payload.get('pre_storage_thaw_method'), 'pre_storage_thaw_duration_min': payload.get('pre_storage_thaw_duration_min'), 'pre_storage_ft_notes': payload.get('pre_storage_ft_notes'), 'notes_pre': payload.get('notes_pre') } # Insert batch record using actual form variables batch_data = { 'batch_id': batch_id, 'operator_id': operator_id, 'family': family, 'species': dec_species if family == 'decECM' else None, 'tissue': dec_tissue if family == 'decECM' else None, 'source_description': f"{family} from {dec_species} {dec_tissue}" if family == 'decECM' and dec_species and dec_tissue else None, 'commercial_product': f"{vendor}: {custom_product or product_name}" if is_commercial else None, 'processing_steps': json.dumps(processing_steps), 'characterization': json.dumps(characterization), 'created_at': datetime.now().isoformat(), 'updated_at': datetime.now().isoformat() } # Debug: Show what we're trying to save st.write("🔍 Debug - Batch data being saved:") st.json(batch_data) conn.execute(""" INSERT OR REPLACE INTO ecm_batches_lab (batch_id, operator_id, family, species, tissue, source_description, commercial_product, processing_steps, characterization, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( batch_data['batch_id'], batch_data['operator_id'], batch_data['family'], batch_data['species'], batch_data['tissue'], batch_data['source_description'], batch_data['commercial_product'], batch_data['processing_steps'], batch_data['characterization'], batch_data['created_at'], batch_data['updated_at'] )) conn.commit() conn.close() st.success(f"✅ **ECM Batch Created and Saved!**") st.success(f"📦 Batch ID: **{batch_id}**") st.info("➡️ Go to **Gelation Experiments** to test this batch on plates") st.info("📚 Go to **Batch Library** to view all your created batches") # Clear form st.session_state.batch_proc_steps = [] st.balloons() except Exception as e: st.error(f"❌ Error saving batch: {e}") import traceback with st.expander("Error Details"): st.code(traceback.format_exc()) # ============================================================================ # MAIN # ============================================================================ def main(): st.set_page_config(page_title="ECM Batch Creation", page_icon="🧬", layout="wide") # Load codebook codebook = { 'family': ["collagen", "decECM", "fibrin", "alginate", "gelMA", "gelatin", "hyaluronan", "PEG_DA", "composite", "other"], 'species': ["human", "porcine", "bovine", "rat", "mouse", "avian", "other"], 'tissues': ["mammary", "dermis", "small_intestine_submucosa", "myocardium", "pericardium", "liver", "lung", "kidney", "bladder", "tendon", "cartilage", "meniscus", "adipose", "placenta", "amniotic_membrane", "esophagus", "cornea", "other"] } show_batch_creation_form(codebook) if __name__ == "__main__": main()
"""
Lab ECM Batch Creation Form
- Document ECM processing (decell, wash, lyoph, reconstitute, etc.)
- Characterize batch (protein, pH, conductivity, UV, etc.)
- Output: batch_id for use in gelation experiments
- No plates, no wells (batch exists independently)
"""
import streamlit as st
import sqlite3
import pandas as pd
from datetime import datetime, date
from pathlib import Path
import json
import os
# Import shared utilities
# Define fallback constants first
COMMON_DILUENTS = ["PBS", "Water", "Tris", "HEPES", "Acetic acid", "Other"]
COMMON_BUFFERS = [
"PBS",
"Tris-HCl",
"HEPES",
"MOPS",
"MES",
"Sodium phosphate",
"Potassium phosphate",
"Other"
]
COMMON_ENZYMES = [
"Trypsin",
"Collagenase",
"Dispase",
"Accutase",
"Proteinase K",
"Papain",
"Elastase",
"Other"
]
DECELL_AGENTS = [
"SDS (Sodium dodecyl sulfate)",
"Triton X-100",
"Tween-20",
"Sodium deoxycholate",
"CHAPS",
"N-lauroylsarcosine sodium salt",
"Peracetic acid",
"Acetic acid",
"Freeze-thaw (physical)",
"Hypotonic/hypertonic",
"Trypsin",
"Collagenase",
"Dispase",
"Accutase",
"Other"
]
DELIPID_SOLVENTS = [
"Isopropanol",
"Ethanol",
"Acetone",
"Chloroform/methanol",
"Petroleum ether",
"Chloroform",
"Methanol",
"Other"
]
COMMON_BASES = ["NaOH", "KOH", "NH4OH", "Other"]
COMMON_ACIDS = ["HCl", "H2SO4", "HNO3", "Other"]
COMMON_SALTS = ["NaCl", "KCl", "CaCl2", "MgCl2", "Other"]
REAGENT_PURPOSES = ["neutralization", "ionic_adjust", "pH_adjust", "other"]
# Try to import from shared_parameters and override fallbacks
try:
from shared_parameters import *
except ImportError:
# Fallback for cloud deployment
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
try:
from shared_parameters import *
except ImportError:
# Keep the fallback constants defined above
pass
# ============================================================================
# DATABASE CONNECTION
# ============================================================================
ROOT = Path(__file__).resolve().parents[1]
DB_PATH = Path(os.getenv("GELPREDICT_DB", str(ROOT / "gelpredict.db"))).resolve()
def get_connection():
con = sqlite3.connect(str(DB_PATH))
con.row_factory = sqlite3.Row
con.execute("PRAGMA foreign_keys=ON;")
con.execute("PRAGMA journal_mode=WAL;")
return con
def _connect():