forked from aiidalab/aiidalab-widgets-base
-
Notifications
You must be signed in to change notification settings - Fork 0
/
structures.py
1532 lines (1298 loc) · 56.5 KB
/
structures.py
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
"""Module to provide functionality to import structures."""
# pylint: disable=no-self-use
import datetime
import functools
import io
import pathlib
import tempfile
from collections import OrderedDict
import ase
import ipywidgets as ipw
import numpy as np
from copy import deepcopy
# spglib for cell converting
import spglib
# AiiDA imports
from aiida.engine import calcfunction
from aiida.orm import (
CalcFunctionNode,
CalcJobNode,
Data,
Node,
QueryBuilder,
WorkChainNode,
)
from aiida.plugins import DataFactory
from ase import Atom, Atoms
from ase.data import chemical_symbols, covalent_radii
from sklearn.decomposition import PCA
from traitlets import Bool,Dict, Instance, Int, List, Unicode, Union, default, dlink, link, observe
# Local imports
from .data import LigandSelectorWidget
from .utils import StatusHTML, get_ase_from_file, get_formula
from .viewers import StructureDataViewer
CifData = DataFactory("cif")
StructureData = DataFactory("structure")
TrajectoryData = DataFactory("array.trajectory")
SYMBOL_RADIUS = {key: covalent_radii[i] for i, key in enumerate(chemical_symbols)}
class StructureManagerWidget(ipw.VBox):
"""Upload a structure and store it in AiiDA database.
Attributes:
structure(Atoms): trait that contains the selected structure. 'None' if no structure is selected.
structure_node(StructureData, CifData): trait that contains AiiDA structure object
node_class(str): trait that contains structure_node type (as string).
"""
input_structure = Union([Instance(Atoms), Instance(Data)], allow_none=True)
structure = Union([Instance(Atoms), Instance(Data)], allow_none=True)
structure_node = Instance(Data, allow_none=True, read_only=True)
node_class = Unicode()
list_of_representations = List()
#brand_new_structure = Bool()
SUPPORTED_DATA_FORMATS = {"CifData": "cif", "StructureData": "structure"}
def __init__(
self,
importers,
viewer=None,
editors=None,
storable=True,
node_class=None,
**kwargs,
):
"""
Arguments:
importers(list): list of tuples each containing the displayed name of importer and the
importer object. Each object should contain 'structure' trait pointing to the imported
structure. The trait will be linked to 'structure' trait of this class.
storable(bool): Whether to provide Store button (together with Store format)
node_class(str): AiiDA node class for storing the structure.
Possible values: 'StructureData', 'CifData' or None (let the user decide).
Note: If your workflows require a specific node class, better fix it here.
"""
# History of modifications
self.history = []
# Undo functionality.
btn_undo = ipw.Button(description="Undo", button_style="success")
btn_undo.on_click(self.undo)
self.structure_set_by_undo = False
# To keep track of last inserted structure object
self._inserted_structure = None
# Structure viewer.
if viewer:
self.viewer = viewer
else:
self.viewer = StructureDataViewer(**kwargs)
dlink((self, "structure_node"), (self.viewer, "structure"))
dlink((self, "input_structure"), (self.viewer, "input_structure"))
# Store button.
self.btn_store = ipw.Button(description="Store in AiiDA", disabled=True)
self.btn_store.on_click(self.store_structure)
# Label and description that are stored along with the new structure.
self.structure_label = ipw.Text(description="Label")
self.structure_description = ipw.Text(description="Description")
# Store format selector.
data_format = ipw.RadioButtons(
options=self.SUPPORTED_DATA_FORMATS, description="Data type:"
)
link((data_format, "label"), (self, "node_class"))
# Store button, store class selector, description.
store_and_description = [self.btn_store] if storable else []
if node_class is None:
store_and_description.append(data_format)
elif node_class in self.SUPPORTED_DATA_FORMATS:
self.node_class = node_class
else:
raise ValueError(
"Unknown data format '{}'. Options: {}".format(
node_class, list(self.SUPPORTED_DATA_FORMATS.keys())
)
)
self.output = ipw.HTML("")
children = [
self._structure_importers(importers),
self.viewer,
ipw.HBox(
store_and_description
+ [self.structure_label, self.structure_description]
),
]
structure_editors = self._structure_editors(editors)
if structure_editors:
structure_editors = ipw.VBox([btn_undo, structure_editors])
accordion = ipw.Accordion([structure_editors])
accordion.selected_index = None
accordion.set_title(0, "Edit Structure")
children += [accordion]
super().__init__(children=children + [self.output], **kwargs)
def _structure_importers(self, importers):
"""Preparing structure importers."""
if not importers:
raise ValueError(
"The parameter importers should contain a list (or tuple) of "
"importers, got a falsy object."
)
# If there is only one importer - no need to make tabs.
if len(importers) == 1:
# Assigning a function which will be called when importer provides a structure.
dlink((importers[0], "structure"), (self, "input_structure"))
#if importers[0].has_trait("brand_new_structure"):
# link((importers[0], "brand_new_structure"), (self.viewer, "brand_new_structure"))
# link((importers[0], "brand_new_structure"), (self, "brand_new_structure"))
return importers[0]
# Otherwise making one tab per importer.
importers_tab = ipw.Tab()
importers_tab.children = [i for i in importers] # One importer per tab.
for i, importer in enumerate(importers):
# Labeling tabs.
importers_tab.set_title(i, importer.title)
dlink((importer, "structure"), (self, "input_structure"))
#if importer.has_trait("brand_new_structure"):
# link((importer, "brand_new_structure"), (self.viewer, "brand_new_structure"))
# link((importer, "brand_new_structure"), (self, "brand_new_structure"))
return importers_tab
def _structure_editors(self, editors):
"""Preparing structure editors."""
if editors and len(editors) == 1:
link((editors[0], "structure"), (self, "structure"))
if editors[0].has_trait("selection"):
link((editors[0], "selection"), (self.viewer, "selection"))
if editors[0].has_trait("list_of_representations"):
link((editors[0], "list_of_representations"), (self.viewer, "list_of_representations"))
link((editors[0], "list_of_representations"), (self, "list_of_representations"))
if editors[0].has_trait("camera_orientation"):
dlink(
(self.viewer._viewer, "_camera_orientation"),
(editors[0], "camera_orientation"),
) # pylint: disable=protected-access
return editors[0]
# If more than one editor was defined.
if editors:
editors_tab = ipw.Tab()
editors_tab.children = tuple(editors)
for i, editor in enumerate(editors):
editors_tab.set_title(i, editor.title)
link((editor, "structure"), (self, "structure"))
if editor.has_trait("selection"):
link((editor, "selection"), (self.viewer, "selection"))
if editor.has_trait("list_of_representations"):
link((editors, "list_of_representations"), (self.viewer, "list_of_representations"))
link((editors, "list_of_representations"), (self, "list_of_representations"))
if editor.has_trait("camera_orientation"):
dlink(
(self.viewer._viewer, "_camera_orientation"),
(editor, "camera_orientation"),
) # pylint: disable=protected-access
return editors_tab
return None
def store_structure(self, _=None):
"""Stores the structure in AiiDA database."""
if self.structure_node is None:
return
if self.structure_node.is_stored:
self.output.value = "Already stored in AiiDA [{}], skipping...".format(
self.structure_node
)
return
self.btn_store.disabled = True
self.structure_node.label = self.structure_label.value
self.structure_label.disabled = True
self.structure_node.description = self.structure_description.value
self.structure_description.disabled = True
if isinstance(self.input_structure, Data) and self.input_structure.is_stored:
# Make a link between self.input_structure and self.structure_node
@calcfunction
def user_modifications(source_structure): # pylint: disable=unused-argument
return self.structure_node
structure_node = user_modifications(self.input_structure)
else:
structure_node = self.structure_node.store()
self.output.value = f"Stored in AiiDA [{structure_node}]"
def undo(self, _):
"""Undo modifications."""
self.structure_set_by_undo = True
if self.history:
self.history = self.history[:-1]
if self.history:
#self.brand_new_structure = False
self.structure = self.history[-1][0]
#print("in undo",self.history[-1][1])
self.list_of_representations = self.history[-1][1]
else:
self.input_structure = None
self.structure_set_by_undo = False
@staticmethod
@default("node_class")
def _default_node_class():
return "StructureData"
@observe("node_class")
def _change_structure_node(self, _=None):
with self.hold_trait_notifications():
self._sync_structure_node()
def _sync_structure_node(self):
"""Synchronize the structure_node trait using the currently provided info."""
if len(self.history) > 1:
# There are some modifications, so converting from ASE.
structure_node = self._convert_to_structure_node(self.structure)
else:
structure_node = self._convert_to_structure_node(self.input_structure)
self.set_trait("structure_node", structure_node)
def _convert_to_structure_node(self, structure):
"""Convert structure of any type to the StructureNode object."""
if structure is None:
return None
structure_node_type = DataFactory(
self.SUPPORTED_DATA_FORMATS[self.node_class]
) # pylint: disable=invalid-name
# If the input_structure trait is set to Atoms object, structure node must be created from it.
if isinstance(structure, Atoms):
# If the Atoms object was created by SmilesWidget,
# attach its SMILES code as an extra.
structure_node = structure_node_type(ase=structure)
if "smiles" in structure.info:
structure_node.set_extra("smiles", structure.info["smiles"])
return structure_node
# If the input_structure trait is set to AiiDA node, check what type
if isinstance(structure, Data):
# Transform the structure to the structure_node_type if needed.
if isinstance(structure, structure_node_type):
return structure
# Using self.structure, as it was already converted to the ASE Atoms object.
return structure_node_type(ase=self.structure)
@observe("structure_node")
def _observe_structure_node(self, change):
"""Modify structure label and description when a new structure is provided."""
struct = change["new"]
if struct is None:
self.btn_store.disabled = True
self.structure_label.value = ""
self.structure_label.disabled = True
self.structure_description.value = ""
self.structure_description.disabled = True
return
if struct.is_stored:
self.btn_store.disabled = True
self.structure_label.value = struct.label
self.structure_label.disabled = True
self.structure_description.value = struct.description
self.structure_description.disabled = True
else:
self.btn_store.disabled = False
self.structure_label.value = self.structure.get_chemical_formula()
self.structure_label.disabled = False
self.structure_description.value = ""
self.structure_description.disabled = False
@observe("input_structure")
def _observe_input_structure(self, change):
"""Returns ASE atoms object and sets structure_node trait."""
# If the `input_structure` trait is set to Atoms object, then the `structure` trait should be set to it as well.
self.history = []
if isinstance(change["new"], Atoms):
self.structure = change["new"]
# If the `input_structure` trait is set to AiiDA node, then the `structure` trait should
# be converted to an ASE Atoms object.
elif isinstance(
change["new"], CifData
): # Special treatement of the CifData object
str_io = io.StringIO(change["new"].get_content())
self.structure = ase.io.read(
str_io, format="cif", reader="ase", store_tags=True
)
elif isinstance(change["new"], StructureData):
self.structure = change["new"].get_ase()
else:
self.structure = None
@observe("list_of_representations")
def _observe_list_of_representations(self, change=None):
"""Update list of representations in the history list."""
#print("observe list_rep of history")
self.history[-1]=(self.history[-1][0],deepcopy(self.list_of_representations))
#print(self.history)
@observe("structure")
def _structure_changed(self, change=None):
"""Perform some operations that depend on the value of `structure` trait.
This function enables/disables `btn_store` widget if structure is provided/set to None.
Also, the function sets `structure_node` trait to the selected node type.
"""
if not self.structure_set_by_undo:
self.history.append((change["new"],deepcopy(self.list_of_representations)))
#print("history: ",self.history)
# If structure trait was set to None, structure_node should become None as well.
if self.structure is None:
self.set_trait("structure_node", None)
self.btn_store.disabled = True
return
self.btn_store.disabled = False
with self.hold_trait_notifications():
self._sync_structure_node()
class StructureUploadWidget(ipw.VBox):
"""Class that allows to upload structures from user's computer."""
structure = Union([Instance(Atoms), Instance(Data)], allow_none=True)
def __init__(
self, title="", description="Upload Structure", allow_trajectories=False
):
self.title = title
self.file_upload = ipw.FileUpload(
description=description, multiple=False, layout={"width": "initial"}
)
# Whether to allow uploading multiple structures from a single file.
# In this case, we create TrajectoryData node.
self.allow_trajectories = allow_trajectories
supported_formats = ipw.HTML(
"""<a href="https://wiki.fysik.dtu.dk/ase/ase/io/io.html#ase.io.write" target="_blank">
Supported structure formats
</a>"""
)
self._status_message = StatusHTML(clear_after=5)
self.file_upload.observe(self._on_file_upload, names="value")
super().__init__(
children=[self.file_upload, supported_formats, self._status_message]
)
def _validate_and_fix_ase_cell(self, ase_structure, vacuum_ang=10.0):
"""
Checks if the ase Atoms object has a cell set,
otherwise sets it to bounding box plus specified "vacuum" space
"""
if not ase_structure:
return None
cell = ase_structure.cell
# TODO: Since AiiDA 2.0, zero cell is possible if PBC=false
# so we should honor that here and do not put artificial cell
# around gas phase molecules.
if (
np.linalg.norm(cell[0]) < 0.1
or np.linalg.norm(cell[1]) < 0.1
or np.linalg.norm(cell[2]) < 0.1
):
# if any of the cell vectors is too short, consider it faulty
# set cell as bounding box + vacuum_ang
bbox = np.ptp(ase_structure.positions, axis=0)
new_structure = ase_structure.copy()
new_structure.cell = bbox + vacuum_ang
return new_structure
return ase_structure
def _on_file_upload(self, change=None):
"""When file upload button is pressed."""
for fname, item in change["new"].items():
self.structure = self._read_structure(fname, item["content"])
self.file_upload.value.clear()
break
def _read_structure(self, fname, content):
suffix = "".join(pathlib.Path(fname).suffixes)
if suffix == ".cif":
try:
return CifData(file=io.BytesIO(content))
except Exception as e:
self._status_message.message = f"""
<div class="alert alert-warning">Could not parse CIF file {fname}: {e}
Trying ASE reader...</div>
"""
with tempfile.NamedTemporaryFile(suffix=suffix) as temp_file:
temp_file.write(content)
temp_file.flush()
try:
if suffix == ".cif":
structures = get_ase_from_file(temp_file.name, format="cif")
else:
structures = get_ase_from_file(temp_file.name)
except ValueError as e:
self._status_message.message = f"""
<div class="alert alert-danger">ERROR: {e}</div>
"""
return None
except KeyError:
self._status_message.message = f"""
<div class="alert alert-danger">ERROR: Could not parse file {fname}</div>
"""
return None
if len(structures) > 1:
if self.allow_trajectories:
return TrajectoryData(
structurelist=[
StructureData(
ase=self._validate_and_fix_ase_cell(ase_struct)
)
for ase_struct in structures
]
)
else:
self._status_message.message = f"""
<div class="alert alert-danger">ERROR: More than one structure found in file {fname}</div>
"""
return None
return self._validate_and_fix_ase_cell(structures[0])
class StructureExamplesWidget(ipw.VBox):
"""Class to provide example structures for selection."""
structure = Instance(Atoms, allow_none=True)
def __init__(self, examples, title="", **kwargs):
self.title = title
self.on_structure_selection = lambda structure_ase, name: None
self._select_structure = ipw.Dropdown(
options=self.get_example_structures(examples)
)
self._select_structure.observe(self._on_select_structure, names=["value"])
super().__init__(children=[self._select_structure], **kwargs)
@staticmethod
def get_example_structures(examples):
"""Get the list of example structures."""
if not isinstance(examples, list):
raise ValueError(
"parameter examples should be of type list, {} given".format(
type(examples)
)
)
return [("Select structure", False)] + examples
def _on_select_structure(self, change): # pylint: disable=unused-argument
"""When structure is selected."""
self.structure = (
get_ase_from_file(self._select_structure.value)[0]
if self._select_structure.value
else None
)
@default("structure")
def _default_structure(self):
return None
class StructureBrowserWidget(ipw.VBox):
"""Class to query for structures stored in the AiiDA database.
:param title: Title of the widget displayed on a tab in StructureManagerWidget
:type title: string
:param query_types: A tuple of Data node types that are searched (default: StructureData, CifData)
:type query_types: tuple
"""
structure = Union([Instance(Atoms), Instance(Data)], allow_none=True)
def __init__(self, title="", query_types=None):
self.title = title
# Structure objects we want to query for.
if query_types:
self.query_structure_type = query_types
else:
self.query_structure_type = (StructureData, CifData)
# Extracting available process labels.
qbuilder = QueryBuilder().append((CalcJobNode, WorkChainNode), project="label")
self.drop_label = ipw.Dropdown(
options=sorted({"All"}.union({i[0] for i in qbuilder.iterall() if i[0]})),
value="All",
description="Process Label",
disabled=True,
style={"description_width": "120px"},
layout={"width": "50%"},
)
self.drop_label.observe(self.search, names="value")
# Disable process labels selection if we are not looking for the calculated structures.
def disable_drop_label(change):
self.drop_label.disabled = not change["new"] == "calculated"
# Select structures kind.
self.mode = ipw.RadioButtons(
options=["all", "uploaded", "edited", "calculated"], layout={"width": "25%"}
)
self.mode.observe(self.search, names="value")
self.mode.observe(disable_drop_label, names="value")
# Date range.
# Note: there is Date picker widget, but it currently does not work in Safari:
# https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20List.html#Date-picker
date_text = ipw.HTML(value="<p>Select the date range:</p>")
self.start_date_widget = ipw.Text(
value="", description="From: ", style={"description_width": "120px"}
)
self.end_date_widget = ipw.Text(value="", description="To: ")
# Search button.
btn_search = ipw.Button(
description="Search",
button_style="info",
layout={"width": "initial", "margin": "2px 0 0 2em"},
)
btn_search.on_click(self.search)
age_selection = ipw.VBox(
[
date_text,
ipw.HBox([self.start_date_widget, self.end_date_widget, btn_search]),
],
layout={"border": "1px solid #fafafa", "padding": "1em"},
)
h_line = ipw.HTML("<hr>")
box = ipw.VBox([age_selection, h_line, ipw.HBox([self.mode, self.drop_label])])
self.results = ipw.Dropdown(layout={"width": "900px"})
self.results.observe(self._on_select_structure, names="value")
self.search()
super().__init__([box, h_line, self.results])
def preprocess(self):
"""Search structures in AiiDA database and add formula extra to them."""
queryb = QueryBuilder()
queryb.append(
self.query_structure_type, filters={"extras": {"!has_key": "formula"}}
)
for item in queryb.all(): # iterall() would interfere with set_extra()
try:
formula = get_formula(item[0])
item[0].set_extra("formula", formula)
except ValueError:
pass
def search(self, _=None):
"""Launch the search of structures in AiiDA database."""
self.preprocess()
qbuild = QueryBuilder()
# If the date range is valid, use it for the search
try:
start_date = datetime.datetime.strptime(
self.start_date_widget.value, "%Y-%m-%d"
)
end_date = datetime.datetime.strptime(
self.end_date_widget.value, "%Y-%m-%d"
) + datetime.timedelta(hours=24)
# Otherwise revert to the standard (i.e. last 7 days)
except ValueError:
start_date = datetime.datetime.now() - datetime.timedelta(days=7)
end_date = datetime.datetime.now() + datetime.timedelta(hours=24)
self.start_date_widget.value = start_date.strftime("%Y-%m-%d")
self.end_date_widget.value = end_date.strftime("%Y-%m-%d")
filters = {}
filters["ctime"] = {"and": [{">": start_date}, {"<=": end_date}]}
if self.mode.value == "uploaded":
qbuild2 = (
QueryBuilder()
.append(self.query_structure_type, project=["id"], tag="structures")
.append(Node, with_outgoing="structures")
)
processed_nodes = [n[0] for n in qbuild2.all()]
if processed_nodes:
filters["id"] = {"!in": processed_nodes}
qbuild.append(self.query_structure_type, filters=filters)
elif self.mode.value == "calculated":
if self.drop_label.value == "All":
qbuild.append((CalcJobNode, WorkChainNode), tag="calcjobworkchain")
else:
qbuild.append(
(CalcJobNode, WorkChainNode),
filters={"label": self.drop_label.value},
tag="calcjobworkchain",
)
qbuild.append(
self.query_structure_type,
with_incoming="calcjobworkchain",
filters=filters,
)
elif self.mode.value == "edited":
qbuild.append(CalcFunctionNode)
qbuild.append(
self.query_structure_type,
with_incoming=CalcFunctionNode,
filters=filters,
)
elif self.mode.value == "all":
qbuild.append(self.query_structure_type, filters=filters)
qbuild.order_by({self.query_structure_type: {"ctime": "desc"}})
matches = {n[0] for n in qbuild.iterall()}
matches = sorted(matches, reverse=True, key=lambda n: n.ctime)
options = OrderedDict()
options[f"Select a Structure ({len(matches)} found)"] = False
for mch in matches:
label = f"PK: {mch.id}"
label += " | " + mch.ctime.strftime("%Y-%m-%d %H:%M")
label += " | " + mch.get_extra("formula", "")
label += " | " + mch.node_type.split(".")[-2]
label += " | " + mch.label
label += " | " + mch.description
options[label] = mch
self.results.options = options
def _on_select_structure(self, _=None):
self.structure = self.results.value or None
class SmilesWidget(ipw.VBox):
"""Convert SMILES into 3D structure."""
structure = Instance(Atoms, allow_none=True)
#brand_new_structure = Bool()
SPINNER = """<i class="fa fa-spinner fa-pulse" style="color:red;" ></i>"""
def __init__(self, title=""):
# pylint: disable=unused-import
self.title = title
try:
from openbabel import openbabel # noqa: F401
from openbabel import pybel # noqa: F401
except ImportError:
super().__init__(
[
ipw.HTML(
"The SmilesWidget requires the OpenBabel library, "
"but the library was not found."
)
]
)
return
try:
from rdkit import Chem # noqa: F401
from rdkit.Chem import AllChem # noqa: F401
except ImportError:
super().__init__(
[
ipw.HTML(
"The SmilesWidget requires the rdkit library, "
"but the library was not found."
)
]
)
return
self.smiles = ipw.Text(placeholder="C=C")
self.create_structure_btn = ipw.Button(
description="Generate molecule",
button_style="primary",
tooltip="Generate molecule from SMILES string",
)
self.create_structure_btn.on_click(self._on_button_pressed)
self.output = ipw.HTML("")
super().__init__(
[ipw.HBox([self.smiles, self.create_structure_btn]), self.output]
)
def _make_ase(self, species, positions, smiles):
"""Create ase Atoms object."""
# Get the principal axes and realign the molecule along z-axis.
positions = PCA(n_components=3).fit_transform(positions)
atoms = Atoms(species, positions=positions, pbc=False)
atoms.cell = np.ptp(atoms.positions, axis=0) + 10
atoms.center()
# We're attaching this info so that it
# can be later stored as an extra on AiiDA Structure node.
atoms.info["smiles"] = smiles
return atoms
def _pybel_opt(self, smiles, steps):
"""Optimize a molecule using force field and pybel (needed for complex SMILES)."""
from openbabel import openbabel as ob
from openbabel import pybel as pb
obconversion = ob.OBConversion()
obconversion.SetInFormat("smi")
obmol = ob.OBMol()
obconversion.ReadString(obmol, smiles)
pbmol = pb.Molecule(obmol)
pbmol.make3D(forcefield="uff", steps=50)
pbmol.localopt(forcefield="gaff", steps=200)
pbmol.localopt(forcefield="mmff94", steps=100)
f_f = pb._forcefields["uff"] # pylint: disable=protected-access
f_f.Setup(pbmol.OBMol)
f_f.ConjugateGradients(steps, 1.0e-9)
f_f.GetCoordinates(pbmol.OBMol)
species = [chemical_symbols[atm.atomicnum] for atm in pbmol.atoms]
positions = np.asarray([atm.coords for atm in pbmol.atoms])
return self._make_ase(species, positions, smiles)
def _rdkit_opt(self, smiles, steps):
"""Optimize a molecule using force field and rdkit (needed for complex SMILES)."""
from rdkit import Chem
from rdkit.Chem import AllChem
mol = Chem.MolFromSmiles(smiles)
if mol is None:
# Something is seriously wrong with the SMILES code,
# just return None and don't attempt anything else.
self.output.value = "RDKit ERROR: Invalid SMILES string"
return None
mol = Chem.AddHs(mol)
AllChem.EmbedMolecule(mol, maxAttempts=20, randomSeed=42)
if AllChem.UFFHasAllMoleculeParams(mol):
AllChem.UFFOptimizeMolecule(mol, maxIters=steps)
else:
self.output.value = "RDKit WARNING: Missing UFF parameters"
positions = mol.GetConformer().GetPositions()
natoms = mol.GetNumAtoms()
species = [mol.GetAtomWithIdx(j).GetSymbol() for j in range(natoms)]
return self._make_ase(species, positions, smiles)
def _mol_from_smiles(self, smiles, steps=1000):
"""Convert SMILES to ase structure try rdkit then pybel"""
try:
return self._rdkit_opt(smiles, steps)
except ValueError as e:
self.output.value = str(e)
self.output.value += " Trying OpenBabel..."
return self._pybel_opt(smiles, steps)
def _on_button_pressed(self, change): # pylint: disable=unused-argument
"""Convert SMILES to ase structure when button is pressed."""
self.output.value = ""
if not self.smiles.value:
return
spinner = f"Screening possible conformers {self.SPINNER}" # font-size:20em;
self.output.value = spinner
self.structure = self._mol_from_smiles(self.smiles.value)
# Don't overwrite possible error/warning messages
if self.output.value == spinner:
self.output.value = ""
@default("structure")
def _default_structure(self):
return None
def _register_structure(operator):
"""
Decorator for methods that manipulate (operate on) the selected structure.
Checks whether a structure and selection is set and ensures that the
arguments for structure and selection are passed by copy rather than
reference. A pop-up warning message is shown in case that neither a
structure or selection are set.
"""
@functools.wraps(operator)
def inner(ref, *args, **kwargs):
if not ref.structure:
ref._status_message.message = """
<div class="alert alert-info">
<strong>Please choose a structure first.</strong>
</div>
"""
else:
operator(
ref,
*args,
**kwargs,
atoms=ref.structure.copy(),
)
return inner
def _register_selection(operator):
"""
Decorator for methods that manipulate (operate on) the selected structure.
Checks whether a structure and selection is set and ensures that the
arguments for structure and selection are passed by copy rather than
reference. A pop-up warning message is shown in case that neither a
structure or selection are set.
"""
@functools.wraps(operator)
def inner(ref, *args, **kwargs):
if not ref.selection:
ref._status_message.message = """
<div class="alert alert-info">
<strong>Please select atoms first.</strong>
</div>
"""
else:
operator(
ref,
*args,
**kwargs,
selection=ref.selection.copy(),
)
return inner
class BasicCellEditor(ipw.VBox):
"""Widget that allows for the basic cell editing."""
structure = Instance(Atoms, allow_none=True)
def __init__(self, title="Cell transform"):
self.title = title
# cell transfor opration widget
primitive_cell = ipw.Button(
description="Convert to primitive cell",
layout={"width": "initial"},
)
primitive_cell.on_click(self.def_primitive_cell)
conventional_cell = ipw.Button(
description="Convert to conventional cell",
layout={"width": "initial"},
)
conventional_cell.on_click(self.def_conventional_cell)
super().__init__(
children=[
ipw.HBox(
[
primitive_cell,
conventional_cell,
],
),
],
)
@_register_structure
def def_primitive_cell(self, _=None, atoms=None):
atoms = self._to_standard_cell(atoms, to_primitive=True)
self.structure = atoms
@_register_structure
def def_conventional_cell(self, _=None, atoms=None):
atoms = self._to_standard_cell(atoms, to_primitive=False)
self.structure = atoms
@staticmethod
def _to_standard_cell(
structure: Atoms, to_primitive=False, no_idealize=False, symprec=1e-5
):
"""The `standardize_cell` method from spglib and apply to ase.Atoms"""
lattice = structure.get_cell()
positions = structure.get_scaled_positions()
numbers = structure.get_atomic_numbers()
cell = (lattice, positions, numbers)
# operation
lattice, positions, numbers = spglib.standardize_cell(
cell, to_primitive=to_primitive, no_idealize=no_idealize, symprec=symprec
)
return Atoms(
cell=lattice,
scaled_positions=positions,
numbers=numbers,
pbc=[True, True, True],
)
class BasicStructureEditor(ipw.VBox): # pylint: disable=too-many-instance-attributes
"""
Widget that allows for the basic structure (molecule and
position of periodic structure in cell) editing."""
structure = Instance(Atoms, allow_none=True)
list_of_representations = List([[]])
selection = List(Int)
camera_orientation = List()
def __init__(self, title=""):
self.title = title
# Define action vector.
self.axis_p1 = ipw.Text(
description="Starting point", value="0 0 0", layout={"width": "initial"}
)
self.axis_p2 = ipw.Text(
description="Ending point", value="0 0 1", layout={"width": "initial"}
)
btn_def_atom1 = ipw.Button(
description="From selection", layout={"width": "initial"}
)
btn_def_atom1.on_click(self.def_axis_p1)