-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathviewers.py
More file actions
1623 lines (1404 loc) · 58.3 KB
/
Copy pathviewers.py
File metadata and controls
1623 lines (1404 loc) · 58.3 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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
"""Jupyter viewers for AiiDA data objects."""
# pylint: disable=no-self-use
import base64
import copy
import re
import warnings
import ase
import ipywidgets as ipw
import nglview
import numpy as np
import shortuuid
import spglib
import traitlets as tl
import vapory
from aiida import cmdline, orm, tools
from ase.data import colors
from IPython.display import clear_output, display
from matplotlib.colors import to_rgb
from .dicts import RGB_COLORS, Colors, Radius
from .misc import CopyToClipboardButton, ReversePolishNotation
from .utils import ase2spglib, list_to_string_range, string_range_to_list
AIIDA_VIEWER_MAPPING = {}
def register_viewer_widget(key):
"""Register widget as a viewer for the given key."""
def registration_decorator(widget):
AIIDA_VIEWER_MAPPING[key] = widget
return widget
return registration_decorator
def viewer(obj, **kwargs):
"""Display AiiDA data types in Jupyter notebooks.
Returns the object itself if the viewer wasn't found."""
if not isinstance(obj, orm.Node): # only working with AiiDA nodes
warnings.warn(
f"This viewer works only with AiiDA objects, got {type(obj)}", stacklevel=2
)
return obj
if obj.node_type in AIIDA_VIEWER_MAPPING:
_viewer = AIIDA_VIEWER_MAPPING[obj.node_type]
return _viewer(obj, **kwargs)
else:
# No viewer registered for this type, return object itself
return obj
class AiidaNodeViewWidget(ipw.VBox):
node = tl.Instance(orm.Node, allow_none=True)
def __init__(self, **kwargs):
self._output = ipw.Output()
super().__init__(
children=[
self._output,
],
**kwargs,
)
@tl.observe("node")
def _observe_node(self, change):
if change["new"] != change["old"]:
with self._output:
clear_output()
if change["new"]:
display(viewer(change["new"]))
@register_viewer_widget("data.core.dict.Dict.")
class DictViewer(ipw.VBox):
value = tl.Unicode()
"""Viewer class for Dict object.
:param parameter: Dict object to be viewed
:type parameter: Dict
:param downloadable: If True, add link/button to download the content of the object
:type downloadable: bool"""
def __init__(self, parameter, downloadable=True, **kwargs):
import pandas as pd
# Here we are defining properties of 'df' class (specified while exporting pandas table into html).
# Since the exported object is nothing more than HTML table, all 'standard' HTML table settings
# can be applied to it as well.
# For more information on how to controle the table appearance please visit:
# https://css-tricks.com/complete-guide-table-element/
self.widget = ipw.HTML()
ipw.dlink((self, "value"), (self.widget, "value"))
self.value += """
<style>
.df { border: none; }
.df tbody tr:nth-child(odd) { background-color: #e5e7e9; }
.df tbody tr:nth-child(odd):hover { background-color: #f5b7b1; }
.df tbody tr:nth-child(even):hover { background-color: #f5b7b1; }
.df tbody td { min-width: 300px; text-align: center; border: none }
.df th { text-align: center; border: none; border-bottom: 1px solid black;}
</style>
"""
pd.set_option("max_colwidth", 100)
dataf = pd.DataFrame(
[(key, value) for key, value in sorted(parameter.get_dict().items())],
columns=["Key", "Value"],
)
# specify that exported table belongs to 'df' class
# this is used to setup table's appearance using CSS
# `colwidths-auto` and `table` are also required for proper table rendering in MyST: https://myst-parser.readthedocs.io/en/latest/syntax/tables.html
self.value += dataf.to_html(classes="df colwidths-auto table", index=False)
if downloadable:
payload = base64.b64encode(dataf.to_csv(index=False).encode()).decode()
fname = f"{parameter.pk}.csv"
self.value += f"""Download table in csv format: <a download="{fname}"
href="data:text/csv;base64,{payload}" target="_blank">{fname}</a>"""
super().__init__([self.widget], **kwargs)
class NglViewerRepresentation(ipw.HBox):
"""This class represents the parameters for displaying a structure in NGLViewer.
It is utilized in the structure viewer, where multiple representations can be defined,
each specifying how to visually represent a particular subset of atoms.
"""
viewer_class = None # The structure viewer class that contains this representation.
def __init__(self, style_id, indices=None, deletable=True, atom_show_threshold=1):
"""Initialize the representation.
style_id: str
Unique identifier for the representation.
indices: list
List of indices to be displayed.
deletable: bool
If True, add a button to delete the representation.
atom_show_threshold: int
only show the atom if the corresponding value in the representation array is larger or equal than this threshold.
"""
self.atom_show_threshold = atom_show_threshold
self.style_id = style_id
self.show = ipw.Checkbox(
value=True,
layout={"width": "40px"},
style={"description_width": "0px"},
disabled=False,
)
self.selection = ipw.Text(
value=list_to_string_range(indices, shift=1) if indices is not None else "",
layout={"width": "80px"},
style={"description_width": "0px"},
)
self.type = ipw.Dropdown(
options=["ball+stick", "spacefill"],
value="ball+stick",
disabled=False,
layout={"width": "100px"},
style={"description_width": "0px"},
)
self.size = ipw.FloatText(
value=3,
layout={"width": "40px"},
style={"description_width": "0px"},
)
self.color = ipw.Dropdown(
options=["element", "red", "green", "blue", "yellow", "orange", "purple"],
value="element",
disabled=False,
layout={"width": "80px"},
style={"description_width": "initial"},
)
# Delete button.
self.delete_button = ipw.Button(
description="",
icon="trash",
button_style="danger",
layout={
"width": "50px",
"visibility": "visible" if deletable else "hidden",
},
)
self.delete_button.on_click(self.delete_myself)
super().__init__(
children=[
self.show,
self.selection,
self.type,
self.size,
self.color,
self.delete_button,
]
)
def delete_myself(self, _):
self.viewer_class.delete_representation(self)
def sync_myself_to_array_from_atoms_object(self, structure: ase.Atoms | None):
"""Update representation from the structure object."""
if structure:
if self.style_id in structure.arrays:
self.selection.value = list_to_string_range(
np.where(self.atoms_in_representation(structure))[0], shift=1
)
def add_myself_to_atoms_object(self, structure: ase.Atoms | None):
"""Add representation array to the structure object. If the array already exists, update it."""
if structure:
array_representation = np.full(len(structure), -1, dtype=int)
selection = np.array(
string_range_to_list(self.selection.value, shift=-1)[0], dtype=int
)
# Only attempt to display the existing atoms.
array_representation[selection[selection < len(structure)]] = 1
structure.set_array(self.style_id, array_representation)
def atoms_in_representation(self, structure: ase.Atoms | None = None):
"""Return an array of booleans indicating which atoms are present in the representation."""
if structure and self.style_id in structure.arrays:
return structure.arrays[self.style_id] >= self.atom_show_threshold
natoms = 0 if not structure else len(structure)
return np.zeros(natoms, dtype=bool)
def nglview_parameters(self, indices):
"""Return the parameters dictionary of a representation."""
nglview_parameters_dict = {
"type": "spacefill",
"params": {
"sele": "@" + ",".join(map(str, indices))
if len(indices) > 0
else "none",
"opacity": 1,
"color": self.color.value,
},
}
if self.type.value == "ball+stick":
nglview_parameters_dict["params"]["radiusScale"] = self.size.value * 0.08
elif self.type.value == "spacefill":
nglview_parameters_dict["params"]["radiusScale"] = self.size.value * 0.25
return nglview_parameters_dict
class _StructureDataBaseViewer(ipw.VBox):
"""Base viewer class for AiiDA structure or trajectory objects.
Traits:
_all_representations: list, containing all the representations of the structure.
input_selection: list used mostly by external tools to populate the selection field.
selection: list of currently selected atoms.
displayed_selection: list of currently displayed atoms in the displayed structure, which also includes super-cell.
supercell: list of supercell dimensions.
cell: ase.cell.Cell object.
"""
_all_representations = tl.List()
input_selection = tl.List(tl.Int(), allow_none=True)
selection = tl.List(tl.Int())
displayed_selection = tl.List(tl.Int())
supercell = tl.List(tl.Int())
cell = tl.Instance(ase.cell.Cell, allow_none=True)
DEFAULT_SELECTION_OPACITY = 0.2
DEFAULT_SELECTION_RADIUS = 6
DEFAULT_SELECTION_COLOR = "green"
REPRESENTATION_PREFIX = "_aiidalab_viewer_representation_"
DEFAULT_REPRESENTATION = "_aiidalab_viewer_representation_default"
def __init__(
self,
configure_view=True,
configuration_tabs=None,
default_camera="orthographic",
**kwargs,
):
"""Initialize the viewer.
:param configure_view: If True, add configuration tabs (deprecated).
:param configuration_tabs: List of configuration tabs (default: ["Selection", "Appearance", "Cell", "Download"]).
:param default_camera: default camera (orthographic|perspective), can be changed in the Appearance tab.
"""
# Defining viewer box.
# Nglviwer
self._viewer = nglview.NGLWidget()
self._viewer.camera = default_camera
self._viewer.observe(self._on_atom_click, names="picked")
self._viewer.stage.set_parameters(mouse_preset="pymol")
view_box = ipw.VBox([self._viewer])
configuration_tabs_map = {
"Cell": self._cell_tab(),
"Selection": self._selection_tab(),
"Appearance": self._appearance_tab(),
"Download": self._download_tab(),
}
if configure_view is not True:
warnings.warn(
"`configure_view` is deprecated, please use `configuration_tabs` instead.",
DeprecationWarning,
stacklevel=2,
)
if not configure_view:
configuration_tabs.clear()
# Constructing configuration box
if configuration_tabs is None:
configuration_tabs = ["Selection", "Appearance", "Cell", "Download"]
if len(configuration_tabs) != 0:
self.configuration_box = ipw.Tab(
layout=ipw.Layout(flex="1 1 auto", width="auto")
)
self.configuration_box.children = [
configuration_tabs_map[tab_title] for tab_title in configuration_tabs
]
for i, title in enumerate(configuration_tabs):
self.configuration_box.set_title(i, title)
children = [ipw.HBox([view_box, self.configuration_box])]
view_box.layout = {"width": "60%"}
else:
children = [view_box]
if "children" in kwargs:
children += kwargs.pop("children")
super().__init__(children, **kwargs)
def _selection_tab(self):
"""Defining the selection tab."""
# 1. Selected atoms.
self._selected_atoms = ipw.Text(
description="Select atoms:",
value="",
style={"description_width": "initial"},
)
# 2. Copy to clipboard
copy_to_clipboard = CopyToClipboardButton(description="Copy to clipboard")
tl.link((self._selected_atoms, "value"), (copy_to_clipboard, "value"))
# 3. Informing about wrong syntax.
self.wrong_syntax = ipw.HTML(
value="""<i class="fa fa-times" style="color:red;font-size:2em;" ></i> wrong syntax""",
layout={"visibility": "hidden"},
)
# 4. Button to clear selection.
clear_selection = ipw.Button(description="Clear selection")
clear_selection.on_click(
lambda _: self.set_trait("displayed_selection", [])
) # lambda cannot contain assignments
# 5. Button to apply selection
apply_displayed_selection = ipw.Button(description="Apply selection")
apply_displayed_selection.on_click(self.apply_displayed_selection)
self.selection_info = ipw.HTML()
return ipw.VBox(
[
ipw.HBox([self._selected_atoms, self.wrong_syntax]),
ipw.HTML(
value="""
<p style="font-weight:800;">You can either specify ranges:
<font style="font-style:italic;font-weight:400;">1 5..8 10</font>
</p>
<p style="font-weight:800;">or expressions:
<font style="font-style:italic;font-weight:400;">(x>1 and name not [N,O]) or d_from [1,1,1]>2 or id>=10</font>
</p>"""
),
ipw.HBox(
[copy_to_clipboard, clear_selection, apply_displayed_selection]
),
self.selection_info,
]
)
def _appearance_tab(self):
"""Defining the appearance tab."""
# 1. Supercell
def change_supercell(_=None):
self.supercell = [
_supercell[0].value,
_supercell[1].value,
_supercell[2].value,
]
_supercell = [
ipw.BoundedIntText(value=1, min=1, layout={"width": "40px"}),
ipw.BoundedIntText(value=1, min=1, layout={"width": "40px"}),
ipw.BoundedIntText(value=1, min=1, layout={"width": "40px"}),
]
for elem in _supercell:
elem.observe(change_supercell, names="value")
supercell_selector = ipw.HBox(
[
ipw.HTML(
description="Super cell:", style={"description_width": "initial"}
)
]
+ _supercell
)
# 2. Choose background color.
background_color = ipw.ColorPicker(
description="Background",
style={"description_width": "initial"},
layout={"width": "200px"},
)
tl.link((background_color, "value"), (self._viewer, "background"))
background_color.value = "white"
# 3. Camera switcher
camera_type = ipw.ToggleButtons(
options=[("Orthographic", "orthographic"), ("Perspective", "perspective")],
description="Camera type:",
value=self._viewer.camera,
layout={"align_self": "flex-start"},
style={"button_width": "115.5px"},
)
def change_camera(change):
self._viewer.camera = change["new"]
camera_type.observe(change_camera, names="value")
# 4. Center button.
center_button = ipw.Button(description="Center molecule")
center_button.on_click(lambda c: self._viewer.center())
# 5. representations buttons
self.representations_header = ipw.HBox(
[
ipw.HTML(
"""<p style="text-align:center">Show</p>""",
layout={"width": "40px"},
),
ipw.HTML(
"""<p style="text-align:center">Atoms</p>""",
layout={"width": "80px"},
),
ipw.HTML(
"""<p style="text-align:center">Type</p>""",
layout={"width": "100px"},
),
ipw.HTML(
"""<p style="text-align:center">Size</p>""",
layout={"width": "40px"},
),
ipw.HTML(
"""<p style="text-align:center">Color</p>""",
layout={"width": "80px"},
),
ipw.HTML(
"""<p style="text-align:center">Delete</p>""",
layout={"width": "50px"},
),
]
)
self.atoms_not_represented = ipw.HTML()
add_new_representation_button = ipw.Button(
description="Add representation", button_style="info"
)
add_new_representation_button.on_click(self._add_representation)
apply_representations = ipw.Button(description="Apply representations")
apply_representations.on_click(self._apply_representations)
self.representation_output = ipw.VBox()
# The default representation is always present and cannot be deleted.
self._all_representations = [
NglViewerRepresentation(
style_id=self.DEFAULT_REPRESENTATION,
deletable=False,
atom_show_threshold=0,
)
]
representation_accordion = ipw.Accordion(
children=[
ipw.VBox(
[
self.representations_header,
self.representation_output,
self.atoms_not_represented,
ipw.HBox(
[apply_representations, add_new_representation_button]
),
]
)
],
)
representation_accordion.set_title(0, "Representations")
representation_accordion.selected_index = None
return ipw.VBox(
[
supercell_selector,
background_color,
camera_type,
center_button,
representation_accordion,
]
)
def _add_representation(self, _=None, style_id=None, indices=None):
"""Add a representation to the list of representations."""
self._all_representations = self._all_representations + [
NglViewerRepresentation(
style_id=style_id or f"{self.REPRESENTATION_PREFIX}{shortuuid.uuid()}",
indices=indices,
)
]
self._apply_representations()
def delete_representation(self, representation: NglViewerRepresentation):
try:
index = self._all_representations.index(representation)
except ValueError:
self.representation_add_message.message = f"""<span style="color:red">Error:</span> Rep. {representation} not found."""
return
self._all_representations = (
self._all_representations[:index] + self._all_representations[index + 1 :]
)
if representation.style_id in self.structure.arrays:
del self.structure.arrays[representation.style_id]
del representation
self._apply_representations()
@tl.observe("_all_representations")
def _observe_all_representations(self, change):
"""Update the list of representations."""
self.representation_output.children = change["new"]
if change["new"]:
self._all_representations[-1].viewer_class = self
def _povray_cylinder(self, v1, v2, radius, color):
"""Create a cylinder for POVRAY."""
return vapory.Cylinder(
v1,
v2,
radius,
vapory.Pigment("color", color),
vapory.Finish("phong", 0.8, "reflection", 0.05),
)
def _cylinder(self, v1, v2, radius, color):
"""Create a cylinder for NGLViewer."""
return (
"cylinder",
tuple(v1),
tuple(v2),
tuple(color),
radius,
)
def _compute_bonds(self, structure, radius=1.0, color="element", povray=False):
"""Create an list of bonds for the structure."""
import ase.neighborlist
bonds = []
if len(structure) <= 1:
return []
# The radius is scaled by 0.04 to have a better visual appearance.
radius = radius * 0.04
# The value 1.09 is chosen based on our experience. It is a good compromise between showing too many bonds
# and not showing bonds that should be there.
cutoff = ase.neighborlist.natural_cutoffs(structure, mult=1.09)
ii, bond_vectors = ase.neighborlist.neighbor_list(
"iD", structure, cutoff, self_interaction=False
)
nb = len(ii)
# bond start position
v1 = structure.positions[ii]
# middle position
v2 = v1 + bond_vectors * 0.5
# Choose the correct way for computing the cylinder.
if povray:
symbols = structure.get_chemical_symbols()
bonds = [
self._povray_cylinder(v1[ib], v2[ib], radius, Colors[symbols[ii[ib]]])
for ib in range(nb)
]
else:
if color == "element":
numbers = structure.get_atomic_numbers()
bonds = [
self._cylinder(
v1[ib], v2[ib], radius, colors.jmol_colors[numbers[ii[ib]]]
)
for ib in range(nb)
]
else:
bonds = [
self._cylinder(v1[ib], v2[ib], radius, RGB_COLORS[color])
for ib in range(nb)
]
return bonds
def _apply_representations(self, change=None):
"""Apply the representations to the displayed structure."""
representation_ids = []
# Representation can only be applied if a structure is present.
if self.structure is None:
return
# Add existing representations to the structure.
for representation in self._all_representations:
representation.add_myself_to_atoms_object(self.structure)
representation_ids.append(representation.style_id)
# Remove missing representations from the structure.
for array in self.structure.arrays:
if (
array.startswith(self.REPRESENTATION_PREFIX)
and array not in representation_ids
):
del self.structure.arrays[array]
self._observe_structure({"new": self.structure})
self._check_missing_atoms_in_representations()
def _check_missing_atoms_in_representations(self):
missing_atoms = np.zeros(self.natoms)
for rep in self._all_representations:
missing_atoms += rep.atoms_in_representation(self.structure)
missing_atoms = np.where(missing_atoms == 0)[0]
if len(missing_atoms) > 0:
self.atoms_not_represented.value = (
"Atoms excluded from representations: "
+ list_to_string_range(list(missing_atoms), shift=1)
)
else:
self.atoms_not_represented.value = ""
@tl.observe("cell")
def _observe_cell(self, _=None):
# Updtate the Cell and Periodicity.
if self.cell:
self.cell_a.value = "<i><b>a</b></i>: {:.4f} {:.4f} {:.4f}".format(
*self.cell.array[0]
)
self.cell_b.value = "<i><b>b</b></i>: {:.4f} {:.4f} {:.4f}".format(
*self.cell.array[1]
)
self.cell_c.value = "<i><b>c</b></i>: {:.4f} {:.4f} {:.4f}".format(
*self.cell.array[2]
)
self.cell_a_length.value = "|<i><b>a</b></i>|: {:.4f}".format(
self.cell.lengths()[0]
)
self.cell_b_length.value = "|<i><b>b</b></i>|: {:.4f}".format(
self.cell.lengths()[1]
)
self.cell_c_length.value = "|<i><b>c</b></i>|: {:.4f}".format(
self.cell.lengths()[2]
)
self.cell_alpha.value = f"α: {self.cell.angles()[0]:.4f}"
self.cell_beta.value = f"β: {self.cell.angles()[1]:.4f}"
self.cell_gamma.value = f"γ: {self.cell.angles()[2]:.4f}"
spglib_structure = ase2spglib(self.structure)
symmetry_dataset = spglib.get_symmetry_dataset(
spglib_structure, symprec=1e-5, angle_tolerance=1.0
)
periodicity_map = {
(True, True, True): "xyz",
(True, False, False): "x",
(False, True, False): "y",
(False, False, True): "z",
(True, True, False): "xy",
(True, False, True): "xz",
(False, True, True): "yz",
(False, False, False): "-",
}
self.cell_spacegroup.value = f"Spacegroup: {symmetry_dataset['international']} (No.{symmetry_dataset['number']})"
self.cell_hall.value = f"Hall: {symmetry_dataset['hall']} (No.{symmetry_dataset['hall_number']})"
self.periodicity.value = (
f"Periodicity: {periodicity_map[tuple(self.structure.pbc)]}"
)
else:
self.cell_a.value = "<i><b>a</b></i>:"
self.cell_b.value = "<i><b>b</b></i>:"
self.cell_c.value = "<i><b>c</b></i>:"
self.cell_a_length.value = "|<i><b>a</b></i>|:"
self.cell_b_length.value = "|<i><b>b</b></i>|:"
self.cell_c_length.value = "|<i><b>c</b></i>|:"
self.cell_alpha.value = "α:"
self.cell_beta.value = "β:"
self.cell_gamma.value = "γ:"
self.cell_spacegroup.value = ""
self.cell_hall.value = ""
self.periodicity.value = ""
def _cell_tab(self):
self.cell_a = ipw.HTML()
self.cell_b = ipw.HTML()
self.cell_c = ipw.HTML()
self.cell_a_length = ipw.HTML()
self.cell_b_length = ipw.HTML()
self.cell_c_length = ipw.HTML()
self.cell_alpha = ipw.HTML()
self.cell_beta = ipw.HTML()
self.cell_gamma = ipw.HTML()
self.cell_spacegroup = ipw.HTML()
self.cell_hall = ipw.HTML()
self.periodicity = ipw.HTML()
self._observe_cell()
return ipw.VBox(
[
ipw.HTML("Length unit: angstrom (Å)"),
ipw.HBox(
[
ipw.VBox(
[
ipw.HTML("Cell vectors:"),
self.cell_a,
self.cell_b,
self.cell_c,
]
),
ipw.VBox(
[
ipw.HTML("Сell vectors length:"),
self.cell_a_length,
self.cell_b_length,
self.cell_c_length,
],
layout={"margin": "0 0 0 50px"},
),
]
),
ipw.HBox(
[
ipw.VBox(
[
ipw.HTML("Angles:"),
self.cell_alpha,
self.cell_beta,
self.cell_gamma,
]
),
ipw.VBox(
[
ipw.HTML("Symmetry information:"),
self.cell_spacegroup,
self.cell_hall,
self.periodicity,
],
layout={"margin": "0 0 0 50px"},
),
]
),
]
)
def _download_tab(self):
"""Defining the download tab."""
# 1. Choose download file format.
self.file_format = ipw.Dropdown(
label="Extended xyz",
# File extension and format may be different. Therefore, we define both.
options=(
("xyz", {"extension": "xyz", "format": "xyz"}),
("cif", {"extension": "cif", "format": "cif"}),
("Extended xyz", {"extension": "xyz", "format": "extxyz"}),
("xsf", {"extension": "xsf", "format": "xsf"}),
),
layout={"width": "200px"},
description="File format:",
)
# 2. Download button.
self.download_btn = ipw.Button(description="Download")
self.download_btn.on_click(self.download)
self.download_box = ipw.VBox(
children=[
ipw.Label("Download as file:"),
ipw.HBox([self.file_format, self.download_btn]),
]
)
# 3. Screenshot button
self.screenshot_btn = ipw.Button(description="Screenshot", icon="camera")
self.screenshot_btn.on_click(lambda _: self._viewer.download_image())
self.screenshot_box = ipw.VBox(
children=[ipw.Label("Create a screenshot:"), self.screenshot_btn]
)
# 4. Render a high quality image
self.render_btn = ipw.Button(description="Render", icon="paint-brush")
self.render_btn.on_click(self._render_structure)
self.render_box = ipw.VBox(
children=[ipw.Label("Render an image with POVRAY:"), self.render_btn]
)
return ipw.VBox([self.download_box, self.screenshot_box, self.render_box])
def _render_structure(self, change=None):
"""Render the structure with POVRAY."""
if not isinstance(self.displayed_structure, ase.Atoms):
return
self.render_btn.disabled = True
omat = np.array(self._viewer._camera_orientation).reshape(4, 4).transpose()
zfactor = np.linalg.norm(omat[0, 0:3])
omat[0:3, 0:3] = omat[0:3, 0:3] / zfactor
bb = copy.deepcopy(self.displayed_structure)
bb.pbc = (False, False, False)
for i in bb:
ixyz = omat[0:3, 0:3].dot(np.array([i.x, i.y, i.z]) + omat[0:3, 3])
i.x, i.y, i.z = -ixyz[0], ixyz[1], ixyz[2]
vertices = []
cell = bb.get_cell()
vertices.append(np.array([0, 0, 0]))
vertices.extend(cell)
vertices.extend(
[
cell[0] + cell[1],
cell[0] + cell[2],
cell[1] + cell[2],
cell[0] + cell[1] + cell[2],
]
)
for n, i in enumerate(vertices):
ixyz = omat[0:3, 0:3].dot(i + omat[0:3, 3])
vertices[n] = np.array([-ixyz[0], ixyz[1], ixyz[2]])
bonds = self._compute_bonds(bb, povray=True)
edges = []
for x, i in enumerate(vertices):
for j in vertices[x + 1 :]:
if (
np.linalg.norm(np.cross(i - j, vertices[1] - vertices[0])) < 0.001
or np.linalg.norm(np.cross(i - j, vertices[2] - vertices[0]))
< 0.001
or np.linalg.norm(np.cross(i - j, vertices[3] - vertices[0]))
< 0.001
):
edge = vapory.Cylinder(
i,
j,
0.06,
vapory.Texture(
vapory.Pigment(
"color", [212 / 255.0, 175 / 255.0, 55 / 255.0]
)
),
vapory.Finish("phong", 0.9, "reflection", 0.01),
)
edges.append(edge)
camera = vapory.Camera(
"perspective",
"location",
[0, 0, -zfactor / 1.5],
"look_at",
[0.0, 0.0, 0.0],
)
light = vapory.LightSource([0, 0, -100.0], "color", [1.5, 1.5, 1.5])
spheres = [
vapory.Sphere(
[i.x, i.y, i.z],
Radius[i.symbol],
vapory.Texture(vapory.Pigment("color", np.array(Colors[i.symbol]))),
vapory.Finish("phong", 0.9, "reflection", 0.05),
)
for i in bb
]
objects = (
[light]
+ spheres
+ edges
+ bonds
+ [vapory.Background("color", np.array(to_rgb(self._viewer.background)))]
)
scene = vapory.Scene(camera, objects=objects)
fname = bb.get_chemical_formula() + ".png"
scene.render(
fname,
width=2560,
height=1440,
antialiasing=0.000,
quality=11,
remove_temp=False,
)
with open(fname, "rb") as raw:
payload = base64.b64encode(raw.read()).decode()
self._download(payload=payload, filename=fname)
self.render_btn.disabled = False
def _on_atom_click(self, _=None):
"""Update selection when clicked on atom."""
if hasattr(self._viewer, "component_0"):
# Did not click on atom:
if "atom1" not in self._viewer.picked.keys():
return
index = self._viewer.picked["atom1"]["index"]
displayed_selection = self.displayed_selection.copy()
if displayed_selection:
if index not in displayed_selection:
displayed_selection.append(index)
else:
displayed_selection.remove(index)
else:
displayed_selection = [index]
self.displayed_selection = displayed_selection
def highlight_atoms(
self,
list_of_atoms,
):
"""Highlighting atoms according to the provided list."""
if not hasattr(self._viewer, "component_0"):
return
# Create the dictionaries for highlight_representations.
for i, representation in enumerate(self._all_representations):
# First remove the previous highlight_representation.
self._viewer._remove_representations_by_name(
repr_name=f"highlight_representation_{i}", component=0
)
# Then add the new one if needed.
indices = np.intersect1d(
list_of_atoms,
np.where(
representation.atoms_in_representation(self.displayed_structure)
)[0],
)
if len(indices) > 0:
params = representation.nglview_parameters(indices)
params["params"]["name"] = f"highlight_representation_{i}"
params["params"]["opacity"] = 0.8
params["params"]["color"] = "darkgreen"
params["params"]["component_index"] = 0
# Use directly the remote call for more flexibility.
self._viewer._remote_call(
"addRepresentation",
target="compList",
args=[params["type"]],
kwargs=params["params"],
)
def remove_viewer_components(self, c=None):
"""Remove all components from the viewer except the one specified."""
if hasattr(self._viewer, "component_0"):
self._viewer.component_0.clear_representations()
cid = self._viewer.component_0.id