forked from realthunder/FreeCAD_assembly3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsys_sympy.py
1343 lines (1095 loc) · 40.4 KB
/
sys_sympy.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
from collections import namedtuple
import pprint
from .deps import with_metaclass
from .proxy import ProxyType, PropertyInfo
from .system import System, SystemBase, SystemExtension
from .utils import syslogger as logger, objName
import sympy as sp
import sympy.vector as spv
import scipy.optimize as sopt
import numpy as np
class _AlgoType(ProxyType):
'SciPy minimize algorithm meta class'
_typeID = '_AlgorithmType'
_typeEnum = 'AlgorithmType'
_propGroup = 'SolverAlgorithm'
_proxyName = '_algo'
@classmethod
def setDefaultTypeID(mcs,obj,name=None):
if not name:
name = _AlgoPowell.getName()
super(_AlgoType,mcs).setDefaultTypeID(obj,name)
def _makeProp(name,doc='',tp='App::PropertyFloat',group=None):
if not group:
group = _AlgoType._propGroup
info = PropertyInfo(_AlgoType,name,tp,doc,duplicate=True,group=group)
return info.Key
_makeProp('Tolerance','','App::PropertyPrecision','Solver')
class _AlgoBase(with_metaclass(_AlgoType, object)):
_id = -2
_common_options = [_makeProp('maxiter',
'Maximum number of function evaluations','App::PropertyInteger')]
_options = []
NeedHessian = False
NeedJacobian = True
def __init__(self,obj):
self.Object = obj
@classmethod
def getName(cls):
return cls.__name__[5:].replace('_','-')
@property
def Options(self):
ret = {}
for key in self._common_options + self._options:
name = _AlgoType.getPropertyInfo(key).Name
v = getattr(self.Object,name,None)
if v:
ret[name] = v
return ret
@property
def Tolerance(self):
tol = self.Object.Tolerance
return tol if tol else None
@classmethod
def getPropertyInfoList(cls):
return ['Tolerance'] + cls._common_options + cls._options
class _AlgoNoJacobian(_AlgoBase):
NeedJacobian = False
class _AlgoNelder_Mead(_AlgoNoJacobian):
_id = 0
_options = [
_makeProp('maxfev',
'Maximum allowed number of function evaluations. Both maxiter and\n'
'maxfev Will default to N*200, where N is the number of variables.\n'
'If neither maxiter or maxfev is set. If both maxiter and maxfev \n'
'are set, minimization will stop at the first reached.',
'App::PropertyInteger'),
_makeProp('xatol',
'Absolute error in xopt between iterations that is acceptable for\n'
'convergence.'),
_makeProp('fatol',
'Absolute error in func(xopt) between iterations that is \n'
'acceptable for convergence.'),
]
class _AlgoPowell(_AlgoNelder_Mead):
_id = 1
class _AlgoCG(_AlgoBase):
_id = 2
_options = [
_makeProp('norm','Order of norm (Inf is max, -Inf is min).'),
_makeProp('gtol','Gradient norm must be less than gtol before '
'successful termination'),
]
class _AlgoBFGS(_AlgoCG):
_id = 3
class _AlgoNeedHessian(_AlgoBase):
NeedHessian = True
class _AlgoNewton_CG(_AlgoNeedHessian):
_id = 4
_options = [
_makeProp('xtol','Average relative error in solution xopt acceptable '
'for convergence.'),
]
class _AlgoL_BFGS_B(_AlgoBase):
_id = 5
_options = [
_makeProp('maxcor',
'The maximum number of variable metric corrections used to define\n'
'the limited memory matrix. (The limited memory BFGS method does\n'
'not store the full hessian but uses this many terms in an \n'
'approximation to it.)','App::PropertyInteger'),
_makeProp('factr',
'The iteration stops when \n'
' (f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr * eps,\n'
'where eps is the machine precision, which is automatically \n'
'generated by the code. Typical values for factr are: 1e12 for\n'
'low accuracy; 1e7 for moderate accuracy; 10.0 for extremely high\n'
'accuracy.'),
_makeProp('ftol','The iteration stops when (f^k - f^{k+1})/max{|f^k|,'
'|f^{k+1}|,1} <= ftol.'),
_makeProp('gtol','The iteration will stop when max{|proj g_i | i = 1, '
'..., n} <= gtol\nwhere pg_i is the i-th component of the projected'
'gradient.'),
_makeProp('maxfun','Maximum number of function evaluations.',
'App::PropertyInteger'),
_makeProp('maxls','Maximum number of line search steps (per iteration).'
'Default is 20.'),
]
class _AlgoTNC(_AlgoBase):
_id = 6
_options = [
_makeProp('offset',
'Value to subtract from each variable. If None, the offsets are \n'
'(up+low)/2 for interval bounded variables and x for the others.'),
_makeProp('maxCGit',
'Maximum number of hessian*vector evaluations per main iteration.\n'
'If maxCGit == 0, the direction chosen is -gradient if maxCGit<0,\n'
'maxCGit is set to max(1,min(50,n/2)). Defaults to -1.'),
_makeProp('eta','Severity of the line search. if < 0 or > 1, set to'
'0.25. Defaults to -1.'),
_makeProp('stepmx',
'Maximum step for the line search. May be increased during call.\n'
'If too small, it will be set to 10.0. Defaults to 0.'),
_makeProp('accuracy',
'Relative precision for finite difference calculations. If <=\n'
'machine_precision, set to sqrt(machine_precision). Defaults to 0.'),
_makeProp('minifev','Minimum function value estimate. Defaults to 0.',
'App::PropertyInteger'),
_makeProp('ftol',
'Precision goal for the value of f in the stopping criterion.\n'
'If ftol < 0.0, ftol is set to 0.0 defaults to -1.'),
_makeProp('xtol',
'Precision goal for the value of x in the stopping criterion\n'
'(after applying x scaling factors). If xtol < 0.0, xtol is set\n'
'to sqrt(machine_precision). Defaults to -1.'),
_makeProp('gtol',
'Precision goal for the value of the projected gradient in the\n'
'stopping criterion (after applying x scaling factors). If \n'
'gtol < 0.0, gtol is set to 1e-2 * sqrt(accuracy). Setting it to\n'
'0.0 is not recommended. Defaults to -1.'),
_makeProp('rescale',
'Scaling factor (in log10) used to trigger f value rescaling. If\n'
'0, rescale at each iteration. If a large value, never rescale.\n'
'If < 0, rescale is set to 1.3.')
]
class _AlgoCOBYLA(_AlgoNoJacobian):
_id = 7
_options = [
_makeProp('rhobeg','Reasonable initial changes to the variables'),
_makeProp('tol',
'Final accuracy in the optimization (not precisely guaranteed).\n'
'This is a lower bound on the size of the trust region'),
]
class _AlgoSLSQP(_AlgoBase):
_id = 8
_options = [
_makeProp('ftol',
'Precision goal for the value of f in the stopping criterion'),
]
class _Algodogleg(_AlgoNeedHessian):
_id = 9
_options = [
_makeProp('initial_trust_radius','Initial trust-region radius'),
_makeProp('max_trust_radius',
'Maximum value of the trust-region radius. No steps that are\n'
'longer than this value will be proposed'),
_makeProp('eta',
'Trust region related acceptance stringency for proposed steps'),
_makeProp('gtol','Gradient norm must be less than gtol before '
'successful termination'),
]
class _Algotrust_ncg(_Algodogleg):
_id = 10
class SystemSymPy(with_metaclass(System, SystemBase)):
_id = 2
def __init__(self,obj):
super(SystemSymPy,self).__init__(obj)
_AlgoType.attach(obj)
def onDetach(self,obj):
_AlgoType.detach(obj,True)
@classmethod
def getName(cls):
return 'SymPy + SciPy'
def isConstraintSupported(self,cstrName):
return _MetaType.isConstraintSupported(cstrName) or \
getattr(_SystemSymPy,'add'+cstrName)
def getSystem(self,obj):
return _SystemSymPy(self,_AlgoType.getProxy(obj))
def isDisabled(self,_obj):
return False
def onChanged(self,obj,prop):
_AlgoType.onChanged(obj,prop)
super(SystemSymPy,self).onChanged(obj,prop)
class _Base(object):
def __init__(self,name,g):
self._symobj = None
self.group = g
self.solvingGroup = None
self._name = name
def reset(self,g):
self.solvingGroup = g
self._symobj = None
@property
def Name(self):
if self._name:
return '{}<{}>'.format(self._name,self.__class__.__name__[1:])
return '<unknown>'
@property
def SymObj(self):
if self._symobj is None:
self._symobj = self.getSymObj()
return self._symobj
@property
def SymStr(self):
sym = self.SymObj
if isinstance(sym,spv.Vector):
sym = spv.express(sym,_gref)
if sym:
return '{} = {}'.format(self._name, sym)
def getSymObj(self):
return None
def __repr__(self):
return '"{}"'.format(self.__class__.__name__[1:])
class _Param(_Base):
def __init__(self,name,v,g):
super(_Param,self).__init__(name,g)
self.val = v
self._sym = sp.Dummy(self._name,real=True)
self._symobj = self._sym
self._val = sp.Float(self.val)
def reset(self,g):
if self.group == g:
self._symobj = self._sym
else:
self._symobj = self._val
@property
def Name(self):
return '_' + self._name
@property
def _repr(self):
return self.val
def __repr__(self):
return '_{}:{}'.format(self._name,self._val)
class _MetaType(type):
_types = []
_typeMap = {}
def __init__(cls, name, bases, attrs):
super(_MetaType,cls).__init__(name,bases,attrs)
if len(cls._args):
logger.trace('registing sympy {}', cls.__name__)
mcs = cls.__class__
mcs._types.append(cls)
mcs._typeMap[cls.__name__[1:]] = cls
@classmethod
def isConstraintSupported(mcs,name):
cls = mcs._typeMap.get(name,None)
if cls:
return issubclass(cls,_Constraint)
class _MetaBase(with_metaclass(_MetaType, _Base)):
_args = ()
_opts = ()
_vargs = ()
def __init__(self,system,args,kargs):
cls = self.__class__
n = len(cls._args)+len(cls._opts)
max_args = n
if kargs is None:
kargs = {}
if 'group' in kargs:
g = kargs['group']
kargs.pop('group')
elif len(args) > n:
g = args[n]
max_args = n+1
else:
g = 0
if not g:
g = system.GroupHandle
super(_MetaBase,self).__init__(system.Tag,g)
if len(args) < len(cls._args):
raise ValueError('not enough parameters when making ' + str(self))
if len(args) > max_args:
raise ValueError('too many parameters when making ' + str(self))
for i,p in enumerate(args):
if i < len(cls._args):
setattr(self,cls._args[i],p)
continue
i -= len(cls._args)
if isinstance(cls._opts[i],tuple):
setattr(self,cls._opts[i][0],p)
else:
setattr(self,cls._opts[i],p)
for k in self._opts:
if isinstance(k,tuple):
k,p = k
else:
p = 0
if k in kargs:
p = kargs[k]
if hasattr(self,k):
raise KeyError('duplicate key "{}" while making '
'{}'.format(k,self))
kargs.pop(k)
setattr(self,k,p)
if len(kargs):
for k in kargs:
raise KeyError('unknown key "{}" when making {}'.format(
k,self))
if cls._vargs:
nameTagSave = system.NameTag
if nameTagSave:
nameTag = nameTagSave + '.' + cls.__name__[1:] + '.'
else:
nameTag = cls.__name__[1:] + '.'
for k in cls._vargs:
v = getattr(self,k)
system.NameTag = nameTag+k
setattr(self,k,system.addParamV(v,g))
system.NameTag = nameTagSave
@property
def _repr(self):
v = {}
cls = self.__class__
for k in cls._args:
attr = getattr(self,k)
v[k] = getattr(attr,'_repr',attr)
for k in cls._opts:
if isinstance(k,(tuple,list)):
attr = getattr(self,k[0])
if attr != k[1]:
v[k[0]] = attr
continue
attr = getattr(self,k)
if attr:
v[k] = attr
return v
def __repr__(self):
return '\n{}:{{\n {}\n'.format(self.Name,
pprint.pformat(self._repr,indent=1,width=1)[1:])
def getEqWithParams(self,_args):
return self.getEq()
def getEq(self):
return []
if hasattr(spv,'CoordSys3D'):
CoordSystem = spv.CoordSys3D
CoordSystemName = 'CoordSys3D'
else:
CoordSystem = spv.CoordSysCartesian
CoordSystemName = 'CoordSysCartesian'
_gref = CoordSystem('gref')
def _makeVector(v,ref=None):
if not ref:
ref = _gref
if isinstance(v, spv.Vector):
if isinstance(v, spv.VectorZero):
return v
x,y,z = _vectorComponent(v)
return x*ref.i + y*ref.j + z*ref.k
x,y,z = v
return x.SymObj * ref.i + y.SymObj * ref.j + z.SymObj * ref.k
def _project(wrkpln,*args):
if not wrkpln:
return [ e.Vector for e in args ]
r = wrkpln.CoordSys
return [ e.Vector.dot(r.i)+e.Vector.dot(r.j) for e in args ]
def _distance(wrkpln,p1,p2):
e1,e2 = _project(wrkpln,p1,p2)
return (e1-e2).magnitude()
def _pointPlaneDistance(pt,pln):
e = _project(pln,[pt])
return (e[0]-pln.origin.Vector).magnitude()
def _pointLineDistance(wrkpln,pt,line):
ep,ea,eb = _project(wrkpln,pt,line.p1,line.p2)
eab = ea - eb
return eab.cross(ea-ep).magnitude()/eab.magnitude()
def _directionConsine(wrkpln,l1,l2,supplement=False):
v1,v2 = _project(wrkpln,l1,l2)
if supplement:
v1 = v1 * -1.0
return v1.dot(v2)/(v1.magnitude()*v2.magnitude())
_x = 'i'
_y = 'j'
_z = 'k'
def _vectorComponent(v,*args,**kargs):
if not args:
args = (_x,_y,_z)
if isinstance(v,spv.VectorZero):
return [sp.S.Zero]*len(args)
v = spv.express(v,_gref)
ret = [v.components.get(getattr(_gref,a),sp.S.Zero) for a in args]
subs = kargs.get('subs',None)
if not subs:
return ret
return [ c.subs(subs) for c in ret ]
def _vectorsParallel(args,a,b):
a = a.Vector
b = b.Vector
r = a.cross(b)
# _ = args
# return r.magnitude()
#
# SolveSpace does it like below instead of above. Not sure why, but tests
# show the below equations have better chance to be solved by various
# algorithms
#
rx,ry,rz = _vectorComponent(r)
x,y,z = [ abs(c) for c in _vectorComponent(a,subs=args)]
if x > y and x > z:
return [ry, rz]
elif y > z:
return [rz, rx]
else:
return [rx, ry]
def _vectorsEqual(projected,v1,v2):
if projected:
x1,y1 = _vectorComponent(v1,_x,_y)
x2,y2 = _vectorComponent(v2,_x,_y)
return (x1-x2,y1-y2)
# return (v1-v2).magnitude()
#
# SolveSpace does it like below instead of above. See comments in
# _vectorsParallel()
#
x1,y1,z1 = _vectorComponent(v1)
x2,y2,z2 = _vectorComponent(v2)
return (x1-x2,y1-y2,z1-z2)
class _Entity(_MetaBase):
@classmethod
def make(cls,system):
return lambda *args,**kargs :\
system.addEntity(cls(system,args,kargs))
@property
def CoordSys(self):
return _gref
class _Vector(_Entity):
Vector = _Entity.SymObj
@property
def CoordSys(self):
return self.Vector.system
class _Point(_Vector):
pass
class _Point2d(_Point):
_args = ('wrkpln', 'u', 'v')
def getSymObj(self):
r = self.wrkpln.CoordSys
return self.u.SymObj * r.i + self.v.SymObj * r.j
class _Point2dV(_Point2d):
_vargs = ('u','v')
class _Point3d(_Point):
_args = ('x','y','z')
def getSymObj(self):
return _makeVector([self.x,self.y,self.z])
class _Point3dV(_Point3d):
_vargs = _Point3d._args
class _Normal(_Vector):
@property
def Vector(self):
return self.SymObj.k
class _Normal3d(_Normal):
_args = ('qw','qx','qy','qz')
@property
def Q(self):
return self.qw.SymObj,self.qx.SymObj,self.qy.SymObj,self.qz.SymObj
def getSymObj(self):
name = self._name if self._name else 'R'
return _gref.orient_new_quaternion(name,*self.Q)
def getEq(self):
# make sure the quaternion are normalized
return sp.Matrix(self.Q).norm() - 1.0
@property
def SymStr(self):
return '{} = gref.orient_new_quaternion("{}",{},{},{},{})'.format(
self._name, self._name, self.qw.SymObj,
self.qx.SymObj,self.qy.SymObj,self.qz.SymObj)
class _Normal3dV(_Normal3d):
_vargs = _Normal3d._args
class _Normal2d(_Normal):
_args = ('wrkpln',)
@property
def Q(self):
return self.wrkpln.normal.Q
def getSymObj(self):
return self.wrkpln.normal.SymObj
class _Distance(_Entity):
_args = ('d',)
def getSymObj(self):
return sp.Float(self.d)
class _DistanceV(_Distance):
_vargs = _Distance._args
class _LineSegment(_Vector):
_args = ('p1','p2')
def getSymObj(self):
return self.p1.Vector - self.p2.Vector
# class _Cubic(_Entity):
# _args = ('wrkpln', 'p1', 'p2', 'p3', 'p4')
class _ArcOfCircle(_Entity):
_args = ('wrkpln', 'center', 'start', 'end')
@property
def CoordSys(self):
return self.wrkpln.SymObj
def getSymObj(self):
return _project(self.wrkpln,self.center,self.start,self.end)
@property
def Center(self):
return self.SymObj[0]
@property
def Start(self):
return self.SymObj[1]
@property
def End(self):
return self.SymObj[2]
@property
def Radius(self):
return (self.Center-self.Start).magnitude()
def getEq(self):
return self.Radius - (self.Center-self.End).magnitude()
class _Circle(_Entity):
_args = ('center', 'normal', 'radius')
@property
def Radius(self):
return self.radius.SymObj
@property
def Center(self):
return self.SymObj
def getSymObj(self):
return self.center.Vector
@property
def CoodSys(self):
return self.normal.SymObj
class _CircleV(_Circle):
_vargs = _Circle._args
class _Workplane(_Entity):
_args = ('origin', 'normal')
def getSymObj(self):
name = self._name if self._name else 'W'
return self.normal.SymObj.locate_new(name,self.origin.Vector)
@property
def SymStr(self):
return '{} = {}.locate_new("{}",{})'.format(self._name,
self.normal._name, self._name, self.origin.Vector)
@property
def CoordSys(self):
return self.SymObj
class _Translate(_Vector):
_args = ('src', 'dx', 'dy', 'dz')
# _opts = (('scale',1.0), 'timesApplied')
@property
def Vector(self):
e = self.SymObj
if isinstance(e,spv.Vector):
return e
else:
return e.k
def getSymObj(self):
e = self.src.SymObj
if isinstance(e,spv.Vector):
return e+_makeVector([self.dx,self.dy,self.dz])
elif isinstance(e,CoordSystem):
# This means src is a normal, and we don't translate normal in order
# to be compatibable with solvespace
logger.warn('{} translating normal has no effect',self.Name)
return e
else:
raise ValueError('unsupported transformation {} of '
'{} with type {}'.format(self.Name,self.src,e))
class _Transform(_Translate):
_args = ('src', 'dx', 'dy', 'dz', 'qw', 'qx', 'qy', 'qz')
_opts = (('asAxisAngle',False),
# no support for scal and timesApplied yet
# ('scale',1.0),'timesApplied'
)
@property
def Offset(self):
return _makeVector([self.dx,self.dy,self.dz])
@property
def Q(self):
return self.qw.SymObj,self.qx.SymObj,self.qy.SymObj,self.qz.SymObj
@property
def Axis(self):
return _makeVector([self.qx,self.qy,self.qz])
@property
def Angle(self):
return self.qw.SymObj*sp.pi/180.0
@property
def Orienter(self):
if self.asAxisAngle:
return spv.AxisOrienter(self.Angle, self.Axis)
else:
return spv.QuaternionOrienter(*self.Q)
def getSymObj(self):
e = self.src.SymObj
if isinstance(e,spv.Vector):
if isinstance(e,spv.VectorZero):
return self.Offset
ref = _gref.orient_new(self._name+'_r',self.Orienter)
return _makeVector(e,ref) + self.Offset
# TODO: probably should do this to support cascaded transform, e.g. a
# transformed normal of another transformed normal. But we don't
# currently have that in the constraint system.
#
# if isinstance(e,CoordSystem):
# mat = self.Orienter.rotation_matrix(_gref)*\
# e.rotation_matrix(_gref)
# return CoordSystem(self.name_,rotation_matrix=mat,parent=_gref)
if isinstance(self.src, _Normal):
ref = _gref.orient_new(self._name+'_r',self.Orienter)
return ref.orient_new_quaternion(self._name,*self.src.Q)
raise ValueError('unknown transformation {} of '
'{} with type {}'.format(self.Name,self.src,e))
@property
def SymStr(self):
if self.asAxisAngle:
txt='{}_r=gref.orient_new_axis("{}_r",{},{})'.format(
self._name,self._name,self.Angle,self.Axis)
else:
txt='{}_r=gref.orient_new_quaternion("{}_r",{},{},{},{})'.format(
self._name,self._name,*self.Q)
if isinstance(self.SymObj,spv.Vector):
return '{}\n{}={}'.format(txt,self._name,self.SymObj)
return '{}\n{}={}_r.orient_new_quaternion("{}",{},{},{},{})'.format(
txt,self._name,self._name,self._name,*self.Q)
class _Constraint(_MetaBase):
@classmethod
def make(cls,system):
return lambda *args,**kargs :\
system.addConstraint(cls(system,args,kargs))
class _ProjectingConstraint(_Constraint):
_opts = ('wrkpln',)
def project(self,*args):
return _project(self.wrkpln,*args)
class _PointsDistance(_ProjectingConstraint):
_args = ('d', 'p1', 'p2',)
def getEq(self):
return _distance(self.wrkpln,self.p1,self.p2) - self.d
class _PointsProjectDistance(_Constraint):
_args = ('d', 'p1', 'p2', 'line')
def getEq(self):
dp = self.p1.Vector - self.p2.Vector
pp = self.line.Vector.normalize()
return dp.dot(pp) - self.d
class _PointsCoincident(_ProjectingConstraint):
_args = ('p1', 'p2',)
def getEq(self):
p1,p2 = self.project(self.p1,self.p2)
return _vectorsEqual(self.wrkpln,p1,p2)
class _PointInPlane(_ProjectingConstraint):
_args = ('pt', 'pln')
def getEq(self):
return _pointPlaneDistance(self.pt,self.pln)
class _PointPlaneDistance(_ProjectingConstraint):
_args = ('d', 'pt', 'pln')
def getEq(self):
return _pointPlaneDistance(self.pt,self.pln) - self.d.SymObj
class _PointOnLine(_ProjectingConstraint):
_args = ('pt', 'line',)
def getEq(self):
return _pointLineDistance(self.wrkpln,self.pt,self.line)
class _PointLineDistance(_ProjectingConstraint):
_args = ('d', 'pt', 'line')
def getEq(self):
d = _pointLineDistance(self.wrkpln,self.pt,self.line)
return d**2 - self.d.SymObj**2
class _EqualLength(_ProjectingConstraint):
_args = ('l1', 'l2',)
@property
def Distance1(self):
return _distance(self.wrkpln,self.l1.p1,self.l1.p2)
@property
def Distance2(self):
return _distance(self.wrkpln,self.l2.p1,self.l2.p2)
def getEq(self):
return self.Distance1 - self.Distance2
class _LengthRatio(_EqualLength):
_args = ('ratio', 'l1', 'l2',)
def getEq(self):
return self.Distance1/self.Distance2 - self.ratio.SymObj
class _LengthDifference(_EqualLength):
_args = ('diff', 'l1', 'l2',)
def getEq(self):
return self.Distance1 - self.Distance2 - self.diff.SymObj
class _EqualLengthPointLineDistance(_EqualLength):
_args = ('pt','l1','l2')
@property
def Distance2(self):
return _pointLineDistance(self.wrkpln,self.pt,self.l2)
def getEq(self):
return self.Distance1**2 - self.Distance2**2
class _EqualPointLineDistance(_EqualLengthPointLineDistance):
_args = ('p1','l1','p2','l2')
@property
def Distance1(self):
return _pointLineDistance(self.wrkpln,self.p1,self.l1)
@property
def Distance2(self):
return _pointLineDistance(self.wrkpln,self.p1,self.l2)
class _EqualAngle(_ProjectingConstraint):
_args = ('supplement', 'l1', 'l2', 'l3', 'l4')
@property
def Angle1(self):
return _directionConsine(self.wrkpln,self.l1,self.l2,self.supplement)
@property
def Angle2(self):
return _directionConsine(self.wrkpln,self.l3,self.l4)
def getEq(self):
return self.Angle1 - self.Angle2
class _EqualLineArcLength(_ProjectingConstraint):
_args = ('line', 'arc')
def getEq(self):
raise NotImplementedError('not implemented')
class _Symmetric(_ProjectingConstraint):
_args = ('p1', 'p2', 'pln')
def getEq(self):
e1,e2 = _project(self.wrkpln,self.p1,self.p2)
m = (e1-e2)*0.5
eq = []
# first equation, mid point of p1 and p2 coincide with pln's origin
eq += _vectorsEqual(0,m,self.pln.origin.Vector)
e1,e2 = _project(self.pln,self.p1,self.p2)
# second equation, p1 and p2 cincide when project to pln
eq += _vectorsEqual(self.pln,e1,e2)
return eq
class _SymmetricHorizontal(_Constraint):
_args = ('p1', 'p2', 'wrkpln')
def getEq(self):
e1,e2 = _project(self.wrkpln,self.p1,self.p2)
x1,y1 = _vectorComponent(e1,_x,_y)
x2,y2 = _vectorComponent(e2,_x,_y)
return [x1+x2,y1-y2]
class _SymmetricVertical(_Constraint):
_args = ('p1', 'p2', 'wrkpln')
def getEq(self):
e1,e2 = _project(self.wrkpln,self.p1,self.p2)
x1,y1 = _vectorComponent(e1,_x,_y)
x2,y2 = _vectorComponent(e2,_x,_y)
return [x1-x2,y1+y2]
class _SymmetricLine(_Constraint):
_args = ('p1', 'p2', 'line', 'wrkpln')
def getEq(self):
e1,e2,le1,le2 = _project(self.wrkpln, self.p1, self.p2,
self.line.p1, self.line.p2)
return (e1-e2).dot(le1-le2)
class _MidPoint(_ProjectingConstraint):
_args = ('pt', 'line')
def getEq(self):
e,le1,le2 = _project(self.wrkpln,self.pt,self.line.p1,self.line.p2)
return _vectorsEqual(self.wrkpln,e,(le1-le2)*0.5)
class _PointsHorizontal(_ProjectingConstraint):
_args = ('p1', 'p2')
def getEq(self):
e1,e2 = _project(self.wrkpln,self.p1,self.p2)
x1, = _vectorComponent(e1,_x)
x2, = _vectorComponent(e2,_x)
return x1-x2
class _PointsVertical(_ProjectingConstraint):
_args = ('p1', 'p2')
def getEq(self):
e1,e2 = _project(self.wrkpln,self.p1,self.p2)
y1, = _vectorComponent(e1,_y)
y2, = _vectorComponent(e2,_y)
return y1-y2
class _LineHorizontal(_ProjectingConstraint):
_args = ('line',)
def getEq(self):
e1,e2 = _project(self.wrkpln,self.line.p1,self.line.p2)
x1, = _vectorComponent(e1,_x)
x2, = _vectorComponent(e2,_x)
return x1-x2
class _LineVertical(_ProjectingConstraint):
_args = ('line',)
def getEq(self):
e1,e2 = _project(self.wrkpln,self.line.p1,self.line.p2)
y1, = _vectorComponent(e1,_y)
y2, = _vectorComponent(e2,_y)
return y1-y2
class _Diameter(_Constraint):
_args = ('d', 'c')
def getEq(self):
return self.c.Radius*2 - self.d.SymObj
class _PointOnCircle(_Constraint):
_args = ('pt', 'circle')
def getEq(self):
# to be camptible with slvs, this actual constraint the point to the
# cylinder
e = _project(self.circle.normal,self.pt)
return self.circle.Radius - (e-self.center.Vector).magnitude()
class _SameOrientation(_Constraint):
_args = ('n1', 'n2')
def getEqWithParams(self,args):
if self.n1.group == self.solvingGroup:
n1,n2 = self.n2,self.n1
else:
n1,n2 = self.n1,self.n2
eqs = _vectorsParallel(args,n1,n2)