soominhlee commited on
Commit
56ea749
Β·
verified Β·
1 Parent(s): 31d4a34

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +202 -177
app.py CHANGED
@@ -1,5 +1,4 @@
1
  import os
2
- import json
3
  import numpy as np
4
  import pandas as pd
5
  import gradio as gr
@@ -7,21 +6,26 @@ import pickle
7
  import tensorflow as tf
8
 
9
  # =========================================================
10
- # Settings / Constants (must match training)
11
  # =========================================================
12
  BEST_L = 3
13
  CC_COL = "CarbonContents"
14
 
 
 
 
 
 
 
 
 
 
15
  RPM_RANGE = (150, 650)
16
- RPM_DELTAS = (-200, -150, -100, -50, 50, 100, 150, 200) # ONLY Β±200 around current RPM
17
  FORBID_BOUNDARY = True
18
 
19
  DEFAULT_MIN_GAIN_PRED = 0.5
20
 
21
- # μΆ”μ²œ λŒ€μƒ timepoint rule
22
- START_HOURS = 12.0
23
- START_BDO = 20.0
24
-
25
  # =========================================================
26
  # Gene set (must match training)
27
  # =========================================================
@@ -64,9 +68,19 @@ for k in keys_to_drop:
64
  medium_cols_carbon = list(Carbon_source_dict.keys())
65
  medium_cols_salts = list(Base_dict.keys()) # salts = base
66
  medium_cols_add = list(Additional_dict.keys()) # additives
67
-
68
  medium_cols = medium_cols_carbon + medium_cols_salts + medium_cols_add
69
 
 
 
 
 
 
 
 
 
 
 
 
70
  # =========================================================
71
  # Medium display name mapping (hide "_i" in UI)
72
  # =========================================================
@@ -102,8 +116,7 @@ else:
102
  model = tf.keras.models.load_model(MODEL_PATH, compile=False)
103
 
104
  # =========================================================
105
- # Presets: Top-5 combos from dataset (if CSV exists), else fallback examples
106
- # Preset format: dict[preset_key] = dict[internal_component -> value]
107
  # =========================================================
108
  def _safe_read_csv(path: str):
109
  try:
@@ -114,21 +127,10 @@ def _safe_read_csv(path: str):
114
  return None
115
 
116
  def build_top5_presets_from_csv(csv_path: str, top_k: int = 5):
117
- """
118
- If training CSV is available in Space, derive top-K medium combinations:
119
- - For each BatchNo, take the first timepoint row's medium values
120
- - Define combo by set of nonzero medium components
121
- - Count combos, pick top-K
122
- - For each combo, preset values = median of those components across batches in that combo
123
- """
124
  df = _safe_read_csv(csv_path)
125
- if df is None:
126
- return {}
127
-
128
- if "BatchNo" not in df.columns:
129
  return {}
130
 
131
- # ensure columns exist
132
  for c in medium_cols:
133
  if c not in df.columns:
134
  df[c] = 0.0
@@ -143,23 +145,19 @@ def build_top5_presets_from_csv(csv_path: str, top_k: int = 5):
143
  else:
144
  first_rows = df.groupby("BatchNo", as_index=False).first()
145
 
146
- # numeric
147
  first_rows[medium_cols] = first_rows[medium_cols].apply(pd.to_numeric, errors="coerce").fillna(0.0)
148
 
149
- # combo signature by nonzero components
150
  def signature(row):
151
  nz = [c for c in medium_cols if float(row[c]) != 0.0]
152
  nz.sort()
153
  return "|".join(nz)
154
 
155
  first_rows["_sig"] = first_rows.apply(signature, axis=1)
156
- # drop empty signature (no medium info)
157
  first_rows = first_rows[first_rows["_sig"].astype(str).str.len() > 0].copy()
158
  if len(first_rows) == 0:
159
  return {}
160
 
161
- sig_counts = first_rows["_sig"].value_counts()
162
- top_sigs = sig_counts.head(top_k).index.tolist()
163
 
164
  presets = {}
165
  for i, sig in enumerate(top_sigs, start=1):
@@ -169,12 +167,9 @@ def build_top5_presets_from_csv(csv_path: str, top_k: int = 5):
169
  for c in comps:
170
  vals[c] = float(np.median(sub[c].to_numpy(dtype=float)))
171
  presets[f"TopCombo{i}"] = vals
172
-
173
  return presets
174
 
175
  def fallback_example_presets():
176
- # NOTE: CSVκ°€ Space에 없을 λ•Œλ„ dropdown이 "항상" 보이도둝 μ˜ˆμ‹œ 5개λ₯Ό 제곡
177
- # 값은 0이 μ•„λ‹Œ μ˜ˆμ‹œλ‘œλ§Œ λ„£μ—ˆκ³ , μ‹€μ œ μ‹€ν—˜ 쑰건과 λ‹€λ₯Ό 수 있음.
178
  ex = {
179
  "Example1": {"Glucose_i": 1.0, "YE_i": 10.0, "K2HPO4_i": 3.0, "KH2PO4_i": 1.0, "MgSO4Β·7H2O_i": 0.5},
180
  "Example2": {"Glucose_i": 1.0, "YE_i": 5.0, "NaCl_i": 1.0, "K2HPO4_i": 3.0, "MgSO4Β·7H2O_i": 0.5},
@@ -182,7 +177,6 @@ def fallback_example_presets():
182
  "Example4": {"Glucose_i": 1.0, "YE_i": 10.0, "K2HPO4_i": 3.0, "MgSO4Β·7H2O_i": 0.5, "CSL_i": 5.0},
183
  "Example5": {"Glucose_i": 1.0, "YE_i": 10.0, "K2HPO4_i": 3.0, "MgSO4Β·7H2O_i": 0.5, "IPTG_i": 0.1},
184
  }
185
- # keep only known keys
186
  cleaned = {}
187
  for k, d in ex.items():
188
  dd = {}
@@ -192,7 +186,6 @@ def fallback_example_presets():
192
  cleaned[k] = dd
193
  return cleaned
194
 
195
- # Try to build presets from CSV if it exists in Space
196
  PRESETS = build_top5_presets_from_csv("BDO_Data_cleaned_with_Feed_deltat.csv", top_k=5)
197
  if not PRESETS:
198
  PRESETS = fallback_example_presets()
@@ -204,13 +197,10 @@ def preset_label(preset_key: str) -> str:
204
  items = []
205
  for internal, v in d.items():
206
  disp = INTERNAL_TO_DISP.get(internal, internal)
207
- try:
208
- fv = float(v)
209
- except Exception:
210
- fv = v
211
  items.append((disp, fv))
212
  items = sorted(items, key=lambda x: x[0])
213
- inside = "; ".join([f"{n}={val:g}" if isinstance(val, (int, float, np.floating)) else f"{n}={val}" for n, val in items])
214
  return f"{preset_key} ({inside})"
215
 
216
  PRESET_LABELS = {preset_label(k): k for k in PRESETS.keys()}
@@ -220,18 +210,13 @@ def apply_preset(preset_label_selected: str):
220
  preset_key = PRESET_LABELS.get(preset_label_selected, "")
221
  d = PRESETS.get(preset_key, {})
222
  if not isinstance(d, dict) or len(d) == 0:
223
- return [], [], [], pd.DataFrame(columns=["component", "value"])
224
 
225
- # split by category and convert to display names
226
  carbon_sel, salts_sel, add_sel = [], [], []
227
  rows = []
228
-
229
  for internal, v in d.items():
230
  disp = INTERNAL_TO_DISP.get(internal, internal)
231
- try:
232
- fv = float(v)
233
- except Exception:
234
- fv = 0.0
235
  rows.append([disp, fv])
236
 
237
  if internal in medium_cols_carbon:
@@ -241,11 +226,8 @@ def apply_preset(preset_label_selected: str):
241
  elif internal in medium_cols_add:
242
  add_sel.append(disp)
243
 
244
- df = pd.DataFrame(rows, columns=["component", "value"])
245
- carbon_sel = sorted(list(set(carbon_sel)))
246
- salts_sel = sorted(list(set(salts_sel)))
247
- add_sel = sorted(list(set(add_sel)))
248
- return carbon_sel, salts_sel, add_sel, df
249
 
250
  # =========================================================
251
  # Gene embedding helpers
@@ -269,11 +251,9 @@ def build_gene_embedding(deleted_txt: str, added_txt: str, replaced_txt: str):
269
  for g in deleted:
270
  if g in g2i:
271
  emb[g2i[g]] = -1.0
272
-
273
  for g in added:
274
  if g in g2i:
275
  emb[g2i[g]] += 1.0
276
-
277
  for item in replaced:
278
  if "->" in item:
279
  old, new = [x.strip() for x in item.split("->", 1)]
@@ -284,7 +264,6 @@ def build_gene_embedding(deleted_txt: str, added_txt: str, replaced_txt: str):
284
  else:
285
  if item in g2i:
286
  emb[g2i[item]] = -1.0
287
-
288
  return emb.tolist()
289
 
290
  # =========================================================
@@ -296,51 +275,47 @@ def build_medium_vector_from_df(df: pd.DataFrame):
296
  return vec.tolist()
297
 
298
  dff = df.copy()
299
- if "component" not in dff.columns or "value" not in dff.columns:
 
300
  return vec.tolist()
301
 
302
  dff["component"] = dff["component"].astype(str)
303
- dff["value"] = pd.to_numeric(dff["value"], errors="coerce").fillna(0.0)
304
 
305
  m2i = {m: i for i, m in enumerate(medium_cols)}
306
-
307
  for _, r in dff.iterrows():
308
  disp = r["component"]
309
  internal = DISP_TO_INTERNAL.get(disp, None)
310
  if internal is None:
311
  continue
312
- if internal in m2i:
313
- vec[m2i[internal]] = float(r["value"])
314
-
315
  return vec.tolist()
316
 
317
  def merge_selected_to_table(existing_df, carbon_sel, salts_sel, add_sel):
318
- """
319
- Table rows = union of selected components across 3 categories.
320
- Keep existing values if present.
321
- """
322
  all_sel = []
323
  for arr in [carbon_sel, salts_sel, add_sel]:
324
  if arr:
325
  all_sel.extend(list(arr))
326
  all_sel = sorted(list(dict.fromkeys(all_sel)))
327
 
 
 
328
  if existing_df is None or not isinstance(existing_df, pd.DataFrame) or len(existing_df) == 0:
329
- return pd.DataFrame([[c, 0.0] for c in all_sel], columns=["component", "value"])
330
 
331
  dff = existing_df.copy()
332
- if "component" not in dff.columns or "value" not in dff.columns:
333
- return pd.DataFrame([[c, 0.0] for c in all_sel], columns=["component", "value"])
334
 
335
  dff["component"] = dff["component"].astype(str)
336
- dff["value"] = pd.to_numeric(dff["value"], errors="coerce").fillna(0.0)
337
 
338
- have = {c: float(v) for c, v in zip(dff["component"], dff["value"])}
339
  rows = [[c, have.get(c, 0.0)] for c in all_sel]
340
- return pd.DataFrame(rows, columns=["component", "value"])
341
 
342
  # =========================================================
343
- # Inference core (Β±200 RPM search)
344
  # =========================================================
345
  def _prepare_window(win_raw: np.ndarray, L: int) -> np.ndarray:
346
  if win_raw.shape[0] < L:
@@ -368,6 +343,9 @@ def build_window_matrix(
368
  for c in required:
369
  df[c] = pd.to_numeric(df[c], errors="coerce").fillna(0.0)
370
 
 
 
 
371
  t = df["Time"].to_numpy(dtype=float)
372
  delta_t = np.zeros_like(t, dtype=float)
373
  if len(t) >= 2:
@@ -392,7 +370,7 @@ def build_window_matrix(
392
  rows.append([row_dict[c] for c in feature_cols])
393
  return np.asarray(rows, dtype=np.float32)
394
 
395
- def predict_next_bdo_and_suggest_rpm_pm200(
396
  timepoints: list,
397
  gene_vec: list,
398
  medium_vec: list,
@@ -401,12 +379,14 @@ def predict_next_bdo_and_suggest_rpm_pm200(
401
  feature_cols: list,
402
  gene_cols: list,
403
  medium_cols: list,
404
- seq_len: int = 3,
405
- min_gain_pred: float = 0.5,
406
  ):
407
  df_last = pd.DataFrame(timepoints).copy()
408
- df_last["Time"] = pd.to_numeric(df_last["Time"], errors="coerce").fillna(0.0)
409
- df_last["BDO"] = pd.to_numeric(df_last["BDO"], errors="coerce").fillna(0.0)
 
 
410
  t_last = float(df_last.iloc[-1]["Time"])
411
  bdo_last = float(df_last.iloc[-1]["BDO"])
412
 
@@ -415,8 +395,8 @@ def predict_next_bdo_and_suggest_rpm_pm200(
415
  "decision": "NO_ACTION",
416
  "reason": (
417
  f"μΆ”μ²œ λŒ€μƒ ꡬ간이 μ•„λ‹™λ‹ˆλ‹€.\n"
418
- f"- ν˜„μž¬ Time={t_last:.1f} h, BDO={bdo_last:.2f} g/L\n"
419
- f"- μΆ”μ²œμ€ Time β‰₯ {START_HOURS:.1f} h AND BDO β‰₯ {START_BDO:.1f} g/L μ—μ„œλ§Œ μˆ˜ν–‰ν•©λ‹ˆλ‹€."
420
  ),
421
  }
422
 
@@ -433,7 +413,28 @@ def predict_next_bdo_and_suggest_rpm_pm200(
433
  X_keep = _safe_transform(scaler, win, feature_cols)
434
  pred_keep = float(model.predict(X_keep[None, :, :], verbose=0)[0, 0])
435
 
436
- curr_rpm = float(pd.DataFrame(timepoints).iloc[-1]["rpm"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
  rpm_feat_idx = feature_cols.index("rpm")
438
 
439
  best_pred = pred_keep
@@ -457,26 +458,54 @@ def predict_next_bdo_and_suggest_rpm_pm200(
457
  best_pred = pred
458
  best_rpm = float(rpm_cand)
459
 
460
- gain = float(best_pred - pred_keep)
461
-
462
- if (abs(best_rpm - curr_rpm) < 1e-6) or (gain < float(min_gain_pred)):
463
  return {
464
- "decision": "KEEP_RPM",
465
  "pred_keep": round(pred_keep, 2),
 
 
 
 
466
  }
467
 
468
  return {
469
- "decision": "CHANGE_RPM",
470
  "pred_keep": round(pred_keep, 2),
471
- "pred_best": round(best_pred, 2),
472
- "curr_rpm": round(curr_rpm, 0),
473
- "best_rpm": round(best_rpm, 0),
474
- "gain": round(gain, 2),
475
  }
476
 
477
  # =========================================================
478
- # UI main callback
479
  # =========================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
480
  def run_predict(
481
  deleted_genes,
482
  added_genes,
@@ -487,22 +516,44 @@ def run_predict(
487
  salts_sel,
488
  add_sel,
489
  medium_table,
490
- t1, b1, od1, rpm1, feed1, cc1,
491
- t2, b2, od2, rpm2, feed2, cc2,
492
- t3, b3, od3, rpm3, feed3, cc3,
493
  ):
494
- gene_vec = build_gene_embedding(deleted_genes, added_genes, replaced_genes)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495
 
496
- # medium vector from table (table is union of selected comps)
497
- medium_vec = build_medium_vector_from_df(medium_table)
498
 
499
- timepoints = [
500
- {"Time": t1, "BDO": b1, "OD": od1, "rpm": rpm1, "Feed": feed1, "CarbonContents": cc1},
501
- {"Time": t2, "BDO": b2, "OD": od2, "rpm": rpm2, "Feed": feed2, "CarbonContents": cc2},
502
- {"Time": t3, "BDO": b3, "OD": od3, "rpm": rpm3, "Feed": feed3, "CarbonContents": cc3},
503
- ]
 
 
 
504
 
505
- out = predict_next_bdo_and_suggest_rpm_pm200(
 
 
 
506
  timepoints=timepoints,
507
  gene_vec=gene_vec,
508
  medium_vec=medium_vec,
@@ -515,34 +566,35 @@ def run_predict(
515
  min_gain_pred=float(min_gain_pred),
516
  )
517
 
518
- if out.get("decision") == "NO_ACTION":
519
- return out.get("reason", "μΆ”μ²œμ„ μˆ˜ν–‰ν•  수 μ—†μŠ΅λ‹ˆλ‹€.")
 
 
 
 
 
 
 
 
 
 
520
 
521
- if out.get("decision") == "KEEP_RPM":
522
  return (
523
- "RPM 변경을 ꢌμž₯ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.\n"
524
- f"- λ‹€μŒ μ‹œμ  BDO 예츑 (ν˜„μž¬ RPM μœ μ§€): {out['pred_keep']:.2f} g/L"
 
 
 
 
 
525
  )
526
 
527
- # CHANGE_RPM
528
  return (
529
- f"μ˜ˆμƒ κ°œμ„ ν­μ΄ {float(min_gain_pred):.2f} g/L 이상이라 RPM 변경을 ꢌμž₯ν•©λ‹ˆλ‹€.\n"
530
- f"- λ‹€μŒ μ‹œμ  BDO 예츑 (ν˜„μž¬ RPM μœ μ§€): {out['pred_keep']:.2f} g/L\n"
531
- f"- λ‹€μŒ μ‹œμ  BDO 예츑 (μΆ”μ²œ RPM 적용): {out['pred_best']:.2f} g/L\n"
532
- f"- μΆ”μ²œ RPM: {out['curr_rpm']:.0f} β†’ {out['best_rpm']:.0f} (Ξ”={out['best_rpm']-out['curr_rpm']:+.0f})\n"
533
- f"- μ˜ˆμƒ μ¦κ°€λŸ‰: +{out['gain']:.2f} g/L"
534
  )
535
 
536
- # =========================================================
537
- # UI wiring helpers
538
- # =========================================================
539
- def on_any_medium_select_change(carbon_sel, salts_sel, add_sel, medium_table):
540
- return merge_selected_to_table(medium_table, carbon_sel, salts_sel, add_sel)
541
-
542
- def on_preset_change(preset_label_selected):
543
- carbon_sel, salts_sel, add_sel, df = apply_preset(preset_label_selected)
544
- return carbon_sel, salts_sel, add_sel, df
545
-
546
  # =========================================================
547
  # UI
548
  # =========================================================
@@ -557,7 +609,7 @@ with gr.Blocks() as demo:
557
  with gr.Row():
558
  min_gain_pred = gr.Number(
559
  value=DEFAULT_MIN_GAIN_PRED,
560
- label="RPM λ³€κ²½ μ΅œμ†Œ μ˜ˆμƒ κ°œμ„ ν­ (g/L)"
561
  )
562
 
563
  gr.Markdown("### Strain (genes)")
@@ -575,77 +627,52 @@ with gr.Blocks() as demo:
575
 
576
  gr.Markdown("### Medium components (by category)")
577
  with gr.Row():
578
- carbon_sel = gr.Dropdown(
579
- choices=DISP_CARBON,
580
- multiselect=True,
581
- label="Carbon source",
582
- value=[]
583
- )
584
- salts_sel = gr.Dropdown(
585
- choices=DISP_SALTS,
586
- multiselect=True,
587
- label="Salts",
588
- value=[]
589
- )
590
- add_sel = gr.Dropdown(
591
- choices=DISP_ADD,
592
- multiselect=True,
593
- label="Additives",
594
- value=[]
595
- )
596
 
597
  medium_table = gr.Dataframe(
598
- headers=["component", "value"],
599
  datatype=["str", "number"],
600
  row_count=(0, "dynamic"),
601
  col_count=(2, "fixed"),
602
  interactive=True,
603
- label="Enter values for selected components"
604
  )
605
 
606
- # preset -> sets category selections + table values
607
  preset_name.change(
608
  fn=on_preset_change,
609
  inputs=[preset_name],
610
  outputs=[carbon_sel, salts_sel, add_sel, medium_table],
611
  )
612
 
613
- # any category selection change -> update table (keep values if exist)
614
- carbon_sel.change(
615
- fn=on_any_medium_select_change,
616
- inputs=[carbon_sel, salts_sel, add_sel, medium_table],
617
- outputs=[medium_table],
618
- )
619
- salts_sel.change(
620
- fn=on_any_medium_select_change,
621
- inputs=[carbon_sel, salts_sel, add_sel, medium_table],
622
- outputs=[medium_table],
623
- )
624
- add_sel.change(
625
- fn=on_any_medium_select_change,
626
- inputs=[carbon_sel, salts_sel, add_sel, medium_table],
627
- outputs=[medium_table],
 
 
 
 
 
628
  )
629
 
630
- gr.Markdown("### Enter last 3 timepoints (Time, BDO, OD, rpm, Feed, CarbonContents)")
631
-
632
- def tp_row(title):
633
- gr.Markdown(f"**{title}**")
634
- with gr.Row():
635
- t = gr.Number(label="Time (h)", value=0.0)
636
- b = gr.Number(label="BDO (g/L)", value=0.0)
637
- od = gr.Number(label="OD", value=0.0)
638
- rpm = gr.Number(label="rpm", value=0.0)
639
- feed = gr.Number(label="Feed", value=0.0)
640
- cc = gr.Number(label="CarbonContents", value=0.0)
641
- return t, b, od, rpm, feed, cc
642
-
643
- t1, b1, od1, rpm1, feed1, cc1 = tp_row("Timepoint 1 (oldest)")
644
- t2, b2, od2, rpm2, feed2, cc2 = tp_row("Timepoint 2")
645
- t3, b3, od3, rpm3, feed3, cc3 = tp_row("Timepoint 3 (latest)")
646
 
647
  btn = gr.Button("Predict & Suggest")
648
- out_box = gr.Textbox(label="Output", lines=10)
649
 
650
  btn.click(
651
  fn=run_predict,
@@ -655,9 +682,7 @@ with gr.Blocks() as demo:
655
  preset_name,
656
  carbon_sel, salts_sel, add_sel,
657
  medium_table,
658
- t1, b1, od1, rpm1, feed1, cc1,
659
- t2, b2, od2, rpm2, feed2, cc2,
660
- t3, b3, od3, rpm3, feed3, cc3,
661
  ],
662
  outputs=[out_box],
663
  )
 
1
  import os
 
2
  import numpy as np
3
  import pandas as pd
4
  import gradio as gr
 
6
  import tensorflow as tf
7
 
8
  # =========================================================
9
+ # Settings / Constants
10
  # =========================================================
11
  BEST_L = 3
12
  CC_COL = "CarbonContents"
13
 
14
+ # Eligibility rule for running recommendation
15
+ START_HOURS = 12.0
16
+ START_BDO = 20.0
17
+
18
+ # Feed logic
19
+ CC_THRESHOLD = 20.0
20
+ FEED_VALUE = 50.0 # unit: g/L (assumption for UI display)
21
+
22
+ # RPM search (ONLY Β±200 around current rpm)
23
  RPM_RANGE = (150, 650)
24
+ RPM_DELTAS = (-200, -150, -100, -50, 50, 100, 150, 200)
25
  FORBID_BOUNDARY = True
26
 
27
  DEFAULT_MIN_GAIN_PRED = 0.5
28
 
 
 
 
 
29
  # =========================================================
30
  # Gene set (must match training)
31
  # =========================================================
 
68
  medium_cols_carbon = list(Carbon_source_dict.keys())
69
  medium_cols_salts = list(Base_dict.keys()) # salts = base
70
  medium_cols_add = list(Additional_dict.keys()) # additives
 
71
  medium_cols = medium_cols_carbon + medium_cols_salts + medium_cols_add
72
 
73
+ # =========================================================
74
+ # Units (UI display)
75
+ # =========================================================
76
+ UNIT_MEDIUM_DEFAULT = "g/L"
77
+ UNIT_TIME = "h"
78
+ UNIT_BDO = "g/L"
79
+ UNIT_OD = "AU"
80
+ UNIT_RPM = "rpm"
81
+ UNIT_FEED = "g/L"
82
+ UNIT_CC = "g/L"
83
+
84
  # =========================================================
85
  # Medium display name mapping (hide "_i" in UI)
86
  # =========================================================
 
116
  model = tf.keras.models.load_model(MODEL_PATH, compile=False)
117
 
118
  # =========================================================
119
+ # Presets (Top-5 combos from CSV if exists, else fallback)
 
120
  # =========================================================
121
  def _safe_read_csv(path: str):
122
  try:
 
127
  return None
128
 
129
  def build_top5_presets_from_csv(csv_path: str, top_k: int = 5):
 
 
 
 
 
 
 
130
  df = _safe_read_csv(csv_path)
131
+ if df is None or "BatchNo" not in df.columns:
 
 
 
132
  return {}
133
 
 
134
  for c in medium_cols:
135
  if c not in df.columns:
136
  df[c] = 0.0
 
145
  else:
146
  first_rows = df.groupby("BatchNo", as_index=False).first()
147
 
 
148
  first_rows[medium_cols] = first_rows[medium_cols].apply(pd.to_numeric, errors="coerce").fillna(0.0)
149
 
 
150
  def signature(row):
151
  nz = [c for c in medium_cols if float(row[c]) != 0.0]
152
  nz.sort()
153
  return "|".join(nz)
154
 
155
  first_rows["_sig"] = first_rows.apply(signature, axis=1)
 
156
  first_rows = first_rows[first_rows["_sig"].astype(str).str.len() > 0].copy()
157
  if len(first_rows) == 0:
158
  return {}
159
 
160
+ top_sigs = first_rows["_sig"].value_counts().head(top_k).index.tolist()
 
161
 
162
  presets = {}
163
  for i, sig in enumerate(top_sigs, start=1):
 
167
  for c in comps:
168
  vals[c] = float(np.median(sub[c].to_numpy(dtype=float)))
169
  presets[f"TopCombo{i}"] = vals
 
170
  return presets
171
 
172
  def fallback_example_presets():
 
 
173
  ex = {
174
  "Example1": {"Glucose_i": 1.0, "YE_i": 10.0, "K2HPO4_i": 3.0, "KH2PO4_i": 1.0, "MgSO4Β·7H2O_i": 0.5},
175
  "Example2": {"Glucose_i": 1.0, "YE_i": 5.0, "NaCl_i": 1.0, "K2HPO4_i": 3.0, "MgSO4Β·7H2O_i": 0.5},
 
177
  "Example4": {"Glucose_i": 1.0, "YE_i": 10.0, "K2HPO4_i": 3.0, "MgSO4Β·7H2O_i": 0.5, "CSL_i": 5.0},
178
  "Example5": {"Glucose_i": 1.0, "YE_i": 10.0, "K2HPO4_i": 3.0, "MgSO4Β·7H2O_i": 0.5, "IPTG_i": 0.1},
179
  }
 
180
  cleaned = {}
181
  for k, d in ex.items():
182
  dd = {}
 
186
  cleaned[k] = dd
187
  return cleaned
188
 
 
189
  PRESETS = build_top5_presets_from_csv("BDO_Data_cleaned_with_Feed_deltat.csv", top_k=5)
190
  if not PRESETS:
191
  PRESETS = fallback_example_presets()
 
197
  items = []
198
  for internal, v in d.items():
199
  disp = INTERNAL_TO_DISP.get(internal, internal)
200
+ fv = float(v)
 
 
 
201
  items.append((disp, fv))
202
  items = sorted(items, key=lambda x: x[0])
203
+ inside = "; ".join([f"{n}={val:g} {UNIT_MEDIUM_DEFAULT}" for n, val in items])
204
  return f"{preset_key} ({inside})"
205
 
206
  PRESET_LABELS = {preset_label(k): k for k in PRESETS.keys()}
 
210
  preset_key = PRESET_LABELS.get(preset_label_selected, "")
211
  d = PRESETS.get(preset_key, {})
212
  if not isinstance(d, dict) or len(d) == 0:
213
+ return [], [], [], pd.DataFrame(columns=["component", f"value ({UNIT_MEDIUM_DEFAULT})"])
214
 
 
215
  carbon_sel, salts_sel, add_sel = [], [], []
216
  rows = []
 
217
  for internal, v in d.items():
218
  disp = INTERNAL_TO_DISP.get(internal, internal)
219
+ fv = float(v)
 
 
 
220
  rows.append([disp, fv])
221
 
222
  if internal in medium_cols_carbon:
 
226
  elif internal in medium_cols_add:
227
  add_sel.append(disp)
228
 
229
+ df = pd.DataFrame(rows, columns=["component", f"value ({UNIT_MEDIUM_DEFAULT})"])
230
+ return sorted(set(carbon_sel)), sorted(set(salts_sel)), sorted(set(add_sel)), df
 
 
 
231
 
232
  # =========================================================
233
  # Gene embedding helpers
 
251
  for g in deleted:
252
  if g in g2i:
253
  emb[g2i[g]] = -1.0
 
254
  for g in added:
255
  if g in g2i:
256
  emb[g2i[g]] += 1.0
 
257
  for item in replaced:
258
  if "->" in item:
259
  old, new = [x.strip() for x in item.split("->", 1)]
 
264
  else:
265
  if item in g2i:
266
  emb[g2i[item]] = -1.0
 
267
  return emb.tolist()
268
 
269
  # =========================================================
 
275
  return vec.tolist()
276
 
277
  dff = df.copy()
278
+ value_col = f"value ({UNIT_MEDIUM_DEFAULT})"
279
+ if "component" not in dff.columns or value_col not in dff.columns:
280
  return vec.tolist()
281
 
282
  dff["component"] = dff["component"].astype(str)
283
+ dff[value_col] = pd.to_numeric(dff[value_col], errors="coerce").fillna(0.0)
284
 
285
  m2i = {m: i for i, m in enumerate(medium_cols)}
 
286
  for _, r in dff.iterrows():
287
  disp = r["component"]
288
  internal = DISP_TO_INTERNAL.get(disp, None)
289
  if internal is None:
290
  continue
291
+ vec[m2i[internal]] = float(r[value_col])
 
 
292
  return vec.tolist()
293
 
294
  def merge_selected_to_table(existing_df, carbon_sel, salts_sel, add_sel):
 
 
 
 
295
  all_sel = []
296
  for arr in [carbon_sel, salts_sel, add_sel]:
297
  if arr:
298
  all_sel.extend(list(arr))
299
  all_sel = sorted(list(dict.fromkeys(all_sel)))
300
 
301
+ value_col = f"value ({UNIT_MEDIUM_DEFAULT})"
302
+
303
  if existing_df is None or not isinstance(existing_df, pd.DataFrame) or len(existing_df) == 0:
304
+ return pd.DataFrame([[c, 0.0] for c in all_sel], columns=["component", value_col])
305
 
306
  dff = existing_df.copy()
307
+ if "component" not in dff.columns or value_col not in dff.columns:
308
+ return pd.DataFrame([[c, 0.0] for c in all_sel], columns=["component", value_col])
309
 
310
  dff["component"] = dff["component"].astype(str)
311
+ dff[value_col] = pd.to_numeric(dff[value_col], errors="coerce").fillna(0.0)
312
 
313
+ have = {c: float(v) for c, v in zip(dff["component"], dff[value_col])}
314
  rows = [[c, have.get(c, 0.0)] for c in all_sel]
315
+ return pd.DataFrame(rows, columns=["component", value_col])
316
 
317
  # =========================================================
318
+ # Inference helpers
319
  # =========================================================
320
  def _prepare_window(win_raw: np.ndarray, L: int) -> np.ndarray:
321
  if win_raw.shape[0] < L:
 
343
  for c in required:
344
  df[c] = pd.to_numeric(df[c], errors="coerce").fillna(0.0)
345
 
346
+ # sort by Time (important when user adds more points)
347
+ df = df.sort_values("Time").reset_index(drop=True)
348
+
349
  t = df["Time"].to_numpy(dtype=float)
350
  delta_t = np.zeros_like(t, dtype=float)
351
  if len(t) >= 2:
 
370
  rows.append([row_dict[c] for c in feature_cols])
371
  return np.asarray(rows, dtype=np.float32)
372
 
373
+ def predict_with_optional_feed_and_rpm(
374
  timepoints: list,
375
  gene_vec: list,
376
  medium_vec: list,
 
379
  feature_cols: list,
380
  gene_cols: list,
381
  medium_cols: list,
382
+ seq_len: int,
383
+ min_gain_pred: float,
384
  ):
385
  df_last = pd.DataFrame(timepoints).copy()
386
+ for c in ["Time", "BDO", "Feed", "CarbonContents", "rpm"]:
387
+ df_last[c] = pd.to_numeric(df_last[c], errors="coerce").fillna(0.0)
388
+ df_last = df_last.sort_values("Time").reset_index(drop=True)
389
+
390
  t_last = float(df_last.iloc[-1]["Time"])
391
  bdo_last = float(df_last.iloc[-1]["BDO"])
392
 
 
395
  "decision": "NO_ACTION",
396
  "reason": (
397
  f"μΆ”μ²œ λŒ€μƒ ꡬ간이 μ•„λ‹™λ‹ˆλ‹€.\n"
398
+ f"- ν˜„μž¬ Time={t_last:.1f} {UNIT_TIME}, BDO={bdo_last:.2f} {UNIT_BDO}\n"
399
+ f"- μΆ”μ²œμ€ Time β‰₯ {START_HOURS:.1f} {UNIT_TIME} AND BDO β‰₯ {START_BDO:.1f} {UNIT_BDO} μ—μ„œλ§Œ μˆ˜ν–‰ν•©λ‹ˆλ‹€."
400
  ),
401
  }
402
 
 
413
  X_keep = _safe_transform(scaler, win, feature_cols)
414
  pred_keep = float(model.predict(X_keep[None, :, :], verbose=0)[0, 0])
415
 
416
+ cc_last = float(df_last.iloc[-1]["CarbonContents"])
417
+ feed_last = float(df_last.iloc[-1]["Feed"])
418
+ feed_feat_idx = feature_cols.index("Feed")
419
+
420
+ if (cc_last < CC_THRESHOLD) and (abs(feed_last) < 1e-9):
421
+ win_feed = win.copy()
422
+ win_feed[-1, feed_feat_idx] = float(FEED_VALUE)
423
+ X_feed = _safe_transform(scaler, win_feed, feature_cols)
424
+ pred_feed = float(model.predict(X_feed[None, :, :], verbose=0)[0, 0])
425
+
426
+ gain_feed = float(pred_feed - pred_keep)
427
+ if gain_feed >= float(min_gain_pred):
428
+ return {
429
+ "decision": "FEED",
430
+ "pred_keep": round(pred_keep, 2),
431
+ "pred_after": round(pred_feed, 2),
432
+ "gain": round(gain_feed, 2),
433
+ "feed_from": round(feed_last, 2),
434
+ "feed_to": round(FEED_VALUE, 2),
435
+ }
436
+
437
+ curr_rpm = float(df_last.iloc[-1]["rpm"])
438
  rpm_feat_idx = feature_cols.index("rpm")
439
 
440
  best_pred = pred_keep
 
458
  best_pred = pred
459
  best_rpm = float(rpm_cand)
460
 
461
+ gain_rpm = float(best_pred - pred_keep)
462
+ if (abs(best_rpm - curr_rpm) > 1e-6) and (gain_rpm >= float(min_gain_pred)):
 
463
  return {
464
+ "decision": "CHANGE_RPM",
465
  "pred_keep": round(pred_keep, 2),
466
+ "pred_after": round(best_pred, 2),
467
+ "gain": round(gain_rpm, 2),
468
+ "rpm_from": round(curr_rpm, 0),
469
+ "rpm_to": round(best_rpm, 0),
470
  }
471
 
472
  return {
473
+ "decision": "KEEP",
474
  "pred_keep": round(pred_keep, 2),
 
 
 
 
475
  }
476
 
477
  # =========================================================
478
+ # UI callbacks
479
  # =========================================================
480
+ def on_any_medium_select_change(carbon_sel, salts_sel, add_sel, medium_table):
481
+ return merge_selected_to_table(medium_table, carbon_sel, salts_sel, add_sel)
482
+
483
+ def on_preset_change(preset_label_selected):
484
+ carbon_sel, salts_sel, add_sel, df = apply_preset(preset_label_selected)
485
+ return carbon_sel, salts_sel, add_sel, df
486
+
487
+ def init_timepoints_df():
488
+ # μ΅œμ†Œ 3개 row 제곡
489
+ cols = [f"Time ({UNIT_TIME})",
490
+ f"BDO ({UNIT_BDO})",
491
+ f"OD ({UNIT_OD})",
492
+ f"rpm ({UNIT_RPM})",
493
+ f"Feed ({UNIT_FEED})",
494
+ f"CarbonContents ({UNIT_CC})"]
495
+ data = [
496
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
497
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
498
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
499
+ ]
500
+ return pd.DataFrame(data, columns=cols)
501
+
502
+ def add_timepoint_row(df):
503
+ if df is None or not isinstance(df, pd.DataFrame):
504
+ df = init_timepoints_df()
505
+ df2 = df.copy()
506
+ df2.loc[len(df2)] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
507
+ return df2
508
+
509
  def run_predict(
510
  deleted_genes,
511
  added_genes,
 
516
  salts_sel,
517
  add_sel,
518
  medium_table,
519
+ timepoints_df,
 
 
520
  ):
521
+ # validate timepoints
522
+ if timepoints_df is None or not isinstance(timepoints_df, pd.DataFrame) or len(timepoints_df) < BEST_L:
523
+ return f"TimepointsλŠ” μ΅œμ†Œ {BEST_L}개 이상 μž…λ ₯ν•΄μ•Ό ν•©λ‹ˆλ‹€."
524
+
525
+ df = timepoints_df.copy()
526
+
527
+ # column mapping from UI to internal keys
528
+ col_map = {
529
+ f"Time ({UNIT_TIME})": "Time",
530
+ f"BDO ({UNIT_BDO})": "BDO",
531
+ f"OD ({UNIT_OD})": "OD",
532
+ f"rpm ({UNIT_RPM})": "rpm",
533
+ f"Feed ({UNIT_FEED})": "Feed",
534
+ f"CarbonContents ({UNIT_CC})": "CarbonContents",
535
+ }
536
+ for ui_c, in_c in col_map.items():
537
+ if ui_c not in df.columns:
538
+ return f"Timepoints ν‘œμ— '{ui_c}' 컬럼이 μ—†μŠ΅λ‹ˆλ‹€."
539
+ df[in_c] = pd.to_numeric(df[ui_c], errors="coerce").fillna(0.0)
540
 
541
+ # keep only internal columns
542
+ df = df[list(col_map.values())].copy()
543
 
544
+ # sort by Time and drop rows with all zeros (optional)
545
+ df = df.sort_values("Time").reset_index(drop=True)
546
+
547
+ # require at least BEST_L rows AFTER sorting
548
+ if len(df) < BEST_L:
549
+ return f"TimepointsλŠ” μ΅œμ†Œ {BEST_L}개 이상 μž…λ ₯ν•΄μ•Ό ν•©λ‹ˆλ‹€."
550
+
551
+ timepoints = df.to_dict(orient="records")
552
 
553
+ gene_vec = build_gene_embedding(deleted_genes, added_genes, replaced_genes)
554
+ medium_vec = build_medium_vector_from_df(medium_table)
555
+
556
+ out = predict_with_optional_feed_and_rpm(
557
  timepoints=timepoints,
558
  gene_vec=gene_vec,
559
  medium_vec=medium_vec,
 
566
  min_gain_pred=float(min_gain_pred),
567
  )
568
 
569
+ if out["decision"] == "NO_ACTION":
570
+ return out["reason"]
571
+
572
+ if out["decision"] == "FEED":
573
+ return (
574
+ f"μ˜ˆμƒ κ°œμ„ ν­μ΄ {float(min_gain_pred):.2f} {UNIT_BDO} 이상이라 Feeding을 ꢌμž₯ν•©λ‹ˆλ‹€.\n"
575
+ f"- λ‹€μŒ μ‹œμ  BDO 예츑 (ν˜„μž¬ 쑰건 μœ μ§€): {out['pred_keep']:.2f} {UNIT_BDO}\n"
576
+ f"- λ‹€μŒ μ‹œμ  BDO 예츑 (Feeding 적용): {out['pred_after']:.2f} {UNIT_BDO}\n"
577
+ f"- μΆ”μ²œ Feed: {out['feed_from']:.2f} β†’ {out['feed_to']:.2f} ({UNIT_FEED})\n"
578
+ f"- μ˜ˆμƒ μ¦κ°€λŸ‰: +{out['gain']:.2f} {UNIT_BDO}\n\n"
579
+ f"(Feeding 쑰건: CarbonContents < {CC_THRESHOLD:.1f} {UNIT_CC} AND Feed = 0)"
580
+ )
581
 
582
+ if out["decision"] == "CHANGE_RPM":
583
  return (
584
+ f"μ˜ˆμƒ κ°œμ„ ν­μ΄ {float(min_gain_pred):.2f} {UNIT_BDO} 이상이라 RPM 변경을 ꢌμž₯ν•©λ‹ˆλ‹€.\n"
585
+ f"- λ‹€μŒ μ‹œμ  BDO 예츑 (ν˜„μž¬ RPM μœ μ§€): {out['pred_keep']:.2f} {UNIT_BDO}\n"
586
+ f"- λ‹€μŒ μ‹œμ  BDO 예츑 (μΆ”μ²œ RPM 적용): {out['pred_after']:.2f} {UNIT_BDO}\n"
587
+ f"- μΆ”μ²œ RPM: {out['rpm_from']:.0f} β†’ {out['rpm_to']:.0f} (Ξ”={out['rpm_to']-out['rpm_from']:+.0f} {UNIT_RPM})\n"
588
+ f"- μ˜ˆμƒ μ¦κ°€λŸ‰: +{out['gain']:.2f} {UNIT_BDO}\n\n"
589
+ "주의:\n"
590
+ "- RPM 탐색은 ν˜„μž¬ RPM κΈ°μ€€ Β±200 λ²”μœ„μ—μ„œλ§Œ μˆ˜ν–‰λ©λ‹ˆλ‹€."
591
  )
592
 
 
593
  return (
594
+ "변경을 ꢌμž₯ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.\n"
595
+ f"- λ‹€μŒ μ‹œμ  BDO 예츑 (ν˜„μž¬ 쑰건 μœ μ§€): {out['pred_keep']:.2f} {UNIT_BDO}"
 
 
 
596
  )
597
 
 
 
 
 
 
 
 
 
 
 
598
  # =========================================================
599
  # UI
600
  # =========================================================
 
609
  with gr.Row():
610
  min_gain_pred = gr.Number(
611
  value=DEFAULT_MIN_GAIN_PRED,
612
+ label=f"μ΅œμ†Œ μ˜ˆμƒ κ°œμ„ ν­ ({UNIT_BDO})"
613
  )
614
 
615
  gr.Markdown("### Strain (genes)")
 
627
 
628
  gr.Markdown("### Medium components (by category)")
629
  with gr.Row():
630
+ carbon_sel = gr.Dropdown(choices=DISP_CARBON, multiselect=True, label="Carbon source", value=[])
631
+ salts_sel = gr.Dropdown(choices=DISP_SALTS, multiselect=True, label="Salts", value=[])
632
+ add_sel = gr.Dropdown(choices=DISP_ADD, multiselect=True, label="Additives", value=[])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
633
 
634
  medium_table = gr.Dataframe(
635
+ headers=["component", f"value ({UNIT_MEDIUM_DEFAULT})"],
636
  datatype=["str", "number"],
637
  row_count=(0, "dynamic"),
638
  col_count=(2, "fixed"),
639
  interactive=True,
640
+ label=f"Enter values for selected components (unit: {UNIT_MEDIUM_DEFAULT})"
641
  )
642
 
 
643
  preset_name.change(
644
  fn=on_preset_change,
645
  inputs=[preset_name],
646
  outputs=[carbon_sel, salts_sel, add_sel, medium_table],
647
  )
648
 
649
+ carbon_sel.change(fn=on_any_medium_select_change, inputs=[carbon_sel, salts_sel, add_sel, medium_table], outputs=[medium_table])
650
+ salts_sel.change(fn=on_any_medium_select_change, inputs=[carbon_sel, salts_sel, add_sel, medium_table], outputs=[medium_table])
651
+ add_sel.change(fn=on_any_medium_select_change, inputs=[carbon_sel, salts_sel, add_sel, medium_table], outputs=[medium_table])
652
+
653
+ gr.Markdown("### Timepoints")
654
+ timepoints_df = gr.Dataframe(
655
+ value=init_timepoints_df(),
656
+ headers=[
657
+ f"Time ({UNIT_TIME})",
658
+ f"BDO ({UNIT_BDO})",
659
+ f"OD ({UNIT_OD})",
660
+ f"rpm ({UNIT_RPM})",
661
+ f"Feed ({UNIT_FEED})",
662
+ f"CarbonContents ({UNIT_CC})",
663
+ ],
664
+ datatype=["number", "number", "number", "number", "number", "number"],
665
+ row_count=(3, "dynamic"),
666
+ col_count=(6, "fixed"),
667
+ interactive=True,
668
+ label=f"Enter timepoints (need β‰₯ {BEST_L} rows; sorted by Time internally)"
669
  )
670
 
671
+ add_btn = gr.Button("+ Add timepoint")
672
+ add_btn.click(fn=add_timepoint_row, inputs=[timepoints_df], outputs=[timepoints_df])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
673
 
674
  btn = gr.Button("Predict & Suggest")
675
+ out_box = gr.Textbox(label="Output", lines=12)
676
 
677
  btn.click(
678
  fn=run_predict,
 
682
  preset_name,
683
  carbon_sel, salts_sel, add_sel,
684
  medium_table,
685
+ timepoints_df,
 
 
686
  ],
687
  outputs=[out_box],
688
  )