/
internal.py
3081 lines (2832 loc) · 123 KB
/
internal.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
#!/usr/bin/env python
from __future__ import division
import itertools
import time
from collections import OrderedDict, defaultdict
from copy import deepcopy
import networkx as nx
import numpy as np
from numpy.linalg import multi_dot
from geometric.molecule import Elements, Radii
from geometric.nifty import click, commadash, ang2bohr, bohr2ang, logger
from geometric.rotate import get_expmap, get_expmap_der, is_linear
## Some vector calculus functions
def unit_vector(a):
"""
Vector function: Given a vector a, return the unit vector
"""
return a / np.linalg.norm(a)
def d_unit_vector(a, ndim=3):
term1 = np.eye(ndim)/np.linalg.norm(a)
term2 = np.outer(a, a)/(np.linalg.norm(a)**3)
answer = term1-term2
return answer
def d_cross(a, b):
"""
Given two vectors a and b, return the gradient of the cross product axb w/r.t. a.
(Note that the answer is independent of a.)
Derivative is on the first axis.
"""
d_cross = np.zeros((3, 3), dtype=float)
for i in range(3):
ei = np.zeros(3, dtype=float)
ei[i] = 1.0
d_cross[i] = np.cross(ei, b)
return d_cross
def d_cross_ab(a, b, da, db):
"""
Given two vectors a, b and their derivatives w/r.t. a parameter, return the derivative
of the cross product
"""
answer = np.zeros((da.shape[0], 3), dtype=float)
for i in range(da.shape[0]):
answer[i] = np.cross(a, db[i]) + np.cross(da[i], b)
return answer
def ncross(a, b):
"""
Scalar function: Given vectors a and b, return the norm of the cross product
"""
cross = np.cross(a, b)
return np.linalg.norm(cross)
def d_ncross(a, b):
"""
Return the gradient of the norm of the cross product w/r.t. a
"""
ncross = np.linalg.norm(np.cross(a, b))
term1 = a * np.dot(b, b)
term2 = -b * np.dot(a, b)
answer = (term1+term2)/ncross
return answer
def nudot(a, b):
r"""
Given two vectors a and b, return the dot product (\hat{a}).b.
"""
ev = a / np.linalg.norm(a)
return np.dot(ev, b)
def d_nudot(a, b):
r"""
Given two vectors a and b, return the gradient of
the norm of the dot product (\hat{a}).b w/r.t. a.
"""
return np.dot(d_unit_vector(a), b)
def ucross(a, b):
r"""
Given two vectors a and b, return the cross product (\hat{a})xb.
"""
ev = a / np.linalg.norm(a)
return np.cross(ev, b)
def d_ucross(a, b):
r"""
Given two vectors a and b, return the gradient of
the cross product (\hat{a})xb w/r.t. a.
"""
ev = a / np.linalg.norm(a)
return np.dot(d_unit_vector(a), d_cross(ev, b))
def nucross(a, b):
r"""
Given two vectors a and b, return the norm of the cross product (\hat{a})xb.
"""
ev = a / np.linalg.norm(a)
return np.linalg.norm(np.cross(ev, b))
def d_nucross(a, b):
r"""
Given two vectors a and b, return the gradient of
the norm of the cross product (\hat{a})xb w/r.t. a.
"""
ev = a / np.linalg.norm(a)
return np.dot(d_unit_vector(a), d_ncross(ev, b))
## End vector calculus functions
def logArray(mat, precision=3, fmt="f"):
fmt="%% .%i%s" % (precision, fmt)
if len(mat.shape) == 1:
for i in range(mat.shape[0]):
logger.info(fmt % mat[i]),
print
elif len(mat.shape) == 2:
for i in range(mat.shape[0]):
for j in range(mat.shape[1]):
logger.info(fmt % mat[i,j]),
print
else:
raise RuntimeError("One or two dimensional arrays only")
class CartesianX(object):
def __init__(self, a, w=1.0):
self.a = a
self.w = w
self.isAngular = False
self.isPeriodic = False
def __repr__(self):
#return "Cartesian-X %i : Weight %.3f" % (self.a+1, self.w)
return "Cartesian-X %i" % (self.a+1)
def __eq__(self, other):
if type(self) is not type(other): return False
eq = self.a == other.a
if eq and self.w != other.w:
logger.warning("Warning: CartesianX same atoms, different weights (%.4f %.4f)" % (self.w, other.w))
return eq
def __ne__(self, other):
return not self.__eq__(other)
def value(self, xyz):
xyz = xyz.reshape(-1,3)
a = self.a
return xyz[a][0]*self.w
def derivative(self, xyz):
xyz = xyz.reshape(-1,3)
derivatives = np.zeros_like(xyz)
derivatives[self.a][0] = self.w
return derivatives
def second_derivative(self, xyz):
xyz = xyz.reshape(-1,3)
deriv2 = np.zeros((xyz.shape[0], xyz.shape[1], xyz.shape[0], xyz.shape[1]))
return deriv2
class CartesianY(object):
def __init__(self, a, w=1.0):
self.a = a
self.w = w
self.isAngular = False
self.isPeriodic = False
def __repr__(self):
# return "Cartesian-Y %i : Weight %.3f" % (self.a+1, self.w)
return "Cartesian-Y %i" % (self.a+1)
def __eq__(self, other):
if type(self) is not type(other): return False
eq = self.a == other.a
if eq and self.w != other.w:
logger.warning("Warning: CartesianY same atoms, different weights (%.4f %.4f)" % (self.w, other.w))
return eq
def __ne__(self, other):
return not self.__eq__(other)
def value(self, xyz):
xyz = xyz.reshape(-1,3)
a = self.a
return xyz[a][1]*self.w
def derivative(self, xyz):
xyz = xyz.reshape(-1,3)
derivatives = np.zeros_like(xyz)
derivatives[self.a][1] = self.w
return derivatives
def second_derivative(self, xyz):
xyz = xyz.reshape(-1,3)
deriv2 = np.zeros((xyz.shape[0], xyz.shape[1], xyz.shape[0], xyz.shape[1]))
return deriv2
class CartesianZ(object):
def __init__(self, a, w=1.0):
self.a = a
self.w = w
self.isAngular = False
self.isPeriodic = False
def __repr__(self):
# return "Cartesian-Z %i : Weight %.3f" % (self.a+1, self.w)
return "Cartesian-Z %i" % (self.a+1)
def __eq__(self, other):
if type(self) is not type(other): return False
eq = self.a == other.a
if eq and self.w != other.w:
logger.warning("Warning: CartesianZ same atoms, different weights (%.4f %.4f)" % (self.w, other.w))
return eq
def __ne__(self, other):
return not self.__eq__(other)
def value(self, xyz):
xyz = xyz.reshape(-1,3)
a = self.a
return xyz[a][2]*self.w
def derivative(self, xyz):
xyz = xyz.reshape(-1,3)
derivatives = np.zeros_like(xyz)
derivatives[self.a][2] = self.w
return derivatives
def second_derivative(self, xyz):
xyz = xyz.reshape(-1,3)
deriv2 = np.zeros((xyz.shape[0], xyz.shape[1], xyz.shape[0], xyz.shape[1]))
return deriv2
class TranslationX(object):
def __init__(self, a, w):
self.a = a
self.w = w
assert len(a) == len(w)
self.isAngular = False
self.isPeriodic = False
def __repr__(self):
# return "Translation-X %s : Weights %s" % (' '.join([str(i+1) for i in self.a]), ' '.join(['%.2e' % i for i in self.w]))
return "Translation-X %s" % (commadash(self.a))
def __eq__(self, other):
if type(self) is not type(other): return False
eq = set(self.a) == set(other.a)
if eq and np.sum((self.w-other.w)**2) > 1e-6:
logger.warning("Warning: TranslationX same atoms, different weights")
eq = False
return eq
def __ne__(self, other):
return not self.__eq__(other)
def value(self, xyz):
xyz = xyz.reshape(-1,3)
a = np.array(self.a)
return np.sum(xyz[a,0]*self.w)
def derivative(self, xyz):
xyz = xyz.reshape(-1,3)
derivatives = np.zeros_like(xyz)
for i, a in enumerate(self.a):
derivatives[a][0] = self.w[i]
return derivatives
def second_derivative(self, xyz):
xyz = xyz.reshape(-1,3)
deriv2 = np.zeros((xyz.shape[0], xyz.shape[1], xyz.shape[0], xyz.shape[1]))
return deriv2
class TranslationY(object):
def __init__(self, a, w):
self.a = a
self.w = w
assert len(a) == len(w)
self.isAngular = False
self.isPeriodic = False
def __repr__(self):
# return "Translation-Y %s : Weights %s" % (' '.join([str(i+1) for i in self.a]), ' '.join(['%.2e' % i for i in self.w]))
return "Translation-Y %s" % (commadash(self.a))
def __eq__(self, other):
if type(self) is not type(other): return False
eq = set(self.a) == set(other.a)
if eq and np.sum((self.w-other.w)**2) > 1e-6:
logger.warning("Warning: TranslationY same atoms, different weights")
eq = False
return eq
def __ne__(self, other):
return not self.__eq__(other)
def value(self, xyz):
xyz = xyz.reshape(-1,3)
a = np.array(self.a)
return np.sum(xyz[a,1]*self.w)
def derivative(self, xyz):
xyz = xyz.reshape(-1,3)
derivatives = np.zeros_like(xyz)
for i, a in enumerate(self.a):
derivatives[a][1] = self.w[i]
return derivatives
def second_derivative(self, xyz):
xyz = xyz.reshape(-1,3)
deriv2 = np.zeros((xyz.shape[0], xyz.shape[1], xyz.shape[0], xyz.shape[1]))
return deriv2
class TranslationZ(object):
def __init__(self, a, w):
self.a = a
self.w = w
assert len(a) == len(w)
self.isAngular = False
self.isPeriodic = False
def __repr__(self):
# return "Translation-Z %s : Weights %s" % (' '.join([str(i+1) for i in self.a]), ' '.join(['%.2e' % i for i in self.w]))
return "Translation-Z %s" % (commadash(self.a))
def __eq__(self, other):
if type(self) is not type(other): return False
eq = set(self.a) == set(other.a)
if eq and np.sum((self.w-other.w)**2) > 1e-6:
logger.warning("Warning: TranslationZ same atoms, different weights")
eq = False
return eq
def __ne__(self, other):
return not self.__eq__(other)
def value(self, xyz):
xyz = xyz.reshape(-1,3)
a = np.array(self.a)
return np.sum(xyz[a,2]*self.w)
def derivative(self, xyz):
xyz = xyz.reshape(-1,3)
derivatives = np.zeros_like(xyz)
for i, a in enumerate(self.a):
derivatives[a][2] = self.w[i]
return derivatives
def second_derivative(self, xyz):
xyz = xyz.reshape(-1,3)
deriv2 = np.zeros((xyz.shape[0], xyz.shape[1], xyz.shape[0], xyz.shape[1]))
return deriv2
class Rotator(object):
def __init__(self, a, x0):
self.a = list(tuple(sorted(a)))
x0 = x0.reshape(-1, 3)
self.x0 = x0.copy()
self.stored_valxyz = np.zeros_like(x0)
self.stored_value = None
self.stored_derxyz = np.zeros_like(x0)
self.stored_deriv = None
self.stored_deriv2xyz = np.zeros_like(x0)
self.stored_deriv2 = None
self.stored_norm = 0.0
# Extra variables to account for the case of linear molecules
# The reference axis used for computing dummy atom position
self.e0 = None
# Dot-squared measures alignment of molecule long axis with reference axis.
# If molecule becomes parallel with reference axis, coordinates must be reset.
self.stored_dot2 = 0.0
# Flag that records linearity of molecule
self.linear = False
def reset(self, x0):
x0 = x0.reshape(-1, 3)
self.x0 = x0.copy()
self.stored_valxyz = np.zeros_like(x0)
self.stored_value = None
self.stored_derxyz = np.zeros_like(x0)
self.stored_deriv = None
self.stored_deriv2xyz = np.zeros_like(x0)
self.stored_deriv2 = None
self.stored_norm = 0.0
self.e0 = None
self.stored_dot2 = 0.0
self.linear = False
def __eq__(self, other):
if type(self) is not type(other): return False
eq = set(self.a) == set(other.a)
if eq and np.sum((self.x0-other.x0)**2) > 1e-6:
logger.warning("Warning: Rotator same atoms, different reference positions")
return eq
def __repr__(self):
return "Rotator %s" % commadash(self.a)
def __ne__(self, other):
return not self.__eq__(other)
def calc_e0(self):
"""
Compute the reference axis for adding dummy atoms.
Only used in the case of linear molecules.
We first find the Cartesian axis that is "most perpendicular" to the molecular axis.
Next we take the cross product with the molecular axis to create a perpendicular vector.
Finally, this perpendicular vector is normalized to make a unit vector.
"""
ysel = self.x0[self.a, :]
vy = ysel[-1]-ysel[0]
ev = vy / np.linalg.norm(vy)
# Cartesian axes.
ex = np.array([1.0,0.0,0.0])
ey = np.array([0.0,1.0,0.0])
ez = np.array([0.0,0.0,1.0])
self.e0 = np.cross(vy, [ex, ey, ez][np.argmin([np.dot(i, ev)**2 for i in [ex, ey, ez]])])
self.e0 /= np.linalg.norm(self.e0)
def value(self, xyz):
xyz = xyz.reshape(-1, 3)
if np.max(np.abs(xyz-self.stored_valxyz)) < 1e-12:
return self.stored_value
else:
xsel = xyz[self.a, :]
ysel = self.x0[self.a, :]
xmean = np.mean(xsel,axis=0)
ymean = np.mean(ysel,axis=0)
if not self.linear and is_linear(xsel, ysel):
# print "Setting linear flag for", self
self.linear = True
if self.linear:
# Handle linear molecules.
vx = xsel[-1]-xsel[0]
vy = ysel[-1]-ysel[0]
# Calculate reference axis (if needed)
if self.e0 is None: self.calc_e0()
#log.debug(vx)
ev = vx / np.linalg.norm(vx)
# Measure alignment of molecular axis with reference axis
self.stored_dot2 = np.dot(ev, self.e0)**2
# Dummy atom is located one Bohr from the molecular center, direction
# given by cross-product of the molecular axis with the reference axis
xdum = np.cross(vx, self.e0)
ydum = np.cross(vy, self.e0)
exdum = xdum / np.linalg.norm(xdum)
eydum = ydum / np.linalg.norm(ydum)
xsel = np.vstack((xsel, exdum+xmean))
ysel = np.vstack((ysel, eydum+ymean))
answer = get_expmap(xsel, ysel)
self.stored_norm = np.linalg.norm(answer)
self.stored_valxyz = xyz.copy()
self.stored_value = answer.copy()
return answer
def derivative(self, xyz):
xyz = xyz.reshape(-1, 3)
if np.max(np.abs(xyz-self.stored_derxyz)) < 1e-12:
return self.stored_deriv
else:
xsel = xyz[self.a, :]
ysel = self.x0[self.a, :]
xmean = np.mean(xsel,axis=0)
ymean = np.mean(ysel,axis=0)
if not self.linear and is_linear(xsel, ysel):
# print "Setting linear flag for", self
self.linear = True
if self.linear:
vx = xsel[-1]-xsel[0]
vy = ysel[-1]-ysel[0]
if self.e0 is None: self.calc_e0()
xdum = np.cross(vx, self.e0)
ydum = np.cross(vy, self.e0)
exdum = xdum / np.linalg.norm(xdum)
eydum = ydum / np.linalg.norm(ydum)
xsel = np.vstack((xsel, exdum+xmean))
ysel = np.vstack((ysel, eydum+ymean))
deriv_raw = get_expmap_der(xsel, ysel)
if self.linear:
# Chain rule is applied to get terms from
# dummy atom derivatives
nxdum = np.linalg.norm(xdum)
dxdum = d_cross(vx, self.e0)
dnxdum = d_ncross(vx, self.e0)
# Derivative of dummy atom position w/r.t. molecular axis vector
dexdum = (dxdum*nxdum - np.outer(dnxdum,xdum))/nxdum**2
# Here we may compute finite difference derivatives to check
# h = 1e-6
# fdxdum = np.zeros((3, 3), dtype=float)
# for i in range(3):
# vx[i] += h
# dPlus = np.cross(vx, self.e0)
# dPlus /= np.linalg.norm(dPlus)
# vx[i] -= 2*h
# dMinus = np.cross(vx, self.e0)
# dMinus /= np.linalg.norm(dMinus)
# vx[i] += h
# fdxdum[i] = (dPlus-dMinus)/(2*h)
# if np.linalg.norm(dexdum - fdxdum) > 1e-6:
# print dexdum - fdxdum
# raise Exception()
# Apply terms from chain rule
deriv_raw[0] -= np.dot(dexdum, deriv_raw[-1])
for i in range(len(self.a)):
deriv_raw[i] += np.dot(np.eye(3), deriv_raw[-1])/len(self.a)
deriv_raw[-2] += np.dot(dexdum, deriv_raw[-1])
deriv_raw = deriv_raw[:-1]
derivatives = np.zeros((xyz.shape[0], 3, 3), dtype=float)
for i, a in enumerate(self.a):
derivatives[a, :, :] = deriv_raw[i, :, :]
self.stored_derxyz = xyz.copy()
self.stored_deriv = derivatives.copy()
return derivatives
def second_derivative(self, xyz):
xyz = xyz.reshape(-1, 3)
if np.max(np.abs(xyz-self.stored_deriv2xyz)) < 1e-12:
return self.stored_deriv2
else:
xsel = xyz[self.a, :]
ysel = self.x0[self.a, :]
xmean = np.mean(xsel,axis=0)
ymean = np.mean(ysel,axis=0)
if not self.linear and is_linear(xsel, ysel):
# print "Setting linear flag for", self
self.linear = True
if self.linear:
vx = xsel[-1]-xsel[0]
vy = ysel[-1]-ysel[0]
if self.e0 is None: self.calc_e0()
xdum = np.cross(vx, self.e0)
ydum = np.cross(vy, self.e0)
exdum = xdum / np.linalg.norm(xdum)
eydum = ydum / np.linalg.norm(ydum)
xsel = np.vstack((xsel, exdum+xmean))
ysel = np.vstack((ysel, eydum+ymean))
deriv_raw, deriv2_raw = get_expmap_der(xsel, ysel, second=True)
if self.linear:
# Chain rule is applied to get terms from dummy atom derivatives
def dexdum_(vx_):
xdum_ = np.cross(vx_, self.e0)
nxdum_ = np.linalg.norm(xdum_)
dxdum_ = d_cross(vx_, self.e0)
dnxdum_ = d_ncross(vx_, self.e0)
dexdum_ = (dxdum_*nxdum_ - np.outer(dnxdum_,xdum_))/nxdum_**2
return dexdum_.copy()
# First indices: elements of vx that are being differentiated w/r.t.
# Last index: elements of exdum itself
dexdum = dexdum_(vx)
dexdum2 = np.zeros((3, 3, 3), dtype=float)
h = 1.0e-3
for i in range(3):
vx[i] += h
dPlus = dexdum_(vx)
vx[i] -= 2*h
dMinus = dexdum_(vx)
vx[i] += h
dexdum2[i] = (dPlus-dMinus)/(2*h)
# Build arrays that contain derivative of dummy atom position
# w/r.t. real atom positions
ddum1 = np.zeros((len(self.a), 3, 3), dtype=float)
ddum1[0] = -dexdum
ddum1[-1] = dexdum
for i in range(len(self.a)):
ddum1[i] += np.eye(3)/len(self.a)
ddum2 = np.zeros((len(self.a), 3, len(self.a), 3, 3), dtype=float)
ddum2[ 0, : , 0, :] = dexdum2
ddum2[-1, : , 0, :] = -dexdum2
ddum2[ 0, :, -1, :] = -dexdum2
ddum2[-1, :, -1, :] = dexdum2
# =====
# Do not delete - reference codes using loops for chain rule terms
# for j in range(len(self.a)): # Loop over atom 1
# for m in range(3): # Loop over xyz of atom 1
# for k in range(len(self.a)): # Loop over atom 2
# for n in range(3): # Loop over xyz of atom 2
# for i in range(3): # Loop over elements of exponential map
# for p in range(3): # Loop over xyz of dummy atom
# deriv2_raw[j, m, k, n, i] += deriv2_raw[j, m, -1, p, i] * ddum1[k, n, p]
# deriv2_raw[j, m, k, n, i] += deriv2_raw[-1, p, k, n, i] * ddum1[j, m, p]
# deriv2_raw[j, m, k, n, i] += deriv_raw[-1, p, i] * ddum2[j, m, k, n, p]
# for q in range(3):
# deriv2_raw[j, m, k, n, i] += deriv2_raw[-1, p, -1, q, i] * ddum1[j, m, p] * ddum1[k, n, q]
# =====
deriv2_raw[:-1, :, :-1, :] += np.einsum('jmpi,knp->jmkni', deriv2_raw[:-1, :, -1, :, :], ddum1, optimize=True)
deriv2_raw[:-1, :, :-1, :] += np.einsum('pkni,jmp->jmkni', deriv2_raw[-1, :, :-1, :, :], ddum1, optimize=True)
deriv2_raw[:-1, :, :-1, :] += np.einsum('pi,jmknp->jmkni', deriv_raw[-1, :, :], ddum2, optimize=True)
deriv2_raw[:-1, :, :-1, :] += np.einsum('pqi,jmp,knq->jmkni', deriv2_raw[-1, :, -1, :, :], ddum1, ddum1, optimize=True)
deriv2_raw = deriv2_raw[:-1, :, :-1, :, :]
second_derivatives = np.zeros((xyz.shape[0], 3, xyz.shape[0], 3, 3), dtype=float)
for i, a in enumerate(self.a):
for j, b in enumerate(self.a):
second_derivatives[a, :, b, :, :] = deriv2_raw[i, :, j, :, :]
return second_derivatives
class RotationA(object):
def __init__(self, a, x0, Rotators, w=1.0):
self.a = tuple(sorted(a))
self.x0 = x0
self.w = w
if self.a not in Rotators:
Rotators[self.a] = Rotator(self.a, x0)
self.Rotator = Rotators[self.a]
self.isAngular = True
self.isPeriodic = False
def __repr__(self):
# return "Rotation-A %s : Weight %.3f" % (' '.join([str(i+1) for i in self.a]), self.w)
return "Rotation-A %s" % (commadash(self.a))
def __eq__(self, other):
if type(self) is not type(other): return False
eq = set(self.a) == set(other.a)
# if eq and np.sum((self.w-other.w)**2) > 1e-6:
# print "Warning: RotationA same atoms, different weights"
# if eq and np.sum((self.x0-other.x0)**2) > 1e-6:
# print "Warning: RotationA same atoms, different reference positions"
return eq
def __ne__(self, other):
return not self.__eq__(other)
def value(self, xyz):
return self.Rotator.value(xyz)[0]*self.w
def derivative(self, xyz):
der_all = self.Rotator.derivative(xyz)
derivatives = der_all[:, :, 0]*self.w
return derivatives
def second_derivative(self, xyz):
deriv2_all = self.Rotator.second_derivative(xyz)
second_derivatives = deriv2_all[:, :, :, :, 0]*self.w
return second_derivatives
class RotationB(object):
def __init__(self, a, x0, Rotators, w=1.0):
self.a = tuple(sorted(a))
self.x0 = x0
self.w = w
if self.a not in Rotators:
Rotators[self.a] = Rotator(self.a, x0)
self.Rotator = Rotators[self.a]
self.isAngular = True
self.isPeriodic = False
def __repr__(self):
# return "Rotation-B %s : Weight %.3f" % (' '.join([str(i+1) for i in self.a]), self.w)
return "Rotation-B %s" % (commadash(self.a))
def __eq__(self, other):
if type(self) is not type(other): return False
eq = set(self.a) == set(other.a)
# if eq and np.sum((self.w-other.w)**2) > 1e-6:
# print "Warning: RotationB same atoms, different weights"
# if eq and np.sum((self.x0-other.x0)**2) > 1e-6:
# print "Warning: RotationB same atoms, different reference positions"
return eq
def __ne__(self, other):
return not self.__eq__(other)
def value(self, xyz):
return self.Rotator.value(xyz)[1]*self.w
def derivative(self, xyz):
der_all = self.Rotator.derivative(xyz)
derivatives = der_all[:, :, 1]*self.w
return derivatives
def second_derivative(self, xyz):
deriv2_all = self.Rotator.second_derivative(xyz)
second_derivatives = deriv2_all[:, :, :, :, 1]*self.w
return second_derivatives
class RotationC(object):
def __init__(self, a, x0, Rotators, w=1.0):
self.a = tuple(sorted(a))
self.x0 = x0
self.w = w
if self.a not in Rotators:
Rotators[self.a] = Rotator(self.a, x0)
self.Rotator = Rotators[self.a]
self.isAngular = True
self.isPeriodic = False
def __repr__(self):
# return "Rotation-C %s : Weight %.3f" % (' '.join([str(i+1) for i in self.a]), self.w)
return "Rotation-C %s" % (commadash(self.a))
def __eq__(self, other):
if type(self) is not type(other): return False
eq = set(self.a) == set(other.a)
# if eq and np.sum((self.w-other.w)**2) > 1e-6:
# print "Warning: RotationC same atoms, different weights"
# if eq and np.sum((self.x0-other.x0)**2) > 1e-6:
# print "Warning: RotationC same atoms, different reference positions"
return eq
def __ne__(self, other):
return not self.__eq__(other)
def value(self, xyz):
return self.Rotator.value(xyz)[2]*self.w
def derivative(self, xyz):
der_all = self.Rotator.derivative(xyz)
derivatives = der_all[:, :, 2]*self.w
return derivatives
def second_derivative(self, xyz):
deriv2_all = self.Rotator.second_derivative(xyz)
second_derivatives = deriv2_all[:, :, :, :, 2]*self.w
return second_derivatives
class Distance(object):
def __init__(self, a, b):
self.a = a
self.b = b
if a == b:
raise RuntimeError('a and b must be different')
self.isAngular = False
self.isPeriodic = False
def __repr__(self):
return "Distance %i-%i" % (self.a+1, self.b+1)
def __eq__(self, other):
if type(self) is not type(other): return False
if self.a == other.a:
if self.b == other.b:
return True
if self.a == other.b:
if self.b == other.a:
return True
return False
def __ne__(self, other):
return not self.__eq__(other)
def value(self, xyz):
xyz = xyz.reshape(-1,3)
a = self.a
b = self.b
return np.sqrt(np.sum((xyz[a]-xyz[b])**2))
def derivative(self, xyz):
xyz = xyz.reshape(-1,3)
derivatives = np.zeros_like(xyz)
m = self.a
n = self.b
u = (xyz[m] - xyz[n]) / np.linalg.norm(xyz[m] - xyz[n])
derivatives[m, :] = u
derivatives[n, :] = -u
return derivatives
def second_derivative(self, xyz):
xyz = xyz.reshape(-1,3)
deriv2 = np.zeros((xyz.shape[0], xyz.shape[1], xyz.shape[0], xyz.shape[1]))
m = self.a
n = self.b
l = np.linalg.norm(xyz[m] - xyz[n])
u = (xyz[m] - xyz[n]) / l
mtx = (np.outer(u, u) - np.eye(3))/l
deriv2[m, :, m, :] = -mtx
deriv2[n, :, n, :] = -mtx
deriv2[m, :, n, :] = mtx
deriv2[n, :, m, :] = mtx
return deriv2
class Angle(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
self.isAngular = True
self.isPeriodic = False
if len({a, b, c}) != 3:
raise RuntimeError('a, b, and c must be different')
def __repr__(self):
return "Angle %i-%i-%i" % (self.a+1, self.b+1, self.c+1)
def __eq__(self, other):
if type(self) is not type(other): return False
if self.b == other.b:
if self.a == other.a:
if self.c == other.c:
return True
if self.a == other.c:
if self.c == other.a:
return True
return False
def __ne__(self, other):
return not self.__eq__(other)
def value(self, xyz):
xyz = xyz.reshape(-1,3)
a = self.a
b = self.b
c = self.c
# vector from first atom to central atom
vector1 = xyz[a] - xyz[b]
# vector from last atom to central atom
vector2 = xyz[c] - xyz[b]
# norm of the two vectors
norm1 = np.sqrt(np.sum(vector1**2))
norm2 = np.sqrt(np.sum(vector2**2))
dot = np.dot(vector1, vector2)
# Catch the edge case that very rarely this number is -1.
if dot / (norm1 * norm2) <= -1.0:
if (np.abs(dot / (norm1 * norm2)) + 1.0) < -1e-6:
raise RuntimeError('Encountered invalid value in angle')
return np.pi
if dot / (norm1 * norm2) >= 1.0:
if (np.abs(dot / (norm1 * norm2)) - 1.0) > 1e-6:
raise RuntimeError('Encountered invalid value in angle')
return 0.0
return np.arccos(dot / (norm1 * norm2))
def normal_vector(self, xyz):
xyz = xyz.reshape(-1,3)
a = self.a
b = self.b
c = self.c
# vector from first atom to central atom
vector1 = xyz[a] - xyz[b]
# vector from last atom to central atom
vector2 = xyz[c] - xyz[b]
# norm of the two vectors
norm1 = np.sqrt(np.sum(vector1**2))
norm2 = np.sqrt(np.sum(vector2**2))
crs = np.cross(vector1, vector2)
crs /= np.linalg.norm(crs)
return crs
def derivative(self, xyz):
xyz = xyz.reshape(-1,3)
derivatives = np.zeros_like(xyz)
m = self.a
o = self.b
n = self.c
# Unit displacement vectors
u_prime = (xyz[m] - xyz[o])
u_norm = np.linalg.norm(u_prime)
v_prime = (xyz[n] - xyz[o])
v_norm = np.linalg.norm(v_prime)
u = u_prime / u_norm
v = v_prime / v_norm
VECTOR1 = np.array([1, -1, 1]) / np.sqrt(3)
VECTOR2 = np.array([-1, 1, 1]) / np.sqrt(3)
if np.linalg.norm(u + v) < 1e-10 or np.linalg.norm(u - v) < 1e-10:
# if they're parallel
if ((np.linalg.norm(u + VECTOR1) < 1e-10) or
(np.linalg.norm(u - VECTOR2) < 1e-10)):
# and they're parallel o [1, -1, 1]
w_prime = np.cross(u, VECTOR2)
else:
w_prime = np.cross(u, VECTOR1)
else:
w_prime = np.cross(u, v)
w = w_prime / np.linalg.norm(w_prime)
term1 = np.cross(u, w) / u_norm
term2 = np.cross(w, v) / v_norm
derivatives[m, :] = term1
derivatives[n, :] = term2
derivatives[o, :] = -(term1 + term2)
return derivatives
def second_derivative(self, xyz):
xyz = xyz.reshape(-1,3)
deriv2 = np.zeros((xyz.shape[0], xyz.shape[1], xyz.shape[0], xyz.shape[1]))
m = self.a
o = self.b
n = self.c
# Unit displacement vectors
u_prime = (xyz[m] - xyz[o])
u_norm = np.linalg.norm(u_prime)
v_prime = (xyz[n] - xyz[o])
v_norm = np.linalg.norm(v_prime)
u = u_prime / u_norm
v = v_prime / v_norm
# Deriv2 derivatives are set to zero in the case of parallel or antiparallel vectors
if np.linalg.norm(u + v) < 1e-10 or np.linalg.norm(u - v) < 1e-10:
return deriv2
# cosine and sine of the bond angle
cq = np.dot(u, v)
sq = np.sqrt(1-cq**2)
uu = np.outer(u, u)
uv = np.outer(u, v)
vv = np.outer(v, v)
de = np.eye(3)
term1 = (uv + uv.T - (3*uu - de)*cq)/(u_norm**2*sq)
term2 = (uv + uv.T - (3*vv - de)*cq)/(v_norm**2*sq)
term3 = (uu + vv - uv*cq - de)/(u_norm*v_norm*sq)
term4 = (uu + vv - uv.T*cq - de)/(u_norm*v_norm*sq)
der1 = self.derivative(xyz)
def zeta(a_, m_, n_):
return (int(a_==m_) - int(a_==n_))
for a in [m, n, o]:
for b in [m, n, o]:
deriv2[a, :, b, :] = (zeta(a, m, o)*zeta(b, m, o)*term1
+ zeta(a, n, o)*zeta(b, n, o)*term2
+ zeta(a, m, o)*zeta(b, n, o)*term3
+ zeta(a, n, o)*zeta(b, m, o)*term4
- (cq/sq) * np.outer(der1[a], der1[b]))
return deriv2
class LinearAngle(object):
def __init__(self, a, b, c, axis):
self.a = a
self.b = b
self.c = c
self.axis = axis
self.isAngular = False
self.isPeriodic = False
if len({a, b, c}) != 3:
raise RuntimeError('a, b, and c must be different')
self.e0 = None
self.stored_dot2 = 0.0
def reset(self, xyz):
xyz = xyz.reshape(-1,3)
a = self.a
b = self.b
c = self.c
# Unit vector pointing from a to c.
v = xyz[c] - xyz[a]
ev = v / np.linalg.norm(v)
# Cartesian axes.
ex = np.array([1.0,0.0,0.0])
ey = np.array([0.0,1.0,0.0])
ez = np.array([0.0,0.0,1.0])
self.e0 = [ex, ey, ez][np.argmin([np.dot(i, ev)**2 for i in [ex, ey, ez]])]
self.stored_dot2 = 0.0
def __repr__(self):
return "LinearAngle%s %i-%i-%i" % (["X","Y"][self.axis], self.a+1, self.b+1, self.c+1)
def __eq__(self, other):
if not hasattr(other, 'axis'): return False
if self.axis is not other.axis: return False
if type(self) is not type(other): return False
if self.b == other.b:
if self.a == other.a:
if self.c == other.c:
return True
if self.a == other.c:
if self.c == other.a:
return True
return False
def __ne__(self, other):
return not self.__eq__(other)
def value(self, xyz):
"""
This function measures the displacement of the BA and BC unit
vectors in the linear angle "ABC". The displacements are measured
along two axes that are perpendicular to the AC unit vector.
"""
xyz = xyz.reshape(-1,3)
a = self.a
b = self.b
c = self.c
# Unit vector pointing from a to c.
v = xyz[c] - xyz[a]
ev = v / np.linalg.norm(v)
if self.e0 is None: self.reset(xyz)
e0 = self.e0
self.stored_dot2 = np.dot(ev, e0)**2
# Now make two unit vectors that are perpendicular to this one.
c1 = np.cross(ev, e0)
e1 = c1 / np.linalg.norm(c1)
c2 = np.cross(ev, e1)
e2 = c2 / np.linalg.norm(c2)
# BA and BC unit vectors in ABC angle
vba = xyz[a]-xyz[b]
eba = vba / np.linalg.norm(vba)
vbc = xyz[c]-xyz[b]
ebc = vbc / np.linalg.norm(vbc)
if self.axis == 0:
answer = np.dot(eba, e1) + np.dot(ebc, e1)
else:
answer = np.dot(eba, e2) + np.dot(ebc, e2)
return answer
def derivative(self, xyz):
xyz = xyz.reshape(-1,3)