minor changes
Browse files
app.py
CHANGED
|
@@ -1,444 +1,443 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import streamlit as st
|
| 3 |
-
import pandas as pd
|
| 4 |
-
import joblib
|
| 5 |
-
import optuna
|
| 6 |
-
import numpy as np
|
| 7 |
-
from catboost import CatBoostClassifier
|
| 8 |
-
|
| 9 |
-
from google import genai
|
| 10 |
-
from google.genai import types
|
| 11 |
-
|
| 12 |
-
from biomaterials import BIOMATERIAL_OPTIONS
|
| 13 |
-
from cell_lines import CELL_LINE_OPTIONS
|
| 14 |
-
|
| 15 |
-
_original_number_input = st.number_input
|
| 16 |
-
|
| 17 |
-
def safe_number_input(label, **kwargs):
|
| 18 |
-
"""
|
| 19 |
-
Clamp `value` into [min_value, max_value] and warn if we had to adjust.
|
| 20 |
-
Then call the real st.number_input with the clamped default.
|
| 21 |
-
"""
|
| 22 |
-
min_value = kwargs.get("min_value", float("-inf"))
|
| 23 |
-
max_value = kwargs.get("max_value", float("inf"))
|
| 24 |
-
value = kwargs.get("value", min_value)
|
| 25 |
-
clamped = min(max(value, min_value), max_value)
|
| 26 |
-
if clamped != value:
|
| 27 |
-
st.warning(
|
| 28 |
-
f"⚠️ Default for “{label}” ({value}) was outside "
|
| 29 |
-
f"[{min_value}, {max_value}]; using {clamped} instead."
|
| 30 |
-
)
|
| 31 |
-
kwargs["value"] = clamped
|
| 32 |
-
return _original_number_input(label, **kwargs)
|
| 33 |
-
|
| 34 |
-
st.number_input = safe_number_input
|
| 35 |
-
|
| 36 |
-
gemini_key =
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
st.
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
(
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
"
|
| 74 |
-
"
|
| 75 |
-
"
|
| 76 |
-
"Nozzle
|
| 77 |
-
"
|
| 78 |
-
"
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
joblib.load('
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
'
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
"
|
| 118 |
-
"
|
| 119 |
-
"
|
| 120 |
-
"Nozzle
|
| 121 |
-
"
|
| 122 |
-
"
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
w_print_pct =
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
st.
|
| 139 |
-
|
| 140 |
-
"
|
| 141 |
-
"
|
| 142 |
-
"
|
| 143 |
-
"<
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
st.
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
)
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
st.
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
st.
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
)
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
c1
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
c1
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
c1
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
)
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
st.session_state.pp_ranges[name]['
|
| 321 |
-
st.session_state.pp_ranges[name]['
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
feat
|
| 328 |
-
feat
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
)
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
st.session_state.
|
| 369 |
-
st.session_state.
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
.
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
st.
|
| 380 |
-
st.
|
| 381 |
-
|
| 382 |
-
"
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
f"
|
| 398 |
-
f"
|
| 399 |
-
f"
|
| 400 |
-
f"
|
| 401 |
-
f"
|
| 402 |
-
f"
|
| 403 |
-
f"
|
| 404 |
-
f"• If
|
| 405 |
-
f"•
|
| 406 |
-
f"•
|
| 407 |
-
f"•
|
| 408 |
-
f"•
|
| 409 |
-
f"•
|
| 410 |
-
f"
|
| 411 |
-
f"
|
| 412 |
-
f"
|
| 413 |
-
f"
|
| 414 |
-
f"
|
| 415 |
-
f"
|
| 416 |
-
f"
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
"
|
| 431 |
-
"
|
| 432 |
-
"
|
| 433 |
-
"
|
| 434 |
-
"Never
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
st.markdown("## 🧪 Fabrication Procedure")
|
| 444 |
st.markdown(resp.text)
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import streamlit as st
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import joblib
|
| 5 |
+
import optuna
|
| 6 |
+
import numpy as np
|
| 7 |
+
from catboost import CatBoostClassifier
|
| 8 |
+
|
| 9 |
+
from google import genai
|
| 10 |
+
from google.genai import types
|
| 11 |
+
|
| 12 |
+
from biomaterials import BIOMATERIAL_OPTIONS
|
| 13 |
+
from cell_lines import CELL_LINE_OPTIONS
|
| 14 |
+
|
| 15 |
+
_original_number_input = st.number_input
|
| 16 |
+
|
| 17 |
+
def safe_number_input(label, **kwargs):
|
| 18 |
+
"""
|
| 19 |
+
Clamp `value` into [min_value, max_value] and warn if we had to adjust.
|
| 20 |
+
Then call the real st.number_input with the clamped default.
|
| 21 |
+
"""
|
| 22 |
+
min_value = kwargs.get("min_value", float("-inf"))
|
| 23 |
+
max_value = kwargs.get("max_value", float("inf"))
|
| 24 |
+
value = kwargs.get("value", min_value)
|
| 25 |
+
clamped = min(max(value, min_value), max_value)
|
| 26 |
+
if clamped != value:
|
| 27 |
+
st.warning(
|
| 28 |
+
f"⚠️ Default for “{label}” ({value}) was outside "
|
| 29 |
+
f"[{min_value}, {max_value}]; using {clamped} instead."
|
| 30 |
+
)
|
| 31 |
+
kwargs["value"] = clamped
|
| 32 |
+
return _original_number_input(label, **kwargs)
|
| 33 |
+
|
| 34 |
+
st.number_input = safe_number_input
|
| 35 |
+
|
| 36 |
+
gemini_key = os.getenv("GEMINI_API_KEY")
|
| 37 |
+
if not gemini_key:
|
| 38 |
+
st.error("Gemini API key not found. Please set GEMINI_API_KEY in your Space settings.")
|
| 39 |
+
st.stop()
|
| 40 |
+
|
| 41 |
+
client = genai.Client(api_key=gemini_key)
|
| 42 |
+
|
| 43 |
+
def scaffold_quality_combined(printability, cell_response,
|
| 44 |
+
weight_printability=0.3, weight_cell_response=0.7):
|
| 45 |
+
"""
|
| 46 |
+
Calculates the Weighted Scaffold Synthesis Quality (WSSQ).
|
| 47 |
+
"""
|
| 48 |
+
if printability == 0:
|
| 49 |
+
return 0.0
|
| 50 |
+
|
| 51 |
+
# Normalization
|
| 52 |
+
norm_p = printability / 3.0
|
| 53 |
+
|
| 54 |
+
# If cell_response is 1 (minimum), avoid division by zero in harmonic mean
|
| 55 |
+
if cell_response <= 1:
|
| 56 |
+
return 100 * norm_p
|
| 57 |
+
|
| 58 |
+
norm_c = (cell_response - 1) / 4.0
|
| 59 |
+
|
| 60 |
+
# Weighted Harmonic Mean
|
| 61 |
+
hm = (weight_printability + weight_cell_response) / (
|
| 62 |
+
(weight_printability / norm_p) +
|
| 63 |
+
(weight_cell_response / norm_c)
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
# Weighted Multiplicative Component
|
| 67 |
+
mc = (norm_p**weight_printability) * (norm_c**weight_cell_response)
|
| 68 |
+
|
| 69 |
+
return 100 * ((hm + mc) / 2.0)
|
| 70 |
+
|
| 71 |
+
PRINT_PARAM_NAMES = [
|
| 72 |
+
"Physical Crosslinking Duration (s)",
|
| 73 |
+
"Photo Crosslinking Duration (s)",
|
| 74 |
+
"Extrusion Pressure (kPa)",
|
| 75 |
+
"Nozzle Movement Speed (mm/s)",
|
| 76 |
+
"Nozzle Diameter (µm)",
|
| 77 |
+
"Syringe Temperature (°C)",
|
| 78 |
+
"Substrate Temperature (°C)",
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
@st.cache_resource
|
| 82 |
+
def load_encoder():
|
| 83 |
+
return joblib.load('cell_line_encoder.joblib')
|
| 84 |
+
|
| 85 |
+
@st.cache_resource
|
| 86 |
+
def load_scalers():
|
| 87 |
+
return (
|
| 88 |
+
joblib.load('scaler_printability.joblib'),
|
| 89 |
+
joblib.load('scaler_cell_response.joblib')
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
@st.cache_resource
|
| 93 |
+
def load_models():
|
| 94 |
+
m_p = CatBoostClassifier(); m_p.load_model('catboost_printability.cbm')
|
| 95 |
+
m_c = CatBoostClassifier(); m_c.load_model('catboost_cell_response.cbm')
|
| 96 |
+
return m_p, m_c
|
| 97 |
+
|
| 98 |
+
encoder = load_encoder()
|
| 99 |
+
scaler_print, scaler_cell = load_scalers()
|
| 100 |
+
model_print, model_cell = load_models()
|
| 101 |
+
|
| 102 |
+
feature_order_print = list(scaler_print.feature_names_in_)
|
| 103 |
+
feature_order_cell = list(scaler_cell.feature_names_in_)
|
| 104 |
+
|
| 105 |
+
if 'bio_rows' not in st.session_state:
|
| 106 |
+
st.session_state.bio_rows = [{
|
| 107 |
+
'mat': BIOMATERIAL_OPTIONS[0],
|
| 108 |
+
'min': 0.0, 'max': 10.0, 'step': 0.1
|
| 109 |
+
}]
|
| 110 |
+
|
| 111 |
+
if 'density_range' not in st.session_state:
|
| 112 |
+
st.session_state.density_range = {'min': 0.0, 'max': 10.0, 'step': 0.1}
|
| 113 |
+
|
| 114 |
+
if 'pp_ranges' not in st.session_state:
|
| 115 |
+
st.session_state.pp_ranges = {
|
| 116 |
+
"Physical Crosslinking Duration (s)": {'min': 0.0, 'max': 300.0, 'step': 5.0},
|
| 117 |
+
"Photo Crosslinking Duration (s)": {'min': 0.0, 'max': 180.0, 'step': 5.0},
|
| 118 |
+
"Extrusion Pressure (kPa)": {'min': 5.0, 'max': 200.0, 'step': 5.0},
|
| 119 |
+
"Nozzle Movement Speed (mm/s)": {'min': 1.0, 'max': 20.0, 'step': 0.5},
|
| 120 |
+
"Nozzle Diameter (µm)": {'min': 100.0,'max': 1000.0, 'step': 50.0},
|
| 121 |
+
"Syringe Temperature (°C)": {'min': 4.0, 'max': 40.0, 'step': 1.0},
|
| 122 |
+
"Substrate Temperature (°C)": {'min': 4.0, 'max': 37.0, 'step': 1.0},
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
# --- Sidebar UI for Weights ---
|
| 126 |
+
st.sidebar.header("⚖️ Optimization Weights")
|
| 127 |
+
# User only controls Cell Response (0 to 100)
|
| 128 |
+
w_cell_pct = st.sidebar.slider("Cell Response Weight (%)", min_value=0, max_value=100, value=70, step=5)
|
| 129 |
+
# Printability is dynamically calculated and cannot be changed manually
|
| 130 |
+
w_print_pct = 100 - w_cell_pct
|
| 131 |
+
st.sidebar.number_input("Printability Weight (%)", value=w_print_pct, disabled=True, help="Auto-calculated to ensure sum is 100%")
|
| 132 |
+
|
| 133 |
+
# Convert back to 0.0 - 1.0 for the mathematical formula
|
| 134 |
+
w_cell = w_cell_pct / 100.0
|
| 135 |
+
w_print = w_print_pct / 100.0
|
| 136 |
+
|
| 137 |
+
st.title("🧬 MLATE: Machine Learning Applications in Tissue Engieering")
|
| 138 |
+
st.markdown(
|
| 139 |
+
"<p style='font-size:1.2em; color:grey;'>"
|
| 140 |
+
"A fully integrated Multi-Tissue, machine learning platform for prediction, optimization and generating procedures for fabricating 3D-(bio)printing scaffolds for tissue engineering. "
|
| 141 |
+
"For more details, please refer to and cite our paper: "
|
| 142 |
+
"<a href='https://doi.org/xxx' target='_blank'>https://doi.org/xxx</a>"
|
| 143 |
+
"</p>",
|
| 144 |
+
unsafe_allow_html=True
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
st.subheader("Biomaterials (enter range for each)")
|
| 148 |
+
if st.button("➕ Add Biomaterial"):
|
| 149 |
+
used = {r['mat'] for r in st.session_state.bio_rows}
|
| 150 |
+
available = [m for m in BIOMATERIAL_OPTIONS if m not in used]
|
| 151 |
+
if available:
|
| 152 |
+
st.session_state.bio_rows.append({
|
| 153 |
+
'mat': available[0], 'min': 0.0, 'max': 10.0, 'step': 0.1
|
| 154 |
+
})
|
| 155 |
+
st.rerun()
|
| 156 |
+
|
| 157 |
+
for i, row in enumerate(st.session_state.bio_rows):
|
| 158 |
+
used_except_current = {
|
| 159 |
+
r['mat'] for idx, r in enumerate(st.session_state.bio_rows) if idx != i
|
| 160 |
+
}
|
| 161 |
+
options = [m for m in BIOMATERIAL_OPTIONS if m not in used_except_current]
|
| 162 |
+
|
| 163 |
+
c1, c2, c3, c4, c5 = st.columns([2, 1, 1, 1, 0.3])
|
| 164 |
+
mat = c1.selectbox(
|
| 165 |
+
"", options,
|
| 166 |
+
index=options.index(row['mat']) if row['mat'] in options else 0,
|
| 167 |
+
key=f"bio_mat_{i}"
|
| 168 |
+
)
|
| 169 |
+
st.session_state.bio_rows[i]['mat'] = mat
|
| 170 |
+
|
| 171 |
+
mn = c2.number_input(
|
| 172 |
+
"Min", min_value=0.0, max_value=row['max'],
|
| 173 |
+
value=row['min'], step=row['step'], key=f"bio_min_{i}"
|
| 174 |
+
)
|
| 175 |
+
mx = c3.number_input(
|
| 176 |
+
"Max", min_value=row['step'], max_value=100.0,
|
| 177 |
+
value=max(row['max'], row['step']), step=row['step'],
|
| 178 |
+
key=f"bio_max_{i}"
|
| 179 |
+
)
|
| 180 |
+
st.session_state.bio_rows[i].update(min=mn, max=mx)
|
| 181 |
+
|
| 182 |
+
st.session_state.bio_rows[i]['step'] = c4.number_input(
|
| 183 |
+
"Step", min_value=0.0,
|
| 184 |
+
max_value=(mx - mn) if mx > mn else 0.1,
|
| 185 |
+
value=row['step'], step=0.1, key=f"bio_step_{i}"
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
if c5.button("❌", key=f"rem_{i}"):
|
| 189 |
+
st.session_state.bio_rows.pop(i)
|
| 190 |
+
st.rerun()
|
| 191 |
+
|
| 192 |
+
st.markdown("---")
|
| 193 |
+
|
| 194 |
+
st.subheader("Cell Line & Density (10^6 cells/ml)")
|
| 195 |
+
col1, col2, col3, col4 = st.columns([2,1,1,1])
|
| 196 |
+
|
| 197 |
+
cell_line = col1.selectbox("Cell Line", CELL_LINE_OPTIONS, key="cell_line_select")
|
| 198 |
+
|
| 199 |
+
if cell_line == "NoCellCultured":
|
| 200 |
+
st.info("🧪 **Acellular 3D printing mode** – No cells will be included. Cell density is forced to 0.")
|
| 201 |
+
st.session_state.density_range.update({'min': 0.0, 'max': 0.0, 'step': 0.0})
|
| 202 |
+
|
| 203 |
+
col2.number_input("Min Density", value=0.0, disabled=True, key="cd_min")
|
| 204 |
+
col3.number_input("Max Density", value=0.0, disabled=True, key="cd_max")
|
| 205 |
+
col4.number_input("Step", value=0.0, disabled=True, key="cd_step")
|
| 206 |
+
else:
|
| 207 |
+
if st.session_state.density_range.get('max', 0) <= 0.1:
|
| 208 |
+
st.session_state.density_range.update({'min': 1.0, 'max': 20.0, 'step': 0.5})
|
| 209 |
+
|
| 210 |
+
dr = st.session_state.density_range
|
| 211 |
+
dmin = col2.number_input(
|
| 212 |
+
"Min Density",
|
| 213 |
+
min_value=0.0,
|
| 214 |
+
max_value=dr['max'],
|
| 215 |
+
value=dr['min'],
|
| 216 |
+
step=dr['step'],
|
| 217 |
+
key="cd_min"
|
| 218 |
+
)
|
| 219 |
+
dmax = col3.number_input(
|
| 220 |
+
"Max Density",
|
| 221 |
+
min_value=dr['step'],
|
| 222 |
+
max_value=1000.0,
|
| 223 |
+
value=max(dr['max'], dr['step']),
|
| 224 |
+
step=dr['step'],
|
| 225 |
+
key="cd_max"
|
| 226 |
+
)
|
| 227 |
+
dstep = col4.number_input(
|
| 228 |
+
"Step",
|
| 229 |
+
min_value=0.0,
|
| 230 |
+
max_value=(dmax - dmin) if dmax > dmin else 0.1,
|
| 231 |
+
value=dr['step'],
|
| 232 |
+
step=0.1,
|
| 233 |
+
key="cd_step"
|
| 234 |
+
)
|
| 235 |
+
st.session_state.density_range.update({'min': dmin, 'max': dmax, 'step': dstep})
|
| 236 |
+
|
| 237 |
+
st.markdown("---")
|
| 238 |
+
|
| 239 |
+
st.subheader("Crosslinking Settings")
|
| 240 |
+
|
| 241 |
+
col_cross1, col_cross2 = st.columns(2)
|
| 242 |
+
|
| 243 |
+
disable_physical = col_cross1.checkbox(
|
| 244 |
+
"Disable Physical Crosslinking",
|
| 245 |
+
value=False,
|
| 246 |
+
help="Check if you do not want physical/ionic crosslinking (e.g. CaCl₂ bath, temperature-induced)"
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
disable_photo = col_cross2.checkbox(
|
| 250 |
+
"Disable Photo Crosslinking",
|
| 251 |
+
value=False,
|
| 252 |
+
help="Check if you do not want UV/visible light crosslinking"
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
st.subheader("Printing Parameters (enter range)")
|
| 256 |
+
|
| 257 |
+
for name in PRINT_PARAM_NAMES:
|
| 258 |
+
if name == "Physical Crosslinking Duration (s)" and disable_physical:
|
| 259 |
+
st.session_state.pp_ranges[name].update({'min': 0.0, 'max': 0.0, 'step': 0.0})
|
| 260 |
+
c1, c2, c3, c4 = st.columns([2,1,1,1])
|
| 261 |
+
c1.write(name + " (DISABLED)")
|
| 262 |
+
c2.number_input("Min", value=0.0, disabled=True, key=f"pp_min_{name}")
|
| 263 |
+
c3.number_input("Max", value=0.0, disabled=True, key=f"pp_max_{name}")
|
| 264 |
+
c4.number_input("Step", value=0.0, disabled=True, key=f"pp_step_{name}")
|
| 265 |
+
continue
|
| 266 |
+
|
| 267 |
+
elif name == "Photo Crosslinking Duration (s)" and disable_photo:
|
| 268 |
+
st.session_state.pp_ranges[name].update({'min': 0.0, 'max': 0.0, 'step': 0.0})
|
| 269 |
+
c1, c2, c3, c4 = st.columns([2,1,1,1])
|
| 270 |
+
c1.write(name + " (DISABLED)")
|
| 271 |
+
c2.number_input("Min", value=0.0, disabled=True, key=f"pp_min_{name}")
|
| 272 |
+
c3.number_input("Max", value=0.0, disabled=True, key=f"pp_max_{name}")
|
| 273 |
+
c4.number_input("Step", value=0.0, disabled=True, key=f"pp_step_{name}")
|
| 274 |
+
continue
|
| 275 |
+
|
| 276 |
+
pmin = st.session_state.pp_ranges[name]['min']
|
| 277 |
+
pmax = st.session_state.pp_ranges[name]['max']
|
| 278 |
+
pstep = st.session_state.pp_ranges[name]['step']
|
| 279 |
+
|
| 280 |
+
c1, c2, c3, c4 = st.columns([2,1,1,1])
|
| 281 |
+
c1.write(name)
|
| 282 |
+
|
| 283 |
+
pmin = c2.number_input(
|
| 284 |
+
"Min", min_value=0.0, max_value=pmax,
|
| 285 |
+
value=pmin, step=pstep, key=f"pp_min_{name}"
|
| 286 |
+
)
|
| 287 |
+
pmax = c3.number_input(
|
| 288 |
+
"Max", min_value=pstep, max_value=10000.0,
|
| 289 |
+
value=max(pmax, pstep), step=pstep, key=f"pp_max_{name}"
|
| 290 |
+
)
|
| 291 |
+
pstep = c4.number_input(
|
| 292 |
+
"Step", min_value=0.0,
|
| 293 |
+
max_value=(pmax - pmin) if pmax > pmin else 1.0,
|
| 294 |
+
value=pstep, step=max(1e-3, pstep/10),
|
| 295 |
+
key=f"pp_step_{name}"
|
| 296 |
+
)
|
| 297 |
+
st.session_state.pp_ranges[name].update(min=pmin, max=pmax, step=pstep)
|
| 298 |
+
st.markdown("---")
|
| 299 |
+
|
| 300 |
+
if st.button("🛠️ Optimize WSSQ"):
|
| 301 |
+
with st.spinner("Running Optuna…"):
|
| 302 |
+
def objective(trial):
|
| 303 |
+
bi_vals = {
|
| 304 |
+
r['mat']: trial.suggest_float(
|
| 305 |
+
f"bio__{r['mat']}", r['min'], r['max'], step=r['step']
|
| 306 |
+
)
|
| 307 |
+
for r in st.session_state.bio_rows
|
| 308 |
+
}
|
| 309 |
+
for m in BIOMATERIAL_OPTIONS:
|
| 310 |
+
bi_vals.setdefault(m, 0.0)
|
| 311 |
+
|
| 312 |
+
cd = 0.0 if cell_line=="NoCellCultured" else trial.suggest_float(
|
| 313 |
+
"cell_density", dr['min'], dr['max'], step=dr['step']
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
pp_vals = {
|
| 317 |
+
name: trial.suggest_float(
|
| 318 |
+
f"pp__{name}",
|
| 319 |
+
st.session_state.pp_ranges[name]['min'],
|
| 320 |
+
st.session_state.pp_ranges[name]['max'],
|
| 321 |
+
step=st.session_state.pp_ranges[name]['step']
|
| 322 |
+
)
|
| 323 |
+
for name in PRINT_PARAM_NAMES
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
feat = {**bi_vals, **pp_vals}
|
| 327 |
+
feat["Cell Density (cells/mL)"] = cd
|
| 328 |
+
feat.update(
|
| 329 |
+
encoder.transform(pd.DataFrame({"Cell Line":[cell_line]}))
|
| 330 |
+
.iloc[0].to_dict()
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
X = pd.DataFrame([feat])
|
| 334 |
+
Xp = X.reindex(columns=feature_order_print, fill_value=0.0)
|
| 335 |
+
Xc = X.reindex(columns=feature_order_cell, fill_value=0.0)
|
| 336 |
+
|
| 337 |
+
p_proba = model_print.predict_proba(scaler_print.transform(Xp))[0]
|
| 338 |
+
c_proba = model_cell .predict_proba(scaler_cell .transform(Xc))[0]
|
| 339 |
+
exp_p = float(np.dot(p_proba, model_print.classes_.astype(float)))
|
| 340 |
+
exp_c = float(np.dot(c_proba, model_cell .classes_.astype(float)))
|
| 341 |
+
|
| 342 |
+
np.random.seed(42)
|
| 343 |
+
# Use dynamic weights from the sidebar sliders
|
| 344 |
+
return scaffold_quality_combined(
|
| 345 |
+
exp_p,
|
| 346 |
+
exp_c,
|
| 347 |
+
weight_printability=w_print,
|
| 348 |
+
weight_cell_response=w_cell
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
sampler = optuna.samplers.TPESampler(
|
| 352 |
+
seed=42,
|
| 353 |
+
n_startup_trials=30,
|
| 354 |
+
multivariate=True,
|
| 355 |
+
group=True,
|
| 356 |
+
consider_prior=True
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
study = optuna.create_study(
|
| 360 |
+
direction="maximize",
|
| 361 |
+
sampler=sampler,
|
| 362 |
+
pruner=optuna.pruners.MedianPruner()
|
| 363 |
+
)
|
| 364 |
+
study.optimize(objective, n_trials=300)
|
| 365 |
+
|
| 366 |
+
# Store results in session state to persist after rerun
|
| 367 |
+
st.session_state.best_params = study.best_trial.params
|
| 368 |
+
st.session_state.best_value = study.best_trial.value
|
| 369 |
+
st.session_state.optimized_cell_line = cell_line
|
| 370 |
+
|
| 371 |
+
if 'best_params' in st.session_state:
|
| 372 |
+
st.success(f"🏆 Best WSSQ: **{st.session_state.best_value:.3f}**")
|
| 373 |
+
best_df = pd.Series(st.session_state.best_params, name="value") \
|
| 374 |
+
.rename_axis("parameter") \
|
| 375 |
+
.to_frame()
|
| 376 |
+
st.table(best_df)
|
| 377 |
+
|
| 378 |
+
st.markdown("---")
|
| 379 |
+
st.subheader("📝 Customize Fabrication Protocol")
|
| 380 |
+
user_inquiry = st.text_area(
|
| 381 |
+
"Add specific limitations, equipment, or extra requirements:",
|
| 382 |
+
placeholder="e.g., I only have a 25G nozzle available, or I need to use a specific UV intensity of 10mW/cm²...",
|
| 383 |
+
key="user_inquiry"
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
if st.button("🚀 Generate Fabrication Procedure"):
|
| 387 |
+
with st.spinner("Generating rigorous fabrication procedure…"):
|
| 388 |
+
|
| 389 |
+
formatted_params = "\n".join([
|
| 390 |
+
f"- {k.replace('bio__', 'Biomaterial: ').replace('pp__', 'Print Setting: ')}: {v:.2f}"
|
| 391 |
+
for k, v in st.session_state.best_params.items()
|
| 392 |
+
])
|
| 393 |
+
|
| 394 |
+
# Base prompt (remains unchanged)
|
| 395 |
+
base_prompt = (
|
| 396 |
+
f"Please act as a senior tissue engineer with 15+ years of hands-on experience in 3D bioprinting for regenerative medicine. "
|
| 397 |
+
f"Write a **highly practical, bench-ready laboratory fabrication protocol** for fabricating a scaffold. "
|
| 398 |
+
f"Assume the reader is an experienced experimentalist who routinely works in a tissue engineering lab.\n\n"
|
| 399 |
+
f"**Use exactly these inputs to tailor every step:**\n"
|
| 400 |
+
f"Target Cell Line: {st.session_state.optimized_cell_line}\n"
|
| 401 |
+
f"Parameters:\n{formatted_params}\n\n"
|
| 402 |
+
f"**Critical requirements for the protocol (you MUST follow all of them):**\n"
|
| 403 |
+
f"• If Target Cell Line is 'NoCellCultured', this is **acellular 3D printing** (not bioprinting). Remove all references to cells, cell viability, cell density, and cell culturing. The final scaffold is cell-free. Change section 6 title to 'Post-Printing Incubation & Storage Instructions' and adapt its content accordingly.\n"
|
| 404 |
+
f"• If any suggested parameter is physically unrealistic (e.g. nozzle diameter 9 µm or syringe temp 2°C) or the nozzle diameter is very small relative to the cell diameter of the target cell line (when cells are used), adjust it slightly in the protocol and explicitly note the adjustment with justification.\n"
|
| 405 |
+
f"• Every quantity must be given in precise, measurable lab units (e.g., 2.5 mL, 1.2 % w/v, 10 mg/mL, 37 °C, 5 min, 150 rpm).\n"
|
| 406 |
+
f"• Include exact timings, temperatures, and workflow order to protect structural fidelity (and cell viability >85 % post-print when cells are used).\n"
|
| 407 |
+
f"• Anticipate and explicitly address common bioprinting pitfalls relevant to the given parameters (nozzle clogging, shear-induced cell death, premature gelation, filament fusion, air bubbles, etc.) and give precise mitigation steps.\n"
|
| 408 |
+
f"• Use only reagents and equipment that are standard in tissue engineering labs; if a specific brand/model is implied by the parameters, note a common equivalent.\n"
|
| 409 |
+
f"• Include simple quality-control checkpoints (visual inspection, live/dead staining timing when cells are used, etc.).\n\n"
|
| 410 |
+
f"Your response must be structured **exactly** with the following sections (no extra sections, no introductory text, no summary, no conclusions):\n"
|
| 411 |
+
f"1. Required Materials & Equipment\n"
|
| 412 |
+
f"2. Sterilization & Safety Precautions\n"
|
| 413 |
+
f"3. Bioink Preparation\n"
|
| 414 |
+
f"4. 3D Bioprinting Settings & Execution\n"
|
| 415 |
+
f"5. Post-processing & Crosslinking\n"
|
| 416 |
+
f"6. Cell Culturing & Incubation Instructions\n"
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
# Append user inquiry if provided
|
| 420 |
+
final_prompt = base_prompt
|
| 421 |
+
if user_inquiry:
|
| 422 |
+
final_prompt += f"\n**Additional User Constraints & Inquiries (Integrate these into the protocol):**\n{user_inquiry}"
|
| 423 |
+
|
| 424 |
+
resp = client.models.generate_content(
|
| 425 |
+
model="gemini-2.5-flash-lite",
|
| 426 |
+
contents=final_prompt,
|
| 427 |
+
config=types.GenerateContentConfig(
|
| 428 |
+
system_instruction=(
|
| 429 |
+
"You are a senior tissue engineer and expert experimentalist specializing in translating optimized bioprinting parameters into reproducible, high-viability laboratory protocols. "
|
| 430 |
+
"Your protocols are used daily by PhD students and post-docs in regenerative medicine labs. "
|
| 431 |
+
"You always prioritize: (1) maximum cell viability and function, (2) structural fidelity of the printed construct, (3) workflow efficiency under sterile conditions, and (4) safety. "
|
| 432 |
+
"Write in clear, imperative, step-by-step language with numbered or bulleted sub-steps. "
|
| 433 |
+
"Never be vague — give exact volumes, times, temperatures, speeds, and concentrations. "
|
| 434 |
+
"Never add disclaimers or theoretical background unless explicitly asked."
|
| 435 |
+
),
|
| 436 |
+
temperature=0.1,
|
| 437 |
+
top_p=0.85,
|
| 438 |
+
max_output_tokens=6144
|
| 439 |
+
)
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
st.markdown("## 🧪 Fabrication Procedure")
|
|
|
|
| 443 |
st.markdown(resp.text)
|