-
Notifications
You must be signed in to change notification settings - Fork 184
/
structure.py
2425 lines (1929 loc) · 91 KB
/
structure.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
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida-core #
# For further information on the license, see the LICENSE.txt file #
# For further information please visit http://www.aiida.net #
###########################################################################
"""This module defines the classes for structures and all related
functions to operate on them.
"""
import copy
import functools
import itertools
import json
from aiida.common.constants import elements
from aiida.common.exceptions import UnsupportedSpeciesError
from .data import Data
__all__ = ('StructureData', 'Kind', 'Site')
# Threshold used to check if the mass of two different Site objects is the same.
_MASS_THRESHOLD = 1.0e-3
# Threshold to check if the sum is one or not
_SUM_THRESHOLD = 1.0e-6
# Default cell
_DEFAULT_CELL = ((0, 0, 0), (0, 0, 0), (0, 0, 0))
_valid_symbols = tuple(i['symbol'] for i in elements.values())
_atomic_masses = {el['symbol']: el['mass'] for el in elements.values()}
_atomic_numbers = {data['symbol']: num for num, data in elements.items()}
def _get_valid_cell(inputcell):
"""Return the cell in a valid format from a generic input.
:raise ValueError: whenever the format is not valid.
"""
try:
the_cell = list(list(float(c) for c in i) for i in inputcell)
if len(the_cell) != 3:
raise ValueError
if any(len(i) != 3 for i in the_cell):
raise ValueError
except (IndexError, ValueError, TypeError):
raise ValueError('Cell must be a list of three vectors, each defined as a list of three coordinates.')
return the_cell
def get_valid_pbc(inputpbc):
"""Return a list of three booleans for the periodic boundary conditions,
in a valid format from a generic input.
:raise ValueError: if the format is not valid.
"""
if isinstance(inputpbc, bool):
the_pbc = (inputpbc, inputpbc, inputpbc)
elif hasattr(inputpbc, '__iter__'):
# To manage numpy lists of bools, whose elements are of type numpy.bool_
# and for which isinstance(i,bool) return False...
if hasattr(inputpbc, 'tolist'):
the_value = inputpbc.tolist()
else:
the_value = inputpbc
if all(isinstance(i, bool) for i in the_value):
if len(the_value) == 3:
the_pbc = tuple(i for i in the_value)
elif len(the_value) == 1:
the_pbc = (the_value[0], the_value[0], the_value[0])
else:
raise ValueError('pbc length must be either one or three.')
else:
raise ValueError('pbc elements are not booleans.')
else:
raise ValueError('pbc must be a boolean or a list of three booleans.', inputpbc)
return the_pbc
def has_ase():
""":return: True if the ase module can be imported, False otherwise."""
try:
import ase # noqa: F401
except ImportError:
return False
return True
def has_pymatgen():
""":return: True if the pymatgen module can be imported, False otherwise."""
try:
import pymatgen # noqa: F401
except ImportError:
return False
return True
def get_pymatgen_version():
""":return: string with pymatgen version, None if can not import."""
if not has_pymatgen():
return None
try:
from pymatgen import __version__
except ImportError:
# this was changed in version 2022.0.3
from pymatgen.core import __version__
return __version__
def has_spglib():
""":return: True if the spglib module can be imported, False otherwise."""
try:
import spglib # noqa: F401
except ImportError:
return False
return True
def calc_cell_volume(cell):
"""Compute the three-dimensional cell volume in Angstrom^3.
:param cell: the cell vectors; the must be a 3x3 list of lists of floats
:returns: the cell volume.
"""
import numpy as np
return np.abs(np.dot(cell[0], np.cross(cell[1], cell[2])))
def _create_symbols_tuple(symbols):
"""Returns a tuple with the symbols provided. If a string is provided,
this is converted to a tuple with one single element.
"""
if isinstance(symbols, str):
symbols_list = (symbols,)
else:
symbols_list = tuple(symbols)
return symbols_list
def _create_weights_tuple(weights):
"""Returns a tuple with the weights provided. If a number is provided,
this is converted to a tuple with one single element.
If None is provided, this is converted to the tuple (1.,)
"""
import numbers
if weights is None:
weights_tuple = (1.0,)
elif isinstance(weights, numbers.Number):
weights_tuple = (weights,)
else:
weights_tuple = tuple(float(i) for i in weights)
return weights_tuple
def create_automatic_kind_name(symbols, weights):
"""Create a string obtained with the symbols appended one
after the other, without spaces, in alphabetical order;
if the site has a vacancy, a X is appended at the end too.
"""
sorted_symbol_list = list(set(symbols))
sorted_symbol_list.sort() # In-place sort
name_string = ''.join(sorted_symbol_list)
if has_vacancies(weights):
name_string += 'X'
return name_string
def validate_weights_tuple(weights_tuple, threshold):
"""Validates the weight of the atomic kinds.
:raise: ValueError if the weights_tuple is not valid.
:param weights_tuple: the tuple to validate. It must be a
a tuple of floats (as created by :func:_create_weights_tuple).
:param threshold: a float number used as a threshold to check that the sum
of the weights is <= 1.
If the sum is less than one, it means that there are vacancies.
Each element of the list must be >= 0, and the sum must be <= 1.
"""
w_sum = sum(weights_tuple)
if any(i < 0.0 for i in weights_tuple) or (w_sum - 1.0 > threshold):
raise ValueError('The weight list is not valid (each element must be positive, and the sum must be <= 1).')
def is_valid_symbol(symbol):
"""Validates the chemical symbol name.
:return: True if the symbol is a valid chemical symbol (with correct
capitalization), or the dummy X, False otherwise.
Recognized symbols are for elements from hydrogen (Z=1) to lawrencium
(Z=103). In addition, a dummy element unknown name (Z=0) is supported.
"""
return symbol in _valid_symbols
def validate_symbols_tuple(symbols_tuple):
"""Used to validate whether the chemical species are valid.
:param symbols_tuple: a tuple (or list) with the chemical symbols name.
:raises: UnsupportedSpeciesError if any symbol in the tuple is not a valid chemical
symbol (with correct capitalization).
Refer also to the documentation of :func:is_valid_symbol
"""
if len(symbols_tuple) == 0:
valid = False
else:
valid = all(is_valid_symbol(sym) for sym in symbols_tuple)
if not valid:
raise UnsupportedSpeciesError(
f'At least one element of the symbol list {symbols_tuple} has not been recognized.'
)
def is_ase_atoms(ase_atoms):
"""Check if the ase_atoms parameter is actually a ase.Atoms object.
:param ase_atoms: an object, expected to be an ase.Atoms.
:return: a boolean.
Requires the ability to import ase, by doing 'import ase'.
"""
import ase
return isinstance(ase_atoms, ase.Atoms)
def group_symbols(_list):
"""Group a list of symbols to a list containing the number of consecutive
identical symbols, and the symbol itself.
Examples
--------
* ``['Ba','Ti','O','O','O','Ba']`` will return
``[[1,'Ba'],[1,'Ti'],[3,'O'],[1,'Ba']]``
* ``[ [ [1,'Ba'],[1,'Ti'] ],[ [1,'Ba'],[1,'Ti'] ] ]`` will return
``[[2, [ [1, 'Ba'], [1, 'Ti'] ] ]]``
:param _list: a list of elements representing a chemical formula
:return: a list of length-2 lists of the form [ multiplicity , element ]
"""
the_list = copy.deepcopy(_list)
the_list.reverse()
grouped_list = [[1, the_list.pop()]]
while the_list:
elem = the_list.pop()
if elem == grouped_list[-1][1]:
# same symbol is repeated
grouped_list[-1][0] += 1
else:
grouped_list.append([1, elem])
return grouped_list
def get_formula_from_symbol_list(_list, separator=''):
"""Return a string with the formula obtained from the list of symbols.
Examples
--------
* ``[[1,'Ba'],[1,'Ti'],[3,'O']]`` will return ``'BaTiO3'``
* ``[[2, [ [1, 'Ba'], [1, 'Ti'] ] ]]`` will return ``'(BaTi)2'``
:param _list: a list of symbols and multiplicities as obtained from
the function group_symbols
:param separator: a string used to concatenate symbols. Default empty.
:return: a string
"""
list_str = []
for elem in _list:
if elem[0] == 1:
multiplicity_str = ''
else:
multiplicity_str = str(elem[0])
if isinstance(elem[1], str):
list_str.append(f'{elem[1]}{multiplicity_str}')
elif elem[0] > 1:
list_str.append(f'({get_formula_from_symbol_list(elem[1], separator=separator)}){multiplicity_str}')
else:
list_str.append(f'{get_formula_from_symbol_list(elem[1], separator=separator)}{multiplicity_str}')
return separator.join(list_str)
def get_formula_group(symbol_list, separator=''):
"""Return a string with the chemical formula from a list of chemical symbols.
The formula is written in a compact" way, i.e. trying to group as much as
possible parts of the formula.
.. note:: it works for instance very well if structure was obtained
from an ASE supercell.
Example of result:
``['Ba', 'Ti', 'O', 'O', 'O', 'Ba', 'Ti', 'O', 'O', 'O',
'Ba', 'Ti', 'Ti', 'O', 'O', 'O']`` will return ``'(BaTiO3)2BaTi2O3'``.
:param symbol_list: list of symbols
(e.g. ['Ba','Ti','O','O','O'])
:param separator: a string used to concatenate symbols. Default empty.
:returns: a string with the chemical formula for the given structure.
"""
def group_together(_list, group_size, offset):
""":param _list: a list
:param group_size: size of the groups
:param offset: beginning grouping after offset elements
:return : a list of lists made of groups of size group_size
obtained by grouping list elements together
The first elements (up to _list[offset-1]) are not grouped
example:
``group_together(['O','Ba','Ti','Ba','Ti'],2,1) =
['O',['Ba','Ti'],['Ba','Ti']]``
"""
the_list = copy.deepcopy(_list)
the_list.reverse()
grouped_list = []
for _ in range(offset):
grouped_list.append([the_list.pop()])
while the_list:
sub_list = []
for _ in range(group_size):
if the_list:
sub_list.append(the_list.pop())
grouped_list.append(sub_list)
return grouped_list
def cleanout_symbol_list(_list):
""":param _list: a list of groups of symbols and multiplicities
:return : a list where all groups with multiplicity 1 have
been reduced to minimum
example: ``[[1,[[1,'Ba']]]]`` will return ``[[1,'Ba']]``
"""
the_list = []
for elem in _list:
if elem[0] == 1 and isinstance(elem[1], list):
the_list.extend(elem[1])
else:
the_list.append(elem)
return the_list
def group_together_symbols(_list, group_size):
"""Successive application of group_together, group_symbols and
cleanout_symbol_list, in order to group a symbol list, scanning all
possible offsets, for a given group size
:param _list: the symbol list (see function group_symbols)
:param group_size: the size of the groups
:return the_symbol_list: the new grouped symbol list
:return has_grouped: True if we grouped something
"""
the_symbol_list = copy.deepcopy(_list)
has_grouped = False
offset = 0
while not has_grouped and offset < group_size:
grouped_list = group_together(the_symbol_list, group_size, offset)
new_symbol_list = group_symbols(grouped_list)
if len(new_symbol_list) < len(grouped_list):
the_symbol_list = copy.deepcopy(new_symbol_list)
the_symbol_list = cleanout_symbol_list(the_symbol_list)
has_grouped = True
# print get_formula_from_symbol_list(the_symbol_list)
offset += 1
return the_symbol_list, has_grouped
def group_all_together_symbols(_list):
"""Successive application of the function group_together_symbols, to group
a symbol list, scanning all possible offsets and group sizes
:param _list: the symbol list (see function group_symbols)
:return: the new grouped symbol list
"""
has_finished = False
group_size = 2
the_symbol_list = copy.deepcopy(_list)
while not has_finished and group_size <= len(_list) // 2:
# try to group as much as possible by groups of size group_size
the_symbol_list, has_grouped = group_together_symbols(the_symbol_list, group_size)
has_finished = has_grouped
group_size += 1
# stop as soon as we managed to group something
# or when the group_size is too big to get anything
return the_symbol_list
# initial grouping of the chemical symbols
old_symbol_list = [-1]
new_symbol_list = group_symbols(symbol_list)
# successively apply the grouping procedure until the symbol list does not
# change anymore
while new_symbol_list != old_symbol_list:
old_symbol_list = copy.deepcopy(new_symbol_list)
new_symbol_list = group_all_together_symbols(old_symbol_list)
return get_formula_from_symbol_list(new_symbol_list, separator=separator)
def get_formula(symbol_list, mode='hill', separator=''):
"""Return a string with the chemical formula.
:param symbol_list: a list of symbols, e.g. ``['H','H','O']``
:param mode: a string to specify how to generate the formula, can
assume one of the following values:
* 'hill' (default): count the number of atoms of each species,
then use Hill notation, i.e. alphabetical order with C and H
first if one or several C atom(s) is (are) present, e.g.
``['C','H','H','H','O','C','H','H','H']`` will return ``'C2H6O'``
``['S','O','O','H','O','H','O']`` will return ``'H2O4S'``
From E. A. Hill, J. Am. Chem. Soc., 22 (8), pp 478-494 (1900)
* 'hill_compact': same as hill but the number of atoms for each
species is divided by the greatest common divisor of all of them, e.g.
``['C','H','H','H','O','C','H','H','H','O','O','O']``
will return ``'CH3O2'``
* 'reduce': group repeated symbols e.g.
``['Ba', 'Ti', 'O', 'O', 'O', 'Ba', 'Ti', 'O', 'O', 'O',
'Ba', 'Ti', 'Ti', 'O', 'O', 'O']`` will return ``'BaTiO3BaTiO3BaTi2O3'``
* 'group': will try to group as much as possible parts of the formula
e.g.
``['Ba', 'Ti', 'O', 'O', 'O', 'Ba', 'Ti', 'O', 'O', 'O',
'Ba', 'Ti', 'Ti', 'O', 'O', 'O']`` will return ``'(BaTiO3)2BaTi2O3'``
* 'count': same as hill (i.e. one just counts the number
of atoms of each species) without the re-ordering (take the
order of the atomic sites), e.g.
``['Ba', 'Ti', 'O', 'O', 'O','Ba', 'Ti', 'O', 'O', 'O']``
will return ``'Ba2Ti2O6'``
* 'count_compact': same as count but the number of atoms
for each species is divided by the greatest common divisor of
all of them, e.g.
``['Ba', 'Ti', 'O', 'O', 'O','Ba', 'Ti', 'O', 'O', 'O']``
will return ``'BaTiO3'``
:param separator: a string used to concatenate symbols. Default empty.
:return: a string with the formula
.. note:: in modes reduce, group, count and count_compact, the
initial order in which the atoms were appended by the user is
used to group and/or order the symbols in the formula
"""
if mode == 'group':
return get_formula_group(symbol_list, separator=separator)
# for hill and count cases, simply count the occurences of each
# chemical symbol (with some re-ordering in hill)
if mode in ['hill', 'hill_compact']:
if 'C' in symbol_list:
ordered_symbol_set = sorted(set(symbol_list), key=lambda elem: {'C': '0', 'H': '1'}.get(elem, elem))
else:
ordered_symbol_set = sorted(set(symbol_list))
the_symbol_list = [[symbol_list.count(elem), elem] for elem in ordered_symbol_set]
elif mode in ['count', 'count_compact']:
ordered_symbol_indexes = sorted([symbol_list.index(elem) for elem in set(symbol_list)])
ordered_symbol_set = [symbol_list[i] for i in ordered_symbol_indexes]
the_symbol_list = [[symbol_list.count(elem), elem] for elem in ordered_symbol_set]
elif mode == 'reduce':
the_symbol_list = group_symbols(symbol_list)
else:
raise ValueError('Mode should be hill, hill_compact, group, reduce, count or count_compact')
if mode in ['hill_compact', 'count_compact']:
from math import gcd
the_gcd = functools.reduce(gcd, [e[0] for e in the_symbol_list])
the_symbol_list = [[e[0] // the_gcd, e[1]] for e in the_symbol_list]
return get_formula_from_symbol_list(the_symbol_list, separator=separator)
def get_symbols_string(symbols, weights):
"""Return a string that tries to match as good as possible the symbols
and weights. If there is only one symbol (no alloy) with 100%
occupancy, just returns the symbol name. Otherwise, groups the full
string in curly brackets, and try to write also the composition
(with 2 precision only).
If (sum of weights<1), we indicate it with the X symbol followed
by 1-sum(weights) (still with 2 digits precision, so it can be 0.00)
:param symbols: the symbols as obtained from <kind>._symbols
:param weights: the weights as obtained from <kind>._weights
.. note:: Note the difference with respect to the symbols and the
symbol properties!
"""
if len(symbols) == 1 and weights[0] == 1.0:
return symbols[0]
pieces = []
for symbol, weight in zip(symbols, weights):
pieces.append(f'{symbol}{weight:4.2f}')
if has_vacancies(weights):
pieces.append(f'X{1.0 - sum(weights):4.2f}')
return f"{{{''.join(sorted(pieces))}}}"
def has_vacancies(weights):
"""Returns True if the sum of the weights is less than one.
It uses the internal variable _SUM_THRESHOLD as a threshold.
:param weights: the weights
:return: a boolean
"""
w_sum = sum(weights)
return not 1.0 - w_sum < _SUM_THRESHOLD
def symop_ortho_from_fract(cell):
"""Creates a matrix for conversion from orthogonal to fractional
coordinates.
Taken from
svn://www.crystallography.net/cod-tools/trunk/lib/perl5/Fractional.pm,
revision 850.
:param cell: array of cell parameters (three lengths and three angles)
"""
import math
import numpy
a, b, c, alpha, beta, gamma = cell
alpha, beta, gamma = [math.pi * x / 180 for x in [alpha, beta, gamma]]
ca, cb, cg = [math.cos(x) for x in [alpha, beta, gamma]]
sg = math.sin(gamma)
return numpy.array(
[
[a, b * cg, c * cb],
[0, b * sg, c * (ca - cb * cg) / sg],
[0, 0, c * math.sqrt(sg * sg - ca * ca - cb * cb + 2 * ca * cb * cg) / sg],
]
)
def symop_fract_from_ortho(cell):
"""Creates a matrix for conversion from fractional to orthogonal
coordinates.
Taken from
svn://www.crystallography.net/cod-tools/trunk/lib/perl5/Fractional.pm,
revision 850.
:param cell: array of cell parameters (three lengths and three angles)
"""
import math
import numpy
a, b, c, alpha, beta, gamma = cell
alpha, beta, gamma = [math.pi * x / 180 for x in [alpha, beta, gamma]]
ca, cb, cg = [math.cos(x) for x in [alpha, beta, gamma]]
sg = math.sin(gamma)
ctg = cg / sg
D = math.sqrt(sg * sg - cb * cb - ca * ca + 2 * ca * cb * cg) # noqa: N806
return numpy.array(
[
[1.0 / a, -(1.0 / a) * ctg, (ca * cg - cb) / (a * D)],
[0, 1.0 / (b * sg), -(ca - cb * cg) / (b * D * sg)],
[0, 0, sg / (c * D)],
]
)
def ase_refine_cell(aseatoms, **kwargs):
"""Detect the symmetry of the structure, remove symmetric atoms and
refine unit cell.
:param aseatoms: an ase.atoms.Atoms instance
:param symprec: symmetry precision, used by spglib
:return newase: refined cell with reduced set of atoms
:return symmetry: a dictionary describing the symmetry space group
"""
from ase.atoms import Atoms
from spglib import get_symmetry_dataset, refine_cell
spglib_tuple = (
aseatoms.get_cell(),
aseatoms.get_scaled_positions(),
aseatoms.get_atomic_numbers(),
)
cell, positions, numbers = refine_cell(spglib_tuple, **kwargs)
refined_atoms = (
cell,
positions,
numbers,
)
sym_dataset = get_symmetry_dataset(refined_atoms, **kwargs)
unique_numbers = []
unique_positions = []
for i in set(sym_dataset['equivalent_atoms']):
unique_numbers.append(numbers[i])
unique_positions.append(positions[i])
unique_atoms = Atoms(unique_numbers, scaled_positions=unique_positions, cell=cell, pbc=True)
return unique_atoms, {
'hm': sym_dataset['international'],
'hall': sym_dataset['hall'],
'tables': sym_dataset['number'],
'rotations': sym_dataset['rotations'],
'translations': sym_dataset['translations'],
}
def atom_kinds_to_html(atom_kind):
"""Construct in html format
an alloy with 0.5 Ge, 0.4 Si and 0.1 vacancy is represented as
Ge<sub>0.5</sub> + Si<sub>0.4</sub> + vacancy<sub>0.1</sub>
Args:
-----
atom_kind: a string with the name of the atomic kind, as printed by
kind.get_symbols_string(), e.g. Ba0.80Ca0.10X0.10
Returns:
--------
html code for rendered formula
"""
# Parse the formula (TODO can be made more robust though never fails if
# it takes strings generated with kind.get_symbols_string())
import re
matched_elements = re.findall(r'([A-Z][a-z]*)([0-1][.[0-9]*]?)?', atom_kind)
# Compose the html string
html_formula_pieces = []
for element in matched_elements:
# replace element X by 'vacancy'
species = element[0] if element[0] != 'X' else 'vacancy'
weight = element[1] if element[1] != '' else None
if weight is not None:
html_formula_pieces.append(f'{species}<sub>{weight}</sub>')
else:
html_formula_pieces.append(species)
html_formula = ' + '.join(html_formula_pieces)
return html_formula
class StructureData(Data):
"""Data class that represents an atomic structure.
The data is organized as a collection of sites together with a cell, the boundary conditions (whether they are
periodic or not) and other related useful information.
"""
_set_incompatibilities = [
('ase', 'cell'),
('ase', 'pbc'),
('ase', 'pymatgen'),
('ase', 'pymatgen_molecule'),
('ase', 'pymatgen_structure'),
('cell', 'pymatgen'),
('cell', 'pymatgen_molecule'),
('cell', 'pymatgen_structure'),
('pbc', 'pymatgen'),
('pbc', 'pymatgen_molecule'),
('pbc', 'pymatgen_structure'),
('pymatgen', 'pymatgen_molecule'),
('pymatgen', 'pymatgen_structure'),
('pymatgen_molecule', 'pymatgen_structure'),
]
_dimensionality_label = {0: '', 1: 'length', 2: 'surface', 3: 'volume'}
_internal_kind_tags = None
def __init__(
self, cell=None, pbc=None, ase=None, pymatgen=None, pymatgen_structure=None, pymatgen_molecule=None, **kwargs
):
args = {
'cell': cell,
'pbc': pbc,
'ase': ase,
'pymatgen': pymatgen,
'pymatgen_structure': pymatgen_structure,
'pymatgen_molecule': pymatgen_molecule,
}
for left, right in self._set_incompatibilities:
if args[left] is not None and args[right] is not None:
raise ValueError(f'cannot pass {left} and {right} at the same time')
super().__init__(**kwargs)
if any(ext is not None for ext in [ase, pymatgen, pymatgen_structure, pymatgen_molecule]):
if ase is not None:
self.set_ase(ase)
if pymatgen is not None:
self.set_pymatgen(pymatgen)
if pymatgen_structure is not None:
self.set_pymatgen_structure(pymatgen_structure)
if pymatgen_molecule is not None:
self.set_pymatgen_molecule(pymatgen_molecule)
else:
if cell is None:
cell = _DEFAULT_CELL
self.set_cell(cell)
if pbc is None:
pbc = [True, True, True]
self.set_pbc(pbc)
def get_dimensionality(self):
"""Return the dimensionality of the structure and its length/surface/volume.
Zero-dimensional structures are assigned "volume" 0.
:return: returns a dictionary with keys "dim" (dimensionality integer), "label" (dimensionality label)
and "value" (numerical length/surface/volume).
"""
return _get_dimensionality(self.pbc, self.cell)
def set_ase(self, aseatoms):
"""Load the structure from a ASE object"""
if is_ase_atoms(aseatoms):
# Read the ase structure
self.cell = aseatoms.cell
self.pbc = aseatoms.pbc
self.clear_kinds() # This also calls clear_sites
for atom in aseatoms:
self.append_atom(ase=atom)
else:
raise TypeError('The value is not an ase.Atoms object')
def set_pymatgen(self, obj, **kwargs):
"""Load the structure from a pymatgen object.
.. note:: Requires the pymatgen module (version >= 3.0.13, usage
of earlier versions may cause errors).
"""
typestr = type(obj).__name__
try:
func = getattr(self, f'set_pymatgen_{typestr.lower()}')
except AttributeError:
raise AttributeError(f"Converter for '{typestr}' to AiiDA structure does not exist")
func(obj, **kwargs)
def set_pymatgen_molecule(self, mol, margin=5):
"""Load the structure from a pymatgen Molecule object.
:param margin: the margin to be added in all directions of the
bounding box of the molecule.
.. note:: Requires the pymatgen module (version >= 3.0.13, usage
of earlier versions may cause errors).
"""
box = [
max(x.coords.tolist()[0] for x in mol.sites) - min(x.coords.tolist()[0] for x in mol.sites) + 2 * margin,
max(x.coords.tolist()[1] for x in mol.sites) - min(x.coords.tolist()[1] for x in mol.sites) + 2 * margin,
max(x.coords.tolist()[2] for x in mol.sites) - min(x.coords.tolist()[2] for x in mol.sites) + 2 * margin,
]
self.set_pymatgen_structure(mol.get_boxed_structure(*box))
self.pbc = [False, False, False]
def set_pymatgen_structure(self, struct):
"""Load the structure from a pymatgen Structure object.
.. note:: periodic boundary conditions are set to True in all
three directions.
.. note:: Requires the pymatgen module (version >= 3.3.5, usage
of earlier versions may cause errors).
:raise ValueError: if there are partial occupancies together with spins.
"""
def build_kind_name(species_and_occu):
"""Build a kind name from a pymatgen Composition, including an additional ordinal if spin is included,
e.g. it returns '<specie>1' for an atom with spin < 0 and '<specie>2' for an atom with spin > 0,
otherwise (no spin) it returns None
:param species_and_occu: a pymatgen species and occupations dictionary
:return: a string representing the kind name or None
"""
species = list(species_and_occu.keys())
occupations = list(species_and_occu.values())
# As of v2023.9.2, the ``properties`` argument is removed and the ``spin`` argument should be used.
# See: https://github.com/materialsproject/pymatgen/commit/118c245d6082fe0b13e19d348fc1db9c0d512019
# The ``spin`` argument was introduced in v2023.6.28.
# See: https://github.com/materialsproject/pymatgen/commit/9f2b3939af45d5129e0778d371d814811924aeb6
has_spin_attribute = hasattr(species[0], '_spin')
if has_spin_attribute:
has_spin = any(specie.spin != 0 for specie in species)
else:
has_spin = any(specie.as_dict().get('properties', {}).get('spin', 0) != 0 for specie in species)
has_partial_occupancies = len(occupations) != 1 or occupations[0] != 1.0
if has_partial_occupancies and has_spin:
raise ValueError('Cannot set partial occupancies and spins at the same time')
if has_spin:
symbols = [specie.symbol for specie in species]
kind_name = create_automatic_kind_name(symbols, occupations)
# If there is spin, we can only have a single specie, otherwise we would have raised above
specie = species[0]
if has_spin_attribute:
spin = specie.spin
else:
spin = specie.as_dict().get('properties', {}).get('spin', 0)
if spin < 0:
kind_name += '1'
else:
kind_name += '2'
return kind_name
return None
self.cell = struct.lattice.matrix.tolist()
self.pbc = [True, True, True]
self.clear_kinds()
for site in struct.sites:
species_and_occu = site.species
if 'kind_name' in site.properties:
kind_name = site.properties['kind_name']
else:
kind_name = build_kind_name(species_and_occu)
inputs = {
'symbols': [x.symbol for x in species_and_occu.keys()],
'weights': list(species_and_occu.values()),
'position': site.coords.tolist(),
}
if kind_name is not None:
inputs['name'] = kind_name
self.append_atom(**inputs)
def _validate(self):
"""Performs some standard validation tests."""
from aiida.common.exceptions import ValidationError
super()._validate()
try:
_get_valid_cell(self.cell)
except ValueError as exc:
raise ValidationError(f'Invalid cell: {exc}')
try:
get_valid_pbc(self.pbc)
except ValueError as exc:
raise ValidationError(f'Invalid periodic boundary conditions: {exc}')
_validate_dimensionality(self.pbc, self.cell)
try:
# This will try to create the kinds objects
kinds = self.kinds
except ValueError as exc:
raise ValidationError(f'Unable to validate the kinds: {exc}')
from collections import Counter
counts = Counter([k.name for k in kinds])
for count in counts:
if counts[count] != 1:
raise ValidationError(f"Kind with name '{count}' appears {counts[count]} times instead of only one")
try:
# This will try to create the sites objects
sites = self.sites
except ValueError as exc:
raise ValidationError(f'Unable to validate the sites: {exc}')
for site in sites:
if site.kind_name not in [k.name for k in kinds]:
raise ValidationError(f'A site has kind {site.kind_name}, but no specie with that name exists')
kinds_without_sites = set(k.name for k in kinds) - set(s.kind_name for s in sites)
if kinds_without_sites:
raise ValidationError(
f'The following kinds are defined, but there are no sites with that kind: {list(kinds_without_sites)}'
)
def _prepare_xsf(self, main_file_name=''):
"""Write the given structure to a string of format XSF (for XCrySDen)."""
if self.is_alloy or self.has_vacancies:
raise NotImplementedError('XSF for alloys or systems with vacancies not implemented.')
sites = self.sites
return_string = 'CRYSTAL\nPRIMVEC 1\n'
for cell_vector in self.cell:
return_string += ' '.join([f'{i:18.10f}' for i in cell_vector])
return_string += '\n'
return_string += 'PRIMCOORD 1\n'
return_string += f'{int(len(sites))} 1\n'
for site in sites:
# I checked above that it is not an alloy, therefore I take the
# first symbol
return_string += f'{_atomic_numbers[self.get_kind(site.kind_name).symbols[0]]} '
return_string += '%18.10f %18.10f %18.10f\n' % tuple(site.position)
return return_string.encode('utf-8'), {}
def _prepare_cif(self, main_file_name=''):
"""Write the given structure to a string of format CIF."""
from aiida.orm import CifData
cif = CifData(ase=self.get_ase())
return cif._prepare_cif()
def _prepare_chemdoodle(self, main_file_name=''):
"""Write the given structure to a string of format required by ChemDoodle."""
from itertools import product
import numpy as np
supercell_factors = [1, 1, 1]
# Get cell vectors and atomic position
lattice_vectors = np.array(self.base.attributes.get('cell'))
base_sites = self.base.attributes.get('sites')
start1 = -int(supercell_factors[0] / 2)
start2 = -int(supercell_factors[1] / 2)
start3 = -int(supercell_factors[2] / 2)
stop1 = start1 + supercell_factors[0]
stop2 = start2 + supercell_factors[1]
stop3 = start3 + supercell_factors[2]
grid1 = range(start1, stop1)
grid2 = range(start2, stop2)
grid3 = range(start3, stop3)
atoms_json = []
# Manual recenter of the structure
center = (lattice_vectors[0] + lattice_vectors[1] + lattice_vectors[2]) / 2.0
for ix, iy, iz in product(grid1, grid2, grid3):
for base_site in base_sites:
shift = (ix * lattice_vectors[0] + iy * lattice_vectors[1] + iz * lattice_vectors[2] - center).tolist()
kind_name = base_site['kind_name']
kind_string = self.get_kind(kind_name).get_symbols_string()
atoms_json.append(
{
'l': kind_string,
'x': base_site['position'][0] + shift[0],
'y': base_site['position'][1] + shift[1],
'z': base_site['position'][2] + shift[2],
'atomic_elements_html': atom_kinds_to_html(kind_string),
}
)
cell_json = {
't': 'UnitCell',
'i': 's0',
'o': (-center).tolist(),
'x': (lattice_vectors[0] - center).tolist(),
'y': (lattice_vectors[1] - center).tolist(),
'z': (lattice_vectors[2] - center).tolist(),
'xy': (lattice_vectors[0] + lattice_vectors[1] - center).tolist(),
'xz': (lattice_vectors[0] + lattice_vectors[2] - center).tolist(),
'yz': (lattice_vectors[1] + lattice_vectors[2] - center).tolist(),
'xyz': (lattice_vectors[0] + lattice_vectors[1] + lattice_vectors[2] - center).tolist(),
}