Samad14 commited on
Commit
09fc54e
·
1 Parent(s): d54a751

feat(md): clay simulation-parameter controls (force field, solvent, run length)

Browse files
bioai-platform/backend/app/routers/md.py CHANGED
@@ -20,6 +20,9 @@ class MDRunRequest(BaseModel):
20
  pdb_id: str = Field(..., pattern=r"^[A-Za-z0-9]{4}$", description="4-char PDB ID")
21
  mode: str = Field(default="minimize", pattern=r"^(minimize|equilibrate|production)$")
22
  platform: str | None = Field(default=None, description="Optional OpenMM platform (CPU/Reference)")
 
 
 
23
 
24
 
25
  class MDJobResponse(BaseModel):
@@ -46,6 +49,9 @@ async def run_md(request: Request, body: MDRunRequest, user_id: str = Depends(re
46
  "pdb_id": body.pdb_id,
47
  "mode": body.mode,
48
  "platform": body.platform,
 
 
 
49
  "tool_type": "md",
50
  },
51
  }
 
20
  pdb_id: str = Field(..., pattern=r"^[A-Za-z0-9]{4}$", description="4-char PDB ID")
21
  mode: str = Field(default="minimize", pattern=r"^(minimize|equilibrate|production)$")
22
  platform: str | None = Field(default=None, description="Optional OpenMM platform (CPU/Reference)")
23
+ forcefield: str | None = Field(default=None, pattern=r"^[a-z0-9_-]+$", description="Force field; only 'amber14' is currently supported")
24
+ solvent: str | None = Field(default=None, pattern=r"^(obc1|obc2|gbn2)$", description="Implicit solvent model (explicit water not supported)")
25
+ run_length_ps: float | None = Field(default=None, ge=50, le=5000, description="Desired production length in ps (production mode only; engine may clamp to wall-clock budget)")
26
 
27
 
28
  class MDJobResponse(BaseModel):
 
49
  "pdb_id": body.pdb_id,
50
  "mode": body.mode,
51
  "platform": body.platform,
52
+ "forcefield": body.forcefield,
53
+ "solvent": body.solvent,
54
+ "run_length_ps": body.run_length_ps,
55
  "tool_type": "md",
56
  },
57
  }
bioai-platform/backend/app/tools/md_sim.py CHANGED
@@ -275,7 +275,14 @@ def _sasa_shrake_ruger(
275
  # Main entry point
276
  # ---------------------------------------------------------------------------
277
 
278
- def run_simulation(pdb_id: str, mode: str = "minimize", platform: str | None = None) -> dict:
 
 
 
 
 
 
 
279
  """Run a short MD simulation on a PDB structure.
280
 
281
  Args:
@@ -283,6 +290,13 @@ def run_simulation(pdb_id: str, mode: str = "minimize", platform: str | None = N
283
  mode: 'minimize', 'equilibrate', or 'production'.
284
  platform: Optional OpenMM platform name to force (e.g. 'CPU',
285
  'Reference'); None lets OpenMM pick the default.
 
 
 
 
 
 
 
286
 
287
  Returns:
288
  Dict with energy, RMSD, RMSF, and simulation metadata.
@@ -312,7 +326,7 @@ def run_simulation(pdb_id: str, mode: str = "minimize", platform: str | None = N
312
  try:
313
  if _check_openmm():
314
  try:
315
- return _run_openmm(pdb_path, pdb_id, mode, platform)
316
  except Exception as exc:
317
  # OpenMM can reject structures with incomplete residues,
318
  # non-standard ligands it cannot strip cleanly, or other
@@ -455,16 +469,45 @@ def _add_missing_terminal_oxt(modeller) -> int:
455
  return len(targets)
456
 
457
 
458
- def _run_openmm(pdb_path: str, pdb_id: str, mode: str, platform_name: str | None = None) -> dict:
 
 
 
 
 
 
 
 
459
  """Core OpenMM simulation with correct implicit-solvent setup."""
460
  from openmm.app import PDBFile, ForceField, Simulation, CutoffNonPeriodic, Modeller
461
  from openmm import unit, LangevinMiddleIntegrator, Platform
462
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
463
  # Load structure
464
  pdb = PDBFile(pdb_path)
465
  # OpenMM 8.x: implicit solvent is loaded as an explicit force field file,
466
  # not via the createSystem(implicitSolvent=...) kwarg (which is rejected).
467
- forcefield = ForceField("amber14-all.xml", "implicit/obc2.xml")
468
 
469
  # Keep only standard amino acids — water, ions, ligands, and nucleic acids
470
  # have no AMBER14 protein template and would crash createSystem().
@@ -613,7 +656,11 @@ def _run_openmm(pdb_path: str, pdb_id: str, mode: str, platform_name: str | None
613
  t_cal = time.time()
614
  simulation.step(400)
615
  cal_rate = 400.0 / max(time.time() - t_cal, 1e-6)
616
- planned = _adaptive_production_steps(n_atoms)
 
 
 
 
617
  budget_steps = max(int(cal_rate * _PRODUCTION_BUDGET_SECONDS), int(PRODUCTION_MIN_PS * 500))
618
  production_steps = min(planned, budget_steps)
619
  logger.info("Measured throughput %.0f steps/s -> production %d steps (%.0f ps)",
@@ -701,12 +748,22 @@ def _run_openmm(pdb_path: str, pdb_id: str, mode: str, platform_name: str | None
701
  rg_avg = round(float(np.mean(rg_vals)), 2) if rg_vals else None
702
  sasa_avg = round(float(np.mean(sasa_vals)), 1) if sasa_vals else None
703
 
 
 
 
 
 
 
 
704
  return _to_native({
705
  "pdb_id": pdb_id,
706
  "mode": mode,
707
  "engine": "openmm",
708
- "forcefield": "amber14-all",
709
- "implicit_solvent": "OBC2",
 
 
 
710
  "temperature_k": 300,
711
  "timestep_fs": 2,
712
  "minimization_steps": MINIMIZATION_STEPS,
 
275
  # Main entry point
276
  # ---------------------------------------------------------------------------
277
 
278
+ def run_simulation(
279
+ pdb_id: str,
280
+ mode: str = "minimize",
281
+ platform: str | None = None,
282
+ forcefield: str | None = None,
283
+ solvent: str | None = None,
284
+ run_length_ps: float | None = None,
285
+ ) -> dict:
286
  """Run a short MD simulation on a PDB structure.
287
 
288
  Args:
 
290
  mode: 'minimize', 'equilibrate', or 'production'.
291
  platform: Optional OpenMM platform name to force (e.g. 'CPU',
292
  'Reference'); None lets OpenMM pick the default.
293
+ forcefield: 'amber14' (only AMBER14 protein templates are
294
+ supported — any other value falls back to AMBER14).
295
+ solvent: 'obc1', 'obc2', or 'gbn2' implicit-solvent XML file.
296
+ Explicit solvent is not supported.
297
+ run_length_ps: Desired production length in picoseconds
298
+ (production mode only). The engine still clamps the run to
299
+ the wall-clock budget.
300
 
301
  Returns:
302
  Dict with energy, RMSD, RMSF, and simulation metadata.
 
326
  try:
327
  if _check_openmm():
328
  try:
329
+ return _run_openmm(pdb_path, pdb_id, mode, platform, forcefield, solvent, run_length_ps)
330
  except Exception as exc:
331
  # OpenMM can reject structures with incomplete residues,
332
  # non-standard ligands it cannot strip cleanly, or other
 
469
  return len(targets)
470
 
471
 
472
+ def _run_openmm(
473
+ pdb_path: str,
474
+ pdb_id: str,
475
+ mode: str,
476
+ platform_name: str | None = None,
477
+ forcefield_name: str | None = None,
478
+ solvent_name: str | None = None,
479
+ run_length_ps: float | None = None,
480
+ ) -> dict:
481
  """Core OpenMM simulation with correct implicit-solvent setup."""
482
  from openmm.app import PDBFile, ForceField, Simulation, CutoffNonPeriodic, Modeller
483
  from openmm import unit, LangevinMiddleIntegrator, Platform
484
 
485
+ # Implicit-solvent XML files OpenMM ships with the AMBER14 data set.
486
+ # Explicit water/ions require a periodic box + TIP3P plus ion parameters
487
+ # that are not set up here — reject (fall back) rather than fake it.
488
+ _SOLVENT_XML = {
489
+ "obc1": "implicit/obc1.xml",
490
+ "obc2": "implicit/obc2.xml",
491
+ "gbn2": "implicit/gbn2.xml",
492
+ }
493
+ forcefield_key = forcefield_name or "amber14"
494
+ if forcefield_key != "amber14":
495
+ # Only AMBER14 protein templates exist in the bundled data set.
496
+ # Never silently run a "different" force field — honor the request
497
+ # by falling back and recording the fact.
498
+ logger.warning("Force field %r not supported — falling back to amber14", forcefield_key)
499
+ forcefield_key = "amber14"
500
+ solvent_key = (solvent_name or "obc2").lower()
501
+ solvent_xml = _SOLVENT_XML.get(solvent_key, "implicit/obc2.xml")
502
+ if solvent_key not in _SOLVENT_XML:
503
+ logger.warning("Solvent %r not supported — falling back to obc2", solvent_name)
504
+ solvent_key = "obc2"
505
+
506
  # Load structure
507
  pdb = PDBFile(pdb_path)
508
  # OpenMM 8.x: implicit solvent is loaded as an explicit force field file,
509
  # not via the createSystem(implicitSolvent=...) kwarg (which is rejected).
510
+ forcefield = ForceField("amber14-all.xml", solvent_xml)
511
 
512
  # Keep only standard amino acids — water, ions, ligands, and nucleic acids
513
  # have no AMBER14 protein template and would crash createSystem().
 
656
  t_cal = time.time()
657
  simulation.step(400)
658
  cal_rate = 400.0 / max(time.time() - t_cal, 1e-6)
659
+ # Desired length: user request if provided, otherwise adaptive default.
660
+ # 2 fs timestep -> 500 steps per picosecond. Only meaningful in
661
+ # production mode; still clamped below to the wall-clock budget.
662
+ requested_ps = float(run_length_ps) if run_length_ps else None
663
+ planned = int(requested_ps * 500) if requested_ps else _adaptive_production_steps(n_atoms)
664
  budget_steps = max(int(cal_rate * _PRODUCTION_BUDGET_SECONDS), int(PRODUCTION_MIN_PS * 500))
665
  production_steps = min(planned, budget_steps)
666
  logger.info("Measured throughput %.0f steps/s -> production %d steps (%.0f ps)",
 
748
  rg_avg = round(float(np.mean(rg_vals)), 2) if rg_vals else None
749
  sasa_avg = round(float(np.mean(sasa_vals)), 1) if sasa_vals else None
750
 
751
+ notes: list[str] = []
752
+ if mode == "production" and run_length_ps and int(run_length_ps * 500) > production_steps:
753
+ notes.append(
754
+ f"Requested {int(run_length_ps)} ps of production dynamics, but the engine "
755
+ f"clamped the run to {production_steps / 500:.0f} ps to fit the wall-clock budget."
756
+ )
757
+
758
  return _to_native({
759
  "pdb_id": pdb_id,
760
  "mode": mode,
761
  "engine": "openmm",
762
+ "forcefield": forcefield_key,
763
+ "forcefield_detail": "amber14-all" if forcefield_key == "amber14" else forcefield_key,
764
+ "implicit_solvent": solvent_key.upper(),
765
+ "requested_production_ps": int(run_length_ps) if run_length_ps else None,
766
+ "note": "\n".join(notes) if notes else None,
767
  "temperature_k": 300,
768
  "timestep_fs": 2,
769
  "minimization_steps": MINIMIZATION_STEPS,
bioai-platform/backend/app/worker.py CHANGED
@@ -184,7 +184,14 @@ def _run_md(job: dict) -> None:
184
 
185
  try:
186
  logger.info("Running MD simulation: PDB=%s mode=%s", pdb_id, mode)
187
- result = run_simulation(pdb_id, mode, platform=payload.get("platform"))
 
 
 
 
 
 
 
188
  from app.services.artifact_storage import upload_json
189
  storage_url = upload_json(job["id"], "result", result)
190
  supabase = get_client()
 
184
 
185
  try:
186
  logger.info("Running MD simulation: PDB=%s mode=%s", pdb_id, mode)
187
+ result = run_simulation(
188
+ pdb_id,
189
+ mode,
190
+ platform=payload.get("platform"),
191
+ forcefield=payload.get("forcefield"),
192
+ solvent=payload.get("solvent"),
193
+ run_length_ps=payload.get("run_length_ps"),
194
+ )
195
  from app.services.artifact_storage import upload_json
196
  storage_url = upload_json(job["id"], "result", result)
197
  supabase = get_client()
bioai-platform/frontend/src/app/(dashboard)/analyze/md/page.tsx CHANGED
@@ -2,15 +2,26 @@
2
  import { useState, useEffect, useCallback } from "react";
3
  import { useRouter } from "next/navigation";
4
  import { motion } from "framer-motion";
5
- import { ArrowLeft, Play, Loader2, Activity, Clock, Zap, BarChart3, Info } from "lucide-react";
6
  import { fadeUp } from "@/lib/animations";
7
  import { useAuditTrail } from "@/hooks/useAuditTrail";
8
  import { runMD, getMDStatus, type MDSimulationResult } from "@/lib/api";
 
9
 
10
  const MODES = [
11
- { value: "minimize", label: "Minimization Only", desc: "500 steps, ~5 sec", detail: "Energy minimization using L-BFGS. Removes steric clashes and high-energy contacts." },
12
- { value: "equilibrate", label: "Minimize + Equilibrate", desc: "1500 steps, ~30 sec", detail: "Minimization followed by NVT equilibration at 300K with Langevin thermostat." },
13
- { value: "production", label: "Full Short Run", desc: "Adaptive, up to ~1 ns", detail: "Complete MD: minimization, equilibration, and an adaptive production run (up to 250-1000 ps) with trajectory recording, temperature, Rg, and SASA." },
 
 
 
 
 
 
 
 
 
 
14
  ];
15
 
16
  export default function MDPage() {
@@ -19,6 +30,9 @@ export default function MDPage() {
19
 
20
  const [pdbId, setPdbId] = useState("");
21
  const [mode, setMode] = useState("minimize");
 
 
 
22
  const [jobId, setJobId] = useState<string | null>(null);
23
  const [status, setStatus] = useState<string>("");
24
  const [result, setResult] = useState<MDSimulationResult | null>(null);
@@ -68,7 +82,7 @@ export default function MDPage() {
68
  setError("");
69
  setResult(null);
70
  try {
71
- const res = await runMD(stored, mode);
72
  setJobId(res.job_id);
73
  setStatus(res.status);
74
  } catch (e: any) {
@@ -86,7 +100,7 @@ export default function MDPage() {
86
  setError("");
87
  setResult(null);
88
  try {
89
- const res = await runMD(pdbId.trim(), mode);
90
  setJobId(res.job_id);
91
  setStatus(res.status);
92
  } catch (e: any) {
@@ -110,34 +124,41 @@ export default function MDPage() {
110
  </motion.div>
111
 
112
  <motion.div variants={fadeUp} initial={{ y: 24 }} animate="show">
113
- <div className="glass-card p-5">
114
  <label className="block text-sm text-text-secondary mb-2">PDB ID</label>
115
  <div className="flex gap-2 mb-4">
116
- <input value={pdbId} onChange={(e) => setPdbId(e.target.value.toUpperCase())}
117
  placeholder="e.g. 1TIM" maxLength={4}
118
- className="w-32 px-3 py-2 rounded-lg bg-surface-1 border border-surface-3 text-text-primary text-sm font-mono uppercase placeholder:text-text-muted focus:outline-none focus:border-accent-cyan"
119
  onKeyDown={(e) => e.key === "Enter" && handleSubmit()} />
120
  </div>
121
 
122
  <label className="block text-sm text-text-secondary mb-2">Simulation Mode</label>
123
- <div className="grid grid-cols-1 sm:grid-cols-3 gap-2 mb-3">
124
- {MODES.map((m) => (
125
- <button key={m.value} onClick={() => setMode(m.value)}
126
- className={`p-3 rounded-lg border text-left transition-all ${
127
- mode === m.value ? "border-accent-cyan bg-accent-cyan/10" : "border-surface-3 bg-surface-1 hover:bg-surface-2"
128
- }`}>
129
- <div className="text-sm font-medium text-text-primary">{m.label}</div>
130
- <div className="text-xs text-text-muted mt-0.5">{m.desc}</div>
131
- </button>
132
- ))}
 
 
 
 
 
 
 
 
 
133
  </div>
134
- <p className="text-xs text-text-muted mb-3">{selectedMode.detail}</p>
135
 
136
- <button onClick={handleSubmit} disabled={loading || !pdbId.trim()}
137
- className="btn-primary px-4 py-2 text-sm flex items-center gap-2">
138
  {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />}
139
  {status === "running" || status === "queued" ? `Status: ${status}...` : "Run Simulation"}
140
- </button>
141
  </div>
142
  </motion.div>
143
 
@@ -150,7 +171,7 @@ export default function MDPage() {
150
  {result && (
151
  <motion.div initial={{ opacity: 0, y: 16 }} animate={{ opacity: 1, y: 0 }} className="mt-6 space-y-4">
152
  {/* Simulation Parameters */}
153
- <div className="glass-card p-5">
154
  <h3 className="text-sm font-semibold text-text-primary mb-3 flex items-center gap-2">
155
  <Activity className="w-4 h-4 text-accent-cyan" /> {result.engine === "openmm" ? "Simulation Parameters" : "Analysis Parameters"}
156
  </h3>
@@ -194,7 +215,7 @@ export default function MDPage() {
194
 
195
  {/* Step Counts — only for OpenMM */}
196
  {result.engine === "openmm" && (
197
- <div className="glass-card p-5">
198
  <h3 className="text-sm font-semibold text-text-primary mb-3 flex items-center gap-2">
199
  <BarChart3 className="w-4 h-4 text-accent-purple" /> Integration Steps
200
  </h3>
@@ -220,7 +241,7 @@ export default function MDPage() {
220
 
221
  {/* Energy */}
222
  {result.engine === "openmm" && (
223
- <div className="glass-card p-5">
224
  <h3 className="text-sm font-semibold text-text-primary mb-1 flex items-center gap-2">
225
  <Zap className="w-4 h-4 text-accent-amber" /> Energy Analysis
226
  </h3>
@@ -284,7 +305,7 @@ export default function MDPage() {
284
 
285
  {/* Temperature / Kinetic Energy */}
286
  {result.engine === "openmm" && result.temperature && result.temperature.length > 0 && (
287
- <div className="glass-card p-5">
288
  <h3 className="text-sm font-semibold text-text-primary mb-1">Temperature — Thermostat Coupling</h3>
289
  <p className="text-xs text-text-muted mb-3">Instantaneous temperature (Langevin thermostat, {result.temperature_k} K target). Fluctuations around the target indicate a stable equilibrated ensemble.</p>
290
  <div className="bg-surface-1 rounded-lg p-3 h-40 flex items-end gap-px">
@@ -320,7 +341,7 @@ export default function MDPage() {
320
 
321
  {/* Radius of Gyration */}
322
  {result.radius_of_gyration && result.radius_of_gyration.length > 1 && (
323
- <div className="glass-card p-5">
324
  <h3 className="text-sm font-semibold text-text-primary mb-1">Radius of Gyration — Compactness</h3>
325
  <p className="text-xs text-text-muted mb-3">Mass-weighted size over time. Rising Rg = expanding/unfolding; stable Rg = compact, folded state.</p>
326
  <div className="bg-surface-1 rounded-lg p-3 h-40 flex items-end gap-px">
@@ -356,7 +377,7 @@ export default function MDPage() {
356
 
357
  {/* Solvent-Accessible Surface Area */}
358
  {result.sasa && result.sasa.length > 0 && (
359
- <div className="glass-card p-5">
360
  <h3 className="text-sm font-semibold text-text-primary mb-1">Solvent-Accessible Surface Area</h3>
361
  <p className="text-xs text-text-muted mb-3">Shrake-Rüger SASA with a 1.4 A probe. Decreasing SASA = compaction/burial; increasing = expansion or partial unfolding.</p>
362
  <div className="bg-surface-1 rounded-lg p-3 h-40 flex items-end gap-px">
@@ -392,7 +413,7 @@ export default function MDPage() {
392
 
393
  {/* RMSD */}
394
  {result.rmsd.length > 0 && (
395
- <div className="glass-card p-5">
396
  <h3 className="text-sm font-semibold text-text-primary mb-1">RMSD — Structural Drift</h3>
397
  <p className="text-xs text-text-muted mb-3">Root-mean-square deviation vs minimized reference. Lower = more stable.</p>
398
  <div className="bg-surface-1 rounded-lg p-3 h-40 flex items-end gap-px">
@@ -425,7 +446,7 @@ export default function MDPage() {
425
 
426
  {/* RMSF */}
427
  {result.rmsf && result.rmsf.length > 0 && (
428
- <div className="glass-card p-5">
429
  <h3 className="text-sm font-semibold text-text-primary mb-1">RMSF — Per-Residue Flexibility</h3>
430
  <p className="text-xs text-text-muted mb-3">Root-mean-square fluctuation per residue. High = flexible region, low = rigid/core.</p>
431
  <div className="bg-surface-1 rounded-lg p-3 h-40 flex items-end gap-px">
@@ -458,7 +479,7 @@ export default function MDPage() {
458
 
459
  {/* Secondary Structure */}
460
  {result.secondary_structure && (
461
- <div className="glass-card p-5">
462
  <h3 className="text-sm font-semibold text-text-primary mb-3">Secondary Structure Composition</h3>
463
  <div className="flex gap-3 mb-3">
464
  {[
@@ -496,7 +517,7 @@ export default function MDPage() {
496
 
497
  {/* Structural Metrics (BioPython fallback) */}
498
  {result.radius_of_gyration_angstrom !== undefined && (
499
- <div className="glass-card p-5">
500
  <h3 className="text-sm font-semibold text-text-primary mb-3">Structural Metrics</h3>
501
  <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
502
  <div className="bg-surface-1 rounded-lg p-3">
@@ -530,7 +551,7 @@ export default function MDPage() {
530
  )}
531
 
532
  {/* Interpretation */}
533
- <div className="glass-card p-5">
534
  <h3 className="text-sm font-semibold text-text-primary mb-3 flex items-center gap-2">
535
  <Info className="w-4 h-4 text-accent-cyan" /> Interpretation
536
  </h3>
 
2
  import { useState, useEffect, useCallback } from "react";
3
  import { useRouter } from "next/navigation";
4
  import { motion } from "framer-motion";
5
+ import { ArrowLeft, Play, Loader2, Activity, Zap, BarChart3, Info } from "lucide-react";
6
  import { fadeUp } from "@/lib/animations";
7
  import { useAuditTrail } from "@/hooks/useAuditTrail";
8
  import { runMD, getMDStatus, type MDSimulationResult } from "@/lib/api";
9
+ import { ClaySegmented, ClaySlider, CriticalButton, FlatInput } from "@/components/ui";
10
 
11
  const MODES = [
12
+ { value: "minimize", label: "Minimization Only", short: "Minimize", desc: "500 steps, ~5 sec", detail: "Energy minimization using L-BFGS. Removes steric clashes and high-energy contacts." },
13
+ { value: "equilibrate", label: "Minimize + Equilibrate", short: "Equilibrate", desc: "1500 steps, ~30 sec", detail: "Minimization followed by NVT equilibration at 300K with Langevin thermostat." },
14
+ { value: "production", label: "Full Short Run", short: "Production", desc: "Adaptive, up to ~1 ns", detail: "Complete MD: minimization, equilibration, and an adaptive production run (up to 250-1000 ps) with trajectory recording, temperature, Rg, and SASA." },
15
+ ];
16
+
17
+ const FORCEFIELDS = [
18
+ { value: "amber14", label: "AMBER14 (ff14SB)" },
19
+ ];
20
+
21
+ const SOLVENTS = [
22
+ { value: "obc2", label: "Implicit · OBC2" },
23
+ { value: "gbn2", label: "Implicit · GBN2" },
24
+ { value: "obc1", label: "Implicit · OBC1" },
25
  ];
26
 
27
  export default function MDPage() {
 
30
 
31
  const [pdbId, setPdbId] = useState("");
32
  const [mode, setMode] = useState("minimize");
33
+ const [forcefield, setForcefield] = useState("amber14");
34
+ const [solvent, setSolvent] = useState("obc2");
35
+ const [runLengthPs, setRunLengthPs] = useState(250);
36
  const [jobId, setJobId] = useState<string | null>(null);
37
  const [status, setStatus] = useState<string>("");
38
  const [result, setResult] = useState<MDSimulationResult | null>(null);
 
82
  setError("");
83
  setResult(null);
84
  try {
85
+ const res = await runMD(stored, mode, { forcefield, solvent, run_length_ps: runLengthPs });
86
  setJobId(res.job_id);
87
  setStatus(res.status);
88
  } catch (e: any) {
 
100
  setError("");
101
  setResult(null);
102
  try {
103
+ const res = await runMD(pdbId.trim(), mode, { forcefield, solvent, run_length_ps: runLengthPs });
104
  setJobId(res.job_id);
105
  setStatus(res.status);
106
  } catch (e: any) {
 
124
  </motion.div>
125
 
126
  <motion.div variants={fadeUp} initial={{ y: 24 }} animate="show">
127
+ <div className="data-card p-5">
128
  <label className="block text-sm text-text-secondary mb-2">PDB ID</label>
129
  <div className="flex gap-2 mb-4">
130
+ <FlatInput value={pdbId} onChange={(e) => setPdbId(e.target.value.toUpperCase())}
131
  placeholder="e.g. 1TIM" maxLength={4}
132
+ className="w-32 font-mono uppercase"
133
  onKeyDown={(e) => e.key === "Enter" && handleSubmit()} />
134
  </div>
135
 
136
  <label className="block text-sm text-text-secondary mb-2">Simulation Mode</label>
137
+ <ClaySegmented options={MODES.map(m => ({ value: m.value, label: m.short }))} value={mode} onChange={setMode} />
138
+ <p className="text-xs text-text-muted mt-3 mb-4">{selectedMode.detail}</p>
139
+
140
+ <div className="clay p-4 mb-5">
141
+ <p className="text-xs font-semibold uppercase tracking-wide text-text-muted mb-3">Simulation Parameters</p>
142
+
143
+ <label className="block text-xs text-text-secondary mb-1.5">Force Field</label>
144
+ <ClaySegmented options={FORCEFIELDS} value={forcefield} onChange={setForcefield} className="mb-4" />
145
+
146
+ <label className="block text-xs text-text-secondary mb-1.5">Solvent Model</label>
147
+ <ClaySegmented options={SOLVENTS} value={solvent} onChange={setSolvent} />
148
+ <p className="text-xs text-text-muted mt-2 mb-4">Implicit (generalized Born) solvent only. Explicit water/ions aren't supported yet.</p>
149
+
150
+ <label className="block text-xs text-text-secondary mb-1.5">Production Length</label>
151
+ <ClaySlider value={runLengthPs} min={50} max={1000} step={25} unit="ps"
152
+ disabled={mode !== "production"} onChange={setRunLengthPs} />
153
+ <p className="text-xs text-text-muted mt-2">
154
+ {mode === "production" ? `Targets ${runLengthPs} ps of production dynamics; the engine may shorten the run to fit the wall-clock budget.` : "Select Production mode to enable the run-length slider."}
155
+ </p>
156
  </div>
 
157
 
158
+ <CriticalButton onClick={handleSubmit} disabled={loading || !pdbId.trim()}>
 
159
  {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />}
160
  {status === "running" || status === "queued" ? `Status: ${status}...` : "Run Simulation"}
161
+ </CriticalButton>
162
  </div>
163
  </motion.div>
164
 
 
171
  {result && (
172
  <motion.div initial={{ opacity: 0, y: 16 }} animate={{ opacity: 1, y: 0 }} className="mt-6 space-y-4">
173
  {/* Simulation Parameters */}
174
+ <div className="data-card p-5">
175
  <h3 className="text-sm font-semibold text-text-primary mb-3 flex items-center gap-2">
176
  <Activity className="w-4 h-4 text-accent-cyan" /> {result.engine === "openmm" ? "Simulation Parameters" : "Analysis Parameters"}
177
  </h3>
 
215
 
216
  {/* Step Counts — only for OpenMM */}
217
  {result.engine === "openmm" && (
218
+ <div className="data-card p-5">
219
  <h3 className="text-sm font-semibold text-text-primary mb-3 flex items-center gap-2">
220
  <BarChart3 className="w-4 h-4 text-accent-purple" /> Integration Steps
221
  </h3>
 
241
 
242
  {/* Energy */}
243
  {result.engine === "openmm" && (
244
+ <div className="data-card p-5">
245
  <h3 className="text-sm font-semibold text-text-primary mb-1 flex items-center gap-2">
246
  <Zap className="w-4 h-4 text-accent-amber" /> Energy Analysis
247
  </h3>
 
305
 
306
  {/* Temperature / Kinetic Energy */}
307
  {result.engine === "openmm" && result.temperature && result.temperature.length > 0 && (
308
+ <div className="data-card p-5">
309
  <h3 className="text-sm font-semibold text-text-primary mb-1">Temperature — Thermostat Coupling</h3>
310
  <p className="text-xs text-text-muted mb-3">Instantaneous temperature (Langevin thermostat, {result.temperature_k} K target). Fluctuations around the target indicate a stable equilibrated ensemble.</p>
311
  <div className="bg-surface-1 rounded-lg p-3 h-40 flex items-end gap-px">
 
341
 
342
  {/* Radius of Gyration */}
343
  {result.radius_of_gyration && result.radius_of_gyration.length > 1 && (
344
+ <div className="data-card p-5">
345
  <h3 className="text-sm font-semibold text-text-primary mb-1">Radius of Gyration — Compactness</h3>
346
  <p className="text-xs text-text-muted mb-3">Mass-weighted size over time. Rising Rg = expanding/unfolding; stable Rg = compact, folded state.</p>
347
  <div className="bg-surface-1 rounded-lg p-3 h-40 flex items-end gap-px">
 
377
 
378
  {/* Solvent-Accessible Surface Area */}
379
  {result.sasa && result.sasa.length > 0 && (
380
+ <div className="data-card p-5">
381
  <h3 className="text-sm font-semibold text-text-primary mb-1">Solvent-Accessible Surface Area</h3>
382
  <p className="text-xs text-text-muted mb-3">Shrake-Rüger SASA with a 1.4 A probe. Decreasing SASA = compaction/burial; increasing = expansion or partial unfolding.</p>
383
  <div className="bg-surface-1 rounded-lg p-3 h-40 flex items-end gap-px">
 
413
 
414
  {/* RMSD */}
415
  {result.rmsd.length > 0 && (
416
+ <div className="data-card p-5">
417
  <h3 className="text-sm font-semibold text-text-primary mb-1">RMSD — Structural Drift</h3>
418
  <p className="text-xs text-text-muted mb-3">Root-mean-square deviation vs minimized reference. Lower = more stable.</p>
419
  <div className="bg-surface-1 rounded-lg p-3 h-40 flex items-end gap-px">
 
446
 
447
  {/* RMSF */}
448
  {result.rmsf && result.rmsf.length > 0 && (
449
+ <div className="data-card p-5">
450
  <h3 className="text-sm font-semibold text-text-primary mb-1">RMSF — Per-Residue Flexibility</h3>
451
  <p className="text-xs text-text-muted mb-3">Root-mean-square fluctuation per residue. High = flexible region, low = rigid/core.</p>
452
  <div className="bg-surface-1 rounded-lg p-3 h-40 flex items-end gap-px">
 
479
 
480
  {/* Secondary Structure */}
481
  {result.secondary_structure && (
482
+ <div className="data-card p-5">
483
  <h3 className="text-sm font-semibold text-text-primary mb-3">Secondary Structure Composition</h3>
484
  <div className="flex gap-3 mb-3">
485
  {[
 
517
 
518
  {/* Structural Metrics (BioPython fallback) */}
519
  {result.radius_of_gyration_angstrom !== undefined && (
520
+ <div className="data-card p-5">
521
  <h3 className="text-sm font-semibold text-text-primary mb-3">Structural Metrics</h3>
522
  <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
523
  <div className="bg-surface-1 rounded-lg p-3">
 
551
  )}
552
 
553
  {/* Interpretation */}
554
+ <div className="data-card p-5">
555
  <h3 className="text-sm font-semibold text-text-primary mb-3 flex items-center gap-2">
556
  <Info className="w-4 h-4 text-accent-cyan" /> Interpretation
557
  </h3>
bioai-platform/frontend/src/lib/api.ts CHANGED
@@ -596,8 +596,14 @@ export type MDSimulationResult = {
596
  secondary_structure?: { helix: number; sheet: number; coil: number };
597
  };
598
 
599
- export async function runMD(pdbId: string, mode: string = 'minimize'): Promise<{ job_id: string; status: string }> {
600
- const res = await longApi.post('/api/md/run', { pdb_id: pdbId, mode });
 
 
 
 
 
 
601
  return res.data;
602
  }
603
 
 
596
  secondary_structure?: { helix: number; sheet: number; coil: number };
597
  };
598
 
599
+ export type MDRunOptions = {
600
+ forcefield?: string;
601
+ solvent?: string;
602
+ run_length_ps?: number;
603
+ };
604
+
605
+ export async function runMD(pdbId: string, mode: string = 'minimize', options?: MDRunOptions): Promise<{ job_id: string; status: string }> {
606
+ const res = await longApi.post('/api/md/run', { pdb_id: pdbId, mode, ...options });
607
  return res.data;
608
  }
609