maltefranke commited on
Commit
0b0dafb
路
verified 路
1 Parent(s): 224f4e8

Initialize models after GPU allocation; add sampled trajectory playback and default GEOM generation

Browse files
Files changed (3) hide show
  1. app.py +82 -25
  2. backend.py +125 -8
  3. trajectory_view.py +80 -0
app.py CHANGED
@@ -1,6 +1,7 @@
1
  """Morph's public Gradio interface, with ZeroGPU generation."""
2
 
3
- import os
 
4
 
5
  import spaces # Initialize ZeroGPU before importing torch through backend.
6
  import gradio as gr
@@ -8,11 +9,11 @@ import pandas as pd
8
  import py3Dmol
9
  import html
10
 
11
- from backend import REGISTRY, generate_graphs, load_models, present
12
  from gpu_diagnostic import gpu_probe
13
 
14
- DEVICE = os.environ.get("MORPH_DEVICE", "cpu")
15
- USE_GPU = DEVICE.startswith("cuda")
16
 
17
 
18
  def description(key):
@@ -36,7 +37,11 @@ def viewer(records, sample):
36
  if item is None:
37
  return "<p style='color:#65758b;padding:24px'>Generate molecules to explore their 3D structures.</p>"
38
  view = py3Dmol.view(width="100%", height=410)
39
- view.addModel(item["molblock"], "sdf")
 
 
 
 
40
  view.setStyle({"stick": {"radius": 0.15}, "sphere": {"scale": 0.23}})
41
  view.setBackgroundColor("#f7f9fc")
42
  view.zoomTo()
@@ -48,18 +53,32 @@ def viewer(records, sample):
48
  )
49
 
50
 
51
- @spaces.GPU(duration=30)
52
  def sample_on_gpu(key, target_logp, target_n, count, seed):
53
- return generate_graphs(key, target_logp, target_n, count, seed)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
 
56
  def generate(key, target_logp, target_n, count, seed):
57
- if not USE_GPU and count > 2:
58
- raise gr.Error("The CPU preview supports up to two molecules per request.")
59
- sampler = sample_on_gpu if USE_GPU else generate_graphs
60
- graphs = sampler(key, target_logp, target_n, count, seed)
61
- gallery, rows, records, sdf, csv, status = present(
62
- graphs, key, target_logp, target_n, seed
63
  )
64
  choices = [str(record["index"]) for record in records]
65
  selected = choices[0] if choices else None
@@ -75,6 +94,10 @@ def generate(key, target_logp, target_n, count, seed):
75
  sdf,
76
  csv,
77
  status,
 
 
 
 
78
  )
79
 
80
 
@@ -100,13 +123,18 @@ with gr.Blocks(
100
  with gr.Row():
101
  with gr.Column(scale=1, min_width=300):
102
  model = gr.Dropdown(
103
- [(spec["label"], key) for key, spec in REGISTRY.items()],
104
- value="geom-logp",
 
 
 
105
  label="Model",
106
  interactive=True,
107
  )
108
- note = gr.Markdown(description("geom-logp"))
109
- target_logp = gr.Slider(-8, 9, value=2, step=0.1, label="Target logP")
 
 
110
  target_n = gr.Slider(
111
  3,
112
  120,
@@ -117,8 +145,8 @@ with gr.Blocks(
117
  )
118
  count = gr.Slider(
119
  1,
120
- 8 if USE_GPU else 2,
121
- value=4 if USE_GPU else 1,
122
  step=1,
123
  label="Molecules",
124
  )
@@ -132,8 +160,6 @@ with gr.Blocks(
132
  button = gr.Button("Generate molecules", variant="primary", size="lg")
133
  gr.Markdown(
134
  "Shared GPU 路 You may need to sign in to Hugging Face and wait in the queue. Changing the seed gives new samples."
135
- if USE_GPU
136
- else "CPU preview 路 Generation can take a minute or more. Changing the seed gives new samples."
137
  )
138
  gr.Markdown(
139
  "[Checkpoints & evaluation](https://huggingface.co/maltefranke/morph) 路 [Source](https://huggingface.co/spaces/maltefranke/morph-playground/tree/main)"
@@ -155,6 +181,14 @@ with gr.Blocks(
155
  )
156
  structure = gr.HTML(viewer([], None))
157
  gr.Markdown("Drag to rotate 路 Scroll to zoom")
 
 
 
 
 
 
 
 
158
  with gr.Tab("Properties"):
159
  table = gr.Dataframe(
160
  interactive=False, wrap=True, label="Every generation attempt"
@@ -167,17 +201,40 @@ with gr.Blocks(
167
  )
168
  model.change(change_model, model, [target_logp, target_n, note], queue=False)
169
  selected.change(viewer, [records, selected], structure, queue=False)
 
 
 
 
 
 
 
170
  button.click(
171
  generate,
172
  [model, target_logp, target_n, count, seed],
173
- [gallery, table, records, selected, structure, sdf, csv, status],
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  api_name="generate",
175
  concurrency_limit=1,
176
  )
177
 
178
  if __name__ == "__main__":
179
- import torch
180
 
181
- print(f"Runtime: torch={torch.__version__}, CUDA={torch.version.cuda}", flush=True)
182
- load_models(DEVICE)
 
 
 
183
  demo.queue(max_size=24).launch(ssr_mode=False)
 
1
  """Morph's public Gradio interface, with ZeroGPU generation."""
2
 
3
+ import json
4
+ from pathlib import Path
5
 
6
  import spaces # Initialize ZeroGPU before importing torch through backend.
7
  import gradio as gr
 
9
  import py3Dmol
10
  import html
11
 
12
+ from trajectory_view import trajectory_viewer
13
  from gpu_diagnostic import gpu_probe
14
 
15
+ ROOT = Path(__file__).resolve().parent
16
+ REGISTRY = json.loads((ROOT / "models.json").read_text())
17
 
18
 
19
  def description(key):
 
37
  if item is None:
38
  return "<p style='color:#65758b;padding:24px'>Generate molecules to explore their 3D structures.</p>"
39
  view = py3Dmol.view(width="100%", height=410)
40
+ if item.get("molblock"):
41
+ view.addModel(item["molblock"], "sdf")
42
+ else:
43
+ view.addModel()
44
+ view.getModel().addAtoms(item["frames"][-1]["atoms"])
45
  view.setStyle({"stick": {"radius": 0.15}, "sphere": {"scale": 0.23}})
46
  view.setBackgroundColor("#f7f9fc")
47
  view.zoomTo()
 
53
  )
54
 
55
 
56
+ @spaces.GPU(duration=45)
57
  def sample_on_gpu(key, target_logp, target_n, count, seed):
58
+ # Some scientific dependencies probe CUDA while importing. Import them
59
+ # only after ZeroGPU attaches the real device, keeping its parent clean.
60
+ from backend import MODELS, generate_graphs, load_models, present
61
+
62
+ if key not in MODELS:
63
+ load_models("cuda", keys=[key])
64
+ result = generate_graphs(
65
+ key, target_logp, target_n, count, seed, trajectory=True, require_gpu=True
66
+ )
67
+ return present(
68
+ result["graphs"],
69
+ key,
70
+ target_logp,
71
+ target_n,
72
+ seed,
73
+ trajectories=result["trajectories"],
74
+ times=result["times"],
75
+ runtime=result["runtime"],
76
+ )
77
 
78
 
79
  def generate(key, target_logp, target_n, count, seed):
80
+ gallery, rows, records, sdf, csv, status, archive, runtime = sample_on_gpu(
81
+ key, target_logp, target_n, count, seed
 
 
 
 
82
  )
83
  choices = [str(record["index"]) for record in records]
84
  selected = choices[0] if choices else None
 
94
  sdf,
95
  csv,
96
  status,
97
+ gr.update(choices=choices, value=selected),
98
+ trajectory_viewer(records, selected),
99
+ archive,
100
+ runtime,
101
  )
102
 
103
 
 
123
  with gr.Row():
124
  with gr.Column(scale=1, min_width=300):
125
  model = gr.Dropdown(
126
+ [
127
+ (REGISTRY[key]["label"], key)
128
+ for key in ["geom", *[k for k in REGISTRY if k != "geom"]]
129
+ ],
130
+ value="geom",
131
  label="Model",
132
  interactive=True,
133
  )
134
+ note = gr.Markdown(description("geom"))
135
+ target_logp = gr.Slider(
136
+ -8, 9, value=2, step=0.1, label="Target logP", visible=False
137
+ )
138
  target_n = gr.Slider(
139
  3,
140
  120,
 
145
  )
146
  count = gr.Slider(
147
  1,
148
+ 8,
149
+ value=4,
150
  step=1,
151
  label="Molecules",
152
  )
 
160
  button = gr.Button("Generate molecules", variant="primary", size="lg")
161
  gr.Markdown(
162
  "Shared GPU 路 You may need to sign in to Hugging Face and wait in the queue. Changing the seed gives new samples."
 
 
163
  )
164
  gr.Markdown(
165
  "[Checkpoints & evaluation](https://huggingface.co/maltefranke/morph) 路 [Source](https://huggingface.co/spaces/maltefranke/morph-playground/tree/main)"
 
181
  )
182
  structure = gr.HTML(viewer([], None))
183
  gr.Markdown("Drag to rotate 路 Scroll to zoom")
184
+ with gr.Tab("Trajectory"):
185
+ trajectory_selected = gr.Dropdown(
186
+ choices=[], label="Molecule", interactive=True
187
+ )
188
+ trajectory_player = gr.HTML(trajectory_viewer([], None))
189
+ trajectory_file = gr.File(
190
+ label="Download trajectories (JSON + XYZ)"
191
+ )
192
  with gr.Tab("Properties"):
193
  table = gr.Dataframe(
194
  interactive=False, wrap=True, label="Every generation attempt"
 
201
  )
202
  model.change(change_model, model, [target_logp, target_n, note], queue=False)
203
  selected.change(viewer, [records, selected], structure, queue=False)
204
+ trajectory_selected.change(
205
+ trajectory_viewer,
206
+ [records, trajectory_selected],
207
+ trajectory_player,
208
+ queue=False,
209
+ )
210
+ runtime_info = gr.JSON(visible=False)
211
  button.click(
212
  generate,
213
  [model, target_logp, target_n, count, seed],
214
+ [
215
+ gallery,
216
+ table,
217
+ records,
218
+ selected,
219
+ structure,
220
+ sdf,
221
+ csv,
222
+ status,
223
+ trajectory_selected,
224
+ trajectory_player,
225
+ trajectory_file,
226
+ runtime_info,
227
+ ],
228
  api_name="generate",
229
  concurrency_limit=1,
230
  )
231
 
232
  if __name__ == "__main__":
233
+ from huggingface_hub import hf_hub_download
234
 
235
+ # Download once at startup; model construction runs in the GPU worker.
236
+ for spec in REGISTRY.values():
237
+ hf_hub_download(
238
+ "maltefranke/morph", spec["checkpoint"], revision=spec["revision"]
239
+ )
240
  demo.queue(max_size=24).launch(ssr_mode=False)
backend.py CHANGED
@@ -11,6 +11,7 @@ from pathlib import Path
11
  import random
12
  import sys
13
  import tempfile
 
14
 
15
  ROOT = Path(__file__).resolve().parent
16
  sys.path.insert(0, str(ROOT / "runtime"))
@@ -93,7 +94,9 @@ def validate_request(key, target_logp, target_n, count, seed):
93
  raise ValueError("Choose an atom-count target between 3 and 120.")
94
 
95
 
96
- def generate_graphs(key, target_logp, target_n, count, seed):
 
 
97
  """Run the same 100-step EMA sampler used for evaluation."""
98
  validate_request(key, target_logp, target_n, count, seed)
99
  torch.set_float32_matmul_precision("high")
@@ -101,6 +104,8 @@ def generate_graphs(key, target_logp, target_n, count, seed):
101
  np.random.seed(int(seed))
102
  torch.manual_seed(int(seed))
103
  module, data, prior = MODELS[key]
 
 
104
  kind = REGISTRY[key]["kind"]
105
  graphs = []
106
  for n in torch.randint(prior[0], prior[1] + 1, (int(count),)):
@@ -119,15 +124,77 @@ def generate_graphs(key, target_logp, target_n, count, seed):
119
  enabled=module.device.type == "cuda",
120
  ),
121
  ):
122
- generated = module.sample((batch, batch), 0)
123
- generated.to_inplace("cpu", non_blocking=False)
124
- outputs = generated.to_data_list()
 
 
 
125
  assert len(outputs) == int(count)
126
  assert all(torch.isfinite(graph.positions).all() for graph in outputs)
127
- return outputs
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
 
130
- def present(graphs, key, target_logp, target_n, seed):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  """Keep every attempt in the table; export sanitized structures to SDF."""
132
  _, data, _ = MODELS[key]
133
  vocab = data.vocab
@@ -167,7 +234,6 @@ def present(graphs, key, target_logp, target_n, seed):
167
  display = Chem.RemoveHs(Chem.Mol(mol))
168
  rdDepictor.Compute2DCoords(display)
169
  thumbnail = Draw.MolToImage(display, size=(440, 320))
170
- records.append(dict(index=i, molblock=block))
171
  else:
172
  thumbnail = Image.new("RGB", (440, 320), "#f4f6f8")
173
  ImageDraw.Draw(thumbnail).text(
@@ -178,11 +244,62 @@ def present(graphs, key, target_logp, target_n, seed):
178
  caption += f" 路 logP={logp:.2f}"
179
  caption += " 路 valid" if valid else " 路 invalid"
180
  gallery.append((thumbnail, caption))
 
 
 
 
 
 
 
181
  writer.close()
182
  with csv_path.open("w", newline="") as handle:
183
  csv_writer = csv.DictWriter(handle, fieldnames=rows[0])
184
  csv_writer.writeheader()
185
  csv_writer.writerows(rows)
186
  status = f"**{valid_count} / {len(graphs)} chemically valid** 路 Seed {int(seed)}"
 
 
187
  status += "\n\nAll attempts are shown. SDF includes sanitized structures; CSV includes every attempt."
188
- return gallery, rows, records, str(sdf_path), str(csv_path), status
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  import random
12
  import sys
13
  import tempfile
14
+ import zipfile
15
 
16
  ROOT = Path(__file__).resolve().parent
17
  sys.path.insert(0, str(ROOT / "runtime"))
 
94
  raise ValueError("Choose an atom-count target between 3 and 120.")
95
 
96
 
97
+ def generate_graphs(
98
+ key, target_logp, target_n, count, seed, *, trajectory=False, require_gpu=False
99
+ ):
100
  """Run the same 100-step EMA sampler used for evaluation."""
101
  validate_request(key, target_logp, target_n, count, seed)
102
  torch.set_float32_matmul_precision("high")
 
104
  np.random.seed(int(seed))
105
  torch.manual_seed(int(seed))
106
  module, data, prior = MODELS[key]
107
+ if require_gpu and module.device.type != "cuda":
108
+ raise RuntimeError("This endpoint requires real CUDA inference.")
109
  kind = REGISTRY[key]["kind"]
110
  graphs = []
111
  for n in torch.randint(prior[0], prior[1] + 1, (int(count),)):
 
124
  enabled=module.device.type == "cuda",
125
  ),
126
  ):
127
+ generated = module.sample((batch, batch), 0, return_traj=trajectory)
128
+ if trajectory:
129
+ outputs = [frames[-1] for frames in generated]
130
+ else:
131
+ generated.to_inplace("cpu", non_blocking=False)
132
+ outputs = generated.to_data_list()
133
  assert len(outputs) == int(count)
134
  assert all(torch.isfinite(graph.positions).all() for graph in outputs)
135
+ if not trajectory:
136
+ return outputs
137
+ times = [0.0, *np.cumsum(module.integrator.get_time_steps()).tolist()]
138
+ assert all(len(frames) == len(times) == 101 for frames in generated)
139
+ runtime = dict(
140
+ device=str(module.device),
141
+ gpu=torch.cuda.get_device_name() if module.device.type == "cuda" else None,
142
+ torch=torch.__version__,
143
+ precision="bfloat16" if module.device.type == "cuda" else "float32",
144
+ model=key,
145
+ checkpoint_sha256=REGISTRY[key]["sha256"],
146
+ initial_count_prior=list(prior),
147
+ integration_steps=100,
148
+ frames_per_molecule=101,
149
+ coordinate_units="angstrom",
150
+ time_grid="log; final integration boundary 0.999",
151
+ )
152
+ return dict(graphs=outputs, trajectories=generated, times=times, runtime=runtime)
153
 
154
 
155
+ def frame_atoms(graph, vocab):
156
+ """Export raw graph geometry, including chemically invalid intermediate states."""
157
+ positions = graph.positions.tolist()
158
+ atom_types = graph.atom_types.tolist()
159
+ charges = graph.charge_types.tolist()
160
+ atoms = [
161
+ dict(
162
+ elem=vocab.atom_tokens[a],
163
+ x=round(p[0], 5),
164
+ y=round(p[1], 5),
165
+ z=round(p[2], 5),
166
+ charge=int(vocab.charge_tokens[c]),
167
+ bonds=[],
168
+ bondOrder=[],
169
+ )
170
+ for a, c, p in zip(atom_types, charges, positions, strict=True)
171
+ ]
172
+ edge_types, edge_index = graph.get_edge_types_triu(
173
+ no_bond_idx=list(vocab.edge_tokens).index("<NO_BOND>")
174
+ )
175
+ for edge, (a, b) in zip(edge_types.tolist(), edge_index.T.tolist(), strict=True):
176
+ token = vocab.edge_tokens[edge]
177
+ if token == "<NO_BOND>":
178
+ continue
179
+ order = 1.5 if str(token) == "4" else float(token)
180
+ atoms[a]["bonds"].append(b)
181
+ atoms[a]["bondOrder"].append(order)
182
+ atoms[b]["bonds"].append(a)
183
+ atoms[b]["bondOrder"].append(order)
184
+ return atoms
185
+
186
+
187
+ def present(
188
+ graphs,
189
+ key,
190
+ target_logp,
191
+ target_n,
192
+ seed,
193
+ *,
194
+ trajectories=None,
195
+ times=None,
196
+ runtime=None,
197
+ ):
198
  """Keep every attempt in the table; export sanitized structures to SDF."""
199
  _, data, _ = MODELS[key]
200
  vocab = data.vocab
 
234
  display = Chem.RemoveHs(Chem.Mol(mol))
235
  rdDepictor.Compute2DCoords(display)
236
  thumbnail = Draw.MolToImage(display, size=(440, 320))
 
237
  else:
238
  thumbnail = Image.new("RGB", (440, 320), "#f4f6f8")
239
  ImageDraw.Draw(thumbnail).text(
 
244
  caption += f" 路 logP={logp:.2f}"
245
  caption += " 路 valid" if valid else " 路 invalid"
246
  gallery.append((thumbnail, caption))
247
+ record = dict(index=i, molblock=block if mol is not None else None)
248
+ if trajectories is not None:
249
+ record["frames"] = [
250
+ dict(time=float(t), atoms=frame_atoms(frame, vocab))
251
+ for t, frame in zip(times, trajectories[i - 1], strict=True)
252
+ ]
253
+ records.append(record)
254
  writer.close()
255
  with csv_path.open("w", newline="") as handle:
256
  csv_writer = csv.DictWriter(handle, fieldnames=rows[0])
257
  csv_writer.writeheader()
258
  csv_writer.writerows(rows)
259
  status = f"**{valid_count} / {len(graphs)} chemically valid** 路 Seed {int(seed)}"
260
+ if runtime is not None and runtime["device"].startswith("cuda"):
261
+ status += " 路 GPU"
262
  status += "\n\nAll attempts are shown. SDF includes sanitized structures; CSV includes every attempt."
263
+ if trajectories is None:
264
+ return gallery, rows, records, str(sdf_path), str(csv_path), status
265
+ archive = directory / "trajectories.zip"
266
+ with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED) as zip_file:
267
+ zip_file.writestr(
268
+ "generation.json",
269
+ json.dumps(
270
+ dict(
271
+ **runtime,
272
+ seed=int(seed),
273
+ target_logp=float(target_logp) if kind == "logp" else None,
274
+ target_n=int(target_n) if kind == "count" else None,
275
+ ),
276
+ indent=2,
277
+ ),
278
+ )
279
+ for record in records:
280
+ zip_file.writestr(
281
+ f"molecule_{record['index']}.json", json.dumps(record["frames"])
282
+ )
283
+ xyz = []
284
+ for frame in record["frames"]:
285
+ xyz.extend(
286
+ [
287
+ str(len(frame["atoms"])),
288
+ f"t={frame['time']:.9f}; coordinates in angstrom",
289
+ ]
290
+ )
291
+ xyz.extend(
292
+ f"{a['elem']} {a['x']:.5f} {a['y']:.5f} {a['z']:.5f}"
293
+ for a in frame["atoms"]
294
+ )
295
+ zip_file.writestr(f"molecule_{record['index']}.xyz", "\n".join(xyz) + "\n")
296
+ return (
297
+ gallery,
298
+ rows,
299
+ records,
300
+ str(sdf_path),
301
+ str(csv_path),
302
+ status,
303
+ str(archive),
304
+ runtime,
305
+ )
trajectory_view.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Client-side trajectory playback with changing atom counts and bonds."""
2
+
3
+ import html
4
+ import json
5
+
6
+
7
+ def trajectory_viewer(records, sample):
8
+ record = next((r for r in records if r["index"] == int(sample or 0)), None)
9
+ if record is None or not record.get("frames"):
10
+ return "<p style='padding:24px;color:#65758b'>Generate molecules to play their trajectories.</p>"
11
+ frames = json.dumps(record["frames"], separators=(",", ":")).replace("</", "<\\/")
12
+ document = """<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1">
13
+ <script src="https://3Dmol.org/build/3Dmol-min.js"></script>
14
+ <style>
15
+ body{margin:0;font:14px system-ui,sans-serif;color:#26364a;background:#f7f9fc}
16
+ #scene{height:405px;position:relative;width:100%}
17
+ .controls{padding:12px 14px;display:flex;gap:10px;align-items:center;flex-wrap:wrap}
18
+ button,select{font:inherit;border:1px solid #ccd6e3;border-radius:7px;background:white;padding:7px 12px;cursor:pointer;color:#26364a}
19
+ #play{background:#3478f6;color:white;border-color:#3478f6;min-width:73px}
20
+ #scrub{width:100%;accent-color:#3478f6;margin:0 0 5px}
21
+ #readout{font-variant-numeric:tabular-nums;margin-left:auto}
22
+ .hint{margin:0;padding:0 14px 12px;color:#697a90;font-size:12px}
23
+ </style></head><body>
24
+ <div id="scene" aria-label="Molecular trajectory"></div>
25
+ <div class="controls">
26
+ <input id="scrub" aria-label="Trajectory frame" type="range" min="0" step="1" value="0">
27
+ <button id="play">Play</button><button id="restart">Restart</button>
28
+ <label>Speed <select id="speed" aria-label="Playback speed"><option value="0.5">0.5脳</option><option value="1" selected>1脳</option><option value="2">2脳</option></select></label>
29
+ <label><input type="checkbox" id="loop" checked> Loop</label>
30
+ <label><input type="checkbox" id="bonds" checked> Bonds</label>
31
+ <span id="readout" aria-live="off"></span>
32
+ </div><p class="hint">Drag to rotate 路 Scroll to zoom 路 Frames show the sampled states, including atom insertions and deletions.</p>
33
+ <script>
34
+ const frames=__FRAMES__;
35
+ const viewer=$3Dmol.createViewer(document.getElementById('scene'),{backgroundColor:'#f7f9fc',antialias:true});
36
+ const scrub=document.getElementById('scrub'),play=document.getElementById('play'),readout=document.getElementById('readout');
37
+ scrub.max=frames.length-1;
38
+ let frame=0,playing=false,last=0,pausedAtEnd=0;
39
+ function draw(index,fit=false){
40
+ frame=Math.max(0,Math.min(frames.length-1,index));
41
+ const camera=fit?null:viewer.getView();
42
+ viewer.removeAllModels();
43
+ // 3Dmol mutates atom objects; each display gets a fresh copy of the raw frame.
44
+ const atoms=frames[frame].atoms.map(a=>({...a,bonds:[...a.bonds],bondOrder:[...a.bondOrder]}));
45
+ viewer.addModel().addAtoms(atoms);
46
+ const style={sphere:{scale:0.23}};
47
+ if(document.getElementById('bonds').checked)style.stick={radius:0.10};
48
+ viewer.setStyle({},style);
49
+ if(fit)viewer.zoomTo();else viewer.setView(camera);
50
+ viewer.render();scrub.value=frame;
51
+ readout.textContent=`t = ${frames[frame].time.toFixed(2)} 路 N = ${atoms.length}`;
52
+ document.body.dataset.frame=String(frame);document.body.dataset.atomCount=String(atoms.length);
53
+ }
54
+ function pause(){playing=false;play.textContent='Play';}
55
+ play.onclick=()=>{if(playing){pause();return;}if(frame===frames.length-1)draw(0);playing=true;last=0;pausedAtEnd=0;play.textContent='Pause';};
56
+ document.getElementById('restart').onclick=()=>{pause();draw(0);};
57
+ scrub.oninput=()=>{pause();draw(Number(scrub.value));};
58
+ document.getElementById('bonds').onchange=()=>draw(frame);
59
+ document.addEventListener('visibilitychange',()=>{if(document.hidden)pause();});
60
+ function tick(now){
61
+ if(playing){
62
+ const interval=1000/(25*Number(document.getElementById('speed').value));
63
+ if(!last)last=now;
64
+ if(frame===frames.length-1){
65
+ if(!document.getElementById('loop').checked)pause();
66
+ else{if(!pausedAtEnd)pausedAtEnd=now;if(now-pausedAtEnd>=1000){draw(0);last=now;pausedAtEnd=0;}}
67
+ }else if(now-last>=interval){draw(frame+1);last=now;}
68
+ }
69
+ requestAnimationFrame(tick);
70
+ }
71
+ // Fit to the finished molecule, then keep its camera stable throughout playback.
72
+ draw(frames.length-1,true);draw(0);requestAnimationFrame(tick);
73
+ window.addEventListener('resize',()=>{viewer.resize();viewer.render();});
74
+ </script></body></html>""".replace("__FRAMES__", frames)
75
+ return (
76
+ '<iframe title="Trajectory player" sandbox="allow-scripts allow-same-origin" '
77
+ 'style="width:100%;height:555px;border:0;border-radius:12px" srcdoc="'
78
+ + html.escape(document, quote=True)
79
+ + '"></iframe>'
80
+ )