atomeye-widget 3.1.0__tar.gz

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.
@@ -0,0 +1,17 @@
1
+ # Meson build directories
2
+ /build*/
3
+ /dist/
4
+
5
+ __pycache__/
6
+ *.pyc
7
+ *.egg-info/
8
+ .DS_Store
9
+
10
+ # Meson subprojects are downloaded from their wrap files
11
+ /subprojects/*/
12
+ /subprojects/packagecache/
13
+
14
+ # built by wasm/build.sh
15
+ /wasm/python/atomeye_widget/static/
16
+ /wasm/python/dist/
17
+ /subprojects/.wraplock
@@ -0,0 +1,32 @@
1
+ MIT License
2
+
3
+ Copyright (c) 1999-2006 Ju Li
4
+ Copyright (c) 2004-2005 Futoshi Shimizu
5
+ Copyright (c) 2009-2026 James Kermode and contributors
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
24
+
25
+ -------------------------------------------------------------------------------
26
+
27
+ atomeye_widget/static/widget.js contains AtomEye compiled to WebAssembly,
28
+ together with libraries under their own licences: extxyz and libcleri (MIT),
29
+ PCRE2 (BSD), libpng, zlib and libjpeg (their own permissive licences), and
30
+ the Emscripten runtime (MIT). The X11 key symbol table in it derives from
31
+ keysymdef.h of the X11 protocol headers (MIT/X11), and the font of the
32
+ keyboard shortcuts list is the public domain X11 "fixed" font.
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.5
2
+ Name: atomeye-widget
3
+ Version: 3.1.0
4
+ Summary: AtomEye, the atomistic configuration viewer by Ju Li, as a WebAssembly notebook widget for marimo and Jupyter
5
+ Project-URL: Homepage, https://github.com/jameskermode/AtomEye
6
+ Project-URL: Issues, https://github.com/jameskermode/AtomEye/issues
7
+ Project-URL: Demo, https://jameskermode.github.io/AtomEye/
8
+ Author: Ju Li, Futoshi Shimizu, James Kermode
9
+ Maintainer: James Kermode
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: ASE,anywidget,atomistic,extxyz,jupyter,marimo,visualisation
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Environment :: WebAssembly :: Emscripten
15
+ Classifier: Framework :: Jupyter
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Topic :: Scientific/Engineering :: Chemistry
20
+ Classifier: Topic :: Scientific/Engineering :: Physics
21
+ Classifier: Topic :: Scientific/Engineering :: Visualization
22
+ Requires-Python: >=3.9
23
+ Requires-Dist: anywidget>=0.9
24
+ Requires-Dist: traitlets
25
+ Provides-Extra: ase
26
+ Requires-Dist: ase; extra == 'ase'
27
+ Requires-Dist: numpy; extra == 'ase'
28
+ Provides-Extra: test
29
+ Requires-Dist: ase; extra == 'test'
30
+ Requires-Dist: numpy; extra == 'test'
31
+ Requires-Dist: pytest; extra == 'test'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # atomeye-widget
35
+
36
+ [AtomEye](https://github.com/jameskermode/AtomEye), the atomistic
37
+ configuration viewer, as a notebook widget. The viewer itself runs in the
38
+ browser as WebAssembly, so the widget needs no compiled extension, no
39
+ display and no server-side rendering: it works in
40
+ [marimo](https://marimo.io) (including WASM notebooks), Jupyter and
41
+ anywhere else [anywidget](https://anywidget.dev) does.
42
+
43
+ pip install atomeye-widget
44
+
45
+ It is a pure Python package, so in a notebook that runs in the browser
46
+ (marimo WASM, JupyterLite, Pyodide) `micropip.install("atomeye-widget")`
47
+ installs it too.
48
+
49
+ ```python
50
+ from ase.build import bulk
51
+ from atomeye_widget import AtomEyeWidget
52
+
53
+ w = AtomEyeWidget(bulk("Si", cubic=True) * (3, 3, 3))
54
+ w # in marimo: mo.ui.anywidget(w)
55
+ ```
56
+
57
+ `AtomEyeWidget` takes an `ase.Atoms`, a list of them (a trajectory) or
58
+ Extended XYZ text. The package also registers itself as an ASE viewer:
59
+ `ase.visualize.view(atoms, viewer="atomeye_widget")` returns the widget.
60
+
61
+ - `w.frame = 5` shows another frame of a trajectory; `w.show(atoms)` shows
62
+ something new, keeping the view.
63
+ - `w.run_command("toggle_bond_mode")` runs any AtomEye command;
64
+ `w.run_script(text)` several. Per-atom arrays of the `Atoms` are
65
+ available for colouring: `w.aux_property_coloring("charge")`.
66
+ - A new view shows the atoms at a third of their usual size, with bonds,
67
+ so that the structure is visible. `AtomEyeWidget(atoms, startup="")`
68
+ gives AtomEye's own defaults (full-size atoms, no bonds), and `startup`
69
+ can be any AtomEye commands to run first, one per line.
70
+ - `w.capture()` asks the browser for a PNG, which arrives in `w.png`.
71
+
72
+ Press `?` on the view (or the "? shortcuts" button) for a list of the
73
+ keyboard and mouse controls. The mouse and keyboard work as in AtomEye on the desktop: drag to rotate,
74
+ Shift-drag to translate, wheel or right-drag to move in and out,
75
+ right-click an atom for information about it (shown under "AtomEye
76
+ output"); on a touch screen, one finger rotates, two
77
+ fingers translate, pinching moves in and out and holding a finger still
78
+ on an atom gives the information, and, after clicking on the view to give it the keyboard, the
79
+ usual keys (`b` bonds, `k` coordination colouring, `Delete`/`Insert` next
80
+ and previous frame, ...).
81
+
82
+ `examples/marimo_demo.py` in the source tree is a small marimo app; it
83
+ runs in your browser at <https://jameskermode.github.io/AtomEye/>.
84
+
85
+ The JavaScript bundle `atomeye_widget/static/widget.js` is built from the
86
+ C sources with Emscripten: see `wasm/README.md` in the source tree.
87
+
88
+ ## Credits and licence
89
+
90
+ AtomEye was written by Ju Li, with the scripting interface of AtomEye 3
91
+ by Futoshi Shimizu. If you use it in published work, please cite
92
+ J. Li, "AtomEye: an efficient atomistic configuration viewer",
93
+ Modelling Simul. Mater. Sci. Eng. 11 (2003) 173,
94
+ [doi:10.1088/0965-0393/11/2/305](https://doi.org/10.1088/0965-0393/11/2/305).
95
+ The port to the browser and this widget are by James Kermode.
96
+
97
+ MIT licence, with the permission of the original authors: see `LICENSE`.
@@ -0,0 +1,64 @@
1
+ # atomeye-widget
2
+
3
+ [AtomEye](https://github.com/jameskermode/AtomEye), the atomistic
4
+ configuration viewer, as a notebook widget. The viewer itself runs in the
5
+ browser as WebAssembly, so the widget needs no compiled extension, no
6
+ display and no server-side rendering: it works in
7
+ [marimo](https://marimo.io) (including WASM notebooks), Jupyter and
8
+ anywhere else [anywidget](https://anywidget.dev) does.
9
+
10
+ pip install atomeye-widget
11
+
12
+ It is a pure Python package, so in a notebook that runs in the browser
13
+ (marimo WASM, JupyterLite, Pyodide) `micropip.install("atomeye-widget")`
14
+ installs it too.
15
+
16
+ ```python
17
+ from ase.build import bulk
18
+ from atomeye_widget import AtomEyeWidget
19
+
20
+ w = AtomEyeWidget(bulk("Si", cubic=True) * (3, 3, 3))
21
+ w # in marimo: mo.ui.anywidget(w)
22
+ ```
23
+
24
+ `AtomEyeWidget` takes an `ase.Atoms`, a list of them (a trajectory) or
25
+ Extended XYZ text. The package also registers itself as an ASE viewer:
26
+ `ase.visualize.view(atoms, viewer="atomeye_widget")` returns the widget.
27
+
28
+ - `w.frame = 5` shows another frame of a trajectory; `w.show(atoms)` shows
29
+ something new, keeping the view.
30
+ - `w.run_command("toggle_bond_mode")` runs any AtomEye command;
31
+ `w.run_script(text)` several. Per-atom arrays of the `Atoms` are
32
+ available for colouring: `w.aux_property_coloring("charge")`.
33
+ - A new view shows the atoms at a third of their usual size, with bonds,
34
+ so that the structure is visible. `AtomEyeWidget(atoms, startup="")`
35
+ gives AtomEye's own defaults (full-size atoms, no bonds), and `startup`
36
+ can be any AtomEye commands to run first, one per line.
37
+ - `w.capture()` asks the browser for a PNG, which arrives in `w.png`.
38
+
39
+ Press `?` on the view (or the "? shortcuts" button) for a list of the
40
+ keyboard and mouse controls. The mouse and keyboard work as in AtomEye on the desktop: drag to rotate,
41
+ Shift-drag to translate, wheel or right-drag to move in and out,
42
+ right-click an atom for information about it (shown under "AtomEye
43
+ output"); on a touch screen, one finger rotates, two
44
+ fingers translate, pinching moves in and out and holding a finger still
45
+ on an atom gives the information, and, after clicking on the view to give it the keyboard, the
46
+ usual keys (`b` bonds, `k` coordination colouring, `Delete`/`Insert` next
47
+ and previous frame, ...).
48
+
49
+ `examples/marimo_demo.py` in the source tree is a small marimo app; it
50
+ runs in your browser at <https://jameskermode.github.io/AtomEye/>.
51
+
52
+ The JavaScript bundle `atomeye_widget/static/widget.js` is built from the
53
+ C sources with Emscripten: see `wasm/README.md` in the source tree.
54
+
55
+ ## Credits and licence
56
+
57
+ AtomEye was written by Ju Li, with the scripting interface of AtomEye 3
58
+ by Futoshi Shimizu. If you use it in published work, please cite
59
+ J. Li, "AtomEye: an efficient atomistic configuration viewer",
60
+ Modelling Simul. Mater. Sci. Eng. 11 (2003) 173,
61
+ [doi:10.1088/0965-0393/11/2/305](https://doi.org/10.1088/0965-0393/11/2/305).
62
+ The port to the browser and this widget are by James Kermode.
63
+
64
+ MIT licence, with the permission of the original authors: see `LICENSE`.
@@ -0,0 +1,253 @@
1
+ """AtomEye as a notebook widget.
2
+
3
+ The viewer runs in the browser as WebAssembly, so this works wherever
4
+ anywidget does - marimo (including WASM notebooks), Jupyter, VS Code -
5
+ without the compiled ``atomeye`` package or a display on the server::
6
+
7
+ from ase.build import bulk
8
+ from atomeye_widget import AtomEyeWidget
9
+
10
+ w = AtomEyeWidget(bulk("Si", cubic=True) * (3, 3, 3))
11
+ w # in marimo: mo.ui.anywidget(w)
12
+ w.run_command("toggle_bond_mode")
13
+
14
+ The mouse and the keyboard work in the widget as they do in AtomEye on
15
+ the desktop; click on it first to give it the keyboard.
16
+
17
+ AtomEye is by Ju Li, with the scripting interface of AtomEye 3 by
18
+ Futoshi Shimizu: J. Li, Modelling Simul. Mater. Sci. Eng. 11 (2003) 173.
19
+ """
20
+
21
+ import pathlib
22
+ from io import StringIO
23
+
24
+ import anywidget
25
+ import traitlets
26
+
27
+ # the version of AtomEye (meson.build) whose viewer is in static/widget.js
28
+ __version__ = "3.1.0"
29
+ __all__ = ["AtomEyeWidget", "to_extxyz", "view_atomeye_widget"]
30
+
31
+ _STATIC = pathlib.Path(__file__).parent / "static"
32
+
33
+ # ASE array names and what AtomEye calls them
34
+ _NAME_MAP = {"positions": "pos", "masses": "mass", "numbers": "Z"}
35
+
36
+
37
+ def _extxyz_frame(atoms):
38
+ """One Extended XYZ frame for an ase.Atoms, as AtomEye wants it.
39
+
40
+ The cell is padded in non-periodic directions and only per-atom arrays
41
+ the viewer can show (real, integer and logical ones) are included.
42
+ """
43
+ import numpy as np
44
+
45
+ n = len(atoms)
46
+ cell = np.array(atoms.get_cell(), dtype=float)
47
+ pbc = np.asarray(atoms.get_pbc(), dtype=bool)
48
+ pos = np.asarray(atoms.positions, dtype=float)
49
+ for i, p in enumerate(pbc):
50
+ if not p and n > 0:
51
+ extent = pos[:, i].max() - pos[:, i].min()
52
+ cell[i, i] = max(cell[i, i], max(1.0, 2 * extent))
53
+
54
+ props = ["species:S:1", "pos:R:3"]
55
+ columns = [pos]
56
+ formats = ["%.10g"] * 3
57
+ for key, value in atoms.arrays.items():
58
+ if key == "positions":
59
+ continue
60
+ name = _NAME_MAP.get(key, key)
61
+ value = np.asarray(value)
62
+ if value.ndim == 1:
63
+ value = value.reshape(n, 1)
64
+ if value.ndim != 2 or value.shape[0] != n or value.shape[1] == 0:
65
+ continue
66
+ if not name or any(c in name for c in ':= "\t\n'):
67
+ continue
68
+ kind = value.dtype.kind
69
+ if kind == "f":
70
+ code, fmt = "R", "%.10g"
71
+ elif kind in "iub":
72
+ code, fmt = "I", "%d"
73
+ value = value.astype(int)
74
+ else:
75
+ continue
76
+ props.append("%s:%s:%d" % (name, code, value.shape[1]))
77
+ columns.append(value)
78
+ formats.extend([fmt] * value.shape[1])
79
+
80
+ body = StringIO()
81
+ if n > 0:
82
+ np.savetxt(body, np.column_stack(columns), fmt=" ".join(formats))
83
+ rows = body.getvalue().splitlines()
84
+ lattice = " ".join("%.10g" % x for x in cell.ravel())
85
+ header = 'Lattice="%s" Properties=%s pbc="%s"' % (
86
+ lattice, ":".join(props), " ".join("T" if p else "F" for p in pbc))
87
+ lines = [str(n), header]
88
+ lines.extend("%s %s" % (s, row)
89
+ for s, row in zip(atoms.get_chemical_symbols(), rows))
90
+ return "\n".join(lines) + "\n"
91
+
92
+
93
+ def to_extxyz(atoms):
94
+ """Extended XYZ text and number of frames for `atoms`.
95
+
96
+ `atoms` is an ase.Atoms, a sequence of them (a trajectory), or text
97
+ that is already in Extended XYZ format.
98
+ """
99
+ if isinstance(atoms, str):
100
+ text = atoms if atoms.endswith("\n") else atoms + "\n"
101
+ return text, _count_frames(text)
102
+ if hasattr(atoms, "get_chemical_symbols"):
103
+ atoms = [atoms]
104
+ frames = [_extxyz_frame(a) for a in atoms]
105
+ if not frames:
106
+ raise ValueError("no frames to show")
107
+ return "".join(frames), len(frames)
108
+
109
+
110
+ def _count_frames(text):
111
+ lines = text.splitlines()
112
+ i = count = 0
113
+ while i < len(lines) and lines[i].strip():
114
+ try:
115
+ i += int(lines[i].split()[0]) + 2
116
+ except ValueError:
117
+ raise ValueError("not Extended XYZ text: line %d should be "
118
+ "a number of atoms" % (i + 1)) from None
119
+ count += 1
120
+ return count
121
+
122
+
123
+ class AtomEyeWidget(anywidget.AnyWidget):
124
+ """AtomEye viewer for marimo and Jupyter notebooks.
125
+
126
+ Parameters
127
+ ----------
128
+ atoms : ase.Atoms, sequence of ase.Atoms, or str
129
+ What to show: a configuration, a trajectory, or Extended XYZ text.
130
+ frame : int
131
+ Which frame of a trajectory to show first.
132
+ width, height : int
133
+ Size of the view in pixels.
134
+ commands : sequence of str
135
+ AtomEye commands to run once the configuration is shown.
136
+ startup : str, optional
137
+ AtomEye commands a new view runs before anything else, one per
138
+ line. By default the atoms are drawn at a third of their usual
139
+ size and bonds are shown; pass ``""`` for AtomEye's own defaults
140
+ (full-size atoms, no bonds).
141
+ """
142
+
143
+ _esm = _STATIC / "widget.js"
144
+
145
+ xyz = traitlets.Unicode("").tag(sync=True)
146
+ frame = traitlets.Int(0).tag(sync=True)
147
+ width = traitlets.Int(600).tag(sync=True)
148
+ height = traitlets.Int(450).tag(sync=True)
149
+ commands = traitlets.List(traitlets.Unicode()).tag(sync=True)
150
+ startup = traitlets.Unicode(None, allow_none=True).tag(sync=True)
151
+ png = traitlets.Bytes(b"").tag(sync=True)
152
+
153
+ def __init__(self, atoms=None, *, frame=0, width=600, height=450,
154
+ commands=(), startup=None, **kwargs):
155
+ super().__init__(width=width, height=height,
156
+ commands=list(commands), startup=startup, **kwargs)
157
+ self.n_frames = 0
158
+ #: (command, message) pairs the viewer has reported, mostly errors
159
+ self.messages = []
160
+ self.on_msg(self._on_message)
161
+ if atoms is not None:
162
+ self.show(atoms, frame)
163
+
164
+ def _on_message(self, _widget, content, _buffers):
165
+ if isinstance(content, dict) and content.get("type") == "message":
166
+ self.messages.append((content.get("command"),
167
+ content.get("message")))
168
+
169
+ @traitlets.validate("frame")
170
+ def _valid_frame(self, proposal):
171
+ frame = proposal["value"]
172
+ n = getattr(self, "n_frames", 0)
173
+ if n and not -n <= frame < n:
174
+ raise traitlets.TraitError(
175
+ "frame %d out of range: there are %d" % (frame, n))
176
+ return frame % n if n else frame
177
+
178
+ def show(self, atoms, frame=0):
179
+ """Show a new configuration or trajectory, keeping the view."""
180
+ text, n = to_extxyz(atoms)
181
+ if not -n <= frame < n:
182
+ raise IndexError("frame %d out of range: there are %d" % (frame, n))
183
+ self.n_frames = n
184
+ with self.hold_sync():
185
+ self.frame = frame % n
186
+ self.xyz = text
187
+
188
+ def run_command(self, command):
189
+ """Run an AtomEye command, such as ``"toggle_bond_mode"``,
190
+ ``"aux_property_coloring 0"`` or ``"rotate 0 0.1"``.
191
+
192
+ Commands run in the browser, so nothing is returned; errors are
193
+ shown under the view and collected in `messages`.
194
+ """
195
+ command = command.strip()
196
+ if "\n" in command:
197
+ raise ValueError("one command at a time: see run_script()")
198
+ if command and not command.startswith("#"):
199
+ self.commands = self.commands + [command]
200
+
201
+ def run_script(self, script):
202
+ """Run a script of AtomEye commands, one per line."""
203
+ lines = [l.strip() for l in script.splitlines()]
204
+ self.commands = self.commands + [
205
+ l for l in lines if l and not l.startswith("#")]
206
+
207
+ def aux_property_coloring(self, name):
208
+ """Colour the atoms by the per-atom property `name`."""
209
+ self.run_command("aux_property_coloring %s" % name)
210
+
211
+ def capture(self):
212
+ """Ask the browser for the view as a PNG. It arrives in `png`
213
+ shortly afterwards (observe the trait to be told when)."""
214
+ self.send({"type": "capture"})
215
+
216
+
217
+ # ----------------------------------------------------------------------
218
+ # ASE viewer plugin:
219
+ #
220
+ # from ase.visualize import view
221
+ # view(atoms, viewer="atomeye_widget")
222
+ #
223
+ # ASE finds VIEWER_ENTRYPOINT through the "ase.visualize" entry point
224
+ # declared in pyproject.toml, and calls view_atomeye_widget().
225
+ # ----------------------------------------------------------------------
226
+
227
+ def view_atomeye_widget(atoms, data=None, repeat=None, **kwargs):
228
+ """Show `atoms` (an Atoms object or a list of them) in a notebook.
229
+
230
+ This is the function behind
231
+ ``ase.visualize.view(atoms, viewer="atomeye_widget")``. It returns an
232
+ :class:`AtomEyeWidget`, which a notebook shows when it is the value of
233
+ a cell (in marimo, wrap it: ``mo.ui.anywidget(view(...))``). Keyword
234
+ arguments are passed on to :class:`AtomEyeWidget`. `data` (a volumetric
235
+ dataset) is not supported and is ignored.
236
+ """
237
+ if repeat is not None:
238
+ if hasattr(atoms, "get_chemical_symbols"):
239
+ atoms = atoms.repeat(repeat)
240
+ else:
241
+ atoms = [a.repeat(repeat) for a in atoms]
242
+ return AtomEyeWidget(atoms, **kwargs)
243
+
244
+
245
+ try:
246
+ from ase.utils.plugins import ExternalViewer
247
+ except ImportError: # ASE not installed, or too old to have viewer plugins
248
+ pass
249
+ else:
250
+ VIEWER_ENTRYPOINT = ExternalViewer(
251
+ desc="View atoms in a notebook using AtomEye (WebAssembly)",
252
+ module="atomeye_widget",
253
+ )