forked from willsheffler/pymol
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxyzMath.py
1815 lines (1544 loc) · 64.8 KB
/
xyzMath.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
"""
Easy 3D Linear Algebra, like xyz\* in rosetta
"""
from random import gauss, uniform
from math import pi, sqrt, sin, cos, acos, asin, atan2, degrees, radians, copysign
from itertools import chain, product, izip
import math
import operator as op
EPS = 0.00001
SQRTEPS = sqrt(EPS)
ATET = 54.735610317245360079 # asin(sr2/sr3)
AOCT = 35.264389682754668343 # asin(sr1/sr3)
AICS = 20.89774264557 # asin(G/2/sr3)
def isint(x):
return type(x) is int
def isfloat(x):
return type(x) is float
def isnum(x):
return isint(x) or isfloat(x)
def isiter(x):
return hasattr(x, "__iter__")
def islist(x):
return type(x) is list
def istuple(x):
return type(x) is tuple
def isvec(x):
return hasattr(x, 'x') and hasattr(x, 'y') and hasattr(x, 'z')
def ismat(x):
return all(hasattr(x, a) for a in 'xx xy xz yx yy yz zx zy zz'.split())
def isxform(x):
return hasattr(x, "__Xform__")
class Vec(object):
"""a Vector like xyzVector<Real> in rosetta
>>> v = Vec(1,2,3)
>>> print v, 10*v
(1.000000,2.000000,3.000000) (10.000000,20.000000,30.000000)
multiplication is a dot prod at the moment
>>> v*v
14.0
>>> assert Vec(1,0,-0) == Vec(1,-0,0)
"""
def to_rosetta(v):
from rosetta.numeric import xyzVector_double_t
return xyzVector_double_t(v.x, v.y, v.z)
def __Vec__(self):
return True
def __init__(self, x=0.0, y=None, z=None):
if y is None:
if isnum(x):
self.x, self.y, self.z = (float(x),) * 3
elif isvec(x):
self.x, self.y, self.z = x.x, x.y, x.z
elif isiter(x):
i = iter(x)
self.x, self.y, self.z = i.next(), i.next(), i.next()
else:
raise NotImplementedError
elif z is not None:
assert isnum(x) and isnum(y) and isnum(z)
self.x, self.y, self.z = float(x), float(y), float(z)
else:
raise NotImplementedError
assert isfloat(self.x)
assert isfloat(self.y)
assert isfloat(self.z)
def dot(u, v):
assert isvec(v)
return u.x * v.x + u.y * v.y + u.z * v.z
def normdot(u, v):
assert isvec(v)
return min(1.0, max(-1.0, u.dot(v) / u.length() / v.length()))
def angle(u, v):
assert isvec(v)
d = u.normdot(v)
if d > 1.0 - EPS:
return 0.0
if d < EPS - 1.0:
return pi
return acos(d)
def angle_degrees(u, v):
return degrees(u.angle(v))
def lineangle(u, v):
assert isvec(v)
if u.length() < SQRTEPS or v.length < SQRTEPS:
return 0.0
ang = abs(acos(u.normdot(v)))
return ang if ang < pi / 2.0 else pi - ang
def lineangle_degrees(u, v):
if isvec(v):
return degrees(u.lineangle(v))
raise NotImplementedError
def length(u):
return sqrt(u.dot(u))
def length_squared(u):
return u.dot(u)
def distance(u, v):
assert isvec(v)
return (u - v).length()
def distance_squared(u, v):
assert isvec(v)
return (u - v).length_squared()
def cross(u, v):
assert isvec(v)
return Vec(u.y * v.z - u.z * v.y, u.z * v.x - u.x * v.z, u.x * v.y - u.y * v.x)
def __mul__(u, a):
if isnum(a):
return Vec(u.x * a, u.y * a, u.z * a)
elif isvec(a):
return u.dot(a)
else:
return a.__rmul__(u)
def __rmul__(u, a):
return u * a
def __add__(u, v):
if isvec(v):
return Vec(u.x + v.x, u.y + v.y, u.z + v.z)
return v.__radd__(u)
def __sub__(u, v):
if isvec(v):
return Vec(u.x - v.x, u.y - v.y, u.z - v.z)
return v.__rsub__(u)
def __neg__(u):
return Vec(-u.x, -u.y, -u.z)
def __div__(u, a):
return u * (1.0 / a)
def __str__(self):
return "(%f,%f,%f)" % (self.x, self.y, self.z)
def __repr__(self):
return "Vec( %f, %f, %f )" % (self.x, self.y, self.z)
def normalize(u):
l = u.length()
u.x /= l
u.y /= l
u.z /= l
def normalized(u):
v = Vec(u)
v.normalize()
return v
def outer(u, v):
assert isvec(v)
return Mat(u.x * v.x, u.x * v.y, u.x * v.z,
u.y * v.x, u.y * v.y, u.y * v.z,
u.z * v.x, u.z * v.y, u.z * v.z)
def __eq__(self, other):
assert isvec(other)
return (abs(self.x - other.x) < EPS and
abs(self.y - other.y) < EPS and
abs(self.z - other.z) < EPS)
def rounded(self, sd):
return Vec(round(self.x, sd), round(self.y, sd), round(self.z, sd))
def unit(v):
if abs(v.x) > SQRTEPS:
return v / v.x
elif abs(v.y) > SQRTEPS:
return v / v.y
elif abs(v.z) > SQRTEPS:
return v / v.z
def __len__(v):
return 3
def abs(v):
return Vec(abs(v.x), abs(v.y), abs(v.z))
def __getitem__(v, i):
if i is 0:
return v.x
if i is 1:
return v.x
if i is 2:
return v.x
raise IndexError
def tuple(v):
return (v.x, v.y, v.z)
def key(v):
return v.abs().unit().rounded(6).tuple()
def round0(v):
if abs(v.x) < EPS:
v.x = 0
if abs(v.y) < EPS:
v.y = 0
if abs(v.z) < EPS:
v.z = 0
Ux = Vec(1, 0, 0)
Uy = Vec(0, 1, 0)
Uz = Vec(0, 0, 1)
V0 = Vec(0, 0, 0)
def randvec(n=None):
if n is None:
return Vec(gauss(0, 1), gauss(0, 1), gauss(0, 1))
return [Vec(gauss(0, 1), gauss(0, 1), gauss(0, 1)) for i in range(n)]
def randveccube(r=1.0):
return Vec(uniform(-1, 1), uniform(-1, 1), uniform(-1, 1)) * r
def randvecball(r=1.0):
v = randveccube(r)
while v.length_squared() > r * r:
v = randveccube(r)
return v
def randnorm(n=None):
"""
>>> assert abs(randnorm().length()-1.0) < 0.0000001
"""
if n is None:
return randvec().normalized()
return (randvec().normalized() for i in range(n))
def coplanar(x1, x2, x3, x4):
"""
>>> u,v,w = randvec(3)
>>> a,b,c = (gauss(0,10) for i in range(3))
>>> assert coplanar(u, v, w, u + a*(u-v) + b*(v-w) + c*(w-u) )
>>> assert not coplanar(u, v, w, u + a*(u-v) + b*(v-w) + c*(w-u) + randvec().cross(u-v) )
"""
return abs((x3 - x1).dot((x2 - x1).cross(x4 - x3))) < SQRTEPS
def rmsd(l, m):
"""
>>> l,m = randvec(6),randvec(6)
>>> rmsd(l,l)
0.0
"""
rmsd = 0.0
for u, v in izip(l, m):
rmsd += u.distance_squared(v)
return sqrt(rmsd)
class Mat(object):
"""docstring for Mat
>>> m = Mat(2,0,0,0,1,0,0,0,1)
>>> print m
Mat[ (2.000000,0.000000,0.000000), (0.000000,1.000000,0.000000), (0.000000,0.000000,1.000000) ]
>>> print m*m
Mat[ (4.000000,0.000000,0.000000), (0.000000,1.000000,0.000000), (0.000000,0.000000,1.000000) ]
>>> print Mat(*range(1,10)) * Mat(*range(10,19))
Mat[ (84.000000,90.000000,96.000000), (201.000000,216.000000,231.000000), (318.000000,342.000000,366.000000) ]
>>> assert Mat(0.0,1.0,2.0,3,4,5,6,7,8) == Mat(-0,1,2,3,4,5.0,6.0,7.0,8.0)
>>> print Mat(100,2,3,4,5,6,7,8,9).det()
-297.0
>>> m = Mat(100,2,3,4,5,6,7,8,9)
>>> assert m * ~m == Imat
"""
def to_rosetta(m):
from rosetta.numeric import xyzMatrix_double_t
r = xyzMatrix_double_t()
r.xx(m.xx); r.xy(m.xy); r.xz(m.xz)
r.yx(m.yx); r.yy(m.yy); r.yz(m.yz)
r.zx(m.zx); r.zy(m.zy); r.zz(m.zz)
return r
def __Mat__(self):
return True
def __init__(self, xx=None, xy=None, xz=None, yx=None, yy=None, yz=None, zx=None, zy=None, zz=None):
super(Mat, self).__init__()
if xx is None: # identity default
self.xx, self.xy, self.xz = 1.0, 0.0, 0.0
self.yx, self.yy, self.yz = 0.0, 1.0, 0.0
self.zx, self.zy, self.zz = 0.0, 0.0, 1.0
print type(self.xx)
elif xy is None and ismat(xx):
if not isnum(xx.xx):
self.xx, self.xy, self.xz = xx.xx(), xx.xy(), xx.xz()
self.yx, self.yy, self.yz = xx.yx(), xx.yy(), xx.yz()
self.zx, self.zy, self.zz = xx.zx(), xx.zy(), xx.zz()
else:
self.xx, self.xy, self.xz = xx.xx(), xx.xy(), xx.xz()
self.yx, self.yy, self.yz = xx.yx(), xx.yy(), xx.yz()
self.zx, self.zy, self.zz = xx.zx(), xx.zy(), xx.zz()
elif yx is None and isvec(xx) and isvec(xy) and isvec(xz):
self.xx, self.xy, self.xz = xx.x, xy.x, xz.x
self.yx, self.yy, self.yz = xx.y, xy.y, xz.y
self.zx, self.zy, self.zz = xx.z, xy.z, xz.z
elif isnum(xx):
self.xx, self.xy, self.xz = float(xx), float(xy), float(xz)
self.yx, self.yy, self.yz = float(yx), float(yy), float(yz)
self.zx, self.zy, self.zz = float(zx), float(zy), float(zz)
else:
raise NotImplementedError
# assert isnum(self.xx) and isnum(self.xy) and isnum(self.xz)
# assert isnum(self.yx) and isnum(self.yy) and isnum(self.yz)
# assert isnum(self.zx) and isnum(self.zy) and isnum(self.zz)
def row(m, i):
assert isint(i)
if i is 0:
return Vec(m.xx, m.xy, m.xz)
elif i is 1:
return Vec(m.yx, m.yy, m.yz)
elif i is 2:
return Vec(m.zx, m.zy, m.zz)
else:
assert 0 <= i and i <= 2
def col(m, i):
assert isint(i)
if i is 0:
return Vec(m.xx, m.yx, m.zx)
elif i is 1:
return Vec(m.xy, m.yy, m.zy)
elif i is 2:
return Vec(m.xz, m.yz, m.zz)
else:
assert 0 <= i and i <= 2
def rowx(m):
return m.row(0)
def rowy(m):
return m.row(1)
def rowz(m):
return m.row(2)
def colx(m):
return m.col(0)
def coly(m):
return m.col(1)
def colz(m):
return m.col(2)
def __invert__(m):
"""
>>> from random import random
>>> for i in range(10):
... m = random()*Mat(random(),random(),random(),random(),random(),random(),random(),random(),random())
... assert ~m*m == Imat
... assert m*~m == Imat
"""
return Mat(m.zz * m.yy - m.zy * m.yz, -(m.zz * m.xy - m.zy * m.xz), m.yz * m.xy - m.yy * m.xz,
-(m.zz * m.yx - m.zx * m.yz), m.zz * m.xx -
m.zx * m.xz, -(m.yz * m.xx - m.yx * m.xz),
m.zy * m.yx - m.zx * m.yy, -(m.zy * m.xx - m.zx * m.xy), m.yy * m.xx - m.yx * m.xy) / m.det()
def __mul__(m, rhs):
if isnum(rhs):
return Mat(rhs * m.xx, rhs * m.xy, rhs * m.xz, rhs * m.yx, rhs * m.yy, rhs * m.yz, rhs * m.zx, rhs * m.zy, rhs * m.zz)
elif isvec(rhs):
return Vec(m.rowx() * rhs, m.rowy() * rhs, m.rowz() * rhs)
elif ismat(rhs):
return Mat(m.rowx() * rhs.colx(), m.rowx() * rhs.coly(), m.rowx() * rhs.colz(),
m.rowy() * rhs.colx(), m.rowy() * rhs.coly(), m.rowy() * rhs.colz(),
m.rowz() * rhs.colx(), m.rowz() * rhs.coly(), m.rowz() * rhs.colz())
else:
return rhs.__rmul__(m)
def __rmul__(m, v):
if isnum(v):
return m * v
elif isvec(v):
return Vec(m.colx() * v, m.coly() * v, m.colz() * v)
def __div__(m, v):
return m * (1 / v)
def __add__(m, v):
if isnum(v):
return Mat(v + m.xx, v + m.xy, v + m.xz, v + m.yx, v + m.yy, v + m.yz, v + m.zx, v + m.zy, v + m.zz)
elif ismat(v):
return Mat(v.xx + m.xx, v.xy + m.xy, v.xz + m.xz, v.yx + m.yx, v.yy + m.yy, v.yz + m.yz, v.zx + m.zx, v.zy + m.zy, v.zz + m.zz)
else:
return v.__radd__(m)
def __sub__(m, v):
return m + -v
def __neg__(m):
return m * -1
def __str__(m):
return "Mat[ %s, %s, %s ]" % (
str(m.rowx()), str(m.rowy()), str(m.rowz()))
def __repr__(m):
return "Mat( %s, %s, %s )" % (
repr(m.colx()), repr(m.coly()), repr(m.colz()))
def transpose(m):
m = Mat(m.xx, m.yx, m.zx, m.xy, m.yy, m.zy, m.xz, m.yz, m.zz)
def transposed(m):
return Mat(m.xx, m.yx, m.zx,
m.xy, m.yy, m.zy, m.xz, m.yz, m.zz)
def det(m):
# a11 (a33 a22- a32 a23)- a21 ( a33 a12- a32 a13)+
# a31( a23 a12- a22 a13)
return m.xx * (m.zz * m.yy - m.zy * m.yz) - m.yx * (m.zz * m.xy - m.zy * m.xz) + m.zx * (m.yz * m.xy - m.yy * m.xz)
def trace(m):
return m.xx + m.yy + m.zz
def add_diagonal(m, v):
return Mat(v.x + m.xx, m.xy, m.xz,
m.yx, v.y + m.yy, m.yz, m.zx, m.zy, v.z + m.zz)
def is_rotation(m):
return (m.colx().isnormal() and m.coly().isnormal() and m.colz().isnormal() and
m.rowx().isnormal() and m.rowy().isnormal() and m.rowz().isnormal())
def __eq__(self, other):
return (
abs(self.xx - other.xx) < EPS and
abs(self.xy - other.xy) < EPS and
abs(self.xz - other.xz) < EPS and
abs(self.yx - other.yx) < EPS and
abs(self.yy - other.yy) < EPS and
abs(self.yz - other.yz) < EPS and
abs(self.zx - other.zx) < EPS and
abs(self.zy - other.zy) < EPS and
abs(self.zz - other.zz) < EPS)
def __neq__(self, odher):
return not self == other
def rotation_axis(R):
"""
>>> axis ,ang = randnorm(),uniform(-pi,pi)
>>> axis2,ang2 = rotation_matrix(axis,ang).rotation_axis()
>>> assert abs( abs(ang) - abs(ang2) ) < EPS
>>> assert axis == axis2 * copysign(1,ang*ang2)
"""
cos_theta = sin_cos_range((R.trace() - 1.0) / 2.0)
if cos_theta > -1.0 + EPS and cos_theta < 1.0 - EPS:
x = (1.0 if R.zy > R.yz else -1.0) * \
sqrt(max(0.0, (R.xx - cos_theta) / (1.0 - cos_theta)))
y = (1.0 if R.xz > R.zx else -1.0) * \
sqrt(max(0.0, (R.yy - cos_theta) / (1.0 - cos_theta)))
z = (1.0 if R.yx > R.xy else -1.0) * \
sqrt(max(0.0, (R.zz - cos_theta) / (1.0 - cos_theta)))
theta = acos(cos_theta)
assert abs(x * x + y * y + z * z - 1) <= 0.01
return Vec(x, y, z), theta
elif cos_theta >= 1.0 - EPS:
return Vec(1.0, 0.0, 0.0), 0.0
else:
nnT = (R + Imat) / 2.0
x, y, z = 0.0, 0.0, 0.0
if nnT.xx > EPS:
x = sqrt(nnT.xx)
y = nnT.yx / x
z = nnT.zx / x
elif nnT.yy > EPS:
x = 0
y = sqrt(nnT.yy)
z = nnT.zy / y
else:
assert(nnT.zz > EPS)
x = 0
y = 0
z = sqrt(nnT.zz)
assert abs(x * x + y * y + z * z - 1.0) <= 0.01
return Vec(x, y, z), pi
def euler_angles(self):
FLOAT_PRECISION = 1e-5
if self.zz >= 1 - FLOAT_PRECISION:
e1 = math.acos(sin_cos_range(self.xx))
e2 = 0.0
e3 = 0.0
return Vec(e1, e2, e3)
if self.zz <= -1 + FLOAT_PRECISION:
e1 = math.acos(sin_cos_range(self.xx))
e2 = 0.0
e3 = math.pi
return Vec(e1, e2, e3)
# sin2theta = 1 - cos2theta.
pos_sin_theta = math.sqrt(1 - self.zz * self.zz)
# two values are possible here: my convention is to use positive theta only.
# corresponding theta between [0,pi/2] -> [0,90] since st > 0
# and asin returns value between [-pi/2, pi/2]
e3 = math.asin(pos_sin_theta)
# decide whether the actual positive theta is between [pi/2, pi[ using the value of cos(theta)
# which happens to be the matrix element self.zz (and is thus signed).
if self.zz < 0:
e3 = math.pi - e3
# e1 = math.atan2( -UU(1,3), UU(2,3) ) # between -Pi and Pi -> [-180,180]
# e2 = math.atan2( UU(3,1), UU(3,2) ) # between -Pi and Pi -> [-180, 180]
# this is atan( sin_phi * c, cos_phi * c ) as opposed to Alex's atan(
# -sin_phi * c, -cos_phi * c ).
e1 = math.atan2(self.zx, -self.zy)
e2 = math.atan2(self.xz, self.yz)
return Vec(e1, e2, e3)
def from_euler_angles(self, euler):
phi = euler.x()
psi = euler.y()
theta = euler.z()
cos_phi = math.cos(phi)
sin_phi = math.sin(phi)
cos_psi = math.cos(psi)
sin_psi = math.sin(psi)
cos_theta = math.cos(theta)
sin_theta = math.sin(theta)
self.xx = cos_psi * cos_phi - cos_theta * sin_phi * sin_psi
self.xy = cos_psi * sin_phi + cos_theta * cos_phi * sin_psi
self.xz = sin_psi * sin_theta
self.yx = -sin_psi * cos_phi - cos_theta * sin_phi * cos_psi
self.yy = -sin_psi * sin_phi + cos_theta * cos_phi * cos_psi
self.yz = cos_psi * sin_theta
self.zx = sin_theta * sin_phi
self.zy = -sin_theta * cos_phi
self.zz = cos_theta
return self
Imat = Mat(1, 0, 0, 0, 1, 0, 0, 0, 1)
def projection_matrix(v):
m = Mat(v.x * v.x, v.x * v.y, v.x * v.z, v.y * v.x, v.y *
v.y, v.y * v.z, v.z * v.x, v.z * v.y, v.z * v.z)
return m / v.dot(v)
def proj(u, v):
"""
>>> u = Vec(1,0,0); v = Vec(1,1,1)
>>> proj(u,v)
Vec( 1.000000, 0.000000, 0.000000 )
"""
return projection_matrix(u) * v
def projperp(u, v):
"""
>>> u = Vec(1,0,0); v = Vec(1,1,1)
>>> projperp(u,v)
Vec( 0.000000, 1.000000, 1.000000 )
"""
return v - proj(u, v)
def rotation_matrix(axis, angle):
n = axis.normalized()
sin_theta = sin(angle)
cos_theta = cos(angle)
R = projection_matrix(n)
R *= 1.0 - cos_theta
R.xx += cos_theta
R.xy -= sin_theta * n.z
R.xz += sin_theta * n.y
R.yx += sin_theta * n.z
R.yy += cos_theta
R.yz -= sin_theta * n.x
R.zx -= sin_theta * n.y
R.zy += sin_theta * n.x
R.zz += cos_theta
return R
def rotation_matrix_degrees(axis, angle):
""" get a rotation matrix
>>> rx180 = rotation_matrix_degrees(Vec(1,0,0),180.0)
>>> rx90 = rotation_matrix_degrees(Vec(1,0,0),90.0)
>>> print rx90*rx90 == rx180
True
>>> r = rotation_matrix_degrees(Vec(1,0,0),45.0)
>>> print r
Mat[ (1.000000,0.000000,0.000000), (0.000000,0.707107,-0.707107), (0.000000,0.707107,0.707107) ]
>>> assert r*r == rx90
>>> assert r*r*r*r == rx180
>>> assert r*r*r*r*r*r*r*r == Imat
>>> assert ~r == r.transposed()
>>> ang = uniform(0,1)*360.0-180.0
>>> v = randvec()
>>> axs = randnorm()
>>> while(abs(v.dot(axs))>0.9): axs = randnorm()
>>> u = rotation_matrix_degrees(projperp(v,axs),ang)*v
>>> assert abs(u.angle_degrees(v)-abs(ang)) < SQRTEPS
>>> test_rotation_mat()
test_rotation_mat PASS
"""
return rotation_matrix(axis, radians(angle))
def test_rotation_mat():
import random
for i in range(100):
a0 = randnorm()
t0 = uniform(-pi, pi)
a, t = rotation_matrix(a0, t0).rotation_axis()
if t0 < 0.01:
continue
if abs(t - pi) < EPS:
if (abs(a.x - a0.x) < 0.001 and abs(a.y - a0.y) < 0.001 and abs(a.z - a0.z) < 0.001) or \
(abs(a.x + a0.x) < 0.001 and abs(a.y + a0.y) < 0.001 and abs(a.z + a0.z) < 0.001):
continue
else:
print a0
print a
return False
if not abs(t - t0) < EPS or not (a.normalized() - a0.normalized()).length() < EPS:
print a0.normalized(), t0
print a.normalized(), t
print "FAIL"
return
print "test_rotation_mat PASS"
def randrot(n=None):
if n is None:
return rotation_matrix_degrees(randnorm(), uniform(0, 1) * 360)
return (rotation_matrix_degrees(randnorm(), uniform(0, 1) * 360) for i in range(n))
class Xform(object):
"""Coordinate frame like rosetta Xform, behaves also as a rosetta Stub
>>> x = Xform(R=Imat,t=Uz)
>>> print x
Xform( Mat[ (1.000000,0.000000,0.000000), (0.000000,1.000000,0.000000), (0.000000,0.000000,1.000000) ], (0.000000,0.000000,1.000000) )
>>> assert (x*x) == Xform(R=Imat,t=2*Uz)
>>> x = Xform(R=rotation_matrix_degrees(Vec(1,0,0),90.0),t=Vec(0,0,0))
>>> print x
Xform( Mat[ (1.000000,0.000000,0.000000), (0.000000,0.000000,-1.000000), (0.000000,1.000000,0.000000) ], (0.000000,0.000000,0.000000) )
>>> assert x*x*x*x == Ixform
>>> x.t = Ux
>>> assert x*x*x*x == Xform(R=Imat,t=4*Ux)
>>> x.t = Uz
>>> print x
Xform( Mat[ (1.000000,0.000000,0.000000), (0.000000,0.000000,-1.000000), (0.000000,1.000000,0.000000) ], (0.000000,0.000000,1.000000) )
>>> assert x == Xform(R=rotation_matrix_degrees(Ux, 90.0),t=Vec(0, 0,1))
>>> assert x*x == Xform(R=rotation_matrix_degrees(Ux,180.0),t=Vec(0,-1,1))
>>> assert x*x*x == Xform(R=rotation_matrix_degrees(Ux,270.0),t=Vec(0,-1,0))
>>> assert x*x*x*x == Xform(R=rotation_matrix_degrees(Ux, 0.0),t=Vec(0, 0,0))
>>> assert x*x*x*x*x == Xform(R=rotation_matrix_degrees(Ux, 90.0),t=Vec(0, 0,1))
>>> assert x*x*x*x*x*x == Xform(R=rotation_matrix_degrees(Ux,180.0),t=Vec(0,-1,1))
>>> assert x*x*x*x*x*x*x == Xform(R=rotation_matrix_degrees(Ux,270.0),t=Vec(0,-1,0))
>>> assert x*x*x*x*x*x*x*x == Xform(R=rotation_matrix_degrees(Ux, 0.0),t=Vec(0, 0,0))
>>> x = Xform(rotation_matrix_degrees(Vec(1,2,3),123),Vec(5,7,9))
>>> assert ~x * x == Ixform
>>> assert x * ~x == Ixform
Frames / RTs are interchangable:
>>> fr = Xform(rotation_matrix_degrees(Vec(1,2,3), 65.64),t=Vec(3,2,1))
>>> to = Xform(rotation_matrix_degrees(Vec(7,5,3),105.44),t=Vec(10,9,8))
>>> x = to/fr
>>> assert to/Ixform == to
>>> assert Ixform/fr == ~fr
>>> assert (to * ~fr) * fr == to
>>> assert x * fr == to
>>> a1 = randnorm()
>>> b1 = randnorm()
>>> ang = uniform(0,1)*360.0-180.0
>>> a2 = rotation_matrix_degrees(a1.cross(randnorm()),ang) * a1
>>> b2 = rotation_matrix_degrees(b1.cross(randnorm()),ang) * b1
>>> assert abs(angle(a1,a2) - angle(b1,b2)) < EPS
>>> xa = Xform().from_two_vecs(a1,a2)
>>> xb = Xform().from_two_vecs(b1,b2)
>>> assert xa.tolocal(a1) == xb.tolocal(b1)
>>> assert xa.tolocal(a2) == xb.tolocal(b2)
>>> assert ~xa*a1 == ~xb*b1
>>> assert ~xa*a2 == ~xb*b2
>>> assert xb/xa*a1 == b1
>>> assert xb/xa*a2 == b2
add/sub with Vecs:
>>> X = randxform()
>>> u,v = randvec(2)
>>> assert isxform(u+X) and isxform(X+u) and isxform(u-X) and isxform(X-u)
>>> assert X*v+u == (u+X)*v
>>> assert X*(v+u) == (X+u)*v
>>> assert Xform(u)*X*v == (u+X)*v
>>> assert X*Xform(u)*v == (X+u)*v
>>> assert X*v-u == (u-X)*v
>>> assert X*(v-u) == (X-u)*v
mul,div with Mats:
>>> R = randrot()
>>> assert isxform(R*X) and isxform(X*R)
>>> assert R*X*u == (R*X)*u == R*(X*u)
>>> assert X*R*u == (X*R)*u == X*(R*u)
>>> assert Xform(R)*X*u == Xform(R)*(X*u)
>>> assert X*Xform(R)*u == X*(Xform(R,V0)*u)
>>> assert X/X*v == v
mul/div Xforms:
>>> Y = randxform()
>>> assert isxform(X/Y) and isxform(X*Y)
>>> assert X/Y*v == X*~Y*v
these don't work yet:
>>> axis,ang,cen = randnorm(),uniform(-pi,pi),randvec() #doctest: +SKIP
>>> X = rotation_around(axis,ang,cen) #doctest: +SKIP
>>> axis2,ang2,cen2 = X.rotation_center() #doctest: +SKIP
>>> assert abs( abs(ang) - abs(ang2) ) < EPS #doctest: +SKIP
>>> assert axis == axis2 * copysign(1,ang*ang2) #doctest: +SKIP
>>> print cen #doctest: +SKIP
>>> print cen2 #doctest: +SKIP
>>> x = Xform( Mat( Vec( 0.816587, -0.306018, 0.489427 ), Vec( 0.245040, 0.951487, 0.186086 ), Vec( -0.522629, -0.032026, 0.851959 ) ), Vec( 1.689794, 1.535762, -0.964428 ) )
>>> assert repr(x) == "Xform( Mat( Vec( 0.816587, -0.306018, 0.489427 ), Vec( 0.245040, 0.951487, 0.186086 ), Vec( -0.522629, -0.032026, 0.851959 ) ), Vec( 1.689794, 1.535762, -0.964428 ) )"
"""
def __Xform__(self):
return True
def __init__(self, R=None, t=None):
super(Xform, self).__init__()
if isvec(R) and t is None:
R, t = Imat, R
self.R = R if R else Imat
self.t = t if t else V0
assert ismat(self.R) and isvec(self.t)
# def rotation_center(X):
# axis,ang = X.rotation_axis()
# cen = -(X.R-Imat).transposed()*X.t
# return axis,ang,cen
def from_four_points(s, cen, a, b, c):
s.t = cen
e1 = (a - b).normalized()
e3 = e1.cross(c - b).normalized()
e2 = e1.cross(e3).normalized()
# print "from_four_points"
# print e1
# print e2
# print e3
s.R = Mat(e1.x, e2.x, e3.x, e1.y, e2.y, e3.y, e1.z, e2.z, e3.z)
return s
def from_two_vecs(s, a, b):
e1 = a.normalized()
e2 = projperp(a, b).normalized()
e3 = e1.cross(e2)
return Xform(Mat(e1.x, e2.x, e3.x, e1.y, e2.y, e3.y, e1.z, e2.z, e3.z), V0)
def tolocal(s, x):
return s.R.transposed() * (x - s.t)
def toglobal(s, x):
return (s.R * x) + s.t
def __invert__(self):
R = ~self.R
t = R * -self.t
return Xform(R, t)
def inverse(self):
return ~self
def __mul__(X, o):
if isvec(o):
return X.R * o + X.t
elif isxform(o):
return Xform(X.R * o.R, X.R * (o.t) + X.t)
elif ismat(o):
return Xform(X.R * o, X.t)
elif islist(o):
return [X * x for x in o]
elif istuple(o):
return tuple([X * x for x in o])
elif isiter(o):
return (X * x for x in o)
else:
return o.__rmul__(X)
def __rmul__(X, o):
if ismat(o):
return Xform(o * X.R, o * X.t)
raise NotImplementedError
def __div__(X, o):
if isxform(o):
return X * ~o
return o.__rdiv__(X)
def __add__(X, v):
if isvec(v):
return Xform(X.R, X.t + X.R * v)
return v.__radd__(X)
def __radd__(X, v):
if isvec(v):
return Xform(X.R, X.t + v)
raise NotImplementedError
def __sub__(X, v):
if isvec(v):
return Xform(X.R, X.t - X.R * v)
return v.__rsub__(X)
def __rsub__(X, v):
if isvec(v):
return Xform(X.R, X.t - v)
raise NotImplementedError
def __str__(self):
return "Xform( %s, %s )" % (str(self.R), str(self.t))
def __repr__(self):
return "Xform( %s, %s )" % (repr(self.R), repr(self.t))
def __eq__(X, Y):
assert isxform(Y)
return X.R == Y.R and X.t == Y.t
def __neq__(self, other):
return not self == other
def rotation_axis(X):
return X.R.rotation_axis()
def rotation_axis_center(X):
axis, ang = X.R.rotation_axis()
# these points lie on a circle who's center is the center of rotation
p0 = Vec(0, 0, 0)
p1 = Vec(X * p0)
p2 = Vec(X * p1)
p1 -= axis * (p1 - p0).dot(axis)
p2 -= axis * (p2 - p1).dot(axis)
assert(abs((p1 - p0).dot(axis)) < 0.000001)
assert(abs((p2 - p1).dot(axis)) < 0.000001)
d = p1.length()
if(d < 0.000001):
return axis, ang, Vec(0, 0, 0)
if abs(2.0 * math.tan(ang / 2.0)) < 0.001:
return axis, ang, None
l = d / (2.0 * math.tan(ang / 2.0))
tocen = p1.normalized().cross(axis) * l
assert(abs(tocen.length() - l) < 0.0001)
# correct direction based on curvature
if(tocen.dot(p2 - p1) < 0.0):
tocen = -tocen
cen = (p0 + p1) / 2.0 + tocen
return axis, ang, cen
def pretty(self):
a, r = self.rotation_axis()
if self.t.length() > EPS:
return "Xform( axis=%s, ang=%f, dir=%s, dis=%f )" % (str(a), degrees(r), str(self.t.normalized()), self.t.length())
else:
return "Xform( axis=%s, ang=%f, dir=%s, dis=%f )" % (str(a), degrees(r), str(V0), 0)
Ixform = Xform(Imat, V0)
def read_tokens(f):
for line in f:
for token in line.split():
yield token
def read_xforms(fname, N=9e9, start=0):
xforms = list()
with open(fname) as fin:
for i in range(start):
fin.readline()
while True:
x = list(chain(*(fin.readline().split() for i in range(4))))
if len(xforms) is N or not x:
break
x = map(float, x)
xforms.append(Xform(Mat(*x[:9]), Vec(*x[9:])))
return xforms
def stub(cen=None, a=None, b=None, c=None):
if cen is None:
cen = a
if c is None:
cen, a, b, c = cen, cen, a, b
# print cen
# print a
# print b
# print c
return Xform().from_four_points(cen, a, b, c)
def randxform(n=None):
if n is None:
return Xform(randrot(), randvec())
return (Xform(randrot(), randvec()) for i in range(n))
def rotation_around(axs, ang, cen=None):
"""
>>> x = rotation_around(Ux,1,Uy)
>>> x * Uy
Vec( 0.000000, 1.000000, 0.000000 )
"""
if not cen:
cen = Vec(0, 0, 0)
R = rotation_matrix(axs, ang)
return Xform(R, R * -cen + cen)
def rotation_around_degrees(
axs, ang, cen=None): return rotation_around(axs, radians(ang), cen)
RAD = rotation_around_degrees
def test():
test_rotation_mat()
def dihedral(p1, p2, p3, p4):
"""
>>> dihedral_degrees(Ux,Uy,V0,Uz)
90.0
>>> dihedral_degrees(Ux,V0,Uy,Uz)
-90.0
"""
a = (p2 - p1).normalized()
b = (p3 - p2).normalized()
c = (p4 - p3).normalized()
x = -a.dot(c) + a.dot(b) * b.dot(c)
y = a.dot(b.cross(c))
return atan2(y, x)