pyiraspa 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyiraspa/__init__.py ADDED
@@ -0,0 +1,879 @@
1
+ """pyiraspa — Jupyter notebook interface for iRASPA-WebGPU."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import gzip
7
+ import json
8
+ import struct
9
+ import uuid
10
+ from pathlib import Path
11
+ from typing import Any, Mapping, NamedTuple, Optional, Sequence, Union
12
+
13
+ from .crystal import Crystal, crystal
14
+ from .symmetry.space_group import (
15
+ expand_asymmetric_unit,
16
+ expand_fractional_sites,
17
+ resolve_space_group,
18
+ resolve_space_group_like,
19
+ )
20
+
21
+ __version__ = "0.1.0"
22
+
23
+ __all__ = [
24
+ "Crystal",
25
+ "crystal",
26
+ "expand_asymmetric_unit",
27
+ "expand_fractional_sites",
28
+ "resolve_space_group",
29
+ "resolve_space_group_like",
30
+ "data_path",
31
+ "demo_cif",
32
+ "demo_poscar",
33
+ "demo_xyz",
34
+ "demo_traj_xyz",
35
+ "demo_pdb",
36
+ "demo_traj_pdb",
37
+ "demo_irmof1",
38
+ "demo_cubtc",
39
+ "view",
40
+ "load_library",
41
+ "read_pdb_trajectory",
42
+ "PDBTrajectory",
43
+ "embed_library",
44
+ "CDN_URL",
45
+ "__version__",
46
+ ]
47
+
48
+ _PKG = Path(__file__).resolve().parent
49
+ _STATIC = _PKG / "static" / "iraspa-webgpu.js"
50
+ _DATA = _PKG / "data"
51
+
52
+ #: Where a viewer looks for the library when it is not in the notebook (see ``embed_library``).
53
+ #: Derived from ``__version__``: the npm package ``iraspa-webgpu`` must be published with the same version.
54
+ CDN_URL = f"https://cdn.jsdelivr.net/npm/iraspa-webgpu@{__version__}/dist/iraspa-webgpu.iife.js"
55
+
56
+ #: How the JavaScript library is stored in the notebook outputs:
57
+ #:
58
+ #: - ``"once"`` (default): only the first viewer of a kernel session carries the library (gzip-compressed,
59
+ #: about 70 kB); all later viewers reuse it. If the output of that first viewer is cleared and the notebook
60
+ #: is reopened, the other viewers load the library from ``CDN_URL``, or ask to re-run a viewer cell.
61
+ #: - ``"always"``: every viewer output carries the library (self-contained outputs, larger notebooks).
62
+ #: - ``"never"``: no viewer carries it; the library is loaded from ``CDN_URL`` (needs a network connection).
63
+ embed_library = "once"
64
+
65
+ _embed_state: dict = {"done": False, "cell": None}
66
+
67
+
68
+ def _current_cell_id() -> Optional[str]:
69
+ """Identifier of the notebook cell that is being executed, if the front end sends one."""
70
+ try:
71
+ from IPython import get_ipython
72
+
73
+ shell = get_ipython()
74
+ parent = shell.get_parent() if shell is not None else {}
75
+ metadata = parent.get("metadata", {}) if isinstance(parent, dict) else {}
76
+ cell_id = metadata.get("cellId") or metadata.get("cell_id")
77
+ return str(cell_id) if cell_id else None
78
+ except Exception:
79
+ return None
80
+
81
+
82
+ def _library_html() -> str:
83
+ """A script that defines ``window.iRASPA`` from the bundled library (stored gzip-compressed)."""
84
+ if not _STATIC.is_file():
85
+ return ""
86
+ payload = base64.b64encode(gzip.compress(_STATIC.read_bytes(), 9, mtime=0)).decode("ascii")
87
+ return f"""<script>
88
+ (function() {{
89
+ if (window.iRASPA || window.__iraspaLoad) return;
90
+ window.__iraspaLoad = (async function() {{
91
+ var b = atob("{payload}");
92
+ var u = new Uint8Array(b.length);
93
+ for (var i = 0; i < b.length; i++) u[i] = b.charCodeAt(i);
94
+ var stream = new Blob([u]).stream().pipeThrough(new DecompressionStream("gzip"));
95
+ var code = await new Response(stream).text();
96
+ var s = document.createElement("script");
97
+ s.textContent = code;
98
+ document.head.appendChild(s);
99
+ if (!window.iRASPA) throw new Error("iRASPA library did not load");
100
+ }})();
101
+ window.__iraspaLoad.catch(function() {{}});
102
+ }})();
103
+ </script>
104
+ """
105
+
106
+
107
+ def load_library():
108
+ """Display the JavaScript library on its own (optional, e.g. in the first cell of a notebook).
109
+
110
+ The viewers of all other cells then reuse it, and none of their outputs has to carry it.
111
+ """
112
+ from IPython.display import HTML, display
113
+
114
+ _embed_state["done"] = True
115
+ _embed_state["cell"] = _current_cell_id()
116
+ display(HTML(_library_html()))
117
+
118
+
119
+ def _flatten(values: Any) -> list:
120
+ """Nested sequences (or a numpy array) -> (flat list of floats, shape)."""
121
+ try:
122
+ import numpy as np
123
+
124
+ array = np.asarray(values, dtype=float)
125
+ return array.ravel().tolist(), tuple(array.shape)
126
+ except ImportError:
127
+ pass
128
+ shape = []
129
+ level = values
130
+ while isinstance(level, (list, tuple)):
131
+ shape.append(len(level))
132
+ level = level[0] if level else None
133
+ flat = [values]
134
+ for _ in shape:
135
+ flat = [x for sub in flat for x in sub]
136
+ return [float(x) for x in flat], tuple(shape)
137
+
138
+
139
+ class PDBTrajectory(NamedTuple):
140
+ """The result of :func:`read_pdb_trajectory`."""
141
+
142
+ elements: list
143
+ positions: list # frames x atoms x [x, y, z]
144
+ cell: Any # (a, b, c, alpha, beta, gamma), a list of these (one per frame) if the cell changes, or None
145
+ labels: list # atom names
146
+ resnames: list # residue names
147
+
148
+
149
+ def read_pdb_trajectory(text: str) -> PDBTrajectory:
150
+ """Parse a (multi-model) PDB file into ``(elements, positions, cell, labels, resnames)``.
151
+
152
+ ``positions`` is a list of frames, each a list of ``[x, y, z]``. ``cell`` is ``(a, b, c, alpha, beta, gamma)``
153
+ from the CRYST1 records: one tuple if all models have the same cell, a list with one tuple per model if the
154
+ cell changes (e.g. an NPT simulation), or None without CRYST1 records. The element is taken from columns
155
+ 77-78, or else from the atom name. All models must have the same number of atoms.
156
+ """
157
+ frames: list = []
158
+ cells: list = []
159
+ current: list = []
160
+ elements: list = []
161
+ labels: list = []
162
+ resnames: list = []
163
+ cell = None
164
+
165
+ def flush():
166
+ nonlocal current
167
+ if current:
168
+ frames.append(current)
169
+ cells.append(cell)
170
+ current = []
171
+
172
+ for raw in text.splitlines():
173
+ if raw.startswith("CRYST1") and len(raw) >= 54:
174
+ try:
175
+ cell = tuple(float(raw[a:b]) for a, b in ((6, 15), (15, 24), (24, 33), (33, 40), (40, 47), (47, 54)))
176
+ except ValueError:
177
+ pass
178
+ elif raw.startswith("MODEL") or raw.startswith("ENDMDL"):
179
+ flush()
180
+ elif (raw.startswith("ATOM") or raw.startswith("HETATM")) and len(raw) >= 54:
181
+ current.append([float(raw[30:38]), float(raw[38:46]), float(raw[46:54])])
182
+ if not frames: # first frame: elements, atom names and residue names
183
+ name = raw[12:16].strip()
184
+ element = raw[76:78].strip() if len(raw) >= 78 else ""
185
+ if not element:
186
+ letters = "".join(ch for ch in name if ch.isalpha())
187
+ element = letters[:1].upper() if letters else "X"
188
+ elements.append(element[:1].upper() + element[1:].lower())
189
+ labels.append(name)
190
+ resnames.append(raw[17:20].strip())
191
+ flush()
192
+ if not frames:
193
+ raise ValueError("No ATOM/HETATM records in the PDB data")
194
+ if any(len(frame) != len(elements) for frame in frames):
195
+ raise ValueError("The models of the PDB data do not all have the same number of atoms")
196
+ if any(c is None for c in cells):
197
+ result_cell = None
198
+ elif all(c == cells[0] for c in cells):
199
+ result_cell = cells[0]
200
+ else:
201
+ result_cell = cells
202
+ return PDBTrajectory(elements, frames, result_cell, labels, resnames)
203
+
204
+
205
+
206
+ def data_path(name: str) -> Path:
207
+ """Path to a bundled example file (e.g. ``demo.cif``)."""
208
+ path = _DATA / name
209
+ if not path.is_file():
210
+ raise FileNotFoundError(
211
+ f"Bundled data file not found: {name} (looked in {_DATA})"
212
+ )
213
+ return path
214
+
215
+
216
+ def demo_cif() -> str:
217
+ """Return the bundled MOF-fragment CIF text."""
218
+ return data_path("demo.cif").read_text(encoding="utf-8")
219
+
220
+
221
+ def demo_poscar() -> str:
222
+ return data_path("demo.poscar").read_text(encoding="utf-8")
223
+
224
+
225
+ def demo_xyz() -> str:
226
+ return data_path("demo.xyz").read_text(encoding="utf-8")
227
+
228
+
229
+ def demo_traj_xyz() -> str:
230
+ """Bundled multi-frame XYZ trajectory (water bend)."""
231
+ return data_path("demo_traj.xyz").read_text(encoding="utf-8")
232
+
233
+
234
+ def demo_pdb() -> str:
235
+ return data_path("demo.pdb").read_text(encoding="utf-8")
236
+
237
+
238
+ def demo_traj_pdb() -> str:
239
+ """Bundled multi-model PDB trajectory (water bend)."""
240
+ return data_path("demo_traj.pdb").read_text(encoding="utf-8")
241
+
242
+
243
+ def demo_irmof1() -> str:
244
+ """Bundled IRMOF-1 CIF (Fm-3m, full crystal)."""
245
+ return data_path("IRMOF-1.cif").read_text(encoding="utf-8")
246
+
247
+
248
+ def demo_cubtc() -> str:
249
+ """Bundled Cu-BTC (HKUST-1) CIF."""
250
+ return data_path("Cu-BTC.cif").read_text(encoding="utf-8")
251
+
252
+
253
+ def _js_literal(value: Any) -> str:
254
+ return json.dumps(value)
255
+
256
+
257
+ class view:
258
+ """Accumulate viewer commands and embed a static WebGPU viewer in Jupyter.
259
+
260
+ Communication is one-way (Python → JS), like py3Dmol: after the cell
261
+ renders, interaction works without a live kernel.
262
+
263
+ Click an atom to show element / label / coordinates in the viewer HUD.
264
+ """
265
+
266
+ def __init__(
267
+ self,
268
+ width: int = 640,
269
+ height: int = 480,
270
+ background: str = "white",
271
+ js: Optional[str] = None,
272
+ embed: Optional[str] = None,
273
+ ) -> None:
274
+ if embed not in (None, "once", "always", "never"):
275
+ raise ValueError('embed must be "once", "always" or "never"')
276
+ self._embed = embed # None: use pyiraspa.embed_library
277
+ self.width = width
278
+ self.height = height
279
+ self._id = "iraspa_" + uuid.uuid4().hex
280
+ self._commands: list[str] = []
281
+ self._js_url = js
282
+ self._background = background
283
+
284
+ def addModel(
285
+ self,
286
+ data: Union[str, Crystal],
287
+ format: str = "cif",
288
+ name: Optional[str] = None,
289
+ ) -> "view":
290
+ """Add a new Movie. For XYZ, multi-frame files become a trajectory.
291
+
292
+ Pass a :class:`Crystal` to use native ``addCrystal`` (SymmetryKit in JS).
293
+ """
294
+ if isinstance(data, Crystal):
295
+ return self.addCrystal(data, name=name)
296
+ payload = data
297
+ fmt = format
298
+ label = name
299
+ if label is None:
300
+ self._commands.append(
301
+ f"viewer.addModel({_js_literal(payload)}, {_js_literal(fmt)});"
302
+ )
303
+ else:
304
+ self._commands.append(
305
+ f"viewer.addModel({_js_literal(payload)}, {_js_literal(fmt)}, {_js_literal(label)});"
306
+ )
307
+ return self
308
+
309
+ def addCrystal(
310
+ self,
311
+ data: Union[Crystal, Mapping[str, Any]],
312
+ name: Optional[str] = None,
313
+ ) -> "view":
314
+ """Add a crystal via native JS ``addCrystal`` (no CIF round-trip)."""
315
+ if isinstance(data, Crystal):
316
+ spec = data.to_spec()
317
+ label = name if name is not None else data.name
318
+ else:
319
+ spec = dict(data)
320
+ label = name if name is not None else spec.get("name")
321
+ if label is None:
322
+ self._commands.append(f"viewer.addCrystal({_js_literal(spec)});")
323
+ else:
324
+ self._commands.append(
325
+ f"viewer.addCrystal({_js_literal(spec)}, {_js_literal(label)});"
326
+ )
327
+ return self
328
+
329
+ def addPositions(
330
+ self,
331
+ positions: Any,
332
+ elements: Union[str, Sequence[str]],
333
+ cell: Optional[Sequence[float]] = None,
334
+ name: Optional[str] = None,
335
+ precision: str = "i16",
336
+ bonds: bool = True,
337
+ labels: Optional[Sequence[str]] = None,
338
+ max_frames: Optional[int] = None,
339
+ resnames: Optional[Sequence[str]] = None,
340
+ color: Any = None,
341
+ radius: Optional[float] = None,
342
+ ) -> "view":
343
+ """Add a Movie from an array of positions (compact: a few bytes per atom per frame).
344
+
345
+ ``positions`` has shape (frames, atoms, 3) or (atoms, 3), in Å (a numpy array or nested lists).
346
+ ``elements`` is one symbol per atom, or a single symbol for all atoms. ``cell`` is (a, b, c) or
347
+ (a, b, c, alpha, beta, gamma), or one such cell per frame (shape (frames, 3) or (frames, 6), e.g. for an
348
+ NPT simulation). ``color`` and ``radius`` (in Å) set the colour and the sphere radius of all atoms of this
349
+ movie (see :meth:`setAtomStyle` for selections); ``resnames`` are optional residue names. ``precision`` is "i16" (16-bit, resolution = extent / 65535, default)
350
+ or "f32" (32-bit floats). With ``bonds=False`` no bonds are generated (e.g. for Lennard-Jones particles).
351
+ ``max_frames`` keeps at most that number of frames, evenly spaced.
352
+ """
353
+ if precision not in ("i16", "f32"):
354
+ raise ValueError('precision must be "i16" or "f32"')
355
+ flat, shape = _flatten(positions)
356
+ if len(shape) == 2:
357
+ shape = (1,) + shape
358
+ if len(shape) != 3 or shape[2] != 3 or shape[0] == 0 or shape[1] == 0:
359
+ raise ValueError("positions must have shape (frames, atoms, 3) or (atoms, 3)")
360
+ n_frames, n_atoms = shape[0], shape[1]
361
+ if any(x != x or x in (float("inf"), float("-inf")) for x in flat):
362
+ raise ValueError("positions contains NaN or infinite values")
363
+ symbols = [elements] * n_atoms if isinstance(elements, str) else [str(e) for e in elements]
364
+ if len(symbols) != n_atoms:
365
+ raise ValueError(f"elements has {len(symbols)} entries, but there are {n_atoms} atoms")
366
+ if labels is not None and len(labels) != n_atoms:
367
+ raise ValueError(f"labels has {len(labels)} entries, but there are {n_atoms} atoms")
368
+ if resnames is not None and len(resnames) != n_atoms:
369
+ raise ValueError(f"resnames has {len(resnames)} entries, but there are {n_atoms} atoms")
370
+
371
+ def one_cell(values: Any) -> list:
372
+ out = [float(x) for x in values]
373
+ if len(out) == 3:
374
+ out += [90.0, 90.0, 90.0]
375
+ if len(out) != 6:
376
+ raise ValueError("cell must be (a, b, c) or (a, b, c, alpha, beta, gamma), or one of these per frame")
377
+ return out
378
+
379
+ cells: Any = None
380
+ if cell is not None:
381
+ cell_flat, cell_shape = _flatten(cell)
382
+ if len(cell_shape) == 1:
383
+ cells = one_cell(cell_flat)
384
+ elif len(cell_shape) == 2 and cell_shape[0] == n_frames:
385
+ width = cell_shape[1]
386
+ cells = [one_cell(cell_flat[f * width : (f + 1) * width]) for f in range(n_frames)]
387
+ else:
388
+ raise ValueError(f"cell must be one cell, or one cell for each of the {n_frames} frames")
389
+
390
+ per_frame = n_atoms * 3
391
+ if max_frames is not None and n_frames > max_frames:
392
+ if max_frames < 1:
393
+ raise ValueError("max_frames must be at least 1")
394
+ if max_frames == 1:
395
+ keep = [0]
396
+ else:
397
+ keep = sorted({round(k * (n_frames - 1) / (max_frames - 1)) for k in range(max_frames)})
398
+ flat = [x for f in keep for x in flat[f * per_frame : (f + 1) * per_frame]]
399
+ if cells is not None and isinstance(cells[0], list):
400
+ cells = [cells[f] for f in keep]
401
+ n_frames = len(keep)
402
+
403
+ spec: dict = {"elements": symbols, "frames": n_frames, "encoding": precision, "bonds": bool(bonds)}
404
+ if precision == "f32":
405
+ raw = struct.pack(f"<{len(flat)}f", *flat)
406
+ else:
407
+ origin = [min(flat[d::3]) for d in range(3)]
408
+ extent = [max(flat[d::3]) - origin[d] for d in range(3)]
409
+ scale = [e / 65535.0 if e > 0.0 else 1.0 for e in extent]
410
+ quantized = [min(65535, max(0, round((x - origin[i % 3]) / scale[i % 3]))) for i, x in enumerate(flat)]
411
+ raw = struct.pack(f"<{len(quantized)}H", *quantized)
412
+ spec["origin"] = origin
413
+ spec["scale"] = scale
414
+ spec["positions"] = base64.b64encode(raw).decode("ascii")
415
+ if cells is not None:
416
+ spec["cell"] = cells
417
+ if labels is not None:
418
+ spec["labels"] = [str(x) for x in labels]
419
+ if resnames is not None:
420
+ spec["resnames"] = [str(x) for x in resnames]
421
+ if name is None:
422
+ self._commands.append(f"viewer.addTrajectoryBinary({_js_literal(spec)});")
423
+ else:
424
+ self._commands.append(f"viewer.addTrajectoryBinary({_js_literal(spec)}, {_js_literal(name)});")
425
+ if color is not None or radius is not None:
426
+ self.setAtomStyle(color=color, radius=radius, movieIndex=-1)
427
+ return self
428
+
429
+ def setAtomStyle(
430
+ self,
431
+ *,
432
+ indices: Optional[Sequence[int]] = None,
433
+ elements: Union[None, str, Sequence[str]] = None,
434
+ resnames: Union[None, str, Sequence[str]] = None,
435
+ names: Union[None, str, Sequence[str]] = None,
436
+ color: Any = None,
437
+ radius: Optional[float] = None,
438
+ hidden: Optional[bool] = None,
439
+ movieIndex: Optional[int] = None,
440
+ ) -> "view":
441
+ """Override the colour, radius or visibility of atoms.
442
+
443
+ Selection (all given criteria must match; without any, all atoms are selected): ``indices`` (0-based atom
444
+ indices), ``elements`` ("O" or ["C", "N"]), ``resnames`` (PDB residue names) and ``names`` (atom names).
445
+ Style: ``color`` ("#rrggbb", a colour name such as "pink", or (r, g, b) in 0..1), ``radius`` (sphere radius
446
+ in Å, instead of the element radius times the style scale) and ``hidden``. The call applies to the movies
447
+ added so far: to all of them, or to ``movieIndex`` (negative counts from the last one). Later calls
448
+ override earlier ones, so a general style can be followed by a more specific one.
449
+
450
+ Example: ``v.setAtomStyle(elements="H", hidden=True)``; ``v.setAtomStyle(resnames="ALA", color="orange")``.
451
+ """
452
+ selection: dict = {}
453
+ if indices is not None:
454
+ selection["indices"] = [int(i) for i in indices]
455
+ for key, value in (("elements", elements), ("resnames", resnames), ("names", names)):
456
+ if value is not None:
457
+ selection[key] = [value] if isinstance(value, str) else [str(x) for x in value]
458
+ style: dict = {}
459
+ if color is not None:
460
+ if isinstance(color, str):
461
+ style["color"] = color
462
+ else:
463
+ rgb = [float(x) for x in color]
464
+ if len(rgb) != 3 or not all(0.0 <= x <= 1.0 for x in rgb):
465
+ raise ValueError("color must be a string or (r, g, b) with values between 0 and 1")
466
+ style["color"] = rgb
467
+ if radius is not None:
468
+ if not float(radius) > 0.0:
469
+ raise ValueError("radius must be positive")
470
+ style["radius"] = float(radius)
471
+ if hidden is not None:
472
+ style["hidden"] = bool(hidden)
473
+ if not style:
474
+ raise ValueError("setAtomStyle: give at least one of color, radius and hidden")
475
+ args = f"{_js_literal(selection)}, {_js_literal(style)}"
476
+ if movieIndex is not None:
477
+ args += f", {int(movieIndex)}"
478
+ self._commands.append(f"viewer.setAtomStyle({args});")
479
+ return self
480
+
481
+ def addTrajectory(
482
+ self,
483
+ data: str,
484
+ format: str = "xyz",
485
+ name: Optional[str] = None,
486
+ compact: bool = False,
487
+ elements: Union[None, str, Sequence[str]] = None,
488
+ bonds: bool = True,
489
+ precision: str = "i16",
490
+ max_frames: Optional[int] = None,
491
+ color: Any = None,
492
+ radius: Optional[float] = None,
493
+ ) -> "view":
494
+ """Add a Movie from multi-frame XYZ/PDB (or a single-frame other format).
495
+
496
+ With ``compact=True`` (PDB only) the file is read in Python and stored as a compact array of positions
497
+ (see :meth:`addPositions`): about ten times smaller in the notebook than the PDB text. ``elements``
498
+ then optionally overrides the elements of the file (one symbol for all atoms, or one per atom), and
499
+ ``bonds``, ``precision`` and ``max_frames`` are passed on. A cell that changes from model to model
500
+ (CRYST1 records, e.g. NPT) is kept per frame. ``color`` and ``radius`` (Å) set the colour and sphere
501
+ radius of all atoms of this movie (also without ``compact``).
502
+ """
503
+ if compact:
504
+ if format.lower() != "pdb":
505
+ raise ValueError("compact=True is only available for the pdb format")
506
+ pdb = read_pdb_trajectory(data)
507
+ return self.addPositions(
508
+ pdb.positions,
509
+ pdb.elements if elements is None else elements,
510
+ cell=pdb.cell,
511
+ name=name,
512
+ precision=precision,
513
+ bonds=bonds,
514
+ labels=pdb.labels,
515
+ max_frames=max_frames,
516
+ resnames=pdb.resnames,
517
+ color=color,
518
+ radius=radius,
519
+ )
520
+ if name is None:
521
+ self._commands.append(
522
+ f"viewer.addTrajectory({_js_literal(data)}, {_js_literal(format)});"
523
+ )
524
+ else:
525
+ self._commands.append(
526
+ f"viewer.addTrajectory({_js_literal(data)}, {_js_literal(format)}, {_js_literal(name)});"
527
+ )
528
+ if color is not None or radius is not None:
529
+ self.setAtomStyle(color=color, radius=radius, movieIndex=-1)
530
+ return self
531
+
532
+ def addFrame(self, data: str, format: str = "cif", movieIndex: Optional[int] = None) -> "view":
533
+ """Append a frame to the last movie (or movieIndex)."""
534
+ if movieIndex is None:
535
+ self._commands.append(
536
+ f"viewer.addFrame({_js_literal(data)}, {_js_literal(format)});"
537
+ )
538
+ else:
539
+ self._commands.append(
540
+ f"viewer.addFrame({_js_literal(data)}, {_js_literal(format)}, {int(movieIndex)});"
541
+ )
542
+ return self
543
+
544
+ def addScene(self, name: Optional[str] = None) -> "view":
545
+ """Start a new Scene (collage row)."""
546
+ if name is None:
547
+ self._commands.append("viewer.addScene();")
548
+ else:
549
+ self._commands.append(f"viewer.addScene({_js_literal(name)});")
550
+ return self
551
+
552
+ def arrangeCollage(self, gap: float = 3.0) -> "view":
553
+ """Place movies side-by-side (scenes as rows) by setting origins."""
554
+ self._commands.append(f"viewer.arrangeCollage({float(gap)});")
555
+ return self
556
+
557
+ def setFrame(self, index: int) -> "view":
558
+ """Sync selected frame index across all movies."""
559
+ self._commands.append(f"viewer.setFrame({int(index)});")
560
+ return self
561
+
562
+ def setPlaybackControls(self, on: bool = True) -> "view":
563
+ """Show Play/Stop, step buttons, loop, and frame timeline slider."""
564
+ self._commands.append(
565
+ f"viewer.setPlaybackControls({'true' if on else 'false'});"
566
+ )
567
+ return self
568
+
569
+ def setFPS(self, fps: float) -> "view":
570
+ self._commands.append(f"viewer.setFPS({float(fps)});")
571
+ return self
572
+
573
+ def setLoop(self, on: bool = True) -> "view":
574
+ self._commands.append(f"viewer.setLoop({'true' if on else 'false'});")
575
+ return self
576
+
577
+ def stepFrame(self, delta: int = 1) -> "view":
578
+ self._commands.append(f"viewer.stepFrame({int(delta)});")
579
+ return self
580
+
581
+ def play(self) -> "view":
582
+ self._commands.append("viewer.play();")
583
+ return self
584
+
585
+ def stop(self) -> "view":
586
+ self._commands.append("viewer.stop();")
587
+ return self
588
+
589
+ def addOscillatingMovie(
590
+ self,
591
+ data: str,
592
+ format: str = "cif",
593
+ frames: int = 24,
594
+ amplitude: float = 0.4,
595
+ name: Optional[str] = None,
596
+ ) -> "view":
597
+ """Add a Movie with a sine-displaced trajectory (visible motion for demos)."""
598
+ opts: dict[str, Any] = {"frames": int(frames), "amplitude": float(amplitude)}
599
+ if name is not None:
600
+ opts["name"] = name
601
+ self._commands.append(
602
+ f"viewer.addOscillatingMovie({_js_literal(data)}, {_js_literal(format)}, {_js_literal(opts)});"
603
+ )
604
+ return self
605
+
606
+ def setMovieOrigin(self, movieIndex: int, x: float, y: float, z: float) -> "view":
607
+ self._commands.append(
608
+ f"viewer.setMovieOrigin({int(movieIndex)}, {float(x)}, {float(y)}, {float(z)});"
609
+ )
610
+ return self
611
+
612
+ def setStyle(self, style: Mapping[str, Any]) -> "view":
613
+ self._commands.append(f"viewer.setStyle({_js_literal(dict(style))});")
614
+ return self
615
+
616
+ def setRepresentationStyle(self, style: str = "fancy") -> "view":
617
+ """iRASPA preset: ``default`` | ``fancy`` (VDW+AO) | ``licorice``."""
618
+ self._commands.append(f"viewer.setRepresentationStyle({_js_literal(style)});")
619
+ return self
620
+
621
+ def addUnitCell(self) -> "view":
622
+ self._commands.append("viewer.addUnitCell();")
623
+ return self
624
+
625
+ def setUnitCell(self, on: bool = True) -> "view":
626
+ self._commands.append(f"viewer.setUnitCell({'true' if on else 'false'});")
627
+ return self
628
+
629
+ def setUnitCellScale(self, scale: float = 1.0) -> "view":
630
+ """iRASPA unitCellScaleFactor — thickness of the cell frame."""
631
+ self._commands.append(f"viewer.setUnitCellScale({float(scale)});")
632
+ return self
633
+
634
+ def setReplicas(
635
+ self,
636
+ nx: int,
637
+ ny: int,
638
+ nz: int,
639
+ allModels: bool = False,
640
+ ) -> "view":
641
+ """iRASPA-QT display replicas (n×m×p view copies; does not bake a supercell)."""
642
+ self._commands.append(
643
+ f"viewer.setReplicas({int(nx)}, {int(ny)}, {int(nz)}, "
644
+ f"{'true' if allModels else 'false'});"
645
+ )
646
+ return self
647
+
648
+ def replicateUnitCell(
649
+ self,
650
+ nx: int = 1,
651
+ ny: int = 1,
652
+ nz: int = 1,
653
+ allModels: bool = False,
654
+ ) -> "view":
655
+ """Alias for :meth:`setReplicas` (py3Dmol-style name)."""
656
+ return self.setReplicas(nx, ny, nz, allModels=allModels)
657
+
658
+ def setReplicaRange(
659
+ self,
660
+ min_ijk: tuple[int, int, int],
661
+ max_ijk: tuple[int, int, int],
662
+ allModels: bool = False,
663
+ ) -> "view":
664
+ """Inclusive replica range per axis (negative indices allowed)."""
665
+ mn = ",".join(str(int(x)) for x in min_ijk)
666
+ mx = ",".join(str(int(x)) for x in max_ijk)
667
+ self._commands.append(
668
+ f"viewer.setReplicaRange([{mn}], [{mx}], "
669
+ f"{'true' if allModels else 'false'});"
670
+ )
671
+ return self
672
+
673
+ def replicate(
674
+ self,
675
+ nx: int,
676
+ ny: int,
677
+ nz: int,
678
+ allModels: bool = False,
679
+ ) -> "view":
680
+ """Bake an n×m×p supercell (expands lattice; resets display replicas)."""
681
+ self._commands.append(
682
+ f"viewer.replicate({int(nx)}, {int(ny)}, {int(nz)}, "
683
+ f"{'true' if allModels else 'false'});"
684
+ )
685
+ return self
686
+
687
+ def setBackground(self, color: str) -> "view":
688
+ self._background = color
689
+ self._commands.append(f"viewer.setBackground({_js_literal(color)});")
690
+ return self
691
+
692
+ def setOrthographic(self, on: bool = True) -> "view":
693
+ self._commands.append(f"viewer.setOrthographic({'true' if on else 'false'});")
694
+ return self
695
+
696
+ def setHideHydrogens(self, on: bool = True) -> "view":
697
+ self._commands.append(f"viewer.setHideHydrogens({'true' if on else 'false'});")
698
+ return self
699
+
700
+ def setAxes(self, on: bool = True) -> "view":
701
+ """Show/hide the global XYZ orientation widget (off by default)."""
702
+ self._commands.append(f"viewer.setAxes({'true' if on else 'false'});")
703
+ return self
704
+
705
+ def setCellAxes(self, on: bool = True) -> "view":
706
+ """Draw RGB a/b/c axes from each structure cell origin."""
707
+ self._commands.append(f"viewer.setCellAxes({'true' if on else 'false'});")
708
+ return self
709
+
710
+ def setToolbar(self, on: bool = True) -> "view":
711
+ """Show Measure / AO / PNG / XYZ / CIF toolbar."""
712
+ self._commands.append(f"viewer.setToolbar({'true' if on else 'false'});")
713
+ return self
714
+
715
+ def setAmbientOcclusion(
716
+ self, on: bool = True, quality: str = "medium"
717
+ ) -> "view":
718
+ """Enable iRASPA-style object-space ambient occlusion (low|medium|high)."""
719
+ self._commands.append(
720
+ f"viewer.setAmbientOcclusion({'true' if on else 'false'}, {_js_literal(quality)});"
721
+ )
722
+ return self
723
+
724
+ def setHDR(
725
+ self,
726
+ on: bool = True,
727
+ exposure: float | None = None,
728
+ bonds: bool | None = None,
729
+ ) -> "view":
730
+ """iRASPA HDR tone map (default/licorice on @ 1.5; Fancy off)."""
731
+ opts: list[str] = []
732
+ if exposure is not None:
733
+ opts.append(f"exposure: {float(exposure)}")
734
+ if bonds is not None:
735
+ opts.append(f"bonds: {'true' if bonds else 'false'}")
736
+ opt_js = ("{ " + ", ".join(opts) + " }") if opts else "undefined"
737
+ self._commands.append(
738
+ f"viewer.setHDR({'true' if on else 'false'}, {opt_js});"
739
+ )
740
+ return self
741
+
742
+ def setIsosurface(
743
+ self,
744
+ isolevel: float | None = None,
745
+ opacity: float | None = None,
746
+ color: str | None = None,
747
+ color_back: str | None = None,
748
+ visible: bool | None = None,
749
+ all_frames: bool = False,
750
+ ) -> "view":
751
+ """Configure CUBE/CHGCAR isosurface (opacity&lt;1 → transparent dual-cull)."""
752
+ opts: list[str] = []
753
+ if isolevel is not None:
754
+ opts.append(f"isolevel: {float(isolevel)}")
755
+ if opacity is not None:
756
+ opts.append(f"opacity: {float(opacity)}")
757
+ if color is not None:
758
+ opts.append(f"color: {_js_literal(color)}")
759
+ if color_back is not None:
760
+ opts.append(f"colorBack: {_js_literal(color_back)}")
761
+ if visible is not None:
762
+ opts.append(f"visible: {'true' if visible else 'false'}")
763
+ if all_frames:
764
+ opts.append("all: true")
765
+ opt_js = "{ " + ", ".join(opts) + " }" if opts else "{}"
766
+ self._commands.append(f"viewer.setIsosurface({opt_js});")
767
+ return self
768
+
769
+ def setMovieLabels(self, on: bool = True) -> "view":
770
+ """Show floating name labels above each movie (collage)."""
771
+ self._commands.append(f"viewer.setMovieLabels({'true' if on else 'false'});")
772
+ return self
773
+
774
+ def setMeasureMode(self, on: bool = True) -> "view":
775
+ """Enable click-two-atoms distance measurement (Å)."""
776
+ self._commands.append(f"viewer.setMeasureMode({'true' if on else 'false'});")
777
+ return self
778
+
779
+ def zoomTo(self) -> "view":
780
+ self._commands.append("viewer.zoomTo();")
781
+ return self
782
+
783
+ def clear(self) -> "view":
784
+ self._commands.append("viewer.clear();")
785
+ return self
786
+
787
+ def removeAllModels(self) -> "view":
788
+ self._commands.append("viewer.removeAllModels();")
789
+ return self
790
+
791
+ def _library_script(self) -> str:
792
+ """The library for this output: a custom URL, the embedded bundle, or nothing (reuse / CDN)."""
793
+ if self._js_url:
794
+ return f'<script src="{self._js_url}"></script>'
795
+ mode = self._embed or embed_library
796
+ if mode not in ("once", "always", "never"):
797
+ raise ValueError('pyiraspa.embed_library must be "once", "always" or "never"')
798
+ if mode == "never":
799
+ return ""
800
+ if mode == "once":
801
+ cell = _current_cell_id()
802
+ # Embed in the first viewer of the session, and again when the cell that carries the library is re-run
803
+ if _embed_state["done"] and not (cell is not None and cell == _embed_state["cell"]):
804
+ return ""
805
+ _embed_state["done"] = True
806
+ _embed_state["cell"] = cell
807
+ return _library_html()
808
+
809
+ def _repr_html_(self) -> str:
810
+ uid = self._id
811
+ cmds = "\n ".join(self._commands)
812
+ lib = self._library_script()
813
+ options = (
814
+ f"{{ width: {self.width}, height: {self.height}, background: {_js_literal(self._background)} }}"
815
+ )
816
+ return f"""
817
+ <div id="{uid}" style="width:{self.width}px;height:{self.height}px;position:relative;"></div>
818
+ {lib}
819
+ <script>
820
+ (function() {{
821
+ var el = document.getElementById("{uid}");
822
+ function fail(msg) {{
823
+ el.innerHTML = "<pre style='color:#a00;padding:8px;white-space:pre-wrap'></pre>";
824
+ el.firstChild.textContent = msg;
825
+ }}
826
+ if (!navigator.gpu) {{
827
+ fail("WebGPU is required (Chrome/Edge 113+ or Safari 18+).");
828
+ return;
829
+ }}
830
+ function start() {{
831
+ var api = window.iRASPA;
832
+ var viewer = api.createViewer ? api.createViewer("{uid}", {options}) : new api.Viewer("{uid}", {options});
833
+ viewer.ready().then(function() {{
834
+ {cmds}
835
+ }}).catch(function(err) {{ fail(String(err)); }});
836
+ }}
837
+ function missing() {{
838
+ fail("The iRASPA viewer library is not in this notebook any more, and could not be downloaded. "
839
+ + "Re-run this cell (or any cell that shows a viewer).");
840
+ }}
841
+ function fromCDN() {{
842
+ if (window.iRASPA) return start();
843
+ if (!window.__iraspaCDN) {{
844
+ window.__iraspaCDN = new Promise(function(resolve, reject) {{
845
+ var s = document.createElement("script");
846
+ s.src = {_js_literal(CDN_URL)};
847
+ s.onload = function() {{ window.iRASPA ? resolve() : reject(); }};
848
+ s.onerror = reject;
849
+ document.head.appendChild(s);
850
+ }});
851
+ }}
852
+ window.__iraspaCDN.then(start, missing);
853
+ }}
854
+ var t0 = Date.now();
855
+ (function wait() {{
856
+ if (window.iRASPA && (window.iRASPA.createViewer || window.iRASPA.Viewer)) return start();
857
+ if (window.__iraspaLoad) {{
858
+ window.__iraspaLoad.then(function() {{ window.iRASPA ? start() : fromCDN(); }}, fromCDN);
859
+ return;
860
+ }}
861
+ // Another output of this notebook may still be loading the library: wait briefly before downloading it
862
+ if (Date.now() - t0 < 2000) return setTimeout(wait, 50);
863
+ fromCDN();
864
+ }})();
865
+ }})();
866
+ </script>
867
+ """
868
+
869
+ def show(self) -> "view":
870
+ try:
871
+ from IPython.display import display
872
+
873
+ display(self)
874
+ except Exception:
875
+ pass
876
+ return self
877
+
878
+ def __repr__(self) -> str:
879
+ return f"<pyiraspa.view id={self._id} commands={len(self._commands)}>"