""" Spatial Seeding Builder for Cell Growth GUIs - Complex bioprinting/microinjection pattern specification - XY patterns, Z-depth strategies, cell distribution - JSON storage for flexible pattern encoding """ import streamlit as st import json from typing import Dict, List, Optional, Tuple from shared_parameters import ( INJECTION_PATTERNS, Z_DEPTH_STRATEGIES, SPACING_PATTERNS, SPACING_RANGES, CELLS_PER_INJECTION_STRATEGIES, INJECTION_PARAMS, WELL_GEOMETRY, DEFAULT_BIOPRINT_PARAMS ) def calculate_hydrogel_height(volume_uL: float, well_type: str) -> float: """ Calculate hydrogel height in mm based on volume and well geometry. Args: volume_uL: Volume of hydrogel in microliters well_type: e.g., "96-well", "24-well", "6-well" Returns: Height in mm """ if well_type not in WELL_GEOMETRY: return 0.0 area_mm2 = WELL_GEOMETRY[well_type]["area_mm2"] # Convert volume from μL to mm³ (1 μL = 1 mm³) volume_mm3 = volume_uL # Height = Volume / Area height_mm = volume_mm3 / area_mm2 return height_mm def show_spatial_seeding_builder( key_prefix: str = "spatial", hydrogel_volume_uL: float = None, well_type: str = None, seeding_method: str = None, is_literature: bool = False ) -> Optional[Dict]: """ Interactive UI for building spatial seeding patterns (works for ALL seeding methods). Optional add-on component like media builder - captures spatial context when available. Not just for bioprinting! Also captures: - Simple top-seeding density patterns - Mixed-in-gel cell distribution - Literature data with partial spatial info Args: key_prefix: Unique key prefix for session state hydrogel_volume_uL: Volume of hydrogel in well (for height calculation) well_type: e.g., "96-well", "24-well" (for height calculation) seeding_method: Primary seeding method (shows relevant options) is_literature: If True, shows "unknown" options for missing data Returns JSON-serializable dict with full pattern specification, or None if not applicable. Example output: { "pattern_type": "grid_2d", "rows": 3, "columns": 10, "xy_spacing_mm": 0.5, "spacing_pattern": "uniform", "z_strategy": "void_formation", "z_ref": "from_bottom", "z_start_mm": 0.5, "z_end_mm": 1.5, "hydrogel_height_mm": 2.0, "cells_per_injection": 50, "cell_distribution": "uniform", "needle_gauge": 30, "injection_volume_uL": 5.0, "total_injections": 30, "total_cells": 1500, "notes": "3 rows of 10 injections, creating vertical voids" } """ # Optional expander (like media builder) - COLLAPSED by default with st.expander("🎯 Spatial Seeding Details (Optional)", expanded=False): st.caption("📍 Skip this for simple experiments | Expand for bioprinting or detailed spatial documentation") # Quick action buttons at top col_btn1, col_btn2, col_btn3 = st.columns(3) with col_btn1: if seeding_method and "bioprint" in seeding_method.lower(): if st.button("⚡ Load My Bioprinting Defaults", key=f"{key_prefix}_load_defaults", help="One-click: 700μL/24-well, 3×10 grid, 0.3/1.5mm spacing", use_container_width=True): st.session_state[f"{key_prefix}_load_defaults_flag"] = True st.rerun() with col_btn2: skip_spatial = st.button("⏭️ Skip Spatial Details", key=f"{key_prefix}_skip", help="Don't capture spatial parameters", use_container_width=True) if skip_spatial: return None with col_btn3: st.caption("👈 Most experiments can skip this") # Check if defaults should be loaded load_defaults = st.session_state.pop(f"{key_prefix}_load_defaults_flag", False) # Pre-populate session state with defaults if button was clicked if load_defaults: st.session_state[f"{key_prefix}_pattern_default"] = DEFAULT_BIOPRINT_PARAMS["pattern_type"] st.session_state[f"{key_prefix}_grid_rows_default"] = DEFAULT_BIOPRINT_PARAMS["rows"] st.session_state[f"{key_prefix}_grid_cols_default"] = DEFAULT_BIOPRINT_PARAMS["columns"] st.session_state[f"{key_prefix}_xy_within_default"] = DEFAULT_BIOPRINT_PARAMS["xy_spacing_within_line_mm"] st.session_state[f"{key_prefix}_xy_between_default"] = DEFAULT_BIOPRINT_PARAMS["xy_spacing_between_lines_mm"] st.session_state[f"{key_prefix}_z_start_default"] = DEFAULT_BIOPRINT_PARAMS["z_start_mm"] st.session_state[f"{key_prefix}_z_end_default"] = DEFAULT_BIOPRINT_PARAMS["z_end_mm"] st.session_state[f"{key_prefix}_cells_default"] = DEFAULT_BIOPRINT_PARAMS["cells_per_injection"] st.session_state[f"{key_prefix}_needle_default"] = DEFAULT_BIOPRINT_PARAMS["needle_size"] st.session_state[f"{key_prefix}_vol_default"] = DEFAULT_BIOPRINT_PARAMS["hydrogel_volume_uL"] # For volume input st.session_state[f"{key_prefix}_inj_vol_default"] = DEFAULT_BIOPRINT_PARAMS["injection_volume_uL"] # For injection volume st.session_state[f"{key_prefix}_flow_default"] = DEFAULT_BIOPRINT_PARAMS["flow_rate_uL_per_sec"] st.success("✅ Defaults loaded! Scroll down to see all values populated.") st.markdown("---") # Mode selection mode_choice = st.radio( "Detail Level", ["Simple (density + distribution only)", "Full (bioprinting grid, Z-depth, etc.)"], key=f"{key_prefix}_mode_choice", help="Simple mode for most experiments; Full mode for bioprinting" ) # Simplified mode if mode_choice.startswith("Simple"): return _show_simplified_spatial(key_prefix, hydrogel_volume_uL, well_type, seeding_method, is_literature) # Full mode for bioprinting/microinjection st.markdown("**Full Spatial Pattern Builder**") st.caption("Define XY pattern, Z-depth (from bottom of well), and cell distribution") # Nested expanders for each section st.caption("👇 Expand sections below as needed:") # ========== XY PATTERN ========== with st.expander("🗺️ XY Pattern", expanded=load_defaults): col_pat, col_dims = st.columns([1, 2]) with col_pat: # Use default if set default_pattern = st.session_state.get(f"{key_prefix}_pattern_default", "grid_2d") try: default_idx = INJECTION_PATTERNS.index(default_pattern) except ValueError: default_idx = INJECTION_PATTERNS.index("grid_2d") if "grid_2d" in INJECTION_PATTERNS else 0 pattern_type = st.selectbox( "Pattern Type", INJECTION_PATTERNS, index=default_idx, key=f"{key_prefix}_pattern", format_func=lambda x: x.replace("_", " ").title() ) with col_dims: if pattern_type == "single_point": st.info("Single injection at center") rows, cols = 1, 1 elif pattern_type == "linear_array": cols = st.number_input( "Number of injections in line", min_value=1, max_value=100, value=10, key=f"{key_prefix}_linear_n" ) rows = 1 st.caption(f"Total: {cols} injections") elif pattern_type == "grid_2d": col_r, col_c = st.columns(2) with col_r: default_rows = st.session_state.get(f"{key_prefix}_grid_rows_default", 3) rows = st.number_input( "Rows (lines)", min_value=1, max_value=50, value=default_rows, key=f"{key_prefix}_grid_rows" ) with col_c: default_cols = st.session_state.get(f"{key_prefix}_grid_cols_default", 10) cols = st.number_input( "Columns (injections per line)", min_value=1, max_value=100, value=default_cols, key=f"{key_prefix}_grid_cols" ) st.caption(f"Total: {rows} lines × {cols} injections/line = {rows * cols} injections") elif pattern_type == "concentric_circles": circles = st.number_input( "Number of concentric circles", min_value=1, max_value=10, value=3, key=f"{key_prefix}_circles" ) points_per_circle = st.number_input( "Points per circle", min_value=1, max_value=50, value=8, key=f"{key_prefix}_circle_points" ) rows, cols = circles, points_per_circle st.caption(f"Total: {circles * points_per_circle} injections") else: rows, cols = 1, 1 st.caption("Custom pattern - specify in notes") # ========== XY SPACING ========== with st.expander("📏 XY Spacing", expanded=True): col_sp1, col_sp2 = st.columns([1, 2]) with col_sp1: spacing_pattern = st.selectbox( "Spacing Pattern", SPACING_PATTERNS, key=f"{key_prefix}_spacing_pattern", format_func=lambda x: x.replace("_", " ").title() ) with col_sp2: if spacing_pattern == "uniform": # For grid patterns, offer separate spacing for within-line and between-lines if pattern_type == "grid_2d" and rows > 1: col_sp_within, col_sp_between = st.columns(2) with col_sp_within: default_within = st.session_state.get(f"{key_prefix}_xy_within_default", 0.3) xy_spacing_within = st.number_input( "Within line (mm)", min_value=0.05, max_value=50.0, value=default_within, step=0.05, key=f"{key_prefix}_xy_spacing_within", help="Spacing between injections in same line" ) with col_sp_between: default_between = st.session_state.get(f"{key_prefix}_xy_between_default", 1.5) xy_spacing_between = st.number_input( "Between lines (mm)", min_value=0.05, max_value=50.0, value=default_between, step=0.1, key=f"{key_prefix}_xy_spacing_between", help="Spacing between parallel lines" ) # Store both spacings xy_spacing = xy_spacing_within # Default for calculations st.session_state[f"{key_prefix}_xy_spacing_between_value"] = xy_spacing_between else: default_spacing = st.session_state.get(f"{key_prefix}_xy_within_default", 0.5) xy_spacing = st.number_input( "XY spacing (mm)", min_value=0.05, max_value=50.0, value=default_spacing, step=0.05, key=f"{key_prefix}_xy_spacing" ) elif spacing_pattern in ["gradient_increasing", "gradient_decreasing"]: col_min, col_max = st.columns(2) with col_min: spacing_min = st.number_input( "Min spacing (mm)", min_value=0.05, max_value=50.0, value=0.1, step=0.05, key=f"{key_prefix}_spacing_min" ) with col_max: spacing_max = st.number_input( "Max spacing (mm)", min_value=0.05, max_value=50.0, value=3.0, step=0.1, key=f"{key_prefix}_spacing_max" ) xy_spacing = (spacing_min + spacing_max) / 2 # Average else: xy_spacing = st.number_input( "Average spacing (mm)", min_value=0.05, max_value=50.0, value=1.0, step=0.1, key=f"{key_prefix}_xy_spacing_avg" ) # ========== HYDROGEL HEIGHT CALCULATOR ========== with st.expander("📐 Hydrogel Height & Z-Reference", expanded=True): st.caption("**All Z-depths measured from bottom of well (Z=0 at well bottom)**") # Always allow manual override/input col_h1, col_h2, col_h3 = st.columns(3) with col_h1: # Well type (use provided or ask) if well_type: st.info(f"Well type: **{well_type}**") manual_well_type = well_type else: manual_well_type = st.selectbox( "Well Type", list(WELL_GEOMETRY.keys()), index=list(WELL_GEOMETRY.keys()).index("24-well") if "24-well" in WELL_GEOMETRY else 0, key=f"{key_prefix}_well_type" ) with col_h2: # Volume (use provided or ask, allow override) default_vol = hydrogel_volume_uL if hydrogel_volume_uL else st.session_state.get(f"{key_prefix}_vol_default", 700.0) manual_volume = st.number_input( "Hydrogel Volume (μL)", min_value=1.0, max_value=5000.0, value=float(default_vol), step=10.0, key=f"{key_prefix}_manual_vol", help="Enter total volume of hydrogel in well" ) with col_h3: # Calculate height if manual_well_type and manual_volume: hydrogel_height_mm = calculate_hydrogel_height(manual_volume, manual_well_type) st.metric("Gel Height", f"{hydrogel_height_mm:.2f} mm") st.caption(f"From {manual_volume:.0f} μL") else: hydrogel_height_mm = st.number_input( "Or enter height (mm)", min_value=0.1, max_value=20.0, value=2.0, step=0.1, key=f"{key_prefix}_manual_height" ) if hydrogel_height_mm: st.info(f"💡 **Valid Z range: 0.0 mm (bottom) to {hydrogel_height_mm:.2f} mm (top of gel)**") # ========== Z-DEPTH STRATEGY ========== with st.expander("⬇️ Z-Depth Strategy", expanded=True): st.caption("Z-depths measured from bottom of well") col_z1, col_z2 = st.columns([1, 2]) with col_z1: # Default to void_formation if defaults loaded default_z_strat = st.session_state.get(f"{key_prefix}_z_strategy_default", "void_formation" if load_defaults else "single_depth") try: z_strat_idx = Z_DEPTH_STRATEGIES.index(default_z_strat) except ValueError: z_strat_idx = 0 z_strategy = st.selectbox( "Z Strategy", Z_DEPTH_STRATEGIES, index=z_strat_idx, key=f"{key_prefix}_z_strategy", format_func=lambda x: x.replace("_", " ").title() ) with col_z2: if z_strategy == "single_depth": max_z = hydrogel_height_mm if hydrogel_height_mm else 20.0 default_z = min(1.0, max_z * 0.5) if hydrogel_height_mm else 1.0 z_depth = st.number_input( "Z depth from bottom (mm)", min_value=0.0, max_value=max_z, value=default_z, step=0.1, key=f"{key_prefix}_z_single", help=f"Distance from well bottom. Max = {max_z:.2f} mm (top of gel)" ) z_start, z_end = z_depth, z_depth # Validation if hydrogel_height_mm and z_depth > hydrogel_height_mm: st.warning(f"⚠️ Z-depth ({z_depth:.2f} mm) exceeds gel height ({hydrogel_height_mm:.2f} mm)") elif z_strategy in ["void_formation", "z_gradient"]: max_z = hydrogel_height_mm if hydrogel_height_mm else 20.0 # Use session state defaults if set, otherwise calculate from gel height default_start = st.session_state.get(f"{key_prefix}_z_start_default", min(0.5, max_z * 0.25) if hydrogel_height_mm else 0.5) default_end = st.session_state.get(f"{key_prefix}_z_end_default", min(1.5, max_z * 0.75) if hydrogel_height_mm else 1.5) col_zs, col_ze = st.columns(2) with col_zs: z_start = st.number_input( "Z start from bottom (mm)", min_value=0.0, max_value=max_z, value=float(default_start), step=0.01, key=f"{key_prefix}_z_start", help="Starting depth from well bottom" ) with col_ze: z_end = st.number_input( "Z end from bottom (mm)", min_value=0.0, max_value=max_z, value=float(default_end), step=0.01, key=f"{key_prefix}_z_end", help="Ending depth from well bottom" ) # Validation if hydrogel_height_mm: if z_start > hydrogel_height_mm: st.warning(f"⚠️ Z-start ({z_start:.2f} mm) exceeds gel height ({hydrogel_height_mm:.2f} mm)") if z_end > hydrogel_height_mm: st.warning(f"⚠️ Z-end ({z_end:.2f} mm) exceeds gel height ({hydrogel_height_mm:.2f} mm)") if z_strategy == "void_formation": z_diff = abs(z_end - z_start) st.caption(f"💧 Creates void/channel: {z_start:.2f} to {z_end:.2f} mm ({z_diff:.2f} mm depth)") st.caption(f" Needle moves from Z={z_start:.2f} to Z={z_end:.2f} during injection") elif z_strategy == "layered_discrete": n_layers = st.number_input( "Number of Z layers", min_value=1, max_value=10, value=3, key=f"{key_prefix}_z_layers" ) layer_spacing = st.number_input( "Layer spacing (mm)", min_value=0.1, max_value=5.0, value=0.5, step=0.1, key=f"{key_prefix}_z_layer_spacing" ) z_start = 0.5 z_end = z_start + (n_layers - 1) * layer_spacing st.caption(f"Z range: {z_start:.2f} - {z_end:.2f} mm ({n_layers} layers)") else: z_start = st.number_input( "Typical Z depth (mm)", min_value=0.0, max_value=20.0, value=1.0, step=0.1, key=f"{key_prefix}_z_typical" ) z_end = z_start # ========== CELL DISTRIBUTION ========== with st.expander("🔢 Cell Distribution", expanded=True): col_c1, col_c2 = st.columns([1, 2]) with col_c1: cell_distribution = st.selectbox( "Distribution", CELLS_PER_INJECTION_STRATEGIES, key=f"{key_prefix}_cell_dist", format_func=lambda x: x.replace("_", " ").title() ) with col_c2: if cell_distribution == "uniform": default_cells = st.session_state.get(f"{key_prefix}_cells_default", 50) cells_per_inj = st.number_input( "Cells per injection", min_value=1, max_value=100000, value=int(default_cells), step=10, key=f"{key_prefix}_cells_uniform" ) elif cell_distribution in ["gradient_center_high", "gradient_edge_high", "gradient_linear"]: col_cmin, col_cmax = st.columns(2) with col_cmin: cells_min = st.number_input( "Min cells/inj", min_value=1, max_value=100000, value=10, step=5, key=f"{key_prefix}_cells_min" ) with col_cmax: cells_max = st.number_input( "Max cells/inj", min_value=1, max_value=100000, value=100, step=10, key=f"{key_prefix}_cells_max" ) cells_per_inj = (cells_min + cells_max) / 2 # Average else: cells_per_inj = st.number_input( "Average cells per injection", min_value=1, max_value=100000, value=50, step=10, key=f"{key_prefix}_cells_avg" ) # ========== INJECTION PARAMETERS ========== with st.expander("⚙️ Injection Parameters (Optional)", expanded=load_defaults): col_p1, col_p2, col_p3 = st.columns(3) with col_p1: default_needle = DEFAULT_BIOPRINT_PARAMS["needle_size"] if load_defaults else "" needle_size = st.selectbox( "Needle Size", [""] + INJECTION_PARAMS["needle_sizes"], index=INJECTION_PARAMS["needle_sizes"].index(default_needle) + 1 if default_needle in INJECTION_PARAMS["needle_sizes"] else 0, key=f"{key_prefix}_needle", help="Select gauge (e.g., 30G) or direct diameter (e.g., 1.0mm)" ) with col_p2: default_inj_vol = st.session_state.get(f"{key_prefix}_inj_vol_default", 5.0) inj_volume = st.number_input( "Volume/injection (μL)", min_value=0.1, max_value=1000.0, value=float(default_inj_vol), step=0.5, key=f"{key_prefix}_vol" ) with col_p3: default_flow = st.session_state.get(f"{key_prefix}_flow_default", 1.0) flow_rate = st.number_input( "Flow rate (μL/s)", min_value=0.1, max_value=100.0, value=float(default_flow), step=0.1, key=f"{key_prefix}_flow" ) # ========== SUMMARY & TOTALS ========== total_injections = rows * cols total_cells = int(total_injections * cells_per_inj) total_volume = total_injections * inj_volume if inj_volume > 0 else 0 st.markdown("---") st.markdown("##### 📊 Summary") col_sum1, col_sum2, col_sum3, col_sum4 = st.columns(4) with col_sum1: st.metric("Total Injections", total_injections) with col_sum2: st.metric("Total Cells", f"{total_cells:,}") with col_sum3: if total_volume > 0: st.metric("Total Volume", f"{total_volume:.1f} μL") with col_sum4: if total_injections > 0 and xy_spacing > 0: footprint = (rows * xy_spacing) * (cols * xy_spacing) if pattern_type == "grid_2d" else 0 if footprint > 0: st.metric("XY Footprint", f"{footprint:.1f} mm²") # Pattern description pattern_desc = _generate_pattern_description( pattern_type, rows, cols, spacing_pattern, xy_spacing, z_strategy, z_start, z_end, cells_per_inj, cell_distribution ) st.info(f"**Pattern:** {pattern_desc}") # ========== BUILD JSON ========== spatial_pattern = { "mode": "full", "pattern_type": pattern_type, "rows": rows, "columns": cols, "xy_spacing_mm": xy_spacing, "xy_spacing_within_line_mm": st.session_state.get(f"{key_prefix}_xy_spacing_within_value", xy_spacing), "xy_spacing_between_lines_mm": st.session_state.get(f"{key_prefix}_xy_spacing_between_value", None), "spacing_pattern": spacing_pattern, "z_strategy": z_strategy, "z_reference": "from_bottom", # Always from bottom of well "z_start_mm": z_start, "z_end_mm": z_end, "hydrogel_height_mm": hydrogel_height_mm, "hydrogel_volume_uL": hydrogel_volume_uL, "well_type": well_type, "cells_per_injection": cells_per_inj, "cell_distribution": cell_distribution, "needle_size": needle_size if needle_size else None, "injection_volume_uL": inj_volume, "flow_rate_uL_per_sec": flow_rate if flow_rate > 0 else None, "total_injections": total_injections, "total_cells": total_cells, "total_volume_uL": total_volume, "pattern_description": pattern_desc } return spatial_pattern def _generate_pattern_description( pattern_type: str, rows: int, cols: int, spacing_pattern: str, xy_spacing: float, z_strategy: str, z_start: float, z_end: float, cells_per_inj: float, cell_dist: str ) -> str: """Generate human-readable description of pattern.""" # Pattern part if pattern_type == "single_point": pattern_part = "Single injection" elif pattern_type == "linear_array": pattern_part = f"Linear array: {cols} injections" elif pattern_type == "grid_2d": pattern_part = f"Grid: {rows} rows × {cols} columns = {rows * cols} injections" else: pattern_part = f"{pattern_type.replace('_', ' ').title()}" # Spacing part spacing_part = f"{xy_spacing:.2f} mm spacing" if spacing_pattern != "uniform": spacing_part += f" ({spacing_pattern})" # Z part if z_strategy == "single_depth": z_part = f"Z = {z_start:.2f} mm" elif z_strategy == "void_formation": z_diff = abs(z_end - z_start) z_part = f"Z = {z_start:.2f} to {z_end:.2f} mm (void: {z_diff:.2f} mm)" elif z_strategy == "z_gradient": z_part = f"Z gradient: {z_start:.2f} to {z_end:.2f} mm" else: z_part = f"{z_strategy.replace('_', ' ')}" # Cells part cells_part = f"{int(cells_per_inj)} cells/injection" if cell_dist != "uniform": cells_part += f" ({cell_dist})" return f"{pattern_part}, {spacing_part}, {z_part}, {cells_part}" def _show_simplified_spatial( key_prefix: str, hydrogel_volume_uL: float, well_type: str, seeding_method: str, is_literature: bool ) -> Optional[Dict]: """ Simplified spatial capture for non-bioprinting methods. Captures basic density and distribution info without complex patterns. """ from literature_ui_helpers import numeric_with_unknown, count_with_unknown st.markdown(f"**Spatial Context for: {seeding_method.replace('_', ' ').title()}**") # Calculate hydrogel height if possible hydrogel_height_mm = None if hydrogel_volume_uL and well_type: hydrogel_height_mm = calculate_hydrogel_height(hydrogel_volume_uL, well_type) st.info(f"Hydrogel height: **{hydrogel_height_mm:.2f} mm** (from {hydrogel_volume_uL:.0f} μL in {well_type})") # Seeding density (always relevant) st.markdown("##### Cell Seeding Density") col_d1, col_d2 = st.columns(2) with col_d1: if is_literature: density, density_unknown = numeric_with_unknown( "Seeding Density", min_val=0.0, max_val=1e7, default_val=10000.0, step=1000.0, key=f"{key_prefix}_density", help_text="Cells per cm² (for top seeding) or cells per mL (for mixed)", unit="cells", field_type="concentration" ) else: density = st.number_input( "Seeding Density", min_value=0.0, max_value=1e7, value=10000.0, step=1000.0, key=f"{key_prefix}_density", help="Cells per cm² (for top seeding) or cells per mL (for mixed)" ) density_unknown = False with col_d2: density_units = st.selectbox( "Units", ["cells/cm²", "cells/mL", "cells/well", "cells/μL"], key=f"{key_prefix}_density_units" ) # Distribution pattern (simple) st.markdown("##### Distribution") distribution = st.selectbox( "Cell Distribution", ["uniform", "concentrated_center", "concentrated_edge", "random", "unknown"], key=f"{key_prefix}_simple_dist", help="How cells are distributed spatially" ) # Z-position (relevant for all methods) if hydrogel_height_mm or not is_literature: st.markdown("##### Z-Position") if seeding_method in ["on_top_2D", "overlay"]: z_position = "top_surface" st.info("Cells seeded on **top surface** of gel (Z = gel height)") elif seeding_method in ["mixed_in_gel", "encapsulated"]: z_position = "throughout" st.info("Cells **distributed throughout** gel (all Z-depths)") elif seeding_method == "sandwiched": z_position = "mid_gel" z_depth = hydrogel_height_mm / 2 if hydrogel_height_mm else None if z_depth: st.info(f"Cells at **mid-gel plane** (Z ≈ {z_depth:.2f} mm)") else: st.info("Cells at **mid-gel plane**") else: # Unknown method or literature - ask z_position_options = ["top_surface", "mid_gel", "bottom", "throughout", "unknown"] z_position = st.selectbox( "Z-Position", z_position_options, key=f"{key_prefix}_z_position", help="Where cells are positioned vertically" ) else: z_position = "unknown" # Number of replicates / spots (if applicable) if seeding_method != "mixed_in_gel": st.markdown("##### Spatial Replication") if is_literature: n_spots, n_spots_unknown = count_with_unknown( "Number of Seeding Sites", min_val=1, max_val=100, key=f"{key_prefix}_n_spots", help_text="Number of distinct seeding locations in well" ) else: n_spots = st.number_input( "Number of Seeding Sites", min_value=1, max_value=100, value=1, key=f"{key_prefix}_n_spots", help="Number of distinct seeding locations in well" ) n_spots_unknown = False else: n_spots = 1 # Mixed-in is considered one "uniform" site n_spots_unknown = False # Total cells (calculated or entered) st.markdown("##### Total Cells") if is_literature: total_cells, total_unknown = numeric_with_unknown( "Total Cells", min_val=1.0, max_val=1e8, default_val=50000.0, step=1000.0, key=f"{key_prefix}_total_cells", help_text="Total number of cells seeded in well", unit="cells", field_type="concentration" ) else: total_cells = st.number_input( "Total Cells", min_value=1.0, max_value=1e8, value=50000.0, step=1000.0, key=f"{key_prefix}_total_cells", help="Total number of cells seeded in well" ) total_unknown = False # Notes notes = st.text_area( "Spatial Notes", placeholder="e.g., 'Cells seeded in center ~5mm diameter circle'", key=f"{key_prefix}_spatial_notes" ) # Build simplified JSON spatial_pattern = { "mode": "simplified", "seeding_method": seeding_method, "seeding_density": density if not (is_literature and density_unknown) else None, "density_units": density_units, "density_unknown": density_unknown if is_literature else False, "distribution": distribution, "z_position": z_position, "hydrogel_height_mm": hydrogel_height_mm, "hydrogel_volume_uL": hydrogel_volume_uL, "well_type": well_type, "n_seeding_sites": n_spots if not (is_literature and n_spots_unknown) else None, "total_cells": total_cells if not (is_literature and total_unknown) else None, "notes": notes or None, "pattern_description": _generate_simple_description( seeding_method, density, density_units, distribution, z_position, n_spots, total_cells ) } # Summary st.markdown("---") st.markdown("##### Summary") st.info(f"**{spatial_pattern['pattern_description']}**") return spatial_pattern def _generate_simple_description( method: str, density: float, units: str, distribution: str, z_position: str, n_spots: int, total_cells: float ) -> str: """Generate human-readable description for simplified spatial pattern.""" method_str = method.replace("_", " ").title() density_str = f"{int(density):,} {units}" if density else "density not specified" dist_str = distribution.replace("_", " ") z_str = z_position.replace("_", " ") if n_spots and n_spots > 1: site_str = f" at {n_spots} sites" else: site_str = "" total_str = f", {int(total_cells):,} total cells" if total_cells else "" return f"{method_str}: {density_str}{site_str}, {dist_str} distribution, {z_str}{total_str}" # Example usage comment """ # In cell_growth_lab_gui.py: from spatial_seeding_builder import show_spatial_seeding_builder # In page_new_run(), after seeding method is selected: spatial_pattern = show_spatial_seeding_builder( key_prefix="new_run_spatial", hydrogel_volume_uL=blend_total_volume, well_type=plate_type, seeding_method=seed_method, # Pass selected method is_literature=False ) # In cell_growth_literature_gui.py: spatial_pattern = show_spatial_seeding_builder( key_prefix="lit_spatial", hydrogel_volume_uL=hydrogel_volume, well_type=well_type, seeding_method=seed_method, is_literature=True # Enables "unknown" options ) # Store in database: if spatial_pattern: spatial_pattern_json = json.dumps(spatial_pattern) # Add to cell_runs table: spatial_seeding_pattern TEXT # Display pattern: if run_info.get("spatial_seeding_pattern"): pattern = json.loads(run_info["spatial_seeding_pattern"]) st.info(pattern.get("pattern_description", "Custom spatial pattern")) """