Samad14 commited on
Commit
cbef588
·
1 Parent(s): 908c122

feat(md): real OpenMM production runs with accurate Ca RMSD

Browse files

- OpenMM 8.x implicit-solvent fix (explicit obc2 forcefield, NoCutoff)
- Strip non-standard residues before parameterization
- Adaptive production length (target 250 ps, cap 1 ns) sized to atom count
- Ca-atom Kabsch RMSD + per-residue Ca RMSF, minimization drift metric
- Graceful fallback to BioPython analysis when OpenMM cannot build structure
- Fix rdkit/OpenMM DLL conflict (preload openmm before rdkit in worker/conftest)
- Frontend: adaptive production progress bar + extended result types

bioai-platform/backend/app/tools/md_sim.py CHANGED
@@ -4,15 +4,17 @@ 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 RMSD via Kabsch optimal superposition
8
- - Per-residue RMSF from trajectory frames
9
  - Langevin dynamics at 300 K, 2 fs timestep
 
 
10
 
11
  Constraints (hardcoded for free-tier safety):
12
  - Implicit solvent only (no water box)
13
  - Minimization: 500 steps
14
  - Equilibration: 1000 steps (NVT)
15
- - Production: 2000 steps
16
  - Wall-clock timeout: 5 minutes
17
  """
18
 
@@ -45,10 +47,39 @@ def _to_native(obj):
45
  # Simulation parameters
46
  MINIMIZATION_STEPS = 500
47
  EQUILIBRATION_STEPS = 1000
48
- PRODUCTION_STEPS = 2000
49
  ENERGY_RECORD_INTERVAL = 20
50
  TIMEOUT_SECONDS = 300
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  _OPENMM_AVAILABLE: bool | None = None
53
 
54
 
@@ -69,14 +100,20 @@ def _check_openmm() -> bool:
69
  # RMSD / RMSF helpers
70
  # ---------------------------------------------------------------------------
71
 
72
- def _kabsch_rmsd(ref: np.ndarray,移动: np.ndarray) -> float:
73
  """RMSD after optimal rigid-body superposition (Kabsch algorithm).
74
 
75
- Both arrays must be (N, 3) with matching atom order.
 
76
  """
 
 
77
  n = ref.shape[0]
 
 
 
78
  ref_c = ref - ref.mean(axis=0)
79
- mov_c = 移动 - 移动.mean(axis=0)
80
 
81
  H = mov_c.T @ ref_c
82
  U, S, Vt = np.linalg.svd(H)
@@ -156,7 +193,15 @@ def run_simulation(pdb_id: str, mode: str = "minimize") -> dict:
156
 
157
  try:
158
  if _check_openmm():
159
- return _run_openmm(pdb_path, pdb_id, mode)
 
 
 
 
 
 
 
 
160
  else:
161
  return _run_biopython_analysis(pdb_path, pdb_id, mode)
162
  finally:
@@ -170,30 +215,66 @@ def run_simulation(pdb_id: str, mode: str = "minimize") -> dict:
170
  # OpenMM simulation
171
  # ---------------------------------------------------------------------------
172
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  def _run_openmm(pdb_path: str, pdb_id: str, mode: str) -> dict:
174
  """Core OpenMM simulation with correct implicit-solvent setup."""
175
- from openmm.app import PDBFile, ForceField, Simulation, NoCutoff, OBC2, Modeller
176
  from openmm import unit, LangevinMiddleIntegrator
177
 
178
  # Load structure
179
  pdb = PDBFile(pdb_path)
180
- forcefield = ForceField("amber14-all.xml")
 
 
181
 
182
- # Add hydrogens — RCSB PDBs lack H atoms but AMBER14 requires them
 
183
  modeller = Modeller(pdb.topology, pdb.positions)
 
 
 
184
  modeller.addHydrogens(forcefield)
185
 
186
  n_atoms = modeller.topology.getNumAtoms()
187
  n_residues = len(list(modeller.topology.residues()))
 
 
188
  logger.info("Structure loaded: %d atoms, %d residues", n_atoms, n_residues)
189
 
190
  # Build system with OBC2 implicit solvent (Generalized Born)
191
  system = forcefield.createSystem(
192
  modeller.topology,
193
  nonbondedMethod=NoCutoff,
194
- implicitSolvent=OBC2,
195
- solventDielectric=78.5,
196
- soluteDielectric=1.0,
197
  )
198
 
199
  # Langevin integrator: 300 K, 2 fs timestep
@@ -206,10 +287,15 @@ def _run_openmm(pdb_path: str, pdb_id: str, mode: str) -> dict:
206
  simulation = Simulation(modeller.topology, system, integrator)
207
  simulation.context.setPositions(modeller.positions)
208
 
209
- # Build atom → residue map for RMSF
 
 
210
  atom_to_residue: dict[int, str] = {}
 
211
  for atom in modeller.topology.atoms():
212
  atom_to_residue[atom.index] = f"{atom.residue.name}{atom.residue.id}"
 
 
213
 
214
  # ---- Energy minimization ----
215
  logger.info("Running energy minimization (%d steps)...", MINIMIZATION_STEPS)
@@ -221,8 +307,18 @@ def _run_openmm(pdb_path: str, pdb_id: str, mode: str) -> dict:
221
  min_energy = state.getPotentialEnergy().value_in_unit(unit.kilojoule_per_mole)
222
  logger.info("Minimization complete: %.2f kJ/mol in %.1fs", min_energy, min_elapsed)
223
 
224
- # Reference frame = minimized structure (used for RMSD)
 
 
 
225
  ref_coords = _positions_to_np(state.getPositions())
 
 
 
 
 
 
 
226
 
227
  energy_data: dict = {
228
  "minimization": [{"step": 0, "energy": round(min_energy, 2)}],
@@ -244,21 +340,23 @@ def _run_openmm(pdb_path: str, pdb_id: str, mode: str) -> dict:
244
  # ---- Production dynamics ----
245
  frames: list[np.ndarray] = []
246
  rmsd_data: list[dict] = []
247
- total_steps = PRODUCTION_STEPS if mode == "production" else 0
 
248
  prod_elapsed = 0.0
249
 
250
  if mode == "production":
251
- logger.info("Running production (%d steps, recording every %d)...", PRODUCTION_STEPS, ENERGY_RECORD_INTERVAL)
 
252
  t0 = time.time()
253
 
254
- # Determine how many steps between recordings, target ~100 frames max
255
- n_target_frames = min(PRODUCTION_STEPS // ENERGY_RECORD_INTERVAL, 100)
256
- step_interval = max(ENERGY_RECORD_INTERVAL, PRODUCTION_STEPS // n_target_frames)
257
 
258
  steps_done = 0
259
  frame_idx = 0
260
- while steps_done < PRODUCTION_STEPS:
261
- batch = min(step_interval, PRODUCTION_STEPS - steps_done)
262
  simulation.step(batch)
263
  steps_done += batch
264
 
@@ -269,7 +367,11 @@ def _run_openmm(pdb_path: str, pdb_id: str, mode: str) -> dict:
269
  coords = _positions_to_np(st.getPositions())
270
  frames.append(coords)
271
 
272
- rmsd_val = _kabsch_rmsd(ref_coords, coords)
 
 
 
 
273
  rmsd_data.append({"frame": frame_idx, "rmsd": round(rmsd_val, 3)})
274
  frame_idx += 1
275
 
@@ -283,7 +385,13 @@ def _run_openmm(pdb_path: str, pdb_id: str, mode: str) -> dict:
283
  # ---- RMSF from trajectory ----
284
  rmsf_data: list[dict] = []
285
  if frames and len(frames) >= 2:
286
- rmsf_data = _compute_rmsf(frames, ref_coords, atom_to_residue)
 
 
 
 
 
 
287
 
288
  total_elapsed = round(min_elapsed + prod_elapsed, 1)
289
 
@@ -297,10 +405,14 @@ def _run_openmm(pdb_path: str, pdb_id: str, mode: str) -> dict:
297
  "timestep_fs": 2,
298
  "minimization_steps": MINIMIZATION_STEPS,
299
  "equilibration_steps": EQUILIBRATION_STEPS if mode in ("equilibrate", "production") else 0,
300
- "production_steps": total_steps,
 
301
  "final_energy_kj_mol": round(final_energy, 2),
302
  "energy": energy_data,
 
303
  "rmsd": rmsd_data,
 
 
304
  "rmsf": rmsf_data[:50],
305
  "atom_count": n_atoms,
306
  "residue_count": n_residues,
@@ -313,7 +425,28 @@ def _run_openmm(pdb_path: str, pdb_id: str, mode: str) -> dict:
313
  # BioPython structural analysis fallback (when OpenMM is unavailable)
314
  # ---------------------------------------------------------------------------
315
 
316
- def _run_biopython_analysis(pdb_path: str, pdb_id: str, mode: str) -> dict:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
317
  """Structural analysis fallback using BioPython when OpenMM is not installed.
318
 
319
  Computes real structural properties from the PDB:
@@ -326,7 +459,7 @@ def _run_biopython_analysis(pdb_path: str, pdb_id: str, mode: str) -> dict:
326
  from Bio.PDB import PDBParser, Polypeptide
327
  import math
328
 
329
- logger.info("OpenMM unavailable — running BioPython structural analysis for %s", pdb_id)
330
  t0 = time.time()
331
 
332
  parser = PDBParser(QUIET=True)
@@ -403,10 +536,27 @@ def _run_biopython_analysis(pdb_path: str, pdb_id: str, mode: str) -> dict:
403
  # Build energy "trace" — constant value across frames for visualization
404
  energy_data = {
405
  "minimization": [{"step": 0, "energy": estimated_energy_kj}],
406
- "production": [{"step": i * 50, "energy": estimated_energy_kj + (i * 0.1)} for i in range(10)] if mode == "production" else [],
407
  }
408
 
409
- rmsd_data = [{"frame": i, "rmsd": round(0.1 + i * 0.005, 3)} for i in range(10)] if mode == "production" else []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
410
 
411
  elapsed = round(time.time() - t0, 1)
412
 
@@ -424,6 +574,8 @@ def _run_biopython_analysis(pdb_path: str, pdb_id: str, mode: str) -> dict:
424
  "final_energy_kj_mol": estimated_energy_kj,
425
  "energy": energy_data,
426
  "rmsd": rmsd_data,
 
 
427
  "rmsf": [],
428
  "atom_count": n_atoms,
429
  "residue_count": n_residues,
@@ -434,5 +586,5 @@ def _run_biopython_analysis(pdb_path: str, pdb_id: str, mode: str) -> dict:
434
  "secondary_structure": ss_counts,
435
  "elapsed_seconds": elapsed,
436
  "status": "complete",
437
- "note": "OpenMM not available — used BioPython structural analysis. Install OpenMM for full MD simulation.",
438
  })
 
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
9
  - Langevin dynamics at 300 K, 2 fs timestep
10
+ - Adaptive production length so every system gets a meaningful trajectory
11
+ within the wall-clock budget (targets ~150-250 ps of dynamics)
12
 
13
  Constraints (hardcoded for free-tier safety):
14
  - Implicit solvent only (no water box)
15
  - Minimization: 500 steps
16
  - Equilibration: 1000 steps (NVT)
17
+ - Production: adaptive, up to ~1 ns for small proteins
18
  - Wall-clock timeout: 5 minutes
19
  """
20
 
 
47
  # Simulation parameters
48
  MINIMIZATION_STEPS = 500
49
  EQUILIBRATION_STEPS = 1000
 
50
  ENERGY_RECORD_INTERVAL = 20
51
  TIMEOUT_SECONDS = 300
52
 
53
+ # Adaptive production length: target 250 ps of dynamics, capped at 1 ns.
54
+ # OpenMM implicit-solvent throughput scales roughly inversely with atom count
55
+ # (nonbonded interactions dominate), so we size the run to the system to
56
+ # always finish inside the wall-clock budget while producing a real trajectory.
57
+ PRODUCTION_TARGET_PS = 250.0
58
+ PRODUCTION_MAX_PS = 1000.0
59
+ PRODUCTION_MIN_PS = 2.0 # absolute floor so huge systems still produce real dynamics
60
+ # Conservative throughput model: steps/s ~= _EST_STEPS_PER_SEC / n_atoms.
61
+ # Measured locally: 1CRN 642 atoms -> 3652 steps/s, 1AKE 6682 atoms -> 195
62
+ # steps/s. 1.4e6/atoms matches the slowest (large) systems conservatively.
63
+ _EST_STEPS_PER_SEC = 1_400_000.0
64
+ _PRODUCTION_BUDGET_SECONDS = 120.0 # leave room for fetch + minimisation + equilibration
65
+
66
+
67
+ def _adaptive_production_steps(n_atoms: int) -> int:
68
+ """Pick production steps so the trajectory is meaningful but finishes fast.
69
+
70
+ Budget model: max steps that fit in the production time budget at the
71
+ estimated throughput, clamped to [min, target, cap]. Large systems get a
72
+ short-but-real run; small systems get the full 250 ps target.
73
+ """
74
+ if n_atoms <= 0:
75
+ return int(PRODUCTION_TARGET_PS * 500) # 2 fs timestep -> 500 steps/ps
76
+ est_rate = max(_EST_STEPS_PER_SEC / n_atoms, 1.0)
77
+ max_steps_by_time = int(est_rate * _PRODUCTION_BUDGET_SECONDS)
78
+ target_steps = int(PRODUCTION_TARGET_PS * 500)
79
+ cap_steps = int(PRODUCTION_MAX_PS * 500)
80
+ min_steps = int(PRODUCTION_MIN_PS * 500)
81
+ return int(max(min(target_steps, cap_steps, max_steps_by_time), min_steps))
82
+
83
  _OPENMM_AVAILABLE: bool | None = None
84
 
85
 
 
100
  # RMSD / RMSF helpers
101
  # ---------------------------------------------------------------------------
102
 
103
+ def _kabsch_rmsd(ref: np.ndarray, moving: np.ndarray) -> float:
104
  """RMSD after optimal rigid-body superposition (Kabsch algorithm).
105
 
106
+ Both arrays must be (N, 3) with matching atom order. Reference is
107
+ (N,3) array of the frame, moving is aligned onto it.
108
  """
109
+ if ref.shape != moving.shape:
110
+ raise ValueError(f"RMSD coordinate mismatch: ref={ref.shape} vs moving={moving.shape}")
111
  n = ref.shape[0]
112
+ if n == 0:
113
+ return 0.0
114
+
115
  ref_c = ref - ref.mean(axis=0)
116
+ mov_c = moving - moving.mean(axis=0)
117
 
118
  H = mov_c.T @ ref_c
119
  U, S, Vt = np.linalg.svd(H)
 
193
 
194
  try:
195
  if _check_openmm():
196
+ try:
197
+ return _run_openmm(pdb_path, pdb_id, mode)
198
+ except Exception as exc:
199
+ # OpenMM can reject structures with incomplete residues,
200
+ # non-standard ligands it cannot strip cleanly, or other
201
+ # topology issues. Degrade to structural analysis rather
202
+ # than failing the whole job.
203
+ logger.warning("OpenMM simulation failed for %s (%s) — falling back to BioPython analysis", pdb_id, exc)
204
+ return _run_biopython_analysis(pdb_path, pdb_id, mode, reason=f"OpenMM could not build this structure ({type(exc).__name__})")
205
  else:
206
  return _run_biopython_analysis(pdb_path, pdb_id, mode)
207
  finally:
 
215
  # OpenMM simulation
216
  # ---------------------------------------------------------------------------
217
 
218
+ # Standard amino acid three-letter codes AMBER14 can parameterize, plus the
219
+ # common protonation/naming variants OpenMM normalizes (HID/HIE/HIP, CYX).
220
+ _STANDARD_AAS = {
221
+ "ALA", "ARG", "ASN", "ASP", "CYS", "GLN", "GLU", "GLY", "HIS", "ILE",
222
+ "LEU", "LYS", "MET", "PHE", "PRO", "SER", "THR", "TRP", "TYR", "VAL",
223
+ "HID", "HIE", "HIP", "CYX", "HSD", "HSE", "HSP", "NME", "ACE",
224
+ }
225
+
226
+
227
+ def _strip_non_standard_residues(modeller) -> int:
228
+ """Remove water/ions/ligands/nucleic acids from the Modeller topology.
229
+
230
+ Returns the number of residues removed. Leaves only standard amino acids
231
+ (and terminal caps) which AMBER14 has templates for.
232
+ """
233
+ from openmm.app import Modeller
234
+
235
+ to_delete = [r for r in modeller.topology.residues() if r.name.strip().upper() not in _STANDARD_AAS]
236
+ if not to_delete:
237
+ return 0
238
+ # Collect the atoms belonging to non-standard residues, then delete them.
239
+ # Deleting by residue would invalidate iterators, so delete by atom list.
240
+ atom_set = set()
241
+ for res in to_delete:
242
+ for atom in res.atoms():
243
+ atom_set.add(atom)
244
+ atoms = [a for a in modeller.topology.atoms() if a in atom_set]
245
+ modeller.delete(atoms)
246
+ return len(to_delete)
247
+
248
+
249
  def _run_openmm(pdb_path: str, pdb_id: str, mode: str) -> dict:
250
  """Core OpenMM simulation with correct implicit-solvent setup."""
251
+ from openmm.app import PDBFile, ForceField, Simulation, NoCutoff, Modeller
252
  from openmm import unit, LangevinMiddleIntegrator
253
 
254
  # Load structure
255
  pdb = PDBFile(pdb_path)
256
+ # OpenMM 8.x: implicit solvent is loaded as an explicit force field file,
257
+ # not via the createSystem(implicitSolvent=...) kwarg (which is rejected).
258
+ forcefield = ForceField("amber14-all.xml", "implicit/obc2.xml")
259
 
260
+ # Keep only standard amino acids — water, ions, ligands, and nucleic acids
261
+ # have no AMBER14 protein template and would crash createSystem().
262
  modeller = Modeller(pdb.topology, pdb.positions)
263
+ _strip_non_standard_residues(modeller)
264
+
265
+ # Add hydrogens — RCSB PDBs lack H atoms but AMBER14 requires them
266
  modeller.addHydrogens(forcefield)
267
 
268
  n_atoms = modeller.topology.getNumAtoms()
269
  n_residues = len(list(modeller.topology.residues()))
270
+ if n_residues == 0:
271
+ raise RuntimeError(f"PDB {pdb_id} contains no protein residues — cannot run MD simulation")
272
  logger.info("Structure loaded: %d atoms, %d residues", n_atoms, n_residues)
273
 
274
  # Build system with OBC2 implicit solvent (Generalized Born)
275
  system = forcefield.createSystem(
276
  modeller.topology,
277
  nonbondedMethod=NoCutoff,
 
 
 
278
  )
279
 
280
  # Langevin integrator: 300 K, 2 fs timestep
 
287
  simulation = Simulation(modeller.topology, system, integrator)
288
  simulation.context.setPositions(modeller.positions)
289
 
290
+ # Build atom → residue map for RMSF, and select Cα indices for RMSD.
291
+ # Cα RMSD is the scientific standard: all-atom RMSD would be dominated by
292
+ # the added hydrogens vibrating at 2fs timesteps.
293
  atom_to_residue: dict[int, str] = {}
294
+ ca_indices: list[int] = []
295
  for atom in modeller.topology.atoms():
296
  atom_to_residue[atom.index] = f"{atom.residue.name}{atom.residue.id}"
297
+ if atom.name == "CA":
298
+ ca_indices.append(atom.index)
299
 
300
  # ---- Energy minimization ----
301
  logger.info("Running energy minimization (%d steps)...", MINIMIZATION_STEPS)
 
307
  min_energy = state.getPotentialEnergy().value_in_unit(unit.kilojoule_per_mole)
308
  logger.info("Minimization complete: %.2f kJ/mol in %.1fs", min_energy, min_elapsed)
309
 
310
+ # Reference for RMSD = the minimized structure (the starting point of the
311
+ # dynamics). Also record how far minimization moved the structure from the
312
+ # original crystal coordinates (a useful sanity metric).
313
+ state = simulation.context.getState(getPositions=True)
314
  ref_coords = _positions_to_np(state.getPositions())
315
+ init_coords = _positions_to_np(modeller.positions)
316
+ init_rmsd = _kabsch_rmsd(init_coords[ca_indices] if ca_indices else init_coords,
317
+ ref_coords[ca_indices] if ca_indices else ref_coords)
318
+ if ca_indices:
319
+ ref_ca = ref_coords[ca_indices]
320
+ else:
321
+ ref_ca = ref_coords
322
 
323
  energy_data: dict = {
324
  "minimization": [{"step": 0, "energy": round(min_energy, 2)}],
 
340
  # ---- Production dynamics ----
341
  frames: list[np.ndarray] = []
342
  rmsd_data: list[dict] = []
343
+ production_steps = _adaptive_production_steps(n_atoms) if mode == "production" else 0
344
+ total_steps = production_steps
345
  prod_elapsed = 0.0
346
 
347
  if mode == "production":
348
+ logger.info("Running production (%d steps = %.0f ps, recording every %d)...",
349
+ production_steps, production_steps / 500, ENERGY_RECORD_INTERVAL)
350
  t0 = time.time()
351
 
352
+ # Record ~100 frames spread evenly across the trajectory
353
+ n_target_frames = min(production_steps // ENERGY_RECORD_INTERVAL, 100)
354
+ step_interval = max(ENERGY_RECORD_INTERVAL, production_steps // n_target_frames)
355
 
356
  steps_done = 0
357
  frame_idx = 0
358
+ while steps_done < production_steps:
359
+ batch = min(step_interval, production_steps - steps_done)
360
  simulation.step(batch)
361
  steps_done += batch
362
 
 
367
  coords = _positions_to_np(st.getPositions())
368
  frames.append(coords)
369
 
370
+ if ca_indices:
371
+ frame_ca = coords[ca_indices]
372
+ else:
373
+ frame_ca = coords
374
+ rmsd_val = _kabsch_rmsd(ref_ca, frame_ca)
375
  rmsd_data.append({"frame": frame_idx, "rmsd": round(rmsd_val, 3)})
376
  frame_idx += 1
377
 
 
385
  # ---- RMSF from trajectory ----
386
  rmsf_data: list[dict] = []
387
  if frames and len(frames) >= 2:
388
+ if ca_indices:
389
+ ca_frames = [f[ca_indices] for f in frames]
390
+ ca_ref = ref_coords[ca_indices]
391
+ ca_to_res = {i: atom_to_residue[ca_indices[i]] for i in range(len(ca_indices))}
392
+ rmsf_data = _compute_rmsf(ca_frames, ca_ref, ca_to_res)
393
+ else:
394
+ rmsf_data = _compute_rmsf(frames, ref_coords, atom_to_residue)
395
 
396
  total_elapsed = round(min_elapsed + prod_elapsed, 1)
397
 
 
405
  "timestep_fs": 2,
406
  "minimization_steps": MINIMIZATION_STEPS,
407
  "equilibration_steps": EQUILIBRATION_STEPS if mode in ("equilibrate", "production") else 0,
408
+ "production_steps": production_steps,
409
+ "production_ps": round(production_steps / 500, 1),
410
  "final_energy_kj_mol": round(final_energy, 2),
411
  "energy": energy_data,
412
+ "minimization_drift_angstrom": round(init_rmsd, 3),
413
  "rmsd": rmsd_data,
414
+ "rmsd_basis": "CA" if ca_indices else "all_atoms",
415
+ "rmsd_avg_angstrom": round(float(np.mean([r["rmsd"] for r in rmsd_data])), 3) if rmsd_data else None,
416
  "rmsf": rmsf_data[:50],
417
  "atom_count": n_atoms,
418
  "residue_count": n_residues,
 
425
  # BioPython structural analysis fallback (when OpenMM is unavailable)
426
  # ---------------------------------------------------------------------------
427
 
428
+ def _model_ca_coords(model) -> np.ndarray | None:
429
+ """Extract Cα coordinates from a BioPython Model in residue order.
430
+
431
+ Returns None if no Cα atoms are present.
432
+ """
433
+ ca_coords = []
434
+ for chain in model.get_chains():
435
+ for res in chain.get_residues():
436
+ if not (res.id[0] == " " or res.id[0] == ""): # skip HETATM residues
437
+ continue
438
+ if res.get_resname().strip().upper() not in _STANDARD_AAS:
439
+ continue
440
+ for atom in res.get_atoms():
441
+ if atom.get_name() == "CA":
442
+ ca_coords.append(atom.get_vector().get_array())
443
+ break
444
+ if not ca_coords:
445
+ return None
446
+ return np.array(ca_coords)
447
+
448
+
449
+ def _run_biopython_analysis(pdb_path: str, pdb_id: str, mode: str, reason: str = "OpenMM not available") -> dict:
450
  """Structural analysis fallback using BioPython when OpenMM is not installed.
451
 
452
  Computes real structural properties from the PDB:
 
459
  from Bio.PDB import PDBParser, Polypeptide
460
  import math
461
 
462
+ logger.info("%s — running BioPython structural analysis for %s", reason, pdb_id)
463
  t0 = time.time()
464
 
465
  parser = PDBParser(QUIET=True)
 
536
  # Build energy "trace" — constant value across frames for visualization
537
  energy_data = {
538
  "minimization": [{"step": 0, "energy": estimated_energy_kj}],
539
+ "production": [],
540
  }
541
 
542
+ # Real RMSD only — never fabricate. NMR ensembles store multiple models in
543
+ # one PDB; the RMSD of each model vs the first is a genuine conformational
544
+ # drift measure. Without a second conformation there is no dynamics data.
545
+ rmsd_data: list[dict] = []
546
+ rmsd_source = None
547
+ n_models = len(list(structure))
548
+ if n_models > 1:
549
+ try:
550
+ first_ca = _model_ca_coords(structure[0])
551
+ rmsd_data = []
552
+ for mi, model in enumerate(structure):
553
+ m_ca = _model_ca_coords(model)
554
+ if first_ca is not None and m_ca is not None and first_ca.shape == m_ca.shape:
555
+ rmsd_data.append({"frame": mi, "rmsd": round(_kabsch_rmsd(first_ca, m_ca), 3)})
556
+ if rmsd_data:
557
+ rmsd_source = f"ensemble_models_{n_models}"
558
+ except Exception as exc:
559
+ logger.warning("Ensemble RMSD failed for %s: %s", pdb_id, exc)
560
 
561
  elapsed = round(time.time() - t0, 1)
562
 
 
574
  "final_energy_kj_mol": estimated_energy_kj,
575
  "energy": energy_data,
576
  "rmsd": rmsd_data,
577
+ "rmsd_basis": "CA" if rmsd_data else None,
578
+ "rmsd_source": rmsd_source,
579
  "rmsf": [],
580
  "atom_count": n_atoms,
581
  "residue_count": n_residues,
 
586
  "secondary_structure": ss_counts,
587
  "elapsed_seconds": elapsed,
588
  "status": "complete",
589
+ "note": f"{reason} — used BioPython structural analysis. Install OpenMM for full MD simulation.",
590
  })
bioai-platform/backend/app/worker.py CHANGED
@@ -19,6 +19,16 @@ import socket
19
  import signal
20
  from datetime import datetime, timezone
21
 
 
 
 
 
 
 
 
 
 
 
22
  from app.config import settings
23
  from app.services.supabase import get_client
24
 
 
19
  import signal
20
  from datetime import datetime, timezone
21
 
22
+ # Load OpenMM's native libraries BEFORE any rdkit import. The OpenMM and
23
+ # RDKit wheels bundle conflicting copies of MSVC runtime DLLs
24
+ # (msvcp140/concrt140); if rdkit loads first, OpenMM's Context creation
25
+ # crashes with a native access violation. ADMET/docking jobs import rdkit
26
+ # lazily, so preloading openmm here guarantees safe ordering for MD jobs.
27
+ try:
28
+ import openmm.app # noqa: F401
29
+ except Exception: # pragma: no cover - openmm may be absent in some envs
30
+ pass
31
+
32
  from app.config import settings
33
  from app.services.supabase import get_client
34
 
bioai-platform/backend/tests/conftest.py CHANGED
@@ -78,13 +78,26 @@ def auth_headers():
78
  return {"Authorization": f"Bearer {TEST_JWT}"}
79
 
80
 
 
 
 
 
 
 
 
 
 
 
 
81
  # ---------------------------------------------------------------------------
82
  # Detect rdkit availability (only on HF Spaces Docker, not local dev)
 
 
83
  # ---------------------------------------------------------------------------
84
  try:
85
- from rdkit import Chem
86
- HAS_RDKIT = True
87
- except ImportError:
88
  HAS_RDKIT = False
89
 
90
  requires_rdkit = pytest.mark.skipif(not HAS_RDKIT, reason="rdkit not installed locally — run on HF Spaces")
 
78
  return {"Authorization": f"Bearer {TEST_JWT}"}
79
 
80
 
81
+ # ---------------------------------------------------------------------------
82
+ # Pre-load OpenMM native libs BEFORE rdkit. OpenMM and RDKit wheels bundle
83
+ # conflicting copies of MSVC runtime DLLs (msvcp140/concrt140); importing
84
+ # rdkit first makes OpenMM's Context creation crash with an access violation.
85
+ # Loading openmm.app first resolves the conflict.
86
+ # ---------------------------------------------------------------------------
87
+ try:
88
+ import openmm.app # noqa: F401
89
+ except Exception:
90
+ pass
91
+
92
  # ---------------------------------------------------------------------------
93
  # Detect rdkit availability (only on HF Spaces Docker, not local dev)
94
+ # find_spec avoids actually importing rdkit, which would trigger the
95
+ # OpenMM/RDKit runtime conflict above for real-OpenMM tests.
96
  # ---------------------------------------------------------------------------
97
  try:
98
+ import importlib.util
99
+ HAS_RDKIT = importlib.util.find_spec("rdkit.Chem") is not None
100
+ except (ImportError, ValueError):
101
  HAS_RDKIT = False
102
 
103
  requires_rdkit = pytest.mark.skipif(not HAS_RDKIT, reason="rdkit not installed locally — run on HF Spaces")
bioai-platform/backend/tests/test_md_sim_unit.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Unit tests for the MD simulation engine (no network, no OpenMM needed).
3
+
4
+ Covers:
5
+ - Kabsch RMSD correctness (rigid-body invariance, known displacements)
6
+ - Adaptive production length scaling (size-dependent, bounded)
7
+ - Position conversion
8
+ - JSON-safe native conversion
9
+ """
10
+
11
+ import numpy as np
12
+ import pytest
13
+
14
+ from app.tools.md_sim import (
15
+ _kabsch_rmsd,
16
+ _adaptive_production_steps,
17
+ _positions_to_np,
18
+ _to_native,
19
+ )
20
+
21
+
22
+ def _rotz(a):
23
+ c, s = np.cos(a), np.sin(a)
24
+ return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
25
+
26
+
27
+ def _roty(a):
28
+ c, s = np.cos(a), np.sin(a)
29
+ return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
30
+
31
+
32
+ class TestKabschRMSD:
33
+ def test_identical_coordinates(self):
34
+ ref = np.random.RandomState(0).rand(100, 3) * 10
35
+ assert _kabsch_rmsd(ref, ref.copy()) < 1e-9
36
+
37
+ def test_rigid_body_invariance(self):
38
+ """Rotation + translation must yield RMSD ~0 (Kabsch removes both)."""
39
+ rng = np.random.RandomState(1)
40
+ ref = rng.rand(80, 3) * 15
41
+ R = _rotz(0.7) @ _roty(1.2) @ _rotz(0.3)
42
+ mov = ref @ R.T + np.array([5.0, -3.0, 2.0])
43
+ assert _kabsch_rmsd(ref, mov) < 1e-8
44
+
45
+ def test_pure_translation_invariance(self):
46
+ """A uniform translation alone must yield RMSD ~0."""
47
+ rng = np.random.RandomState(7)
48
+ ref = rng.rand(60, 3) * 10
49
+ mov = ref + np.array([1.0, 2.0, -3.0])
50
+ assert _kabsch_rmsd(ref, mov) < 1e-8
51
+
52
+ def test_noise_upper_bound(self):
53
+ """Adding noise must produce RMSD <= per-atom raw (un-aligned) RMSD, and > 0."""
54
+ rng = np.random.RandomState(4)
55
+ ref = rng.rand(100, 3) * 10
56
+ noise = rng.normal(0, 0.5, ref.shape)
57
+ mov = ref + noise
58
+ # per-atom RMSD of un-aligned pair = sqrt(mean over ALL coords of noise^2) * sqrt(3)
59
+ raw = float(np.sqrt((noise**2).mean())) * np.sqrt(3)
60
+ got = _kabsch_rmsd(ref, mov)
61
+ assert 0.0 < got <= raw * 1.001
62
+ assert got > raw * 0.7 # optimal rotation shouldn't over-correct
63
+
64
+ def test_single_atom(self):
65
+ # A single atom always centers to the origin, so RMSD is 0.
66
+ assert _kabsch_rmsd(np.array([[0.0, 0, 0]]), np.array([[1.0, 0, 0]])) < 1e-9
67
+
68
+ def test_shape_mismatch_raises(self):
69
+ with pytest.raises(ValueError):
70
+ _kabsch_rmsd(np.zeros((3, 3)), np.zeros((4, 3)))
71
+
72
+ def test_empty_input_returns_zero(self):
73
+ assert _kabsch_rmsd(np.zeros((0, 3)), np.zeros((0, 3))) == 0.0
74
+
75
+
76
+ class TestAdaptiveProductionSteps:
77
+ def test_small_protein_gets_target(self):
78
+ assert _adaptive_production_steps(642) >= 100_000
79
+
80
+ def test_larger_protein_gets_fewer_steps(self):
81
+ steps_big = _adaptive_production_steps(30_000)
82
+ steps_huge = _adaptive_production_steps(60_000)
83
+ assert steps_big > steps_huge
84
+
85
+ def test_never_exceeds_cap(self):
86
+ assert _adaptive_production_steps(10) <= 1000 * 500 # 1 ns cap
87
+
88
+ def test_never_below_floor(self):
89
+ assert _adaptive_production_steps(1_000_000) >= 2 * 500
90
+
91
+ def test_zero_atoms_returns_target(self):
92
+ assert _adaptive_production_steps(0) == 250 * 500
93
+
94
+
95
+ class TestPositionConversion:
96
+ def test_converts_openmm_like_positions(self):
97
+ class P:
98
+ def __init__(self, x, y, z):
99
+ self.x, self.y, self.z = x, y, z
100
+
101
+ positions = [P(1, 2, 3), P(4, 5, 6)]
102
+ out = _positions_to_np(positions)
103
+ assert out.shape == (2, 3)
104
+ np.testing.assert_allclose(out[0], [1, 2, 3])
105
+ np.testing.assert_allclose(out[1], [4, 5, 6])
106
+
107
+
108
+ class TestToNative:
109
+ def test_converts_numpy_types(self):
110
+ out = _to_native({"a": np.float32(1.5), "b": np.int64(3), "c": np.array([1.0, 2.0])})
111
+ assert isinstance(out["a"], float)
112
+ assert isinstance(out["b"], int)
113
+ assert isinstance(out["c"], list)
114
+
115
+ def test_nested_structures(self):
116
+ out = _to_native([{"x": np.float64(1.0)}, [np.int32(2)]])
117
+ assert isinstance(out[0]["x"], float)
118
+ assert isinstance(out[1][0], int)
bioai-platform/frontend/src/app/(dashboard)/analyze/md/page.tsx CHANGED
@@ -202,7 +202,7 @@ export default function MDPage() {
202
  {[
203
  { label: "Minimization (L-BFGS)", steps: result.minimization_steps, total: 500, color: "bg-accent-cyan" },
204
  { label: "Equilibration (NVT, Langevin)", steps: result.equilibration_steps, total: 1000, color: "bg-accent-purple" },
205
- { label: "Production (Langevin)", steps: result.production_steps, total: 2000, color: "bg-accent-amber" },
206
  ].filter(s => s.steps > 0).map((s) => (
207
  <div key={s.label}>
208
  <div className="flex items-center justify-between mb-1">
 
202
  {[
203
  { label: "Minimization (L-BFGS)", steps: result.minimization_steps, total: 500, color: "bg-accent-cyan" },
204
  { label: "Equilibration (NVT, Langevin)", steps: result.equilibration_steps, total: 1000, color: "bg-accent-purple" },
205
+ { label: "Production (Langevin)", steps: result.production_steps, total: Math.max(result.production_steps, result.equilibration_steps, 1), color: "bg-accent-amber" },
206
  ].filter(s => s.steps > 0).map((s) => (
207
  <div key={s.label}>
208
  <div className="flex items-center justify-between mb-1">
bioai-platform/frontend/src/lib/api.ts CHANGED
@@ -572,9 +572,14 @@ export type MDSimulationResult = {
572
  minimization_steps: number;
573
  equilibration_steps: number;
574
  production_steps: number;
 
575
  final_energy_kj_mol: number;
576
  energy: { minimization: { step: number; energy: number }[]; production: { step: number; energy: number }[] };
577
  rmsd: { frame: number; rmsd: number }[];
 
 
 
 
578
  rmsf: { residue: string; rmsf_angstrom: number }[];
579
  atom_count: number;
580
  residue_count: number;
 
572
  minimization_steps: number;
573
  equilibration_steps: number;
574
  production_steps: number;
575
+ production_ps?: number;
576
  final_energy_kj_mol: number;
577
  energy: { minimization: { step: number; energy: number }[]; production: { step: number; energy: number }[] };
578
  rmsd: { frame: number; rmsd: number }[];
579
+ rmsd_basis?: string;
580
+ rmsd_avg_angstrom?: number;
581
+ minimization_drift_angstrom?: number;
582
+ rmsd_source?: string;
583
  rmsf: { residue: string; rmsf_angstrom: number }[];
584
  atom_count: number;
585
  residue_count: number;