forked from MaterSim/PyXtal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsymmetry.py
More file actions
5484 lines (4825 loc) · 201 KB
/
symmetry.py
File metadata and controls
5484 lines (4825 loc) · 201 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Module for storing & accessing symmetry group information, including
- Group class
- Wyckoff_Position class.
- Hall class
"""
from __future__ import annotations
import functools
import importlib.util
import itertools
import operator
import os
import re
from copy import deepcopy
from ast import literal_eval
import numpy as np
from monty.serialization import loadfn
from numpy.random import Generator
from pandas import read_csv
from pyxtal.constants import all_sym_directions, hex_cell, letters, ASU_bounds
from pyxtal.operations import (
OperationAnalyzer,
SymmOp,
apply_ops,
check_images,
create_matrix,
distance,
distance_matrix,
filtered_coords,
filtered_coords_euclidean,
)
from pyxtal.asu_constraints import ASU, ASUCondition, create_asu_for_space_group
def rf(package_name, resource_path):
package_path = importlib.util.find_spec(
package_name).submodule_search_locations[0]
return os.path.join(package_path, resource_path)
"""
Properties for Lazy Loading
"""
class SymmetryData:
_k_subgroup = None
_t_subgroup = None
def __init__(self):
self._wyckoff_sg = None
self._wyckoff_lg = None
self._wyckoff_rg = None
self._wyckoff_pg = None
self._symmetry_sg = None
self._symmetry_lg = None
self._symmetry_rg = None
self._symmetry_pg = None
self._generator_sg = None
self._generator_lg = None
self._generator_rg = None
self._generator_pg = None
self._t_subgroup = None
self._k_subgroup = None
self._hall_table = None
@classmethod
def get_t_subgroup(cls):
if cls._t_subgroup is None:
cls._t_subgroup = loadfn(rf("pyxtal", "database/t_subgroup.json"))
return cls._t_subgroup
@classmethod
def get_k_subgroup(cls):
if cls._k_subgroup is None:
cls._k_subgroup = loadfn(rf("pyxtal", "database/k_subgroup.json"))
return cls._k_subgroup
def get_wyckoff_sg(self):
if self._wyckoff_sg is None:
self._wyckoff_sg = read_csv(rf("pyxtal", "database/wyckoff_list.csv"))
return self._wyckoff_sg
def get_wyckoff_lg(self):
if self._wyckoff_lg is None:
self._wyckoff_lg = read_csv(rf("pyxtal", "database/layer.csv"))
return self._wyckoff_lg
def get_wyckoff_rg(self):
if self._wyckoff_rg is None:
self._wyckoff_rg = read_csv(rf("pyxtal", "database/rod.csv"))
return self._wyckoff_rg
def get_wyckoff_pg(self):
if self._wyckoff_pg is None:
self._wyckoff_pg = read_csv(rf("pyxtal", "database/point.csv"))
return self._wyckoff_pg
def get_symmetry_sg(self):
if self._symmetry_sg is None:
self._symmetry_sg = read_csv(rf("pyxtal", "database/wyckoff_symmetry.csv"))
return self._symmetry_sg
def get_symmetry_lg(self):
if self._symmetry_lg is None:
self._symmetry_lg = read_csv(rf("pyxtal", "database/layer_symmetry.csv"))
return self._symmetry_lg
def get_symmetry_rg(self):
if self._symmetry_rg is None:
self._symmetry_rg = read_csv(rf("pyxtal", "database/rod_symmetry.csv"))
return self._symmetry_rg
def get_symmetry_pg(self):
if self._symmetry_pg is None:
self._symmetry_pg = read_csv(rf("pyxtal", "database/point_symmetry.csv"))
return self._symmetry_pg
def get_generator_sg(self):
if self._generator_sg is None:
self._generator_sg = read_csv(rf("pyxtal", "database/wyckoff_generators.csv"))
return self._generator_sg
def get_generator_lg(self):
if self._generator_lg is None:
self._generator_lg = read_csv(rf("pyxtal", "database/layer_generators.csv"))
return self._generator_lg
def get_generator_rg(self):
if self._generator_rg is None:
self._generator_rg = read_csv(rf("pyxtal", "database/rod_generators.csv"))
return self._generator_rg
def get_generator_pg(self):
if self._generator_pg is None:
self._generator_pg = read_csv(rf("pyxtal", "database/point_generators.csv"))
return self._generator_pg
def get_hall_table(self):
if self._hall_table is None:
self._hall_table = read_csv(rf("pyxtal", "database/HM_Full.csv"), sep=",")
return self._hall_table
# ------------------------------ Constants ---------------------------------------
SYMDATA = SymmetryData()
HALL_TABLE = SYMDATA.get_hall_table()
face_centers = [22, 42, 43, 69, 70, 196, 202, 203, 209, 210,
216, 219, 225, 226, 227, 228]
body_centers = [23, 24, 44, 45, 46, 71, 72, 73, 74, 79,
80, 82, 87, 88, 97, 98, 107, 108, 109, 110,
119, 120, 121, 122, 139, 140, 141, 142, 197, 199,
204, 206, 211, 214, 217, 220, 229, 230]
a_centers = [38, 39, 40, 41]
c_centers = [5, 8, 9, 12, 15, 20, 21, 35, 36, 37, 63, 64, 65, 66, 67, 68]
r_centers = [146, 148, 155, 160, 161, 166, 167]
# screw axes
screw_21a = [18, 19, 24, 51, 54, 55, 56, 58, 59, 60, 61, 62, 68, 72, 73,
90, 92, 94, 96, 113, 114, 122, 127, 128, 129, 130, 135, 136,
137, 138, 198, 199, 205, 206, 210, 212, 213, 214, 227, 228, 230]
screw_41a = [210, 213, 214, 227, 228, 230]
screw_42a = [208, 223, 224, 226]
screw_43a = [212]
screw_21b = [4, 11, 14, 18, 19, 24, 52, 55, 56, 57, 58, 59, 61, 62, 64, 67,
72, 73, 74, 90, 92, 94, 96, 113, 114, 127, 128, 129, 130, 135,
136, 137, 138, 198, 199, 205, 206, 210, 212, 213, 214, 227, 228, 230]
screw_41b = [210, 213, 214, 227, 228, 230]
screw_42b = [208, 223, 224, 226]
screw_43b = [212]
screw_21c = [17, 19, 20, 24, 26, 29, 31, 33, 36, 53, 57, 60, 61, 62, 63, 64,
73, 76, 78, 80, 88, 91, 92, 95, 96, 98, 109, 110, 141, 142, 169,
170, 173, 176, 178, 179, 182, 185, 186, 193, 194, 198, 199, 205,
206, 210, 212, 213, 214, 227, 228, 230]
screw_41c = [76, 80, 88, 91, 92, 98, 109, 110, 141, 142, 210, 213, 214, 227, 228, 230]
screw_42c = [77, 84, 86, 93, 94, 101, 102, 105, 106, 131, 132, 133, 134, 135,
136, 137, 138, 208, 223, 224, 226]
screw_43c = [78, 95, 96, 212]
screw_31c = [144, 151, 152, 169, 172, 178, 181]
screw_32c = [145, 153, 154, 170, 171, 179, 180]
screw_61c = [169, 178]
screw_62c = [171, 180]
screw_63c = [173, 176, 182, 185, 186, 193, 194]
screw_64c = [172, 181]
screw_65c = [170, 179]
# glide planes
b_glide_a = [32, 39, 41, 45, 50, 55, 57, 60, 61, 72, 73, 100, 106,
110, 117, 125, 127, 133, 135, 205, 206, 230]
c_glide_a = [27, 29, 37, 49, 54, 56, 66, 68, 101, 103, 108, 116, 120,
124, 130, 132, 138, 140, 142, 158, 159, 161, 163, 165,
167, 184, 185, 186, 188, 190, 192, 193, 194]
n_glide_a = [30, 33, 34, 48, 52, 58, 62, 102, 104, 109, 118, 126,
128, 134, 136, 201, 222, 224]
d_glide_a = [43, 70, 203, 227, 228]
a_glide_b = [28, 29, 32, 33, 40, 41, 45, 46, 50, 55, 72, 100, 106, 117,
125, 127, 133, 135, 142]
c_glide_b = [7, 9, 13, 14, 15, 26, 27, 30, 36, 37, 49, 54, 56, 57, 60,
61, 63, 64, 66, 68, 73, 101, 103, 108, 110, 116, 120, 124,
130, 132, 138, 140, 159, 163, 184, 186, 190, 192, 194, 205, 206, 230]
n_glide_b = [31, 34, 48, 52, 53, 58, 102, 104, 118, 126, 128, 134, 136,
141, 201, 222, 224]
d_glide_b = [43, 70, 203, 227, 228]
a_glide_c = [51, 52, 53, 54, 61, 62, 68, 73, 88, 141, 142, 205, 206, 230]
b_glide_c = [64, 67, 74]
n_glide_c = [48, 50, 56, 59, 60, 85, 86, 125, 126, 129, 130, 133, 134,
137, 138, 201, 222, 224]
d_glide_c = [70, 203, 227, 228]
cn_glide_110 = [103, 104, 105, 106, 108, 112, 113, 114, 124, 126, 128,
130, 131, 133, 135, 137, 138, 140, 158, 161, 165, 167,
184, 185, 188, 192, 193, 218, 219, 222, 223, 224, 226,
228]
an_glide_011 = [222, 224]
bn_glide_101 = [222, 224]
d_glide_110 = [109, 110, 122, 141, 142, 220, 230]
d_glide_011 = [220, 230]
d_glide_101 = [220, 230]
spglib_hall_numbers = [
1, 2, 3, 6, 9, 18, 21, 30, 39, 57, 60, 63, 72, 81, 90, 108, 109, 112, 115, 116,
119, 122, 123, 124, 125, 128, 134, 137, 143, 149, 155, 161, 164, 170, 173, 176,
182, 185, 191, 197, 203, 209, 212, 215, 218, 221, 227, 228, 230, 233, 239, 245,
251, 257, 263, 266, 269, 275, 278, 284, 290, 292, 298, 304, 310, 313, 316, 322,
334, 335, 337, 338, 341, 343, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358,
359, 361, 363, 364, 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, 404, 406, 407, 408, 410, 412, 413,
414, 416, 418, 419, 420, 422, 424, 425, 426, 428, 430, 431, 432, 433, 435, 436,
438, 439, 440, 441, 442, 443, 444, 446, 447, 448, 449, 450, 452, 454, 455, 456,
457, 458, 460, 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, 497, 498, 500, 501, 502, 503, 504, 505, 506, 507, 508,
509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 520, 521, 523, 524, 525, 527,
529, 530,
]
# The map between standard space group and hall numbers
pyxtal_hall_numbers = [
1, 2, 3, 6, 9, 18, 21, 30, 39, 57, 60, 63, 72, 81, 90, 108, 109, 112, 115, 116,
119, 122, 123, 124, 125, 128, 134, 137, 143, 149, 155, 161, 164, 170, 173, 176,
182, 185, 191, 197, 203, 209, 212, 215, 218, 221, 227, 229, 230, 234, 239, 245,
251, 257, 263, 266, 269, 275, 279, 284, 290, 292, 298, 304, 310, 313, 316, 323,
334, 336, 337, 338, 341, 343, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358,
360, 362, 363, 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, 403, 405, 406, 407, 409, 411, 412, 413,
415, 417, 418, 419, 421, 423, 424, 425, 427, 429, 430, 431, 432, 433, 435, 436,
438, 439, 440, 441, 442, 443, 444, 446, 447, 448, 449, 450, 452, 454, 455, 456,
457, 458, 460, 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, 496, 497, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508,
509, 510, 511, 512, 513, 514, 515, 516, 517, 519, 520, 522, 523, 524, 526, 528,
529, 530,
]
# --------------------------- Hall class -----------------------------
class Hall:
"""
Class for conversion between Hall and standard spacegroups
http://cci.lbl.gov/sginfo/itvb_2001_table_a1427_hall_symbols.html
Args:
spg_num: interger number between 1 and 230
style: spglib or pyxtal
permutation: allow permutation or not
"""
def __init__(self, spgnum, style="pyxtal", permutation=False):
self.spg = spgnum
if style == "pyxtal":
self.hall_default = pyxtal_hall_numbers[spgnum - 1]
else:
self.hall_default = spglib_hall_numbers[spgnum - 1]
self.hall_numbers = []
self.hall_symbols = []
self.Ps = [] # convertion from standard
self.P1s = [] # inverse convertion to standard
for id in range(len(HALL_TABLE["Hall"])):
if HALL_TABLE["Spg_num"][id] == spgnum:
include = True if permutation else HALL_TABLE["Permutation"][id] == 0
if include:
self.hall_numbers.append(HALL_TABLE["Hall"][id])
self.hall_symbols.append(HALL_TABLE["Symbol"][id])
self.Ps.append(abc2matrix(HALL_TABLE["P"][id]))
self.P1s.append(abc2matrix(HALL_TABLE["P^-1"][id]))
elif HALL_TABLE["Spg_num"][id] > spgnum:
break
if len(self.hall_numbers) == 0:
msg = "hall numbers cannot be found, check input " + spgnum
raise RuntimeError(msg)
# --------------------------- Group class -----------------------------
class Group:
"""
Class for storing a set of Wyckoff positions for a symmetry group.
See the documentation for details about settings.
Examples
--------
>>> from pyxtal.symmetry import Group
>>> g = Group(64)
>>> g
-- Spacegroup --# 64 (Cmce)--
16g site symm: 1
8f site symm: m..
8e site symm: .2.
8d site symm: 2..
8c site symm: -1
4b site symm: 2/m..
4a site symm: 2/m..
One can access data such as `symbol`, `number` and `Wyckoff_positions`:
>>> g.symbol
'Cmce'
>>> g.number
64
>>> g.Wyckoff_positions[0]
Wyckoff position 16g in space group 64 with site symmetry 1
x, y, z
-x, -y+1/2, z+1/2
-x, y+1/2, -z+1/2
x, -y, -z
-x, -y, -z
x, y+1/2, -z+1/2
x, -y+1/2, z+1/2
-x, y, z
x+1/2, y+1/2, z
-x+1/2, -y+1, z+1/2
-x+1/2, y+1, -z+1/2
x+1/2, -y+1/2, -z
-x+1/2, -y+1/2, -z
x+1/2, y+1, -z+1/2
x+1/2, -y+1, z+1/2
-x+1/2, y+1/2, z
We also provide several utilities functions, e.g.,
one can search the possible wyckoff_combinations by a formula:
>>> g.list_wyckoff_combinations([4, 2])
([], [], [])
>>> g.list_wyckoff_combinations([4, 8])
([[['4a'], ['8c']],
[['4a'], ['8d']],
[['4a'], ['8e']],
[['4a'], ['8f']],
[['4b'], ['8c']],
[['4b'], ['8d']],
[['4b'], ['8e']],
[['4b'], ['8f']]],
[False, True, True, True, False, True, True, True],
[[[6], [4]], [[6], [3]], [[6], [2]], [[6], [1]],
[[5], [4]], [[5], [3]], [[5], [2]], [[5], [1]]]
)
Or search the subgroup information:
>>> g.get_max_t_subgroup()['subgroup']
[12, 14, 15, 20, 36, 39, 41]
Or check if a given composition is compatible with Wyckoff positions:
>>> g = Group(225)
>>> g.check_compatible([64, 28, 24])
(True, True)
Or check the possible transition paths to a given supergroup:
>>> g = Group(59)
>>> g.search_supergroup_paths(139, 2)
[[71, 139], [129, 139], [137, 139]]
Args:
group: The group symbol or international number
dim (int, default: 3): The periodic dimension of the group
use_hall (bool, default: False): Whether or not use the hall number
style (str, default: ``pyxtal``): The choice of hall number (``pyxtal``/``spglib``)
quick (bool, default: False): Whether or not ignore the wyckoff information
"""
def __init__(self, group, dim=3, use_hall=False, style="pyxtal", quick=False):
self.string = None
self.dim = dim
names = ["Point", "Rod", "Layer", "Space"]
self.header = "-- " + names[dim] + "group --"
# Retrieve symbol and number for the group (avoid redundancy)
if not use_hall:
self.symbol, self.number = get_symbol_and_number(group, dim)
else:
self.symbol = HALL_TABLE["Symbol"][group - 1]
self.number = HALL_TABLE["Spg_num"][group - 1]
self.PBC, self.lattice_type = get_pbc_and_lattice(self.number, dim)
if dim == 3:
self.lattice_id = self.get_lattice_id()
results = get_point_group(self.number)
self.point_group, self.pg_number, self.polar, self.inversion, self.chiral = results
# Lazy load Wyckoff positions and hall data unless quick=True
if not quick:
self._initialize_hall_data(group, use_hall, style, dim)
self._initialize_wyckoff_data(dim)
def _initialize_hall_data(self, group, use_hall, style, dim):
"""Initialize hall number and transformation matrices."""
if dim == 3:
if not use_hall:
if style == "pyxtal":
self.hall_number = pyxtal_hall_numbers[self.number - 1]
else:
self.hall_number = spglib_hall_numbers[self.number - 1]
else:
self.hall_number = group
self.P = abc2matrix(HALL_TABLE["P"][self.hall_number - 1])
self.P1 = abc2matrix(HALL_TABLE["P^-1"][self.hall_number - 1])
else:
self.hall_number, self.P, self.P1 = None, None, None
def _initialize_wyckoff_data(self, dim):
"""Initialize Wyckoff positions and organize them."""
# Wyckoff positions, site_symmetry, generator
self.wyckoffs = get_wyckoffs(self.number, dim=dim)
self.w_symm = get_wyckoff_symmetry(self.number, dim=dim)
# Create dicts with relevant Wyckoff position data lazily
wpdicts_gen = [
{
"index": i,
"letter": letter_from_index(i, self.wyckoffs, dim=self.dim),
"ops": self.wyckoffs[i],
"multiplicity": len(self.wyckoffs[i]),
"symmetry": self.w_symm[i],
"PBC": self.PBC,
"dim": self.dim,
"number": self.number,
"symbol": self.symbol,
"P": self.P,
"P1": self.P1,
"hall_number": self.hall_number,
"directions": self.get_symmetry_directions(),
"lattice_type": self.lattice_type,
}
for i in range(len(self.wyckoffs))
]
# A list of Wyckoff_positions sorted by descending multiplicity
#self.Wyckoff_positions = []
#for wpdict in wpdicts:
# wp = Wyckoff_position.from_dict(wpdict)
# self.Wyckoff_positions.append(wp)
# Use a generator to avoid keeping the full list of dicts in memory
self.Wyckoff_positions = [
Wyckoff_position.from_dict(wpdict) for wpdict in wpdicts_gen
]
# Organize wyckoffs by multiplicity
self.wyckoffs_organized = organized_wyckoffs(self)
def __str__(self):
if self.string is not None:
return self.string
else:
s = self.header
s += "# " + str(self.number) + " (" + self.symbol + ")--"
for wp in self.Wyckoff_positions:
s += "\n" + wp.get_label()
if not hasattr(wp, "site_symm"):
wp.get_site_symmetry()
s += "\tsite symm: " + wp.site_symm
self.string = s
return self.string
def __repr__(self):
return str(self)
def __iter__(self):
yield from self.Wyckoff_positions
def __getitem__(self, index):
return self.get_wyckoff_position(index)
def __len__(self):
return len(self.wyckoffs)
def get_ferroelectric_groups(self):
"""
Return the list of possible ferroelectric point groups
"""
return para2ferro(self.point_group)
def get_site_dof(self, sites):
"""
Compute the degree of freedom for each site.
Args:
sites (list): List of site labels, e.g. ['4a', '8b'] or ['a', 'b']
Returns:
numpy.ndarray: Array of degrees of freedom for each site
"""
def extract_dof(site):
site_letter = site[-1] if len(site) > 1 else site
id = len(self) - letters.index(site_letter) - 1
xyz_str = self[id].ops[0].as_xyz_str()
return len(set(re.sub(r"[^a-z]+", "", xyz_str)))
return np.array([extract_dof(site) for site in sites])
def get_orders(self):
"""
Get possible Wyckoff position orders based on the composition and Z range.
"""
orders = []
for map_str in self.get_alternatives()['Transformed WP']: #[1:]:
original_list = map_str.split()
sorted_reference = sorted(original_list)
order = [sorted_reference.index(char) for char in original_list]
orders.append(order)
orders = np.array(orders, dtype=int)
return orders
def get_spg_representation(self):
"""
Get the one-hot encoding of the space group.
(lattice_id, symmetry_matrix)
Returns:
id: an integer between 0 and 13
one_hot: a (15, 26) numpy (0, 1) array
"""
return self.lattice_id, self.get_spg_symmetry_object().to_one_hot()
def get_subgroup_composition(self, ids, g_types=['t', 'k'], max_atoms=100,
max_wps=20, verbose=False):
"""
Get the composition of the subgroup Wyckoff positions.
Args:
ids (list, optional): Nested list of Wyckoff position indices [[0]].
verbose (bool): Whether to print debug information.
g_types (list): List of subgroup types to consider ('t' for translationengleiche, 'k' for klassengleiche).
max_atoms (int): Maximum number of atoms to consider for subgroup search.
Returns:
list: List of multiplicities of the Wyckoff positions.
"""
if verbose:
strs = f"{self.number} ({self.symbol}): "
for i in ids:
for id in i:
wp = self[id]
strs += f"{wp.multiplicity}{wp.letter} "
print(strs)
sub_symmetries = []
N_atoms = sum([self[id].multiplicity for i in ids for id in i])
for g_type in g_types:
if g_type == 't':
sub = self.get_max_t_subgroup()
else:
sub = self.get_max_k_subgroup()
for i, sub_g in enumerate(sub['subgroup']):
if N_atoms * sub['index'][i] > max_atoms:
continue
sub_gg = Group(sub_g)
relation = sub['relations'][i]#; print(relation)
sub_ids = [[] for _ in range(len(ids))]
for j, _ids in enumerate(ids):
for id in _ids:
true_id = len(self)-id-1
relation[true_id].sort()
for r in relation[true_id]:
letter = r[-1]#; print("test letter:", relation[true_id])
sub_ids[j].append(len(sub_gg) - letters.index(letter) - 1)
if sum(len(sublist) for sublist in sub_ids) <= max_wps:
data = (sub_g, sub_ids, N_atoms * sub['index'][i])
if data not in sub_symmetries:
sub_symmetries.append(data)
if verbose:
strs = f"{sub_gg.number} ({sub_gg.symbol}): "
for i in sub_ids:
for id in i:
wp = sub_gg[id]
strs += f"{wp.multiplicity}{wp.letter} "
print(strs, data)
return sub_symmetries
def get_lattice_id(self):
"""
Compute the id for the lattice.
Returns:
id (int): Encoded lattice id
- 0: triclinic-P
- 1: monoclinic-P
- 2: monoclinic-C
- 3: orthorhombic-P
- 4: orthorhombic-A
- 5: orthorhombic-B
- 6: orthorhombic-C
- 7: orthorhombic-I
- 8: orthorhombic-F
- 9: tetragonal-P
- 10: tetragonal-I
- 11: hexagonal-P
- 12: hexagonal-R
- 13: cubic-P
- 14: cubic-I
- 15: cubic-F
"""
if self.lattice_type in ["triclinic"]:
id = 0
elif self.lattice_type in ["monoclinic"]:
if self.symbol[0] == "P":
id = 1
else:
id = 2
elif self.lattice_type in ["orthorhombic"]:
if self.symbol[0] == "P":
id = 3
elif self.symbol[0] == "A":
id = 4
elif self.symbol[0] == "B":
id = 5
elif self.symbol[0] == "C":
id = 6
elif self.symbol[0] == "I":
id = 7
elif self.symbol[0] == "F":
id = 8
elif self.lattice_type in ["tetragonal"]:
if self.symbol[0] == "P":
id = 9
elif self.symbol[0] == "I":
id = 10
elif self.lattice_type in ["hexagonal", "trigonal", "rhombohedral"]:
if self.symbol[0] == "P":
id = 11
elif self.symbol[0] == "R":
id = 12
else: # cubic
if self.symbol[0] == "P":
id = 13
elif self.symbol[0] == "I":
id = 14
elif self.symbol[0] == "F":
id = 15
return id
def get_ASU(self):
"""
Get the asymmetric unit for the space group.
Returns:
list: A list of inequalities defining the asymmetric unit.
"""
return ASU_bounds[self.number-1]
def get_ASU_instance(self):
"""
Get the asymmetric unit (ASU) for the space group.
Available methods for ASU construction include:
- project_to_asu(coord): Project a given coordinate to the ASU.
- is_valid(coord): Check if a given coordinate is within the ASU.
"""
return create_asu_for_space_group(self.number)
def get_lattice_dof(self):
"""
Compute the degree of freedom for the lattice
"""
if self.lattice_type in ["triclinic"]:
dof = 6
elif self.lattice_type in ["monoclinic"]:
dof = 4
elif self.lattice_type in ["orthorhombic"]:
dof = 3
elif self.lattice_type in ["tetragonal", "hexagonal", "trigonal"]:
dof = 2
else:
dof = 1
return dof
def is_valid_hkl(self, h, k, l):
"""
Check if the given (h, k, l) is allowed by the space group symmetry.
Args:
h (int): Miller index h
k (int): Miller index k
l (int): Miller index l
Returns:
bool: True if (h, k, l) is allowed, False otherwise
"""
# Check if the (h, k, l) is allowed by the space group symmetry
# This is a placeholder implementation and should be replaced with the actual symmetry check
return is_hkl_allowed(h, k, l, self.number)
def get_reflection_conditions(self):
"""
Get the reflection conditions for the space group.
Returns:
dict: A dictionary with keys as (h, k, l) tuples and values as booleans indicating if the reflection is allowed.
"""
dicts = {"fcs (all odd/even)": face_centers,
"bcs (h+k+l=2n)": body_centers,
"acs (k+l=2n)": a_centers,
"ccs (h+k=2n)": c_centers,
"rcs (h-k-l=3n)": r_centers,
"screw_21a (h00), h=2n": screw_21a,
"screw_41a (h00), h=4n": screw_41a,
"screw_42a (h00), h=2n": screw_42a,
"screw_43a (h00), h=4n": screw_43a,
"screw_21b (0k0), k=2n": screw_21b,
"screw_41b (0k0), k=4n": screw_41b,
"screw_42b (0k0), k=2n": screw_42b,
"screw_43b (0k0), k=4n": screw_43b,
"screw_21c (00l), l=2n": screw_21c,
"screw_41c (00l), l=4n": screw_41c,
"screw_42c (00l), l=2n": screw_42c,
"screw_43c (00l), l=4n": screw_43c,
"screw_31c (00l), l=3n": screw_31c,
"screw_32c (00l), l=3n": screw_32c,
"screw_61c (00l), l=6n": screw_61c,
"screw_62c (00l), l=3n": screw_62c,
"screw_63c (00l), l=2n": screw_63c,
"screw_64c (00l), l=3n": screw_64c,
"screw_65c (00l), l=6n": screw_65c,
"b_glide_a (0kl), k=2n": b_glide_a,
"c_glide_a (0kl), l=2n": c_glide_a,
"n_glide_a (0kl), k+l=2n": n_glide_a,
"d_glide_a (0kl), k+l=4n": d_glide_a,
"a_glide_b (h0l), h=2n": a_glide_b,
"c_glide_b (h0l), l=2n": c_glide_b,
"n_glide_b (h0l), h+l=2n": n_glide_b,
"d_glide_b (h0l), h+l=4n": d_glide_b,
"a_glide_c (0kl), h=2n": a_glide_c,
"b_glide_c (0kl), l=2n": b_glide_c,
"n_glide_c (0kl), h+l=2n": n_glide_c,
"d_glide_c (0kl), l=2n": d_glide_c,
"cn_glide_110 (hhl), l=2n": cn_glide_110,
"an_glide_011 (hkk), h=2n": an_glide_011,
"bn_glide_101 (hkh), k=2n": bn_glide_101,
"glide_110 (hhl), l=2n 2h+l=4n": d_glide_110,
"glide_011 (hkk), h=2n 2k+h=4n": d_glide_011,
"glide_101 (hkh), k=2n 2h+k=4n": d_glide_101,
}
print(f"Reflection condition applied")
for key in dicts:
if self.number in dicts[key]:
print(key)
def generate_possible_hkls(self, h_max, k_max=None, l_max=None, max_square=12):
"""
Generate reasonable hkl indices within a cutoff for different crystal systems.
This function considers the extinction conditions to limit the hkls.
Args:
max_h: maximum absolute value for h, k, l
"""
if k_max is None: k_max = h_max
if l_max is None: l_max = h_max
if self.number > 194: # cubic
base_signs = [(1, 1, 1)]
elif self.number >= 143: # hexagonal/trigonal
base_signs = [(1, 1, 1), (1, -1, 1)]
elif self.number >= 16: # orthorhombic
base_signs = [(1, 1, 1)]
elif self.number >= 3: # 2/m
base_signs = [(1, 1, 1), (1, 1, -1)]
#elif self.number >= 6: # m
# base_signs = [(1, 1, 1), (1, 1, -1), (-1, 1, 1), (-1, 1, -1)]
#elif self.number >= 3: # 2
# base_signs = [(1, 1, 1), (1, -1, 1), (-1, 1, 1), (1, -1, -1)]
#elif self.number >= 2: # -1
# base_signs = [(1, 1, 1), (1, 1, -1), (1, -1, 1), (-1, 1, 1)]
else: # 1
base_signs = [(1, 1, 1), (1, 1, -1), (1, -1, 1), (-1, 1, 1),
(1, -1, -1), (-1, 1, -1), (-1, -1, 1), (-1, -1, -1)]
# Generate all possible hkls and filter by extinction rules
possible_hkls = []
canonical_seen = set() # Track canonical forms to avoid duplicates
symmetry_seen = set() # Track symmetry-equivalent hkls
# Build reciprocal-space rotation operators from the general Wyckoff position
reciprocal_ops = []
op_seen = set()
if len(self.wyckoffs) > 0 and len(self.wyckoffs[0]) > 0:
for op in self.wyckoffs[0]:
try:
matrix = np.rint(np.linalg.inv(op.rotation_matrix).T).astype(int)
except np.linalg.LinAlgError:
continue
key = tuple(matrix.flatten().tolist())
if key not in op_seen:
op_seen.add(key)
reciprocal_ops.append(matrix)
if len(reciprocal_ops) == 0:
reciprocal_ops = [np.eye(3, dtype=int)]
def get_symmetry_key(hkl):
vec = np.array(hkl, dtype=int)
orbit = [tuple((matrix @ vec).tolist()) for matrix in reciprocal_ops]
return max(orbit)
for h in range(0, h_max + 1):
# add permutation
k_min = 0 #if self.number > 3 else h
for k in range(k_min, k_max + 1):
# add additional
l_min = 0 #if self.number > 15 else h
for l in range(l_min, l_max + 1):
if h == 0 and k == 0 and l == 0: # Exclude (0,0,0)
continue
if h*h + k*k + l*l > max_square:
continue
canonical = get_canonical_hkl(h, k, l, self.number)
if canonical in canonical_seen: continue
if h*h + k*k + l*l > 0: # exclude (0,0,0)
# Add all permutations and sign variations
valid_hkls = []
for signs in base_signs:
if 2 < self.number < 16 and h == 0 and signs[2]==-1: continue
sh, sk, sl = signs[0]*h, signs[1]*k, signs[2]*l
if is_hkl_allowed(sh, sk, sl, self.number):
if (sh, sk, sl) not in valid_hkls:
valid_hkls.append((sh, sk, sl))
#print('AAAAAAAAAAAAAAAAAAA', h, k, l, sh, sk, sl)
if valid_hkls:
canonical_seen.add(canonical)
for hkl in valid_hkls:
symmetry_key = get_symmetry_key(hkl)
if symmetry_key not in symmetry_seen:
symmetry_seen.add(symmetry_key)
possible_hkls.append(hkl)
# Sort by h²+k²+l² in ascending order
possible_hkls.sort(key=lambda hkl: hkl[0]**2 + hkl[1]**2 + hkl[2]**2)
return possible_hkls # remove duplicates
def generate_hkl_guesses(self, h_max=2, k_max=None, l_max=None, max_square=12,
total_square=100, max_size=2000000, reduce=True,
verbose=False):
"""
Generate reasonable hkl indices within a cutoff for different crystal systems.
This function considers the extinction conditions to limit the hkls.
Args:
h_max: maximum absolute value for h
l_max: maximum absolute value for k
k_max: maximum absolute value for l
max_square: maximum h^2 + k^2 + l^2
max_size: maximum number of guesses to return
reduce: whether or not reduce the number of guesses
verbose: whether or not print the possible hkls
"""
if k_max is None: k_max = h_max
if l_max is None: l_max = h_max
possible_hkls = self.generate_possible_hkls(h_max, k_max, l_max,
max_square=max_square)
possible_hkls = np.array(possible_hkls)
n_hkls = len(possible_hkls)
if verbose: print([tuple(hkl) for hkl in possible_hkls])
if self.number >= 195:
guesses = np.reshape(possible_hkls, (len(possible_hkls), 1, 3))
elif self.number >= 143:
double_indices = np.array(list(itertools.combinations(range(n_hkls), 2)))
doubles = possible_hkls[double_indices] # Shape: (n_doubles, 2, 3)
base_signs = np.array([(1, 1, 1), (1, -1, 1)])
all_guesses = []
for double in doubles:
for signs in base_signs:
signed_double = double * signs[np.newaxis, :]
all_guesses.extend(list(itertools.permutations(signed_double)))
guesses = np.array(all_guesses)
elif self.number >= 75:
# Generate all double combinations
double_indices = np.array(list(itertools.combinations(range(n_hkls), 2)))
doubles = possible_hkls[double_indices] # Shape: (n_doubles, 2, 3)
all_guesses = []
for double in doubles:
all_guesses.extend(list(itertools.permutations(double)))
guesses = np.array(all_guesses)
elif self.number >= 16:
triple_indices = np.array(list(itertools.combinations(range(n_hkls), 3)))
triples = possible_hkls[triple_indices] # Shape: (n_triples, 3, 3)
all_guesses = []
for triple in triples:
all_guesses.extend(list(itertools.permutations(triple)))
guesses = np.array(all_guesses)
elif self.number >= 3:
# Generate all quadruple combinations
quadruple_indices = np.array(list(itertools.combinations(range(n_hkls), 4)))
quadruples = possible_hkls[quadruple_indices] # Shape: (n_quadruples, 4, 3)
base_signs = np.array([(1, 1, 1), (1, 1, -1)])
#from time import time
#t0 = time()
n_quads = len(quadruples)
n_signs = len(base_signs)
n_perms = 24 # 4! permutations
quads_expanded = np.tile(quadruples[:, np.newaxis, :, :], (1, n_signs, 1, 1))
signs_expanded = np.tile(base_signs[np.newaxis, :, np.newaxis, :], (n_quads, 1, 4, 1))
signed_quads = quads_expanded * signs_expanded
signed_quads = signed_quads.reshape(-1, 4, 3)
perms = np.array(list(itertools.permutations(range(4))))
guesses = np.empty((n_signs * n_quads * n_perms, 4, 3), dtype=int)
for i, perm in enumerate(perms):
start_idx = i * n_signs * n_quads
end_idx = (i + 1) * n_signs * n_quads
guesses[start_idx:end_idx] = signed_quads[:, perm, :]
#t1 = time()
#if verbose: print("Time for generating quadruple hkl guesses:", t1 - t0, len(quadruples), len(guesses))
sums = np.sum(guesses**2, axis=(1, 2))#; print(len(sums))
ids = np.argsort(sums)
sums = sums[sums <= total_square]
ids = ids[:len(sums)]
guesses = guesses[ids]
#print("Debug", guesses[-1], total_square, max_square); import sys; sys.exit()
if max_size is not None:
if len(ids) > max_size:
guesses = guesses[:max_size]
if reduce:
if verbose: print("Reducing hkl guesses...", len(guesses))
guesses = self.reduce_hkl_guesses(guesses)
return guesses
def reduce_hkl_guesses(self, hkls):
"""
Reduce the hkl guesses by removing duplicates based on canonical forms.
Args:
hkls (list): np.ndarray of hkl guesses tuples
Returns:
list: Reduced hkls
"""
#print("Raw", len(hkls), "hkl guesses for space group", self.number)
if 143 <= self.number <= 194:
# must follow the ordering constraints if two hkls have the same signs
# (h1, k1) >= (h2, k2) >= 0
condition1 = hkls[:, 0, :2] >= hkls[:, 1, :2] # (h1, k1) >= (h2, k2)
condition2 = hkls[:, 1, :2] >= 0 # (h2, k2) >= 0
mask1 = np.all(condition1 & condition2, axis=1)
condition3 = hkls[:, 0, :2] <= hkls[:, 1, :2] # (h1, k1) <= (h2, k2)
condition4 = hkls[:, 1, :2] <= 0 # (h2, k2) <= 0
mask2 = np.all(condition3 & condition4, axis=1)
mask3 = hkls[:, 0, 2] >= hkls[:, 1, 2] # l1 >= l2
mask = (mask1 | mask2) & mask3#; print(mask.sum(), mask1.sum(), mask2.sum(), mask3.sum())
hkls = hkls[~mask]
#print("Reducing order", len(hkls), "hkl guesses for space group", self.number)
B = np.zeros([len(hkls), 2, 2])
B[:,:,0] = 4/3 * (hkls[:,:,0] ** 2 + hkls[:,:,0] * hkls[:,:,1] + hkls[:,:,1] ** 2)
B[:,:,1] = hkls[:,:,2] ** 2
hkls = hkls[np.linalg.det(B) != 0]
#print("Reducing colinear", len(hkls), "hkl guesses for space group", self.number)
elif 74 < self.number < 143:
# must follow the ordering constraints
mask1 = np.all(hkls[:,0,:] >= hkls[:,1,:], axis=1) # (h1, k1, l1) >= (h2, k2, l2)
hkls = hkls[~mask1]
#print("Reducing order", len(hkls), "hkl guesses for space group", self.number)
# must be non-coplanar
B = np.zeros([len(hkls), 2, 2])
B[:,:,0] = hkls[:,:,0] ** 2 + hkls[:,:,1] ** 2
B[:,:,1] = hkls[:,:,2] ** 2
hkls = hkls[np.linalg.det(B) != 0]
# print("Reducing colinear", len(hkls), "hkl guesses for space group", self.number)
elif 15 < self.number < 75:
# must follow the ordering constraints