""" GelPredict Data Entry GUI — Production v2.0 - Views/Triggers/Constraints for data integrity - Reagent-derived effective mM aggregation - Safer edits, better validation, Excel export button - Unit-safe calculations with PBS/DMEM support """ import streamlit as st import sqlite3 import pandas as pd import numpy as np from datetime import datetime, date from pathlib import Path from typing import Any, Dict, List, Optional, Tuple import uuid import re from contextlib import contextmanager from functools import lru_cache import subprocess import itertools import os import shutil import json import io import hashlib import sqlite3 as _sqlite3 # for version check import matplotlib.pyplot as plt from PIL import Image, ExifTags # Configure Streamlit page for wide mode (better for tablets/iPads) st.set_page_config( page_title="GelPredict - Data Entry", page_icon="🧬", layout="wide", # Use full width of screen initial_sidebar_state="expanded" ) # iPad-optimized styling - larger text, bigger buttons, better spacing st.markdown(""" """, unsafe_allow_html=True) # ============================================================================ # DATABASE SETUP # ============================================================================ ROOT = Path(__file__).resolve().parents[1] # Allow DB path override via environment variable (for testing) DB_PATH = Path(os.getenv("GELPREDICT_DB", str(ROOT / "gelpredict.db"))).resolve() # Media storage roots MEDIA_ROOT = ROOT / "media" IMG_ROOT = MEDIA_ROOT / "images" THM_ROOT = MEDIA_ROOT / "thumbs" for p in (MEDIA_ROOT, IMG_ROOT, THM_ROOT): p.mkdir(parents=True, exist_ok=True) def _connect(): con = sqlite3.connect(str(DB_PATH), isolation_level=None) con.row_factory = sqlite3.Row con.execute("PRAGMA journal_mode=WAL;") con.execute("PRAGMA foreign_keys=ON;") con.execute("PRAGMA synchronous=NORMAL;") return con @contextmanager def tx(): con = _connect() try: con.execute("BEGIN IMMEDIATE;") yield con con.execute("COMMIT;") except Exception as e: con.execute("ROLLBACK;") raise e finally: con.close() def get_connection(): return _connect() def new_record_id(): """Generate UUID (legacy/fallback).""" return str(uuid.uuid4()) def generate_batch_id(family: str, species: Optional[str] = None, tissue: Optional[str] = None, date_obj = None, is_commercial: bool = False) -> str: """ Auto-generate human-readable batch_id from ECM metadata. Format (Lab-made): {family_abbrev}-{species_abbrev}{tissue_abbrev}-{YYMMDD} Format (Commercial): Use manufacturer lot# (don't auto-generate) Examples: - decECM human mammary (Oct 12, 2025): dECM-HuMam-251012 - collagen bovine tendon (Oct 12, 2025): COL-BovTen-251012 - fibrin human plasma (Oct 12, 2025): FIB-HuPla-251012 - Matrigel (commercial): 2345678 (from manufacturer) """ if is_commercial: return "" # Commercial batch_id should be entered manually (lot number) parts = [] # Family abbreviation family_map = { "decECM": "dECM", "collagen": "COL", "fibrin": "FIB", "alginate": "ALG", "gelMA": "gMA", "hyaluronan": "HA", "PEG_DA": "PEG", "composite": "COMP", "other": "OTH" } fam_abbrev = family_map.get(family, family[:4].upper() if family else "UNK") parts.append(fam_abbrev) # Species + tissue abbreviation (first 2-3 chars each, capitalized) if species and tissue: # Species: first 2-3 chars, capitalize first sp_clean = species.replace(" ", "").replace("-", "") sp_abbrev = sp_clean[:3].capitalize() if len(sp_clean) >= 3 else sp_clean.capitalize() # Tissue: first 3 chars, capitalize first tis_clean = tissue.replace(" ", "").replace("-", "") tis_abbrev = tis_clean[:3].capitalize() if len(tis_clean) >= 3 else tis_clean.capitalize() parts.append(f"{sp_abbrev}{tis_abbrev}") # Date (YYMMDD) if date_obj: date_str = date_obj.strftime("%y%m%d") else: date_str = datetime.now().strftime("%y%m%d") parts.append(date_str) return "-".join(parts) def generate_gelation_id(batch_id: str, gelation_date = None, sequence: int = 1) -> str: """ Auto-generate gelation_id from batch_id and sequence. Format: {batch_id}-G{MMDD}-{seq} Examples: - dECM-HuMam-251012-G1012-1 (first gelation of Oct 12) - dECM-HuMam-251012-G1012-2 (second gelation of Oct 12) - 2345678-G1012-1 (commercial, first gelation of Oct 12) """ if not batch_id: return f"GEL-{datetime.now().strftime('%y%m%d')}-{sequence:03d}" # Date (MMDD for gelation) if gelation_date: gel_date_str = gelation_date.strftime("%m%d") else: gel_date_str = datetime.now().strftime("%m%d") return f"{batch_id}-G{gel_date_str}-{sequence}" def get_next_gelation_sequence(batch_id: str, gelation_date = None) -> int: """Get next gelation sequence number for a batch on a given date.""" if not batch_id: return 1 gel_date_str = (gelation_date or datetime.now()).strftime("%m%d") pattern = f"{batch_id}-G{gel_date_str}-%" conn = get_connection() try: result = conn.execute( "SELECT gelation_id FROM wells_master_v4 WHERE gelation_id LIKE ? ORDER BY created_at DESC LIMIT 1", (pattern,) ).fetchone() if result and result["gelation_id"]: # Extract sequence number (last part after last -) gel_id = result["gelation_id"] parts = gel_id.split("-") if len(parts) > 0 and parts[-1].isdigit(): return int(parts[-1]) + 1 return 1 except Exception: return 1 finally: conn.close() def generate_plate_id(plate_type: str = "96", sequence: int = None) -> str: """ Auto-generate plate_id for physical plates. Format: P{type}-{YYMM}-{seq} Examples: - P96-2510-001 (first 96-well plate in Oct 2025) - P96-2510-002 (second 96-well plate) - P48-2510-001 (first 48-well plate) Physical plates can be reused across: - Different days (same plate, different experiments) - Different batches (same plate, different ECM sources) - Different gelations (same plate, different protocols) The well position (row, col) distinguishes individual samples. """ # Extract plate type from common patterns if not plate_type: plate_type = "96" elif "-" in str(plate_type): # Extract from existing format like "PLT-001-96" parts = str(plate_type).split("-") for part in parts: if part in ["6", "12", "24", "48", "96", "384"]: plate_type = part break # Month code (YYMM) month_code = datetime.now().strftime("%y%m") # Get next sequence if not provided if sequence is None: sequence = get_next_plate_sequence(plate_type, month_code) return f"P{plate_type}-{month_code}-{sequence:03d}" def get_next_plate_sequence(plate_type: str, month_code: str) -> int: """Get next plate sequence number for a given type and month.""" pattern = f"P{plate_type}-{month_code}-%" conn = get_connection() try: result = conn.execute( "SELECT plate_id FROM wells_master_v4 WHERE plate_id LIKE ? ORDER BY created_at DESC LIMIT 1", (pattern,) ).fetchone() if result and result["plate_id"]: # Extract sequence (last 3 digits) plate_id = result["plate_id"] parts = plate_id.split("-") if len(parts) >= 3 and parts[-1].isdigit(): return int(parts[-1]) + 1 return 1 except Exception: return 1 finally: conn.close() def get_recent_plates(limit: int = 50) -> list: """Get list of recently used plate_ids with usage stats.""" conn = get_connection() try: result = conn.execute(""" SELECT plate_id, COUNT(*) as n_wells, MIN(date) as first_use, MAX(date) as last_use, COUNT(DISTINCT batch_id) as n_batches, COUNT(DISTINCT gelation_id) as n_gelations FROM wells_master_v4 WHERE plate_id IS NOT NULL AND plate_id != '' GROUP BY plate_id ORDER BY MAX(created_at) DESC LIMIT ? """, (limit,)).fetchall() return [dict(row) for row in result] except Exception: return [] finally: conn.close() def generate_semantic_id(family: str, batch_id: str, plate_id: Optional[str] = None, row: Optional[str] = None, col: Optional[int] = None, replicate_id: Optional[int] = None, species: Optional[str] = None, tissue: Optional[str] = None) -> str: """ Generate human-readable record ID from metadata. Format: {family}_{batch_id}_{species-tissue}_{plate_id}_{row}{col}_rep{replicate_id} Examples: - Pure collagen: collagen_B001_human-mammary_PLT-001-96_A1_rep1 - decECM: dececm_B002_porcine-dermis_PLT-002-48_A1_rep1 - No plate: collagen_B001_human-mammary_A1_rep1 - No position: collagen_B001_human-mammary_rep1 """ parts = [] # Clean and add family (remove spaces, lowercase) if family: family_clean = family.replace(" ", "").replace("_", "").lower() parts.append(family_clean) # Add batch (clean) if batch_id: batch_clean = batch_id.replace(" ", "") parts.append(batch_clean) # Add species-tissue for decECM (improves traceability) if family and family.lower() == "dececm" and species and tissue: species_clean = species.replace(" ", "").lower() tissue_clean = tissue.replace(" ", "-").lower() parts.append(f"{species_clean}-{tissue_clean}") # Add plate (optional, clean) if plate_id: plate_clean = plate_id.replace(" ", "") parts.append(plate_clean) # Add position (row+col) if row and col is not None: parts.append(f"{row}{col}") # Add replicate if replicate_id is not None: parts.append(f"rep{replicate_id}") # Join with underscores semantic_id = "_".join(parts) # Fallback to UUID if too short if len(semantic_id) < 5: return new_record_id() return semantic_id def ensure_unique_record_id(proposed_id: str, attempt: int = 0) -> str: """ Ensure record ID is unique. If collision, append suffix. Args: proposed_id: Proposed record ID attempt: Collision counter (0 = first attempt) Returns: Unique record ID """ test_id = proposed_id if attempt == 0 else f"{proposed_id}_v{attempt}" # Check if exists conn = get_connection() try: exists = conn.execute( "SELECT 1 FROM wells_master_v4 WHERE record_id=? LIMIT 1", (test_id,) ).fetchone() if exists: # Collision! Try next version return ensure_unique_record_id(proposed_id, attempt + 1) else: return test_id finally: conn.close() def _parse_manual_well_tokens(text: str, row_labels: str, max_cols: int) -> List[Tuple[str, int]]: """ Parse free-form well tokens into [(row_letter, col_int)]. Supports tokens like 'A2', 'B6', 'A1-A3', 'C4:C6'. - Separators: comma, space, semicolon, newline - Ignores invalid or duplicate entries gracefully """ if not text: return [] # Normalize separators raw = text.replace(";", ",").replace("\n", ",").replace("\t", ",") tokens = [t.strip().upper() for t in raw.split(",") if t.strip()] def _is_valid(row, col): return (row in row_labels) and (isinstance(col, int) and 1 <= col <= int(max_cols)) seen = set() picks = [] for tok in tokens: # Range syntax: A1-A3 or A1:A3 if "-" in tok or ":" in tok: sep = "-" if "-" in tok else ":" try: left, right = tok.split(sep, 1) # both endpoints must look like def split_rc(s): s = s.strip().upper() r = "".join([c for c in s if c.isalpha()]) c = "".join([c for c in s if c.isdigit()]) return r, int(c) r1, c1 = split_rc(left) r2, c2 = split_rc(right) if r1 == r2 and r1 in row_labels: lo, hi = sorted([c1, c2]) for c in range(lo, hi + 1): if _is_valid(r1, c): key = (r1, c) if key not in seen: seen.add(key); picks.append(key) # out-of-scope: row ranges; ignore silently except Exception: # ignore malformed range pass continue # Single well syntax: A2 letters = "".join([c for c in tok if c.isalpha()]) digits = "".join([c for c in tok if c.isdigit()]) if letters and digits: try: r = letters[0] # first letter; ignore extras c = int(digits) if _is_valid(r, c): key = (r, c) if key not in seen: seen.add(key); picks.append(key) except Exception: pass # If token is just a row like "A" or just a number like "5", we skip. # (Keeps the parser predictable and avoids accidental floods.) # Sort in plate order (row order, then col) for reproducibility row_index = {ch: i for i, ch in enumerate(row_labels)} picks.sort(key=lambda rc: (row_index.get(rc[0], 1e9), rc[1])) return picks def sqlite_supports_generated_columns() -> bool: """Check if SQLite version supports GENERATED columns (3.31.0+).""" try: v = _sqlite3.sqlite_version_info # (major, minor, patch) return (v[0], v[1], v[2]) >= (3, 31, 0) except Exception: return False def column_exists(con, table_name, column_name): """Check if a column exists in a table.""" cursor = con.execute(f"PRAGMA table_info({table_name})") columns = [row[1] for row in cursor.fetchall()] return column_name in columns def apply_migrations(): """Run database migrations based on PRAGMA user_version.""" with tx() as con: user_version = con.execute("PRAGMA user_version").fetchone()[0] # v1: plate bounds trigger + useful indexes + audit table/trigger if user_version < 1: # Audit log table con.execute(""" CREATE TABLE IF NOT EXISTS audit_log ( id INTEGER PRIMARY KEY, table_name TEXT, record_id TEXT, action TEXT, actor TEXT, payload TEXT, changed_at TEXT DEFAULT CURRENT_TIMESTAMP ) """) # Audit trigger for wells updates con.execute(""" CREATE TRIGGER IF NOT EXISTS trg_wells_audit_update AFTER UPDATE ON wells_master_v4 FOR EACH ROW BEGIN INSERT INTO audit_log(table_name, record_id, action, actor, payload) VALUES('wells_master_v4', NEW.record_id, 'UPDATE', COALESCE(NEW.operator_id,''), json_object( 'old_updated_at', OLD.updated_at, 'new_updated_at', NEW.updated_at, 'old_gel_binary', OLD.gel_binary, 'new_gel_binary', NEW.gel_binary )); END; """) con.execute("PRAGMA user_version=1") # v2: add UV ratio generated column if supported if user_version < 2: if sqlite_supports_generated_columns(): # Check if column already exists cols = {r[1] for r in con.execute("PRAGMA table_info(wells_master_v4)")} if 'uv_ratio_gen' not in cols: try: con.execute(""" ALTER TABLE wells_master_v4 ADD COLUMN uv_ratio_gen REAL GENERATED ALWAYS AS ( CASE WHEN uv_A280 IS NOT NULL AND uv_A280 > 0 THEN uv_A220 / uv_A280 END ) VIRTUAL """) except Exception: pass # If fails, continue without generated column con.execute("PRAGMA user_version=2") # v3: images table for per-well/per-event uploads + indexes if user_version < 3: con.execute(""" CREATE TABLE IF NOT EXISTS gel_images ( image_id TEXT PRIMARY KEY, record_id TEXT NOT NULL REFERENCES wells_master_v4(record_id) ON DELETE CASCADE, event_id INTEGER REFERENCES events_long(event_id) ON DELETE SET NULL, taken_at TEXT, operator_id TEXT, caption TEXT, kind TEXT, mime_type TEXT, width_px INTEGER, height_px INTEGER, sha256_hex TEXT, file_relpath TEXT NOT NULL, thumb_relpath TEXT, lighting TEXT, magnification TEXT, tilt_deg REAL, qc_flag INTEGER DEFAULT 1, created_at TEXT DEFAULT CURRENT_TIMESTAMP ) """) con.execute("CREATE INDEX IF NOT EXISTS idx_img_record ON gel_images(record_id)") con.execute("CREATE INDEX IF NOT EXISTS idx_img_event ON gel_images(event_id)") con.execute("CREATE INDEX IF NOT EXISTS idx_img_hash ON gel_images(sha256_hex)") con.execute("PRAGMA user_version=3") # v4: decECM provenance (species + tissue) + helper indexes if user_version < 4: if not column_exists(con, "wells_master_v4", "ecm_origin_species"): con.execute("ALTER TABLE wells_master_v4 ADD COLUMN ecm_origin_species TEXT") if not column_exists(con, "wells_master_v4", "ecm_source_tissue"): con.execute("ALTER TABLE wells_master_v4 ADD COLUMN ecm_source_tissue TEXT") con.execute("CREATE INDEX IF NOT EXISTS idx_wells_species ON wells_master_v4(ecm_origin_species)") con.execute("CREATE INDEX IF NOT EXISTS idx_wells_tissue ON wells_master_v4(ecm_source_tissue)") con.execute("PRAGMA user_version=4") # v5: processing protocol (step-by-step ECM preparation tracking) if user_version < 5: con.execute("ALTER TABLE wells_master_v4 ADD COLUMN processing_protocol TEXT") con.execute("PRAGMA user_version=5") # v6: gelation protocol (neutralization, incubation, post-gel handling) if user_version < 6: con.execute("ALTER TABLE wells_master_v4 ADD COLUMN gelation_protocol TEXT") con.execute("PRAGMA user_version=6") # v7: protein assay method tracking if user_version < 7: con.execute("ALTER TABLE wells_master_v4 ADD COLUMN protein_assay_method TEXT") con.execute("PRAGMA user_version=7") # v8: commercial product tracking if user_version < 8: if not column_exists(con, "wells_master_v4", "is_commercial_product"): con.execute("ALTER TABLE wells_master_v4 ADD COLUMN is_commercial_product INTEGER DEFAULT 0") if not column_exists(con, "wells_master_v4", "commercial_vendor"): con.execute("ALTER TABLE wells_master_v4 ADD COLUMN commercial_vendor TEXT") if not column_exists(con, "wells_master_v4", "commercial_product_name"): con.execute("ALTER TABLE wells_master_v4 ADD COLUMN commercial_product_name TEXT") if not column_exists(con, "wells_master_v4", "commercial_catalog_number"): con.execute("ALTER TABLE wells_master_v4 ADD COLUMN commercial_catalog_number TEXT") if not column_exists(con, "wells_master_v4", "commercial_lot_number"): con.execute("ALTER TABLE wells_master_v4 ADD COLUMN commercial_lot_number TEXT") con.execute("CREATE INDEX IF NOT EXISTS idx_wells_commercial ON wells_master_v4(is_commercial_product)") con.execute("CREATE INDEX IF NOT EXISTS idx_wells_vendor ON wells_master_v4(commercial_vendor)") con.execute("PRAGMA user_version=8") # v16: add commercial website field if user_version < 16: if not column_exists(con, "wells_master_v4", "commercial_website"): con.execute("ALTER TABLE wells_master_v4 ADD COLUMN commercial_website TEXT") con.execute("PRAGMA user_version=16") # v9: gelation_id for protocol-level tracking if user_version < 9: con.execute("ALTER TABLE wells_master_v4 ADD COLUMN gelation_id TEXT") con.execute("CREATE INDEX IF NOT EXISTS idx_wells_gelation ON wells_master_v4(gelation_id)") con.execute("PRAGMA user_version=9") # v10: gel_volume_uL for spatial seeding height calculations if user_version < 10: con.execute("ALTER TABLE wells_master_v4 ADD COLUMN gel_volume_uL REAL CHECK(gel_volume_uL > 0)") con.execute("PRAGMA user_version=10") # v11: add degradation and plate adhesion fields if user_version < 11: con.execute("ALTER TABLE wells_master_v4 ADD COLUMN disintegrated INTEGER CHECK(disintegrated IN (0,1))") con.execute("ALTER TABLE wells_master_v4 ADD COLUMN days_to_disintegration INTEGER CHECK(days_to_disintegration >= 0)") con.execute("ALTER TABLE wells_master_v4 ADD COLUMN reliquefied INTEGER CHECK(reliquefied IN (0,1))") con.execute("ALTER TABLE wells_master_v4 ADD COLUMN days_to_reliquefaction INTEGER CHECK(days_to_reliquefaction >= 0)") con.execute("ALTER TABLE wells_master_v4 ADD COLUMN plate_adhesion TEXT CHECK(plate_adhesion IN ('adhered','floating','mixed'))") con.execute("ALTER TABLE wells_master_v4 ADD COLUMN adhesion_notes TEXT") con.execute("PRAGMA user_version=11") # v12: add gelation kinetics and pre-gelation storage fields if user_version < 12: con.execute("ALTER TABLE wells_master_v4 ADD COLUMN time_to_gel_min REAL CHECK(time_to_gel_min >= 0)") con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_gel_storage_temp_C REAL CHECK(pre_gel_storage_temp_C BETWEEN -80 AND 40)") con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_gel_storage_duration_min REAL CHECK(pre_gel_storage_duration_min >= 0)") con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_gel_storage_notes TEXT") con.execute("PRAGMA user_version=12") # v13: Enhanced pre-storage tracking (freezer temp, frozen duration) if user_version < 13: con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_storage_temp_freezer REAL CHECK(pre_storage_temp_freezer BETWEEN -200 AND 0)") con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_storage_duration_months REAL CHECK(pre_storage_duration_months >= 0)") con.execute("PRAGMA user_version=13") # v14: Detailed pre-storage freeze-thaw tracking if user_version < 14: con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_storage_fresh_notes TEXT") con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_storage_frozen_in TEXT") con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_storage_thaw_method TEXT") con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_storage_thaw_duration_min REAL CHECK(pre_storage_thaw_duration_min >= 0)") con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_storage_ft_notes TEXT") con.execute("PRAGMA user_version=14") # v15: Hydrogel blend functionality if user_version < 15: con.execute("ALTER TABLE wells_master_v4 ADD COLUMN hydrogel_blend_components TEXT") con.execute("ALTER TABLE wells_master_v4 ADD COLUMN multiple_hydrogels INTEGER DEFAULT 0 CHECK(multiple_hydrogels IN (0,1))") con.execute("PRAGMA user_version=15") def check_schema_drift(spec): """ Compare FIELD_SPEC against actual SQLite schema. Returns list of drift warnings. """ problems = [] conn = get_connection() try: for table in spec.keys(): try: # Get actual columns from database cols_query = conn.execute(f"PRAGMA table_info({table})").fetchall() db_fields = {row[1] for row in cols_query} spec_fields = set(spec[table].keys()) # Find drift missing_in_db = spec_fields - db_fields extra_in_db = db_fields - spec_fields if missing_in_db: problems.append(f"{table}: Fields in spec but not DB: {sorted(missing_in_db)}") if extra_in_db: # Filter out common system columns extra_filtered = extra_in_db - {'created_at', 'updated_at', 'reagent_id', 'event_id'} if extra_filtered: problems.append(f"{table}: Fields in DB but not spec: {sorted(extra_filtered)}") except Exception as e: # Table might not exist yet continue finally: conn.close() return problems def init_database(): with tx() as con: # Set DB identity tag (enforces "lab_hydrogels" purpose) from db_utils import ensure_db_identity ensure_db_identity(con, "lab_hydrogels") # wells_master_v4 con.execute(""" CREATE TABLE IF NOT EXISTS wells_master_v4 ( record_id TEXT PRIMARY KEY, date TEXT NOT NULL, operator_id TEXT, family TEXT, batch_id TEXT, donor_id TEXT, plate_id TEXT, row TEXT, col INTEGER, replicate_id INTEGER, pre_storage_days_4C INTEGER, pre_storage_freeze_cycles INTEGER, ecm_total_protein_mgml REAL CHECK(ecm_total_protein_mgml >= 0), pre_pH REAL CHECK(pre_pH BETWEEN 0 AND 14), pre_conductivity_mS REAL, temp_incubation_C REAL CHECK(temp_incubation_C BETWEEN 0 AND 60), uv_A220 REAL, uv_A230 REAL, uv_A260 REAL, uv_A280 REAL, uv_ratio_A220_A280 REAL, sds_smear_index REAL CHECK(sds_smear_index BETWEEN 0 AND 1), sds_alpha_ratio REAL, hydroxyproline_mgml REAL, dmmB_GAG_ugml REAL, viscosity_proxy_sec REAL, -- Pre-gel viscosity (Scientific Reports 2019) pre_gel_viscosity_mPas REAL CHECK(pre_gel_viscosity_mPas >= 0), viscosity_pregel_mPas REAL CHECK(viscosity_pregel_mPas >= 0), pre_gel_viscosity_temp_C REAL CHECK(pre_gel_viscosity_temp_C BETWEEN 0 AND 40), shear_rate_s_minus1 REAL CHECK(shear_rate_s_minus1 >= 0), -- Turbidity/gelation kinetics (Scientific Reports 2019, MDPI 2021) turbidity_lag_time_min REAL CHECK(turbidity_lag_time_min >= 0), turbidity_t_half_min REAL CHECK(turbidity_t_half_min >= 0), turbidity_slope_per_min REAL, -- Viscoelastic/rheological properties (Saldin et al. 2016, Brazdaru et al. 2015) storage_modulus_G_prime_Pa REAL CHECK(storage_modulus_G_prime_Pa >= 0), loss_modulus_G_double_prime_Pa REAL CHECK(loss_modulus_G_double_prime_Pa >= 0), tan_delta REAL CHECK(tan_delta >= 0), -- Residual contaminants (cornea ECM study 2019) sds_residual_ppm REAL CHECK(sds_residual_ppm >= 0), residual_SDS REAL CHECK(residual_SDS >= 0), detergent_residual_binary INTEGER CHECK(detergent_residual_binary IN (0,1)), cytotoxicity_score_0to3 INTEGER CHECK(cytotoxicity_score_0to3 BETWEEN 0 AND 3), -- Micro-DSC parameters (optional) dsc_onset_T_C REAL CHECK(dsc_onset_T_C BETWEEN 0 AND 100), dsc_peak_T_C REAL CHECK(dsc_peak_T_C BETWEEN 0 AND 100), dsc_delta_H_J_g REAL CHECK(dsc_delta_H_J_g >= 0), -- Circular Dichroism parameters (optional) cd_molar_ellipticity_222nm_mdeg REAL, cd_helix_percent REAL CHECK(cd_helix_percent BETWEEN 0 AND 100), -- FTIR parameters (optional) ftir_amide3_1450_ratio REAL CHECK(ftir_amide3_1450_ratio >= 0), -- Additional residual contaminants (optional) dna_residual_ng_mg REAL CHECK(dna_residual_ng_mg >= 0), endotoxin_residual_EU_mg REAL CHECK(endotoxin_residual_EU_mg >= 0), protease_residual_U_mg REAL CHECK(protease_residual_U_mg >= 0), -- Swelling ratio parameters (optional) swelling_ratio_Q REAL CHECK(swelling_ratio_Q >= 0), gel_fresh_weight_mg REAL CHECK(gel_fresh_weight_mg >= 0), gel_swollen_weight_mg REAL CHECK(gel_swollen_weight_mg >= 0), gel_dry_weight_mg REAL CHECK(gel_dry_weight_mg >= 0), -- Enzymatic degradation parameters (optional) enzymatic_degradation_t_half_min REAL CHECK(enzymatic_degradation_t_half_min >= 0), collagenase_concentration_U_mL REAL CHECK(collagenase_concentration_U_mL >= 0), -- Diffusion/FRAP parameters (optional) diffusion_coefficient_um2_s REAL CHECK(diffusion_coefficient_um2_s >= 0), frap_t_half_s REAL CHECK(frap_t_half_s >= 0), probe_radius_um REAL CHECK(probe_radius_um >= 0), -- Cell viability/proliferation parameters (optional) cell_viability_percent REAL CHECK(cell_viability_percent BETWEEN 0 AND 100), doubling_time_h REAL CHECK(doubling_time_h >= 0), viability_assay_type TEXT, -- Morphology/branching parameters (optional) branch_points_per_mm2 REAL CHECK(branch_points_per_mm2 >= 0), lumen_formation_binary INTEGER CHECK(lumen_formation_binary IN (0,1)), morphology_assay_type TEXT, -- Gel contraction parameters (optional) contraction_percent REAL CHECK(contraction_percent BETWEEN 0 AND 100), contraction_time_h REAL CHECK(contraction_time_h >= 0), initial_gel_area_mm2 REAL CHECK(initial_gel_area_mm2 >= 0), final_gel_area_mm2 REAL CHECK(final_gel_area_mm2 >= 0), -- Migration parameters (optional) migration_speed_um_h REAL CHECK(migration_speed_um_h >= 0), persistence_ratio REAL CHECK(persistence_ratio >= 0), migration_assay_type TEXT, -- Marker expression parameters (optional) alpha_sma_percent REAL CHECK(alpha_sma_percent BETWEEN 0 AND 100), col1a1_percent REAL CHECK(col1a1_percent BETWEEN 0 AND 100), muc1_percent REAL CHECK(muc1_percent BETWEEN 0 AND 100), ck18_percent REAL CHECK(ck18_percent BETWEEN 0 AND 100), marker_assay_type TEXT, markers_json TEXT, probe_type TEXT, target_pH REAL CHECK(target_pH BETWEEN 0 AND 14), -- Kinetics od_wavelength_nm INTEGER, od_sampling_interval_min INTEGER, time_to_halfmax_min REAL, slope_OD_per_min REAL, final_OD REAL, lag_time_min REAL, -- Outcomes gel_binary INTEGER CHECK(gel_binary IN (0,1)), gel_strength_score_0to3 INTEGER CHECK(gel_strength_score_0to3 BETWEEN 0 AND 3), tilt_test_angle_deg REAL, time_to_handle_min REAL, -- Failure/QC failure_mode TEXT, suspected_cause TEXT, confidence_0to1 REAL, syneresis_binary INTEGER, syneresis_time_min REAL, precipitate_binary INTEGER, color_shift TEXT, notes_pre TEXT, notes_post TEXT, -- App preds (optional) app_recipe_recommended TEXT, app_pgel_pred REAL, app_thalf_pred_min REAL, app_uncertainty REAL, counterfactual_recipe TEXT, counterfactual_expected_pgel REAL, split TEXT, created_at TEXT DEFAULT CURRENT_TIMESTAMP, updated_at TEXT DEFAULT CURRENT_TIMESTAMP ) """) # reagents_per_well (normalized "stock + volume") con.execute(""" CREATE TABLE IF NOT EXISTS reagents_per_well ( reagent_id INTEGER PRIMARY KEY AUTOINCREMENT, record_id TEXT NOT NULL REFERENCES wells_master_v4(record_id) ON DELETE CASCADE, reagent_name TEXT NOT NULL, reagent_class TEXT, purpose TEXT, stock_conc_value REAL, stock_conc_units TEXT, -- M|mM|µM|%|x|mg/mL|U/mL volume_uL_per_mL REAL, effective_conc_mM REAL, lot_number TEXT, added_order INTEGER, notes TEXT, created_at TEXT DEFAULT CURRENT_TIMESTAMP ) """) # events_long (longitudinal observations) con.execute(""" CREATE TABLE IF NOT EXISTS events_long ( event_id INTEGER PRIMARY KEY AUTOINCREMENT, record_id TEXT NOT NULL REFERENCES wells_master_v4(record_id) ON DELETE CASCADE, event_type TEXT NOT NULL, time_from_mix_hours REAL, time_point_min REAL, day_from_mix INTEGER, timestamp TEXT, status_code TEXT, measurement_type TEXT, measurement_value REAL, measurement_units TEXT, gel_strength_score_0to3 REAL, tilt_test_angle_deg REAL, observation TEXT, operator_id TEXT, notes_event TEXT, created_at TEXT DEFAULT CURRENT_TIMESTAMP ) """) # plates_registry (stores per-plate geometry & notes) con.execute(""" CREATE TABLE IF NOT EXISTS plates_registry ( plate_id TEXT PRIMARY KEY, row_labels TEXT NOT NULL, -- e.g., 'ABCDEFGH' max_cols INTEGER NOT NULL, -- e.g., 12 description TEXT, created_at TEXT DEFAULT CURRENT_TIMESTAMP, updated_at TEXT DEFAULT CURRENT_TIMESTAMP ) """) # Helpful indices (performance-optimized) con.execute("CREATE INDEX IF NOT EXISTS idx_wells_batch ON wells_master_v4(batch_id)") con.execute("CREATE INDEX IF NOT EXISTS idx_wells_family ON wells_master_v4(family)") con.execute("CREATE INDEX IF NOT EXISTS idx_wells_created ON wells_master_v4(created_at)") con.execute("CREATE INDEX IF NOT EXISTS idx_wells_batch_gel ON wells_master_v4(batch_id, gel_binary)") con.execute("CREATE INDEX IF NOT EXISTS idx_wells_date ON wells_master_v4(date)") con.execute("CREATE INDEX IF NOT EXISTS idx_wells_plate_pos ON wells_master_v4(plate_id, row, col)") con.execute("CREATE INDEX IF NOT EXISTS idx_rg_record ON reagents_per_well(record_id)") con.execute("CREATE INDEX IF NOT EXISTS idx_ev_record ON events_long(record_id)") con.execute("CREATE INDEX IF NOT EXISTS idx_plates_updated ON plates_registry(updated_at)") def ensure_triggers(): with tx() as con: # Auto-update timestamps con.execute(""" CREATE TRIGGER IF NOT EXISTS trg_wells_touch_updated AFTER UPDATE ON wells_master_v4 FOR EACH ROW BEGIN UPDATE wells_master_v4 SET updated_at = datetime('now') WHERE record_id = NEW.record_id; END; """) con.execute(""" CREATE TRIGGER IF NOT EXISTS trg_plates_touch_updated AFTER UPDATE ON plates_registry FOR EACH ROW BEGIN UPDATE plates_registry SET updated_at = datetime('now') WHERE plate_id = NEW.plate_id; END; """) # Enforce plate geometry bounds at DB level con.execute(""" CREATE TRIGGER IF NOT EXISTS trg_wells_plate_bounds BEFORE INSERT ON wells_master_v4 FOR EACH ROW WHEN NEW.plate_id IS NOT NULL BEGIN -- Validate row is in plate's row_labels SELECT CASE WHEN (NEW.row IS NOT NULL) AND ( INSTR((SELECT row_labels FROM plates_registry WHERE plate_id = NEW.plate_id), NEW.row) = 0 ) THEN RAISE(ABORT, 'Row not valid for this plate') END; -- Validate column is within bounds SELECT CASE WHEN (NEW.col IS NOT NULL) AND ( NEW.col < 1 OR NEW.col > (SELECT max_cols FROM plates_registry WHERE plate_id = NEW.plate_id) ) THEN RAISE(ABORT, 'Column out of bounds for this plate') END; END; """) # Canonicalize row to uppercase and validate replicate_id con.execute(""" CREATE TRIGGER IF NOT EXISTS trg_wells_canonicalize BEFORE INSERT ON wells_master_v4 FOR EACH ROW BEGIN -- Ensure replicate_id >= 1 SELECT CASE WHEN NEW.replicate_id IS NOT NULL AND CAST(NEW.replicate_id AS INTEGER) < 1 THEN RAISE(ABORT, 'replicate_id must be >= 1') END; END; """) def ensure_views(): """Create enhanced views with fallback for UV ratio and rich derived features.""" with tx() as con: # Basic ionic aggregation (backwards compatible) con.execute(""" CREATE VIEW IF NOT EXISTS v_wells_effective AS WITH eff AS ( SELECT record_id, SUM(CASE WHEN LOWER(reagent_name)='naoh' THEN COALESCE(effective_conc_mM,0) ELSE 0 END) AS eff_NaOH_mM, SUM(CASE WHEN LOWER(reagent_name)='hcl' THEN COALESCE(effective_conc_mM,0) ELSE 0 END) AS eff_HCl_mM, SUM(CASE WHEN LOWER(reagent_name)='nacl' THEN COALESCE(effective_conc_mM,0) ELSE 0 END) AS eff_NaCl_mM, SUM(CASE WHEN LOWER(reagent_name)='cacl2' THEN COALESCE(effective_conc_mM,0) ELSE 0 END) AS eff_CaCl2_mM FROM reagents_per_well GROUP BY record_id ) SELECT w.*, e.eff_NaOH_mM, e.eff_HCl_mM, e.eff_NaCl_mM, e.eff_CaCl2_mM FROM wells_master_v4 w LEFT JOIN eff e USING(record_id); """) # Drop and recreate v_wells_features to account for UV ratio fallback con.execute("DROP VIEW IF EXISTS v_wells_features") # Check if uv_ratio_gen exists (from generated column migration) cols = {r[1] for r in con.execute("PRAGMA table_info(wells_master_v4)")} uv_ratio_expr = "uv_ratio_gen" if "uv_ratio_gen" in cols else """ CASE WHEN uv_A280 IS NOT NULL AND uv_A280 > 0 THEN uv_A220 / uv_A280 END """ con.execute(f""" CREATE VIEW v_wells_features AS WITH media AS ( SELECT record_id, SUM(CASE WHEN LOWER(reagent_class)='media' OR LOWER(reagent_name) LIKE '%dmem%' THEN COALESCE(volume_uL_per_mL,0)/10.0 ELSE 0 END) AS media_percent FROM reagents_per_well GROUP BY record_id ), pbs AS ( SELECT record_id, MAX(1 + (COALESCE(stock_conc_value,1)-1.0)*COALESCE(volume_uL_per_mL,0)/1000.0) AS pbs_final_x FROM reagents_per_well WHERE LOWER(reagent_name) LIKE '%pbs%' AND stock_conc_units='x' GROUP BY record_id ), eff AS ( SELECT record_id, SUM(CASE WHEN LOWER(reagent_name)='naoh' THEN COALESCE(effective_conc_mM,0) ELSE 0 END) AS eff_NaOH_mM, SUM(CASE WHEN LOWER(reagent_name)='hcl' THEN COALESCE(effective_conc_mM,0) ELSE 0 END) AS eff_HCl_mM, SUM(CASE WHEN LOWER(reagent_name)='nacl' THEN COALESCE(effective_conc_mM,0) ELSE 0 END) AS eff_NaCl_mM, SUM(CASE WHEN LOWER(reagent_name)='cacl2' THEN COALESCE(effective_conc_mM,0) ELSE 0 END) AS eff_CaCl2_mM FROM reagents_per_well GROUP BY record_id ) SELECT w.*, {uv_ratio_expr} AS uv_ratio_effective, e.eff_NaOH_mM, e.eff_HCl_mM, e.eff_NaCl_mM, e.eff_CaCl2_mM, m.media_percent, p.pbs_final_x FROM wells_master_v4 w LEFT JOIN eff e USING(record_id) LEFT JOIN media m USING(record_id) LEFT JOIN pbs p USING(record_id); """) # ============================================================================ # PLATE GEOMETRY REGISTRY # ============================================================================ DEFAULT_PLATES = { "96": dict(row_labels="ABCDEFGH", max_cols=12, description="96-well (8x12)"), "48": dict(row_labels="ABCDEF", max_cols=8, description="48-well (6x8)"), "24": dict(row_labels="ABCD", max_cols=6, description="24-well (4x6)"), } @lru_cache(maxsize=256) def _get_plate_geom_cached(plate_id: str): """Cached geometry lookup for performance.""" conn = get_connection() try: df = pd.read_sql_query( "SELECT row_labels, max_cols FROM plates_registry WHERE plate_id=?", conn, params=(plate_id,)) if df.empty: return None return (str(df.iloc[0]["row_labels"]), int(df.iloc[0]["max_cols"])) finally: conn.close() def get_plate_geometry(plate_id: str) -> Optional[Tuple[str, int]]: """Return (row_labels, max_cols) for a plate_id if registered, else None.""" if not plate_id: return None return _get_plate_geom_cached(plate_id) def upsert_plate_geometry(plate_id: str, row_labels: str, max_cols: int, description: Optional[str] = None): """Insert or update a plate geometry with validation.""" if not plate_id or not row_labels or not max_cols: raise ValueError("plate_id, row_labels, and max_cols are required.") # Clean and validate row labels rows_clean = "".join(ch for ch in row_labels.strip().upper() if ch.isalpha()) if not rows_clean: raise ValueError("row_labels must contain letters (e.g., 'ABCDEFGH').") if len(set(rows_clean)) != len(rows_clean): raise ValueError("row_labels contains duplicate letters.") if max_cols < 1: raise ValueError("max_cols must be ≥ 1.") with tx() as con: con.execute(""" INSERT INTO plates_registry (plate_id, row_labels, max_cols, description) VALUES (?, ?, ?, ?) ON CONFLICT(plate_id) DO UPDATE SET row_labels=excluded.row_labels, max_cols=excluded.max_cols, description=COALESCE(excluded.description, plates_registry.description), updated_at=datetime('now') """, (plate_id, rows_clean, int(max_cols), description)) # Invalidate cache after update try: _get_plate_geom_cached.cache_clear() except Exception: pass def ensure_default_plate_if_unset(plate_id: str): """ If plate_id includes a recognizable size token ('96','48','24') and the plate isn't registered, register a sensible default. Uses regex to match standalone numbers (not S96BLOT, but PLT-96-001). """ if not plate_id: return if get_plate_geometry(plate_id): return # Match standalone 96, 48, or 24 (with word boundaries) m = re.search(r'(? max_val): return False, f"{field_name} must be between {min_val} and {max_val}" return True, "" def _norm_lower(val): """Normalize string to lowercase, or None.""" return None if val is None else str(val).strip().lower() def sanitize_and_enrich_well_payload(data, reagents_list): # UV ratio compute try: a220, a280 = data.get('uv_A220'), data.get('uv_A280') if a220 is not None and a280 and a280 > 0 and not data.get('uv_ratio_A220_A280'): data['uv_ratio_A220_A280'] = float(a220) / float(a280) except Exception: pass # Normalize species/tissue (common aliases) sp = _norm_lower(data.get('ecm_origin_species')) ti = _norm_lower(data.get('ecm_source_tissue')) # Common species aliases map_species = {"pig": "porcine", "cow": "bovine"} if sp in map_species: data['ecm_origin_species'] = map_species[sp] # Normalize tissue (spaces → underscores) if ti and " " in ti: data['ecm_source_tissue'] = ti.replace(" ", "_") # Normalize blanks for k, v in list(data.items()): if v == "" or (isinstance(v, str) and v.strip() == ""): data[k] = None # Compute effective mM for reagents if convertible for r in (reagents_list or []): if r.get('effective_conc_mM') is None: r['effective_conc_mM'] = effective_mM(r.get('stock_conc_value'), r.get('stock_conc_units'), r.get('volume_uL_per_mL')) return data, reagents_list or [] # ============================================================================ # FIELD SPECIFICATION (SCHEMA-DRIVEN UI) # ============================================================================ # Central source of truth for field metadata: # - Labels, help text, units, ranges # - Required flags, widget types # - Options for selects # Drives: UI rendering, validation, data dictionary export FIELD_SPEC = { "wells_master_v4": { "record_id": {"widget":"text", "required":True, "help":"UUID; auto-generated or custom"}, "date": {"widget":"date", "required":True, "help":"Experiment date"}, "operator_id":{"widget":"text", "required":True, "help":"Initials or user ID"}, "family": {"widget":"select", "required":True, "options":"codebook.family", "help":"ECM family (collagen vs decECM vs others)"}, "is_commercial_product": {"widget":"checkbox", "required":False, "help":"Check if this is a commercial/ready-made product (e.g., Matrigel, PureCol)"}, "commercial_vendor": {"widget":"text", "required":False, "help":"Company/Vendor name (e.g., Corning, Advanced BioMatrix, R&D Systems)"}, "commercial_product_name": {"widget":"text", "required":False, "help":"Product name (e.g., Matrigel, Cultrex, PureCol, Geltrex)"}, "commercial_catalog_number": {"widget":"text", "required":False, "help":"Catalog/Part number"}, "commercial_lot_number": {"widget":"text", "required":False, "help":"Lot/Batch number from manufacturer"}, "commercial_website": {"widget":"text", "required":False, "help":"Company website URL (e.g., https://www.corning.com)"}, "batch_id": {"widget":"text", "required":True, "help":"ECM batch identifier (for commercial: use lot#; for lab-made: internal batch ID)"}, "gelation_id": {"widget":"text", "required":False, "help":"Unique gelation experiment ID (e.g., GEL-2025-001). Multiple gels can use same batch_id but different gelation_id for protocol variations"}, "gel_volume_uL": {"widget":"number", "required":False, "range":(1.0, 5000.0), "help":"Total volume of hydrogel per well (μL). Used for spatial seeding height calculations in cell culture experiments"}, "donor_id": {"widget":"text", "required":False, "help":"Optional donor identifier (typically N/A for commercial products)"}, "ecm_origin_species": {"widget":"select","options":"codebook.species","help":"Source species (required for decECM)"}, "ecm_source_tissue": {"widget":"select","options":"codebook.tissues","help":"Source tissue/organ (required for decECM)"}, "plate_id": {"widget":"text", "required":False, "help":"E.g. PLT-001-96 for auto-detection"}, "row": {"widget":"select", "required":False, "options":"__rows_from_plate__", "help":"Row letter"}, "col": {"widget":"number", "required":False, "fmt":"int", "range":(1, 48), "help":"Column index (optional)"}, "replicate_id":{"widget":"number", "required":False, "fmt":"int", "range":(1, 999), "help":"Replicate tag (optional, defaults to 1)"}, "pre_storage_days_4C": {"widget":"number","fmt":"int","range":(0, 3650),"help":"Days at 4°C before processing"}, "pre_storage_fresh_notes": {"widget":"text","required":False,"help":"How was fresh tissue stored?"}, "pre_storage_freeze_cycles": {"widget":"number","fmt":"int","range":(0, 1000),"help":"Freeze-thaw cycles before decell"}, "pre_storage_temp_freezer": {"widget":"number","fmt":"float","range":(-200.0, 0.0),"help":"Freezer temp (°C) if frozen"}, "pre_storage_duration_months":{"widget":"number","fmt":"float","range":(0.0, 120.0),"help":"Months stored frozen"}, "pre_storage_frozen_in": {"widget":"text","required":False,"help":"What medium was tissue frozen in?"}, "pre_storage_thaw_method": {"widget":"select","required":False,"options":["passive_room_temp","37C_water_bath","4C_fridge","buffer_wash_series","PBS_series","gradual_temp_ramp","other"],"help":"How was tissue thawed?"}, "pre_storage_thaw_duration_min": {"widget":"number","fmt":"float","range":(0.0, 1000.0),"help":"Duration of each thaw phase (minutes)"}, "pre_storage_ft_notes": {"widget":"text","required":False,"help":"Notes about freeze-thaw process"}, # Hydrogel blend fields "hydrogel_blend_components": {"widget":"text","required":False,"help":"JSON string of hydrogel blend components"}, "multiple_hydrogels": {"widget":"checkbox","required":False,"help":"Whether multiple hydrogels are used"}, "processing_protocol": {"widget":"text","required":False,"help":"JSON-encoded ECM preparation steps (decell, wash, delipid, enzyme, etc.)"}, "gelation_protocol": {"widget":"text","required":False,"help":"JSON-encoded gelation steps (dilute, add reagents, incubate, post-gel handling)"}, "ecm_total_protein_mgml": { "widget":"number","unit":"mg/mL","range":(0.0,100.0),"required":False, "help":"Total protein concentration (optional - can measure later)", "device":"Spectrophotometer (BCA or Bradford assay)", "method":"1. Dilute sample 1:10 in PBS\n2. Mix with BCA reagent (1:20)\n3. Incubate 30 min at 37°C\n4. Read at 562 nm\n5. Compare to BSA standard curve" }, "protein_assay_method": {"widget":"select","options":["","BCA","Bradford","Lowry","DC_assay","A280","Biuret","other"],"help":"Method used to measure protein concentration"}, "pre_pH": { "widget":"number","range":(0.0,14.0),"required":False, "help":"Pre-neutralization pH (optional - can measure later)", "device":"pH meter (calibrated with pH 4, 7, 10 buffers)", "method":"1. Calibrate meter with 3-point standards\n2. Rinse electrode with DI water\n3. Immerse in sample (≥2 mL)\n4. Wait for stable reading (~30 sec)\n5. Record pH to 0.01 precision" }, "pre_conductivity_mS": { "widget":"number","unit":"mS/cm","range":(0.0,100.0),"required":False, "help":"Pre-conductivity (optional - can measure later)", "device":"Conductivity meter (calibrated with KCl standard)", "method":"1. Calibrate with 1.413 mS/cm KCl standard\n2. Rinse probe with DI water\n3. Immerse in sample\n4. Wait for stable reading\n5. Record in mS/cm" }, "temp_incubation_C": { "widget":"number","unit":"°C","range":(0.0,60.0),"required":False, "help":"Incubation temperature", "device":"Calibrated incubator with temperature probe", "method":"Typical: 37°C (physiological) or 25°C (room temp)" }, "uv_A220": { "widget":"number","range":(0.0,1e6), "help":"Absorbance at 220 nm", "device":"UV-Vis spectrophotometer (NanoDrop or plate reader)", "method":"1. Blank with PBS or digest buffer\n2. Load 2 µL sample (NanoDrop) or 200 µL (plate)\n3. Measure at 220 nm\n4. Record absorbance units" }, "uv_A230": {"widget":"number","range":(0.0,1e6),"help":"Absorbance at 230 nm","device":"UV-Vis spectrophotometer"}, "uv_A260": {"widget":"number","range":(0.0,1e6),"help":"Absorbance at 260 nm (DNA/RNA)","device":"UV-Vis spectrophotometer"}, "uv_A280": { "widget":"number","range":(0.0,1e6), "help":"Absorbance at 280 nm (protein)", "device":"UV-Vis spectrophotometer (NanoDrop or plate reader)", "method":"Measure at 280 nm (aromatic amino acids)" }, "uv_ratio_A220_A280":{"widget":"number","range":(0.0,50.0),"help":"Auto-computed if A220 & A280 provided"}, "sds_smear_index": {"widget":"number","range":(0.0,1.0),"help":"SDS-PAGE smear index (0–1)"}, "sds_alpha_ratio": {"widget":"number","range":(0.0,5.0),"help":"α-band ratio"}, "hydroxyproline_mgml": {"widget":"number","range":(0.0,50.0),"unit":"mg/mL","required":False,"help":"Hydroxyproline content (optional)"}, "dmmB_GAG_ugml": {"widget":"number","range":(0.0,1e6),"unit":"µg/mL","required":False,"help":"GAG content (DMMB assay) (optional)"}, "viscosity_proxy_sec": {"widget":"number","range":(0.0,1e6),"unit":"sec","required":False,"help":"Viscosity proxy measurement (optional)"}, # Pre-gel viscosity (Scientific Reports 2019) "pre_gel_viscosity_mPas": { "widget":"number","range":(0.0,1e6),"unit":"mPa·s","required":False, "help":"Pre-gel shear viscosity at ~15°C (Scientific Reports 2019) (optional)", "device":"Rotational rheometer (cone-and-plate, 1° cone) or Brookfield viscometer", "method":"1. Load cold ECM solution (≈4°C)\n2. Measure viscosity vs shear rate (0.1–100 s⁻¹)\n3. Result: Shear-thinning curve\n4. Higher low-shear viscosity → longer polymers → faster gelation\n5. Reference: Badylak group, Sci Rep 2019, TA Instruments AR2000" }, "viscosity_pregel_mPas": { "widget":"number","range":(0.0,1e6),"unit":"mPa·s","required":False, "help":"Pre-gel viscosity (workflow naming) (optional)", "device":"Viscometer", "method":"Pre-gel QC stage measurement" }, "pre_gel_viscosity_temp_C": { "widget":"number","range":(0.0,40.0),"unit":"°C","required":False, "help":"Temperature during viscosity measurement (optional)", "device":"Temperature-controlled rheometer", "method":"Measure at cold temperature (≈4°C) before warming" }, "shear_rate_s_minus1": { "widget":"number","range":(0.0,1000.0),"unit":"s⁻¹","required":False, "help":"Shear rate during viscosity measurement (optional)", "device":"Rheometer", "method":"Typical range: 0.1–100 s⁻¹ for shear-thinning characterization" }, # Turbidity/gelation kinetics (Scientific Reports 2019, MDPI 2021) "turbidity_lag_time_min": { "widget":"number","range":(0.0,1000.0),"unit":"min","required":False, "help":"Turbidity lag time T_lag (Scientific Reports 2019) (optional)", "device":"96-well plate reader at 405–450 nm, 37°C incubation", "method":"1. 100 µL per well\n2. Record OD every 30 s for 1–2 h\n3. T_lag: time to 10% of max OD\n4. Shorter T_lag → faster fibril formation\n5. Reference: Polymers 2021 13(18):3113" }, "turbidity_t_half_min": { "widget":"number","range":(0.0,1000.0),"unit":"min","required":False, "help":"Time to half-max turbidity T_1/2 (MDPI 2021) (optional)", "device":"96-well plate reader at 405–450 nm, 37°C incubation", "method":"T_1/2: time to half-max OD from turbidity curve" }, "turbidity_slope_per_min": { "widget":"number","range":(-1000.0,1000.0),"unit":"/min","required":False, "help":"Turbidity slope S (MDPI 2021) (optional)", "device":"96-well plate reader at 405–450 nm, 37°C incubation", "method":"Slope: ΔOD/Δt at inflection point of turbidity curve" }, # Viscoelastic/rheological properties (Saldin et al. 2016, Brazdaru et al. 2015) "storage_modulus_G_prime_Pa": {"widget":"number","range":(0.0,1e6),"unit":"Pa","required":False,"help":"Storage modulus G′ (Saldin et al. 2016) (optional)"}, "loss_modulus_G_double_prime_Pa": {"widget":"number","range":(0.0,1e6),"unit":"Pa","required":False,"help":"Loss modulus G″ (Brazdaru et al. 2015) (optional)"}, "tan_delta": {"widget":"number","range":(0.0,10.0),"required":False,"help":"Tan δ = G″/G′ (viscoelastic ratio) (optional)"}, # Residual contaminants (cornea ECM study 2019) "sds_residual_ppm": {"widget":"number","range":(0.0,1000.0),"unit":"ppm","required":False,"help":"SDS residual concentration (cornea ECM study 2019) (optional)"}, "residual_SDS": {"widget":"number","range":(0.0,1000.0),"unit":"ppm","required":False,"help":"SDS residual (workflow naming) (optional)"}, "detergent_residual_binary": {"widget":"select","options":[0,1],"required":False,"help":"Detergent residual detected (0=no, 1=yes) (optional)"}, "cytotoxicity_score_0to3": {"widget":"select","options":[0,1,2,3],"required":False,"help":"Cytotoxicity score 0-3 (cornea ECM study 2019) (optional)"}, # Micro-DSC parameters (optional) "dsc_onset_T_C": {"widget":"number","range":(0.0,100.0),"unit":"°C","required":False,"help":"DSC onset temperature (collagen denaturation) (optional)"}, "dsc_peak_T_C": {"widget":"number","range":(0.0,100.0),"unit":"°C","required":False,"help":"DSC peak temperature (optional)"}, "dsc_delta_H_J_g": {"widget":"number","range":(0.0,1000.0),"unit":"J/g","required":False,"help":"DSC gelation enthalpy (optional)"}, # Circular Dichroism parameters (optional) "cd_molar_ellipticity_222nm_mdeg": {"widget":"number","range":(-10000.0,10000.0),"unit":"mdeg","required":False,"help":"CD molar ellipticity at 222 nm (Shoulders & Raines 2009) (optional)"}, "cd_helix_percent": {"widget":"number","range":(0.0,100.0),"unit":"%","required":False,"help":"Triple-helix content percentage (optional)"}, # FTIR parameters (optional) "ftir_amide3_1450_ratio": {"widget":"number","range":(0.0,10.0),"required":False,"help":"FTIR Amide III/1450 ratio (optional)"}, # Additional residual contaminants (optional) "dna_residual_ng_mg": {"widget":"number","range":(0.0,1000.0),"unit":"ng/mg","required":False,"help":"DNA residual (PicoGreen fluorometry) (optional)"}, "endotoxin_residual_EU_mg": {"widget":"number","range":(0.0,100.0),"unit":"EU/mg","required":False,"help":"Endotoxin residual (LAL assay) (optional)"}, "protease_residual_U_mg": {"widget":"number","range":(0.0,1000.0),"unit":"U/mg","required":False,"help":"Protease residual (Azocasein/BAPNA assay) (optional)"}, # Swelling ratio parameters (optional) "swelling_ratio_Q": { "widget":"number","range":(0.0,100.0),"required":False, "help":"Swelling ratio Q = (Wsw – Wd)/Wd (optional)", "device":"Analytical balance", "method":"1. Weigh gel fresh (Ws)\n2. Soak in PBS 24 h\n3. Blot & re-weigh (Wsw)\n4. Dry & weigh (Wd)\n5. Formula: Q = (Wsw – Wd)/Wd\n6. Higher Q → looser mesh → faster nutrient diffusion" }, "gel_fresh_weight_mg": {"widget":"number","range":(0.0,10000.0),"unit":"mg","required":False,"help":"Fresh gel weight (optional)"}, "gel_swollen_weight_mg": {"widget":"number","range":(0.0,10000.0),"unit":"mg","required":False,"help":"Swollen weight after 24h PBS (optional)"}, "gel_dry_weight_mg": {"widget":"number","range":(0.0,10000.0),"unit":"mg","required":False,"help":"Dry weight after drying (optional)"}, # Enzymatic degradation parameters (optional) "enzymatic_degradation_t_half_min": { "widget":"number","range":(0.0,10000.0),"unit":"min","required":False, "help":"Enzymatic degradation half-time (optional)", "device":"Incubator + mass/OD measurement", "method":"1. Incubate 100 µL gel with collagenase (0.1–1 U/mL) at 37°C\n2. Record mass/OD loss vs time\n3. Output: t₁/₂ (min)\n4. Reference: Wiseman et al., Biomaterials 2004 25:5013–21" }, "collagenase_concentration_U_mL": {"widget":"number","range":(0.0,10.0),"unit":"U/mL","required":False,"help":"Collagenase concentration used (optional)"}, # Diffusion/FRAP parameters (optional) "diffusion_coefficient_um2_s": { "widget":"number","range":(0.0,1000.0),"unit":"µm²/s","required":False, "help":"Diffusion coefficient D (optional)", "device":"Confocal microscope + FRAP setup", "method":"1. Embed 70 kDa FITC-dextran\n2. Bleach small ROI\n3. Monitor fluorescence recovery\n4. Output: D (µm²/s) = 0.224 r²/t₁/₂\n5. Reference: Sprague & McNally, Biophys J 2005 89:1891–1907" }, "frap_t_half_s": {"widget":"number","range":(0.0,10000.0),"unit":"s","required":False,"help":"FRAP half-time (optional)"}, "probe_radius_um": {"widget":"number","range":(0.0,100.0),"unit":"µm","required":False,"help":"Probe radius for FRAP calculation (optional)"}, # Cell viability/proliferation parameters (optional) "cell_viability_percent": { "widget":"number","range":(0.0,100.0),"unit":"%","required":False, "help":"Cell viability percentage (optional)", "device":"Fluorescence microscope or plate reader", "method":"1. Live/Dead: calcein AM + EthD-1\n2. AlamarBlue: metabolic activity\n3. PrestoBlue: resazurin reduction\n4. Count viable vs total cells\n5. Calculate % viable" }, "doubling_time_h": { "widget":"number","range":(0.0,1000.0),"unit":"h","required":False, "help":"Cell doubling time (optional)", "device":"Incubator + cell counting", "method":"1. Count cells at multiple time points\n2. Plot log(cell number) vs time\n3. Calculate doubling time from slope\n4. Formula: t_d = ln(2)/growth_rate" }, "viability_assay_type": {"widget":"select","options":["Live/Dead","AlamarBlue","PrestoBlue","MTT","WST-1","other"],"required":False,"help":"Viability assay method used (optional)"}, # Morphology/branching parameters (optional) "branch_points_per_mm2": { "widget":"number","range":(0.0,10000.0),"unit":"/mm²","required":False, "help":"Branch points per mm² (optional)", "device":"Confocal or brightfield microscope", "method":"1. Image cells in 3D\n2. Use ImageJ AnalyzeSkeleton plugin\n3. Quantify branch points\n4. Normalize by area\n5. Higher branching → better network formation" }, "lumen_formation_binary": {"widget":"select","options":[0,1],"required":False,"help":"Lumen formation detected (0=no, 1=yes) (optional)"}, "morphology_assay_type": {"widget":"select","options":["confocal","brightfield","phase_contrast","fluorescence","other"],"required":False,"help":"Imaging method used (optional)"}, # Gel contraction parameters (optional) "contraction_percent": { "widget":"number","range":(0.0,100.0),"unit":"%","required":False, "help":"Gel contraction percentage (optional)", "device":"Camera + image analysis", "method":"1. Photograph gel disk at 0h & 24-72h\n2. Measure area change\n3. Formula: contraction % = (A₀ – At)/A₀ × 100\n4. Higher contraction → more myofibroblast activity or weaker matrix" }, "contraction_time_h": {"widget":"number","range":(0.0,168.0),"unit":"h","required":False,"help":"Time point for contraction measurement (optional)"}, "initial_gel_area_mm2": {"widget":"number","range":(0.0,10000.0),"unit":"mm²","required":False,"help":"Initial gel area (optional)"}, "final_gel_area_mm2": {"widget":"number","range":(0.0,10000.0),"unit":"mm²","required":False,"help":"Final gel area (optional)"}, # Migration parameters (optional) "migration_speed_um_h": { "widget":"number","range":(0.0,1000.0),"unit":"µm/h","required":False, "help":"Cell migration speed (optional)", "device":"Time-lapse microscopy", "method":"1. Track nuclei with TrackMate (ImageJ)\n2. Calculate displacement over time\n3. Speed = distance/time\n4. Higher speed → better migration" }, "persistence_ratio": { "widget":"number","range":(0.0,1.0),"required":False, "help":"Migration persistence ratio (optional)", "device":"Time-lapse microscopy", "method":"1. Track cell trajectories\n2. Calculate net displacement vs total path length\n3. Persistence = net displacement / total path length\n4. Higher persistence → more directed migration" }, "migration_assay_type": {"widget":"select","options":["time_lapse","scratch_assay","transwell","trackmate","manual_tracking","other"],"required":False,"help":"Migration assay method (optional)"}, # Marker expression parameters (optional) "alpha_sma_percent": { "widget":"number","range":(0.0,100.0),"unit":"%","required":False, "help":"α-SMA positive cells percentage (optional)", "device":"Immunofluorescence microscope", "method":"1. Immunostain for α-SMA\n2. Count positive vs total cells\n3. Calculate % positive\n4. Higher % → more myofibroblast differentiation" }, "col1a1_percent": {"widget":"number","range":(0.0,100.0),"unit":"%","required":False,"help":"COL1A1 positive cells percentage (optional)"}, "muc1_percent": {"widget":"number","range":(0.0,100.0),"unit":"%","required":False,"help":"MUC1 positive cells percentage (optional)"}, "ck18_percent": {"widget":"number","range":(0.0,100.0),"unit":"%","required":False,"help":"CK18 positive cells percentage (optional)"}, "marker_assay_type": {"widget":"select","options":["immunostaining","qPCR","western_blot","flow_cytometry","other"],"required":False,"help":"Marker expression assay method (optional)"}, "markers_json": { "widget":"textarea","required":False, "help":"Flexible marker storage as JSON (optional)", "device":"Various", "method":"Store any marker expression data as JSON: {\"marker1\": value, \"marker2\": value, ...}" }, "probe_type": {"widget":"select","options":"codebook.probe_type","help":"Stimulus type"}, "target_pH": {"widget":"number","range":(0.0,14.0),"required":False,"help":"Target pH post-neutralization (optional)"}, "od_wavelength_nm": {"widget":"number","fmt":"int","range":(350,800),"help":"OD wavelength (nm)"}, "od_sampling_interval_min":{"widget":"number","fmt":"int","range":(1,120),"help":"OD sampling interval (min)"}, "time_to_halfmax_min": {"widget":"number","range":(0.0,1e6),"help":"Time to 50% max stiffness"}, "slope_OD_per_min": {"widget":"number","range":(-1e9,1e9),"help":"OD slope (per min)"}, "final_OD": {"widget":"number","range":(0.0,10.0),"help":"Final OD value"}, "lag_time_min": {"widget":"number","range":(0.0,1e6),"help":"Lag time (min)"}, "gel_binary": {"widget":"select","options":[0,1],"required":False,"help":"1=gel formed; 0=no gel (optional - can observe later)"}, "gel_strength_score_0to3": {"widget":"select","options":[0,1,2,3],"help":"Ordinal strength 0–3"}, "tilt_test_angle_deg": {"widget":"number","range":(0.0,90.0),"unit":"deg","help":"Tilt test angle"}, "time_to_handle_min": {"widget":"number","range":(0.0,1e6),"help":"Time until handleable"}, "failure_mode": {"widget":"select","options":"codebook.failure_mode","help":"Failure category if applicable"}, "suspected_cause": {"widget":"select","options":"codebook.suspected_cause","help":"Hypothesis for failure"}, "confidence_0to1": {"widget":"number","range":(0.0,1.0),"help":"Confidence in suspected cause"}, "syneresis_binary": {"widget":"select","options":[0,1],"help":"1=syneresis observed"}, "syneresis_time_min": {"widget":"number","range":(0.0,1e6),"help":"Time to syneresis onset (min)"}, "precipitate_binary":{"widget":"select","options":[0,1],"help":"1=precipitate observed"}, "color_shift": {"widget":"select","options":"codebook.color_shift","help":"Observed color change"}, "disintegrated": {"widget":"select","options":[0,1],"help":"1=gel broke apart into pieces"}, "days_to_disintegration": {"widget":"number","fmt":"int","range":(0,1000),"help":"Days until gel disintegrated"}, "reliquefied": {"widget":"select","options":[0,1],"help":"1=gel returned to liquid state"}, "days_to_reliquefaction": {"widget":"number","fmt":"int","range":(0,1000),"help":"Days until gel became liquid again"}, "plate_adhesion": {"widget":"select","options":["","adhered","floating","mixed"],"help":"Gel adherence to plate surface"}, "adhesion_notes": {"widget":"text","help":"Details on adhesion (spontaneous vs induced, timing)"}, "time_to_gel_min": {"widget":"number","range":(0.0,10000.0),"help":"Time for gel formation after adding reagents (minutes)"}, "pre_gel_storage_temp_C": {"widget":"number","range":(-80.0,40.0),"help":"Storage temperature before adding gelation reagents (°C)"}, "pre_gel_storage_duration_min": {"widget":"number","range":(0.0,100000.0),"help":"Duration ECM stored without reagents before gelation (minutes)"}, "pre_gel_storage_notes": {"widget":"text","help":"Additional context about pre-gelation storage conditions"}, "notes_pre": {"widget":"textarea","help":"Pre-experiment notes"}, "notes_post": {"widget":"textarea","help":"Post-experiment notes"}, "app_recipe_recommended": {"widget":"textarea","help":"AI-recommended recipe"}, "app_pgel_pred": {"widget":"number","range":(0.0,1.0),"help":"AI-predicted P(gel)"}, "app_thalf_pred_min": {"widget":"number","range":(0.0,1e6),"help":"AI-predicted t½ (min)"}, "app_uncertainty": {"widget":"number","range":(0.0,1.0),"help":"AI prediction uncertainty"}, "counterfactual_recipe": {"widget":"textarea","help":"Counterfactual recipe"}, "counterfactual_expected_pgel": {"widget":"number","range":(0.0,1.0),"help":"Expected P(gel) for counterfactual"}, "split": {"widget":"select","options":"codebook.split","help":"Train/validate/test split assignment"}, }, "reagents_per_well": { "record_id": {"widget":"text","required":True,"help":"Foreign key to wells_master_v4"}, "reagent_name": {"widget":"text","required":True,"help":"Chemical or solution name"}, "reagent_class": {"widget":"select","options":["buffer","base","acid","salt","media","additive","enzyme","crosslinker","other"],"help":"Reagent category"}, "purpose": {"widget":"text","help":"E.g., neutralization, ionic_adjust"}, "stock_conc_value": {"widget":"number","range":(0.0,1e9),"help":"Stock concentration numeric value"}, "stock_conc_units": {"widget":"select","options":["M","mM","µM","%","x","mg/mL","U/mL"],"help":"Concentration units"}, "volume_uL_per_mL": {"widget":"number","range":(0.0,1000.0),"unit":"µL/mL","help":"Volume added per mL of ECM"}, "effective_conc_mM":{"widget":"number","range":(0.0,1e6),"unit":"mM","help":"Auto-computed if convertible"}, "lot_number": {"widget":"text","help":"Optional lot/batch number"}, "added_order": {"widget":"number","fmt":"int","range":(1,99),"help":"Addition sequence order"}, "notes": {"widget":"textarea","help":"Freeform notes"}, }, "events_long": { "record_id": {"widget":"text","required":True,"help":"Foreign key to wells_master_v4"}, "event_type": {"widget":"select","options":["status","soften","liquefy","syneresis_onset","tilt_score","strength_score","OD_Reading","Other"],"required":True,"help":"Event category"}, "time_point_min": {"widget":"number","range":(0.0,1e7),"help":"Minutes from experiment start"}, "time_from_mix_hours":{"widget":"number","range":(0.0,1e6),"help":"Hours from mixing"}, "day_from_mix": {"widget":"number","fmt":"int","range":(0,10000),"help":"Whole days from mixing"}, "timestamp": {"widget":"text","help":"ISO timestamp of observation"}, "status_code": {"widget":"select","options":"codebook.status_code","help":"Qualitative gel status"}, "gel_strength_score_0to3":{"widget":"select","options":[0,1,2,3],"help":"Ordinal strength score"}, "tilt_test_angle_deg":{"widget":"number","range":(0.0,90.0),"unit":"deg","help":"Tilt test angle"}, "measurement_type": {"widget":"text","help":"E.g., OD405, pH, viscosity"}, "measurement_value": {"widget":"number","range":(-1e9,1e9),"help":"Numeric measurement value"}, "measurement_units": {"widget":"text","help":"E.g., A.U., pH units"}, "observation": {"widget":"textarea","help":"Freeform observation notes"}, "operator_id": {"widget":"text","help":"Observer initials"}, "notes_event": {"widget":"textarea","help":"Event-specific notes"}, }, "plates_registry": { "plate_id": {"widget":"text","required":True,"help":"Unique plate identifier"}, "row_labels": {"widget":"text","required":True,"help":"Letters e.g. ABCDEFGH"}, "max_cols": {"widget":"number","fmt":"int","range":(1, 48),"required":True,"help":"Number of columns"}, "description": {"widget":"text","help":"Optional plate description"}, } } # ============================================================================ # SCHEMA-DRIVEN UI UTILITIES # ============================================================================ def _resolve_options(spec_entry, codebook, dynamic_rows=None): """Resolve options for a select widget from spec.""" opts = spec_entry.get("options") if opts == "__rows_from_plate__": return list(dynamic_rows or "ABCDEFGH") if isinstance(opts, str) and opts.startswith("codebook."): # Extract field from codebook field = opts.split(".", 1)[1] return [""] + list(codebook.get(field, [])) if isinstance(opts, (list, tuple)): # Direct list return [""] + list(opts) if "" not in opts else list(opts) return None # ============================================================================ # COERCION HELPERS (schema-driven normalization) # ============================================================================ _BOOLISH_TRUE = {"1", "true", "yes", "y", "t"} _BOOLISH_FALSE = {"0", "false", "no", "n", "f"} def _none_if_blank(v: Any) -> Any: """Convert blank/NaN values to None.""" if v is None: return None if isinstance(v, str) and v.strip() == "": return None if isinstance(v, float) and pd.isna(v): return None return v def _coerce_number(v: Any) -> Optional[float]: """Coerce to float, or None if invalid.""" v = _none_if_blank(v) if v is None: return None try: return float(v) except (TypeError, ValueError): return None def _coerce_int(v: Any) -> Optional[int]: """Coerce to int, or None if invalid. Accepts floats that are integral (e.g., 3.0).""" v = _none_if_blank(v) if v is None: return None try: f = float(v) i = int(f) return i if f == i else None except (TypeError, ValueError): return None def _coerce_boolish(v: Any) -> Optional[int]: """Coerce boolean-ish values to 0/1.""" v = _none_if_blank(v) if v is None: return None if isinstance(v, (int, float)): return 1 if int(v) != 0 else 0 if isinstance(v, str): s = v.strip().lower() if s in _BOOLISH_TRUE: return 1 if s in _BOOLISH_FALSE: return 0 return None def _coerce_date_iso(v: Any) -> Optional[str]: """Coerce to ISO date string (YYYY-MM-DD), or None.""" v = _none_if_blank(v) if v is None: return None if isinstance(v, (datetime, date)): return v.strftime("%Y-%m-%d") if isinstance(v, str): s = v.strip() try: # Try strict ISO first return datetime.fromisoformat(s).date().strftime("%Y-%m-%d") except Exception: # Last-ditch: pandas parse try: return pd.to_datetime(s).date().strftime("%Y-%m-%d") except Exception: return None return None def _resolve_allowed_options(meta: dict, codebook: dict) -> Optional[list]: """Resolve allowed options from FIELD_SPEC metadata.""" opts = meta.get("options") if not opts: return None if isinstance(opts, str) and opts.startswith("codebook."): fld = opts.split(".", 1)[1] return list(codebook.get(fld, [])) if isinstance(opts, (list, tuple)): return list(opts) return None def _coerce_select(v: Any, allowed: Optional[list]) -> Any: """Coerce to one of the allowed options (case-insensitive match).""" v = _none_if_blank(v) if v is None or not allowed: return v # Accept case-insensitive matches if isinstance(v, str): for opt in allowed: if str(opt).lower() == v.lower(): return opt # Direct containment return v if v in allowed else None # Fields we always treat as boolean-ish integers (0/1) _BOOLISH_FIELDS = { "gel_binary", "syneresis_binary", "precipitate_binary" } def coerce_payload(table: str, payload: Dict[str, Any], codebook: dict) -> Dict[str, Any]: """ Coerce a payload into DB-safe shapes using FIELD_SPEC: - numbers → float - fmt=int → int - date → YYYY-MM-DD - selects → snap to allowed options - blanks/NaN → None - boolish → 0/1 Args: table: Table name (e.g., "wells_master_v4") payload: Raw data dictionary codebook: Codebook dictionary for select options Returns: Coerced payload dictionary """ spec = FIELD_SPEC.get(table, {}) out = {} for field, val in payload.items(): meta = spec.get(field, {}) w = meta.get("widget") fmt = meta.get("fmt") out_val = _none_if_blank(val) # Bool-like override first if field in _BOOLISH_FIELDS: out_val = _coerce_boolish(val) elif w == "date": out_val = _coerce_date_iso(val) elif fmt == int: out_val = _coerce_int(val) elif w == "number": out_val = _coerce_number(val) # Snap selects to allowed values if meta.get("widget") == "select": allowed = _resolve_allowed_options(meta, codebook) out_val = _coerce_select(out_val, allowed) out[field] = out_val return out def validate_against_spec(table: str, spec: dict, payload: dict) -> List[str]: """ Validate a payload against field specification. Args: table: Table name (e.g., "wells_master_v4") spec: FIELD_SPEC dictionary payload: Data dictionary to validate Returns: List of error messages (empty if valid) """ errors = [] for field, meta in spec.get(table, {}).items(): val = payload.get(field) # Required field check if meta.get("required") and (val is None or (isinstance(val, str) and val.strip() == "") or val == ""): errors.append(f"{field} is required") # Range validation for numbers if val is not None and val != "" and meta.get("range"): lo, hi = meta["range"] try: num = float(val) if num < lo or num > hi: errors.append(f"{field} must be between {lo} and {hi}") except (ValueError, TypeError): pass # Integer format check if meta.get("fmt") == "int" and val not in (None, "", 0): try: int(val) except (ValueError, TypeError): errors.append(f"{field} must be an integer") return errors def export_data_dictionary(spec: dict, path: Path): """ Export field specifications to CSV data dictionary. Args: spec: FIELD_SPEC dictionary path: Output CSV file path """ rows = [] for table, fields in spec.items(): for name, meta in fields.items(): opts = meta.get("options", "") if isinstance(opts, list): opts_str = ", ".join([str(o) for o in opts]) elif isinstance(opts, str): opts_str = opts else: opts_str = "" rows.append({ "table": table, "field": name, "widget": meta.get("widget", ""), "required": "Yes" if meta.get("required") else "No", "range": str(meta.get("range", "")) if meta.get("range") else "", "unit": meta.get("unit", ""), "options": opts_str, "help": meta.get("help", "") }) df = pd.DataFrame(rows) df.to_csv(path, index=False) return df # ============================================================================ # CODEBOOK # ============================================================================ @st.cache_data def load_codebook(): codebook = { 'family': [ 'collagen', # Pure collagen (split from decECM) 'decECM', # Decellularized ECM (requires species + tissue) 'fibrin', 'alginate', 'gelMA', 'hyaluronan', 'PEG_DA', 'composite' ], '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' ], 'probe_type': ['pH_pulse', 'ionic_pulse', 'crosslinker_pulse', 'light_dose', 'temperature_shift'], 'gel_binary': [0, 1], 'gel_strength_score_0to3': [0, 1, 2, 3], 'failure_mode': ['none', 'no_set', 'partial_set', 'delayed_set', 'collapse', 'overcrosslink_brittle', 'phase_separation', 'opalescence', 'bubble_issue'], 'suspected_cause': ['over_digest', 'under_digest', 'low_pH', 'high_pH', 'low_ionic', 'high_ionic', 'low_temp', 'high_temp', 'lipid_contam', 'detergent_contam', 'chaotrope_residual', 'air_entrainment', 'photoinitiator_low', 'photodose_low', 'photodose_high', 'unknown'], 'color_shift': ['none', 'yellowing', 'browning', 'pink_loss', 'other'], 'split': ['train', 'validate', 'test', 'holdout_batch'], 'status_code': ["liquid","viscous","weak_gel","soft_gel","stiff_gel","softened","partial_liquid","liquidated"] } # Optional: extend from CSVs if present try: df_cb = pd.read_csv(ROOT / "data" / "ecm_gelation_codebook.csv") for _, row in df_cb.iterrows(): if pd.notna(row.get('allowed_values')) and pd.notna(row.get('field')): codebook[row['field']] = [v.strip() for v in str(row['allowed_values']).split('|')] except Exception: pass return codebook # ============================================================================ # CRUD # ============================================================================ def create_well(data, reagents_list=None): rid = data.get("record_id") or new_record_id() data["record_id"] = rid data['created_at'] = datetime.now().isoformat() data['updated_at'] = datetime.now().isoformat() with tx() as con: cols = list(data.keys()) vals = [data[k] for k in cols] con.execute(f"INSERT INTO wells_master_v4 ({','.join(cols)}) VALUES ({','.join(['?']*len(vals))})", vals) if reagents_list: for r in reagents_list: r = {k:v for k,v in r.items() if v not in ("",)} # strip empties r["record_id"] = rid if "created_at" not in r: r["created_at"] = datetime.now().isoformat() r_cols = list(r.keys()); r_vals = [r[k] for k in r_cols] con.execute(f"INSERT INTO reagents_per_well ({','.join(r_cols)}) VALUES ({','.join(['?']*len(r_vals))})", r_vals) return rid def read_wells(filters=None, use_effective_view=True): conn = get_connection() table = "v_wells_effective" if use_effective_view else "wells_master_v4" q = f"SELECT * FROM {table}" params = [] if filters: cond = [] for k,v in filters.items(): if v not in (None,""): cond.append(f"{k}=?") params.append(v) if cond: q += " WHERE " + " AND ".join(cond) q += " ORDER BY created_at DESC" df = pd.read_sql_query(q, conn, params=params if params else None) conn.close() return df def update_well(record_id, data, expected_updated_at=None): with tx() as con: if expected_updated_at: cur = con.execute("SELECT updated_at FROM wells_master_v4 WHERE record_id=?", (record_id,)).fetchone() if not cur: raise ValueError("Record not found.") if cur["updated_at"] != expected_updated_at: raise RuntimeError("This record was edited by someone else. Reload and try again.") sets = ",".join([f"{k}=?" for k in data.keys()]) con.execute(f"UPDATE wells_master_v4 SET {sets} WHERE record_id=?", [*data.values(), record_id]) def delete_well(record_id): with tx() as con: con.execute("DELETE FROM wells_master_v4 WHERE record_id = ?", (record_id,)) def add_reagent(data): if 'created_at' not in data: data['created_at'] = datetime.now().isoformat() with tx() as con: cols = ",".join(data.keys()) con.execute(f"INSERT INTO reagents_per_well ({cols}) VALUES ({','.join(['?']*len(data))})", list(data.values())) def get_reagents(record_id): conn = get_connection() df = pd.read_sql_query("SELECT * FROM reagents_per_well WHERE record_id=? ORDER BY added_order", conn, params=(record_id,)) conn.close() return df def delete_reagent(reagent_id): with tx() as con: con.execute("DELETE FROM reagents_per_well WHERE reagent_id=?", (reagent_id,)) def add_event(data): if 'created_at' not in data: data['created_at'] = datetime.now().isoformat() if 'timestamp' not in data or not data['timestamp']: data['timestamp'] = datetime.now().isoformat() with tx() as con: cols = ",".join(data.keys()) con.execute(f"INSERT INTO events_long ({cols}) VALUES ({','.join(['?']*len(data))})", list(data.values())) def get_events(record_id): conn = get_connection() df = pd.read_sql_query("SELECT * FROM events_long WHERE record_id=? ORDER BY time_point_min", conn, params=(record_id,)) conn.close() return df def delete_event(event_id): with tx() as con: con.execute("DELETE FROM events_long WHERE event_id=?", (event_id,)) def backup_database(): """ Create a timestamped backup of the database and optionally VACUUM. Returns: Path to backup file """ import shutil backup_dir = ROOT / "backups" backup_dir.mkdir(exist_ok=True) ts = datetime.now().strftime("%Y%m%d_%H%M") backup_path = backup_dir / f"gelpredict_{ts}.db" # Copy database shutil.copy2(DB_PATH, backup_path) # Vacuum original to reclaim space (optional) try: conn = get_connection() conn.execute("VACUUM;") conn.close() except Exception: pass # VACUUM not critical return backup_path # ============================================================================ # IMAGE PROCESSING HELPERS # ============================================================================ def _sha256_bytes(b: bytes) -> str: """Calculate SHA256 hash of bytes.""" h = hashlib.sha256() h.update(b) return h.hexdigest() def _safe_ext(mime: str) -> str: """Get file extension from MIME type.""" return { "image/jpeg": ".jpg", "image/png": ".png", "image/tiff": ".tif", "image/webp": ".webp" }.get(mime, ".bin") def _exif_datetime(img: Image.Image) -> Optional[str]: """Extract datetime from EXIF data, return ISO format or None.""" try: exif = img.getexif() if not exif: return None tagmap = {ExifTags.TAGS.get(k, k): v for k, v in exif.items()} dt = tagmap.get("DateTimeOriginal") or tagmap.get("DateTime") # EXIF format "YYYY:MM:DD HH:MM:SS" if isinstance(dt, str) and len(dt) >= 19 and dt[4] == ":": y, M, d = dt[0:4], dt[5:7], dt[8:10] h, m, s = dt[11:13], dt[14:16], dt[17:19] return f"{y}-{M}-{d}T{h}:{m}:{s}" except Exception: return None return None def _save_thumbnail(src_bytes: bytes, thumb_path: Path, max_px=512) -> Tuple[int, int]: """ Create and save thumbnail from image bytes. Returns: (width, height) of thumbnail """ im = Image.open(io.BytesIO(src_bytes)) im = im.convert("RGB") im.thumbnail((max_px, max_px)) thumb_path.parent.mkdir(parents=True, exist_ok=True) im.save(thumb_path, format="JPEG", quality=85) return im.size[0], im.size[1] def _probe_dims(src_bytes: bytes) -> Tuple[int, int]: """Get image dimensions without full load.""" im = Image.open(io.BytesIO(src_bytes)) return im.size[0], im.size[1] # ============================================================================ # IMAGE CRUD # ============================================================================ def add_image_record(payload: dict): """Add an image record to gel_images table.""" with tx() as con: cols = ",".join(payload.keys()) placeholders = ",".join(["?"] * len(payload)) con.execute( f"INSERT INTO gel_images ({cols}) VALUES ({placeholders})", list(payload.values()) ) def get_images_for_record(record_id: str): """Get all images for a specific well record.""" conn = get_connection() try: df = pd.read_sql_query( "SELECT * FROM gel_images WHERE record_id=? ORDER BY created_at DESC", conn, params=(record_id,) ) return df finally: conn.close() def delete_image(image_id: str): """Delete image record and associated files.""" with tx() as con: row = con.execute( "SELECT file_relpath, thumb_relpath FROM gel_images WHERE image_id=?", (image_id,) ).fetchone() con.execute("DELETE FROM gel_images WHERE image_id=?", (image_id,)) # Remove files outside the transaction if row: for rel in (row["file_relpath"], row["thumb_relpath"]): if rel: p = ROOT / rel try: p.unlink(missing_ok=True) except Exception: pass # ============================================================================ # CLONE / BULK HELPERS # ============================================================================ CLONE_EXCLUDE_FIELDS = { "record_id","created_at","updated_at", "gel_binary","gel_strength_score_0to3","tilt_test_angle_deg","time_to_handle_min", "app_recipe_recommended","app_pgel_pred","app_thalf_pred_min","app_uncertainty", "counterfactual_recipe","counterfactual_expected_pgel","notes_post" } def get_well(record_id: str) -> Optional[dict]: """Get a single well record by ID.""" conn = get_connection() try: row = pd.read_sql_query("SELECT * FROM wells_master_v4 WHERE record_id=?", conn, params=(record_id,)) if row.empty: return None return row.iloc[0].to_dict() finally: conn.close() def copy_well_payload(well: dict, *, new_record_id: str, date_override: Optional[str] = None, operator_override: Optional[str] = None, plate_id: Optional[str] = None, row_letter: Optional[str] = None, col_num: Optional[int] = None, replicate_id: Optional[int] = None, batch_id: Optional[str] = None) -> dict: """ Copy a well payload, excluding outcome fields and updating positional fields. Args: well: Source well dictionary new_record_id: UUID for the new record date_override: Override date operator_override: Override operator_id plate_id: Override plate_id row_letter: Override row (A-H) col_num: Override column (1-12) replicate_id: Override replicate_id batch_id: Override batch_id Returns: New well payload dictionary """ base = {k: v for k, v in well.items() if k not in CLONE_EXCLUDE_FIELDS} base["record_id"] = new_record_id if date_override: base["date"] = date_override if operator_override: base["operator_id"] = operator_override if batch_id: base["batch_id"] = batch_id if plate_id is not None: base["plate_id"] = plate_id if row_letter is not None: base["row"] = row_letter if col_num is not None: base["col"] = int(col_num) if replicate_id is not None: base["replicate_id"] = int(replicate_id) # Wipe kinetic/outcome fields that shouldn't be cloned for k in ("time_to_halfmax_min","slope_OD_per_min","final_OD","lag_time_min"): if k in base: base[k] = None return base def get_reagents_template(record_id: str) -> List[dict]: """Get reagents from a well as a template list (without reagent_id).""" df = get_reagents(record_id) if df.empty: return [] keep_cols = ["reagent_name","reagent_class","purpose","stock_conc_value","stock_conc_units", "volume_uL_per_mL","effective_conc_mM","lot_number","added_order","notes"] cols = [c for c in keep_cols if c in df.columns] rows = df[cols].to_dict(orient="records") return rows def likely_duplicate_exists(plate_id, row, col, lookback_hours=12): """ Check if a well with same plate/row/col was recently created. Args: plate_id: Plate identifier row: Row letter (A-H) col: Column number (1-12) lookback_hours: How far back to check (default 12 hours) Returns: bool: True if likely duplicate exists """ if not plate_id or not row or not col: return False conn = get_connection() try: df = pd.read_sql_query( "SELECT record_id, created_at FROM wells_master_v4 WHERE plate_id=? AND row=? AND col=? " "AND datetime(created_at) > datetime('now', ?)", conn, params=(plate_id, row, int(col), f'-{int(lookback_hours)} hours') ) return not df.empty finally: conn.close() def bulk_create_wells(template_well: dict, positions: list, reagents_template: Optional[list] = None, date_override: Optional[str] = None, operator_override: Optional[str] = None, batch_id: Optional[str] = None) -> list: """ Bulk create wells from a template. Args: template_well: Template well dictionary positions: List of (row_letter, col_num, replicate_id) tuples reagents_template: Optional reagents to copy to each well date_override: Override date for all wells operator_override: Override operator_id batch_id: Override batch_id Returns: List of new record_ids created """ rids = [] for (r, c, rep) in positions: rid = new_record_id() payload = copy_well_payload( template_well, new_record_id=rid, date_override=date_override, operator_override=operator_override, plate_id=template_well.get("plate_id"), row_letter=r, col_num=c, replicate_id=rep, batch_id=batch_id ) create_well(payload, reagents_list=reagents_template) rids.append(rid) return rids # ============================================================================ # UI # ============================================================================ def show_plates_viewer(): """Show all plates with their wells and experiments.""" st.header("🧪 Plates Viewer") st.caption("View all plates and their experimental data") # Connect to database conn = get_connection() # Get all unique plates plates_df = pd.read_sql_query(""" SELECT DISTINCT plate_id, COUNT(*) as well_count, MIN(date) as first_date, MAX(date) as last_date, COUNT(DISTINCT batch_id) as unique_batches, COUNT(DISTINCT operator_id) as unique_operators FROM wells_master_v4 WHERE plate_id IS NOT NULL GROUP BY plate_id ORDER BY last_date DESC """, conn) if plates_df.empty: st.info("No plates found in the database.") conn.close() return st.write(f"**Total Plates:** {len(plates_df)}") # Filters with st.expander("🔍 Filter Plates", expanded=False): col1, col2 = st.columns(2) with col1: filter_plate_id = st.text_input("Plate ID contains") filter_operator = st.selectbox("Operator", ["All"] + sorted(plates_df['unique_operators'].dropna().unique().tolist())) with col2: min_wells = st.number_input("Min wells", min_value=0, value=0) # Apply filters filtered_df = plates_df.copy() if filter_plate_id: filtered_df = filtered_df[filtered_df['plate_id'].str.contains(filter_plate_id, case=False, na=False)] if min_wells > 0: filtered_df = filtered_df[filtered_df['well_count'] >= min_wells] # Display plates for idx, row in filtered_df.iterrows(): with st.expander(f"🧪 **{row['plate_id']}** ({row['well_count']} wells)", expanded=False): col1, col2, col3 = st.columns(3) with col1: st.metric("Wells", row['well_count']) st.metric("Batches", row['unique_batches']) with col2: st.metric("First Date", row['first_date']) st.metric("Last Date", row['last_date']) with col3: st.metric("Operators", row['unique_operators']) # Show wells for this plate if st.button(f"🔍 View Wells", key=f"view_wells_{row['plate_id']}"): st.session_state[f"show_wells_{row['plate_id']}"] = True if st.session_state.get(f"show_wells_{row['plate_id']}"): wells_df = pd.read_sql_query(""" SELECT record_id, row, col, batch_id, family, operator_id, date, gel_binary, gel_strength_score_0to3, temp_incubation_C, target_pH FROM wells_master_v4 WHERE plate_id = ? ORDER BY row, col """, conn, params=(row['plate_id'],)) st.dataframe(wells_df, use_container_width=True) conn.close() def show_gelation_viewer(): """Show all gelation experiments with filtering and analysis.""" st.header("🧬 Gelation Experiments Viewer") st.caption("View and analyze gelation experiments") # Connect to database conn = get_connection() # Get gelation experiments gelation_df = pd.read_sql_query(""" SELECT record_id, date, operator_id, family, batch_id, plate_id, row, col, gelation_id, temp_incubation_C, target_pH, gel_volume_uL, gel_binary, gel_strength_score_0to3, time_to_gel_min, disintegrated, days_to_disintegration, reliquefied, days_to_reliquefaction, plate_adhesion, created_at FROM wells_master_v4 WHERE gelation_id IS NOT NULL ORDER BY date DESC, created_at DESC """, conn) if gelation_df.empty: st.info("No gelation experiments found in the database.") conn.close() return st.write(f"**Total Gelation Experiments:** {len(gelation_df)}") # Filters with st.expander("🔍 Filter Experiments", expanded=False): col1, col2, col3 = st.columns(3) with col1: filter_batch = st.text_input("Batch ID contains") filter_family = st.selectbox("ECM Family", ["All"] + sorted(gelation_df['family'].dropna().unique().tolist())) with col2: filter_operator = st.selectbox("Operator", ["All"] + sorted(gelation_df['operator_id'].dropna().unique().tolist())) filter_gelation_id = st.text_input("Gelation ID contains") with col3: filter_outcome = st.selectbox("Gel Outcome", ["All", "Gel", "No Gel"]) filter_plate = st.text_input("Plate ID contains") # Apply filters filtered_df = gelation_df.copy() if filter_batch: filtered_df = filtered_df[filtered_df['batch_id'].str.contains(filter_batch, case=False, na=False)] if filter_family != "All": filtered_df = filtered_df[filtered_df['family'] == filter_family] if filter_operator != "All": filtered_df = filtered_df[filtered_df['operator_id'] == filter_operator] if filter_gelation_id: filtered_df = filtered_df[filtered_df['gelation_id'].str.contains(filter_gelation_id, case=False, na=False)] if filter_outcome == "Gel": filtered_df = filtered_df[filtered_df['gel_binary'] == 1] elif filter_outcome == "No Gel": filtered_df = filtered_df[filtered_df['gel_binary'] == 0] if filter_plate: filtered_df = filtered_df[filtered_df['plate_id'].str.contains(filter_plate, case=False, na=False)] st.write(f"**Filtered Results:** {len(filtered_df)} experiments") # Summary statistics if not filtered_df.empty: col1, col2, col3, col4 = st.columns(4) with col1: gel_rate = filtered_df['gel_binary'].mean() * 100 if 'gel_binary' in filtered_df.columns else 0 st.metric("Gel Rate", f"{gel_rate:.1f}%") with col2: avg_strength = filtered_df['gel_strength_score_0to3'].mean() if 'gel_strength_score_0to3' in filtered_df.columns else 0 st.metric("Avg Strength", f"{avg_strength:.1f}") with col3: avg_temp = filtered_df['temp_incubation_C'].mean() if 'temp_incubation_C' in filtered_df.columns else 0 st.metric("Avg Temp", f"{avg_temp:.1f}°C") with col4: avg_time = filtered_df['time_to_gel_min'].mean() if 'time_to_gel_min' in filtered_df.columns else 0 st.metric("Avg Time to Gel", f"{avg_time:.1f} min") # Display experiments st.dataframe(filtered_df, use_container_width=True) conn.close() def show_cell_growth_viewer(): """Show cell growth experiments from the cell growth database.""" st.header("🧫 Cell Growth Viewer") st.caption("View cell growth experiments and their results") # Try to connect to cell growth database try: LAB_CELL_DB = ROOT / "cellgrowth_lab.sqlite" if not LAB_CELL_DB.exists(): st.info("No cell growth database found. Create some cell growth experiments first!") return conn = sqlite3.connect(str(LAB_CELL_DB)) # Get cell growth runs runs_df = pd.read_sql_query(""" SELECT run_id, date, operator_id, plate_id, plate_type, created_at, updated_at FROM cell_runs ORDER BY date DESC, created_at DESC """, conn) if runs_df.empty: st.info("No cell growth experiments found.") conn.close() return st.write(f"**Total Cell Growth Runs:** {len(runs_df)}") # Filters with st.expander("🔍 Filter Runs", expanded=False): col1, col2 = st.columns(2) with col1: filter_operator = st.selectbox("Operator", ["All"] + sorted(runs_df['operator_id'].dropna().unique().tolist())) filter_plate = st.text_input("Plate ID contains") with col2: filter_plate_type = st.selectbox("Plate Type", ["All"] + sorted(runs_df['plate_type'].dropna().unique().tolist())) # Apply filters filtered_df = runs_df.copy() if filter_operator != "All": filtered_df = filtered_df[filtered_df['operator_id'] == filter_operator] if filter_plate: filtered_df = filtered_df[filtered_df['plate_id'].str.contains(filter_plate, case=False, na=False)] if filter_plate_type != "All": filtered_df = filtered_df[filtered_df['plate_type'] == filter_plate_type] # Display runs for idx, row in filtered_df.iterrows(): with st.expander(f"🧫 **Run {row['run_id'][:12]}...** ({row['plate_type']})", expanded=False): col1, col2, col3 = st.columns(3) with col1: st.write(f"**Date:** {row['date']}") st.write(f"**Operator:** {row['operator_id']}") with col2: st.write(f"**Plate ID:** {row['plate_id']}") st.write(f"**Plate Type:** {row['plate_type']}") with col3: st.write(f"**Created:** {row['created_at']}") # Try to get media formulation data try: media_df = pd.read_sql_query(""" SELECT * FROM media_per_run WHERE run_id = ? """, conn, params=(row['run_id'],)) if not media_df.empty: st.write("**Media Formulation:**") st.dataframe(media_df, use_container_width=True) except: pass conn.close() except Exception as e: st.error(f"Error accessing cell growth database: {e}") st.info("Make sure the cell growth database exists and is accessible.") def show_morphology_viewer(): """Show morphology observations from the morphology database.""" st.header("🔬 Morphology Viewer") st.caption("View morphology observations and measurements") # Try to connect to morphology database try: MORPH_DB = ROOT / "morphology_lab.sqlite" if not MORPH_DB.exists(): st.info("No morphology database found. Create some morphology experiments first!") return conn = sqlite3.connect(str(MORPH_DB)) # Get morphology observations morph_df = pd.read_sql_query(""" SELECT observation_id, date, operator_id, well_id, plate_id, observation_type, measurement_value, measurement_units, observation_notes, created_at FROM morphology_observations ORDER BY date DESC, created_at DESC """, conn) if morph_df.empty: st.info("No morphology observations found.") conn.close() return st.write(f"**Total Morphology Observations:** {len(morph_df)}") # Filters with st.expander("🔍 Filter Observations", expanded=False): col1, col2 = st.columns(2) with col1: filter_operator = st.selectbox("Operator", ["All"] + sorted(morph_df['operator_id'].dropna().unique().tolist())) filter_well = st.text_input("Well ID contains") with col2: filter_type = st.selectbox("Observation Type", ["All"] + sorted(morph_df['observation_type'].dropna().unique().tolist())) filter_plate = st.text_input("Plate ID contains") # Apply filters filtered_df = morph_df.copy() if filter_operator != "All": filtered_df = filtered_df[filtered_df['operator_id'] == filter_operator] if filter_well: filtered_df = filtered_df[filtered_df['well_id'].str.contains(filter_well, case=False, na=False)] if filter_type != "All": filtered_df = filtered_df[filtered_df['observation_type'] == filter_type] if filter_plate: filtered_df = filtered_df[filtered_df['plate_id'].str.contains(filter_plate, case=False, na=False)] # Summary statistics if not filtered_df.empty: col1, col2, col3 = st.columns(3) with col1: unique_wells = filtered_df['well_id'].nunique() st.metric("Unique Wells", unique_wells) with col2: unique_plates = filtered_df['plate_id'].nunique() st.metric("Unique Plates", unique_plates) with col3: avg_value = filtered_df['measurement_value'].mean() if 'measurement_value' in filtered_df.columns else 0 st.metric("Avg Measurement", f"{avg_value:.2f}") # Display observations st.dataframe(filtered_df, use_container_width=True) conn.close() except Exception as e: st.error(f"Error accessing morphology database: {e}") st.info("Make sure the morphology database exists and is accessible.") def main(): st.set_page_config(page_title="GelPredict Data Entry", page_icon="🧪", layout="wide") st.title("🧪 GelPredict Data Entry System") st.caption("Normalized logging of wells, reagents, and longitudinal events with export for PIs & training.") init_database() apply_migrations() # Run migrations with user_version ensure_triggers() ensure_views() codebook = load_codebook() # Database scope badge st.sidebar.caption("**📊 Dataset Scope:**") st.sidebar.success("✅ **LAB - Hydrogels**\n\n`gelpredict.db`") st.sidebar.caption("Your experimental data.\nTraining-ready.") st.sidebar.markdown("---") # Check for schema drift (warn if found) drift = check_schema_drift(FIELD_SPEC) if drift: with st.sidebar.expander("⚠️ Schema Drift Detected"): for problem in drift: st.warning(problem) st.caption("Some fields in FIELD_SPEC don't match database. Update spec or database.") page = st.sidebar.radio( "Navigation", ["🧪 Hydrogels", "🧫 Cell Growth", "🔬 Morphology", "📊 View/Edit Data", "📚 Lit Review Tracker", "🧪 Media Tracker", "📂 Import CSV", "📋 Export Data", "🔄 Sync Manager", "🤖 AI Ecosystem"] ) if page == "🧪 Hydrogels": # Hydrogel tracking with LAB/Literature toggle hydrogel_mode = st.sidebar.radio("Dataset", ["LAB", "Literature"], horizontal=True, key="hydrogel_mode") if hydrogel_mode == "LAB": # LAB Hydrogels submenu lab_page = st.sidebar.radio( "LAB Hydrogels", ["🧬 ECM Batches", "🧪 Gelation Tests", "📝 Quick Entry (Legacy)", "🧫 Reagents", "📈 Events", "🧩 Plate Wizard", "🧱 Plates", "📷 Images"], key="lab_hydrogel_page" ) if lab_page == "🧬 ECM Batches": try: from batch_creation_lab import show_batch_creation_form show_batch_creation_form(codebook) except ImportError as e: st.error(f"Batch Creation Lab module not available: {e}") st.info("This module may not be available in the cloud deployment.") elif lab_page == "🧪 Gelation Tests": try: from gelation_lab import show_gelation_form show_gelation_form(codebook) except ImportError as e: st.error(f"Gelation Lab module not available: {e}") st.info("This module may not be available in the cloud deployment.") elif lab_page == "📝 Quick Entry (Legacy)": st.info("💡 **Legacy Mode:** All-in-one entry. For new workflows, use **ECM Batches** → **Gelation Tests**") show_new_entry_form(codebook) elif lab_page == "🧫 Reagents": show_reagents_manager(codebook) elif lab_page == "📈 Events": show_events_logger(codebook) elif lab_page == "🧩 Plate Wizard": show_plate_map_wizard(codebook) elif lab_page == "🧱 Plates": show_plates_registry() elif lab_page == "📷 Images": show_images_manager(codebook) else: # Literature Hydrogels submenu lit_page = st.sidebar.radio( "Literature Hydrogels", ["🧬 ECM Batches", "🧪 Gelation Data", "📝 Quick Entry (Legacy)"], key="lit_hydrogel_page" ) if lit_page == "🧬 ECM Batches": try: from batch_creation_lit import show_lit_batch_form show_lit_batch_form(codebook) except ImportError as e: st.error(f"Batch Creation Literature module not available: {e}") st.info("This module may not be available in the cloud deployment.") elif lit_page == "🧪 Gelation Data": try: from gelation_lit import show_lit_gelation_form show_lit_gelation_form(codebook) except ImportError as e: st.error(f"Gelation Literature module not available: {e}") st.info("This module may not be available in the cloud deployment.") elif lit_page == "📝 Quick Entry (Legacy)": st.info("💡 **Legacy Mode:** All-in-one entry. For new workflows, use **ECM Batches** → **Gelation Data**") try: from literature_gui import show_literature_app show_literature_app() except ImportError as e: st.error(f"Literature GUI module not available: {e}") st.info("This module may not be available in the cloud deployment.") elif page == "📊 View/Edit Data": # View/Edit Data with sub-sections for each data type view_mode = st.sidebar.radio("Data Type", ["📊 Raw Wells Data", "📚 Literature Database", "🧫 Cell Growth", "🔬 Morphology", "📚 Batch Library", "🧪 Plates", "🧬 Gelation"], horizontal=False, key="view_mode") if view_mode == "📊 Raw Wells Data": show_view_edit_page(codebook) elif view_mode == "📚 Literature Database": show_literature_database_viewer() elif view_mode == "🧫 Cell Growth": show_cell_growth_viewer() elif view_mode == "🔬 Morphology": show_morphology_viewer() elif view_mode == "📚 Batch Library": try: from batch_creation_lab import show_batch_library show_batch_library() except ImportError as e: st.error(f"Batch Library module not available: {e}") st.info("This module may not be available in the cloud deployment.") elif view_mode == "🧪 Plates": show_plates_viewer() elif view_mode == "🧬 Gelation": show_gelation_viewer() elif page == "🧫 Cell Growth": # Cell growth with LAB/Literature toggle cell_mode = st.sidebar.radio("Dataset", ["LAB", "Literature"], horizontal=True, key="cell_mode") if cell_mode == "LAB": try: from cell_growth_lab_gui import show_app as show_lab_cells show_lab_cells() except ImportError as e: st.error(f"Cell Growth Lab module not available: {e}") st.info("This module may not be available in the cloud deployment.") else: try: from cell_growth_literature_gui import show_app as show_lit_cells show_lit_cells() except ImportError as e: st.error(f"Cell Growth Literature module not available: {e}") st.info("This module may not be available in the cloud deployment.") elif page == "🔬 Morphology": # Morphology tracking with LAB/Literature toggle morph_mode = st.sidebar.radio("Dataset", ["LAB", "Literature"], horizontal=True, key="morph_mode") if morph_mode == "LAB": try: from morphology_lab_gui import show_app as show_lab_morph show_lab_morph() except ImportError as e: st.error(f"Morphology Lab module not available: {e}") st.info("This module may not be available in the cloud deployment.") else: try: from morphology_literature_gui import show_app as show_lit_morph show_lit_morph() except ImportError as e: st.error(f"Morphology Literature module not available: {e}") st.info("This module may not be available in the cloud deployment.") elif page == "📚 Lit Review Tracker": try: from lit_review_tracker import show_app as show_tracker show_tracker() except ImportError as e: st.error(f"Literature Review Tracker module not available: {e}") st.info("This module may not be available in the cloud deployment.") # Add literature integration status try: from literature_integration import get_literature_review_summary st.markdown("---") st.subheader("🔗 Literature Integration Status") summary = get_literature_review_summary() col1, col2, col3, col4 = st.columns(4) with col1: st.metric("Total Papers", summary["total_tracked_papers"]) with col2: st.metric("With Data", summary["papers_with_data"]) with col3: st.metric("Auto-Generated", summary["auto_generated_papers"]) with col4: total_data = summary["total_hydrogels_logged"] + summary["total_cell_runs_logged"] + summary["total_morphology_logged"] st.metric("Total Entries", total_data) if summary["papers_by_status"]: st.markdown("**Status Breakdown:**") for status, count in summary["papers_by_status"].items(): st.write(f"• {status.replace('_', ' ').title()}: {count}") if summary["recent_activity"]: st.markdown("**Recent Activity:**") for activity in summary["recent_activity"][:3]: st.caption(f"• {activity['author']} ({activity['year']}) - {activity['title']}") except ImportError: st.caption("ℹ️ Literature integration status not available") except Exception as e: st.caption(f"ℹ️ Literature integration status error: {e}") elif page == "📂 Import CSV": try: from csv_importer import show_csv_importer show_csv_importer() except ImportError as e: st.error(f"CSV Importer module not available: {e}") st.info("This module may not be available in the cloud deployment.") elif page == "📋 Export Data": show_export_page() elif page == "🧪 Media Tracker": try: from media_formulation_tracker import show_app show_app() except ImportError as e: st.error(f"Media Formulation Tracker module not available: {e}") st.info("This module may not be available in the cloud deployment.") elif page == "🔄 Sync Manager": try: from sync_manager import show_sync_app show_sync_app() except ImportError as e: st.error(f"Sync Manager module not available: {e}") st.info("This module may not be available in the cloud deployment.") elif page == "🤖 AI Ecosystem": # AI Ecosystem with subpages ai_page = st.sidebar.radio( "AI Components", ["🏠 AI Overview", "🔮 Recipe Optimizer", "📊 Batch Analysis", "🧠 Model Training", "🔍 Inference Tools", "📈 Performance Metrics"], key="ai_ecosystem_page" ) if ai_page == "🏠 AI Overview": show_ai_ecosystem_overview() elif ai_page == "🔮 Recipe Optimizer": try: from unified_app import show_ai_optimizer_page, load_models clf, reg = load_models() show_ai_optimizer_page(clf, reg, codebook) except ImportError as e: st.error(f"AI Recipe Optimizer module not available: {e}") st.info("This module may not be available in the cloud deployment.") elif ai_page == "📊 Batch Analysis": try: from unified_app import show_batch_analysis_page, load_models clf, reg = load_models() show_batch_analysis_page(clf, reg) except ImportError as e: st.error(f"Batch Analysis module not available: {e}") st.info("This module may not be available in the cloud deployment.") elif ai_page == "🧠 Model Training": show_ai_model_training_page() elif ai_page == "🔍 Inference Tools": show_ai_inference_tools_page() elif ai_page == "📈 Performance Metrics": show_ai_performance_metrics_page() # ============================================================================ # AI ECOSYSTEM FUNCTIONS # ============================================================================ def show_ai_ecosystem_overview(): """Show overview of all AI components and capabilities.""" st.title("🤖 AI Ecosystem Overview") st.markdown(""" ## 🧠 GelPredict AI/ML System GelPredict includes a comprehensive AI ecosystem designed to predict and optimize ECM gelation experiments. """) # Model Status st.subheader("📊 Current Model Status") try: from unified_app import load_models clf, reg = load_models() col1, col2 = st.columns(2) with col1: if clf is not None: st.success("✅ **Classification Model**: Loaded and ready") st.caption("Predicts gelation probability (gel/no-gel)") else: st.warning("⚠️ **Classification Model**: Not trained") st.caption("Train with `python src/train_baseline.py`") with col2: if reg is not None: st.success("✅ **Regression Model**: Loaded and ready") st.caption("Predicts time-to-gelation") else: st.info("ℹ️ **Regression Model**: Optional") st.caption("Provides gelation time estimates") except Exception as e: st.error(f"Could not load models: {e}") # AI Components Overview st.subheader("🔧 AI Components") components = [ { "name": "🔮 Recipe Optimizer", "description": "Real-time recipe optimization using grid search over pH, ionic strength, and temperature", "features": ["P(gel) predictions", "Time-to-gelation estimates", "Alternative conditions", "Save recommendations"] }, { "name": "📊 Batch Analysis", "description": "AI-powered analysis of experimental batches and performance comparison", "features": ["Batch effect analysis", "Failure mode prediction", "Performance metrics", "Cross-validation"] }, { "name": "🧠 Model Training", "description": "Automated training pipeline for classification and regression models", "features": ["Data preprocessing", "Cross-validation", "Feature engineering", "Model persistence"] }, { "name": "🔍 Inference Tools", "description": "Command-line and API tools for batch predictions and optimization", "features": ["CLI predictions", "JSON output", "Grid search", "Utility scoring"] }, { "name": "📈 Performance Metrics", "description": "Comprehensive model evaluation and performance tracking", "features": ["ROC-AUC scores", "R² metrics", "MAE analysis", "Calibration plots"] } ] for component in components: with st.expander(f"**{component['name']}**"): st.write(component['description']) st.markdown("**Features:**") for feature in component['features']: st.markdown(f"• {feature}") # Quick Actions st.subheader("🚀 Quick Actions") col1, col2, col3 = st.columns(3) with col1: if st.button("🔮 Get Recipe Recommendation", use_container_width=True): st.session_state.ai_page = "🔮 Recipe Optimizer" st.rerun() with col2: if st.button("📊 Analyze Batches", use_container_width=True): st.session_state.ai_page = "📊 Batch Analysis" st.rerun() with col3: if st.button("🧠 Train Models", use_container_width=True): st.session_state.ai_page = "🧠 Model Training" st.rerun() # Data Requirements st.subheader("📋 Data Requirements") st.markdown(""" **To enable AI predictions, you need:** ✅ **Minimum 20-30 experiments** (mix of successful and failed gels) ✅ **12 core features** (protein concentration, pH, conductivity, etc.) ✅ **Binary outcomes** (gel_binary: 0/1) ✅ **Time-to-gelation** (for regression model) **Optional but recommended:** 🔸 **Batch metadata** (batch_id, family, donor_id) 🔸 **Failure documentation** (failure_mode, suspected_cause) 🔸 **Advanced assays** (hydroxyproline, GAG content, viscosity) 🔸 **Quality metrics** (UV ratios, SDS-PAGE data) """) # Training Instructions with st.expander("🎓 How to Train Your First AI Model"): st.markdown(""" ### Step 1: Collect Data 1. Enter experimental data using the **📝 New Data Entry** forms 2. Include both successful and failed gelation attempts 3. Document failure modes and suspected causes ### Step 2: Export Training Data 1. Go to **📋 Export Data** 2. Download the **Training Dataset (CSV)** 3. Save as `data/ecm_runs.csv` ### Step 3: Train Models ```bash python src/train_baseline.py ``` ### Step 4: Use AI Predictions 1. Refresh this page to see updated model status 2. Use **🔮 Recipe Optimizer** for recommendations 3. Run experiments based on AI suggestions 4. Record outcomes to improve the model """) def show_ai_model_training_page(): """Show model training interface and instructions.""" st.title("🧠 AI Model Training") st.markdown(""" ## 📊 Training Pipeline GelPredict uses automated machine learning to train both classification and regression models from your experimental data. """) # Current training data status st.subheader("📋 Training Data Status") try: df_wells = read_wells(use_effective_view=True) if df_wells.empty: st.warning("⚠️ No experimental data found. Enter some experiments first!") return # Count experiments with required data has_gel_binary = len(df_wells[df_wells['gel_binary'].notna()]) has_time_to_halfmax = len(df_wells[df_wells['time_to_halfmax_min'].notna()]) has_required_features = len(df_wells[df_wells['ecm_total_protein_mgml'].notna()]) col1, col2, col3 = st.columns(3) with col1: st.metric("Total Experiments", len(df_wells)) with col2: st.metric("With Gel Outcomes", has_gel_binary) with col3: st.metric("With Timing Data", has_time_to_halfmax) # Check if ready for training if has_gel_binary >= 20 and has_required_features >= 20: st.success("✅ **Ready for training!** You have sufficient data.") elif has_gel_binary >= 10: st.warning("⚠️ **Minimum data available.** Consider collecting more experiments for better performance.") else: st.error("❌ **Insufficient data.** Need at least 20 experiments with gel outcomes.") except Exception as e: st.error(f"Error checking training data: {e}") # Training instructions st.subheader("🎯 Training Instructions") st.markdown(""" ### Option 1: Export and Train Manually 1. **Export your data**: - Go to **📋 Export Data** - Download **Training Dataset (CSV)** - Save as `data/ecm_runs.csv` 2. **Run training**: ```bash python src/train_baseline.py ``` 3. **Check results**: - Models saved to `models/` directory - Check console for performance metrics ### Option 2: Command Line Training ```bash # Train with default settings python src/train_baseline.py # Train with custom CSV file python src/train_baseline.py --csv data/my_data.csv # Check model performance python src/infer_recipe.py --json inputs.json ``` """) # Model architecture st.subheader("🏗️ Model Architecture") st.markdown(""" **Classification Model (Gel/No-Gel)**: - **Algorithm**: Logistic Regression with Isotonic Calibration - **Features**: 12 core experimental parameters - **Output**: Probability of successful gelation (0-1) - **Evaluation**: ROC-AUC, Average Precision, F1-Score **Regression Model (Time-to-Gelation)**: - **Algorithm**: Random Forest Regressor (300 trees) - **Features**: Same 12 parameters - **Output**: Estimated time to half-maximum gelation (minutes) - **Evaluation**: R², Mean Absolute Error """) # Feature importance st.subheader("📊 Feature Engineering") st.markdown(""" **Core Features Used**: - `ecm_total_protein_mgml` - Total protein concentration - `pre_pH` - Initial pH before neutralization - `pre_conductivity_mS` - Conductivity measurements - `temp_incubation_C` - Incubation temperature - `uv_ratio_A220_A280` - UV absorbance ratio - `sds_smear_index` - SDS-PAGE degradation proxy - `sds_alpha_ratio` - Collagen chain ratio - `target_pH` - Target neutralization pH - `NaCl_mM_added` - Additional NaCl concentration - `CaCl2_mM_added` - CaCl2 concentration - `DMEM_percent` - DMEM media percentage - `PBS_10x_uL_per_mL` - PBS volume added """) def show_ai_inference_tools_page(): """Show command-line inference tools and usage.""" st.title("🔍 AI Inference Tools") st.markdown(""" ## 💻 Command-Line AI Tools GelPredict provides powerful command-line tools for batch predictions and recipe optimization. """) # CLI Tools st.subheader("🛠️ Available Tools") tools = [ { "name": "`src/infer_recipe.py`", "description": "Single recipe optimization and prediction", "usage": "python src/infer_recipe.py --json inputs.json", "output": "JSON with recommended recipe and predictions" }, { "name": "`src/train_baseline.py`", "description": "Train classification and regression models", "usage": "python src/train_baseline.py --csv data/ecm_runs.csv", "output": "Trained models saved to models/ directory" }, { "name": "`app/streamlit_app.py`", "description": "Standalone AI prediction interface", "usage": "streamlit run app/streamlit_app.py", "output": "Web interface for real-time predictions" } ] for tool in tools: with st.expander(f"**{tool['name']}**"): st.write(tool['description']) st.code(tool['usage'], language="bash") st.caption(f"Output: {tool['output']}") # Input format st.subheader("📝 Input Format") st.markdown(""" ### JSON Input File (`inputs.json`) ```json { "ecm_total_protein_mgml": 7.5, "pre_pH": 4.2, "pre_conductivity_mS": 3.1, "temp_incubation_C": 37.0, "uv_ratio_A220_A280": 5.2, "sds_smear_index": 0.3, "sds_alpha_ratio": 0.9, "DMEM_percent": 0.0, "PBS_10x_uL_per_mL": 0.0, "NaCl_mM_added": 120.0, "CaCl2_mM_added": 0.0, "target_pH": 7.2 } ``` """) # Example usage st.subheader("🎯 Example Usage") st.markdown(""" ### 1. Create Input File ```bash # Create inputs.json with your ECM batch characteristics echo '{ "ecm_total_protein_mgml": 7.5, "pre_pH": 4.2, "pre_conductivity_mS": 3.1, "temp_incubation_C": 37.0, "uv_ratio_A220_A280": 5.2, "sds_smear_index": 0.3, "sds_alpha_ratio": 0.9, "DMEM_percent": 0.0, "PBS_10x_uL_per_mL": 0.0, "NaCl_mM_added": 120.0, "CaCl2_mM_added": 0.0, "target_pH": 7.2 }' > inputs.json ``` ### 2. Run Optimization ```bash python src/infer_recipe.py --json inputs.json ``` ### 3. Interpret Results ```json { "recommended": { "target_pH": 7.35, "PBS_10x_uL_per_mL": 12.5, "temp_incubation_C": 37.0 }, "predictions": { "P_gel": 0.847, "t_half_min": 18.3, "utility": 0.801 } } ``` """) # Batch processing st.subheader("📦 Batch Processing") st.markdown(""" ### Process Multiple Batches ```bash # Create multiple input files for i in {1..10}; do python src/infer_recipe.py --json batch_${i}.json > results_${i}.json done # Combine results cat results_*.json > all_recommendations.json ``` ### Integration with Data Pipeline ```bash # Export data → Train → Predict → Update database python src/train_baseline.py python src/infer_recipe.py --json new_batch.json # Use results to populate database with predictions ``` """) def show_ai_performance_metrics_page(): """Show model performance metrics and evaluation.""" st.title("📈 AI Performance Metrics") st.markdown(""" ## 📊 Model Evaluation Track and analyze the performance of your AI models with comprehensive metrics. """) # Check if models exist models_dir = Path("models") clf_path = models_dir / "gel_classifier.joblib" reg_path = models_dir / "thalf_regressor.joblib" if not clf_path.exists(): st.warning("⚠️ No trained models found. Train models first using the Model Training page.") return try: import joblib clf = joblib.load(clf_path) reg = joblib.load(reg_path) if reg_path.exists() else None st.success("✅ Models loaded successfully!") # Model info st.subheader("🧠 Model Information") col1, col2 = st.columns(2) with col1: st.markdown("**Classification Model**") st.caption(f"Algorithm: {type(clf['model']).__name__}") st.caption(f"Features: {len(clf['features'])} parameters") st.caption("Purpose: Predict gelation probability") with col2: if reg: st.markdown("**Regression Model**") st.caption(f"Algorithm: {type(reg['model']).__name__}") st.caption(f"Features: {len(reg['features'])} parameters") st.caption("Purpose: Predict time-to-gelation") else: st.info("Regression model not available") # Performance metrics st.subheader("📊 Performance Metrics") # Get training data for evaluation df_wells = read_wells(use_effective_view=True) if df_wells.empty: st.warning("No data available for evaluation") return # Classification metrics st.markdown("### Classification Model Performance") df_cls = df_wells.dropna(subset=['gel_binary']) if len(df_cls) >= 4: # Simulate predictions (in real implementation, you'd load actual metrics) st.info("💡 **Note**: Actual performance metrics are computed during training.") st.markdown(""" **Typical Performance**: - **ROC-AUC**: 0.75-0.90 (depending on data quality) - **Average Precision**: 0.70-0.85 - **F1-Score**: 0.65-0.80 **Interpretation**: - ROC-AUC > 0.8: Good discrimination - AP > 0.7: Good precision-recall balance - F1 > 0.7: Good overall performance """) else: st.warning("Insufficient data for classification evaluation") # Regression metrics if reg: st.markdown("### Regression Model Performance") df_reg = df_wells.dropna(subset=['time_to_halfmax_min', 'gel_binary']) df_reg_ok = df_reg[df_reg['gel_binary'] == 1] if len(df_reg_ok) >= 5: st.info("💡 **Note**: Actual performance metrics are computed during training.") st.markdown(""" **Typical Performance**: - **R²**: 0.60-0.85 (depending on data quality) - **MAE**: 5-15 minutes - **RMSE**: 8-20 minutes **Interpretation**: - R² > 0.7: Good predictive power - MAE < 10 min: Accurate timing predictions - RMSE < 15 min: Low prediction error """) else: st.warning("Insufficient successful gels for regression evaluation") # Feature importance st.subheader("🔍 Feature Importance") st.markdown(""" **Key Features for Gelation Prediction**: 1. **Protein Concentration** - Primary driver of gel strength 2. **pH Conditions** - Critical for neutralization 3. **Ionic Strength** - Affects gelation kinetics 4. **Temperature** - Influences gelation rate 5. **UV Ratios** - Protein quality indicators 6. **SDS-PAGE Metrics** - Degradation assessment **Model Interpretability**: - Feature importance scores available in trained models - Partial dependence plots show parameter effects - SHAP values explain individual predictions """) # Model validation st.subheader("✅ Model Validation") st.markdown(""" **Validation Strategy**: - **Train/Test Split**: 75% training, 25% testing - **Cross-Validation**: 5-fold CV for robust estimates - **Batch Validation**: Holdout batches for generalization - **Time-based Split**: Recent data for temporal validation **Quality Checks**: ✅ **Data Quality**: Missing values, outliers, consistency ✅ **Feature Engineering**: Proper scaling, encoding ✅ **Model Calibration**: Probability calibration ✅ **Overfitting**: Training vs. validation performance """) # Recommendations st.subheader("💡 Model Improvement Recommendations") st.markdown(""" **To Improve Performance**: 1. **Collect More Data**: - Aim for 50+ experiments for robust training - Include diverse ECM sources and conditions - Document failure modes systematically 2. **Feature Engineering**: - Add proteomics data (hydroxyproline, GAG content) - Include rheological measurements - Add batch metadata (donor, processing details) 3. **Advanced Models**: - Try ensemble methods (XGBoost, LightGBM) - Implement deep learning for complex patterns - Add physics-informed constraints 4. **Validation**: - Use stratified sampling for balanced splits - Implement time-series validation - Test on completely new ECM sources """) except Exception as e: st.error(f"Error loading models: {e}") # ============================================================================ # VISUAL QC HELPERS # ============================================================================ def render_plate_heatmap(plate_id: str, date_str: Optional[str] = None): """ Render a plate heatmap showing gel_strength_score_0to3 for visual QC. Args: plate_id: Plate ID to visualize date_str: Optional date filter (YYYY-MM-DD) """ if not plate_id: st.info("Enter a plate_id to view heatmap.") return g = get_plate_geometry(plate_id) if not g: st.info(f"Plate '{plate_id}' not registered. Register it first in Plates Registry.") return rows, max_cols = g # Pull wells for this plate (optionally same date) filters = {"plate_id": plate_id} df = read_wells(filters, use_effective_view=True) if date_str: df = df[df["date"] == date_str] if df.empty: st.warning(f"No wells found for plate '{plate_id}'" + (f" on {date_str}" if date_str else "")) return # Build grid of gel_strength_score_0to3 (NaN → -1) r_index = {ch: i for i, ch in enumerate(rows)} grid = np.full((len(rows), int(max_cols)), -1.0) for _, r in df.iterrows(): if pd.isna(r.get("row")) or pd.isna(r.get("col")): continue rr = str(r["row"]) cc = int(r["col"]) if rr in r_index and 1 <= cc <= int(max_cols): val = r.get("gel_strength_score_0to3") grid[r_index[rr], cc - 1] = -1 if pd.isna(val) else float(val) # Create heatmap fig, ax = plt.subplots(figsize=(min(10, 0.6 * int(max_cols) + 2), min(8, 0.4 * len(rows) + 2))) cax = ax.imshow(grid, aspect="auto", interpolation="nearest", cmap="RdYlGn", vmin=-1, vmax=3) ax.set_xticks(range(int(max_cols))) ax.set_xticklabels([str(i) for i in range(1, int(max_cols) + 1)], rotation=0) ax.set_yticks(range(len(rows))) ax.set_yticklabels(list(rows)) ax.set_xlabel("Column") ax.set_ylabel("Row") title = f"Plate {plate_id} — Gel Strength" if date_str: title += f" ({date_str})" ax.set_title(title) cbar = fig.colorbar(cax, ax=ax) cbar.set_label("Gel Strength (−1=missing, 0-3=score)") st.pyplot(fig) plt.close(fig) # Show summary stats valid_scores = grid[grid >= 0] if len(valid_scores) > 0: col1, col2, col3, col4 = st.columns(4) col1.metric("Wells tested", len(valid_scores)) col2.metric("Mean strength", f"{valid_scores.mean():.2f}") col3.metric("Gelled (≥1)", f"{(valid_scores >= 1).sum()}") col4.metric("Strong (≥2)", f"{(valid_scores >= 2).sum()}") # ============================================================================ # UI HELPER: MEASUREMENT PROTOCOLS # ============================================================================ def show_measurement_protocol(field_name: str, table: str = "wells_master_v4"): """ Display device and method information for a field if available in FIELD_SPEC. Args: field_name: Field name to show protocol for table: Table name (default: wells_master_v4) """ if table not in FIELD_SPEC or field_name not in FIELD_SPEC[table]: return field_spec = FIELD_SPEC[table][field_name] device = field_spec.get("device") method = field_spec.get("method") if device or method: with st.expander(f"ℹ️ How to measure {field_name}", expanded=False): if device: st.markdown(f"**Device:** {device}") if method: st.markdown("**Protocol:**") st.text(method) # ============================================================================ # UI PAGE FUNCTIONS # ============================================================================ def show_new_entry_form(codebook): st.header("Create New Well Entry") # Initialize session state for selected wells if 'selected_wells' not in st.session_state: st.session_state.selected_wells = [] # Metadata section (regular inputs - not in form) st.subheader("📋 Metadata") # First row: Date, Operator, Family (horizontal) 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: family = st.selectbox( "ECM Family*", options=[""] + codebook['family'], index=2 if "decECM" in codebook['family'] else 0 # Default to "decECM" ) # Commercial Product Checkbox (needs to come early) is_commercial = st.checkbox( "🏭 Commercial/Ready-Made Product", value=False, help="Check if this is a commercial product (e.g., Matrigel, PureCol, Cultrex, Geltrex)" ) # Commercial Product Details (show only if commercial) if is_commercial: st.markdown("**🏷️ Commercial Product Details**") st.caption("For commercial products, use manufacturer's lot number as Batch ID") # Common products dropdown + custom option COMMON_COMMERCIAL_PRODUCTS = { "Matrigel": {"vendor": "Corning", "family_hint": "collagen"}, "Matrigel GFR": {"vendor": "Corning", "family_hint": "collagen"}, "Cultrex": {"vendor": "R&D Systems", "family_hint": "collagen"}, "Cultrex BME": {"vendor": "R&D Systems", "family_hint": "collagen"}, "Geltrex": {"vendor": "Thermo Fisher", "family_hint": "collagen"}, "PureCol": {"vendor": "Advanced BioMatrix", "family_hint": "collagen"}, "VitroCol": {"vendor": "Advanced BioMatrix", "family_hint": "collagen"}, "Rat Tail Collagen I": {"vendor": "Corning", "family_hint": "collagen"}, "Collagen I": {"vendor": "Invitrogen", "family_hint": "collagen"}, "Custom/Other": {"vendor": "", "family_hint": ""} } comm_col1, comm_col2 = st.columns(2) with comm_col1: product_name = st.selectbox( "Product Name*", options=[""] + list(COMMON_COMMERCIAL_PRODUCTS.keys()), help="Select a common product or choose Custom/Other" ) if product_name and product_name != "Custom/Other": # Auto-fill vendor vendor = COMMON_COMMERCIAL_PRODUCTS[product_name]["vendor"] else: vendor = st.text_input("Vendor Name*", help="e.g., Corning, Advanced BioMatrix, R&D Systems") with comm_col2: if product_name == "Custom/Other": custom_product = st.text_input("Custom Product Name*") else: custom_product = None catalog_num = st.text_input("Catalog/Part Number", help="e.g., 354234, 3432-005-01") website = st.text_input("Company Website", placeholder="https://www.corning.com", help="Company website URL") lot_num = st.text_input("Lot/Batch Number*", help="From manufacturer label - will be used as Batch ID") st.caption("⚠️ Note: ECM Provenance and Processing Protocol are typically N/A for commercial products") else: # Initialize variables if not commercial product_name = None vendor = None custom_product = None catalog_num = None website = None lot_num = None # ECM Provenance (species and tissue origin) - BEFORE batch_id generation st.markdown("**🧬 ECM Provenance** (species and tissue origin)") if is_commercial: st.caption("⚠️ For commercial products: check product datasheet for source species/tissue if available") prov_col1, prov_col2 = st.columns(2) with prov_col1: dec_species = st.selectbox( "Origin species*" if family == "decECM" else "Origin species", [""] + codebook['species'], index=1 if "human" in codebook['species'] else 0, # Default to "human" help="Required for decECM, optional for other ECM types. For commercial: see datasheet." ) with prov_col2: dec_tissue = st.selectbox( "Source tissue/organ*" if family == "decECM" else "Source tissue/organ", [""] + codebook['tissues'], index=1 if "mammary" in codebook['tissues'] else 0, # Default to "mammary" help="Required for decECM, optional for other ECM types. For commercial: see datasheet." ) st.markdown("---") # ========== CITATION INTEGRATION ========== st.subheader("📚 Literature Integration (Optional)") st.caption("Link this lab experiment to relevant literature for context and comparison") # Citation parser section st.markdown("### 🔍 Quick Add from Citation") st.caption("Paste full citation to auto-extract fields") citation_input = st.text_area( "Paste Citation", placeholder="""Example: Smith J, Jones K. (2023). Decellularized mammary ECM promotes organoid formation. Biomaterials. DOI: 10.1016/j.biomaterials.2023.001 Or: Smith et al. Decellularized mammary ECM promotes organoid formation. Biomaterials, 2023. https://doi.org/10.1016/j.biomaterials.2023.001""", height=100, key="lab_citation_paste" ) if st.button("🔍 Parse Citation", type="secondary", key="lab_parse"): if citation_input: try: from literature_gui import parse_citation parsed = parse_citation(citation_input) st.session_state["lab_parsed_citation"] = parsed # Show what was extracted st.success("✅ Citation parsed! Fields auto-filled below:") col_p1, col_p2, col_p3 = st.columns(3) with col_p1: if parsed.get("first_author"): st.info(f"Author: {parsed['first_author']}") with col_p2: if parsed.get("publication_year"): st.info(f"Year: {parsed['publication_year']}") with col_p3: if parsed.get("doi"): st.info(f"DOI: {parsed['doi'][:20]}...") if parsed.get("paper_title"): st.info(f"Title: {parsed['paper_title'][:80]}...") except Exception as e: st.error(f"Failed to parse citation: {e}") # Get parsed values if available parsed = st.session_state.get("lab_parsed_citation", {}) # Source tracking fields st.markdown("**📖 Source Information**") source_col1, source_col2, source_col3 = st.columns(3) with source_col1: first_author = st.text_input( "First Author (optional)", value=parsed.get("first_author", "") or "", placeholder="Smith", help="Last name of first author for reference" ) publication_year = st.number_input( "Publication Year (optional)", min_value=1950, max_value=2030, value=parsed.get("publication_year") or None, step=1, help="Year of publication for reference" ) with source_col2: paper_title = st.text_input( "Paper Title (optional)", value=parsed.get("paper_title", "") or "", placeholder="ECM gelation kinetics", help="Brief description or title for reference" ) source_label = st.text_input( "Source Label (optional)", value=parsed.get("source_label", "") or "", placeholder="Smith2023_Fig2A", help="Short reference ID" ) with source_col3: doi = st.text_input( "DOI (optional)", value=parsed.get("doi", "") or "", placeholder="10.1234/journal.2023.0001", help="Digital Object Identifier" ) citation = st.text_area("Full Citation (optional)", height=60, placeholder="Smith J, Doe A, et al. (2023). Journal of ECM Research. 15:123-145.", help="Complete citation for reference") st.markdown("---") # Batch & Gelation ID section (auto-generated for lab-made) st.markdown("**🧪 Batch & Gelation Identifiers**") # For commercial products, batch_id comes from lot number if is_commercial and lot_num: batch_id = lot_num st.info(f"📦 Batch ID (from lot#): **{batch_id}**") else: # Auto-generate batch_id for lab-made ECM if family and dec_species and dec_tissue: suggested_batch_id = generate_batch_id(family, dec_species, dec_tissue, date_input, is_commercial) batch_id = st.text_input( "Batch ID*", value=suggested_batch_id, help="Auto-generated from family-species-tissue-date. Can override." ) else: batch_id = st.text_input( "Batch ID*", help="Fill in Family, Species, and Tissue above for auto-generation" ) # Auto-generate gelation_id if batch_id: next_seq = get_next_gelation_sequence(batch_id, date_input) suggested_gelation_id = generate_gelation_id(batch_id, date_input, next_seq) gel_col1, gel_col2 = st.columns([3, 1]) with gel_col1: gelation_id = st.text_input( "Gelation ID*", value=suggested_gelation_id, help="Auto-generated. Multiple gelations can share same batch_id." ) with gel_col2: if st.button("🔄 Next Seq"): # Increment sequence current_parts = gelation_id.split("-") if len(current_parts) > 0 and current_parts[-1].isdigit(): new_seq = int(current_parts[-1]) + 1 st.session_state["custom_gelation_seq"] = new_seq st.rerun() st.caption(f"💡 Same batch → different gelation IDs for protocol variants") else: gelation_id = "" st.warning("⚠️ Set Batch ID first to auto-generate Gelation ID") # Plate ID Selection (reuse or create new) st.markdown("**🧫 Plate Selection**") st.caption("Physical plates can be reused across days and batches") # Load recent plates recent_plates = get_recent_plates(limit=50) plate_mode = st.radio( "Plate Option", ["Reuse Existing Plate", "Create New Plate"], horizontal=True, help="Reuse a physical plate for new experiments or generate a new plate ID" ) if plate_mode == "Reuse Existing Plate" and recent_plates: # Show recent plates with usage stats st.caption("**Select from recently used plates:**") plate_options = [""] + [ f"{p['plate_id']} (Used: {p['first_use']} to {p['last_use']}, {p['n_wells']} wells, {p['n_batches']} batches)" for p in recent_plates ] plate_ids_list = [""] + [p['plate_id'] for p in recent_plates] selected_idx = st.selectbox( "Select Plate*", range(len(plate_options)), format_func=lambda i: plate_options[i] ) plate_id = plate_ids_list[selected_idx] if selected_idx > 0 else "" if plate_id: # Show plate history plate_info = recent_plates[selected_idx - 1] st.info(f""" 📊 **Plate History:** - First used: {plate_info['first_use']} - Last used: {plate_info['last_use']} - Total wells: {plate_info['n_wells']} - Batches used: {plate_info['n_batches']} - Gelations: {plate_info['n_gelations']} """) st.success(f"✅ Reusing plate: **{plate_id}**") elif plate_mode == "Reuse Existing Plate" and not recent_plates: st.warning("No existing plates found. Create a new one below.") plate_id = "" else: # Create New Plate st.caption("**Generate new physical plate ID:**") new_plate_col1, new_plate_col2, new_plate_col3 = st.columns([2, 2, 1]) with new_plate_col1: plate_type = st.selectbox( "Plate Type*", ["6", "12", "24", "48", "96", "384"], index=4, # Default to 96-well help="Number of wells in the physical plate" ) with new_plate_col2: suggested_plate_id = generate_plate_id(plate_type) plate_id = st.text_input( "Plate ID*", value=suggested_plate_id, help="Auto-generated. Can override." ) with new_plate_col3: if st.button("🔄 Next"): # Increment sequence parts = plate_id.split("-") if len(parts) == 3 and parts[-1].isdigit(): new_seq = int(parts[-1]) + 1 plate_id = f"{parts[0]}-{parts[1]}-{new_seq:03d}" st.rerun() st.success(f"✅ New plate: **{plate_id}**") # Load plate geometry (must happen before we use row_labels/max_cols) if plate_id: ensure_default_plate_if_unset(plate_id) geom = get_plate_geometry(plate_id) if geom: row_labels, max_cols = geom else: row_labels, max_cols = "ABCDEFGH", 12 # Default fallback else: row_labels, max_cols = "ABCDEFGH", 12 # Default if no plate selected # Donor ID donor_id = st.text_input("Donor ID (optional)") # Replicate ID replicate_id = st.number_input("Replicate ID", min_value=1, value=1) # Auto-generate semantic ID preview (using first selected well if available) if family and batch_id and st.session_state.selected_wells: first_well = st.session_state.selected_wells[0] preview_row = first_well[0] preview_col = int(first_well[1:]) preview_id = generate_semantic_id( family, batch_id, plate_id, preview_row, preview_col, replicate_id, species=dec_species, tissue=dec_tissue ) st.info(f"📝 Record ID preview: **{preview_id}**") st.caption("(Auto-generated from metadata above. Each selected well gets a unique ID.)") elif family and batch_id: st.info("📝 Fill in well positions above to see record ID preview") else: st.warning("⚠️ Fill in Family and Batch ID to generate record ID") # Inline plate geometry editor if plate_id: with st.expander("⚙️ Plate geometry (register / edit)", expanded=False): pg1, pg2 = st.columns([2,1]) with pg1: new_rows = st.text_input("Row labels", value=row_labels, help="Continuous string, e.g., ABCDEFGH") with pg2: new_cols = st.number_input("Max columns", min_value=1, max_value=48, value=int(max_cols)) desc = st.text_input("Description", value="") if st.button("💾 Save plate geometry"): try: upsert_plate_geometry(plate_id, new_rows.strip(), int(new_cols), description=(desc or None)) st.success("✅ Plate geometry saved.") # Refresh local vars row_labels, max_cols = new_rows.strip(), int(new_cols) except Exception as e: st.error(f"❌ Failed to save geometry: {e}") # Well selection (now that plate and geometry are defined) st.subheader("📍 Select Well Positions") st.caption(f"💡 Using plate **{plate_id or '(not selected)'}** with geometry: {row_labels} × {max_cols}") if not plate_id: st.warning("⚠️ Please select or create a plate above before selecting wells") else: # Well selection interface well_col1, well_col2, well_col3 = st.columns([2, 2, 1]) with well_col1: selected_row = st.selectbox("Select Row", options=[""] + list(row_labels), key="well_row", help=f"Available rows for {plate_id}: {row_labels}") with well_col2: selected_col = st.selectbox("Select Column", options=[""] + [str(i) for i in range(1, int(max_cols)+1)], key="well_col", help=f"Available columns: 1-{max_cols}") with well_col3: add_well = st.button("➕ Add", type="secondary") # Add well to selection if add_well and selected_row and selected_col: well_id = f"{selected_row}{selected_col}" if well_id not in st.session_state.selected_wells: st.session_state.selected_wells.append(well_id) st.rerun() else: st.warning(f"⚠️ Well {well_id} is already selected") # Display selected wells if st.session_state.selected_wells: st.write(f"**Selected Wells ({len(st.session_state.selected_wells)}):**") well_display_cols = st.columns(6) # Display wells in columns for i, well in enumerate(st.session_state.selected_wells): col_idx = i % 6 with well_display_cols[col_idx]: if st.button(f"❌ {well}", key=f"remove_{well}", help=f"Remove {well}"): st.session_state.selected_wells.remove(well) st.rerun() # Clear all button if st.button("🗑️ Clear All Wells"): st.session_state.selected_wells = [] st.rerun() else: st.info("👆 Select rows and columns above to add wells to this entry") st.markdown("---") # Visual separator st.subheader("🧊 Pre-Processing Tissue Storage") st.caption("⚠️ **BEFORE** any decellularization or ECM processing began (raw tissue storage)") st.info("💡 This is NOT the freeze-thaw decell technique (add that as a Protocol Step below). This tracks how the original tissue was stored.") # Pre-storage temperature and duration c1a, c1b = st.columns(2) with c1a: pre_storage_temp = st.selectbox("Storage temp (°C)", ["", "4°C (fridge)", "-20°C (freezer)", "-80°C (ultra-freezer)", "-196°C (LN2)", "Other"], help="Temperature at which tissue was stored before processing", key="pre_storage_temp") if pre_storage_temp == "Other": pre_storage_temp_custom = st.number_input("Custom temp (°C)", -200.0, 50.0, 0.0, 1.0, key="pre_storage_temp_custom") else: pre_storage_temp_custom = None unk_days = st.checkbox("Unknown", key="unk_pre_days", help="Check if not reported/unknown") pre_storage_days = st.number_input("Days stored", min_value=0, value=0, disabled=unk_days, help="Duration of storage at selected temperature") if unk_days: pre_storage_days = None with c1b: pre_storage_fresh_notes = st.text_input("Storage notes", placeholder="e.g., in PBS, in culture media", help="Optional: how was tissue stored?") # Frozen storage st.markdown("**Frozen Storage (long-term):**") c2, c3, c4 = st.columns(3) with c2: unk_frozen_months = st.checkbox("Unknown", key="unk_pre_frozen_mo", help="Check if not reported/unknown") pre_storage_duration_months = st.number_input("Frozen duration (months)", 0.0, 120.0, 0.0, 0.5, disabled=unk_frozen_months, help="How long tissue was stored frozen BEFORE starting processing") if unk_frozen_months: pre_storage_duration_months = None with c3: unk_freezer_temp = st.checkbox("Unknown", key="unk_pre_frz_temp", help="Check if not reported/unknown") pre_storage_temp_freezer = st.number_input("Freezer temp (°C)", -200.0, 0.0, -80.0, 10.0, disabled=unk_freezer_temp, help="Storage temp: -20°C (standard), -80°C (long-term), -196°C (LN2)") if unk_freezer_temp: pre_storage_temp_freezer = None with c4: pre_storage_frozen_in = st.text_input("Frozen in", placeholder="e.g., dry, in buffer, with cryoprotectant", help="Optional: what medium was tissue frozen in?") # Freeze-thaw cycles during storage/transport st.markdown("**Freeze-Thaw Cycles (during storage/transport):**") st.caption("💡 NOT the intentional freeze-thaw decell technique - this is accidental/transport cycles") ft1, ft2, ft3, ft4 = st.columns(4) with ft1: unk_pre_ft_cycles = st.checkbox("Unknown", key="unk_pre_ft_cyc", help="Check if not reported/unknown") pre_storage_freeze_cycles = st.number_input("# Cycles", min_value=0, value=0, disabled=unk_pre_ft_cycles, help="# times frozen then thawed during storage/shipping") if unk_pre_ft_cycles: 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"], help="How was tissue thawed each time?") with ft3: unk_thaw_dur = st.checkbox("Unk", key="unk_pre_thaw_dur", help="Unknown/not reported") pre_storage_thaw_duration_min = st.number_input("Thaw duration (min)", 0.0, 1000.0, 30.0, 5.0, disabled=unk_thaw_dur, help="Duration of each thaw phase") if unk_thaw_dur: pre_storage_thaw_duration_min = None with ft4: pre_storage_ft_notes = st.text_input("Freeze-thaw notes", placeholder="e.g., thawed in series of PBS washes, slow thaw at 4°C", help="Describe your thaw process") st.caption("📌 **Example 1:** Tissue excised, frozen dry at -80°C for 3 months, never thawed → Frozen duration: 3, Temp: -80°C, Cycles: 0") st.caption("📌 **Example 2:** Tissue frozen at -80°C, shipped on dry ice (thawed once during receipt), then refrozen → Cycles: 1, Thaw method: passive_room_temp") st.caption("📌 **Example 3 (Your workflow):** Frozen at -80°C, thawed via series of PBS washes before decell → Cycles: 1, Thaw method: buffer_wash_series, Notes: '3× PBS washes, 15min each'") st.caption("✅ **For literature:** Check 'Unknown' for parameters not reported in the paper") # Protocol Builder (OUTSIDE form - uses buttons) st.markdown("---") st.subheader("🔬 ECM Processing Protocol (Optional)") st.caption("Build your ECM preparation protocol step-by-step") # Initialize session state for processing steps if "proc_steps" not in st.session_state: st.session_state.proc_steps = [] # Buttons to add different step types st.caption("**Add Processing Steps:**") row1_cols = st.columns(6) with row1_cols[0]: if st.button("➕ Decell", key="add_decell_exp"): st.session_state.proc_steps.append({"type": "decell", "id": len(st.session_state.proc_steps)}) st.rerun() with row1_cols[1]: if st.button("➕ Wash", key="add_wash_exp"): st.session_state.proc_steps.append({"type": "wash", "id": len(st.session_state.proc_steps)}) st.rerun() with row1_cols[2]: if st.button("➕ Delipid", key="add_delipid_exp"): st.session_state.proc_steps.append({"type": "delipid", "id": len(st.session_state.proc_steps)}) st.rerun() with row1_cols[3]: if st.button("➕ Enzyme", key="add_enzyme_exp"): st.session_state.proc_steps.append({"type": "enzyme", "id": len(st.session_state.proc_steps)}) st.rerun() with row1_cols[4]: if st.button("➕ Homogenize", key="add_homog_exp"): st.session_state.proc_steps.append({"type": "homogenize", "id": len(st.session_state.proc_steps)}) st.rerun() with row1_cols[5]: if st.button("➕ Grind/Mill", key="add_grind_exp"): st.session_state.proc_steps.append({"type": "grind", "id": len(st.session_state.proc_steps)}) st.rerun() row2_cols = st.columns(6) with row2_cols[0]: if st.button("➕ Freeze-Thaw", key="add_freeze_exp"): st.session_state.proc_steps.append({"type": "freeze_thaw", "id": len(st.session_state.proc_steps)}) st.rerun() with row2_cols[1]: if st.button("➕ Lyophilize", key="add_lyoph_exp"): st.session_state.proc_steps.append({"type": "lyophilize", "id": len(st.session_state.proc_steps)}) st.rerun() with row2_cols[2]: if st.button("➕ Reconstitute", key="add_recon_exp"): st.session_state.proc_steps.append({"type": "reconstitute", "id": len(st.session_state.proc_steps)}) st.rerun() with row2_cols[3]: if st.button("➕ pH Adjust", key="add_ph_exp"): st.session_state.proc_steps.append({"type": "ph_adjust", "id": len(st.session_state.proc_steps)}) st.rerun() with row2_cols[4]: if st.button("➕ Dialysis", key="add_dialysis_exp"): st.session_state.proc_steps.append({"type": "dialysis", "id": len(st.session_state.proc_steps)}) st.rerun() with row2_cols[5]: if st.button("➕ Filtration", key="add_filter_exp"): st.session_state.proc_steps.append({"type": "filtration", "id": len(st.session_state.proc_steps)}) st.rerun() row3_cols = st.columns(6) with row3_cols[0]: if st.button("➕ Centrifuge", key="add_centrifuge_exp"): st.session_state.proc_steps.append({"type": "centrifuge", "id": len(st.session_state.proc_steps)}) st.rerun() with row3_cols[1]: if st.button("➕ Storage", key="add_storage_exp"): st.session_state.proc_steps.append({"type": "storage", "id": len(st.session_state.proc_steps)}) st.rerun() with row3_cols[2]: if st.button("➕ Other", key="add_other_exp"): st.session_state.proc_steps.append({"type": "other", "id": len(st.session_state.proc_steps)}) st.rerun() with row3_cols[5]: if st.button("🗑️ Clear All", key="clear_all_steps_exp"): st.session_state.proc_steps = [] st.rerun() if st.session_state.proc_steps: st.caption(f"**{len(st.session_state.proc_steps)} step(s) added**") # Display and edit each step processing_steps = [] for i, step in enumerate(st.session_state.proc_steps): with st.expander(f"Step {i+1}: {step['type'].title()}", expanded=True): col1, col2, col3 = st.columns([3, 3, 1]) if step["type"] == "decell": try: from shared_parameters import DECELL_AGENTS except ImportError: DECELL_AGENTS = ["Trypsin", "Collagenase", "Dispase", "Accutase", "Other"] dcol1, dcol2, dcol3, dcol4 = st.columns(4) with dcol1: reagent_sel = st.selectbox("Reagent", DECELL_AGENTS, key=f"decell_reag_sel_exp_{step['id']}") if reagent_sel == "Other": reagent = st.text_input("Specify reagent", placeholder="e.g., custom detergent", key=f"decell_reag_other_exp_{step['id']}") else: reagent = reagent_sel with dcol2: unk_conc = st.checkbox("Unk", key=f"unk_decell_conc_exp_{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_exp_{step['id']}") conc_unit = st.selectbox("Units", ["%","M","mM","mg/mL","v/v"], disabled=unk_conc, key=f"decell_unit_exp_{step['id']}") if unk_conc: conc_val, conc_unit = None, None with dcol3: unk_dur = st.checkbox("Unk", key=f"unk_decell_dur_exp_{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_exp_{step['id']}") if unk_dur: duration = None unk_temp = st.checkbox("Unk", key=f"unk_decell_temp_exp_{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_exp_{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_exp_{step['id']}", help="Unknown/not reported") changes = st.number_input("# Changes", 1, 100, 3, 1, disabled=unk_chg, key=f"decell_chg_exp_{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_exp_{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}) elif step["type"] == "wash": from shared_parameters import COMMON_BUFFERS wcol1, wcol2, wcol3, wcol4 = st.columns(4) with wcol1: solution_sel = st.selectbox("Solution", COMMON_BUFFERS + ["DI water"], key=f"wash_sol_sel_exp_{step['id']}") if solution_sel == "Other": solution = st.text_input("Specify solution", placeholder="e.g., custom buffer", key=f"wash_sol_other_exp_{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_exp_{step['id']}") conc_unit = st.selectbox("Units", ["x","M","mM","%","n/a"], key=f"wash_unit_exp_{step['id']}") with wcol3: washes = st.number_input("# Washes", 1, 20, 3, 1, key=f"wash_num_exp_{step['id']}") duration = st.number_input("Duration each (min)", 0.0, 500.0, 15.0, 5.0, key=f"wash_dur_exp_{step['id']}") with wcol4: temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"wash_temp_exp_{step['id']}", help="Wash temperature") notes = st.text_input("Notes (optional)", placeholder="e.g., shaking, flow rate", key=f"wash_notes_exp_{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}) elif step["type"] == "delipid": from shared_parameters import DELIPID_SOLVENTS dlcol1, dlcol2, dlcol3, dlcol4 = st.columns(4) with dlcol1: solvent_sel = st.selectbox("Solvent", DELIPID_SOLVENTS, key=f"delip_solv_sel_exp_{step['id']}") if solvent_sel == "Other": solvent = st.text_input("Specify solvent", placeholder="e.g., custom solvent", key=f"delip_solv_other_exp_{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_exp_{step['id']}") conc_unit = st.selectbox("Units", ["%","v/v"], key=f"delip_unit_exp_{step['id']}") with dlcol3: duration = st.number_input("Duration (hours)", 0.0, 100.0, 2.0, 0.25, key=f"delip_dur_exp_{step['id']}") temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"delip_temp_exp_{step['id']}", help="Room temp, fridge, etc.") with dlcol4: times = st.number_input("# Times", 1, 20, 3, 1, key=f"delip_times_exp_{step['id']}", help="Number of repetitions") notes = st.text_input("Notes (optional)", placeholder="e.g., vortex, solvent grade", key=f"delip_notes_exp_{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}) elif step["type"] == "enzyme": from shared_parameters import COMMON_ENZYMES ecol1, ecol2, ecol3, ecol4 = st.columns(4) with ecol1: enzyme_sel = st.selectbox("Enzyme", COMMON_ENZYMES, key=f"enz_name_sel_exp_{step['id']}") if enzyme_sel == "Other": enzyme = st.text_input("Specify enzyme", placeholder="e.g., custom enzyme", key=f"enz_name_other_exp_{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_exp_{step['id']}") units = st.selectbox("Units", ["mg/mL", "U/mL", "mg/g"], key=f"enz_units_exp_{step['id']}") with ecol3: duration = st.number_input("Duration (hours)", 0.0, 500.0, 48.0, 1.0, key=f"enz_dur_exp_{step['id']}") with ecol4: temp = st.number_input("Temp (°C)", 0.0, 50.0, 4.0, 1.0, key=f"enz_temp_exp_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., pH maintained, shaking speed", key=f"enz_notes_exp_{step['id']}") processing_steps.append({"type": "enzyme", "enzyme": enzyme, "concentration": conc, "conc_units": units, "duration_hours": duration, "temp_C": temp, "notes": notes or None}) elif step["type"] == "homogenize": from app.shared_parameters import COMMON_BUFFERS, COMMON_DILUENTS 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_exp_{step['id']}") if medium == "Other": medium = st.text_input("Specify medium", placeholder="e.g., 0.1M HCl", key=f"homog_medium_other_exp_{step['id']}") with hcol2: rpm = st.number_input("RPM", 0, 50000, 10000, 1000, key=f"homog_rpm_exp_{step['id']}") duration = st.number_input("Duration (min)", 0.0, 500.0, 5.0, 1.0, key=f"homog_dur_exp_{step['id']}") with hcol3: temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"homog_temp_exp_{step['id']}") passes = st.number_input("# Passes", 1, 20, 1, 1, key=f"homog_passes_exp_{step['id']}") with hcol4: volume = st.number_input("Volume (mL)", 0.0, 1000.0, 10.0, 1.0, key=f"homog_vol_exp_{step['id']}") ratio = st.text_input("Tissue:Medium ratio", placeholder="e.g., 1:10, 1:20", key=f"homog_ratio_exp_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., sterile conditions, ice bath", key=f"homog_notes_exp_{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}) elif step["type"] == "grind": gcol1, gcol2, gcol3, gcol4 = st.columns(4) with gcol1: method = st.selectbox("Method", ["mortar_pestle", "ball_mill", "cryomill", "other"], key=f"grind_method_exp_{step['id']}") if method == "other": method = st.text_input("Specify method", key=f"grind_method_other_exp_{step['id']}") with gcol2: duration = st.number_input("Duration (min)", 0.0, 500.0, 5.0, 1.0, key=f"grind_dur_exp_{step['id']}") with gcol3: temp = st.number_input("Temp (°C)", -200.0, 50.0, 4.0, 1.0, key=f"grind_temp_exp_{step['id']}") with gcol4: cycles = st.number_input("# Cycles", 1, 50, 1, 1, key=f"grind_cycles_exp_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., liquid nitrogen, sterile", key=f"grind_notes_exp_{step['id']}") processing_steps.append({"type": "grind", "method": method, "duration_min": duration, "temp_C": temp, "cycles": cycles, "notes": notes or None}) elif step["type"] == "freeze_thaw": ftcol1, ftcol2, ftcol3, ftcol4 = st.columns(4) with ftcol1: cycles = st.number_input("# Cycles", 1, 50, 3, 1, key=f"ft_cycles_exp_{step['id']}") with ftcol2: freeze_temp = st.number_input("Freeze temp (°C)", -200.0, 0.0, -80.0, 10.0, key=f"ft_ftemp_exp_{step['id']}") with ftcol3: thaw_temp = st.number_input("Thaw temp (°C)", 0.0, 50.0, 37.0, 1.0, key=f"ft_ttemp_exp_{step['id']}") with ftcol4: duration_cycle = st.number_input("Duration/cycle (min)", 0.0, 1000.0, 60.0, 5.0, key=f"ft_dur_exp_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., liquid nitrogen, water bath", key=f"ft_notes_exp_{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}) elif step["type"] == "lyophilize": with col1: unk_lyoph_dur = st.checkbox("Unk", key=f"unk_lyoph_dur_exp_{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_exp_{step['id']}") if unk_lyoph_dur: duration = None with col2: unk_lyoph_temp = st.checkbox("Unk", key=f"unk_lyoph_temp_exp_{step['id']}", help="Unknown/not reported") temp = st.number_input("Temp (°C)", -100.0, 0.0, -40.0, 5.0, disabled=unk_lyoph_temp, key=f"lyoph_temp_exp_{step['id']}") if unk_lyoph_temp: temp = None with col3: pressure = st.text_input("Pressure", placeholder="e.g., <0.1 mBar", key=f"lyoph_press_exp_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., ramp rate, condenser temp", key=f"lyoph_notes_exp_{step['id']}") processing_steps.append({"type": "lyophilize", "duration_hours": duration, "temp_C": temp, "pressure": pressure, "notes": notes or None}) elif step["type"] == "reconstitute": st.caption("💡 **Critical for concentration tracking:** Enter lyophilized weight and reconstitution volume to calculate final ECM concentration") from shared_parameters import COMMON_DILUENTS recol1, recol2, recol3, recol4 = st.columns(4) with recol1: solvent_sel = st.selectbox("Solvent", COMMON_DILUENTS, key=f"recon_solv_sel_exp_{step['id']}") if solvent_sel == "Other": solvent = st.text_input("Specify solvent", placeholder="e.g., custom buffer", key=f"recon_solv_other_exp_{step['id']}") else: solvent = solvent_sel with recol2: unk_lyoph_weight = st.checkbox("Unk", key=f"unk_recon_wt_exp_{step['id']}", help="Unknown/not reported") lyoph_weight_mg = st.number_input("Lyoph weight (mg)", 0.0, 10000.0, 100.0, 1.0, disabled=unk_lyoph_weight, key=f"recon_wt_exp_{step['id']}", help="Dry weight of lyophilized ECM powder") if unk_lyoph_weight: lyoph_weight_mg = None with recol3: unk_recon_vol = st.checkbox("Unk", key=f"unk_recon_vol_exp_{step['id']}", help="Unknown/not reported") recon_volume_mL = st.number_input("Recon volume (mL)", 0.0, 1000.0, 10.0, 0.1, disabled=unk_recon_vol, key=f"recon_vol_exp_{step['id']}", help="Volume of solvent added to reconstitute") if unk_recon_vol: recon_volume_mL = None with recol4: unk_recon_temp = st.checkbox("Unk", key=f"unk_recon_temp_exp_{step['id']}", help="Unknown/not reported") recon_temp = st.number_input("Temp (°C)", 0.0, 50.0, 4.0, 1.0, disabled=unk_recon_temp, key=f"recon_temp_exp_{step['id']}", help="Temperature during reconstitution/stirring") if unk_recon_temp: recon_temp = None # Calculate final concentration if lyoph_weight_mg and recon_volume_mL and lyoph_weight_mg > 0 and recon_volume_mL > 0: final_conc = lyoph_weight_mg / recon_volume_mL st.success(f"✅ **Final concentration: {final_conc:.2f} mg/mL**") notes = st.text_input("Notes (optional)", placeholder="e.g., stirred overnight at 4°C, with pepsin 0.1 mg/mL", key=f"recon_notes_exp_{step['id']}", help="Pepsin digestion often happens here!") processing_steps.append({"type": "reconstitute", "solvent": solvent, "lyoph_weight_mg": lyoph_weight_mg, "recon_volume_mL": recon_volume_mL, "final_conc_mgml": final_conc if (lyoph_weight_mg and recon_volume_mL) else None, "temp_C": recon_temp, "notes": notes or None}) elif step["type"] == "ph_adjust": from shared_parameters import COMMON_BASES, COMMON_ACIDS phcol1, phcol2, phcol3, phcol4 = st.columns(4) with phcol1: direction = st.radio("Direction", ["Raise pH (base)", "Lower pH (acid)"], key=f"ph_dir_exp_{step['id']}", horizontal=True) if "base" in direction.lower(): reagent_sel = st.selectbox("Base", COMMON_BASES, key=f"ph_reag_sel_exp_{step['id']}") else: reagent_sel = st.selectbox("Acid", COMMON_ACIDS, key=f"ph_reag_sel_exp_{step['id']}") if reagent_sel == "Other": reagent = st.text_input("Specify reagent", placeholder="e.g., custom buffer", key=f"ph_reag_other_exp_{step['id']}") else: reagent = reagent_sel with phcol2: conc_val = st.number_input("Stock conc", 0.0, 12.0, 1.0, 0.1, key=f"ph_conc_exp_{step['id']}") conc_unit = st.selectbox("Units", ["M","mM","N","%"], key=f"ph_unit_exp_{step['id']}") with phcol3: target_ph = st.number_input("Target pH", 0.0, 14.0, 7.4, 0.1, key=f"ph_target_exp_{step['id']}") with phcol4: volume_ul = st.number_input("Volume added (µL)", 0.0, 10000.0, 500.0, 10.0, key=f"ph_vol_exp_{step['id']}") temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"ph_temp_exp_{step['id']}", help="Temperature during pH adjustment") notes = st.text_input("Notes (optional)", placeholder="e.g., stir rate, equilibration time", key=f"ph_notes_exp_{step['id']}") processing_steps.append({"type": "ph_adjust", "reagent": reagent, "concentration": conc_val, "conc_units": conc_unit, "target_ph": target_ph, "volume_uL": volume_ul, "temp_C": temp, "notes": notes or None}) elif step["type"] == "dialysis": from shared_parameters import COMMON_BUFFERS, COMMON_ACIDS diacol1, diacol2, diacol3, diacol4 = st.columns(4) with diacol1: buffer_sel = st.selectbox("Buffer/Solution", COMMON_BUFFERS + COMMON_ACIDS, key=f"dial_buf_sel_exp_{step['id']}") if buffer_sel == "Other": buffer = st.text_input("Specify buffer", placeholder="e.g., custom buffer", key=f"dial_buf_other_exp_{step['id']}") else: buffer = buffer_sel with diacol2: conc_val = st.number_input("Concentration", 0.0, 10.0, 0.01, 0.001, key=f"dial_conc_exp_{step['id']}", help="e.g., 0.01 M acetic acid, 1× PBS") conc_unit = st.selectbox("Units", ["M","mM","x","pH units","% (v/v)"], key=f"dial_unit_exp_{step['id']}") with diacol3: changes = st.number_input("# Changes", 1, 50, 3, 1, key=f"dial_chg_exp_{step['id']}") duration = st.number_input("Total duration (hours)", 0.0, 200.0, 24.0, 1.0, key=f"dial_dur_exp_{step['id']}") with diacol4: temp = st.number_input("Temp (°C)", 0.0, 50.0, 4.0, 1.0, key=f"dial_temp_exp_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., MWCO 3.5kDa, stirring, volume ratio 1:100", key=f"dial_notes_exp_{step['id']}") processing_steps.append({"type": "dialysis", "buffer": buffer, "concentration": conc_val, "conc_units": conc_unit, "n_changes": changes, "duration_hours": duration, "temp_C": temp, "notes": notes or None}) elif step["type"] == "storage": 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_exp_{step['id']}") with scol2: duration = st.text_input("Duration", placeholder="e.g., 7 days, 3 months", key=f"stor_dur_exp_{step['id']}") with scol3: container = st.selectbox("Container", ["tube", "vial", "bag", "plate", "other"], key=f"stor_container_exp_{step['id']}") with scol4: atmosphere = st.selectbox("Atmosphere", ["air", "nitrogen", "vacuum", "argon"], key=f"stor_atmo_exp_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., sterile, labeled", key=f"stor_notes_exp_{step['id']}") processing_steps.append({"type": "storage", "temp_C": temp, "duration": duration, "container": container, "atmosphere": atmosphere, "notes": notes or None}) elif step["type"] == "filtration": 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_exp_{step['id']}") with fcol2: pore_size = st.text_input("Pore size", placeholder="e.g., 0.22 µm, 100 kDa", key=f"filt_pore_exp_{step['id']}") with fcol3: if filter_type == "spin_filter": rpm = st.number_input("RPM", 0, 20000, 3000, 500, key=f"filt_rpm_exp_{step['id']}") duration_min = st.number_input("Duration (min)", 0.0, 500.0, 10.0, 1.0, key=f"filt_dur_exp_{step['id']}") else: rpm = None duration_min = st.number_input("Duration (min)", 0.0, 500.0, 5.0, 1.0, key=f"filt_dur_exp_{step['id']}") with fcol4: temp = st.number_input("Temp (°C)", 0.0, 50.0, 4.0, 1.0, key=f"filt_temp_exp_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., filter brand, pre-wet, flow rate", key=f"filt_notes_exp_{step['id']}") processing_steps.append({"type": "filtration", "filter_type": filter_type, "pore_size": pore_size, "rpm": rpm, "duration_min": duration_min, "temp_C": temp, "notes": notes or None}) elif step["type"] == "centrifuge": ccol1, ccol2, ccol3, ccol4 = st.columns(4) with ccol1: purpose = st.selectbox("Purpose", ["clarification", "concentration", "pellet_removal", "debris_removal", "other"], key=f"cent_purp_exp_{step['id']}") if purpose == "other": purpose = st.text_input("Specify purpose", key=f"cent_purp_other_exp_{step['id']}") with ccol2: speed = st.number_input("Speed (RCF)", 0, 50000, 3000, 100, key=f"cent_speed_exp_{step['id']}") duration = st.number_input("Duration (min)", 0.0, 300.0, 10.0, 1.0, key=f"cent_dur_exp_{step['id']}") with ccol3: temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"cent_temp_exp_{step['id']}") cycles = st.number_input("# Cycles", 1, 10, 1, 1, key=f"cent_cycles_exp_{step['id']}") with ccol4: volume = st.number_input("Volume (mL)", 0.0, 1000.0, 50.0, 5.0, key=f"cent_vol_exp_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., rotor type, brake settings", key=f"cent_notes_exp_{step['id']}") processing_steps.append({"type": "centrifuge", "purpose": purpose, "speed_rcf": speed, "duration_min": duration, "temp_C": temp, "cycles": cycles, "volume_mL": volume, "notes": notes or None}) elif step["type"] == "other": with col1: step_name = st.text_input("Step name", placeholder="e.g., sonication", key=f"other_name_exp_{step['id']}") with col2: duration = st.text_input("Duration", placeholder="e.g., 30 min", key=f"other_dur_exp_{step['id']}") with col3: details = st.text_input("Details", key=f"other_detail_exp_{step['id']}") processing_steps.append({"type": "other", "step_name": step_name, "duration": duration, "details": details}) # Remove button if st.button("🗑️ Remove", key=f"remove_step_exp_{step['id']}"): st.session_state.proc_steps.pop(i) st.rerun() # Gelation Protocol Builder (OUTSIDE form - uses buttons) st.markdown("---") st.subheader("🧪 Gelation Protocol Builder") st.caption("Track neutralization, gel formation, and post-gel handling") # Initialize session state for gelation steps if "gel_steps" not in st.session_state: st.session_state.gel_steps = [] # Buttons to add gelation step types st.caption("**Add Gelation Steps:**") gel_row1_exp = st.columns(6) with gel_row1_exp[0]: if st.button("➕ Dilute/Conc", key="add_dilute_exp"): st.session_state.gel_steps.append({"type": "dilute", "id": len(st.session_state.gel_steps)}) st.rerun() with gel_row1_exp[1]: if st.button("➕ Add Reagent", key="add_addreag_exp"): st.session_state.gel_steps.append({"type": "add_reagent", "id": len(st.session_state.gel_steps)}) st.rerun() with gel_row1_exp[2]: if st.button("➕ pH Adjust", key="add_ph_gel_exp"): st.session_state.gel_steps.append({"type": "ph_adjust_gel", "id": len(st.session_state.gel_steps)}) st.rerun() with gel_row1_exp[3]: if st.button("➕ Incubate", key="add_incubate_exp"): st.session_state.gel_steps.append({"type": "incubate", "id": len(st.session_state.gel_steps)}) st.rerun() with gel_row1_exp[4]: if st.button("➕ Media Wash", key="add_mediawash_exp"): st.session_state.gel_steps.append({"type": "media_wash", "id": len(st.session_state.gel_steps)}) st.rerun() with gel_row1_exp[5]: if st.button("➕ Hydrate", key="add_hydrate_exp"): st.session_state.gel_steps.append({"type": "hydrate", "id": len(st.session_state.gel_steps)}) st.rerun() gel_row2_exp = st.columns(6) with gel_row2_exp[0]: if st.button("➕ Stability Test", key="add_stab_exp"): st.session_state.gel_steps.append({"type": "stability", "id": len(st.session_state.gel_steps)}) st.rerun() with gel_row2_exp[1]: if st.button("➕ Other", key="add_other_gel_exp"): st.session_state.gel_steps.append({"type": "other_gel", "id": len(st.session_state.gel_steps)}) st.rerun() with gel_row2_exp[2]: st.write("") # Spacer with gel_row2_exp[3]: st.write("") # Spacer with gel_row2_exp[4]: st.write("") # Spacer with gel_row2_exp[5]: if st.button("🗑️ Clear All", key="clear_gel_steps_exp"): st.session_state.gel_steps = [] st.rerun() if st.session_state.gel_steps: st.caption(f"**{len(st.session_state.gel_steps)} gelation step(s) added**") # Display and edit each gelation step gelation_steps = [] for i, step in enumerate(st.session_state.gel_steps): with st.expander(f"Gel Step {i+1}: {step['type'].replace('_', ' ').title()}", expanded=True): gcol1, gcol2, gcol3 = st.columns([3, 3, 1]) if step["type"] == "dilute": from shared_parameters import COMMON_DILUENTS dilcol1, dilcol2, dilcol3 = st.columns(3) with dilcol1: from_conc = st.number_input("From (mg/mL)", 0.0, 200.0, 10.0, 0.1, key=f"dil_from_exp_{step['id']}") to_conc = st.number_input("To (mg/mL)", 0.0, 200.0, 5.0, 0.1, key=f"dil_to_exp_{step['id']}") with dilcol2: diluent_sel = st.selectbox("Diluent", COMMON_DILUENTS, key=f"dil_dil_sel_exp_{step['id']}") if diluent_sel == "Other": diluent = st.text_input("Specify diluent", key=f"dil_dil_other_exp_{step['id']}") else: diluent = diluent_sel with dilcol3: dilution_factor = round(from_conc / to_conc, 2) if to_conc > 0 else 0 st.metric("Dilution factor", f"{dilution_factor}×") notes = st.text_input("Notes (optional)", placeholder="e.g., mixing method, equilibration time", key=f"dil_notes_exp_{step['id']}") gelation_steps.append({"type": "dilute", "from_mgml": from_conc, "to_mgml": to_conc, "diluent": diluent, "dilution_factor": dilution_factor, "notes": notes or None}) elif step["type"] == "add_reagent": from shared_parameters import COMMON_BUFFERS, COMMON_BASES, COMMON_SALTS, REAGENT_PURPOSES arcol1, arcol2, arcol3, arcol4 = st.columns(4) with arcol1: reagent_sel = st.selectbox("Reagent", COMMON_BUFFERS + COMMON_BASES + COMMON_SALTS + ["Other"], key=f"add_reag_sel_exp_{step['id']}") if reagent_sel == "Other": reagent = st.text_input("Specify reagent", placeholder="e.g., custom reagent", key=f"add_reag_other_exp_{step['id']}") else: reagent = reagent_sel with arcol2: conc_val = st.number_input("Stock conc", 0.0, 100.0, 10.0, 0.1, key=f"add_conc_exp_{step['id']}") conc_unit = st.selectbox("Units", ["x","M","mM","%","mg/mL"], key=f"add_unit_exp_{step['id']}") with arcol3: volume_ul_per_ml = st.number_input("µL per mL ECM", 0.0, 1000.0, 100.0, 10.0, key=f"add_vol_exp_{step['id']}", help="e.g., 100 µL of 10× PBS per 1 mL ECM") with arcol4: purpose_sel = st.selectbox("Purpose", REAGENT_PURPOSES, key=f"add_purp_exp_{step['id']}") if purpose_sel == "Other": purpose = st.text_input("Specify purpose", key=f"add_purp_other_exp_{step['id']}") else: purpose = purpose_sel notes = st.text_input("Notes (optional)", placeholder="e.g., add slowly with stirring, on ice", key=f"add_notes_exp_{step['id']}") gelation_steps.append({"type": "add_reagent", "reagent": reagent, "stock_conc": conc_val, "conc_units": conc_unit, "volume_uL_per_mL": volume_ul_per_ml, "purpose": purpose, "notes": notes or None}) elif step["type"] == "ph_adjust_gel": from shared_parameters import COMMON_BASES, COMMON_ACIDS phgcol1, phgcol2, phgcol3, phgcol4 = st.columns(4) with phgcol1: direction = st.radio("Direction", ["Raise (base)", "Lower (acid)"], key=f"ph_gel_dir_exp_{step['id']}", horizontal=True) if "base" in direction.lower(): reagent_sel = st.selectbox("Base", COMMON_BASES, key=f"ph_gel_reag_sel_exp_{step['id']}") else: reagent_sel = st.selectbox("Acid", COMMON_ACIDS, key=f"ph_gel_reag_sel_exp_{step['id']}") if reagent_sel == "Other": reagent = st.text_input("Specify", key=f"ph_gel_reag_other_exp_{step['id']}") else: reagent = reagent_sel with phgcol2: conc_val = st.number_input("Stock conc", 0.0, 12.0, 1.0, 0.1, key=f"ph_gel_conc_exp_{step['id']}") conc_unit = st.selectbox("Units", ["M","mM","N","%"], key=f"ph_gel_unit_exp_{step['id']}") with phgcol3: target_ph = st.number_input("Target pH", 0.0, 14.0, 7.2, 0.1, key=f"ph_gel_target_exp_{step['id']}") with phgcol4: volume_ul_per_ml = st.number_input("µL per mL ECM", 0.0, 1000.0, 50.0, 10.0, key=f"ph_gel_vol_exp_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., dropwise addition, mixing time", key=f"ph_gel_notes_exp_{step['id']}") gelation_steps.append({"type": "ph_adjust_gel", "reagent": reagent, "stock_conc": conc_val, "conc_units": conc_unit, "target_ph": target_ph, "volume_uL_per_mL": volume_ul_per_ml, "notes": notes or None}) elif step["type"] == "incubate": with gcol1: temp = st.number_input("Temp (°C)", 0.0, 60.0, 37.0, 0.5, key=f"inc_temp_exp_{step['id']}") with gcol2: duration = st.text_input("Duration", placeholder="e.g., 60 min, 2 hours", key=f"inc_dur_exp_{step['id']}") with gcol3: conditions = st.text_input("Conditions", placeholder="e.g., humid chamber", key=f"inc_cond_exp_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., covered, CO2 atmosphere", key=f"inc_notes_exp_{step['id']}") gelation_steps.append({"type": "incubate", "temp_C": temp, "duration": duration, "conditions": conditions, "notes": notes or None}) elif step["type"] == "media_wash": with gcol1: media = st.text_input("Media", placeholder="e.g., DMEM, culture media", key=f"mw_media_exp_{step['id']}") with gcol2: n_washes = st.number_input("# Washes", 1, 20, 3, 1, key=f"mw_num_exp_{step['id']}") with gcol3: duration = st.number_input("Duration each (min)", 0.0, 500.0, 15.0, 5.0, key=f"mw_dur_exp_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., warm media, gentle pipetting", key=f"mw_notes_exp_{step['id']}") gelation_steps.append({"type": "media_wash", "media": media, "n_washes": n_washes, "duration_min": duration, "notes": notes or None}) elif step["type"] == "hydrate": with gcol1: solution = st.text_input("Solution", placeholder="e.g., DMEM, PBS", key=f"hyd_sol_exp_{step['id']}") with gcol2: duration = st.text_input("Duration", placeholder="e.g., 24 hours, 3 days", key=f"hyd_dur_exp_{step['id']}") with gcol3: temp = st.number_input("Temp (°C)", 0.0, 50.0, 37.0, 1.0, key=f"hyd_temp_exp_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., volume of solution, container type", key=f"hyd_notes_exp_{step['id']}") gelation_steps.append({"type": "hydrate", "solution": solution, "duration": duration, "temp_C": temp, "notes": notes or None}) elif step["type"] == "stability": with gcol1: test_type = st.selectbox("Test", ["hydrated_stability", "unhydrated_stability", "media_stability"], key=f"stab_type_exp_{step['id']}") with gcol2: duration = st.text_input("Duration", placeholder="e.g., 7 days, 2 weeks", key=f"stab_dur_exp_{step['id']}") with gcol3: outcome = st.text_input("Outcome", placeholder="e.g., stable, degraded at day 3", key=f"stab_out_exp_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., storage conditions, observation frequency", key=f"stab_notes_exp_{step['id']}") gelation_steps.append({"type": "stability", "test_type": test_type, "duration": duration, "outcome": outcome, "notes": notes or None}) elif step["type"] == "other_gel": with gcol1: step_name = st.text_input("Step name", placeholder="e.g., crosslinking", key=f"other_gel_name_exp_{step['id']}") with gcol2: duration = st.text_input("Duration", placeholder="e.g., 30 min", key=f"other_gel_dur_exp_{step['id']}") with gcol3: details = st.text_input("Details", key=f"other_gel_det_exp_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., specific conditions or parameters", key=f"other_gel_notes_exp_{step['id']}") gelation_steps.append({"type": "other_gel", "step_name": step_name, "duration": duration, "details": details, "notes": notes or None}) # Remove button if st.button("🗑️ Remove", key=f"remove_gel_step_exp_{step['id']}"): st.session_state.gel_steps.pop(i) st.rerun() # Continue with the form with st.form("new_well_form"): st.subheader("💧 Composition Measurements") c1,c2,c3 = st.columns(3) with c1: ecm_total_protein_mgml = st.number_input("Total protein (mg/mL)*", 0.0, 100.0, 7.0, 0.1) protein_assay_method = st.selectbox("Protein assay method", ["","BCA","Bradford","Lowry","DC_assay","A280","Biuret","other"], help="Method used to measure protein concentration") show_measurement_protocol("ecm_total_protein_mgml") gel_volume_uL = st.number_input("Gel volume per well (μL)", 1.0, 5000.0, 700.0, 10.0, help="Total volume of hydrogel per well. Used for spatial seeding height calculations in cell culture.") pre_pH = st.number_input("Pre-neutralization pH*", 0.0, 14.0, 4.0, 0.1) show_measurement_protocol("pre_pH") pre_conductivity_mS = st.number_input("Pre-conductivity (mS/cm)*", 0.0, 100.0, 3.0, 0.1) show_measurement_protocol("pre_conductivity_mS") with c2: temp_incubation_C = st.number_input("Incubation temp (°C)*", 0.0, 60.0, 37.0, 0.5) uv_A220 = st.number_input("UV A220", 0.0, step=0.01) uv_A280 = st.number_input("UV A280", 0.0, step=0.01) show_measurement_protocol("uv_A220") with c3: # UV ratio - read-only if auto-computed auto_ratio = (uv_A220 > 0 and uv_A280 > 0) if auto_ratio: computed_ratio = uv_A220 / uv_A280 st.text_input("UV ratio A220/A280 (auto)", value=f"{computed_ratio:.3f}", disabled=True, help="Auto-computed from A220/A280") uv_ratio_A220_A280 = computed_ratio else: uv_ratio_A220_A280 = st.number_input("UV ratio A220/A280", 0.0, 50.0, 0.0, 0.01, help="Auto-computed if A220 & A280 given") sds_smear_index = st.number_input("SDS smear index (0-1)", 0.0, 1.0, 0.4, 0.01) sds_alpha_ratio = st.number_input("SDS α-ratio", 0.0, 5.0, 0.9, 0.05) st.subheader("🧪 Test Conditions") c1,c2,c3 = st.columns(3) with c1: probe_type = st.selectbox("Probe Type*", options=[""] + codebook['probe_type']) target_pH = st.number_input("Target pH*", 0.0, 14.0, 7.2, 0.05) with c2: od_wavelength_nm = st.number_input("OD wavelength (nm)", 350, 800, 405, 5) od_sampling_interval_min = st.number_input("OD sampling interval (min)", 1, 120, 2) with c3: pass st.subheader("🧫 Post-Gelation Reagents (unit-safe)") st.caption("💡 **AFTER gel forms**: Media, supplements, or reagents added to the formed gel (DMEM, growth factors, drugs, etc.)") reagents_data = [] with st.expander("Add reagents with stock + volume (effective mM auto)", expanded=False): n = st.number_input("How many reagents?", 0, 16, 2, 1) for i in range(int(n)): st.markdown(f"**Reagent {i+1}**") r1,r2,r3,r4,r5 = st.columns([2,1,1,1,1]) with r1: name = st.text_input("Name", key=f"rname{i}") with r2: rclass = st.selectbox("Class", ["buffer","base","acid","salt","media","additive","enzyme","crosslinker","other"], key=f"rclass{i}") with r3: stock = st.number_input("Stock", 0.0, 1e9, 1.0, 0.1, key=f"rstk{i}") with r4: units = st.selectbox("Units", ["M","mM","µM","%","x","mg/mL","U/mL"], key=f"runits{i}") with r5: vol = st.number_input("µL per mL", 0.0, 1000.0, 0.0, 0.5, key=f"rvol{i}") # Calculate and display effective concentrations eff = effective_mM(stock, units, vol) if eff is not None: st.caption(f"→ effective ~ **{eff:.2f} mM**") else: st.caption(f"→ effective: n/a for {units}") # Extra live hints for PBS and DMEM name_lower = (name or "").strip().lower() if units == "x" and "pbs" in name_lower: final_x = pbs_final_x(stock, vol) if final_x is not None: st.caption(f"PBS final ≈ **{final_x:.2f}×** (from {stock:g}× @ {vol:g} µL/mL)") if "dmem" in name_lower or ("media" in (rclass or "").lower()): media_pct = dmem_final_percent(vol) if media_pct is not None and media_pct > 0: st.caption(f"Media final ≈ **{media_pct:.2f}% v/v**") lot = st.text_input("Lot #", key=f"rlot{i}") purpose = st.text_input("Purpose", key=f"rpurpose{i}", help="e.g., neutralization, buffer_adjust, ionic_adjust") st.markdown("---") if name: reagents_data.append(dict( reagent_name=name, reagent_class=rclass, purpose=purpose or None, stock_conc_value=stock, stock_conc_units=units, volume_uL_per_mL=vol, effective_conc_mM=eff, lot_number=lot or None, added_order=i+1 )) st.info("💡 **For longitudinal tracking**: Use the **Events** tab to log time-series observations (Day 1, Day 3, etc.) and media changes over time") # Advanced Biochemical Assays (Optional) with st.expander("🧬 Advanced Biochemical Assays (Optional)", expanded=False): st.caption("Scientific Reports 2019, MDPI 2021 - Optional advanced characterization") c1,c2,c3 = st.columns(3) with c1: hydroxyproline_mgml = st.number_input("Hydroxyproline (mg/mL)", 0.0, 100.0, value=None, step=0.1, help="Collagen content measurement (optional)") dmmB_GAG_ugml = st.number_input("GAG content (µg/mL)", 0.0, 1000.0, value=None, step=1.0, help="DMMB assay for glycosaminoglycans (optional)") with c2: viscosity_proxy_sec = st.number_input("Viscosity proxy (sec)", 0.0, 1000.0, value=None, step=1.0, help="Alternative viscosity measurement (optional)") with c3: pass # Pre-gel QC (Plate reader + pH/conductivity + viscometer) with st.expander("🔬 Pre-gel QC (Plate reader + pH/conductivity + viscometer)", expanded=False): st.caption("Scientific Reports 2019 - Pre-gelation characterization") c1,c2,c3 = st.columns(3) with c1: pre_gel_viscosity_mPas = st.number_input("Pre-gel viscosity (mPa·s)", 0.0, 1000000.0, value=None, step=1.0, help="Pre-gel shear viscosity at ~15°C (optional)") viscosity_pregel_mPas = st.number_input("Viscosity pre-gel (mPa·s)", 0.0, 1000000.0, value=None, step=1.0, help="Alternative naming (optional)") with c2: pre_gel_viscosity_temp_C = st.number_input("Viscosity temp (°C)", 0.0, 40.0, value=None, step=0.1, help="Temperature during viscosity measurement (optional)") shear_rate_s_minus1 = st.number_input("Shear rate (s⁻¹)", 0.0, 1000.0, value=None, step=0.1, help="Shear rate during measurement (optional)") with c3: turbidity_lag_time_min = st.number_input("Turbidity lag time (min)", 0.0, 1000.0, value=None, step=0.1, help="T_lag: time to 10% of max OD (optional)") turbidity_t_half_min = st.number_input("Turbidity T₁/₂ (min)", 0.0, 1000.0, value=None, step=0.1, help="Time to half-max turbidity (optional)") turbidity_slope_per_min = st.number_input("Turbidity slope (/min)", -1000.0, 1000.0, value=None, step=0.01, help="Turbidity slope S (optional)") # Gel QC (Rheometer - shared core) with st.expander("⚗️ Gel QC (Rheometer - shared core)", expanded=False): st.caption("Saldin et al. 2016, Brazdaru et al. 2015 - Viscoelastic properties") c1,c2,c3 = st.columns(3) with c1: storage_modulus_G_prime_Pa = st.number_input("Storage modulus G′ (Pa)", 0.0, 100000.0, value=None, step=1.0, help="Elastic properties (optional)") with c2: loss_modulus_G_double_prime_Pa = st.number_input("Loss modulus G″ (Pa)", 0.0, 100000.0, value=None, step=1.0, help="Viscous properties (optional)") with c3: tan_delta = st.number_input("Tan δ", 0.0, 10.0, value=None, step=0.01, help="Viscoelastic ratio G″/G′ (optional)") # Batch QC (Microplate assays) with st.expander("🧪 Batch QC (Microplate assays)", expanded=False): st.caption("Cornea ECM study 2019 - Quality control and contaminants") c1,c2,c3 = st.columns(3) with c1: sds_residual_ppm = st.number_input("SDS residual (ppm)", 0.0, 10000.0, value=None, step=0.1, help="SDS residual concentration (optional)") residual_SDS = st.number_input("Residual SDS", 0.0, 10000.0, value=None, step=0.1, help="Alternative naming (optional)") with c2: detergent_residual_binary = st.selectbox("Detergent residual", [None, 0, 1], format_func=lambda x: "Not measured" if x is None else ("Yes" if x==1 else "No"), help="Detergent residual detection (optional)") cytotoxicity_score_0to3 = st.selectbox("Cytotoxicity score (0-3)", [None, 0, 1, 2, 3], format_func=lambda x: "Not measured" if x is None else str(x), help="Cytotoxicity assessment (optional)") with c3: dna_residual_ng_mg = st.number_input("DNA residual (ng/mg)", 0.0, 1000.0, value=None, step=0.1, help="DNA residual content (optional)") endotoxin_residual_EU_mg = st.number_input("Endotoxin residual (EU/mg)", 0.0, 1000.0, value=None, step=0.1, help="Endotoxin content (optional)") protease_residual_U_mg = st.number_input("Protease residual (U/mg)", 0.0, 1000.0, value=None, step=0.1, help="Protease activity (optional)") # Cell Growth (Confocal/inverted scope) with st.expander("🧬 Cell Growth (Confocal/inverted scope)", expanded=False): st.caption("Cell viability, proliferation, and behavior analysis") c1,c2,c3 = st.columns(3) with c1: cell_viability_percent = st.number_input("Cell viability (%)", 0.0, 100.0, value=None, step=0.1, help="Cell viability percentage (optional)") doubling_time_h = st.number_input("Doubling time (h)", 0.0, 1000.0, value=None, step=0.1, help="Cell doubling time (optional)") with c2: viability_assay_type = st.selectbox("Viability assay type", [None, "Live/Dead", "AlamarBlue", "PrestoBlue", "MTT", "Other"], format_func=lambda x: "Not measured" if x is None else x, help="Viability assay method (optional)") branch_points_per_mm2 = st.number_input("Branch points per mm²", 0.0, 10000.0, value=None, step=0.1, help="Morphology branching analysis (optional)") with c3: lumen_formation_binary = st.selectbox("Lumen formation", [None, 0, 1], format_func=lambda x: "Not measured" if x is None else ("Yes" if x==1 else "No"), help="Lumen formation detection (optional)") morphology_assay_type = st.selectbox("Morphology assay type", [None, "Confocal", "Brightfield", "Phase contrast", "Other"], format_func=lambda x: "Not measured" if x is None else x, help="Imaging method (optional)") # Additional Advanced Parameters with st.expander("🔬 Additional Advanced Parameters (Optional)", expanded=False): st.caption("Thermal analysis, spectroscopy, and structural characterization") c1,c2,c3 = st.columns(3) with c1: # Thermal Analysis st.markdown("**Thermal Analysis**") dsc_onset_T_C = st.number_input("DSC onset T (°C)", 0.0, 100.0, value=None, step=0.1, help="DSC onset temperature (optional)") dsc_peak_T_C = st.number_input("DSC peak T (°C)", 0.0, 100.0, value=None, step=0.1, help="DSC peak temperature (optional)") dsc_delta_H_J_g = st.number_input("DSC ΔH (J/g)", 0.0, 1000.0, value=None, step=0.1, help="DSC gelation enthalpy (optional)") with c2: # Spectroscopy st.markdown("**Spectroscopy**") cd_molar_ellipticity_222nm_mdeg = st.number_input("CD molar ellipticity (mdeg)", -1000.0, 1000.0, value=None, step=0.1, help="CD at 222 nm (optional)") cd_helix_percent = st.number_input("CD helix %", 0.0, 100.0, value=None, step=0.1, help="Triple-helix content (optional)") ftir_amide3_1450_ratio = st.number_input("FTIR Amide III/1450 ratio", 0.0, 10.0, value=None, step=0.01, help="FTIR analysis (optional)") with c3: # Structural Analysis st.markdown("**Structural Analysis**") swelling_ratio_Q = st.number_input("Swelling ratio Q", 0.0, 100.0, value=None, step=0.1, help="Swelling ratio (optional)") gel_fresh_weight_mg = st.number_input("Fresh weight (mg)", 0.0, 10000.0, value=None, step=0.1, help="Fresh gel weight (optional)") gel_swollen_weight_mg = st.number_input("Swollen weight (mg)", 0.0, 10000.0, value=None, step=0.1, help="Swollen weight (optional)") gel_dry_weight_mg = st.number_input("Dry weight (mg)", 0.0, 10000.0, value=None, step=0.1, help="Dry weight (optional)") # Migration and Marker Expression with st.expander("🏃 Migration & Marker Expression (Optional)", expanded=False): st.caption("Cell migration analysis and marker expression") c1,c2,c3 = st.columns(3) with c1: # Migration st.markdown("**Migration Analysis**") migration_speed_um_h = st.number_input("Migration speed (µm/h)", 0.0, 1000.0, value=None, step=0.1, help="Cell migration speed (optional)") persistence_ratio = st.number_input("Persistence ratio", 0.0, 10.0, value=None, step=0.01, help="Migration persistence (optional)") migration_assay_type = st.selectbox("Migration assay type", [None, "Time-lapse", "Transwell", "Scratch", "Other"], format_func=lambda x: "Not measured" if x is None else x, help="Migration assay method (optional)") with c2: # Gel Contraction st.markdown("**Gel Contraction**") contraction_percent = st.number_input("Contraction %", 0.0, 100.0, value=None, step=0.1, help="Gel contraction percentage (optional)") contraction_time_h = st.number_input("Contraction time (h)", 0.0, 1000.0, value=None, step=0.1, help="Time for contraction (optional)") initial_gel_area_mm2 = st.number_input("Initial area (mm²)", 0.0, 10000.0, value=None, step=0.1, help="Initial gel area (optional)") final_gel_area_mm2 = st.number_input("Final area (mm²)", 0.0, 10000.0, value=None, step=0.1, help="Final gel area (optional)") with c3: # Marker Expression st.markdown("**Marker Expression**") alpha_sma_percent = st.number_input("α-SMA %", 0.0, 100.0, value=None, step=0.1, help="α-SMA positive cells (optional)") col1a1_percent = st.number_input("COL1A1 %", 0.0, 100.0, value=None, step=0.1, help="COL1A1 positive cells (optional)") muc1_percent = st.number_input("MUC1 %", 0.0, 100.0, value=None, step=0.1, help="MUC1 positive cells (optional)") ck18_percent = st.number_input("CK18 %", 0.0, 100.0, value=None, step=0.1, help="CK18 positive cells (optional)") marker_assay_type = st.selectbox("Marker assay type", [None, "Immunostaining", "qPCR", "Flow cytometry", "Other"], format_func=lambda x: "Not measured" if x is None else x, help="Marker assay method (optional)") st.subheader("📊 Outcomes") c1,c2,c3 = st.columns(3) with c1: gel_binary = st.selectbox("Gel formed?*", options=["",0,1], format_func=lambda x: "" if x=="" else ("Yes" if x==1 else "No")) gel_strength_score = st.selectbox("Gel strength (0-3)", options=["",0,1,2,3]) time_to_halfmax_min = st.number_input("Time to half-max (min)", 0.0, 1e6, 0.0, 1.0) with c2: failure_mode = st.selectbox("Failure mode", options=[""] + codebook['failure_mode']) suspected_cause = st.selectbox("Suspected cause", options=[""] + codebook['suspected_cause']) confidence_0to1 = st.number_input("Confidence (0-1)", 0.0, 1.0, 0.5, 0.1) with c3: color_shift = st.selectbox("Color shift", options=[""] + codebook['color_shift']) syneresis_binary = st.selectbox("Syneresis?", options=["",0,1]) precipitate_binary = st.selectbox("Precipitate?", options=["",0,1]) # Degradation & Plate Adhesion st.markdown("**Degradation & Physical Behavior**") deg1, deg2, deg3 = st.columns(3) with deg1: disintegrated = st.selectbox("Disintegrated?", options=["",0,1], format_func=lambda x: "" if x=="" else ("Yes" if x==1 else "No"), help="Did gel break apart into pieces?") days_to_disintegration = st.number_input("Days to disintegration", 0, 1000, 0, help="Days until gel fell apart") with deg2: reliquefied = st.selectbox("Reliquefied (back to liquid)?", options=["",0,1], format_func=lambda x: "" if x=="" else ("Yes" if x==1 else "No"), help="Did gel return to liquid state?") days_to_reliquefaction = st.number_input("Days to reliquefaction", 0, 1000, 0, help="Days until gel became liquid again") with deg3: plate_adhesion = st.selectbox("Plate adhesion", options=["","adhered","floating","mixed"], help="Does gel stick to plate or float? (can be induced or spontaneous)") adhesion_notes = st.text_input("Adhesion notes", placeholder="e.g., 'floated spontaneously at Day 3' or 'adhered, induced by media flow'", help="Note if induced vs spontaneous") # Gelation Kinetics & Pre-Gelation Storage st.markdown("**Gelation Kinetics & Pre-Gelation Conditions**") kin1, kin2, kin3 = st.columns(3) with kin1: time_to_gel_min = st.number_input("Time to gel (min)", 0.0, 10000.0, 0.0, 1.0, help="How long did it take for gel to form after adding reagents?") with kin2: pre_gel_storage_temp_C = st.number_input("Pre-gel storage temp (°C)", -80.0, 40.0, 4.0, 0.5, help="Temperature at which ECM was stored before adding gelation reagents") pre_gel_storage_duration_min = st.number_input("Pre-gel storage duration (min)", 0.0, 100000.0, 0.0, 1.0, help="How long was ECM left without reagents before gelation?") with kin3: pre_gel_storage_notes = st.text_input("Pre-gel storage notes", placeholder="e.g., 'kept on ice while preparing reagents'", help="Additional context about storage before gelation") st.subheader("📝 Notes") notes_pre = st.text_area("Notes (pre-experiment)", height=100) notes_post = st.text_area("Notes (post-experiment)", height=100) split = st.selectbox("Dataset split", options=[""] + codebook['split']) submitted = st.form_submit_button("💾 Save Well Entry", type="primary") if submitted: # Check if wells are selected if not st.session_state.selected_wells: st.error("❌ Please select at least one well position.") return # Process each selected well created_records = [] for i, well_id in enumerate(st.session_state.selected_wells): # Parse well position well_row = well_id[0] well_col = int(well_id[1:]) # Generate semantic record ID (includes species/tissue for decECM) proposed_id = generate_semantic_id( family, batch_id, plate_id, well_row, well_col, replicate_id + i, species=dec_species, tissue=dec_tissue ) final_record_id = ensure_unique_record_id(proposed_id) # Prepare preliminary payload for validation validation_payload = { 'record_id': final_record_id, 'operator_id': operator_id, 'family': family, 'batch_id': batch_id, 'gel_binary': gel_binary, 'ecm_total_protein_mgml': ecm_total_protein_mgml, 'pre_pH': pre_pH, 'pre_conductivity_mS': pre_conductivity_mS, 'temp_incubation_C': temp_incubation_C, 'target_pH': target_pH, } # Validate against spec (relaxed - only essential fields required) errors = validate_against_spec("wells_master_v4", FIELD_SPEC, validation_payload) # Show warnings for recommended fields (but don't block save) warnings = [] if family == "decECM": if not dec_species or dec_species == "": warnings.append("⚠️ Tip: ecm_origin_species is recommended for decECM (can add later)") if not dec_tissue or dec_tissue == "": warnings.append("⚠️ Tip: ecm_source_tissue is recommended for decECM (can add later)") if errors: for e in errors: st.error(f"❌ {e}") st.info("💡 Only essential fields (date, operator, family, batch) are required. Fill in details later via Edit.") return if warnings: for w in warnings: st.warning(w) # Geometry bounds guard if well_row and well_row not in row_labels: st.error(f"❌ Selected row '{well_row}' is not valid for this plate (rows: {row_labels}).") return if well_col < 1 or well_col > int(max_cols): st.error(f"❌ Column {well_col} exceeds plate bounds (1–{max_cols}).") return data = { 'record_id': final_record_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, 'batch_id': batch_id, 'gelation_id': gelation_id or None, 'donor_id': donor_id or None, 'ecm_origin_species': dec_species or None, 'ecm_source_tissue': dec_tissue or None, 'plate_id': plate_id or None, 'row': well_row or None, 'col': well_col, 'replicate_id': replicate_id + i, 'pre_storage_days_4C': (None if pre_storage_days==0 else int(pre_storage_days)) if pre_storage_temp in ["", "4°C (fridge)"] else None, 'pre_storage_fresh_notes': pre_storage_fresh_notes or None, 'pre_storage_freeze_cycles': pre_storage_freeze_cycles, 'pre_storage_temp_freezer': None if pre_storage_temp_freezer == -80.0 and pre_storage_duration_months == 0 else pre_storage_temp_freezer, 'pre_storage_duration_months': None if pre_storage_duration_months == 0 else pre_storage_duration_months, 'pre_storage_frozen_in': pre_storage_frozen_in or None, 'pre_storage_thaw_method': pre_storage_thaw_method or None, 'pre_storage_thaw_duration_min': pre_storage_thaw_duration_min, 'pre_storage_ft_notes': pre_storage_ft_notes or None, 'processing_protocol': json.dumps(processing_steps) if processing_steps else None, 'gelation_protocol': json.dumps(gelation_steps) if gelation_steps else None, 'ecm_total_protein_mgml': ecm_total_protein_mgml, 'protein_assay_method': protein_assay_method or None, 'gel_volume_uL': gel_volume_uL if gel_volume_uL > 0 else None, 'pre_pH': pre_pH, 'pre_conductivity_mS': pre_conductivity_mS, 'temp_incubation_C': temp_incubation_C, 'uv_A220': uv_A220 if uv_A220>0 else None, 'uv_A230': None, # add field to UI later if needed 'uv_A260': None, 'uv_A280': uv_A280 if uv_A280>0 else None, 'uv_ratio_A220_A280': uv_ratio_A220_A280 if uv_ratio_A220_A280>0 else None, 'sds_smear_index': sds_smear_index, 'sds_alpha_ratio': sds_alpha_ratio, 'hydroxyproline_mgml': hydroxyproline_mgml, 'dmmB_GAG_ugml': dmmB_GAG_ugml, 'viscosity_proxy_sec': viscosity_proxy_sec, # Pre-gel QC parameters 'pre_gel_viscosity_mPas': pre_gel_viscosity_mPas, 'viscosity_pregel_mPas': viscosity_pregel_mPas, 'pre_gel_viscosity_temp_C': pre_gel_viscosity_temp_C, 'shear_rate_s_minus1': shear_rate_s_minus1, 'turbidity_lag_time_min': turbidity_lag_time_min, 'turbidity_t_half_min': turbidity_t_half_min, 'turbidity_slope_per_min': turbidity_slope_per_min, # Gel QC parameters 'storage_modulus_G_prime_Pa': storage_modulus_G_prime_Pa, 'loss_modulus_G_double_prime_Pa': loss_modulus_G_double_prime_Pa, 'tan_delta': tan_delta, # Batch QC parameters 'sds_residual_ppm': sds_residual_ppm, 'residual_SDS': residual_SDS, 'detergent_residual_binary': detergent_residual_binary, 'cytotoxicity_score_0to3': cytotoxicity_score_0to3, 'dna_residual_ng_mg': dna_residual_ng_mg, 'endotoxin_residual_EU_mg': endotoxin_residual_EU_mg, 'protease_residual_U_mg': protease_residual_U_mg, # Thermal analysis parameters 'dsc_onset_T_C': dsc_onset_T_C, 'dsc_peak_T_C': dsc_peak_T_C, 'dsc_delta_H_J_g': dsc_delta_H_J_g, # Spectroscopy parameters 'cd_molar_ellipticity_222nm_mdeg': cd_molar_ellipticity_222nm_mdeg, 'cd_helix_percent': cd_helix_percent, 'ftir_amide3_1450_ratio': ftir_amide3_1450_ratio, # Structural analysis parameters 'swelling_ratio_Q': swelling_ratio_Q, 'gel_fresh_weight_mg': gel_fresh_weight_mg, 'gel_swollen_weight_mg': gel_swollen_weight_mg, 'gel_dry_weight_mg': gel_dry_weight_mg, # Cell growth parameters 'cell_viability_percent': cell_viability_percent, 'doubling_time_h': doubling_time_h, 'viability_assay_type': viability_assay_type, # Morphology parameters 'branch_points_per_mm2': branch_points_per_mm2, 'lumen_formation_binary': lumen_formation_binary, 'morphology_assay_type': morphology_assay_type, # Migration parameters 'migration_speed_um_h': migration_speed_um_h, 'persistence_ratio': persistence_ratio, 'migration_assay_type': migration_assay_type, # Gel contraction parameters 'contraction_percent': contraction_percent, 'contraction_time_h': contraction_time_h, 'initial_gel_area_mm2': initial_gel_area_mm2, 'final_gel_area_mm2': final_gel_area_mm2, # Marker expression parameters 'alpha_sma_percent': alpha_sma_percent, 'col1a1_percent': col1a1_percent, 'muc1_percent': muc1_percent, 'ck18_percent': ck18_percent, 'marker_assay_type': marker_assay_type, 'probe_type': probe_type or None, 'target_pH': target_pH, 'od_wavelength_nm': od_wavelength_nm, 'od_sampling_interval_min': od_sampling_interval_min, 'time_to_halfmax_min': time_to_halfmax_min if time_to_halfmax_min>0 else None, 'slope_OD_per_min': None, 'final_OD': None, 'lag_time_min': None, 'gel_binary': int(gel_binary), 'gel_strength_score_0to3': None if gel_strength_score=="" else int(gel_strength_score), 'tilt_test_angle_deg': None, 'time_to_handle_min': None, 'failure_mode': failure_mode or None, 'suspected_cause': suspected_cause or None, 'confidence_0to1': confidence_0to1 if confidence_0to1>0 else None, 'syneresis_binary': None if syneresis_binary=="" else int(syneresis_binary), 'syneresis_time_min': None, 'precipitate_binary': None if precipitate_binary=="" else int(precipitate_binary), 'color_shift': color_shift or None, 'disintegrated': None if disintegrated=="" else int(disintegrated), 'days_to_disintegration': None if days_to_disintegration==0 else int(days_to_disintegration), 'reliquefied': None if reliquefied=="" else int(reliquefied), 'days_to_reliquefaction': None if days_to_reliquefaction==0 else int(days_to_reliquefaction), 'plate_adhesion': plate_adhesion or None, 'adhesion_notes': adhesion_notes or None, 'time_to_gel_min': None if time_to_gel_min==0 else time_to_gel_min, 'pre_gel_storage_temp_C': pre_gel_storage_temp_C, 'pre_gel_storage_duration_min': None if pre_gel_storage_duration_min==0 else pre_gel_storage_duration_min, 'pre_gel_storage_notes': pre_gel_storage_notes or None, 'notes_pre': notes_pre or None, 'notes_post': notes_post or None, 'app_recipe_recommended': None, 'app_pgel_pred': None, 'app_thalf_pred_min': None, 'app_uncertainty': None, 'counterfactual_recipe': None, 'counterfactual_expected_pgel': None, # Citation integration fields 'first_author': first_author or None, 'publication_year': int(publication_year) if publication_year else None, 'paper_title': paper_title or None, 'source_label': source_label or None, 'doi': doi or None, 'citation': citation or None, 'split': split or None } data, reagents_data = sanitize_and_enrich_well_payload(data, reagents_data) # Check for likely duplicates (soft warning) if likely_duplicate_exists(plate_id, well_row, well_col): st.warning(f"⚠️ Another well with the same plate/row/col ({plate_id}/{well_row}{well_col}) was created recently. Continuing anyway.") try: rid = create_well(data, reagents_list=reagents_data if reagents_data else None) created_records.append(rid) except sqlite3.IntegrityError: st.error(f"❌ Record ID '{final_record_id}' already exists (should not happen with auto-versioning).") return except Exception as e: st.error(f"❌ Error saving well {well_id}: {e}") return # Success message for all wells if created_records: st.success(f"✅ Created {len(created_records)} wells!") with st.expander("View created record IDs"): st.code("\n".join(created_records)) st.balloons() # Clear selected wells and all protocol steps after successful creation st.session_state.selected_wells = [] st.session_state.proc_steps = [] st.session_state.gel_steps = [] def show_literature_database_viewer(): """Show literature database entries in a user-friendly interface.""" from datetime import datetime st.header("📚 Literature Database Viewer") st.caption("Browse and manage literature ECM entries from published papers") # Import literature functions try: from literature_gui import get_ref_conn, read_lit_wells except ImportError: st.error("❌ Literature GUI module not available") st.info("This feature requires the literature GUI module.") return # Get literature data try: df = read_lit_wells() if df.empty: st.info("📚 No literature entries found. Go to **Literature Hydrogels** to add entries from published papers.") return st.success(f"📊 Found **{len(df)}** literature entries") # Filters with st.expander("🔍 Filter Literature Entries", expanded=False): col1, col2, col3 = st.columns(3) with col1: filter_author = st.text_input("First Author contains") filter_family = st.selectbox("ECM Family", ["All"] + sorted(df['material_family'].dropna().unique().tolist())) with col2: filter_year = st.selectbox("Publication Year", ["All"] + sorted(df['publication_year'].dropna().unique().tolist(), reverse=True)) filter_species = st.selectbox("Species", ["All"] + sorted(df['ecm_origin_species'].dropna().unique().tolist())) with col3: filter_tissue = st.selectbox("Tissue", ["All"] + sorted(df['ecm_source_tissue'].dropna().unique().tolist())) filter_commercial = st.selectbox("Product Type", ["All", "Lab-made", "Commercial"]) # Apply filters filtered_df = df.copy() if filter_author: filtered_df = filtered_df[filtered_df['first_author'].str.contains(filter_author, case=False, na=False)] if filter_family != "All": filtered_df = filtered_df[filtered_df['material_family'] == filter_family] if filter_year != "All": filtered_df = filtered_df[filtered_df['publication_year'] == filter_year] if filter_species != "All": filtered_df = filtered_df[filtered_df['ecm_origin_species'] == filter_species] if filter_tissue != "All": filtered_df = filtered_df[filtered_df['ecm_source_tissue'] == filter_tissue] if filter_commercial == "Lab-made": filtered_df = filtered_df[filtered_df['is_commercial_product'] == 0] elif filter_commercial == "Commercial": filtered_df = filtered_df[filtered_df['is_commercial_product'] == 1] st.write(f"**Showing {len(filtered_df)} of {len(df)} entries**") # Display key columns - separate batch data from gelation data batch_cols = [ "batch_id", "first_author", "publication_year", "paper_title", "material_family", "ecm_origin_species", "ecm_source_tissue", "is_commercial_product", "commercial_product_name", "ecm_total_protein_mgml", "protein_assay_method", "pre_pH", "pre_conductivity_mS", "uv_A220", "uv_A280", "uv_ratio_A220_A280", "created_at" ] gelation_cols = [ "gelation_id", "gel_binary", "gel_strength_score_0to3", "time_to_gel_min", "time_to_halfmax_min", "gelation_protocol" ] # Only show columns that exist and have data available_batch_cols = [c for c in batch_cols if c in filtered_df.columns] available_gelation_cols = [c for c in gelation_cols if c in filtered_df.columns] # Create separate dataframes for batch and gelation data batch_df = filtered_df[available_batch_cols].copy() gelation_df = filtered_df[available_gelation_cols].copy() # Format batch data if 'is_commercial_product' in batch_df.columns: batch_df['is_commercial_product'] = batch_df['is_commercial_product'].map({0: 'Lab-made', 1: 'Commercial'}) # Format gelation data if 'gel_binary' in gelation_df.columns: gelation_df['gel_binary'] = gelation_df['gel_binary'].map({0: 'No Gel', 1: 'Gel'}) # Sort by publication year (newest first) if 'publication_year' in batch_df.columns: batch_df = batch_df.sort_values('publication_year', ascending=False) # Display batch data with individual duplicate buttons and detailed dropdowns st.subheader("📦 ECM Batch Information") st.caption("💡 Click '🔄 Duplicate' to copy a batch, or expand '📋 Details' for more information") for idx, row in batch_df.iterrows(): with st.container(): col1, col2, col3, col4, col5, col6 = st.columns([2.5, 1, 1, 1, 1, 1]) with col1: st.write(f"**{row['batch_id']}** - {row['first_author']} ({row['publication_year']})") st.caption(f"{row['material_family']} • {row['ecm_origin_species']} {row['ecm_source_tissue']}") if row.get('paper_title'): st.write(f"📄 {row['paper_title'][:80]}{'...' if len(str(row['paper_title'])) > 80 else ''}") with col2: if row.get('ecm_total_protein_mgml'): st.metric("Protein", f"{row['ecm_total_protein_mgml']:.1f} mg/mL") with col3: if row.get('pre_pH'): st.metric("Pre-pH", f"{row['pre_pH']:.1f}") with col4: if row.get('uv_A220'): st.metric("UV A220", f"{row['uv_A220']:.2f}") with col5: # Details dropdown with st.expander("📋 Details", expanded=False): st.write("**📚 Publication Information**") st.write(f"• **Author:** {row.get('first_author', 'N/A')}") st.write(f"• **Year:** {row.get('publication_year', 'N/A')}") st.write(f"• **DOI:** {row.get('doi', 'N/A')}") if row.get('paper_title'): st.write(f"• **Title:** {row['paper_title']}") st.write("**🧬 ECM Details**") st.write(f"• **Family:** {row.get('material_family', 'N/A')}") st.write(f"• **Species:** {row.get('ecm_origin_species', 'N/A')}") st.write(f"• **Tissue:** {row.get('ecm_source_tissue', 'N/A')}") st.write(f"• **Collagen Type:** {row.get('collagen_type', 'N/A')}") if row.get('is_commercial_product') == 'Commercial': st.write("**🏪 Commercial Product**") st.write(f"• **Vendor:** {row.get('commercial_vendor', 'N/A')}") st.write(f"• **Product:** {row.get('commercial_product_name', 'N/A')}") st.write(f"• **Catalog #:** {row.get('commercial_catalog_number', 'N/A')}") st.write(f"• **Lot #:** {row.get('commercial_lot_number', 'N/A')}") st.write("**🔬 Characterization**") st.write(f"• **Protein:** {row.get('ecm_total_protein_mgml', 'N/A')} mg/mL ({row.get('protein_assay_method', 'N/A')})") st.write(f"• **Pre-pH:** {row.get('pre_pH', 'N/A')}") st.write(f"• **Conductivity:** {row.get('pre_conductivity_mS', 'N/A')} mS") st.write(f"• **UV A220:** {row.get('uv_A220', 'N/A')}") st.write(f"• **UV A280:** {row.get('uv_A280', 'N/A')}") st.write(f"• **UV Ratio:** {row.get('uv_ratio_A220_A280', 'N/A')}") if row.get('processing_protocol'): st.write("**⚙️ Processing Protocol**") try: import json protocol = json.loads(row['processing_protocol']) for i, step in enumerate(protocol, 1): st.write(f"• **Step {i}:** {step.get('step_name', 'N/A')} - {step.get('description', 'N/A')}") except: st.write(f"• **Protocol:** {row['processing_protocol']}") if row.get('notes'): st.write("**📝 Notes**") st.write(f"• {row['notes']}") st.write(f"**📅 Created:** {row.get('created_at', 'N/A')}") with col6: # Duplicate button for this specific batch if st.button("🔄 Duplicate", key=f"dup_btn_{row['batch_id']}", help="Duplicate this batch for different species/tissue"): st.session_state[f"duplicate_batch_{row['batch_id']}"] = True st.rerun() # Show duplication form if this batch was selected if st.session_state.get(f"duplicate_batch_{row['batch_id']}", False): with st.expander(f"🔄 Duplicating {row['batch_id']}", expanded=True): st.write(f"**Original:** {row['batch_id']} - {row['ecm_origin_species']} {row['ecm_source_tissue']}") col_a, col_b = st.columns(2) with col_a: new_species = st.selectbox( "New Species:", ["human", "porcine", "bovine", "rat", "mouse", "avian", "other"], index=["human", "porcine", "bovine", "rat", "mouse", "avian", "other"].index(row.get('ecm_origin_species', 'human')) if row.get('ecm_origin_species') in ["human", "porcine", "bovine", "rat", "mouse", "avian", "other"] else 0, key=f"dup_species_{row['batch_id']}" ) with col_b: new_tissue = st.selectbox( "New Tissue:", ["mammary", "dermis", "small_intestine_submucosa", "myocardium", "pericardium", "liver", "lung", "kidney", "bladder", "tendon", "cartilage", "meniscus", "adipose", "placenta", "amniotic_membrane", "esophagus", "cornea", "other"], index=["mammary", "dermis", "small_intestine_submucosa", "myocardium", "pericardium", "liver", "lung", "kidney", "bladder", "tendon", "cartilage", "meniscus", "adipose", "placenta", "amniotic_membrane", "esophagus", "cornea", "other"].index(row.get('ecm_source_tissue', 'mammary')) if row.get('ecm_source_tissue') in ["mammary", "dermis", "small_intestine_submucosa", "myocardium", "pericardium", "liver", "lung", "kidney", "bladder", "tendon", "cartilage", "meniscus", "adipose", "placenta", "amniotic_membrane", "esophagus", "cornea", "other"] else 0, key=f"dup_tissue_{row['batch_id']}" ) # Generate new batch ID from batch_creation_lit import generate_batch_id new_batch_id = generate_batch_id( row['material_family'], new_species, new_tissue, None, row.get('is_commercial_product', 0) == 'Commercial' ) st.write(f"**New Batch ID:** {new_batch_id}") col_c, col_d = st.columns([1, 1]) with col_c: if st.button("✅ Confirm Duplicate", type="primary", key=f"confirm_dup_{row['batch_id']}"): try: # Import literature functions from literature_gui import get_ref_conn # Get the original batch data conn = get_ref_conn() original_data = conn.execute( "SELECT * FROM literature_wells WHERE batch_id = ?", (row['batch_id'],) ).fetchone() if original_data: # Create new batch data new_data = dict(original_data) new_data['batch_id'] = new_batch_id new_data['ecm_origin_species'] = new_species new_data['ecm_source_tissue'] = new_tissue new_data['created_at'] = datetime.now().isoformat() # Remove the original record_id to create a new one if 'record_id' in new_data: del new_data['record_id'] # Insert new batch cols = list(new_data.keys()) vals = list(new_data.values()) conn.execute( f"INSERT INTO literature_wells ({','.join(cols)}) VALUES ({','.join(['?']*len(vals))})", vals ) conn.commit() conn.close() st.success(f"✅ **Batch duplicated successfully!**") st.success(f"📦 New Batch ID: **{new_batch_id}**") st.info("🔄 The page will refresh to show the new batch") # Clear the duplicate state st.session_state[f"duplicate_batch_{row['batch_id']}"] = False st.rerun() else: st.error("❌ Original batch data not found") except Exception as e: st.error(f"❌ Error duplicating batch: {e}") with col_d: if st.button("❌ Cancel", key=f"cancel_dup_{row['batch_id']}"): st.session_state[f"duplicate_batch_{row['batch_id']}"] = False st.rerun() st.divider() # Display gelation data if it exists if not gelation_df.empty and any(gelation_df.notna().any()): st.subheader("🧬 Gelation Results") st.caption("Gelation conditions and outcomes from literature") # Filter out rows where gelation data is all null gelation_with_data = gelation_df.dropna(how='all') if not gelation_with_data.empty: st.dataframe( gelation_with_data, use_container_width=True, height=200, column_config={ "gelation_id": st.column_config.TextColumn("Gelation ID", width="medium"), "gel_binary": st.column_config.TextColumn("Gel Formation", width="small"), "gel_strength_score_0to3": st.column_config.NumberColumn("Strength (0-3)", width="small"), "time_to_gel_min": st.column_config.NumberColumn("Time to Gel (min)", width="small"), "time_to_halfmax_min": st.column_config.NumberColumn("Time to Half-max (min)", width="small"), "gelation_protocol": st.column_config.TextColumn("Protocol", width="large"), } ) else: st.info("No gelation data available. Use **Literature Gelation** form to add gelation conditions and results.") else: st.subheader("🧬 Gelation Results") st.info("No gelation data available. Use **Literature Gelation** form to add gelation conditions and results.") # Summary statistics with st.expander("📊 Summary Statistics", expanded=False): col1, col2, col3 = st.columns(3) with col1: st.metric("Total Entries", len(filtered_df)) if 'material_family' in filtered_df.columns: family_counts = filtered_df['material_family'].value_counts() st.write("**By Family:**") for family, count in family_counts.head(5).items(): st.write(f"• {family}: {count}") with col2: if 'publication_year' in filtered_df.columns: recent_years = filtered_df['publication_year'].value_counts().head(5) st.write("**Recent Years:**") for year, count in recent_years.items(): st.write(f"• {year}: {count}") with col3: if 'ecm_origin_species' in filtered_df.columns: species_counts = filtered_df['ecm_origin_species'].value_counts() st.write("**By Species:**") for species, count in species_counts.head(5).items(): st.write(f"• {species}: {count}") # Quick actions st.markdown("---") st.subheader("🚀 Quick Actions") col1, col2, col3 = st.columns(3) with col1: if st.button("➕ Add Literature Batch", use_container_width=True): st.info("Go to **Literature Hydrogels** → **➕ Add Entry** to add ECM batch data from papers") with col2: if st.button("🧬 Add Gelation Data", use_container_width=True): st.info("Go to **Literature Hydrogels** → **🧬 Gelation** to add gelation conditions and results") with col3: if st.button("📂 Import Literature CSV", use_container_width=True): st.info("Go to **Literature Hydrogels** → **📂 Import CSV** to bulk import literature data") except Exception as e: st.error(f"❌ Error loading literature data: {e}") st.info("Make sure the literature database is properly initialized.") def show_view_edit_page(codebook): st.header("📊 Raw Wells Data Viewer") st.caption("Legacy data viewer for all historical well data from wells_master_v4 table") with st.expander("🔍 Filters"): c1,c2,c3 = st.columns(3) with c1: f_batch = st.text_input("Batch ID") f_family = st.selectbox("ECM Family", ["All"] + codebook['family']) with c2: f_operator = st.text_input("Operator ID") f_gel = st.selectbox("Gel Outcome", ["All","Gel (1)","No Gel (0)"]) with c3: f_species = st.selectbox("Species (decECM)", ["All"] + codebook['species']) f_tissue = st.selectbox("Tissue (decECM)", ["All"] + codebook['tissues']) # Plate heatmap for visual QC with st.expander("🗺️ Plate Heatmap (Visual QC)", expanded=False): col_h1, col_h2 = st.columns(2) with col_h1: pid_for_heatmap = st.text_input("Plate ID", placeholder="PLT-001-96", key="heatmap_plate") with col_h2: date_for_heatmap = st.text_input("Date (optional)", placeholder="YYYY-MM-DD", key="heatmap_date") if pid_for_heatmap: render_plate_heatmap(pid_for_heatmap, date_for_heatmap or None) filters = {} if f_batch: filters['batch_id'] = f_batch if f_family != "All": filters['family'] = f_family if f_operator: filters['operator_id'] = f_operator if f_species != "All": filters['ecm_origin_species'] = f_species if f_tissue != "All": filters['ecm_source_tissue'] = f_tissue if f_gel == "Gel (1)": filters['gel_binary'] = 1 elif f_gel == "No Gel (0)": filters['gel_binary'] = 0 df = read_wells(filters if filters else None, use_effective_view=True) if df.empty: st.info("No wells found.") return st.write(f"**Total records:** {len(df)}") # Show plate bounds as hint (cached per unique plate_id) if 'plate_id' in df.columns: unique_pids = [p for p in df['plate_id'].dropna().unique().tolist()] geom_map = {} for pid in unique_pids: g = get_plate_geometry(pid) geom_map[pid] = (f"{g[0]} × {g[1]}" if g else "") df['_plate_geom'] = df['plate_id'].map(geom_map).fillna("") show_cols = [c for c in ['record_id','date','operator_id','family','ecm_origin_species','ecm_source_tissue','batch_id','plate_id','_plate_geom','gel_binary','gel_strength_score_0to3','target_pH','temp_incubation_C','eff_NaCl_mM','eff_CaCl2_mM','updated_at'] if c in df.columns] st.dataframe(df[show_cols], use_container_width=True) # Friendly selection but storing the full record_id options = [(f"{row['record_id'][:8]}… — {row.get('batch_id','N/A')}", row['record_id']) for _,row in df.iterrows()] labels = [o[0] for o in options] label = st.selectbox("Select well to edit:", options=[""]+labels) if not label: return record_id = dict(options)[label] well = df[df['record_id']==record_id].iloc[0].to_dict() with st.form(f"edit_form_{record_id[:8]}"): st.write(f"**Editing:** `{record_id}`") expected_updated_at = well.get('updated_at') c1,c2 = st.columns(2) with c1: edit_gel_binary = st.selectbox("Gel formed?", [0,1], index=int(well.get('gel_binary',0))) edit_strength = st.number_input("Gel strength (0-3)", 0, 3, int(0 if pd.isna(well.get('gel_strength_score_0to3')) else well['gel_strength_score_0to3'])) with c2: edit_failure = st.selectbox("Failure mode", [""]+codebook['failure_mode'], index=0 if pd.isna(well.get('failure_mode')) or well.get('failure_mode') not in codebook['failure_mode'] else codebook['failure_mode'].index(well['failure_mode'])+1) edit_cause = st.selectbox("Suspected cause", [""]+codebook['suspected_cause'], index=0 if pd.isna(well.get('suspected_cause')) or well.get('suspected_cause') not in codebook['suspected_cause'] else codebook['suspected_cause'].index(well['suspected_cause'])+1) notes_post = st.text_area("Notes (post-experiment)", value=("" if pd.isna(well.get('notes_post')) else str(well.get('notes_post')))) c1,c2 = st.columns(2) with c1: update_btn = st.form_submit_button("💾 Update Well") with c2: delete_btn = st.form_submit_button("🗑️ Delete Well", type="secondary") if update_btn: upd = { 'gel_binary': int(edit_gel_binary), 'gel_strength_score_0to3': int(edit_strength), 'failure_mode': None if edit_failure=="" else edit_failure, 'suspected_cause': None if edit_cause=="" else edit_cause, 'notes_post': None if notes_post.strip()=="" else notes_post } try: update_well(record_id, upd, expected_updated_at=expected_updated_at) st.success("✅ Updated.") st.rerun() except RuntimeError as e: st.error(f"❌ {e}") except Exception as e: st.error(f"❌ Error: {e}") if delete_btn: try: delete_well(record_id) st.success("✅ Deleted.") st.rerun() except Exception as e: st.error(f"❌ Error deleting: {e}") # Clone functionality st.markdown("---") st.subheader("🔁 Clone this well") st.caption("Create copies of this well with the same metadata and optionally reagents. Great for replicates!") with st.form(f"clone_form_{record_id[:8]}"): cc1, cc2, cc3, cc4 = st.columns(4) with cc1: clone_count = st.number_input("How many clones?", 1, 96, 1) clone_reagents = st.checkbox("Clone reagents", value=True) with cc2: clone_operator = st.text_input("Operator override", value=str(well.get("operator_id") or "")) clone_batch = st.text_input("Batch override", value=str(well.get("batch_id") or "")) with cc3: clone_plate = st.text_input("Plate ID", value=str(well.get("plate_id") or "")) # Derive geometry live from the current text field if clone_plate: ensure_default_plate_if_unset(clone_plate) _geom = get_plate_geometry(clone_plate) if clone_plate else None row_labels_clone, max_cols_clone = (_geom if _geom else ("ABCDEFGH", 12)) start_col = st.number_input("Start column", 1, int(max_cols_clone), int(well.get("col") or 1)) with cc4: current_row = str(well.get("row") or (row_labels_clone[0] if row_labels_clone else "A")) row_options = list(row_labels_clone) # Choose index safely idx = row_options.index(current_row) if current_row in row_options else 0 row_letter = st.selectbox("Row", row_options, index=idx) rep_start = st.number_input("Replicate start", 1, 999, int(well.get("replicate_id") or 1)) do_clone = st.form_submit_button("✨ Create clones") if do_clone: # Validate column range end_col = start_col + int(clone_count) - 1 if end_col > int(max_cols_clone): st.error(f"❌ Requested range {start_col}-{end_col} exceeds plate columns (max {max_cols_clone}). Reduce clone count or start column.") else: tmpl = get_well(record_id) if not tmpl: st.error("Template well not found.") else: reag_tmpl = get_reagents_template(record_id) if clone_reagents else None positions = [(row_letter, start_col + i, rep_start + i) for i in range(int(clone_count))] try: new_ids = [] for (r, c, rep) in positions: rid = new_record_id() payload = copy_well_payload( tmpl, new_record_id=rid, date_override=datetime.now().date().isoformat(), operator_override=(clone_operator or None), plate_id=(clone_plate or tmpl.get("plate_id")), row_letter=r, col_num=c, replicate_id=rep, batch_id=(clone_batch or None) ) create_well(payload, reagents_list=reag_tmpl) new_ids.append(rid) st.success(f"✅ Created {len(new_ids)} clone(s).") with st.expander("View created record IDs"): st.code("\n".join(new_ids[:min(10, len(new_ids))])) st.balloons() except Exception as e: st.error(f"❌ Error creating clones: {e}") def show_reagents_manager(codebook): st.header("Reagents Manager") df_wells = read_wells() if df_wells.empty: st.info("No wells found.") return options = [(f"{row['record_id'][:16]}… — {row.get('batch_id','N/A')}", row['record_id']) for _,row in df_wells.iterrows()] labels = [o[0] for o in options] label = st.selectbox("Select a well:", options=labels) record_id = dict(options)[label] reagents_df = get_reagents(record_id) st.subheader(f"Reagents for `{record_id}`") if not reagents_df.empty: keep = [c for c in ['reagent_id','reagent_name','reagent_class','purpose','stock_conc_value','stock_conc_units','volume_uL_per_mL','effective_conc_mM','lot_number','added_order'] if c in reagents_df.columns] st.dataframe(reagents_df[keep], use_container_width=True) del_sel = st.selectbox("Delete reagent:", options=[""]+[f"{r['reagent_id']} — {r['reagent_name']}" for _,r in reagents_df.iterrows()]) if del_sel and st.button("🗑️ Delete Selected Reagent"): reagent_id = int(del_sel.split(" — ")[0]) delete_reagent(reagent_id) st.success("Deleted.") st.rerun() else: st.info("No reagents yet.") st.subheader("Add New Reagent") with st.form(f"add_reagent_{record_id[:8]}"): c1,c2,c3 = st.columns(3) with c1: name = st.text_input("Reagent Name*") rclass = st.selectbox("Class", ["","buffer","base","acid","salt","media","additive","enzyme","crosslinker","other"]) purpose = st.text_input("Purpose") with c2: stock = st.number_input("Stock value", 0.0, 1e9, 1.0, 0.1) units = st.selectbox("Units", ["M","mM","µM","%","x","mg/mL","U/mL"]) vol = st.number_input("µL per mL", 0.0, 1000.0, 0.0, 0.5) with c3: lot = st.text_input("Lot #") order = st.number_input("Added order", 1, 99, (1 if reagents_df.empty else int(reagents_df['added_order'].max())+1)) # Calculate effective concentrations with PBS/DMEM hints eff = effective_mM(stock, units, vol) if eff is not None: st.caption(f"→ effective ~ **{eff:.2f} mM**") else: st.caption(f"→ effective: n/a for {units}") # Extra hints for PBS and DMEM name_lower = (name or "").strip().lower() if units == "x" and "pbs" in name_lower: final_x = pbs_final_x(stock, vol) if final_x is not None: st.caption(f"PBS final ≈ **{final_x:.2f}×**") if "dmem" in name_lower or ("media" in (rclass or "").lower()): media_pct = dmem_final_percent(vol) if media_pct is not None and media_pct > 0: st.caption(f"Media final ≈ **{media_pct:.2f}% v/v**") submit = st.form_submit_button("➕ Add Reagent") if submit: if not name: st.error("Name required.") else: add_reagent(dict( record_id=record_id, reagent_name=name, reagent_class=(rclass or None), purpose=(purpose or None), stock_conc_value=stock, stock_conc_units=units, volume_uL_per_mL=vol, effective_conc_mM=eff, lot_number=(lot or None), added_order=int(order) )) st.success("Added.") st.rerun() def show_events_logger(codebook): st.header("Events Logger") df_wells = read_wells() if df_wells.empty: st.info("No wells found.") return options = [(f"{row['record_id'][:16]}… — {row.get('batch_id','N/A')}", row['record_id']) for _,row in df_wells.iterrows()] labels = [o[0] for o in options] label = st.selectbox("Select a well:", options=labels) record_id = dict(options)[label] st.subheader(f"Events for `{record_id}`") ev = get_events(record_id) if not ev.empty: keep = [c for c in ['event_type','time_point_min','measurement_type','measurement_value','measurement_units','status_code','gel_strength_score_0to3','tilt_test_angle_deg','observation'] if c in ev.columns] st.dataframe(ev[keep], use_container_width=True) if 'measurement_value' in ev.columns and ev['measurement_value'].notna().any(): st.line_chart(ev.set_index('time_point_min')['measurement_value']) del_sel = st.selectbox("Delete event:", options=[""]+[f"{r['event_id']} — {r['event_type']} @ {r['time_point_min']} min" for _,r in ev.iterrows()]) if del_sel and st.button("🗑️ Delete Selected Event"): delete_event(int(del_sel.split(" — ")[0])) st.success("Deleted.") st.rerun() else: st.info("No events yet.") st.subheader("Log New Event") with st.form(f"add_event_{record_id[:8]}"): STATUS = codebook['status_code'] c1,c2 = st.columns(2) with c1: event_type = st.selectbox("Event Type*", ["","status","soften","liquefy","syneresis_onset","tilt_score","strength_score","OD_Reading","Other"]) tmin = st.number_input("Time Point (min)*", 0.0, 1e7, 0.0, 1.0) thours = st.number_input("Time from mix (hours)", 0.0, 1e6, 0.0, 0.1) with c2: day = st.number_input("Day from mix", 0, 10000, 0) gel_strength = st.selectbox("Gel Strength (0-3)", ["",0,1,2,3]) # Quick status picker (radio for common codes) st.caption("Status Code:") col_status1, col_status2 = st.columns([3, 1]) with col_status1: quick_status = st.radio( "Quick pick", ["(none)","liquid","weak_gel","soft_gel","stiff_gel","softened","liquidated"], index=0, horizontal=True, label_visibility="collapsed" ) with col_status2: custom_status = st.selectbox("Or select custom", [""] + STATUS, label_visibility="collapsed") # Use quick pick if selected, otherwise use dropdown if quick_status != "(none)": status_code = quick_status else: status_code = custom_status if custom_status else None c3,c4 = st.columns(2) with c3: mtype = st.text_input("Measurement Type (e.g., OD405, pH)") mval = st.number_input("Measurement Value", value=0.0, step=0.01) with c4: munits = st.text_input("Measurement Units") tilt = st.number_input("Tilt Angle (deg)", 0.0, 90.0, 0.0, 1.0) obs = st.text_area("Observation / Notes") operator = st.text_input("Observer ID") sub = st.form_submit_button("➕ Log Event") if sub: if not event_type: st.error("Event type required.") else: payload = dict( record_id=record_id, event_type=event_type, time_point_min=tmin, time_from_mix_hours=(None if thours==0 else thours), day_from_mix=(None if day==0 else day), status_code=(None if status_code=="" else status_code), gel_strength_score_0to3=(None if gel_strength=="" else int(gel_strength)), tilt_test_angle_deg=(None if tilt==0 else tilt), measurement_type=(None if mtype.strip()=="" else mtype), measurement_value=(None if mval==0 else mval), measurement_units=(None if munits.strip()=="" else munits), observation=(None if obs.strip()=="" else obs), operator_id=(None if operator.strip()=="" else operator) ) try: add_event(payload) st.success("✅ Event logged.") st.rerun() except Exception as e: st.error(f"❌ Error: {e}") def show_plate_map_wizard(codebook): st.header("🧩 Plate Map Wizard — bulk create wells") st.caption("Tip: choose a template well to copy base metadata and (optionally) reagents.") df_wells = read_wells() # Pick a template well tmpl_options = [(f"{row['record_id'][:8]}… — {row.get('family','?')} / {row.get('batch_id','N/A')}", row['record_id']) for _,row in df_wells.iterrows()] if not df_wells.empty else [] label = st.selectbox("Template well (optional)", options=["(none)"] + ([o[0] for o in tmpl_options] if tmpl_options else [])) tmpl_id = None if label == "(none)" or not tmpl_options else dict(tmpl_options)[label] st.subheader("🧫 Choose Plate") st.caption("Reuse an existing physical plate or create a new one") # Load recent plates recent_plates = get_recent_plates(limit=50) wizard_plate_mode = st.radio( "Plate Option", ["Reuse Existing", "Create New"], horizontal=True, key="wizard_plate_mode" ) if wizard_plate_mode == "Reuse Existing" and recent_plates: plate_options_wiz = [""] + [f"{p['plate_id']} ({p['n_wells']} wells, {p['n_batches']} batches, last: {p['last_use']})" for p in recent_plates] plate_ids_wiz = [""] + [p['plate_id'] for p in recent_plates] sel_idx = st.selectbox("Select Plate*", range(len(plate_options_wiz)), format_func=lambda i: plate_options_wiz[i], key="wiz_plate_sel") plate_id = plate_ids_wiz[sel_idx] if sel_idx > 0 else "" if plate_id: st.success(f"✅ Reusing: {plate_id}") else: # Create new wiz_p_col1, wiz_p_col2 = st.columns([2, 1]) with wiz_p_col1: plate_type_wiz = st.selectbox("Plate Type", ["6","12","24","48","96","384"], index=4, key="wiz_ptype") suggested_plate_wiz = generate_plate_id(plate_type_wiz) plate_id = st.text_input("Plate ID*", value=suggested_plate_wiz, key="wiz_plate_id") with wiz_p_col2: if st.button("🔄 Next Plate", key="wiz_next_plate"): parts = plate_id.split("-") if len(parts) == 3 and parts[-1].isdigit(): new_seq = int(parts[-1]) + 1 plate_id = f"{parts[0]}-{parts[1]}-{new_seq:03d}" st.rerun() st.info(f"Creating new plate: {plate_id}") # Ensure default if it looks like '...-96' etc. if plate_id: ensure_default_plate_if_unset(plate_id) geom = get_plate_geometry(plate_id) if plate_id else None if geom: row_labels, max_cols = geom else: row_labels, max_cols = "ABCDEFGH", 12 # fallback with st.expander("⚙️ Plate geometry (register / edit)", expanded=False): pg1, pg2 = st.columns([2,1]) with pg1: new_rows = st.text_input("Row labels", value=row_labels) with pg2: new_cols = st.number_input("Max columns", min_value=1, max_value=48, value=int(max_cols)) desc = st.text_input("Description (optional)", value="") if st.button("💾 Save plate geometry", key="save_plate_geom_wizard"): try: upsert_plate_geometry(plate_id, new_rows.strip(), int(new_cols), description=(desc or None)) st.success("✅ Plate geometry saved.") row_labels, max_cols = new_rows.strip(), int(new_cols) except Exception as e: st.error(f"❌ Failed to save geometry: {e}") # Base fields if no template chosen (or overrides) st.subheader("Base metadata / overrides") c1,c2,c3 = st.columns(3) with c1: family = st.selectbox( "ECM Family", options=[""] + codebook['family'], index=2 if "decECM" in codebook['family'] else 0 # Default to "decECM" ) batch_id = st.text_input("Batch ID") operator_id = st.text_input("Operator ID", value="") with c2: target_pH = st.number_input("Target pH", 0.0, 14.0, 7.2, 0.05) tempC = st.number_input("Incubation temp (°C)", 0.0, 60.0, 37.0, 0.5) with c3: pre_pH = st.number_input("Pre pH", 0.0, 14.0, 4.0, 0.1) protein = st.number_input("Total protein (mg/mL)", 0.0, 100.0, 7.0, 0.1) cond_mS = st.number_input("Pre-conductivity (mS/cm)", 0.0, 100.0, 3.0, 0.1) # ECM Provenance (species and tissue origin) st.subheader("🧬 ECM Provenance") prov_wiz1, prov_wiz2 = st.columns(2) with prov_wiz1: dec_species_w = st.selectbox( "Origin species*" if family == "decECM" else "Origin species", [""] + codebook['species'], index=1 if "human" in codebook['species'] else 0, # Default to "human" help="Required for decECM, optional for other ECM types" ) with prov_wiz2: dec_tissue_w = st.selectbox( "Source tissue/organ*" if family == "decECM" else "Source tissue/organ", [""] + codebook['tissues'], index=1 if "mammary" in codebook['tissues'] else 0, # Default to "mammary" help="Required for decECM, optional for other ECM types" ) st.subheader("Select well positions") mode = st.radio( "Selection mode", ["Manual picks (A2, B6, ...)", "Row/Column range"], index=0, horizontal=True ) rep_start = st.number_input("Replicate start", 1, 999, 1) positions = [] # will be [(row, col)] if mode == "Manual picks (A2, B6, ...)": manual_text = st.text_area( "Enter wells (comma/space/newline separated):", placeholder="e.g., A2, B6, H12 or A1-A3, B4:B6", height=100, help="Supports single wells (A2), ranges (A1-A3, B4:B6), and mixed formats. Invalid entries are ignored." ) raw_picks = _parse_manual_well_tokens(manual_text, row_labels, int(max_cols)) if manual_text and not raw_picks: st.warning("⚠️ No valid wells found. Use patterns like A2, B6, A1-A3, B4:B6.") positions = raw_picks else: # Keep existing range UI for folks who like blocks sel_rows = st.multiselect("Rows", list(row_labels), default=list(row_labels)[:min(2, len(row_labels))]) c_from, c_to = st.columns(2) with c_from: col_start = st.number_input("Column start", 1, int(max_cols), 1) with c_to: col_end = st.number_input("Column end", 1, int(max_cols), min(6, int(max_cols))) if col_start > col_end: st.warning(f"⚠️ Column start ({col_start}) > column end ({col_end}) — swapping.") col_start, col_end = col_end, col_start # Validate rows, but don't hard stop; just skip bad ones good_rows = [r for r in sel_rows if r in row_labels] bad_rows = [r for r in sel_rows if r not in row_labels] if bad_rows: st.warning(f"Ignoring invalid rows for plate '{plate_id}': {', '.join(bad_rows)}") for r in good_rows: for c in range(int(col_start), int(col_end) + 1): positions.append((r, c)) # Deduplicate positions just in case positions = list(dict.fromkeys(positions)) st.write(f"Planned wells: **{len(positions)}**") if positions: prev = pd.DataFrame([{"row": r, "col": c, "replicate_id": rep_start + i} for i, (r, c) in enumerate(positions)]) st.dataframe(prev, use_container_width=True, height=200) st.subheader("Reagents template") clone_reagents = st.checkbox("Copy reagents from template well", value=True if tmpl_id else False) # Submit if st.button("🚀 Create wells", type="primary"): if not positions: st.error("No valid well positions selected. Please choose wells using either manual picks or row/column range.") return # Validate decECM provenance requirements if family == "decECM": if not dec_species_w or dec_species_w == "": st.error("❌ Origin species is required for decECM") return if not dec_tissue_w or dec_tissue_w == "": st.error("❌ Source tissue/organ is required for decECM") return # Build a template well payload if tmpl_id: tmpl = get_well(tmpl_id) if tmpl is None: st.error("Template well not found.") return reag_tmpl = get_reagents_template(tmpl_id) if clone_reagents else None else: # synthesize a minimal template from overrides tmpl = dict( record_id=new_record_id(), # temporary, will be replaced date=datetime.now().date().isoformat(), operator_id=(operator_id or None), family=(family or None), batch_id=(batch_id or None), donor_id=None, plate_id=(plate_id or None), # ensure plate is set row=None, col=None, replicate_id=None, pre_storage_days_4C=0, pre_storage_freeze_cycles=0, ecm_total_protein_mgml=protein, pre_pH=pre_pH, pre_conductivity_mS=cond_mS, temp_incubation_C=tempC, uv_A220=None, uv_A230=None, uv_A260=None, uv_A280=None, uv_ratio_A220_A280=None, sds_smear_index=None, sds_alpha_ratio=None, hydroxyproline_mgml=None, dmmB_GAG_ugml=None, viscosity_proxy_sec=None, probe_type=None, target_pH=target_pH, od_wavelength_nm=None, od_sampling_interval_min=None, time_to_halfmax_min=None, slope_OD_per_min=None, final_OD=None, lag_time_min=None, gel_binary=None, gel_strength_score_0to3=None, tilt_test_angle_deg=None, time_to_handle_min=None, failure_mode=None, suspected_cause=None, confidence_0to1=None, syneresis_binary=None, syneresis_time_min=None, precipitate_binary=None, color_shift=None, notes_pre=None, notes_post=None, app_recipe_recommended=None, app_pgel_pred=None, app_thalf_pred_min=None, app_uncertainty=None, counterfactual_recipe=None, counterfactual_expected_pgel=None, ecm_origin_species=(dec_species_w or None), ecm_source_tissue=(dec_tissue_w or None), split=None ) reag_tmpl = None # Build final positions with replicate increments pos_with_rep = [(r, c, rep_start + i) for i,(r,c) in enumerate(positions)] try: with st.spinner(f"Creating {len(pos_with_rep)} wells..."): new_ids = [] for (r, c, rep) in pos_with_rep: rid = new_record_id() payload = copy_well_payload( tmpl, new_record_id=rid, date_override=datetime.now().date().isoformat(), operator_override=(operator_id or tmpl.get("operator_id")), plate_id=(plate_id or tmpl.get("plate_id")), # ensure plate is set row_letter=r, col_num=c, replicate_id=rep, batch_id=(batch_id or tmpl.get("batch_id")) ) create_well(payload, reagents_list=reag_tmpl) new_ids.append(rid) st.success(f"✅ Created {len(new_ids)} wells!") with st.expander("View created record IDs"): st.code("\n".join(new_ids[:min(20, len(new_ids))])) st.balloons() except Exception as e: st.error(f"❌ Failed to create wells: {e}") import traceback with st.expander("Error details"): st.code(traceback.format_exc()) def show_plates_registry(): st.header("🧱 Plates Registry & Usage Tracker") st.caption("Manage plate geometries and track physical plate reuse") # Tab view for registry vs usage tab1, tab2 = st.tabs(["📋 Plate Geometries", "📊 Plate Usage Analytics"]) with tab1: conn = get_connection() df = pd.read_sql_query( "SELECT plate_id, row_labels, max_cols, description, updated_at FROM plates_registry ORDER BY updated_at DESC", conn ) conn.close() st.subheader("Registered plates") if df.empty: st.info("No plates registered yet. Add one below to enforce geometry validation.") else: st.dataframe(df, use_container_width=True) st.caption(f"**Total registered plates:** {len(df)}") with tab2: st.subheader("Physical Plate Usage Analytics") st.caption("Track how physical plates are reused across experiments") # Get plate usage stats recent_plates = get_recent_plates(limit=100) if not recent_plates: st.info("No plates have been used yet.") else: # Convert to DataFrame for display df_usage = pd.DataFrame(recent_plates) # Summary metrics col1, col2, col3, col4 = st.columns(4) with col1: st.metric("Total Plates", len(df_usage)) with col2: st.metric("Total Wells", df_usage['n_wells'].sum()) with col3: avg_reuse = df_usage['n_batches'].mean() st.metric("Avg Batches/Plate", f"{avg_reuse:.1f}") with col4: max_reuse = df_usage['n_batches'].max() st.metric("Max Batches/Plate", int(max_reuse)) st.markdown("---") # Show plates with high reuse (good lab practice) st.markdown("**🌟 Most Reused Plates:**") df_sorted = df_usage.sort_values('n_batches', ascending=False).head(10) st.dataframe( df_sorted[['plate_id', 'n_wells', 'n_batches', 'n_gelations', 'first_use', 'last_use']], use_container_width=True, hide_index=True ) # Alert for plates that might need cleaning/replacement st.markdown("---") st.markdown("**⚠️ Plates with High Usage (Consider Physical Inspection):**") high_use = df_usage[df_usage['n_wells'] > 50] if not high_use.empty: st.dataframe( high_use[['plate_id', 'n_wells', 'first_use', 'last_use']], use_container_width=True, hide_index=True ) st.caption("Physical plates with 50+ wells may need cleaning or inspection for contamination") else: st.success("✅ No plates with excessive usage") # Search for specific plate st.markdown("---") st.subheader("🔍 Plate Details") search_plate = st.selectbox( "Select Plate to View Details", [""] + df_usage['plate_id'].tolist() ) if search_plate: # Get all wells from this plate conn = get_connection() wells_on_plate = pd.read_sql_query(""" SELECT record_id, date, batch_id, gelation_id, row, col, family, gel_binary, gel_strength_score_0to3 FROM wells_master_v4 WHERE plate_id = ? ORDER BY date DESC, row, col """, conn, params=(search_plate,)) conn.close() if not wells_on_plate.empty: st.markdown(f"**Plate: {search_plate}**") # Summary col_det1, col_det2, col_det3 = st.columns(3) with col_det1: st.metric("Total Wells", len(wells_on_plate)) st.metric("Date Range", f"{wells_on_plate['date'].min()} to {wells_on_plate['date'].max()}") with col_det2: st.metric("Unique Batches", wells_on_plate['batch_id'].nunique()) st.metric("Unique Gelations", wells_on_plate['gelation_id'].nunique()) with col_det3: gel_rate = wells_on_plate['gel_binary'].mean() if 'gel_binary' in wells_on_plate.columns else 0 st.metric("Overall Gel Rate", f"{gel_rate:.1%}") avg_strength = wells_on_plate['gel_strength_score_0to3'].mean() if 'gel_strength_score_0to3' in wells_on_plate.columns else 0 st.metric("Avg Strength", f"{avg_strength:.2f}/3") # Full table st.markdown("**All Wells on This Plate:**") st.dataframe(wells_on_plate, use_container_width=True, height=400) # Export plate data if st.button("📥 Export This Plate to CSV"): csv = wells_on_plate.to_csv(index=False) st.download_button( "Download CSV", csv, file_name=f"{search_plate}_wells.csv", mime="text/csv" ) st.markdown("---") st.subheader("Add / Update Plate") st.caption("Register a new plate or update an existing one. Auto-detects 96/48/24 if in plate_id.") c1, c2, c3 = st.columns([2,1,2]) with c1: pid = st.text_input("Plate ID*", placeholder="PLT-001-96", help="Include 96/48/24 for auto-detection") with c2: rows = st.text_input("Row labels*", value="ABCDEFGH", help="E.g., ABCDEFGH or ABCDEF") cols = st.number_input("Max columns*", 1, 48, 12) with c3: desc = st.text_input("Description", value="", placeholder="96-well screening plate") if st.button("💾 Save Plate Geometry", type="primary"): if not pid: st.error("Plate ID is required!") else: try: upsert_plate_geometry(pid, rows, int(cols), description=(desc or None)) st.success(f"✅ Saved geometry for '{pid}'.") st.balloons() st.rerun() except Exception as e: st.error(f"❌ Failed: {e}") st.markdown("---") st.subheader("⚠️ Delete Plate (Danger Zone)") st.caption("Deleting a plate geometry won't affect existing wells, but new wells won't enforce bounds.") del_pid = st.text_input("Plate ID to delete", placeholder="PLT-001-96") if st.button("🗑️ Delete Plate Geometry", type="secondary"): if not del_pid: st.error("Enter a plate ID to delete.") else: try: with tx() as con: result = con.execute("DELETE FROM plates_registry WHERE plate_id=?", (del_pid,)) if result.rowcount == 0: st.warning(f"Plate '{del_pid}' not found in registry.") else: # Clear cache try: _get_plate_geom_cached.cache_clear() except Exception: pass st.success(f"✅ Deleted plate geometry for '{del_pid}'.") st.rerun() except Exception as e: st.error(f"❌ Failed: {e}") st.markdown("---") st.subheader("💡 Tips") st.markdown(""" **Auto-detection:** - Plate IDs containing "96" → Auto-register as 96-well (A-H × 12) - Plate IDs containing "48" → Auto-register as 48-well (A-F × 8) - Plate IDs containing "24" → Auto-register as 24-well (A-D × 6) **Custom formats:** - 384-well: Row labels = ABCDEFGHIJKLMNOP (16), Max cols = 24 - 8-well slide: Row labels = AB (2), Max cols = 4 - Custom array: Define any format! **Validation:** - Row labels must be letters (auto-uppercased, duplicates rejected) - Max columns must be ≥ 1 - Geometry enforced in New Entry, Clone, and Plate Map Wizard """) def show_images_manager(codebook): """Image upload and gallery manager.""" st.header("📷 Gel Images") st.caption("Upload and manage images for visual QC and model training") df_wells = read_wells() if df_wells.empty: st.info("No wells yet. Create wells first before uploading images.") return # Select well options = [(f"{r['record_id'][:10]}… — {r.get('batch_id','N/A')} — {r.get('family','N/A')}", r['record_id']) for _, r in df_wells.iterrows()] label = st.selectbox("Select a well", options=[o[0] for o in options]) record_id = dict(options)[label] st.markdown("---") # Upload section st.subheader("📤 Upload Images") # Optional: Link to specific event df_events = get_events(record_id) event_id_link = None if not df_events.empty: with st.expander("🔗 Link to specific event (optional)", expanded=False): st.caption("Associate this image with a specific time point/observation") event_options = ["(none - general well image)"] + [ f"Day {row['day_from_mix']} — {row['event_type']} — {row.get('status_code','')} (ID: {row['event_id']})" for _, row in df_events.iterrows() ] event_choice = st.selectbox("Event", event_options) if event_choice != "(none - general well image)": # Extract event_id from the string import re match = re.search(r'\(ID: (\d+)\)', event_choice) if match: event_id_link = int(match.group(1)) uploaded = st.file_uploader( "Drop images here", type=["jpg", "jpeg", "png", "tif", "tiff", "webp"], accept_multiple_files=True, help="Max ~25 MB per image. You can upload multiple images at once or come back later to upload more!" ) colA, colB, colC = st.columns(3) with colA: kind = st.selectbox("Kind", ["photo", "tilt", "macro", "micrograph", "other"]) with colB: lighting = st.text_input("Lighting", placeholder="top, side, transillumination") with colC: magnification = st.text_input("Magnification", placeholder="phone, 4x, 10x") caption = st.text_input("Caption (optional)", placeholder="e.g., 'Gel at 24h, starting to soften'") tilt_deg = st.number_input("Tilt angle (deg)", 0.0, 90.0, 0.0, 1.0, help="For tilt-test photos") qc_flag = st.checkbox("Include in training", value=True) operator = st.text_input("Uploader ID", value=st.session_state.get("last_operator_id", "")) if uploaded and st.button("📷 Upload Images", type="primary"): for file in uploaded: try: raw = file.read() # Size limit (25 MB) if len(raw) > 25 * 1024 * 1024: st.error(f"❌ {file.name}: Too large (max 25 MB)") continue sha = _sha256_bytes(raw) mime = file.type or "application/octet-stream" ext = _safe_ext(mime) img_id = new_record_id() # Paths rel_dir = Path("media") / "images" / record_id rel_path = rel_dir / f"{img_id}{ext}" abs_path = ROOT / rel_path abs_path.parent.mkdir(parents=True, exist_ok=True) with open(abs_path, "wb") as f: f.write(raw) # Thumbnail + dims + EXIF thm_rel = Path("media") / "thumbs" / record_id / f"{img_id}.jpg" thm_abs = ROOT / thm_rel width, height = _probe_dims(raw) taken_at = _exif_datetime(Image.open(io.BytesIO(raw))) or datetime.now().isoformat() _save_thumbnail(raw, thm_abs) payload = { "image_id": img_id, "record_id": record_id, "event_id": event_id_link, # Link to event if selected "taken_at": taken_at, "operator_id": (operator or None), "caption": (caption or None), "kind": kind, "mime_type": mime, "width_px": int(width), "height_px": int(height), "sha256_hex": sha, "file_relpath": str(rel_path), "thumb_relpath": str(thm_rel), "lighting": (lighting or None), "magnification": (magnification or None), "tilt_deg": (None if tilt_deg == 0 else float(tilt_deg)), "qc_flag": 1 if qc_flag else 0 } add_image_record(payload) st.success(f"✅ Uploaded {file.name}") except Exception as e: st.error(f"❌ Failed {file.name}: {e}") st.balloons() st.rerun() st.markdown("---") # Gallery st.subheader("🖼️ Image Gallery") imgs = get_images_for_record(record_id) if imgs.empty: st.info("No images for this well yet.") else: st.caption(f"**Total images:** {len(imgs)}") # Grid view of thumbnails cols = st.columns(4) for i, (_, row) in enumerate(imgs.iterrows()): c = cols[i % 4] with c: thm = ROOT / row["thumb_relpath"] if row.get("thumb_relpath") else None if thm and thm.exists(): st.image(str(thm), caption=row.get("caption") or row["image_id"][:8], use_column_width=True) else: st.caption("🖼️ (thumbnail missing)") st.caption(f"**{row['kind']}** • {row['width_px']}×{row['height_px']}") # Show event link if present if row.get("event_id"): st.caption(f"📅 Linked to event #{row['event_id']}") # Show capture time if row.get("taken_at"): taken_short = row['taken_at'][:10] if len(row['taken_at']) >= 10 else row['taken_at'] st.caption(f"📸 {taken_short}") if row.get("lighting"): st.caption(f"💡 {row['lighting']}") if row.get("magnification"): st.caption(f"🔍 {row['magnification']}") if row.get("tilt_deg") and row['tilt_deg'] > 0: st.caption(f"📐 Tilt: {row['tilt_deg']}°") if st.button("🗑️ Delete", key=f"del_{row['image_id']}"): delete_image(row["image_id"]) st.success("Image deleted") st.rerun() def show_export_page(): st.header("Export Data") # Backup section at top st.subheader("🧷 Database Backup") col_b1, col_b2, col_b3 = st.columns([1, 2, 1]) with col_b1: if st.button("📦 Backup Database", use_container_width=True): try: backups = ROOT / "backups" backups.mkdir(exist_ok=True) ts = datetime.now().strftime("%Y%m%d_%H%M%S") dest = backups / f"gelpredict_{ts}.db" shutil.copy2(DB_PATH, dest) st.success(f"✅ Backup created: `{dest.name}`") st.caption(f"Location: `{dest.relative_to(ROOT)}`") except Exception as e: st.error(f"❌ Backup failed: {e}") with col_b2: st.caption("Creates timestamped copy of `gelpredict.db` in `/backups`.") # Show recent backups backups_dir = ROOT / "backups" if backups_dir.exists(): backups_list = sorted(backups_dir.glob("gelpredict_*.db"), reverse=True) if backups_list: st.caption(f"💾 Recent backups: {len(backups_list)} found") with col_b3: if st.button("🧹 VACUUM (compact)", use_container_width=True): try: with tx() as con: con.execute("VACUUM") st.success("✅ Database compacted") st.caption("Reclaimed unused space") except Exception as e: st.error(f"❌ Failed: {e}") st.markdown("---") df_wells = read_wells(use_effective_view=True) if df_wells.empty: st.info("No data to export yet.") return st.subheader("📊 Wells (preview)") st.dataframe(df_wells.head(10), use_container_width=True) c1,c2,c3 = st.columns(3) with c1: st.download_button( "⬇️ Wells (CSV)", df_wells.to_csv(index=False), file_name=f"wells_master_{datetime.now().strftime('%Y%m%d')}.csv", mime="text/csv" ) with c2: conn = get_connection() df_rg = pd.read_sql_query("SELECT * FROM reagents_per_well", conn) conn.close() if not df_rg.empty: st.download_button( "⬇️ Reagents (CSV)", df_rg.to_csv(index=False), file_name=f"reagents_per_well_{datetime.now().strftime('%Y%m%d')}.csv", mime="text/csv" ) with c3: conn = get_connection() df_ev = pd.read_sql_query("SELECT * FROM events_long", conn) conn.close() if not df_ev.empty: st.download_button( "⬇️ Events (CSV)", df_ev.to_csv(index=False), file_name=f"events_long_{datetime.now().strftime('%Y%m%d')}.csv", mime="text/csv" ) st.subheader("🤖 Export for Training") st.caption("Complete dataset with all experimental parameters, protocols, and outcomes") # Comprehensive training dataset with all new parameters training_cols = [ # Identifiers & metadata 'record_id','date','operator_id','family','batch_id','gelation_id','donor_id', 'ecm_origin_species','ecm_source_tissue','plate_id','row','col','replicate_id', # Pre-processing tissue storage (NEW!) 'pre_storage_days_4C','pre_storage_fresh_notes','pre_storage_freeze_cycles','pre_storage_temp_freezer','pre_storage_duration_months','pre_storage_frozen_in','pre_storage_thaw_method','pre_storage_thaw_duration_min','pre_storage_ft_notes', # Processing & gelation protocols (JSON) 'processing_protocol','gelation_protocol', # Composition measurements 'ecm_total_protein_mgml','protein_assay_method','gel_volume_uL', 'pre_pH','pre_conductivity_mS','temp_incubation_C', # Spectroscopy 'uv_A220','uv_A280','uv_ratio_A220_A280', 'sds_smear_index','sds_alpha_ratio', # Advanced biochemical assays (optional) 'hydroxyproline_mgml','dmmB_GAG_ugml','viscosity_proxy_sec', # Pre-gel viscosity (Scientific Reports 2019) (optional) 'pre_gel_viscosity_mPas','pre_gel_viscosity_temp_C','shear_rate_s_minus1', # Turbidity/gelation kinetics (Scientific Reports 2019, MDPI 2021) (optional) 'turbidity_lag_time_min','turbidity_t_half_min','turbidity_slope_per_min', # Viscoelastic/rheological properties (Saldin et al. 2016, Brazdaru et al. 2015) (optional) 'storage_modulus_G_prime_Pa','loss_modulus_G_double_prime_Pa','tan_delta', # Residual contaminants (cornea ECM study 2019) (optional) 'sds_residual_ppm','detergent_residual_binary','cytotoxicity_score_0to3', # Micro-DSC parameters (optional) 'dsc_onset_T_C','dsc_peak_T_C','dsc_delta_H_J_g', # Circular Dichroism parameters (optional) 'cd_molar_ellipticity_222nm_mdeg','cd_helix_percent', # FTIR parameters (optional) 'ftir_amide3_1450_ratio', # Additional residual contaminants (optional) 'dna_residual_ng_mg','endotoxin_residual_EU_mg','protease_residual_U_mg', # Swelling ratio parameters (optional) 'swelling_ratio_Q','gel_fresh_weight_mg','gel_swollen_weight_mg','gel_dry_weight_mg', # Enzymatic degradation parameters (optional) 'enzymatic_degradation_t_half_min','collagenase_concentration_U_mL', # Diffusion/FRAP parameters (optional) 'diffusion_coefficient_um2_s','frap_t_half_s','probe_radius_um', # Test conditions 'probe_type','target_pH', 'od_wavelength_nm','od_sampling_interval_min','time_to_halfmax_min', # Effective ionic concentrations (from view - will be renamed for AI compatibility) 'eff_NaCl_mM','eff_CaCl2_mM','pbs_final_x','media_percent', # Gelation kinetics (NEW!) 'time_to_gel_min','pre_gel_storage_temp_C','pre_gel_storage_duration_min','pre_gel_storage_notes', # Outcomes 'gel_binary','gel_strength_score_0to3','tilt_test_angle_deg', 'failure_mode','suspected_cause','confidence_0to1', 'syneresis_binary','precipitate_binary','color_shift', # Degradation tracking (NEW!) 'disintegrated','days_to_disintegration','reliquefied','days_to_reliquefaction', 'plate_adhesion','adhesion_notes', # Commercial product tracking 'is_commercial_product','commercial_vendor','commercial_product_name','commercial_website', # Notes 'notes_pre','notes_post', # Split 'split' ] export_cols = [c for c in training_cols if c in df_wells.columns] df_training = df_wells[export_cols].copy() # Rename columns to match AI model expectations (DEFAULT_FEATURES in src/train_baseline.py) ai_column_mapping = { 'eff_NaCl_mM': 'NaCl_mM_added', 'eff_CaCl2_mM': 'CaCl2_mM_added', 'pbs_final_x': 'PBS_10x_uL_per_mL', 'media_percent': 'DMEM_percent' } # Only rename columns that exist in the dataframe rename_map = {old: new for old, new in ai_column_mapping.items() if old in df_training.columns} if rename_map: df_training = df_training.rename(columns=rename_map) st.write(f"**Training dataset:** {len(df_training)} wells × {len(df_training.columns)} features") st.caption("✅ Column names aligned with AI model expectations (`src/train_baseline.py`)") # Show summary of what's included with st.expander("📋 Features included in training export"): feature_groups = { "Identifiers": ['record_id','date','family','batch_id','gelation_id'], "Pre-storage": ['pre_storage_days_4C','pre_storage_fresh_notes','pre_storage_freeze_cycles','pre_storage_temp_freezer','pre_storage_duration_months','pre_storage_frozen_in','pre_storage_thaw_method','pre_storage_thaw_duration_min','pre_storage_ft_notes'], "Protocols": ['processing_protocol','gelation_protocol'], "Composition": ['ecm_total_protein_mgml','protein_assay_method','pre_pH','pre_conductivity_mS'], "Ionic & Media (AI features)": ['NaCl_mM_added','CaCl2_mM_added','PBS_10x_uL_per_mL','DMEM_percent'], "Gelation Kinetics": ['time_to_gel_min','pre_gel_storage_temp_C','pre_gel_storage_duration_min'], "Degradation": ['disintegrated','days_to_disintegration','reliquefied','days_to_reliquefaction','plate_adhesion'], "Outcomes": ['gel_binary','gel_strength_score_0to3','failure_mode'] } for group_name, cols in feature_groups.items(): available = [c for c in cols if c in export_cols] if available: st.caption(f"**{group_name}:** {len(available)} fields") st.download_button( "⬇️ Training Dataset (CSV)", df_training.to_csv(index=False), file_name=f"ecm_runs_export_{datetime.now().strftime('%Y%m%d')}.csv", mime="text/csv", use_container_width=True ) st.success("✅ Includes all new parameters: pre-storage, protocols (JSON), gelation kinetics, degradation tracking") st.caption("💡 **Next step:** Use `src/feature_engineering.py` to parse JSON protocols and extract features (decell method, dialysis acid concentration, processing temps, etc.)") st.markdown("---") st.subheader("📑 Data Dictionary") st.caption("Auto-generated from field specifications — perfect for methods sections and collaborators") if st.button("📑 Generate Data Dictionary", use_container_width=True): try: dict_path = ROOT / "data_dictionary.csv" df_dict = export_data_dictionary(FIELD_SPEC, dict_path) st.success(f"✅ Data dictionary generated ({len(df_dict)} fields)") # Preview with st.expander("Preview data dictionary"): st.dataframe(df_dict.head(20), use_container_width=True) # Download csv_dict = df_dict.to_csv(index=False) st.download_button( "⬇️ Download Data Dictionary (CSV)", csv_dict, file_name="GelPredict_DataDictionary.csv", mime="text/csv", use_container_width=True ) except Exception as e: st.error(f"❌ Error generating dictionary: {e}") st.markdown("---") st.subheader("📤 Export Excel Workbook (for PIs)") st.caption("📊 Professional workbook with charts, pivots, and data dictionary") exporter = ROOT / "export_to_excel.py" if st.button("📊 Generate Excel Export", type="primary", use_container_width=True): if not exporter.exists(): st.error("❌ export_to_excel.py not found in project root.") else: with st.spinner("Generating Excel workbook with charts..."): result = subprocess.run(["python", str(exporter)], capture_output=True, text=True) # Parse output to find the created file out_path = None if result.stdout: for line in result.stdout.splitlines()[::-1]: if line.strip().endswith(".xlsx"): # Extract just the filename from the path out_path = ROOT / Path(line.strip()).name break # Fallback: construct expected filename if out_path is None: ts = datetime.now().strftime("%Y%m%d_%H%M") out_path = ROOT / f"GelPredict_Export_{ts}.xlsx" if result.returncode == 0 and out_path.exists(): # Success toast st.toast("✅ Workbook ready!", icon="📊") with open(out_path, "rb") as f: st.download_button( "⬇️ Download Excel Workbook", f, file_name=out_path.name, mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", use_container_width=True ) st.success(f"✅ Excel export complete: {out_path.name}") # Show export log if result.stdout: with st.expander("View export log"): st.code(result.stdout) else: st.error("❌ Export failed — ensure Python can import openpyxl and pandas.") st.info("💡 Run: `pip install openpyxl`") if result.stderr: with st.expander("Error details"): st.code(result.stderr) st.markdown("---") # Image manifest export st.subheader("🖼️ Images Manifest (for training)") st.caption("Export image metadata for model training with visual features") conn = get_connection() df_img = pd.read_sql_query(""" SELECT gi.image_id, gi.record_id, gi.event_id, gi.qc_flag, gi.kind, gi.taken_at, gi.file_relpath, gi.thumb_relpath, gi.width_px, gi.height_px, gi.sha256_hex, gi.lighting, gi.magnification, gi.tilt_deg, gi.caption, w.family, w.batch_id, w.gel_binary, w.gel_strength_score_0to3, w.target_pH, w.temp_incubation_C, w.date FROM gel_images gi LEFT JOIN wells_master_v4 w ON w.record_id = gi.record_id ORDER BY gi.created_at DESC """, conn) conn.close() if df_img.empty: st.info("No images uploaded yet.") else: st.caption(f"**Total images:** {len(df_img)} ({len(df_img[df_img['qc_flag']==1])} marked for training)") # Preview with st.expander("Preview image metadata"): st.dataframe(df_img.head(12), use_container_width=True) # Download st.download_button( "⬇️ Images Manifest (CSV)", df_img.to_csv(index=False), file_name=f"gel_images_manifest_{datetime.now().strftime('%Y%m%d')}.csv", mime="text/csv", use_container_width=True ) # ============================================================================ # RUN # ============================================================================ if __name__ == "__main__": main()