/
atoms.py
3258 lines (2770 loc) · 117 KB
/
atoms.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
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
from __future__ import division, print_function
from ase.atoms import Atoms as ASEAtoms, get_distances as ase_get_distances, Atom as ASEAtom
import ast
from copy import copy
from collections import OrderedDict
import numpy as np
from six import string_types
import warnings
from matplotlib.colors import rgb2hex
import seekpath
from pyiron.atomistics.structure.atom import Atom, ase_to_pyiron as ase_to_pyiron_atom
from pyiron.atomistics.structure.neighbors import Neighbors
from pyiron.atomistics.structure._visualize import Visualize
from pyiron.atomistics.structure.sparse_list import SparseArray, SparseList
from pyiron.atomistics.structure.periodic_table import (
PeriodicTable,
ChemicalElement
)
from pyiron_base import Settings
from scipy.spatial import cKDTree, Voronoi
import spglib
__author__ = "Joerg Neugebauer, Sudarsan Surendralal"
__copyright__ = (
"Copyright 2020, Max-Planck-Institut für Eisenforschung GmbH - "
"Computational Materials Design (CM) Department"
)
__version__ = "1.0"
__maintainer__ = "Sudarsan Surendralal"
__email__ = "surendralal@mpie.de"
__status__ = "production"
__date__ = "Sep 1, 2017"
s = Settings()
class Atoms(ASEAtoms):
"""
The Atoms class represents all the information required to describe a structure at the atomic scale. This class is
derived from the `ASE atoms class`_.
Args:
elements (list/numpy.ndarray): List of strings containing the elements or a list of
atomistics.structure.periodic_table.ChemicalElement instances
numbers (list/numpy.ndarray): List of atomic numbers of elements
symbols (list/numpy.ndarray): List of chemical symbols
positions (list/numpy.ndarray): List of positions
scaled_positions (list/numpy.ndarray): List of scaled positions (relative coordinates)
pbc (list/numpy.ndarray/boolean): Tells if periodic boundary conditions should be applied on the three axes
cell (list/numpy.ndarray instance): A 3x3 array representing the lattice vectors of the structure
Note: Only one of elements/symbols or numbers should be assigned during initialization
Attributes:
indices (numpy.ndarray): A list of size N which gives the species index of the structure which has N atoms
.. _ASE atoms class: https://wiki.fysik.dtu.dk/ase/ase/atoms.html
"""
def __init__(
self,
symbols=None,
positions=None,
numbers=None,
tags=None,
momenta=None,
masses=None,
magmoms=None,
charges=None,
scaled_positions=None,
cell=None,
pbc=None,
celldisp=None,
constraint=None,
calculator=None,
info=None,
indices=None,
elements=None,
dimension=None,
species=None,
**qwargs
):
if symbols is not None:
if elements is None:
elements = symbols
else:
raise ValueError("Only elements OR symbols should be given.")
if (
tags is not None
or momenta is not None
or masses is not None
or charges is not None
or celldisp is not None
or constraint is not None
or calculator is not None
or info is not None
):
s.logger.debug("Not supported parameter used!")
self._store_elements = dict()
self._species_to_index_dict = None
self._is_scaled = False
self._species = list()
self.indices = np.array([])
self.constraints = None
self._pse = PeriodicTable()
self._tag_list = SparseArray()
el_index_lst = list()
element_list = None
if numbers is not None: # for ASE compatibility
if not (elements is None):
raise AssertionError()
elements = self.numbers_to_elements(numbers)
if elements is not None:
el_object_list = None
if isinstance(elements, str):
element_list = self.convert_formula(elements)
elif isinstance(elements, (list, tuple, np.ndarray)):
if not all([isinstance(el, elements[0].__class__) for el in elements]):
object_list = list()
for el in elements:
if isinstance(el, (str, np.str, np.str_)):
object_list.append(self.convert_element(el))
if isinstance(el, ChemicalElement):
object_list.append(el)
if isinstance(el, Atom):
object_list.append(el.element)
if isinstance(el, (int, np.integer)):
# pse = PeriodicTable()
object_list.append(self._pse.element(el))
el_object_list = object_list
if len(elements) == 0:
element_list = elements
else:
if isinstance(elements[0], (list, tuple, np.ndarray)):
elements = np.array(elements).flatten()
if isinstance(elements[0], string_types):
element_list = elements
elif isinstance(elements[0], ChemicalElement):
el_object_list = elements
elif isinstance(elements[0], Atom):
el_object_list = [el.element for el in elements]
positions = [el.position for el in elements]
elif elements.dtype in [int, np.integer]:
el_object_list = self.numbers_to_elements(elements)
else:
raise ValueError(
"Unknown static type for element in list: "
+ str(type(elements[0]))
)
if el_object_list is None:
el_object_list = [self.convert_element(el) for el in element_list]
self.set_species(list(set(el_object_list)))
# species_to_index_dict = {el: i for i, el in enumerate(self.species)}
el_index_lst = [self._species_to_index_dict[el] for el in el_object_list]
elif indices is not None:
el_index_lst = indices
self.set_species(species)
self.indices = np.array(el_index_lst)
el_lst = [el.Abbreviation if el.Parent is None else el.Parent for el in self.species]
symbols = np.array([el_lst[el] for el in self.indices])
self._tag_list._length = len(symbols)
super(Atoms, self).__init__(symbols=symbols, positions=positions, numbers=None,
tags=tags, momenta=momenta, masses=masses,
magmoms=magmoms, charges=charges,
scaled_positions=scaled_positions, cell=cell,
pbc=pbc, celldisp=celldisp, constraint=constraint,
calculator=calculator, info=info)
self.bonds = None
self.units = {"length": "A", "mass": "u"}
self._symmetry_dataset = None
self.set_initial_magnetic_moments(magmoms)
self._high_symmetry_points = None
self._high_symmetry_path = None
self.dimension = dimension
if len(self.positions) > 0:
self.dimension = len(self.positions[0])
else:
self.dimension = 0
self.visualize = Visualize(self)
@property
def species(self):
"""
list: A list of atomistics.structure.periodic_table.ChemicalElement instances
"""
return self._species
# @species.setter
def set_species(self, value):
"""
Setting the species list
Args:
value (list): A list atomistics.structure.periodic_table.ChemicalElement instances
"""
if value is None:
return
value = list(value)
self._species_to_index_dict = {el: i for i, el in enumerate(value)}
self._species = value[:]
self._store_elements = {el.Abbreviation: el for el in value}
@property
def elements(self):
"""
numpy.ndarray: A size N list of atomistics.structure.periodic_table.ChemicalElement instances according
to the ordering of the atoms in the instance
"""
return np.array([self.species[el] for el in self.indices])
def get_high_symmetry_points(self):
"""
dictionary of high-symmetry points defined for this specific structure.
Returns:
dict: high_symmetry_points
"""
return self._high_symmetry_points
def _set_high_symmetry_points(self, new_high_symmetry_points):
"""
Sets new high symmetry points dictionary.
Args:
new_high_symmetry_points (dict): new high symmetry points
"""
if not isinstance(new_high_symmetry_points, dict):
raise ValueError("has to be dict!")
self._high_symmetry_points = new_high_symmetry_points
def add_high_symmetry_points(self, new_points):
"""
Adds new points to the dict of existing high symmetry points.
Args:
new_points (dict): Points to add
"""
if self.get_high_symmetry_points() is None:
raise AssertionError("Construct high symmetry points first. Use self.create_line_mode_structure().")
else:
self._high_symmetry_points.update(new_points)
def get_high_symmetry_path(self):
"""
Path used for band structure calculations
Returns:
dict: dict of pathes with start and end points.
"""
return self._high_symmetry_path
def _set_high_symmetry_path(self, new_path):
"""
Sets new list for the high symmetry path used for band structure calculations.
Args:
new_path (dict): dictionary of lists of tuples with start and end point.
E.G. {"my_path": [('Gamma', 'X'), ('X', 'Y')]}
"""
self._high_symmetry_path = new_path
def add_high_symmetry_path(self, path):
"""
Adds a new path to the dictionary of pathes for band structure calculations.
Args:
path (dict): dictionary of lists of tuples with start and end point.
E.G. {"my_path": [('Gamma', 'X'), ('X', 'Y')]}
"""
if self.get_high_symmetry_path() is None:
raise AssertionError("Construct high symmetry path first. Use self.create_line_mode_structure().")
for values_all in path.values():
for values in values_all:
if not len(values) == 2:
raise ValueError(
"'{}' is not a propper trace! It has to contain exactly 2 values! (start and end point)".format(
values))
for v in values:
if v not in self.get_high_symmetry_points().keys():
raise ValueError("'{}' is not a valid high symmetry point".format(v))
self._high_symmetry_path.update(path)
def add_tag(self, *args, **qwargs):
"""
Add tags to the atoms object.
Examples:
For selective dynamics::
>>> self.add_tag(selective_dynamics=[False, False, False])
"""
self._tag_list.add_tag(*args, **qwargs)
# @staticmethod
def numbers_to_elements(self, numbers):
"""
Convert atomic numbers in element objects (needed for compatibility with ASE)
Args:
numbers (list): List of Element Numbers (as Integers; default in ASE)
Returns:
list: A list of elements as needed for pyiron
"""
# pse = PeriodicTable() # TODO; extend to internal PSE which can contain additional elements and tags
atom_number_to_element = {}
for i_el in set(numbers):
i_el = int(i_el)
atom_number_to_element[i_el] = self._pse.element(i_el)
return [atom_number_to_element[i_el] for i_el in numbers]
def copy(self):
"""
Returns a copy of the instance
Returns:
pyiron.atomistics.structure.atoms.Atoms: A copy of the instance
"""
return self.__copy__()
def to_hdf(self, hdf, group_name="structure"):
"""
Save the object in a HDF5 file
Args:
hdf (pyiron_base.generic.hdfio.FileHDFio): HDF path to which the object is to be saved
group_name (str):
Group name with which the object should be stored. This same name should be used to retrieve the object
"""
# import time
with hdf.open(group_name) as hdf_structure:
# time_start = time.time()
hdf_structure["TYPE"] = str(type(self))
for el in self.species:
if isinstance(el.tags, dict):
with hdf_structure.open("new_species") as hdf_species:
el.to_hdf(hdf_species)
hdf_structure["species"] = [el.Abbreviation for el in self.species]
hdf_structure["indices"] = self.indices
with hdf_structure.open("tags") as hdf_tags:
for tag in self._tag_list.keys():
tag_value = self._tag_list[tag]
if isinstance(tag_value, SparseList):
tag_value.to_hdf(hdf_tags, tag)
hdf_structure["units"] = self.units
hdf_structure["dimension"] = self.dimension
if self.cell is not None:
with hdf_structure.open("cell") as hdf_cell:
# Convert ASE cell object to numpy array before storing
hdf_cell["cell"] = np.array(self.cell)
hdf_cell["pbc"] = self.pbc
# hdf_structure["coordinates"] = self.positions # "Atomic coordinates"
hdf_structure["positions"] = self.positions # "Atomic coordinates"
# potentials with explicit bonds (TIP3P, harmonic, etc.)
if self.bonds is not None:
hdf_structure["explicit_bonds"] = self.bonds
# print ('time in atoms.to_hdf: ', time.time() - time_start)
if self._high_symmetry_points is not None:
hdf_structure["high_symmetry_points"] = self._high_symmetry_points
if self._high_symmetry_path is not None:
hdf_structure["high_symmetry_path"] = self._high_symmetry_path
hdf_structure["info"] = self.info
def from_hdf(self, hdf, group_name="structure"):
"""
Retrieve the object from a HDF5 file
Args:
hdf (pyiron_base.generic.hdfio.FileHDFio): HDF path to which the object is to be saved
group_name (str): Group name from which the Atoms object is retreived.
Returns:
pyiron_atomistic.structure.atoms.Atoms: The retrieved atoms class
"""
if "indices" in hdf[group_name].list_nodes():
with hdf.open(group_name) as hdf_atoms:
if "new_species" in hdf_atoms.list_groups():
with hdf_atoms.open("new_species") as hdf_species:
self._pse.from_hdf(hdf_species)
el_object_list = [
self.convert_element(el, self._pse) for el in hdf_atoms["species"]
]
self.indices = hdf_atoms["indices"]
self._tag_list._length = len(self.indices)
self.set_species(el_object_list)
self.bonds = None
tr_dict = {1: True, 0: False}
self.dimension = hdf_atoms["dimension"]
self.units = hdf_atoms["units"]
if "cell" in hdf_atoms.list_groups():
with hdf_atoms.open("cell") as hdf_cell:
self.cell = hdf_cell["cell"]
self.pbc = hdf_cell["pbc"]
# Backward compatibility
position_tag = "positions"
if position_tag not in hdf_atoms.list_nodes():
position_tag = "coordinates"
if "is_absolute" in hdf_atoms.list_nodes():
if not tr_dict[hdf_atoms["is_absolute"]]:
self.set_scaled_positions(hdf_atoms[position_tag])
else:
self.arrays['positions'] = hdf_atoms[position_tag]
else:
self.arrays['positions'] = hdf_atoms[position_tag]
self.arrays['numbers'] = self.get_atomic_numbers()
if "explicit_bonds" in hdf_atoms.list_nodes():
# print "bonds: "
self.bonds = hdf_atoms["explicit_bonds"]
if "tags" in hdf_atoms.list_groups():
with hdf_atoms.open("tags") as hdf_tags:
tags = hdf_tags.list_nodes()
for tag in tags:
# tr_dict = {'0': False, '1': True}
if isinstance(hdf_tags[tag], (list, np.ndarray)):
my_list = hdf_tags[tag]
self._tag_list[tag] = SparseList(
my_list, length=len(self)
)
else:
my_dict = hdf_tags.get_pandas(tag).to_dict()
my_dict = {
i: val
for i, val in zip(
my_dict["index"], my_dict["values"]
)
}
self._tag_list[tag] = SparseList(
my_dict, length=len(self)
)
if "bonds" in hdf_atoms.list_nodes():
self.bonds = hdf_atoms["explicit_bonds"]
self._high_symmetry_points = None
if "high_symmetry_points" in hdf_atoms.list_nodes():
self._high_symmetry_points = hdf_atoms["high_symmetry_points"]
self._high_symmetry_path = None
if "high_symmetry_path" in hdf_atoms.list_nodes():
self._high_symmetry_path = hdf_atoms["high_symmetry_path"]
if "info" in hdf_atoms.list_nodes():
self.info = hdf_atoms["info"]
return self
else:
return self._from_hdf_old(hdf, group_name)
def _from_hdf_old(self, hdf, group_name="structure"):
"""
This function exits merely for the purpose of backward compatibility
"""
with hdf.open(group_name) as hdf_atoms:
self._pse = PeriodicTable()
if "species" in hdf_atoms.list_groups():
with hdf_atoms.open("species") as hdf_species:
self._pse.from_hdf(hdf_species)
chemical_symbols = np.array(hdf_atoms["elements"], dtype=str)
el_object_list = [
self.convert_element(el, self._pse) for el in chemical_symbols
]
self.set_species(list(set(el_object_list)))
self.indices = [self._species_to_index_dict[el] for el in el_object_list]
self._tag_list._length = len(self)
self.bonds = None
if "explicit_bonds" in hdf_atoms.list_nodes():
# print "bonds: "
self.bonds = hdf_atoms["explicit_bonds"]
if "tags" in hdf_atoms.list_groups():
with hdf_atoms.open("tags") as hdf_tags:
tags = hdf_tags.list_nodes()
for tag in tags:
# tr_dict = {'0': False, '1': True}
if isinstance(hdf_tags[tag], (list, np.ndarray)):
my_list = hdf_tags[tag]
self._tag_list[tag] = SparseList(my_list, length=len(self))
else:
my_dict = hdf_tags.get_pandas(tag).to_dict()
my_dict = {
i: val
for i, val in zip(my_dict["index"], my_dict["values"])
}
self._tag_list[tag] = SparseList(my_dict, length=len(self))
self.cell = None
if "cell" in hdf_atoms.list_groups():
with hdf_atoms.open("cell") as hdf_cell:
self.cell = hdf_cell["cell"]
self.pbc = hdf_cell["pbc"]
tr_dict = {1: True, 0: False}
self.dimension = hdf_atoms["dimension"]
if "is_absolute" in hdf_atoms and not tr_dict[hdf_atoms["is_absolute"]]:
self.positions = hdf_atoms["coordinates"]
else:
self.set_scaled_positions(hdf_atoms["coordinates"])
self.units = hdf_atoms["units"]
if "bonds" in hdf_atoms.list_nodes():
self.bonds = hdf_atoms["explicit_bonds"]
self._high_symmetry_points = None
if "high_symmetry_points" in hdf_atoms.list_nodes():
self._high_symmetry_points = hdf_atoms["high_symmetry_points"]
return self
def select_index(self, el):
"""
Returns the indices of a given element in the structure
Args:
el (str/atomistics.structures.periodic_table.ChemicalElement/list): Element for which the indices should
be returned
Returns:
numpy.ndarray: An array of indices of the atoms of the given element
"""
if isinstance(el, str):
return np.where(self.get_chemical_symbols() == el)[0]
elif isinstance(el, ChemicalElement):
return np.where([e == el for e in self.get_chemical_elements()])[0]
if isinstance(el, (list, np.ndarray)):
if isinstance(el[0], str):
return np.where(np.isin(self.get_chemical_symbols(), el))[0]
elif isinstance(el[0], ChemicalElement):
return np.where([e in el for e in self.get_chemical_elements()])[0]
def select_parent_index(self, el):
"""
Returns the indices of a given element in the structure ignoring user defined elements
Args:
el (str/atomistics.structures.periodic_table.ChemicalElement): Element for which the indices should
be returned
Returns:
numpy.ndarray: An array of indices of the atoms of the given element
"""
parent_basis = self.get_parent_basis()
return parent_basis.select_index(el)
def get_tags(self):
"""
Returns the keys of the stored tags of the structure
Returns:
dict_keys: Keys of the stored tags
"""
return self._tag_list.keys()
def convert_element(self, el, pse=None):
"""
Convert a string or an atom instance into a ChemicalElement instance
Args:
el (str/atomistics.structure.atom.Atom): String or atom instance from which the element should
be generated
pse (atomistics.structure.periodictable.PeriodicTable): PeriodicTable instance from which the element
is generated (optional)
Returns:
atomistics.structure.periodictable.ChemicalElement: The required chemical element
"""
if el in list(self._store_elements.keys()):
return self._store_elements[el]
if isinstance(el, string_types): # as symbol
element = Atom(el, pse=pse).element
elif isinstance(el, Atom):
element = el.element
el = el.element.Abbreviation
elif isinstance(el, ChemicalElement):
element = el
el = el.Abbreviation
else:
raise ValueError("Unknown static type to specify a element")
self._store_elements[el] = element
if hasattr(self, "species"):
if element not in self.species:
self._species.append(element)
self.set_species(self._species)
return element
def get_chemical_formula(self):
"""
Returns the chemical formula of structure
Returns:
str: The chemical formula as a string
"""
species = self.get_number_species_atoms()
formula = ""
for string_sym, num in species.items():
if num == 1:
formula += str(string_sym)
else:
formula += str(string_sym) + str(num)
return formula
def get_chemical_indices(self):
"""
Returns the list of chemical indices as ordered in self.species
Returns:
numpy.ndarray: A list of chemical indices
"""
return self.indices
def get_atomic_numbers(self):
"""
Returns the atomic numbers of all the atoms in the structure
Returns:
numpy.ndarray: A list of atomic numbers
"""
el_lst = [el.AtomicNumber for el in self.species]
return np.array([el_lst[el] for el in self.indices])
def get_chemical_symbols(self):
"""
Returns the chemical symbols for all the atoms in the structure
Returns:
numpy.ndarray: A list of chemical symbols
"""
el_lst = [el.Abbreviation for el in self.species]
return np.array([el_lst[el] for el in self.indices])
def get_parent_symbols(self):
"""
Returns the chemical symbols for all the atoms in the structure even for user defined elements
Returns:
numpy.ndarray: A list of chemical symbols
"""
sp_parent_list = list()
for sp in self.species:
if isinstance(sp.Parent, (float, np.float, type(None))):
sp_parent_list.append(sp.Abbreviation)
else:
sp_parent_list.append(sp.Parent)
return np.array([sp_parent_list[i] for i in self.indices])
def get_parent_basis(self):
"""
Returns the basis with all user defined/special elements as the it's parent
Returns:
pyiron.atomistics.structure.atoms.Atoms: Structure without any user defined elements
"""
parent_basis = copy(self)
new_species = np.array(parent_basis.species)
for i, sp in enumerate(new_species):
if not isinstance(sp.Parent, (float, np.float, type(None))):
pse = PeriodicTable()
new_species[i] = pse.element(sp.Parent)
sym_list = [el.Abbreviation for el in new_species]
if len(sym_list) != len(np.unique(sym_list)):
uni, ind, inv_ind = np.unique(
sym_list, return_index=True, return_inverse=True
)
new_species = new_species[ind].copy()
parent_basis.set_species(list(new_species))
indices_copy = parent_basis.indices.copy()
for i, ind_ind in enumerate(inv_ind):
indices_copy[parent_basis.indices == i] = ind_ind
parent_basis.indices = indices_copy
return parent_basis
parent_basis.set_species(list(new_species))
return parent_basis
def get_chemical_elements(self):
"""
Returns the list of chemical element instances
Returns:
numpy.ndarray: A list of chemical element instances
"""
return self.elements
def get_number_species_atoms(self):
"""
Returns a dictionary with the species in the structure and the corresponding count in the structure
Returns:
collections.OrderedDict: An ordered dictionary with the species and the corresponding count
"""
count = OrderedDict()
# print "sorted: ", sorted(set(self.elements))
for el in sorted(set(self.get_chemical_symbols())):
count[el] = 0
for el in self.get_chemical_symbols():
count[el] += 1
return count
def get_species_symbols(self):
"""
Returns the symbols of the present species
Returns:
numpy.ndarray: List of the symbols of the species
"""
return np.array(sorted([el.Abbreviation for el in self.species]))
def get_species_objects(self):
"""
Returns:
"""
el_set = self.species
el_sym_lst = {el.Abbreviation: i for i, el in enumerate(el_set)}
el_sorted = self.get_species_symbols()
return [el_set[el_sym_lst[el]] for el in el_sorted]
def get_number_of_species(self):
"""
Returns:
"""
return len(self.species)
def get_number_of_degrees_of_freedom(self):
"""
Returns:
"""
return len(self) * self.dimension
def get_center_of_mass(self):
"""
Returns:
com (float): center of mass in A
"""
masses = self.get_masses()
return np.einsum("i,ij->j", masses, self.positions) / np.sum(masses)
def get_masses(self):
"""
Gets the atomic masses of all atoms in the structure
Returns:
numpy.ndarray: Array of masses
"""
el_lst = [el.AtomicMass for el in self.species]
return np.array([el_lst[el] for el in self.indices])
def get_masses_dof(self):
"""
Returns:
"""
dim = self.dimension
return np.repeat(self.get_masses(), dim)
def get_volume(self, per_atom=False):
"""
Args:
per_atom (bool): True if volume per atom is to be returned
Returns:
volume (float): Volume in A**3
"""
if per_atom:
return np.abs(np.linalg.det(self.cell)) / len(self)
else:
return np.abs(np.linalg.det(self.cell))
def get_density(self):
"""
Returns the density in g/cm^3
Returns:
float: Density of the structure
"""
# conv_factor = Ang3_to_cm3/scipi.constants.Avogadro
# with Ang3_to_cm3 = 1e24
conv_factor = 1.660539040427164
return conv_factor * np.sum(self.get_masses()) / self.get_volume()
def get_number_of_atoms(self):
"""
Returns:
"""
# assert(len(self) == np.sum(self.get_number_species_atoms().values()))
return len(self)
def set_absolute(self):
warnings.warn("set_relative is deprecated as of 2020/02/26. It is not guaranteed from v. 0.3", DeprecationWarning)
if self._is_scaled:
self._is_scaled = False
def set_relative(self):
warnings.warn("set_relative is deprecated as of 2020/02/26. It is not guaranteed from v. 0.3", DeprecationWarning)
if not self._is_scaled:
self._is_scaled = True
def center_coordinates_in_unit_cell(self, origin=0, eps=1e-4):
"""
Wrap atomic coordinates within the supercell as given by a1, a2., a3
Args:
origin (float): 0 to confine between 0 and 1, -0.5 to confine between -0.5 and 0.5
eps (float): Tolerance to detect atoms at cell edges
Returns:
pyiron.atomistics.structure.atoms.Atoms: Wrapped structure
"""
if any(self.pbc):
self.set_scaled_positions(
np.mod(self.get_scaled_positions(wrap=False) + eps, 1) - eps + origin
)
return self
def create_line_mode_structure(self,
with_time_reversal=True,
recipe='hpkot',
threshold=1e-07,
symprec=1e-05,
angle_tolerance=-1.0,
):
"""
Uses 'seekpath' to create a new structure with high symmetry points and path for band structure calculations.
Args:
with_time_reversal (bool): if False, and the group has no inversion symmetry,
additional lines are returned as described in the HPKOT paper.
recipe (str): choose the reference publication that defines the special points and paths.
Currently, only 'hpkot' is implemented.
threshold (float): the threshold to use to verify if we are in and edge case
(e.g., a tetragonal cell, but a==c). For instance, in the tI lattice, if abs(a-c) < threshold,
a EdgeCaseWarning is issued. Note that depending on the bravais lattice,
the meaning of the threshold is different (angle, length, …)
symprec (float): the symmetry precision used internally by SPGLIB
angle_tolerance (float): the angle_tolerance used internally by SPGLIB
Returns:
pyiron.atomistics.structure.atoms.Atoms: new structure
"""
input_structure = (self.cell, self.get_scaled_positions(), self.indices)
sp_dict = seekpath.get_path(structure=input_structure,
with_time_reversal=with_time_reversal,
recipe=recipe,
threshold=threshold,
symprec=symprec,
angle_tolerance=angle_tolerance,
)
original_element_list = [el.Abbreviation for el in self.species]
element_list = [original_element_list[l] for l in sp_dict["primitive_types"]]
positions = sp_dict["primitive_positions"]
pbc = self.pbc
cell = sp_dict["primitive_lattice"]
struc_new = Atoms(elements=element_list, scaled_positions=positions, pbc=pbc, cell=cell)
struc_new._set_high_symmetry_points(sp_dict["point_coords"])
struc_new._set_high_symmetry_path({"full": sp_dict["path"]})
return struc_new
def repeat(self, rep):
"""Create new repeated atoms object.
The *rep* argument should be a sequence of three positive
integers like *(2,3,1)* or a single integer (*r*) equivalent
to *(r,r,r)*."""
atoms = self.copy()
atoms *= rep
return atoms
def set_repeat(self, vec):
self *= vec
def repeat_points(self, points, rep, centered=False):
"""
Return points with repetition given according to periodic boundary conditions
Args:
points (np.ndarray/list): xyz vector or list/array of xyz vectors
rep (int/list/np.ndarray): Repetition in each direction.
If int is given, the same value is used for
every direction
centered (bool): Whether the original points should be in the center of
repeated points.
Returns:
(np.ndarray) repeated points
"""
n = np.array([rep]).flatten()
if len(n)==1:
n = np.tile(n, 3)
if len(n)!=3:
raise ValueError('rep must be an integer or a list of 3 integers')
vector = np.array(points)
if vector.shape[-1]!=3:
raise ValueError('points must be an xyz vector or a list/array of xyz vectors')
if centered and np.mod(n, 2).sum()!=3:
warnings.warn('When centered, only odd number of repetition should be used')
v = vector.reshape(-1, 3)
n_lst = []
for nn in n:
if centered:
n_lst.append(np.arange(nn)-int(nn/2))
else:
n_lst.append(np.arange(nn))
meshgrid = np.meshgrid(n_lst[0], n_lst[1], n_lst[2])
v_repeated = np.einsum('ni,ij->nj', np.stack(meshgrid, axis=-1).reshape(-1, 3), self.cell)
v_repeated = v_repeated[:, np.newaxis, :]+v[np.newaxis, :, :]
return v_repeated.reshape((-1,)+vector.shape)
def reset_absolute(self, is_absolute):
raise NotImplementedError("This function was removed!")
def analyse_ovito_cna_adaptive(self, mode="total"):
"""
Use Ovito's common neighbor analysis binding.
Args:
mode ("total"/"numeric"/"str"): Controls the style and level of detail of the output. (Default is "total", only
return a summary of the values in the structure.)
Returns:
(depends on `mode`)
"""
from pyiron.atomistics.structure.ovito import analyse_ovito_cna_adaptive
return analyse_ovito_cna_adaptive(atoms=self, mode=mode)