illustrate-py 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.
Files changed (87) hide show
  1. illustrate/__init__.py +87 -0
  2. illustrate/cli.py +382 -0
  3. illustrate/core/__init__.py +1 -0
  4. illustrate/core/geometry.py +50 -0
  5. illustrate/core/types.py +159 -0
  6. illustrate/formats/__init__.py +1 -0
  7. illustrate/formats/command_stream.py +348 -0
  8. illustrate/formats/pdb.py +290 -0
  9. illustrate/gui/__init__.py +16 -0
  10. illustrate/gui/__main__.py +7 -0
  11. illustrate/gui/actions.py +125 -0
  12. illustrate/gui/controllers/__init__.py +11 -0
  13. illustrate/gui/controllers/render.py +190 -0
  14. illustrate/gui/controllers/settings.py +203 -0
  15. illustrate/gui/controllers/structure.py +268 -0
  16. illustrate/gui/icons/icon.icns +0 -0
  17. illustrate/gui/icons/icon.png +0 -0
  18. illustrate/gui/icons/icon_256.png +0 -0
  19. illustrate/gui/image_frame.py +116 -0
  20. illustrate/gui/kit/__init__.py +62 -0
  21. illustrate/gui/kit/appearance.py +166 -0
  22. illustrate/gui/kit/buttons.py +94 -0
  23. illustrate/gui/kit/icons.py +116 -0
  24. illustrate/gui/kit/sections.py +89 -0
  25. illustrate/gui/kit/shell.py +331 -0
  26. illustrate/gui/kit/themes/__init__.py +181 -0
  27. illustrate/gui/kit/themes/dark/colors.json +70 -0
  28. illustrate/gui/kit/themes/dark/icons/check.svg +1 -0
  29. illustrate/gui/kit/themes/dark/icons/chevron-down.svg +1 -0
  30. illustrate/gui/kit/themes/dark/icons/chevron-up.svg +1 -0
  31. illustrate/gui/kit/themes/dark/icons/tab-scroll-left.svg +1 -0
  32. illustrate/gui/kit/themes/dark/icons/tab-scroll-right.svg +1 -0
  33. illustrate/gui/kit/themes/dark/theme.qss +661 -0
  34. illustrate/gui/kit/themes/light/colors.json +76 -0
  35. illustrate/gui/kit/themes/light/icons/check.svg +1 -0
  36. illustrate/gui/kit/themes/light/icons/chevron-down.svg +1 -0
  37. illustrate/gui/kit/themes/light/icons/chevron-up.svg +1 -0
  38. illustrate/gui/kit/themes/light/theme.qss +602 -0
  39. illustrate/gui/kit/themes/midnight/colors.json +70 -0
  40. illustrate/gui/kit/themes/widgets.qss +104 -0
  41. illustrate/gui/kit/toasts.py +162 -0
  42. illustrate/gui/main.py +30 -0
  43. illustrate/gui/main_window.py +887 -0
  44. illustrate/gui/panels/__init__.py +1 -0
  45. illustrate/gui/panels/outlines.py +185 -0
  46. illustrate/gui/panels/rules.py +422 -0
  47. illustrate/gui/panels/transform.py +165 -0
  48. illustrate/gui/panels/world.py +207 -0
  49. illustrate/gui/pdb_completer.py +223 -0
  50. illustrate/gui/pdb_suggestions.py +37 -0
  51. illustrate/gui/render_params.py +133 -0
  52. illustrate/gui/themes/__init__.py +5 -0
  53. illustrate/gui/themes/dark.qss +52 -0
  54. illustrate/gui/themes/light.qss +52 -0
  55. illustrate/gui/themes/theme.py +27 -0
  56. illustrate/gui/updater.py +141 -0
  57. illustrate/gui/viewport.py +569 -0
  58. illustrate/gui/widgets/__init__.py +20 -0
  59. illustrate/gui/widgets/backend_status.py +307 -0
  60. illustrate/gui/widgets/menus.py +83 -0
  61. illustrate/gui/widgets/render_bar.py +40 -0
  62. illustrate/gui/widgets/render_size_toolbar.py +319 -0
  63. illustrate/gui/widgets/sidebar.py +51 -0
  64. illustrate/gui/workers/__init__.py +70 -0
  65. illustrate/gui/workers/export.py +82 -0
  66. illustrate/gui/workers/pdb_autocomplete.py +220 -0
  67. illustrate/gui/workers/presets.py +65 -0
  68. illustrate/gui/workers/render.py +522 -0
  69. illustrate/gui/workers/settings_io.py +102 -0
  70. illustrate/gui/workers/update.py +30 -0
  71. illustrate/io/__init__.py +1 -0
  72. illustrate/io/image_export.py +119 -0
  73. illustrate/io/params_json.py +330 -0
  74. illustrate/io/preset_store.py +120 -0
  75. illustrate/io/rcsb.py +106 -0
  76. illustrate/presets.py +557 -0
  77. illustrate/rendering/__init__.py +1 -0
  78. illustrate/rendering/api.py +474 -0
  79. illustrate/rendering/kernels.py +1790 -0
  80. illustrate/rendering/numba_kernels.py +890 -0
  81. illustrate/rendering/pipeline.py +736 -0
  82. illustrate_py-0.1.0.dist-info/METADATA +94 -0
  83. illustrate_py-0.1.0.dist-info/RECORD +87 -0
  84. illustrate_py-0.1.0.dist-info/WHEEL +5 -0
  85. illustrate_py-0.1.0.dist-info/entry_points.txt +3 -0
  86. illustrate_py-0.1.0.dist-info/licenses/LICENSE +204 -0
  87. illustrate_py-0.1.0.dist-info/top_level.txt +1 -0
illustrate/__init__.py ADDED
@@ -0,0 +1,87 @@
1
+ """Render PDB structures as Goodsell-style molecular illustrations.
2
+
3
+ Start with ``render_params_from_preset`` and ``render``, then write the image
4
+ with ``export_png`` or ``export_svg``. To render one structure repeatedly,
5
+ classify it once with ``load_pdb`` and use ``prepare_render_session``.
6
+ """
7
+
8
+ from illustrate.io.rcsb import fetch_pdb
9
+ from illustrate.formats.command_stream import (
10
+ ParseError,
11
+ parse_command_file,
12
+ parse_command_stream,
13
+ )
14
+ from illustrate.formats.pdb import load_pdb, read_and_classify_atoms
15
+ from illustrate.rendering.api import (
16
+ estimate_render_size,
17
+ prepare_render_session,
18
+ render,
19
+ render_from_atoms,
20
+ render_from_command_file,
21
+ RenderSession,
22
+ resolve_render_backend,
23
+ )
24
+ from illustrate.io.params_json import (
25
+ PARAMS_JSON_VERSION,
26
+ params_from_json,
27
+ params_to_json,
28
+ )
29
+ from illustrate.io.image_export import (
30
+ export_png,
31
+ export_svg,
32
+ to_rgba,
33
+ write_p3_pnm,
34
+ write_png,
35
+ write_svg,
36
+ )
37
+ from illustrate.core.types import (
38
+ AtomTable,
39
+ OutlineParams,
40
+ RenderParams,
41
+ RenderResult,
42
+ SelectionRule,
43
+ Transform,
44
+ WorldParams,
45
+ )
46
+ from illustrate.presets import (
47
+ PRESET_NAMES,
48
+ default_rules,
49
+ preset_library,
50
+ render_params_from_preset,
51
+ )
52
+
53
+ __all__ = [
54
+ "AtomTable",
55
+ "fetch_pdb",
56
+ "OutlineParams",
57
+ "RenderParams",
58
+ "RenderResult",
59
+ "RenderSession",
60
+ "SelectionRule",
61
+ "Transform",
62
+ "WorldParams",
63
+ "load_pdb",
64
+ "parse_command_file",
65
+ "parse_command_stream",
66
+ "prepare_render_session",
67
+ "ParseError",
68
+ "read_and_classify_atoms",
69
+ "render",
70
+ "render_from_atoms",
71
+ "render_from_command_file",
72
+ "resolve_render_backend",
73
+ "estimate_render_size",
74
+ "PARAMS_JSON_VERSION",
75
+ "params_to_json",
76
+ "params_from_json",
77
+ "write_p3_pnm",
78
+ "write_png",
79
+ "write_svg",
80
+ "export_png",
81
+ "export_svg",
82
+ "to_rgba",
83
+ "PRESET_NAMES",
84
+ "default_rules",
85
+ "preset_library",
86
+ "render_params_from_preset",
87
+ ]
illustrate/cli.py ADDED
@@ -0,0 +1,382 @@
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import re
5
+ import sys
6
+ from importlib import metadata
7
+ from pathlib import Path
8
+ from typing import Annotated
9
+
10
+ import typer
11
+
12
+ from illustrate.core.types import AtomTable, RenderParams, RenderResult
13
+ from illustrate.formats.command_stream import parse_command_stream
14
+ from illustrate.formats.pdb import read_and_classify_atoms
15
+ from illustrate.io.image_export import export_png, export_svg
16
+ from illustrate.io.params_json import params_from_json, params_to_json
17
+ from illustrate.io.rcsb import fetch_pdb
18
+ from illustrate.presets import PRESET_NAMES, render_params_from_preset
19
+ from illustrate.rendering.api import (
20
+ estimate_render_size,
21
+ max_render_scale,
22
+ render,
23
+ render_from_atoms,
24
+ resolve_command_pdb_path,
25
+ )
26
+ from illustrate.rendering.pipeline import MAX_IMAGE_DIMENSION
27
+
28
+ # Blank margin, in pixels, that an auto-sized image keeps around the structure.
29
+ _AUTO_PAD = 30
30
+ _MIN_IMAGE_DIMENSION = 100
31
+ _PDB_ID = re.compile(r"[A-Za-z0-9]{4}")
32
+ _ROTATION = re.compile(r"([xyzXYZ])=([-+]?(?:\d+\.?\d*|\.\d+))")
33
+ _FORMATS = (".png", ".svg")
34
+
35
+ app = typer.Typer(
36
+ add_completion=True,
37
+ context_settings={"help_option_names": ["-h", "--help"]},
38
+ rich_markup_mode=None,
39
+ )
40
+
41
+
42
+ class _CliError(Exception):
43
+ """A problem to report to the user without a traceback."""
44
+
45
+
46
+ def _show_version(value: bool) -> None:
47
+ if value:
48
+ typer.echo(metadata.version("illustrate-py"))
49
+ raise typer.Exit()
50
+
51
+
52
+ def _show_presets(value: bool) -> None:
53
+ if value:
54
+ for name in PRESET_NAMES:
55
+ typer.echo(name)
56
+ raise typer.Exit()
57
+
58
+
59
+ def _preset_name(name: str) -> str:
60
+ for known in PRESET_NAMES:
61
+ if known.casefold() == name.strip().casefold():
62
+ return known
63
+ raise _CliError(f"unknown preset {name!r}; choose one of: {', '.join(PRESET_NAMES)}")
64
+
65
+
66
+ def _parse_rotations(values: list[str]) -> list[tuple[str, float]]:
67
+ rotations: list[tuple[str, float]] = []
68
+ for value in values:
69
+ for part in value.split(","):
70
+ match = _ROTATION.fullmatch(part.strip())
71
+ if match is None:
72
+ raise _CliError(f"cannot read rotation {part!r}; write it as x=30, y=-45 or z=90")
73
+ rotations.append((match.group(1).lower(), float(match.group(2))))
74
+ return rotations
75
+
76
+
77
+ def _structure_path(structure: str) -> Path:
78
+ """Use an existing local file before treating the argument as an RCSB ID."""
79
+ path = Path(structure).expanduser()
80
+ if path.is_file():
81
+ return path
82
+ if _PDB_ID.fullmatch(structure) is None:
83
+ raise _CliError(f"{structure}: no such file, and not a four-character PDB ID")
84
+ try:
85
+ return fetch_pdb(structure)
86
+ except (FileNotFoundError, ConnectionError) as exc:
87
+ raise _CliError(f"{structure}: {exc}") from exc
88
+
89
+
90
+ def _fit_to_size(
91
+ atoms: AtomTable, params: RenderParams, width: int | None, height: int | None
92
+ ) -> None:
93
+ """Set the scale for the supplied pixel bounds, allowing for auto-frame padding."""
94
+ params.world.width = params.world.height = 0
95
+ limit = max_render_scale(params.rules)
96
+ params.transform.scale = min(params.transform.scale, limit)
97
+ frame = 2 * _AUTO_PAD
98
+ # Recompute after resizing because the renderer rounds dimensions to even pixels.
99
+ for _ in range(3):
100
+ bare_width, bare_height = estimate_render_size(atoms, params)
101
+ if bare_width <= 0 or bare_height <= 0:
102
+ raise _CliError("the selection rules leave no atoms to fit")
103
+ factors = [
104
+ (target - frame) / bare
105
+ for target, bare in ((width, bare_width), (height, bare_height))
106
+ if target is not None
107
+ ]
108
+ params.transform.scale = min(params.transform.scale * min(factors), limit)
109
+ if params.transform.scale >= limit:
110
+ break
111
+ params.world.width = params.world.height = -_AUTO_PAD
112
+
113
+
114
+ def _write_image(path: Path, result: RenderResult, *, transparent: bool) -> None:
115
+ opacity = result.opacity if transparent else None
116
+ try:
117
+ path.parent.mkdir(parents=True, exist_ok=True)
118
+ if path.suffix.lower() == ".svg":
119
+ export_svg(path, result.rgb, opacity)
120
+ else:
121
+ export_png(path, result.rgb, opacity)
122
+ except OSError as exc:
123
+ raise _CliError(f"cannot write {path}: {exc}") from exc
124
+
125
+
126
+ def _image_path(path: Path) -> Path:
127
+ if path.suffix == "":
128
+ return path.with_suffix(".png")
129
+ if path.suffix.lower() not in _FORMATS:
130
+ raise _CliError(f"{path}: output must be a .png or .svg file")
131
+ return path
132
+
133
+
134
+ def _render_command_file(
135
+ command_file: Path, output: Path | None, *, backend: str | None, strict: bool, transparent: bool
136
+ ) -> None:
137
+ """Render an original Illustrate command file (``-`` reads it from standard input)."""
138
+ from_stdin = str(command_file) == "-"
139
+ try:
140
+ text = sys.stdin.read() if from_stdin else command_file.read_text(encoding="utf-8")
141
+ except (OSError, UnicodeDecodeError) as exc:
142
+ raise _CliError(f"cannot read command file {command_file}: {exc}") from exc
143
+ try:
144
+ program = parse_command_stream(text, strict_input=strict)
145
+ if program.pdb_file is None:
146
+ raise _CliError("the command file has no read card naming a PDB file")
147
+ target = output if output is not None else program.output_file
148
+ if target is None:
149
+ raise _CliError("the command file has no calculate card; name the image with --output")
150
+ pdb_path = resolve_command_pdb_path(
151
+ program.pdb_file, base_dir=None if from_stdin else command_file.parent
152
+ )
153
+ if not pdb_path.is_file():
154
+ raise _CliError(f"{pdb_path}: PDB file named by the command file was not found")
155
+ # The original program wrote PNM; this renderer writes PNG in its place.
156
+ if output is None:
157
+ target = target.with_suffix(".png")
158
+ target = _image_path(target)
159
+ atoms = read_and_classify_atoms(pdb_path, program.selection_rules, strict_input=strict)
160
+ result = render(program, atoms, backend=backend)
161
+ except (RuntimeError, TypeError, ValueError, OSError) as exc:
162
+ raise _CliError(f"{command_file}: {exc}") from exc
163
+ for warning in program.warnings:
164
+ typer.echo(f"warning: {warning}", err=True)
165
+ _write_image(target, result, transparent=transparent)
166
+ typer.echo(f"{target} {result.width}x{result.height}")
167
+
168
+
169
+ @app.command(
170
+ epilog="STRUCTURES are PDB files or four-character PDB IDs, which are downloaded from RCSB."
171
+ )
172
+ def render_structures(
173
+ structures: Annotated[
174
+ list[str] | None,
175
+ typer.Argument(metavar="STRUCTURES...", show_default=False, help="PDB files or PDB IDs."),
176
+ ] = None,
177
+ output: Annotated[
178
+ Path | None,
179
+ typer.Option("--output", "-o", help="Image to write (.png or .svg), for a single structure."),
180
+ ] = None,
181
+ outdir: Annotated[
182
+ Path | None, typer.Option("--outdir", help="Directory for the images. Default: here.")
183
+ ] = None,
184
+ image_format: Annotated[
185
+ str, typer.Option("--format", help="Image format when --output is not given: png or svg.")
186
+ ] = "png",
187
+ preset: Annotated[
188
+ str | None, typer.Option("--preset", help="Built-in look; see --list-presets.")
189
+ ] = None,
190
+ settings: Annotated[
191
+ Path | None,
192
+ typer.Option("--settings", help="Settings JSON saved from the GUI or by --save-settings."),
193
+ ] = None,
194
+ rotate: Annotated[
195
+ list[str] | None,
196
+ typer.Option(
197
+ "--rotate",
198
+ help="Rotations in degrees, such as x=30,y=-45. The last one listed turns the structure first. May be repeated.",
199
+ ),
200
+ ] = None,
201
+ scale: Annotated[
202
+ float | None, typer.Option("--scale", min=0.01, help="Pixels per ångström.")
203
+ ] = None,
204
+ width: Annotated[
205
+ int | None,
206
+ typer.Option(
207
+ "--width",
208
+ min=_MIN_IMAGE_DIMENSION,
209
+ max=MAX_IMAGE_DIMENSION,
210
+ help="Scale the structure so the image is this many pixels wide.",
211
+ ),
212
+ ] = None,
213
+ height: Annotated[
214
+ int | None,
215
+ typer.Option(
216
+ "--height",
217
+ min=_MIN_IMAGE_DIMENSION,
218
+ max=MAX_IMAGE_DIMENSION,
219
+ help="Scale the structure so the image is this many pixels tall.",
220
+ ),
221
+ ] = None,
222
+ transparent: Annotated[
223
+ bool, typer.Option("--transparent", help="Make the background transparent.")
224
+ ] = False,
225
+ save_settings: Annotated[
226
+ bool,
227
+ typer.Option("--save-settings", help="Also write the settings used, as a .json beside each image."),
228
+ ] = False,
229
+ backend: Annotated[
230
+ str | None,
231
+ typer.Option("--backend", help="Renderer backend: numba, numpy or mlx. Default: best available."),
232
+ ] = None,
233
+ command_file: Annotated[
234
+ Path | None,
235
+ typer.Option(
236
+ "--command-file",
237
+ help="Render an original Illustrate command file instead (- for standard input).",
238
+ ),
239
+ ] = None,
240
+ strict: Annotated[
241
+ bool, typer.Option("--strict", help="Reject malformed PDB or command-file lines.")
242
+ ] = False,
243
+ list_presets: Annotated[
244
+ bool,
245
+ typer.Option("--list-presets", callback=_show_presets, is_eager=True, help="List the presets and exit."),
246
+ ] = False,
247
+ version: Annotated[
248
+ bool,
249
+ typer.Option("--version", callback=_show_version, is_eager=True, help="Print the version and exit."),
250
+ ] = False,
251
+ ) -> None:
252
+ """Render PDB structures as Illustrate-style figures."""
253
+ del list_presets, version
254
+ try:
255
+ failures = _render_all(
256
+ structures or [],
257
+ output=output,
258
+ outdir=outdir,
259
+ image_format=image_format,
260
+ preset=preset,
261
+ settings=settings,
262
+ rotate=rotate or [],
263
+ scale=scale,
264
+ width=width,
265
+ height=height,
266
+ transparent=transparent,
267
+ save_settings=save_settings,
268
+ backend=backend,
269
+ command_file=command_file,
270
+ strict=strict,
271
+ )
272
+ except _CliError as exc:
273
+ typer.echo(f"error: {exc}", err=True)
274
+ raise typer.Exit(2) from exc
275
+ if failures:
276
+ raise typer.Exit(1)
277
+
278
+
279
+ def _render_all(
280
+ structures: list[str],
281
+ *,
282
+ output: Path | None,
283
+ outdir: Path | None,
284
+ image_format: str,
285
+ preset: str | None,
286
+ settings: Path | None,
287
+ rotate: list[str],
288
+ scale: float | None,
289
+ width: int | None,
290
+ height: int | None,
291
+ transparent: bool,
292
+ save_settings: bool,
293
+ backend: str | None,
294
+ command_file: Path | None,
295
+ strict: bool,
296
+ ) -> int:
297
+ """Render the requested inputs and count failures in a multi-structure batch.
298
+
299
+ Invalid requests and single-input failures are raised to the CLI handler.
300
+ """
301
+ fit = width is not None or height is not None
302
+ if command_file is not None:
303
+ look = structures or preset or settings or rotate or scale is not None or fit
304
+ if look or outdir is not None or save_settings:
305
+ raise _CliError(
306
+ "--command-file takes its structure and look from the file; "
307
+ "only --output, --transparent, --backend and --strict apply"
308
+ )
309
+ _render_command_file(
310
+ command_file, output, backend=backend, strict=strict, transparent=transparent
311
+ )
312
+ return 0
313
+
314
+ if preset is not None and settings is not None:
315
+ raise _CliError("use either --preset or --settings, not both")
316
+ if scale is not None and fit:
317
+ raise _CliError("use either --scale or --width/--height, not both")
318
+ suffix = f".{image_format.lower().lstrip('.')}"
319
+ if suffix not in _FORMATS:
320
+ raise _CliError(f"--format must be png or svg, not {image_format!r}")
321
+ rotations = _parse_rotations(rotate)
322
+
323
+ if settings is not None:
324
+ try:
325
+ base = params_from_json(settings.read_text(encoding="utf-8"))
326
+ except (OSError, TypeError, ValueError) as exc:
327
+ raise _CliError(f"cannot read settings {settings}: {exc}") from exc
328
+ if not structures and base.pdb_path:
329
+ structures = [base.pdb_path]
330
+ else:
331
+ base = render_params_from_preset(_preset_name(preset or "Default"), "")
332
+ if not structures:
333
+ raise _CliError("name at least one PDB file or PDB ID (see --help)")
334
+
335
+ if output is not None:
336
+ if len(structures) > 1 or outdir is not None:
337
+ raise _CliError("--output names one image; use --outdir for several structures")
338
+ targets = [_image_path(output)]
339
+ else:
340
+ targets = [(outdir or Path()) / f"{Path(item).stem}{suffix}" for item in structures]
341
+ if len(set(targets)) < len(targets):
342
+ raise _CliError("two structures would write the same image; render them separately")
343
+
344
+ failures = 0
345
+ for structure, target in zip(structures, targets):
346
+ try:
347
+ path = _structure_path(structure)
348
+ params = copy.deepcopy(base)
349
+ params.pdb_path = str(path)
350
+ params.transform.rotations.extend(rotations)
351
+ if scale is not None:
352
+ params.transform.scale = scale
353
+ try:
354
+ atoms = read_and_classify_atoms(path, params.rules, strict_input=strict)
355
+ if fit:
356
+ _fit_to_size(atoms, params, width, height)
357
+ result = render_from_atoms(atoms, params, backend=backend)
358
+ except (RuntimeError, TypeError, ValueError, OSError) as exc:
359
+ raise _CliError(f"{structure}: {exc}") from exc
360
+ _write_image(target, result, transparent=transparent)
361
+ if save_settings:
362
+ target.with_suffix(".json").write_text(params_to_json(params), encoding="utf-8")
363
+ except _CliError as exc:
364
+ if len(structures) == 1:
365
+ raise
366
+ typer.echo(f"error: {exc}", err=True)
367
+ failures += 1
368
+ continue
369
+ typer.echo(f"{target} {result.width}x{result.height}")
370
+ return failures
371
+
372
+
373
+ def main(argv: list[str] | None = None) -> int:
374
+ try:
375
+ app(args=argv, prog_name="illustrate-py")
376
+ except SystemExit as exc:
377
+ return exc.code if isinstance(exc.code, int) else int(exc.code is not None)
378
+ return 0
379
+
380
+
381
+ if __name__ == "__main__":
382
+ raise SystemExit(main())
@@ -0,0 +1 @@
1
+ """Core data contracts and shared geometry helpers."""
@@ -0,0 +1,50 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+
5
+ import numpy as np
6
+ from numpy.typing import NDArray
7
+
8
+
9
+ def catenate(m1: NDArray[np.float32], m2: NDArray[np.float32]) -> NDArray[np.float32]:
10
+ """Compose two 4×4 matrices as ``m2 @ m1`` using Fortran accumulation order."""
11
+ out = np.zeros((4, 4), dtype=np.float32)
12
+ for i in range(4):
13
+ for j in range(4):
14
+ total = 0.0
15
+ for k in range(4):
16
+ total += float(m1[k, j]) * float(m2[i, k])
17
+ out[i, j] = np.float32(total)
18
+ return out
19
+
20
+
21
+ def rotation_x(angle_degrees: float) -> NDArray[np.float32]:
22
+ m = np.eye(4, dtype=np.float32)
23
+ angle = -angle_degrees * math.pi / 180.0
24
+ m[1, 1] = np.float32(math.cos(angle))
25
+ m[1, 2] = np.float32(-math.sin(angle))
26
+ m[2, 1] = np.float32(math.sin(angle))
27
+ m[2, 2] = np.float32(math.cos(angle))
28
+ return m
29
+
30
+
31
+ def rotation_y(angle_degrees: float) -> NDArray[np.float32]:
32
+ m = np.eye(4, dtype=np.float32)
33
+ angle = -angle_degrees * math.pi / 180.0
34
+ m[0, 0] = np.float32(math.cos(angle))
35
+ m[0, 2] = np.float32(math.sin(angle))
36
+ m[2, 0] = np.float32(-math.sin(angle))
37
+ m[2, 2] = np.float32(math.cos(angle))
38
+ return m
39
+
40
+
41
+ def rotation_z(angle_degrees: float) -> NDArray[np.float32]:
42
+ m = np.eye(4, dtype=np.float32)
43
+ angle = -angle_degrees * math.pi / 180.0
44
+ m[0, 0] = np.float32(math.cos(angle))
45
+ m[0, 1] = np.float32(-math.sin(angle))
46
+ m[1, 0] = np.float32(math.sin(angle))
47
+ m[1, 1] = np.float32(math.cos(angle))
48
+ return m
49
+
50
+
@@ -0,0 +1,159 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+ from numpy.typing import NDArray
8
+
9
+
10
+ @dataclass(slots=True)
11
+ class SelectionRule:
12
+ """Atom style for a fixed-column PDB pattern and inclusive residue range.
13
+
14
+ The descriptor covers PDB columns 13–22, with a hyphen matching any
15
+ character in its column. The first match supplies RGB values and a radius
16
+ in ångströms. A zero radius hides the atom.
17
+ """
18
+
19
+ record_name: str
20
+ descriptor: str
21
+ res_low: int
22
+ res_high: int
23
+ color: tuple[float, float, float]
24
+ radius: float
25
+
26
+
27
+ @dataclass(slots=True)
28
+ class WorldParams:
29
+ """Canvas, background, fog, and shadow settings for a render.
30
+
31
+ Two positive dimensions fix the canvas size in pixels, capped at 3000 and
32
+ rounded down to even values. With auto-centering and at least one atom,
33
+ a nonpositive dimension triggers autosizing on both axes. Zero fits the
34
+ structure bounds. A negative value adds padding per edge and a positive
35
+ value subtracts it in autosizing mode.
36
+ """
37
+
38
+ background: tuple[float, float, float] = (1.0, 1.0, 1.0)
39
+ fog_color: tuple[float, float, float] = (1.0, 1.0, 1.0)
40
+ fog_front: float = 1.0
41
+ fog_back: float = 1.0
42
+ shadows: bool = False
43
+ shadow_strength: float = 0.0023
44
+ shadow_angle: float = 2.0
45
+ shadow_min_z: float = 1.0
46
+ shadow_max_dark: float = 0.2
47
+ width: int = 0
48
+ height: int = 0
49
+
50
+
51
+ @dataclass(slots=True)
52
+ class OutlineParams:
53
+ """Thresholds for depth, subunit, and residue outlines.
54
+
55
+ When enabled, kernels 1 and 2 use a discrete Laplacian of depth for contours.
56
+ Kernels 3 and 4 use neighboring depth differences.
57
+ """
58
+
59
+ enabled: bool = False
60
+ contour_low: float = 1.0
61
+ contour_high: float = 10.0
62
+ kernel: int = 4
63
+ z_diff_min: float = 1.0
64
+ z_diff_max: float = 50.0
65
+ subunit_low: float = 3.0
66
+ subunit_high: float = 10.0
67
+ residue_low: float = 3.0
68
+ residue_high: float = 8.0
69
+ residue_diff: float = 6000.0
70
+
71
+
72
+ @dataclass(slots=True)
73
+ class TransformState:
74
+ scale: float = 1.0
75
+ xtran: float = 0.0
76
+ ytran: float = 0.0
77
+ ztran: float = 0.0
78
+ autocenter: int = 0
79
+ rm: NDArray[np.float32] = field(
80
+ default_factory=lambda: np.eye(4, dtype=np.float32),
81
+ )
82
+
83
+
84
+ @dataclass(slots=True)
85
+ class CommandProgram:
86
+ pdb_file: Path | None = None
87
+ selection_rules: list[SelectionRule] = field(default_factory=list[SelectionRule])
88
+ transform: TransformState = field(default_factory=TransformState)
89
+ world: WorldParams = field(default_factory=WorldParams)
90
+ outlines: OutlineParams = field(default_factory=OutlineParams)
91
+ output_file: Path | None = None
92
+ warnings: list[str] = field(default_factory=list[str])
93
+
94
+
95
+ @dataclass(slots=True)
96
+ class AtomTable:
97
+ """Classified coordinates and biological assembly transforms for rendering.
98
+
99
+ ``coord`` holds XYZ coordinates in ångströms, with shape ``(n + 1, 3)``.
100
+ Rows 1 through ``n`` align with ``type_idx``, ``res``, and ``su``. Row 0
101
+ is reserved, and ``type_idx`` holds 1-based indices into the original rule
102
+ list. ``biomat`` stores 3×4 assembly transforms at indices 1 through
103
+ ``nbiomat``. A count of zero renders one copy in the source coordinates.
104
+ """
105
+
106
+ coord: NDArray[np.float32]
107
+ type_idx: NDArray[np.int32]
108
+ res: NDArray[np.int32]
109
+ su: NDArray[np.int32]
110
+ biomat: NDArray[np.float32]
111
+ n: int
112
+ nbiomat: int
113
+
114
+
115
+ @dataclass(slots=True)
116
+ class RenderResult:
117
+ """Rendered uint8 RGB pixels and their separate uint8 opacity plane.
118
+
119
+ RGB has shape ``(height, width, 3)`` and opacity has shape
120
+ ``(height, width)``. Rows follow the renderer's X axis and columns follow
121
+ its Y axis. Opacity ranges from 0 (transparent) to 255 (opaque).
122
+ """
123
+
124
+ rgb: NDArray[np.uint8]
125
+ opacity: NDArray[np.uint8]
126
+ width: int
127
+ height: int
128
+
129
+
130
+ @dataclass(slots=True)
131
+ class Transform:
132
+ """View transform with scale in pixels per ångström.
133
+
134
+ Translation is in view coordinates and in ångströms, before scaling.
135
+ Rotations pair an axis name with an angle in degrees. The last listed
136
+ rotation acts first. Both ``auto`` and ``center`` center the structure in
137
+ X and Y. In Z, ``auto`` places the front near the origin and ``center``
138
+ centers the depth bounds. ``none`` skips automatic translation.
139
+ """
140
+
141
+ scale: float = 12.0
142
+ translate: tuple[float, float, float] = (0.0, 0.0, 0.0)
143
+ rotations: list[tuple[str, float]] = field(default_factory=list[tuple[str, float]])
144
+ autocenter: str = "auto"
145
+
146
+
147
+ @dataclass(slots=True)
148
+ class RenderParams:
149
+ """Everything one render needs: a PDB path, ordered selection rules, and view settings.
150
+
151
+ ``transform`` places the structure, ``world`` sets the canvas, fog and
152
+ shadows, and ``outlines`` sets the ink lines.
153
+ """
154
+
155
+ pdb_path: str
156
+ rules: list[SelectionRule]
157
+ transform: Transform = field(default_factory=Transform)
158
+ world: WorldParams = field(default_factory=WorldParams)
159
+ outlines: OutlineParams = field(default_factory=OutlineParams)
@@ -0,0 +1 @@
1
+ """File and command-stream format parsers."""