-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathtest_viewers.py
More file actions
587 lines (480 loc) · 22.1 KB
/
Copy pathtest_viewers.py
File metadata and controls
587 lines (480 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
import base64
import re
import sys
from io import StringIO
from pathlib import Path
import ase
import numpy as np
import pytest
import traitlets as tl
from aiida import orm
from aiidalab_widgets_base import viewers
@pytest.mark.usefixtures("aiida_profile_clean")
def test_pbc_structure_data_viewer(structure_data_object):
"""Test the periodicity of the structure viewer widget."""
# Prepare a structure with periodicity xy
ase_input = ase.Atoms(
symbols="Li2",
positions=[(0.0, 0.0, 0.0), (1.5, 1.5, 1.5)],
pbc=[True, True, False],
cell=[3.5, 3.5, 3.5],
)
viewer = viewers.StructureDataViewer()
viewer.structure = ase_input
assert viewer.periodicity.value == "Periodicity: xy"
assert viewer.cell_volume.value == "Cell area: 12.2500 (Ų)"
@pytest.mark.usefixtures("aiida_profile_clean")
def test_several_data_viewers(generate_calc_job_node):
v = viewers.viewer(orm.Int(1))
# No viewer for Int, so it should return the input
assert isinstance(v, orm.Int)
# DictViewer
v = viewers.viewer(orm.Dict(dict={"a": 1}))
assert isinstance(v, viewers.DictViewer)
# ProcessNodeViewer
process = generate_calc_job_node(
inputs={
"parameters": orm.Int(1),
"nested": {
"inner": orm.Int(2),
},
}
)
v = viewers.viewer(process)
assert isinstance(v, viewers.ProcessNodeViewerWidget)
@pytest.mark.usefixtures("aiida_profile_clean")
def test_dict_viewer_renders_table_and_csv_payload():
long_value = "0123456789" * 5
escaped_value = "<tag> & value"
parameter = orm.Dict(
dict={
"z-key": escaped_value,
"a-key": long_value,
}
).store()
viewer = viewers.DictViewer(parameter, downloadable=True)
assert "<table" in viewer.value
assert "<th>Key</th>" in viewer.value
assert "<th>Value</th>" in viewer.value
assert viewer.value.index("a-key") < viewer.value.index("z-key")
assert long_value in viewer.value
assert "<tag> & value" in viewer.value
assert escaped_value not in viewer.value
assert f'download="{parameter.pk}.csv"' in viewer.value
match = re.search(r'data:text/csv;base64,([^"]+)', viewer.value)
assert match is not None
decoded_payload = base64.b64decode(match.group(1)).decode()
assert decoded_payload == (
f"Key,Value\na-key,{long_value}\nz-key,{escaped_value}\n"
)
@pytest.mark.usefixtures("aiida_profile_clean")
def test_dict_viewer_skips_download_link_when_disabled():
parameter = orm.Dict(dict={"a": 1}).store()
viewer = viewers.DictViewer(parameter, downloadable=False)
assert "Download table in csv format" not in viewer.value
assert "data:text/csv;base64," not in viewer.value
@pytest.mark.usefixtures("aiida_profile_clean")
def test_folder_data_viewer(folder_data_object):
v = viewers.viewer(folder_data_object)
assert isinstance(v, viewers.FolderDataViewer)
v.files.value = "test1.txt"
assert v.text.value == "content of test1.txt"
v.files.value = "test2.txt"
assert v.text.value == "content of test2.txt"
v.download_btn.click()
# NOTE: We're testing the download() method directly as well,
# since triggering it via self.download_btn.click() callback
# seems to swallow all exceptions.
v.download()
v.files.value = "test.bin"
assert v.text.value == "[Binary file, preview not available]"
v.download()
@pytest.mark.usefixtures("aiida_profile_clean")
def test_structure_data_viewer_storage(monkeypatch, tmp_path, structure_data_object):
v = viewers.viewer(structure_data_object)
assert isinstance(v, viewers.StructureDataViewer)
# Check the `_prepare_payload` function used for downloading.
format_cases = {
"Extended xyz": """MgpMYXR0aWNlPSIzLjg0NzM3IDAuMCAwLjAgMS45MjM2ODUgMy4zMzE5MiAwLjAgMS45MjM2ODUgMS4xMTA2NCAzLjE0MTM2NCIgUHJvcGVydGllcz1zcGVjaWVzOlM6MTpwb3M6UjozOm1hc3NlczpSOjE6X2FpaWRhbGFiX3ZpZXdlcl9yZXByZXNlbnRhdGlvbl9kZWZhdWx0Okk6MSBwYmM9IlQgVCBUIgpTaSAgICAgICAwLjAwMDAwMDAwICAgICAgIDAuMDAwMDAwMDAgICAgICAgMC4wMDAwMDAwMCAgICAgIDI4LjA4NTUwMDAwICAgICAgICAwClNpICAgICAgIDEuOTIzNjg1MDAgICAgICAgMS4xMTA2NDAwMCAgICAgICAwLjc4NTM0MTAwICAgICAgMjguMDg1NTAwMDAgICAgICAgIDAK""",
"xsf": """Q1JZU1RBTApQUklNVkVDCiAzLjg0NzM3MDAwMDAwMDAwIDAuMDAwMDAwMDAwMDAwMDAgMC4wMDAwMDAwMDAwMDAwMAogMS45MjM2ODUwMDAwMDAwMCAzLjMzMTkyMDAwMDAwMDAwIDAuMDAwMDAwMDAwMDAwMDAKIDEuOTIzNjg1MDAwMDAwMDAgMS4xMTA2NDAwMDAwMDAwMCAzLjE0MTM2NDAwMDAwMDAwClBSSU1DT09SRAogMiAxCiAxNCAgICAgMC4wMDAwMDAwMDAwMDAwMCAgICAgMC4wMDAwMDAwMDAwMDAwMCAgICAgMC4wMDAwMDAwMDAwMDAwMAogMTQgICAgIDEuOTIzNjg1MDAwMDAwMDAgICAgIDEuMTEwNjQwMDAwMDAwMDAgICAgIDAuNzg1MzQxMDAwMDAwMDAK""",
"cif": """ZGF0YV9pbWFnZTAKX2NoZW1pY2FsX2Zvcm11bGFfc3RydWN0dXJhbCAgICAgICBTaTIKX2NoZW1pY2FsX2Zvcm11bGFfc3VtICAgICAgICAgICAgICAiU2kyIgpfY2VsbF9sZW5ndGhfYSAgICAgICAzLjg0NzM3Cl9jZWxsX2xlbmd0aF9iICAgICAgIDMuODQ3MzY5ODYzMzc3NDQ4Cl9jZWxsX2xlbmd0aF9jICAgICAgIDMuODQ3MzY5NjE2OTM1ODM2Cl9jZWxsX2FuZ2xlX2FscGhhICAgIDU5Ljk5OTk5NzA5Nzk3MDEyCl9jZWxsX2FuZ2xlX2JldGEgICAgIDU5Ljk5OTk5NjcwNjQwOTMwNgpfY2VsbF9hbmdsZV9nYW1tYSAgICA1OS45OTk5OTg4MjUzMTc1OQoKX3NwYWNlX2dyb3VwX25hbWVfSC1NX2FsdCAgICAiUCAxIgpfc3BhY2VfZ3JvdXBfSVRfbnVtYmVyICAgICAgIDEKCmxvb3BfCiAgX3NwYWNlX2dyb3VwX3N5bW9wX29wZXJhdGlvbl94eXoKICAneCwgeSwgeicKCmxvb3BfCiAgX2F0b21fc2l0ZV90eXBlX3N5bWJvbAogIF9hdG9tX3NpdGVfbGFiZWwKICBfYXRvbV9zaXRlX3N5bW1ldHJ5X211bHRpcGxpY2l0eQogIF9hdG9tX3NpdGVfZnJhY3RfeAogIF9hdG9tX3NpdGVfZnJhY3RfeQogIF9hdG9tX3NpdGVfZnJhY3RfegogIF9hdG9tX3NpdGVfb2NjdXBhbmN5CiAgU2kgIFNpMSAgICAgICAxLjAgIDAuMCAgMC4wICAwLjAgIDEuMDAwMAogIFNpICBTaTIgICAgICAgMS4wICAwLjI1MDAwMDAwMDAwMDAwMDA2ICAwLjI1ICAwLjI1ICAxLjAwMDAK""",
}
# Compatibility with old ASE versions <3.23
old_ase = format_cases.copy()
old_ase["cif"] = (
"""ZGF0YV9pbWFnZTAKX2NoZW1pY2FsX2Zvcm11bGFfc3RydWN0dXJhbCAgICAgICBTaTIKX2NoZW1pY2FsX2Zvcm11bGFfc3VtICAgICAgICAgICAgICAiU2kyIgpfY2VsbF9sZW5ndGhfYSAgICAgICAzLjg0NzM3Cl9jZWxsX2xlbmd0aF9iICAgICAgIDMuODQ3MzcKX2NlbGxfbGVuZ3RoX2MgICAgICAgMy44NDczNwpfY2VsbF9hbmdsZV9hbHBoYSAgICA2MApfY2VsbF9hbmdsZV9iZXRhICAgICA2MApfY2VsbF9hbmdsZV9nYW1tYSAgICA2MAoKX3NwYWNlX2dyb3VwX25hbWVfSC1NX2FsdCAgICAiUCAxIgpfc3BhY2VfZ3JvdXBfSVRfbnVtYmVyICAgICAgIDEKCmxvb3BfCiAgX3NwYWNlX2dyb3VwX3N5bW9wX29wZXJhdGlvbl94eXoKICAneCwgeSwgeicKCmxvb3BfCiAgX2F0b21fc2l0ZV90eXBlX3N5bWJvbAogIF9hdG9tX3NpdGVfbGFiZWwKICBfYXRvbV9zaXRlX3N5bW1ldHJ5X211bHRpcGxpY2l0eQogIF9hdG9tX3NpdGVfZnJhY3RfeAogIF9hdG9tX3NpdGVfZnJhY3RfeQogIF9hdG9tX3NpdGVfZnJhY3RfegogIF9hdG9tX3NpdGVfb2NjdXBhbmN5CiAgU2kgIFNpMSAgICAgICAxLjAgIDAuMDAwMDAgIDAuMDAwMDAgIDAuMDAwMDAgIDEuMDAwMAogIFNpICBTaTIgICAgICAgMS4wICAwLjI1MDAwICAwLjI1MDAwICAwLjI1MDAwICAxLjAwMDAK"""
)
for fmt in format_cases: # noqa: PLC0206
v.file_format.label = fmt
b64_payload = v._prepare_payload()
try:
assert b64_payload == format_cases[fmt], (
f"{fmt} structure payload does not match"
)
except AssertionError:
assert b64_payload == old_ase[fmt], (
f"{fmt} structure payload does not match"
)
# Monkey patch the viewer to avoid the need for a running X server.
# fmt: off
v._viewer._camera_orientation = [
16.619212980943573, 0, 0, 0,
0, 16.619212980943573, 0, 0,
0, 0, 16.619212980943573, 0,
-1.6859999895095825, -1.6859999895095825, -0.6669999957084656, 1,
]
# fmt: on
# Avoid producing temporary files from povray in the repo
monkeypatch.chdir(tmp_path)
v._render_structure()
# Make sure we don't polute current working dir with tempfiles
assert not Path("__temp__.pov").exists()
assert not Path("Si2.png").exists()
@pytest.mark.usefixtures("aiida_profile_clean")
def test_structure_data_viewer_selection(structure_data_object):
v = viewers.viewer(structure_data_object)
# Direct selection.
v._selected_atoms.value = "1..2"
v.apply_displayed_selection()
assert v.selection == [0, 1]
assert v.displayed_selection == [0, 1]
assert "Distance" in v.selection_info.value
# The x coordinate lower than 0.5.
v._selected_atoms.value = "x<0.5"
v.apply_displayed_selection()
assert v.selection == [0]
assert v.displayed_selection == [0]
# The id of the second atom
v._selected_atoms.value = "id > 1"
v.apply_displayed_selection()
assert v.selection == [1]
# or of the two selections.
v._selected_atoms.value = "x>=0.5 or x<0.5"
v.apply_displayed_selection()
assert v.selection == [0, 1]
# Display 2*2*2 supercell
v.supercell = [2, 2, 2]
assert len(v.structure) == 2
assert len(v.displayed_structure) == 16
# Test intersection of the selection with the supercell.
v._selected_atoms.value = "z>0 and z<2.5"
v.apply_displayed_selection()
assert v.selection == [1]
assert v.displayed_selection == [1, 5, 9, 13]
v._selected_atoms.value = "x<=2.0 and z<3"
v.apply_displayed_selection()
assert v.selection == [0, 1]
assert v.displayed_selection == [4, 0, 1]
assert "Angle" in v.selection_info.value
# Convert to boron nitride.
new_structure = v.structure.copy()
new_structure.symbols = ["B", "N"]
v.structure = None
v.structure = new_structure
# Use "name" and "not" operators.
v._selected_atoms.value = "z<2 and name B"
v.apply_displayed_selection()
assert v.selection == [0]
assert v.displayed_selection == [0, 4, 8, 12]
v._selected_atoms.value = "z<2 and name not B"
v.apply_displayed_selection()
assert v.selection == [1]
assert v.displayed_selection == [1, 5, 9, 13]
v._selected_atoms.value = "z<2 and name not [B, O]"
v.apply_displayed_selection()
assert v.selection == [1]
assert v.displayed_selection == [1, 5, 9, 13]
# Use "id" operator.
v._selected_atoms.value = "id == 1 or id == 8"
v.apply_displayed_selection()
assert v.selection == [0, 1]
assert v.displayed_selection == [0, 7]
# Use the d_from operator.
v._selected_atoms.value = "d_from[0,0,0] < 4"
v.apply_displayed_selection()
assert v.selection == [0, 1]
assert v.displayed_selection == [4, 8, 0, 1, 2]
# Use the != operator.
v._selected_atoms.value = "id != 5"
v.apply_displayed_selection()
assert v.selection == [0, 1]
assert v.displayed_selection == [0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
# Use ^ and - operators.
v._selected_atoms.value = "(x-4)^2 + (y-2)^2 < 4"
v.apply_displayed_selection()
assert v.selection == [1, 0]
assert v.displayed_selection == [3, 9, 10]
# Division and multiplication.
v._selected_atoms.value = "x/2 < 1"
v.apply_displayed_selection()
assert v.selection == [0, 1]
assert v.displayed_selection == [4, 0, 1, 2]
v._selected_atoms.value = "x*1.5 < y + z"
v.apply_displayed_selection()
assert v.selection == [0, 1]
assert v.displayed_selection == [2, 3, 4, 6, 7]
# Test wrong syntax.
assert v.wrong_syntax.layout.visibility == "hidden"
v._selected_atoms.value = "x--x"
v.apply_displayed_selection()
assert v.wrong_syntax.layout.visibility == "visible"
@pytest.mark.usefixtures("aiida_profile_clean")
def test_structure_data_viewer_representation(structure_data_object):
v = viewers.viewer(structure_data_object)
# By default, there should be one "default" representation.
assert len(v._all_representations) == 1
assert (
v._all_representations[0].style_id == "_aiidalab_viewer_representation_default"
)
assert v._all_representations[0].selection.value == "1..2"
# Display only one atom.
v._all_representations[0].selection.value = "1"
v._apply_representations()
assert "2" in v.atoms_not_represented.value
# Add a new representation.
v._add_representation()
assert "2" in v.atoms_not_represented.value
v._all_representations[1].selection.value = "2"
v._all_representations[0].type.value = "ball+stick"
v._all_representations[1].type.value = "spacefill"
v._apply_representations()
assert v.atoms_not_represented.value == ""
# Add an atom to the structure.
new_structure = v.structure.copy()
new_structure.append(ase.Atom("C", (0.5, 0.5, 0.5)))
v.structure = None
v.structure = new_structure
# The new atom should appear in the default representation.
assert v._all_representations[0].selection.value == "1 3"
assert "3" not in v.atoms_not_represented.value
# Delete the second representation.
assert v._all_representations[0].delete_button.layout.visibility == "hidden"
assert v._all_representations[1].delete_button.layout.visibility == "visible"
v._all_representations[1].delete_button.click()
assert len(v._all_representations) == 1
assert "2" in v.atoms_not_represented.value
# Try to provide different object type than the viewer accepts.
with pytest.raises(tl.TraitError):
v.structure = 2
with pytest.raises(tl.TraitError):
v.structure = orm.Int(1)
def test_structure_data_viewer_imports_unknown_representation_array():
structure = ase.Atoms(
symbols=["C", "H"],
positions=[(0.0, 0.0, 0.0), (0.0, 0.0, 1.1)],
)
style_id = f"{viewers.StructureDataViewer.REPRESENTATION_PREFIX}custom"
structure.set_array(style_id, np.array([1, -1], dtype=int))
viewer = viewers.StructureDataViewer()
viewer.structure = structure
representation_ids = [rep.style_id for rep in viewer._all_representations]
assert style_id in representation_ids
representation = viewer._all_representations[representation_ids.index(style_id)]
assert representation.selection.value == "1"
assert representation.type.value == "ball+stick"
assert representation.size.value == 3
assert representation.color.value == "element"
def test_structure_data_viewer_imports_encoded_representation_array():
structure = ase.Atoms(
symbols=["C", "H"],
positions=[(0.0, 0.0, 0.0), (0.0, 0.0, 1.1)],
)
style_id = viewers.encode_representation_style_id(
viewers.StructureDataViewer.REPRESENTATION_PREFIX,
representation_type="spacefill",
size=4,
color="red",
token="surface",
)
structure.set_array(style_id, np.array([1, -1], dtype=int))
viewer = viewers.StructureDataViewer()
viewer.structure = structure
representation_ids = [rep.style_id for rep in viewer._all_representations]
assert style_id in representation_ids
representation = viewer._all_representations[representation_ids.index(style_id)]
assert representation.selection.value == "1"
assert representation.type.value == "spacefill"
assert representation.size.value == 4
assert representation.color.value == "red"
@pytest.mark.usefixtures("aiida_profile_clean")
def test_structure_data_viewer_restores_representation_arrays_from_extras():
structure = ase.Atoms(
symbols=["C", "H"],
positions=[(0.0, 0.0, 0.0), (0.0, 0.0, 1.1)],
)
style_id = viewers.encode_representation_style_id(
viewers.StructureDataViewer.REPRESENTATION_PREFIX,
representation_type="spacefill",
size=2,
color="red",
token="stored",
)
node = orm.StructureData(ase=structure)
node.base.extras.set(viewers.VIEWER_REPRESENTATIONS_EXTRA, {style_id: [1, -1]})
viewer = viewers.StructureDataViewer(node)
representation_ids = [rep.style_id for rep in viewer._all_representations]
assert style_id in representation_ids
representation = viewer._all_representations[representation_ids.index(style_id)]
assert representation.selection.value == "1"
assert representation.type.value == "spacefill"
assert representation.size.value == 2
assert representation.color.value == "red"
def test_structure_data_viewer_imports_multiple_encoded_representation_arrays():
structure = ase.Atoms(
symbols=["C", "H", "H"],
positions=[(0.0, 0.0, 0.0), (0.0, 0.0, 1.1), (0.0, 1.0, 0.0)],
)
style_id_1 = viewers.encode_representation_style_id(
viewers.StructureDataViewer.REPRESENTATION_PREFIX,
representation_type="spacefill",
size=2,
color="element",
token="surface",
)
style_id_2 = viewers.encode_representation_style_id(
viewers.StructureDataViewer.REPRESENTATION_PREFIX,
representation_type="ball+stick",
size=4,
color="red",
token="molecule",
)
structure.set_array(style_id_1, np.array([1, -1, -1], dtype=int))
structure.set_array(style_id_2, np.array([-1, 1, 1], dtype=int))
viewer = viewers.StructureDataViewer()
viewer.structure = structure
representation_ids = [rep.style_id for rep in viewer._all_representations]
assert style_id_1 in representation_ids
assert style_id_2 in representation_ids
representation_1 = viewer._all_representations[representation_ids.index(style_id_1)]
representation_2 = viewer._all_representations[representation_ids.index(style_id_2)]
assert representation_1.selection.value == "1"
assert representation_1.type.value == "spacefill"
assert representation_1.size.value == 2
assert representation_2.selection.value == "2..3"
assert representation_2.type.value == "ball+stick"
assert representation_2.size.value == 4
assert representation_2.color.value == "red"
def test_structure_data_viewer_drops_stale_representations_on_structure_change():
structure = ase.Atoms(
symbols=["C", "H"],
positions=[(0.0, 0.0, 0.0), (0.0, 0.0, 1.1)],
)
style_id = viewers.encode_representation_style_id(
viewers.StructureDataViewer.REPRESENTATION_PREFIX,
representation_type="spacefill",
size=2,
color="red",
token="old",
)
structure.set_array(style_id, np.array([1, -1], dtype=int))
viewer = viewers.StructureDataViewer()
viewer.structure = structure
assert style_id in [rep.style_id for rep in viewer._all_representations]
viewer.structure = ase.Atoms(
symbols=["C", "H", "H"],
positions=[(0.0, 0.0, 0.0), (0.0, 0.0, 1.1), (0.0, 1.0, 0.0)],
)
assert [rep.style_id for rep in viewer._all_representations] == [
viewers.DEFAULT_REPRESENTATION
]
assert viewer._all_representations[0].selection.value == "1..3"
def test_structure_data_viewer_updates_encoded_representation_array_name():
structure = ase.Atoms(
symbols=["C", "H"],
positions=[(0.0, 0.0, 0.0), (0.0, 0.0, 1.1)],
)
viewer = viewers.StructureDataViewer()
viewer.structure = structure
viewer._add_representation()
representation = viewer._all_representations[-1]
old_style_id = representation.style_id
representation.selection.value = "2"
representation.type.value = "spacefill"
representation.size.value = 4
representation.color.value = "red"
viewer._apply_representations()
assert old_style_id not in viewer.structure.arrays
assert representation.style_id in viewer.structure.arrays
assert representation.style_id.startswith(
f"{viewer.REPRESENTATION_PREFIX}spacefill_r4_red_"
)
assert viewer.structure.arrays[representation.style_id].tolist() == [-1, 1]
def test_structure_data_viewer_clears_bond_shape_components():
water = ase.Atoms(
symbols=["O", "H", "H"],
positions=[
(0.0, 0.0, 0.119262),
(0.0, 0.763239, -0.477047),
(0.0, -0.763239, -0.477047),
],
)
viewer = viewers.StructureDataViewer()
viewer.structure = water
assert len(viewer._viewer._ngl_component_ids) == 2
viewer.structure = None
assert viewer.displayed_structure is None
assert viewer._viewer._ngl_component_ids == []
assert viewer._viewer._ngl_component_names == []
@pytest.mark.usefixtures("aiida_profile_clean")
def test_compute_bonds_in_structure_data_viewer():
# Check the function to compute bonds.
water = ase.Atoms(
symbols=["O", "H", "H"],
positions=[
(0.0, 0.0, 0.119262),
(0.0, 0.763239, -0.477047),
(0.0, -0.763239, -0.477047),
],
)
viewer = viewers.StructureDataViewer()
bonds = viewer._compute_bonds(water)
assert len(bonds) == 4
@pytest.mark.usefixtures("aiida_profile_clean")
def test_loading_viewer_using_process_type(generate_calc_job_node):
"""Test loading a viewer widget based on the process type of the process node."""
from aiidalab_widgets_base import register_viewer_widget
# Define and register a viewer widget for the calculation type identified by "aiida.calculations:abc".
@register_viewer_widget("aiida.calculations:abc")
class AbcViewer:
def __init__(self, node=None):
self.node = node
# Generate a calc job node with the specific entry point "abc".
process = generate_calc_job_node(entry_point_name="abc")
# Load the viewer widget for the generated process node.
viewer = viewers.viewer(process)
# Verify that the loaded viewer is the correct type and is associated with the intended node.
assert isinstance(viewer, AbcViewer), (
"Viewer is not an instance of the expected viewer class."
)
assert viewer.node == process, "Viewer's node does not match the test process node."
def test_node_view_for_non_widget_viewer():
"""Test that a node with no registered viewer is displayed in an output widget"""
# Intercepting stdout because `ipw.Output` does not
# store outputs in non-interactive environments.
captured = StringIO()
sys.stdout = captured
node_view = viewers.AiidaNodeViewWidget()
node = orm.Int(1)
node_view.node = node
assert node_view.children[0] is node_view._output
assert str(node) in sys.stdout.getvalue()
def test_node_view_caching():
"""Test that providing a given node a second time returns the cached viewer."""
node_view = viewers.AiidaNodeViewWidget()
node = orm.Dict()
node_view.node = node
viewer = node_view.children[0]
assert len(node_view.node_views) == 1
# orm.Int doesn't have a dedicated viewer
# so it will not be cached.
stdout = sys.stdout
with StringIO() as captured:
sys.stdout = captured
node_view.node = orm.Int(2)
sys.stdout = stdout
assert len(node_view.node_views) == 1
node_view.node = None
assert not node_view.children
node_view.node = node
assert node_view.children[0] is viewer
assert len(node_view.node_views) == 1