Saeed commited on
Commit
a3c8ee4
·
verified ·
1 Parent(s): ce87324

minor changes

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