-
Notifications
You must be signed in to change notification settings - Fork 8
/
symmetry.py
1482 lines (1281 loc) · 55.4 KB
/
symmetry.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
"""detecting and forcing symmetry"""
import numpy as np
from scipy.spatial import distance_matrix
from AaronTools import addlogger
from AaronTools.utils.prime_numbers import Primes
from AaronTools.utils.utils import (
rotation_matrix, mirror_matrix, proj, angle_between_vectors, perp_vector
)
class SymmetryElement:
def __init__(self, order, center):
self.order = order
self.operation = np.identity(3)
self.translation = center
def perp_dist(self, coords):
"""distance from each coordinate perpendicular to this symmetry element"""
return np.zeros(len(coords))
def apply_operation(self, coords):
"""returns coords with the symmetry operation applied"""
coords = coords - self.translation
coords = np.matmul(coords, self.operation)
coords += self.translation
return coords
def apply_operation_without_translation(self, coords):
"""
returns coords with the symmetry operation applied but without
translating the coordinates to or from self's center
"""
coords = np.matmul(coords, self.operation)
return coords
def error(self, geom=None, tolerance=None, groups=None, coords=None):
"""
error in this symmetry element for the given geometry
either geom or coords and groups must be given
if groups is not given and geom is, atoms will be grouped by element
"""
if coords is None:
coords = geom.coords
full_coords2 = self.apply_operation(coords)
error = 0
# compute distances between the initial coords and
# the coords after applying the symmetry operation
# but only calculate distances for atoms that might
# be symmetry-equivalent (i.e. in the same inital
# group, which typically is based on what the atom's
# neighbors are)
if groups is not None:
group_names = groups
else:
group_names = geom.elements
for group in set(group_names):
ndx = (group_names == group).nonzero()[0]
coords1 = np.take(coords, ndx, axis=0)
coords2 = np.take(full_coords2, ndx, axis=0)
dist_mat = distance_matrix(coords1, coords2)
perp_dist = self.perp_dist(coords1)
# treat values less than 1 as 1 to avoid numerical nonsense
perp_dist = np.maximum(perp_dist, np.ones(len(ndx)))
error_mat = dist_mat / perp_dist
min_d = max(np.min(error_mat, axis=1))
if min_d > error:
error = min_d
return error
def equivalent_positions(self, coords, groups):
"""
return an array with the indices that are equivalent after
applying this operation
for example:
ndx = element.equivalent_positions(geom.coords, groups)
coords[ndx] should be equal to element.apply_operation(geom.coords)
"""
eq_ndx = np.zeros(len(coords), dtype=int)
init_partitions = dict()
init_ndx = dict()
for i, (coord, group) in enumerate(zip(coords, groups)):
init_partitions.setdefault(group, [])
init_partitions[group].append(coord)
init_ndx.setdefault(group, [])
init_ndx[group].append(i)
for group in init_partitions:
coords = init_partitions[group]
new_coords = self.apply_operation(coords)
dist = distance_matrix(coords, new_coords)
closest_ndx = np.argmin(dist, axis=1)
for i, (atom, ndx) in enumerate(zip(init_partitions[group], closest_ndx)):
j = init_ndx[group][i]
k = init_ndx[group][ndx]
eq_ndx[j] = k
return eq_ndx
@property
def trace(self):
"""trace of this symmetry element's matrix"""
return np.trace(self.operation)
class Identity(SymmetryElement):
def __init__(self):
self.translation = np.zeros(3)
self.operation = np.eye(3)
def __repr__(self):
return "E"
def __lt__(self, other):
return False
class ProperRotation(SymmetryElement):
"""proper rotation"""
def __init__(self, center, axis, n, exp=1):
self.order = n
self.operation = rotation_matrix(
2 * np.pi * exp / n,
axis,
renormalize=False,
)
self.translation = center
self.axis = axis
self.n = n
self.exp = exp
def __repr__(self):
if self.exp > 1:
return "C%i^%i (%5.2f %5.2f %5.2f)" % (
self.n,
self.exp,
*self.axis,
)
return "C%i (%5.2f %5.2f %5.2f)" % (
self.n,
*self.axis,
)
def __lt__(self, other):
if isinstance(other, Identity) or isinstance(other, InversionCenter):
return False
if isinstance(other, ProperRotation):
if self.n == other.n:
return self.exp > other.exp
return self.n < other.n
return False
def perp_dist(self, coords):
v = coords - self.translation
n = np.dot(v, self.axis)
p = np.outer(n, self.axis)
return np.linalg.norm(v - p, axis=1)
class MirrorPlane(SymmetryElement):
"""mirror plane"""
def __init__(self, center, axis, label=None):
self.order = 2
self.translation = center
self.axis = axis
self.operation = mirror_matrix(axis)
self.label = label
def __repr__(self):
if self.label:
return "sigma_%s (%5.2f %5.2f %5.2f)" % (self.label, *self.axis)
return "sigma (%5.2f %5.2f %5.2f)" % tuple(self.axis)
def __lt__(self, other):
if not isinstance(other, MirrorPlane):
return True
if self.label and other.label:
return self.label < other.label
return True
def perp_dist(self, coords):
v = coords - self.translation
return np.dot(v, self.axis[:, None]).flatten()
class InversionCenter(SymmetryElement):
"""inversion center"""
def __init__(self, center):
self.order = 2
self.operation = -np.identity(3)
self.translation = center
def __lt__(self, other):
if isinstance(other, Identity):
return True
return False
def __repr__(self):
return "i (%.2f %.2f %.2f)" % (
*self.translation,
)
def perp_dist(self, coords):
v = coords - self.translation
return np.linalg.norm(v, axis=1)
class ImproperRotation(SymmetryElement):
"""improper rotation"""
def __init__(self, center, axis, n, exp=1):
self.order = n
self.operation = np.matmul(
rotation_matrix(
2 * np.pi * exp / n,
axis,
renormalize=False,
),
mirror_matrix(axis)
)
self.axis = axis
self.translation = center
self.n = n
self.exp = exp
def __repr__(self):
if self.exp > 1:
return "S%i^%i (%5.2f %5.2f %5.2f)" % (
self.n,
self.exp,
*self.axis,
)
return "S%i (%5.2f %5.2f %5.2f)" % (
self.n,
*self.axis,
)
def __lt__(self, other):
if (
isinstance(other, Identity) or
isinstance(other, ProperRotation) or
isinstance(other, InversionCenter)
):
return True
if isinstance(other, ImproperRotation):
if self.n == other.n:
return self.exp > other.exp
return self.n < other.n
return False
def perp_dist(self, coords):
v = coords - self.translation
n = np.dot(v, self.axis)
p = np.outer(n, self.axis)
ax_dist = np.linalg.norm(v - p, axis=1)
sig_dist = np.dot(v, self.axis[:, None]).flatten()
return np.minimum(ax_dist, sig_dist)
@addlogger
class PointGroup:
"""determines point group and valid symmetry operations for a structure"""
LOG = None
def __init__(
self,
geom,
tolerance=0.1,
max_rotation=6,
rotation_tolerance=0.01,
groups=None,
center=None
):
self.geom = geom
self.center = center
if self.center is None:
self.center = geom.COM()
self.elements = self.get_symmetry_elements(
geom,
tolerance=tolerance,
max_rotation=max_rotation,
groups=groups,
rotation_tolerance=rotation_tolerance,
)
self.name = self.determine_point_group(
rotation_tolerance=rotation_tolerance
)
def get_symmetry_elements(
self,
geom,
tolerance=0.1,
max_rotation=6,
rotation_tolerance=0.01,
groups=None,
):
"""
determine what symmetry elements are valid for geom
:param Geometry geom: structre
:param float tolerance: maximum error for an element to be valid
:param int max_rotation: maximum n for Cn (Sn can be 2x this)
:param float rotation_tolerance: tolerance in radians for angle between
axes to be for them to be considered parallel/antiparallel/orthogonal
:rtype: list(SymmetryElement)
"""
CITATION = "doi:10.1002/jcc.22995"
self.LOG.citation(CITATION)
# atoms are grouped based on what they are bonded to
# if there's not many atoms, don't bother splitting them up
# based on ranks
if groups is not None:
atom_ids = np.array(groups)
self.initial_groups = atom_ids
else:
atom_ids = np.array(
geom.canonical_rank(
update=False,
break_ties=False,
invariant=False,
)
)
self.initial_groups = atom_ids
coords = geom.coords
moments, axes = geom.get_principle_axes()
axes = axes.T
valid = [Identity()]
degeneracy = np.ones(3, dtype=int)
for i, m1 in enumerate(moments):
for j, m2 in enumerate(moments):
if i == j:
continue
if np.isclose(m1, m2, rtol=tolerance, atol=tolerance):
degeneracy[i] += 1
com = self.center
inver = InversionCenter(com)
error = inver.error(geom, tolerance, groups=atom_ids)
if error <= tolerance:
valid.append(inver)
if any(np.isclose(m, 0, atol=1e-6) for m in moments):
return valid
ortho_to = []
for vec, degen in zip(axes, degeneracy):
if any(d > 1 for d in degeneracy) and degen == 1:
ortho_to.append(vec)
elif all(d == 1 for d in degeneracy):
ortho_to.append(vec)
# find vectors from COM to each atom
# these might be proper rotation axes
atom_axes = geom.coords - com
# find vectors normal to each pair of atoms
# these might be normal to a miror plane
atom_pair_norms = []
for i, v in enumerate(atom_axes):
dv = atom_axes - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask = np.logical_and(mask2, mask3)
pair_n = np.cross(v, atom_axes[mask])
norms = np.linalg.norm(pair_n, axis=1)
pair_n = np.take(pair_n, np.nonzero(norms), axis=0)[0]
norms = np.take(norms, np.nonzero(norms), axis=0)
pair_n /= norms.T
atom_pair_norms.extend(pair_n.tolist())
atom_pair_norms = np.array(atom_pair_norms)
# find vectors to the midpoints between each
# pair of like atoms
# these might be proper rotations
atom_pairs = []
for atom_id in set(atom_ids):
ndx = (atom_ids == atom_id).nonzero()[0]
subset_axes = np.take(atom_axes, ndx, axis=0)
for i, v in enumerate(subset_axes):
mask = np.ones(len(subset_axes), dtype=bool)
mask[i] = False
pair_v = subset_axes[mask] + v
norms = np.linalg.norm(pair_v, axis=1)
pair_v = np.take(pair_v, np.nonzero(norms), axis=0)[0]
norms = np.take(norms, np.nonzero(norms), axis=0)
pair_v /= norms.T
atom_pairs.extend(pair_v.tolist())
atom_pairs = np.array(atom_pairs)
norms = np.linalg.norm(atom_axes, axis=1)
# don't want axis for an atom that is at the COM (0-vector)
atom_axes = np.take(atom_axes, np.nonzero(norms), axis=0)[0]
# normalize
norms = np.take(norms, np.nonzero(norms))
atom_axes /= norms.T
# s = ""
# for v in atom_axes:
# s += ".arrow %f %f %f " % tuple(com)
# end = com + 2 * v
# s += "%f %f %f\n" % tuple(end)
# with open("test2.bild", "w") as f:
# f.write(s)
# remove parallel/antiparallel axes for single atoms
# print(atom_axes)
mask = np.ones(len(atom_axes), dtype=bool)
for i, v in enumerate(atom_axes):
if not mask[i]:
continue
dv = atom_axes - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
# print(", ".join(["%.2f" % a for a in angles]))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask[:i] *= np.logical_and(mask2, mask3)[:i]
# print(mask)
atom_axes = atom_axes[mask]
# s = ""
# for v in atom_axes:
# s += ".arrow %f %f %f " % tuple(com)
# end = com + 2 * v
# s += "%f %f %f\n" % tuple(end)
# with open("test2.bild", "w") as f:
# f.write(s)
# remove parallel/antiparallel axes for pairs of atoms
mask = np.ones(len(atom_pairs), dtype=bool)
for i, v in enumerate(atom_pairs):
if not mask[i]:
continue
dv = np.delete(atom_pairs, i, axis=0) - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask4 = np.logical_and(mask2, mask3)
mask[:i] *= mask4[:i]
mask[i + 1:] *= mask4[i:]
atom_pairs = atom_pairs[mask]
# remove parallel/antiparallel norms for pairs of atoms
mask = np.ones(len(atom_pair_norms), dtype=bool)
for i, v in enumerate(atom_pair_norms):
if not mask[i]:
continue
dv = np.delete(atom_pair_norms, i, axis=0) - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask4 = np.logical_and(mask2, mask3)
mask[:i] *= mask4[:i]
mask[i + 1:] *= mask4[i:]
atom_pair_norms = atom_pair_norms[mask]
# s = ""
# for v in atom_pair_norms:
# s += ".arrow %f %f %f " % tuple(com)
# end = com + 2 * v
# s += "%f %f %f\n" % tuple(end)
# with open("test2.bild", "w") as f:
# f.write(s)
if len(atom_pairs):
# remove axes for pairs of atoms that are parallel/antiparallel
# to axes for single atoms
mask = np.ones(len(atom_pairs), dtype=bool)
for i, v in enumerate(atom_axes):
dv = atom_pairs - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask *= np.logical_and(mask2, mask3)
atom_pairs = atom_pairs[mask]
if len(atom_pair_norms):
# remove norms for pairs of atoms that are parallel/antiparallel
# to axes for single atoms
mask = np.ones(len(atom_pair_norms), dtype=bool)
for i, v in enumerate(atom_axes):
dv = atom_pair_norms - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask *= np.logical_and(mask2, mask3)
atom_pair_norms = atom_pair_norms[mask]
# s = ""
# for v in atom_pair_norms:
# s += ".arrow %f %f %f " % tuple(com)
# end = com + 2 * v
# s += "%f %f %f\n" % tuple(end)
# with open("test2.bild", "w") as f:
# f.write(s)
# remove axes for single atoms that are parallel/antiparallel
# to moment of inertia axes
mask = np.ones(len(atom_axes), dtype=bool)
for i, v in enumerate(axes):
dv = atom_axes - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask *= np.logical_and(mask2, mask3)
atom_axes = atom_axes[mask]
# remove axes for pairs of atoms that are parallel/antiparallel
# to moment of inertia axes
if len(atom_pairs):
mask = np.ones(len(atom_pairs), dtype=bool)
for i, v in enumerate(axes):
dv = atom_pairs - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask *= np.logical_and(mask2, mask3)
atom_pairs = atom_pairs[mask]
# remove norms for pairs of atoms that are parallel/antiparallel
# to moment of inertia axes
if len(atom_pair_norms):
mask = np.ones(len(atom_pair_norms), dtype=bool)
for i, v in enumerate(axes):
dv = atom_pair_norms - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask *= np.logical_and(mask2, mask3)
atom_pair_norms = atom_pair_norms[mask]
# s = ""
# for v in atom_pair_norms:
# s += ".arrow %f %f %f " % tuple(com)
# end = com + 2 * v
# s += "%f %f %f\n" % tuple(end)
# with open("test2.bild", "w") as f:
# f.write(s)
# remove axes that are not orthogonal to moments of inertia axes
if ortho_to:
mask = np.ones(len(atom_axes), dtype=bool)
pair_mask = np.ones(len(atom_pairs), dtype=bool)
pair_mask_norms = np.ones(len(atom_pair_norms), dtype=bool)
for v in ortho_to:
dv = atom_axes - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask1 = abs(angles - np.pi / 2) < rotation_tolerance
mask *= mask1
if len(atom_pairs):
dv = atom_pairs - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
pair_mask = abs(angles - np.pi / 2) < rotation_tolerance
atom_pairs = atom_pairs[pair_mask]
if len(atom_pair_norms):
dv = atom_pair_norms - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
pair_mask_norms = abs(angles - np.pi / 2) < rotation_tolerance
atom_pair_norms = atom_pair_norms[pair_mask_norms]
atom_axes = atom_axes[mask]
for v in axes:
mask = np.ones(len(atom_axes), dtype=bool)
pair_mask = np.ones(len(atom_pairs), dtype=bool)
pair_mask_norms = np.ones(len(atom_pair_norms), dtype=bool)
dv = atom_axes - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask1 = angles > rotation_tolerance
mask2 = angles < np.pi - rotation_tolerance
mask *= np.logical_and(mask1, mask2)
if len(atom_pairs):
dv = atom_pairs - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
pair_mask1 = angles > rotation_tolerance
pair_mask2 = angles < np.pi - rotation_tolerance
pair_mask *= np.logical_and(pair_mask1, pair_mask2)
atom_pairs = atom_pairs[pair_mask]
if len(atom_pair_norms):
dv = atom_pair_norms - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
atom_pair_norms1 = angles > rotation_tolerance
atom_pair_norms2 = angles < np.pi - rotation_tolerance
pair_mask_norms *= np.logical_and(atom_pair_norms1, atom_pair_norms2)
atom_pair_norms = atom_pair_norms[pair_mask_norms]
if len(atom_pairs) and len(atom_axes):
for v in atom_pairs:
mask = np.ones(len(atom_axes), dtype=bool)
dv = atom_axes - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask1 = angles > rotation_tolerance
mask2 = angles < np.pi - rotation_tolerance
mask *= np.logical_and(mask1, mask2)
atom_axes = atom_axes[mask]
# s = ""
# for v in ortho_to:
# s += ".arrow %f %f %f " % tuple(com)
# end = com + 2 * v
# s += "%f %f %f\n" % tuple(end)
# with open("test2.bild", "w") as f:
# f.write(s)
checked_axes = 0
# find proper rotations along the axes we've found:
# * moments of inertia axes
# * COM -> atom vectors
# * COM -> midpoint of atom paris
# also grab axes for checking mirror planes
check_axes = []
primes = dict()
args = tuple([arg for arg in [axes, atom_axes, atom_pairs] if len(arg)])
principal_axis = None
for ax in np.concatenate(args):
max_n = None
found_n = []
for n in range(2, max_rotation + 1):
if n not in primes:
primes[n] = Primes.primes_below(n // 2)
# print(n, primes[n])
skip = False
for prime in primes[n]:
if n % prime == 0 and prime not in found_n:
# print("skipping", n)
skip = True
break
# if max_n and max_n % n != 0:
# # the highest order proper rotation axis must be
# # divisible by all other coincident axes
# continue
# look for C5^2 stuff
# for exp in range(1, 1 + n // 2):
for exp in range(1, 2):
if exp > 1 and n % exp == 0:
# skip things like C4^2 b/c that's just C2
continue
# see if the error associated with the element is reasonable
rot = ProperRotation(com, ax, n, exp)
error = rot.error(tolerance, groups=atom_ids, coords=coords)
checked_axes += 1
if error <= tolerance:
# print(geom.atoms[i])
# s = ".arrow %f %f %f " % tuple(com)
# end = com + 2 * ax
# s += "%f %f %f\n" % tuple(end)
# with open("test.bild", "a") as f:
# f.write(s)
valid.append(rot)
if principal_axis is None or rot.n > principal_axis[0].n:
principal_axis = [rot]
elif principal_axis is not None and rot.n == principal_axis[0].n:
principal_axis.append(rot)
found_n.append(n)
if n > 2:
# for Cn n != 2, add an element that is the same
# except the axis of rotation is antiparallel
rot2 = ProperRotation(com, -ax, n, exp)
valid.append(rot2)
if not max_n:
max_n = n
check_axes.append(ax)
elif exp == 1:
# can't have Cn^y if you don't have Cn
break
if degeneracy[0] == 3:
# spherical top molecules need more checks related to C2 axes
c2_axes = list(
filter(
lambda ele: isinstance(ele, ProperRotation) and ele.n == 2,
valid,
)
)
# TODO: replace with array operations like before
for i, c2_1 in enumerate(c2_axes):
for c2_2 in c2_axes[:i]:
test_axes = []
if len(c2_axes) == 3:
# T groups - check midpoint
for c2_3 in c2_axes[i:]:
axis = c2_1.axis + c2_2.axis + c2_3.axis
test_axes.append(axis)
axis = c2_1.axis + c2_2.axis - c2_3.axis
test_axes.append(axis)
axis = c2_1.axis - c2_2.axis + c2_3.axis
test_axes.append(axis)
axis = c2_1.axis - c2_2.axis - c2_3.axis
test_axes.append(axis)
else:
# O, I groups - check cross product
test_axes.append(np.cross(c2_1.axis, c2_2.axis))
for axis in test_axes:
norm = np.linalg.norm(axis)
if norm < 1e-5:
continue
axis /= norm
dup = False
for element in valid:
if isinstance(element, ProperRotation):
if 1 - abs(np.dot(element.axis, axis)) < rotation_tolerance:
dup = True
break
if dup:
continue
max_n = None
for n in range(max_rotation, 1, -1):
if max_n and max_n % n != 0:
continue
# for exp in range(1, 1 + n // 2):
for exp in range(1, 2):
if exp > 1 and n % exp == 0:
continue
rot = ProperRotation(com, axis, n, exp)
checked_axes += 1
error = rot.error(tolerance, groups=atom_ids, coords=coords)
if error <= tolerance:
if principal_axis is None or rot.n > principal_axis[0].n:
principal_axis = [rot]
elif principal_axis is not None and rot.n == principal_axis[0].n:
principal_axis.append(rot)
valid.append(rot)
if not max_n:
max_n = n
check_axes.append(ax)
if n > 2:
rot2 = ProperRotation(com, -axis, n, exp)
valid.append(rot2)
elif exp == 1:
break
# improper rotations
# coincident with proper rotations and can be 1x or 2x
# the order of the proper rotation
for element in valid:
if not isinstance(element, ProperRotation):
continue
if element.exp != 1:
continue
for x in [1, 2]:
if x * element.n == 2:
# S2 is inversion - we already checked i
continue
# for exp in range(1, 1 + (x * element.n) // 2):
for exp in range(1, 2):
if exp > 1 and (x * element.n) % exp == 0:
continue
for element2 in valid:
if isinstance(element2, ImproperRotation):
angle = angle_between_vectors(element2.axis, element.axis)
if (
element2.exp == exp and
(
angle < rotation_tolerance or
angle > (np.pi - rotation_tolerance)
) and
element2.n == x * element.n
):
break
else:
imp_rot = ImproperRotation(
element.translation,
element.axis,
x * element.n,
exp,
)
error = imp_rot.error(tolerance, groups=atom_ids, coords=coords)
if error <= tolerance:
valid.append(imp_rot)
rot2 = ImproperRotation(
element.translation,
-element.axis,
x * element.n,
exp
)
valid.append(rot2)
elif exp == 1:
break
c2_axes = list(
filter(
lambda ele: isinstance(ele, ProperRotation) and ele.n == 2 and ele.exp == 1,
valid,
)
)
c2_vectors = np.array([c2.axis for c2 in c2_axes])
sigma_norms = []
if bool(principal_axis) and len(c2_vectors) and principal_axis[0].n != 2:
for ax in principal_axis:
perp = np.cross(ax.axis, c2_vectors)
norms = np.linalg.norm(perp, axis=1)
mask = np.nonzero(norms)
perp = perp[mask]
norms = norms[mask]
perp /= norms[:, None]
sigma_norms.extend(perp)
sigma_norms = np.array(sigma_norms)
mask = np.ones(len(sigma_norms), dtype=bool)
for i, v in enumerate(sigma_norms):
if not mask[i]:
continue
dv = np.delete(sigma_norms, i, axis=0) - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask4 = np.logical_and(mask2, mask3)
mask[:i] *= mask4[:i]
mask[i + 1:] *= mask4[i:]
sigma_norms = sigma_norms[mask]
c2_vectors = np.append(c2_vectors, [-c2.axis for c2 in c2_axes], axis=0)
# mirror axes
# for I, O - only check c2 axes
if (
degeneracy[0] != 3 or
not c2_axes or
(degeneracy[0] == 3 and len(c2_axes) == 3)
):
if len(atom_pair_norms):
mask = np.ones(len(atom_pair_norms), dtype=bool)
for i, v in enumerate(axes):
dv = atom_pair_norms - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask *= np.logical_and(mask2, mask3)
atom_pair_norms = atom_pair_norms[mask]
mask = np.ones(len(atom_pair_norms), dtype=bool)
for i, v in enumerate(check_axes):
dv = atom_pair_norms - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask *= np.logical_and(mask2, mask3)
atom_pair_norms = atom_pair_norms[mask]
if check_axes:
check_axes = np.array(check_axes)
mask = np.ones(len(check_axes), dtype=bool)
for i, v in enumerate(axes):
dv = check_axes - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask *= np.logical_and(mask2, mask3)
check_axes = check_axes[mask]
mask = np.ones(len(check_axes), dtype=bool)
for i, v in enumerate(atom_axes):
dv = check_axes - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask *= np.logical_and(mask2, mask3)
check_axes = check_axes[mask]
mask = np.ones(len(check_axes), dtype=bool)
for i, v in enumerate(atom_pair_norms):
dv = check_axes - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask *= np.logical_and(mask2, mask3)
check_axes = check_axes[mask]
if len(sigma_norms):
sigma_norms = np.array(sigma_norms)
mask = np.ones(len(sigma_norms), dtype=bool)
for i, v in enumerate(axes):
dv = sigma_norms - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
angles = np.nan_to_num(angles)
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask *= np.logical_and(mask2, mask3)
sigma_norms = sigma_norms[mask]
mask = np.ones(len(sigma_norms), dtype=bool)
for i, v in enumerate(atom_axes):
dv = sigma_norms - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask *= np.logical_and(mask2, mask3)
sigma_norms = sigma_norms[mask]
mask = np.ones(len(sigma_norms), dtype=bool)
for i, v in enumerate(atom_pair_norms):
dv = sigma_norms - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask *= np.logical_and(mask2, mask3)
sigma_norms = sigma_norms[mask]
mask = np.ones(len(sigma_norms), dtype=bool)
for i, v in enumerate(check_axes):
dv = sigma_norms - v
c2 = np.linalg.norm(dv, axis=1) ** 2
angles = np.arccos(-0.5 * (c2 - 2))
mask2 = angles > rotation_tolerance
mask3 = angles < np.pi - rotation_tolerance
mask *= np.logical_and(mask2, mask3)
sigma_norms = sigma_norms[mask]
# print("axes")
# for ax in axes:
# print(ax)
#
# print("atom_axes")
# for ax in atom_axes:
# print(ax)
#