atomeye-widget 3.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.
- atomeye_widget/__init__.py +253 -0
- atomeye_widget/static/widget.js +6479 -0
- atomeye_widget-3.1.0.dist-info/METADATA +97 -0
- atomeye_widget-3.1.0.dist-info/RECORD +7 -0
- atomeye_widget-3.1.0.dist-info/WHEEL +4 -0
- atomeye_widget-3.1.0.dist-info/entry_points.txt +2 -0
- atomeye_widget-3.1.0.dist-info/licenses/LICENSE +32 -0
|
@@ -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
|
+
)
|