Samad14 commited on
Commit
2583376
·
1 Parent(s): 1f75a84

feat(md): verified force field/solvent menu (ff14SB/ff15ipq/ff19SB/amberfb15/CHARMM36 x OBC1/OBC2/GBN2) with alanine-dipeptide createSystem startup probe; explicit errors for invalid combos; dynamic frontend menu

Browse files
bioai-platform/backend/app/main.py CHANGED
@@ -198,6 +198,15 @@ async def startup():
198
  except ImportError as e:
199
  logger.warning("OpenMM not available (%s) — MD will use BioPython fallback", e)
200
 
 
 
 
 
 
 
 
 
 
201
  # Launch durable worker (in-process)
202
  from app.worker import start_worker
203
  await start_worker()
 
198
  except ImportError as e:
199
  logger.warning("OpenMM not available (%s) — MD will use BioPython fallback", e)
200
 
201
+ # Verify MD force field / solvent combinations at startup (real
202
+ # alanine-dipeptide createSystem probe). Failures never block boot.
203
+ try:
204
+ from app.tools.md_config import verify_ff_solvent_combos
205
+ combos = verify_ff_solvent_combos()
206
+ logger.info("MD force field verification: %d verified force fields", len(combos))
207
+ except Exception as e:
208
+ logger.warning("MD force field verification failed during startup: %s", e)
209
+
210
  # Launch durable worker (in-process)
211
  from app.worker import start_worker
212
  await start_worker()
bioai-platform/backend/app/routers/md.py CHANGED
@@ -20,7 +20,7 @@ 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
- 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
 
@@ -32,10 +32,26 @@ class MDJobResponse(BaseModel):
32
  error: str | None = None
33
 
34
 
 
 
 
 
 
 
 
 
35
  @router.post("/run", response_model=MDJobResponse)
36
  async def run_md(request: Request, body: MDRunRequest, user_id: str = Depends(require_user_id)):
37
  """Submit an MD simulation job (queued through the durable worker)."""
38
  from app.services.ssrf import validate_url
 
 
 
 
 
 
 
 
39
 
40
  supabase = get_client()
41
  job_id = str(uuid.uuid4())
 
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 from the verified menu (GET /api/md/forcefields)")
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
 
 
32
  error: str | None = None
33
 
34
 
35
+ @router.get("/forcefields")
36
+ async def get_md_forcefields():
37
+ """Return the force field / solvent menu (verified combos only)."""
38
+ from app.tools.md_config import get_forcefields_menu
39
+
40
+ return get_forcefields_menu()
41
+
42
+
43
  @router.post("/run", response_model=MDJobResponse)
44
  async def run_md(request: Request, body: MDRunRequest, user_id: str = Depends(require_user_id)):
45
  """Submit an MD simulation job (queued through the durable worker)."""
46
  from app.services.ssrf import validate_url
47
+ from app.tools.md_config import resolve_combo
48
+
49
+ # Reject invalid force field / solvent combinations immediately with an
50
+ # explicit error (no silent AMBER14/OBC2 fallback).
51
+ try:
52
+ resolve_combo(body.forcefield, body.solvent)
53
+ except ValueError as exc:
54
+ raise HTTPException(status_code=400, detail=str(exc))
55
 
56
  supabase = get_client()
57
  job_id = str(uuid.uuid4())
bioai-platform/backend/app/tools/md_config.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MD force field / solvent configuration with startup verification.
2
+
3
+ The exposed menu of force fields and implicit-solvent models is not a static
4
+ list: every (force field x solvent) combination is verified at import time by
5
+ running a real OpenMM ``createSystem()`` on an embedded alanine-dipeptide
6
+ structure (the canonical test system), using the exact same construction path
7
+ as the simulation engine (PDBFile -> Modeller -> addHydrogens -> createSystem
8
+ with a non-periodic 2.0 nm cutoff). Only combinations that build successfully
9
+ are exposed through ``GET /api/md/forcefields`` and accepted by the run
10
+ endpoints. An unknown or unverified combination raises an explicit ValueError
11
+ instead of silently falling back to AMBER14/OBC2.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import io
17
+ import logging
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ # User-facing force field keys -> bundled OpenMM XML force field files.
22
+ FF_XML: dict[str, str] = {
23
+ "amber14": "amber14-all.xml", # legacy all-residue AMBER14
24
+ "ff14sb": "amber14/protein.ff14SB.xml",
25
+ "ff15ipq": "amber14/protein.ff15ipq.xml",
26
+ "ff19sb": "amber19/protein.ff19SB.xml",
27
+ "amberfb15": "amberfb15.xml",
28
+ "charmm36": "charmm36.xml",
29
+ }
30
+
31
+ FF_LABELS: dict[str, str] = {
32
+ "amber14": "AMBER14 (ff14SB)",
33
+ "ff14sb": "AMBER ff14SB",
34
+ "ff15ipq": "AMBER ff15ipq",
35
+ "ff19sb": "AMBER ff19SB",
36
+ "amberfb15": "AMBER ff15 (amberfb15)",
37
+ "charmm36": "CHARMM36",
38
+ }
39
+
40
+ # Implicit-solvent (Generalized Born) models -> bundled XML files.
41
+ SOLVENT_XML: dict[str, str] = {
42
+ "obc1": "implicit/obc1.xml",
43
+ "obc2": "implicit/obc2.xml",
44
+ "gbn2": "implicit/gbn2.xml",
45
+ }
46
+
47
+ DEFAULT_FORCEFIELD = "amber14"
48
+ DEFAULT_SOLVENT = "obc2"
49
+
50
+ # Heavy-atom alanine dipeptide (ALA-ALA with C-terminal OXT) used as the
51
+ # startup verification probe. It exercises the same Modeller/addHydrogens
52
+ # construction path the real simulation uses, is fully self-contained, and
53
+ # needs no network access. Its geometry is approximate; the probe only checks
54
+ # that createSystem() builds a valid System, so this is acceptable.
55
+ _DIPEPTIDE_PDB = """\
56
+ REMARK 1 CREATED WITH OPENMM 8.5.2
57
+ CRYST1 40.960 18.650 22.520 90.00 90.77 90.00 P 1 1
58
+ ATOM 1 N ALA A 1 17.047 14.099 3.625 1.00 0.00 N
59
+ ATOM 2 CA ALA A 1 16.967 12.784 4.338 1.00 0.00 C
60
+ ATOM 3 C ALA A 1 15.685 12.755 5.133 1.00 0.00 C
61
+ ATOM 4 O ALA A 1 15.268 13.825 5.594 1.00 0.00 O
62
+ ATOM 5 CB ALA A 1 18.170 12.703 5.337 1.00 0.00 C
63
+ ATOM 6 N ALA A 2 15.115 11.555 5.265 1.00 0.00 N
64
+ ATOM 7 CA ALA A 2 13.856 11.469 6.066 1.00 0.00 C
65
+ ATOM 8 C ALA A 2 14.164 10.785 7.379 1.00 0.00 C
66
+ ATOM 9 O ALA A 2 14.993 9.862 7.443 1.00 0.00 O
67
+ ATOM 10 CB ALA A 2 12.732 10.711 5.261 1.00 0.00 C
68
+ ATOM 11 OXT ALA A 2 13.343 11.699 7.316 1.00 0.00 O
69
+ TER 11 ALA A 2
70
+ END
71
+ """
72
+
73
+ _VERIFIED: dict[str, tuple[str, ...]] | None = None
74
+ _VERIFY_ERRORS: dict[tuple[str, str], str] | None = None
75
+
76
+
77
+ def _build_dipeptide_system(forcefield: str, solvent: str) -> None:
78
+ """Run the real construction path on the dipeptide (raises on failure)."""
79
+ from openmm.app import PDBFile, ForceField, Modeller, CutoffNonPeriodic
80
+ from openmm import unit
81
+
82
+ pdb = PDBFile(io.StringIO(_DIPEPTIDE_PDB))
83
+ forcefield_xml = ForceField(FF_XML[forcefield], SOLVENT_XML[solvent])
84
+ modeller = Modeller(pdb.topology, pdb.positions)
85
+ modeller.addHydrogens(forcefield_xml)
86
+ forcefield_xml.createSystem(
87
+ modeller.topology,
88
+ nonbondedMethod=CutoffNonPeriodic,
89
+ nonbondedCutoff=2.0 * unit.nanometer,
90
+ )
91
+
92
+
93
+ def verify_ff_solvent_combos() -> dict[str, tuple[str, ...]]:
94
+ """Verify every (force field x solvent) combo with a real createSystem().
95
+
96
+ Returns a dict mapping each passing force field to the tuple of solvents
97
+ it supports. Results are cached after the first call. When OpenMM is not
98
+ installed, returns an empty mapping (MD degrades to structural analysis).
99
+ """
100
+ global _VERIFIED, _VERIFY_ERRORS
101
+ if _VERIFIED is not None:
102
+ return _VERIFIED
103
+
104
+ verified: dict[str, list[str]] = {ff: [] for ff in FF_XML}
105
+ errors: dict[tuple[str, str], str] = {}
106
+ try:
107
+ import openmm # noqa: F401
108
+ except Exception as e:
109
+ logger.warning("OpenMM unavailable — MD force field verification skipped: %s", e)
110
+ _VERIFIED = {}
111
+ _VERIFY_ERRORS = {}
112
+ return _VERIFIED
113
+
114
+ for ff in FF_XML:
115
+ for solvent in SOLVENT_XML:
116
+ try:
117
+ _build_dipeptide_system(ff, solvent)
118
+ verified[ff].append(solvent)
119
+ except Exception as exc:
120
+ errors[(ff, solvent)] = f"{type(exc).__name__}: {exc}"
121
+ logger.warning(
122
+ "MD combo %s x %s FAILED verification: %s: %s",
123
+ ff, solvent, type(exc).__name__, exc,
124
+ )
125
+ _VERIFIED = {ff: tuple(ff_solvents) for ff, ff_solvents in verified.items()}
126
+ _VERIFY_ERRORS = errors
127
+ logger.info(
128
+ "MD force field verification complete: %d force fields, combos=%s",
129
+ len(_VERIFIED), {ff: list(s) for ff, s in _VERIFIED.items()},
130
+ )
131
+ return _VERIFIED
132
+
133
+
134
+ def get_forcefields_menu() -> dict:
135
+ """Menu payload for GET /api/md/forcefields (verified combos only)."""
136
+ verified = verify_ff_solvent_combos()
137
+ return {
138
+ "forcefields": [
139
+ {"value": ff, "label": FF_LABELS.get(ff, ff)}
140
+ for ff in FF_XML
141
+ if verified.get(ff)
142
+ ],
143
+ "solvents": [{"value": s, "label": f"Implicit · {s.upper()}"} for s in SOLVENT_XML],
144
+ "combos": {ff: list(solvents) for ff, solvents in verified.items()},
145
+ "defaults": {"forcefield": DEFAULT_FORCEFIELD, "solvent": DEFAULT_SOLVENT},
146
+ "probe": {
147
+ "system": "alanine dipeptide (ALA-ALA)",
148
+ "forcefields_tested": len(FF_XML),
149
+ "solvents_tested": len(SOLVENT_XML),
150
+ },
151
+ }
152
+
153
+
154
+ def resolve_combo(forcefield: str | None, solvent: str | None) -> tuple[str, str]:
155
+ """Normalize and validate a requested (forcefield, solvent) pair.
156
+
157
+ Raises ValueError with a clear message when the force field or solvent is
158
+ unknown, or when the specific combination did not pass startup
159
+ verification. No silent fallback: an invalid request is an explicit error.
160
+ """
161
+ ff_key = (forcefield or DEFAULT_FORCEFIELD).strip().lower()
162
+ sol_key = (solvent or DEFAULT_SOLVENT).strip().lower()
163
+
164
+ if ff_key not in FF_XML:
165
+ raise ValueError(
166
+ f"Unsupported force field: {forcefield!r}. Choose from: "
167
+ + ", ".join(FF_XML)
168
+ )
169
+ if sol_key not in SOLVENT_XML:
170
+ raise ValueError(
171
+ f"Unsupported solvent model: {solvent!r}. Choose from: "
172
+ + ", ".join(SOLVENT_XML)
173
+ )
174
+
175
+ verified = verify_ff_solvent_combos()
176
+ if verified and sol_key not in verified.get(ff_key, ()):
177
+ raise ValueError(
178
+ f"Force field '{ff_key}' is not available with solvent '{sol_key}' "
179
+ f"on this deployment. Supported solvents for '{ff_key}': "
180
+ + (", ".join(verified.get(ff_key, ())) if verified.get(ff_key) else "none")
181
+ )
182
+ return ff_key, sol_key
bioai-platform/backend/app/tools/md_sim.py CHANGED
@@ -1,8 +1,10 @@
1
  """Molecular dynamics simulation using OpenMM (implicit solvent only).
2
 
3
  Scientifically accurate simulation with:
4
- - AMBER14 force field (protein parameters)
5
- - OBC2 implicit solvent (Generalized Born / Onufriev-Bashford-Case)
 
 
6
  - Hydrogen addition via OpenMM Modeller
7
  - Real Cα-atom RMSD via Kabsch optimal superposition
8
  - Per-residue RMSF (Cα) from trajectory frames
@@ -293,9 +295,10 @@ def run_simulation(
293
  mode: 'minimize', 'equilibrate', or 'production'.
294
  platform: Optional OpenMM platform name to force (e.g. 'CPU',
295
  'Reference'); None lets OpenMM pick the default.
296
- forcefield: 'amber14' (only AMBER14 protein templates are
297
- supported — any other value falls back to AMBER14).
298
- solvent: 'obc1', 'obc2', or 'gbn2' implicit-solvent XML file.
 
299
  Explicit solvent is not supported.
300
  run_length_ps: Desired production length in picoseconds
301
  (production mode only). The engine still clamps the run to
@@ -305,12 +308,19 @@ def run_simulation(
305
  Dict with energy, RMSD, RMSF, and simulation metadata.
306
 
307
  Raises:
 
 
308
  RuntimeError if PDB fetch fails or OpenMM is unavailable.
309
  """
310
  import urllib.request
311
 
312
  pdb_id = pdb_id.upper().strip()
313
 
 
 
 
 
 
314
  # Fetch PDB from RCSB
315
  pdb_url = f"https://files.rcsb.org/view/{pdb_id}.pdb"
316
  logger.info("Fetching PDB %s from %s", pdb_id, pdb_url)
@@ -485,39 +495,29 @@ def _run_openmm(
485
  from openmm.app import PDBFile, ForceField, Simulation, CutoffNonPeriodic, Modeller
486
  from openmm import unit, LangevinMiddleIntegrator, Platform
487
 
488
- # Implicit-solvent XML files OpenMM ships with the AMBER14 data set.
489
- # Explicit water/ions require a periodic box + TIP3P plus ion parameters
490
- # that are not set up here — reject (fall back) rather than fake it.
491
- _SOLVENT_XML = {
492
- "obc1": "implicit/obc1.xml",
493
- "obc2": "implicit/obc2.xml",
494
- "gbn2": "implicit/gbn2.xml",
495
- }
496
- forcefield_key = forcefield_name or "amber14"
497
- if forcefield_key != "amber14":
498
- # Only AMBER14 protein templates exist in the bundled data set.
499
- # Never silently run a "different" force field — honor the request
500
- # by falling back and recording the fact.
501
- logger.warning("Force field %r not supported — falling back to amber14", forcefield_key)
502
- forcefield_key = "amber14"
503
- solvent_key = (solvent_name or "obc2").lower()
504
- solvent_xml = _SOLVENT_XML.get(solvent_key, "implicit/obc2.xml")
505
- if solvent_key not in _SOLVENT_XML:
506
- logger.warning("Solvent %r not supported — falling back to obc2", solvent_name)
507
- solvent_key = "obc2"
508
 
509
  # Load structure
510
  pdb = PDBFile(pdb_path)
511
  # OpenMM 8.x: implicit solvent is loaded as an explicit force field file,
512
  # not via the createSystem(implicitSolvent=...) kwarg (which is rejected).
513
- forcefield = ForceField("amber14-all.xml", solvent_xml)
514
 
515
  # Keep only standard amino acids — water, ions, ligands, and nucleic acids
516
- # have no AMBER14 protein template and would crash createSystem().
517
  modeller = Modeller(pdb.topology, pdb.positions)
518
  _strip_non_standard_residues(modeller)
519
 
520
- # RCSB PDBs omit the terminal carboxylate oxygen; add it so AMBER14's
521
  # C-terminal templates can match (otherwise addHydrogens() raises).
522
  n_oxt = _add_missing_terminal_oxt(modeller)
523
  if n_oxt:
@@ -763,7 +763,7 @@ def _run_openmm(
763
  "mode": mode,
764
  "engine": "openmm",
765
  "forcefield": forcefield_key,
766
- "forcefield_detail": "amber14-all" if forcefield_key == "amber14" else forcefield_key,
767
  "implicit_solvent": solvent_key.upper(),
768
  "requested_production_ps": int(run_length_ps) if run_length_ps else None,
769
  "note": "\n".join(notes) if notes else None,
 
1
  """Molecular dynamics simulation using OpenMM (implicit solvent only).
2
 
3
  Scientifically accurate simulation with:
4
+ - Verified force field menu (AMBER14, ff14SB, ff15ipq, ff19SB, amberfb15,
5
+ CHARMM36) — every (force field x solvent) pair passed a real
6
+ alanine-dipeptide createSystem() probe at startup (see md_config)
7
+ - Implicit solvent (Generalized Born / OBC1/OBC2/GBN2)
8
  - Hydrogen addition via OpenMM Modeller
9
  - Real Cα-atom RMSD via Kabsch optimal superposition
10
  - Per-residue RMSF (Cα) from trajectory frames
 
295
  mode: 'minimize', 'equilibrate', or 'production'.
296
  platform: Optional OpenMM platform name to force (e.g. 'CPU',
297
  'Reference'); None lets OpenMM pick the default.
298
+ forcefield: Force field key from the verified menu ('amber14',
299
+ 'ff14sb', 'ff15ipq', 'ff19sb', 'amberfb15', 'charmm36').
300
+ An unknown or unverified combination raises ValueError.
301
+ solvent: 'obc1', 'obc2', or 'gbn2' implicit-solvent model.
302
  Explicit solvent is not supported.
303
  run_length_ps: Desired production length in picoseconds
304
  (production mode only). The engine still clamps the run to
 
308
  Dict with energy, RMSD, RMSF, and simulation metadata.
309
 
310
  Raises:
311
+ ValueError if the (forcefield, solvent) combination is unknown or did
312
+ not pass startup verification.
313
  RuntimeError if PDB fetch fails or OpenMM is unavailable.
314
  """
315
  import urllib.request
316
 
317
  pdb_id = pdb_id.upper().strip()
318
 
319
+ # Validate the force field / solvent pair up front so an invalid request
320
+ # fails fast with an explicit error (no silent AMBER14/OBC2 fallback).
321
+ from app.tools.md_config import resolve_combo
322
+ resolve_combo(forcefield, solvent)
323
+
324
  # Fetch PDB from RCSB
325
  pdb_url = f"https://files.rcsb.org/view/{pdb_id}.pdb"
326
  logger.info("Fetching PDB %s from %s", pdb_id, pdb_url)
 
495
  from openmm.app import PDBFile, ForceField, Simulation, CutoffNonPeriodic, Modeller
496
  from openmm import unit, LangevinMiddleIntegrator, Platform
497
 
498
+ from app.tools.md_config import FF_XML, SOLVENT_XML, resolve_combo
499
+
500
+ # Resolve and validate the requested (force field, solvent) pair. Unknown
501
+ # or unverified combinations raise ValueError with an explicit message —
502
+ # there is deliberately no silent AMBER14/OBC2 fallback.
503
+ forcefield_key, solvent_key = resolve_combo(forcefield_name, solvent_name)
504
+ forcefield_xml = FF_XML[forcefield_key]
505
+ solvent_xml = SOLVENT_XML[solvent_key]
506
+ logger.info("MD config: forcefield=%s (%s) solvent=%s (%s)",
507
+ forcefield_key, forcefield_xml, solvent_key, solvent_xml)
 
 
 
 
 
 
 
 
 
 
508
 
509
  # Load structure
510
  pdb = PDBFile(pdb_path)
511
  # OpenMM 8.x: implicit solvent is loaded as an explicit force field file,
512
  # not via the createSystem(implicitSolvent=...) kwarg (which is rejected).
513
+ forcefield = ForceField(forcefield_xml, solvent_xml)
514
 
515
  # Keep only standard amino acids — water, ions, ligands, and nucleic acids
516
+ # have no protein template and would crash createSystem().
517
  modeller = Modeller(pdb.topology, pdb.positions)
518
  _strip_non_standard_residues(modeller)
519
 
520
+ # RCSB PDBs omit the terminal carboxylate oxygen; add it so the
521
  # C-terminal templates can match (otherwise addHydrogens() raises).
522
  n_oxt = _add_missing_terminal_oxt(modeller)
523
  if n_oxt:
 
763
  "mode": mode,
764
  "engine": "openmm",
765
  "forcefield": forcefield_key,
766
+ "forcefield_detail": forcefield_xml if forcefield_key == "amber14" else forcefield_key,
767
  "implicit_solvent": solvent_key.upper(),
768
  "requested_production_ps": int(run_length_ps) if run_length_ps else None,
769
  "note": "\n".join(notes) if notes else None,
bioai-platform/backend/tests/test_md_config.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Unit tests for the MD force field / solvent configuration menu.
3
+
4
+ Covers the parts that do not require OpenMM (fast, always run):
5
+ - FF_XML / SOLVENT_XML menus contain the documented entries
6
+ - get_forcefields_menu() shape and that it only exposes verified combos
7
+ - resolve_combo() normalization and explicit ValueError for unknown force
8
+ fields, unknown solvents, and (when OpenMM is present) unverified pairs
9
+
10
+ The heavy per-combo createSystem() probe is exercised once (skip-if-no-OpenMM)
11
+ to confirm the startup verification itself runs end to end.
12
+ """
13
+
14
+ import pytest
15
+
16
+ from app.tools.md_config import (
17
+ FF_XML,
18
+ SOLVENT_XML,
19
+ DEFAULT_FORCEFIELD,
20
+ DEFAULT_SOLVENT,
21
+ get_forcefields_menu,
22
+ resolve_combo,
23
+ verify_ff_solvent_combos,
24
+ )
25
+
26
+
27
+ class TestMenus:
28
+ def test_forcefield_menu_entries(self):
29
+ assert FF_XML == {
30
+ "amber14": "amber14-all.xml",
31
+ "ff14sb": "amber14/protein.ff14SB.xml",
32
+ "ff15ipq": "amber14/protein.ff15ipq.xml",
33
+ "ff19sb": "amber19/protein.ff19SB.xml",
34
+ "amberfb15": "amberfb15.xml",
35
+ "charmm36": "charmm36.xml",
36
+ }
37
+
38
+ def test_solvent_menu_entries(self):
39
+ assert SOLVENT_XML == {
40
+ "obc1": "implicit/obc1.xml",
41
+ "obc2": "implicit/obc2.xml",
42
+ "gbn2": "implicit/gbn2.xml",
43
+ }
44
+
45
+ def test_defaults_are_amber14_obc2(self):
46
+ assert DEFAULT_FORCEFIELD == "amber14"
47
+ assert DEFAULT_SOLVENT == "obc2"
48
+
49
+
50
+ class TestGetForcefieldsMenu:
51
+ def test_menu_shape(self):
52
+ menu = get_forcefields_menu()
53
+ assert set(menu) >= {"forcefields", "solvents", "combos", "defaults"}
54
+ assert isinstance(menu["forcefields"], list)
55
+ assert isinstance(menu["solvents"], list)
56
+ assert menu["defaults"] == {"forcefield": "amber14", "solvent": "obc2"}
57
+ # every listed force field has at least one verified solvent
58
+ combos = menu["combos"]
59
+ for ff in menu["forcefields"]:
60
+ assert ff["value"] in combos
61
+ assert combos[ff["value"]]
62
+
63
+ def test_combos_only_contain_known_solvents(self):
64
+ menu = get_forcefields_menu()
65
+ for ff, solvents in menu["combos"].items():
66
+ assert ff in FF_XML
67
+ assert set(solvents) <= set(SOLVENT_XML)
68
+
69
+
70
+ class TestResolveCombo:
71
+ def test_defaults(self):
72
+ assert resolve_combo(None, None) == ("amber14", "obc2")
73
+
74
+ def test_normalization(self):
75
+ assert resolve_combo(" ff14SB ", "GBN2") == ("ff14sb", "gbn2")
76
+
77
+ def test_unknown_forcefield_raises(self):
78
+ with pytest.raises(ValueError, match="Unsupported force field"):
79
+ resolve_combo("opls", "obc2")
80
+
81
+ def test_unknown_solvent_raises(self):
82
+ with pytest.raises(ValueError, match="Unsupported solvent"):
83
+ resolve_combo("ff14sb", "explicit")
84
+
85
+ def test_unverified_combo_raises(self):
86
+ # Simulate a deployment where only amber14 passed verification.
87
+ verified = verify_ff_solvent_combos()
88
+ if not verified:
89
+ pytest.skip("OpenMM unavailable — verification empty")
90
+ unverified = [ff for ff in FF_XML if ff not in verified]
91
+ if not unverified:
92
+ pytest.skip("all force fields verified — nothing unverified to test")
93
+ with pytest.raises(ValueError, match="not available"):
94
+ resolve_combo(unverified[0], "obc2")
95
+
96
+
97
+ class TestStartupVerification:
98
+ def test_verification_runs_end_to_end(self):
99
+ verified = verify_ff_solvent_combos()
100
+ if not verified:
101
+ pytest.importorskip("openmm")
102
+ # Every entry maps to a valid force field with known solvents.
103
+ assert verified == {ff: tuple(s) for ff, s in verified.items()}
104
+ for ff, solvents in verified.items():
105
+ assert ff in FF_XML
106
+ assert set(solvents) <= set(SOLVENT_XML)
bioai-platform/frontend/src/app/(dashboard)/analyze/md/page.tsx CHANGED
@@ -5,7 +5,7 @@ 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, ResultsReadyBanner } from "@/components/ui";
10
 
11
  const MODES = [
@@ -14,11 +14,11 @@ const MODES = [
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" },
@@ -32,6 +32,9 @@ export default function MDPage() {
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>("");
@@ -82,6 +85,25 @@ export default function MDPage() {
82
  }
83
  }, []);
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  const handleSubmit = async () => {
86
  if (!pdbId.trim()) return;
87
  setLoading(true);
@@ -108,7 +130,7 @@ export default function MDPage() {
108
 
109
  <motion.div variants={fadeUp} initial={{ y: 24 }} animate="show" className="mb-8">
110
  <h1 className="text-2xl font-bold text-text-primary mb-1">MD Simulation</h1>
111
- <p className="text-sm text-text-secondary">Implicit solvent molecular dynamics using OpenMM/BioPython. AMBER14 force field, OBC2 generalized Born solvent model.</p>
112
  </motion.div>
113
 
114
  <motion.div variants={fadeUp} initial={{ y: 24 }} animate="show">
@@ -129,11 +151,11 @@ export default function MDPage() {
129
  <p className="text-xs font-semibold uppercase tracking-wide text-text-muted mb-3">Simulation Parameters</p>
130
 
131
  <label className="block text-xs text-text-secondary mb-1.5">Force Field</label>
132
- <ClaySegmented options={FORCEFIELDS} value={forcefield} onChange={setForcefield} className="mb-4" />
133
 
134
  <label className="block text-xs text-text-secondary mb-1.5">Solvent Model</label>
135
- <ClaySegmented options={SOLVENTS} value={solvent} onChange={setSolvent} />
136
- <p className="text-xs text-text-muted mt-2 mb-4">Implicit (generalized Born) solvent only. Explicit water/ions aren't supported yet.</p>
137
 
138
  <label className="block text-xs text-text-secondary mb-1.5">Production Length</label>
139
  <ClaySlider value={runLengthPs} min={50} max={1000} step={25} unit="ps"
 
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, getMDForceFields, type MDSimulationResult, type MDForceFieldsMenu } from "@/lib/api";
9
  import { ClaySegmented, ClaySlider, CriticalButton, FlatInput, ResultsReadyBanner } from "@/components/ui";
10
 
11
  const MODES = [
 
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 FALLBACK_FORCEFIELDS = [
18
  { value: "amber14", label: "AMBER14 (ff14SB)" },
19
  ];
20
 
21
+ const FALLBACK_SOLVENTS = [
22
  { value: "obc2", label: "Implicit · OBC2" },
23
  { value: "gbn2", label: "Implicit · GBN2" },
24
  { value: "obc1", label: "Implicit · OBC1" },
 
32
  const [mode, setMode] = useState("minimize");
33
  const [forcefield, setForcefield] = useState("amber14");
34
  const [solvent, setSolvent] = useState("obc2");
35
+ const [forcefields, setForcefields] = useState(FALLBACK_FORCEFIELDS);
36
+ const [solvents, setSolvents] = useState(FALLBACK_SOLVENTS);
37
+ const [menuNote, setMenuNote] = useState("");
38
  const [runLengthPs, setRunLengthPs] = useState(250);
39
  const [jobId, setJobId] = useState<string | null>(null);
40
  const [status, setStatus] = useState<string>("");
 
85
  }
86
  }, []);
87
 
88
+ useEffect(() => {
89
+ let active = true;
90
+ getMDForceFields()
91
+ .then((menu: MDForceFieldsMenu) => {
92
+ if (!active) return;
93
+ const ffs = menu.forcefields.length ? menu.forcefields : FALLBACK_FORCEFIELDS;
94
+ const sols = menu.solvents.length ? menu.solvents : FALLBACK_SOLVENTS;
95
+ setForcefields(ffs);
96
+ setSolvents(sols);
97
+ setForcefield(menu.defaults?.forcefield ?? "amber14");
98
+ setSolvent(menu.defaults?.solvent ?? "obc2");
99
+ setMenuNote(menu.probe
100
+ ? `Force field × solvent pairs verified at startup with a ${menu.probe.system} createSystem() probe.`
101
+ : "");
102
+ })
103
+ .catch(() => { /* keep fallback menus */ });
104
+ return () => { active = false; };
105
+ }, []);
106
+
107
  const handleSubmit = async () => {
108
  if (!pdbId.trim()) return;
109
  setLoading(true);
 
130
 
131
  <motion.div variants={fadeUp} initial={{ y: 24 }} animate="show" className="mb-8">
132
  <h1 className="text-2xl font-bold text-text-primary mb-1">MD Simulation</h1>
133
+ <p className="text-sm text-text-secondary">Implicit solvent molecular dynamics using OpenMM/BioPython. Multiple force fields (AMBER14, ff14SB, ff15ipq, ff19SB, amberfb15, CHARMM36) with OBC1/OBC2/GBN2 generalized Born solvent models.</p>
134
  </motion.div>
135
 
136
  <motion.div variants={fadeUp} initial={{ y: 24 }} animate="show">
 
151
  <p className="text-xs font-semibold uppercase tracking-wide text-text-muted mb-3">Simulation Parameters</p>
152
 
153
  <label className="block text-xs text-text-secondary mb-1.5">Force Field</label>
154
+ <ClaySegmented options={forcefields} value={forcefield} onChange={setForcefield} className="mb-4 flex-wrap" />
155
 
156
  <label className="block text-xs text-text-secondary mb-1.5">Solvent Model</label>
157
+ <ClaySegmented options={solvents} value={solvent} onChange={setSolvent} />
158
+ <p className="text-xs text-text-muted mt-2 mb-4">{menuNote || "Implicit (generalized Born) solvent only. Explicit water/ions aren't supported yet."}</p>
159
 
160
  <label className="block text-xs text-text-secondary mb-1.5">Production Length</label>
161
  <ClaySlider value={runLengthPs} min={50} max={1000} step={25} unit="ps"
bioai-platform/frontend/src/lib/api.ts CHANGED
@@ -602,6 +602,19 @@ export type MDRunOptions = {
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;
 
602
  run_length_ps?: number;
603
  };
604
 
605
+ export type MDForceFieldsMenu = {
606
+ forcefields: { value: string; label: string }[];
607
+ solvents: { value: string; label: string }[];
608
+ combos: Record<string, string[]>;
609
+ defaults: { forcefield: string; solvent: string };
610
+ probe?: { system: string; forcefields_tested: number; solvents_tested: number };
611
+ };
612
+
613
+ export async function getMDForceFields(): Promise<MDForceFieldsMenu> {
614
+ const res = await api.get('/api/md/forcefields');
615
+ return res.data;
616
+ }
617
+
618
  export async function runMD(pdbId: string, mode: string = 'minimize', options?: MDRunOptions): Promise<{ job_id: string; status: string }> {
619
  const res = await longApi.post('/api/md/run', { pdb_id: pdbId, mode, ...options });
620
  return res.data;