-
Notifications
You must be signed in to change notification settings - Fork 7
/
spb_NurbsCrv_maximizeMinimumRadius.py
1790 lines (1352 loc) · 62.5 KB
/
spb_NurbsCrv_maximizeMinimumRadius.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
"""
200112-14: Created from another script.
200128: Import-related update.
200422: Modified pre- and post-object selection behavior.
200504-05: Added function to adjust weight of degree 2 Bezier curves. Refactored various code.
Added bSetMinTargetRad, fRadius_AcceptableMin, and bAdjWeightInDeg2Bezier.
210317: Bug fix.
210725-27: Improvements in Degree 2 Bezier weight adjustment routine.
210814-16: Improvements in tangent control point routines.
210908,12: Major improvements in tangent control point routines for single spanned curves.
221122: Import-related update.
"""
import Rhino
import Rhino.Geometry as rg
import Rhino.Input as ri
import scriptcontext as sc
from System.Diagnostics import Stopwatch
import spb_Crv_inflections
if Rhino.RhinoApp.ExeVersion < 7:
import spb_Crv_radiusMinima
stopwatch = Stopwatch() # One instance will be used for all tests.
class Opts():
keys = []
values = {}
names = {}
riOpts = {}
riAddOpts = {}
stickyKeys = {}
def addOptionDouble(key, names, riOpts):
return lambda getObj: ri.Custom.GetBaseClass.AddOptionDouble(
getObj, englishName=names[key], numberValue=riOpts[key])
def addOptionInteger(key, names, riOpts):
return lambda getObj: ri.Custom.GetBaseClass.AddOptionInteger(
getObj, englishName=names[key], intValue=riOpts[key])
def addOptionList(key, names, listValues, values):
return lambda getObj: ri.Custom.GetBaseClass.AddOptionList(
getObj,
englishOptionName=names[key],
listValues=listValues,
listCurrentIndex=values[key])
def addOptionToggle(key, names, riOpts):
return lambda getObj: ri.Custom.GetBaseClass.AddOptionToggle(
getObj, englishName=names[key], toggleValue=riOpts[key])
key = 'bSetMinTargetRad'; keys.append(key)
values[key] = False
names[key] = 'SetMinTargetRadius'
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'fRadius_AcceptableMin'; keys.append(key)
if sc.doc.ModelUnitSystem == Rhino.UnitSystem.Inches:
values[key] = 0.15
else:
values[key] = 4.0 * Rhino.RhinoMath.UnitScale(
Rhino.UnitSystem.Millimeters, to=sc.doc.ModelUnitSystem)
names[key] = 'Radius'
riOpts[key] = ri.Custom.OptionDouble(initialValue=values[key])
riAddOpts[key] = addOptionDouble(key, names, riOpts)
stickyKeys[key] = '{}({})({})'.format(key, __file__, sc.doc.Name)
key = 'bLimitCrvDev'; keys.append(key)
values[key] = False
names[key] = key[1:]
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'fDevTol'; keys.append(key)
values[key] = 0.1 * sc.doc.ModelAbsoluteTolerance
names[key] = 'Dev'
riOpts[key] = ri.Custom.OptionDouble(initialValue=values[key])
riAddOpts[key] = addOptionDouble(key, names, riOpts)
stickyKeys[key] = '{}({})({})'.format(key, __file__, sc.doc.Name)
key = 'bAdjWeightInDeg2Bezier'; keys.append(key)
values[key] = True
names[key] = key[1:]
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bReplace'; keys.append(key)
values[key] = True
names[key] = 'Action'
riOpts[key] = ri.Custom.OptionToggle(values[key], 'Add', 'Replace')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bEcho'; keys.append(key)
values[key] = True
names[key] = key[1:]
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bDebug'; keys.append(key)
values[key] = False
names[key] = key[1:]
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
# Load sticky.
for key in stickyKeys:
if stickyKeys[key] in sc.sticky:
if key in riOpts:
riOpts[key].CurrentValue = values[key] = sc.sticky[stickyKeys[key]]
else:
values[key] = sc.sticky[stickyKeys[key]]
@classmethod
def setValues(cls):
for key in cls.keys:
if key in cls.riOpts:
cls.values[key] = cls.riOpts[key].CurrentValue
@classmethod
def saveSticky(cls):
for key in cls.stickyKeys:
if key in cls.riOpts:
sc.sticky[cls.stickyKeys[key]] = cls.riOpts[key].CurrentValue
else:
sc.sticky[cls.stickyKeys[key]] = cls.values[key]
def getInput():
"""
Get curve and parameter with optional input.
"""
go = ri.Custom.GetObject()
go.SetCommandPrompt("Select curves")
go.GeometryFilter = Rhino.DocObjects.ObjectType.Curve
#go.DisablePreSelect()
go.AcceptNumber(True, acceptZero=True)
idxs_Opts = {}
while True:
Opts.riAddOpts['bSetMinTargetRad'](go)
if Opts.values['bSetMinTargetRad']: Opts.riAddOpts['fRadius_AcceptableMin'](go)
Opts.riAddOpts['bLimitCrvDev'](go)
if Opts.values['bLimitCrvDev']: Opts.riAddOpts['fDevTol'](go)
Opts.riAddOpts['bAdjWeightInDeg2Bezier'](go)
Opts.riAddOpts['bReplace'](go)
Opts.riAddOpts['bEcho'](go)
Opts.riAddOpts['bDebug'](go)
res = go.GetMultiple(minimumNumber=1, maximumNumber=0)
if res == ri.GetResult.Object:
objrefs = go.Objects()
go.Dispose()
return tuple([objrefs] + [Opts.values[key] for key in Opts.keys])
elif res == ri.GetResult.Cancel:
go.Dispose()
return
else:
# An option was selected or a number was entered.
if res == ri.GetResult.Number:
Opts.riOpts['fDevTol'].CurrentValue = go.Number()
if Opts.riOpts['bLimitCrvDev'].CurrentValue:
key = 'fDevTol'
if Opts.riOpts[key].CurrentValue < 0.0:
Opts.riOpts[key].CurrentValue = Opts.riOpts[key].InitialValue
Opts.setValues()
Opts.saveSticky()
go.ClearCommandOptions()
def getMaximumDeviation(rgCrvA, rgCrvB):
rc = rg.Curve.GetDistancesBetweenCurves(
rgCrvA,
rgCrvB,
tolerance=0.1*sc.doc.ModelAbsoluteTolerance)
if rc[0]:
return rc[1]
def formatDistance(fDistance):
if fDistance is None:
return "(No deviation provided)"
if fDistance == 0.0:
return 0.0
if fDistance < 0.001:
return "{:.2e}".format(fDistance)
else:
return "{:.{}f}".format(fDistance, sc.doc.ModelDistanceDisplayPrecision)
def createNcsWithAdjTanCpSpreadForMaxMinRad_OLD(nc0, bT1WorkEnd, fDevTol=None, nc_forDevComp=None, bDebug=False):
"""
returns list of new NurbsCurves with minimum radii larger than the original.
"""
idxCp_Pos_A = (nc0.Points.Count - 1) if bT1WorkEnd else 0
idxCp_Tan_A = (nc0.Points.Count - 2) if bT1WorkEnd else 1
fRadius_Min_In = getMinimumRadius(nc0)
if fRadius_Min_In is None: return
if bDebug: sEval='fRadius_Min_In'; print sEval+': ',eval(sEval)
ncs_WithLargerMinRadii = []
# Try longer and shorter tangent control point spreads.
for scaleIncr in 0.1, -0.1:
nc_A_Pre = nc0.Duplicate()
scale = 1.0 + scaleIncr
fRadius_MaxMin_ThisScaleDir = None
while True:
sc.escape_test()
nc_WIP = nc0.Duplicate()
if bDebug: sEval='scale'; print sEval+': ',eval(sEval),
xform = rg.Transform.Scale(
anchor=nc_WIP.Points[idxCp_Pos_A].Location,
scaleFactor=scale)
pt_Target = nc_WIP.Points[idxCp_Tan_A].Location
pt_Target.Transform(xform)
nc_WIP.Points[idxCp_Tan_A] = pt_Target
fRadius_Min_WIP = getMinimumRadius(nc_WIP)
if bDebug: sEval='fRadius_Min_WIP'; print sEval+': ',eval(sEval),
if fRadius_Min_WIP <= fRadius_Min_In:
if bDebug: sEval='fRadius_Min_WIP <= fRadius_Min_In'; print sEval+': ',eval(sEval)
# Minimum radius is not increasing,
# so stop and capture the previous curve.
break
if fRadius_MaxMin_ThisScaleDir is not None and fRadius_Min_WIP <= fRadius_MaxMin_ThisScaleDir:
if bDebug: sEval='fRadius_Min_WIP <= fRadius_MaxMin_ThisScaleDir'; print sEval+': ',eval(sEval)
# Minimum radius is now decreasing from best found in this scale direction,
# so stop and capture the previous curve.
break
if fDevTol is not None and nc_forDevComp is not None:
dev = getMaximumDeviation(nc_forDevComp, nc_WIP)
if bDebug:
sEval='dev'; print sEval+': ',eval(sEval),
sEval='dev > fDevTol'; print sEval+': ',eval(sEval),
if dev > fDevTol:
# Deviation is out of tolerance,
# so capture the previous curve.
break
elif bDebug: print
nc_A_Pre.Dispose()
nc_A_Pre = nc_WIP
scale += scaleIncr
fRadius_MaxMin_ThisScaleDir = fRadius_Min_WIP
nc_WIP.Dispose()
if scale != 1.0 + scaleIncr:
# Scale is of nc_A_Pre.
ncs_WithLargerMinRadii.append(nc_A_Pre)
else:
# Fail had occurred at first scale in this direction.
nc_A_Pre.Dispose()
return ncs_WithLargerMinRadii
def getMinimumRadius(nc, epsilon=1e-6, bDebug=False):
"""
Returns:
float(maximum minimum radius)
None for no minimum or for unacceptable curve shapes.
"""
if Rhino.RhinoApp.ExeVersion < 7:
return spb_Crv_radiusMinima.getMinimumRadius(nc_In)
pts = nc.MaxCurvaturePoints() # "An array of points if successful, null if not successful or on error." from https://developer.rhino3d.com/api/RhinoCommon/html/M_Rhino_Geometry_Curve_MaxCurvaturePoints.htm
if pts is None or len(pts) == 0:
bIsArc, arc = nc.TryGetArc(tolerance=epsilon)
if bIsArc:
return arc.Radius
#sc.doc.Objects.AddCurve(nc)
raise ValueError("Why?")
# for pt in pts:
# sc.doc.Objects.AddPoint(pt)
#if len(pts) > 1 and nc.Degree == 2 and nc.SpanCount==1:
# if bDebug:
# print "More than 1 minimum point for Degree 2 Bezier. Curve may be near linear."
# #sc.doc.Objects.AddCurve(nc)
# [sc.doc.Objects.AddPoint(pt) for pt in pts]
# sc.doc.Views.Redraw(); 1/0
# return None
ts = [nc.ClosestPoint(pt)[1] for pt in pts]
min_rad = None
t_min_rad = None
for t in ts:
curvature = nc.CurvatureAt(t).Length
if curvature <= Rhino.RhinoMath.ZeroTolerance:
raise Exception("curvature <= Rhino.RhinoMath.ZeroTolerance")
return None
rad = 1.0 / nc.CurvatureAt(t).Length
if min_rad is None or rad < min_rad:
min_rad = rad
t_min_rad = t
return min_rad
def getMinimaRadii_V7(nc, epsilon=1e-8, bDebug=False):
"""
Returns:
list(float(maximum minimum radius))
None for unacceptable curve shapes.
"""
pts = nc.MaxCurvaturePoints() # "An array of points if successful, null if not successful or on error." from https://developer.rhino3d.com/api/RhinoCommon/html/M_Rhino_Geometry_Curve_MaxCurvaturePoints.htm
if pts is None or len(pts) == 0:
bIsArc, arc = nc.TryGetArc(tolerance=epsilon)
if bIsArc:
return arc.Radius
#sc.doc.Objects.AddCurve(nc)
raise ValueError("Why?")
# for pt in pts:
# sc.doc.Objects.AddPoint(pt)
if len(pts) > 1 and nc.Degree == 2 and nc.SpanCount==1:
if bDebug:
print "More than 1 minimum point for Degree 2 Bezier. Curve may be near linear."
#sc.doc.Objects.AddCurve(nc)
[sc.doc.Objects.AddPoint(pt) for pt in pts]
sc.doc.Views.Redraw(); 1/0
return None, None
ts = [nc.ClosestPoint(pt)[1] for pt in pts]
rads = []
for t in ts:
curvature = nc.CurvatureAt(t).Length
if curvature <= Rhino.RhinoMath.ZeroTolerance:
raise Exception("curvature <= Rhino.RhinoMath.ZeroTolerance")
rad = 1.0 / nc.CurvatureAt(t).Length
rads.append(rad)
return rads
def adjustWeight(nc_In, fRadius_AcceptableMin=None, fDevTol=None, nc_forDevComp=None, epsilon=1e-8, bDebug=False):
"""
Returns:
Success: (rg.NurbsCurve(New), float(minRadius), float(deviation)), None
Fail: None, sLog
"""
if nc_In.Degree != 2 or nc_In.Points.Count > 3:
return None, "Not a degree 2 Bezier."
if nc_In.IsArc(tolerance=epsilon):
return (
None,
"NurbsCurve is already arc-shaped (within {})," \
" and thus has a maximum minimum radius.".format(epsilon))
idxCp_Pos_A = 0
idxCp_Tan_A = 1
fRadius_Min_In = getMinimumRadius(nc_In)
if fRadius_Min_In is None: return None, "Minimum radius could not be obtained."
if bDebug: sEval='fRadius_Min_In'; print sEval+': ',eval(sEval)
if fRadius_AcceptableMin and fRadius_Min_In >= fRadius_AcceptableMin:
return None, "Curve's minimum radius is already >= {}.".format(
fRadius_AcceptableMin)
ncs_Winner_perScaleDir = [None, None]
fRadii_MaxMin_perScaleDir = [None, None]
fDev_perScaleDir = [None, None]
dev = None
def setWeight(nc, weight):
"""
This modifies input NurbsCurve.
Do not use NurbsCurvePointList.SetWeight instead since it relocates the point in R3.
https://discourse.mcneel.com/t/nurbs-definition/13114
"""
nc.Points[1] = rg.ControlPoint(nc.Points[1].Location, weight)
if nc.Points[1].Weight != weight:
raise ValueError("Weight was not set!")
def doesCurveHaveMaximumMinimumRadius(nc):
if getMinimumRadius(nc) is None:
return False
nc_WIP_L = nc.Duplicate()
nc_WIP_M = nc.Duplicate()
nc_WIP_R = nc.Duplicate()
weight_toTry_L = None # This line keeps the variables in a particular order in the Rhino Python Debugger.
weight_toTry_M = nc.Points[1].Weight
weight_delta = 1e-6 #Rhino.RhinoMath.ZeroTolerance
while True:
sc.escape_test()
weight_toTry_L = weight_toTry_M - weight_delta
weight_toTry_R = weight_toTry_M + weight_delta
#
nc_WIP_L.Points[1] = rg.ControlPoint(nc_WIP_L.Points[1].Location, weight=weight_toTry_L)
nc_WIP_M.Points[1] = rg.ControlPoint(nc_WIP_M.Points[1].Location, weight=weight_toTry_M)
nc_WIP_R.Points[1] = rg.ControlPoint(nc_WIP_R.Points[1].Location, weight=weight_toTry_R)
fRad_Min_WIP_L = getMinimumRadius(nc_WIP_L)
fRad_Min_WIP_M = getMinimumRadius(nc_WIP_M)
fRad_Min_WIP_R = getMinimumRadius(nc_WIP_R)
if bDebug:
print "Weight delta: {}".format(weight_delta)
print "W:", weight_toTry_L, weight_toTry_M, weight_toTry_R
print "R:", fRad_Min_WIP_L, fRad_Min_WIP_M, fRad_Min_WIP_R
if (
(fRad_Min_WIP_L is not None and fRad_Min_WIP_L < fRad_Min_WIP_M) and
(fRad_Min_WIP_R is not None and fRad_Min_WIP_R < fRad_Min_WIP_M)
):
return True
if (
fRad_Min_WIP_L is not None and fRad_Min_WIP_M is not None and
not abs(fRad_Min_WIP_L - fRad_Min_WIP_M) <= epsilon
):
return False
if (fRad_Min_WIP_R is not None and fRad_Min_WIP_M is not None and
not abs(fRad_Min_WIP_R - fRad_Min_WIP_M) <= epsilon
):
return False
weight_delta *= 10.0
if doesCurveHaveMaximumMinimumRadius(nc_In):
return None, "Weight is already set for maximum minimum radius."
def doEitherEndHaveRadius(nc, radius):
if areAbsEqual(radius, 1.0 / nc.CurvatureAt(nc.Domain.T0).Length):
return True
if areAbsEqual(radius, 1.0 / nc.CurvatureAt(nc.Domain.T1).Length):
return True
return False
def find_left_edge_weight(nc, starting_weight):
"""
wL will be first weight resulting in 2 minima radii.
"""
nc_WIP = nc.DuplicateCurve()
wL = 10.0
while True:
sc.escape_test()
if wL <= 0.1:
wL = 0.1
break
setWeight(nc_WIP, wL)
if len(getMinimaRadii_V7(nc_WIP)) > 1:
break
wL /= 2.0
wR = starting_weight
while True:
sc.escape_test()
wM = 0.5*wL + 0.5*wR
if areRelEqual(wM, wL):
setWeight(nc_WIP, wL)
rL = getMinimumRadius(nc_WIP)
if bDebug: print wL, rL
#if rL is not None:
# raise Exception("rL should be None!")
setWeight(nc_WIP, wM)
rM = getMinimumRadius(nc_WIP)
if bDebug: print wM, rM
if rM is not None:
return wM
wR = wM
while True:
sc.escape_test()
wR += epsilon
setWeight(nc_WIP, wR)
rR = getMinimumRadius(nc_WIP)
if bDebug: print wR, rR
if rR is not None:
nc_WIP.Dispose()
return wR
setWeight(nc_WIP, wM)
if getMinimumRadius(nc_WIP) is None:
wL = wM
else:
wR = wM
def binarySearch(nc):
# Determine direction from current weight to search.
nc_WIP_L = nc.Duplicate()
nc_WIP_M = nc.Duplicate()
nc_WIP_R = nc.Duplicate()
good_weights = []
good_rads = []
rad = getMinimumRadius(nc)
if rad is not None:
good_weights.append(nc.Points[1].Weight)
good_rads.append(rad)
for p in range(-3,7):
weight_toTry_M = 10.0**p
nc_WIP_M.Points[1] = rg.ControlPoint(nc_WIP_M.Points[1].Location, weight=weight_toTry_M)
rad = getMinimumRadius(nc_WIP_M)
if rad is not None and rad >= sc.doc.ModelAbsoluteTolerance:
good_weights.append(weight_toTry_M)
good_rads.append(rad)
fRad_Min_WIP_M = max(good_rads)
weight_toTry_M = good_weights[good_rads.index(max(good_rads))]
weight_toTry_L = find_left_edge_weight(nc, starting_weight=weight_toTry_M)
weight_toTry_R = 10.0
setWeight(nc_WIP_L, weight_toTry_L)
fRad_Min_WIP_L = getMinimumRadius(nc_WIP_L)
setWeight(nc_WIP_R, weight_toTry_R)
fRad_Min_WIP_R = getMinimumRadius(nc_WIP_R)
if fRad_Min_WIP_L > fRad_Min_WIP_M:
weight_toTry_M = weight_toTry_L + epsilon
setWeight(nc_WIP_M, weight_toTry_M)
fRad_Min_WIP_M = getMinimumRadius(nc_WIP_M)
dev = getMaximumDeviation(nc_forDevComp, nc_WIP_L)
if fRad_Min_WIP_L > fRad_Min_WIP_M:
return (nc_WIP_L, fRad_Min_WIP_L, dev), None
weight_toTry_M = 0.5*weight_toTry_L + 0.5*weight_toTry_R
if fRad_Min_WIP_R > fRad_Min_WIP_M:
raise ValueError("R radius should not be greater than M.")
i = 0
while True:
sc.escape_test()
# Do not use SetWeight. https://discourse.mcneel.com/t/nurbs-definition/13114
nc_WIP_L.Points[1] = rg.ControlPoint(nc_WIP_L.Points[1].Location, weight=weight_toTry_L)
nc_WIP_M.Points[1] = rg.ControlPoint(nc_WIP_M.Points[1].Location, weight=weight_toTry_M)
nc_WIP_R.Points[1] = rg.ControlPoint(nc_WIP_R.Points[1].Location, weight=weight_toTry_R)
fRad_Min_WIP_L = getMinimumRadius(nc_WIP_L)
fRad_Min_WIP_M = getMinimumRadius(nc_WIP_M)
fRad_Min_WIP_R = getMinimumRadius(nc_WIP_R)
if bDebug:
print "i{} W:".format(i), weight_toTry_L, weight_toTry_M, weight_toTry_R
print "i{} R:".format(i), fRad_Min_WIP_L, fRad_Min_WIP_M, fRad_Min_WIP_R
if areRelEqual(weight_toTry_L, weight_toTry_R):
dev = getMaximumDeviation(nc_forDevComp, nc_WIP_M)
nc_WIP_L.Dispose()
nc_WIP_R.Dispose()
return (nc_WIP_M, fRad_Min_WIP_M, dev), None
if fRad_Min_WIP_L is not None:
if areAbsEqual(fRad_Min_WIP_L, fRad_Min_WIP_R):
if areAbsEqual(fRad_Min_WIP_M, fRad_Min_WIP_R):
dev = getMaximumDeviation(nc_forDevComp, nc_WIP_M)
nc_WIP_L.Dispose()
nc_WIP_R.Dispose()
return (nc_WIP_M, fRad_Min_WIP_M, dev), None
if fRad_Min_WIP_M > fRad_Min_WIP_L and fRad_Min_WIP_M > fRad_Min_WIP_R:
if fRad_Min_WIP_L > fRad_Min_WIP_R:
weight_toTry_R = 0.75*weight_toTry_R + 0.25*weight_toTry_M
elif fRad_Min_WIP_L < fRad_Min_WIP_R:
weight_toTry_L = 0.75*weight_toTry_L + 0.25*weight_toTry_M
else:
raise ValueError("asdf")
#weight_toTry_L = 0.75*weight_toTry_L + 0.25*weight_toTry_M
#weight_toTry_R = 0.75*weight_toTry_R + 0.25*weight_toTry_M
elif fRad_Min_WIP_L > fRad_Min_WIP_R and fRad_Min_WIP_M > fRad_Min_WIP_R:
weight_toTry_R = weight_toTry_M
elif fRad_Min_WIP_R > fRad_Min_WIP_L and fRad_Min_WIP_M > fRad_Min_WIP_L:
weight_toTry_L = weight_toTry_M
else:
print "Is this possible?:"
sEval='fRadius_Min_WIP_L'; print ' '+sEval+': ',eval(sEval)
sEval='fRadius_Min_WIP_C'; print ' '+sEval+': ',eval(sEval)
sEval='fRadius_Min_WIP_R'; print ' '+sEval+': ',eval(sEval)
weight_toTry_M = 0.5*weight_toTry_L + 0.5*weight_toTry_R
i += 1
rc = binarySearch(nc_In)
if rc[0] is None:
return rc
if fRadius_AcceptableMin is None and fDevTol is None:
return rc
nc_Ret, fRadius_Min_Res, fDev_Res = rc[0]
if fRadius_AcceptableMin is None and fDevTol is not None:
if fDev_Res <= fDevTol:
return rc
# Will try code below.
elif fRadius_AcceptableMin is not None and fDevTol is None:
if fRadius_Min_Res >= fRadius_AcceptableMin:
return rc
else:
return None, "Minimum radius cannot be achieved."
elif fRadius_AcceptableMin is not None and fDevTol is not None:
sLogs = []
if fRadius_Min_Res < fRadius_AcceptableMin:
return None, "Minimum radius cannot be achieved."
if fDev_Res <= fDevTol:
return rc
# Will try code below.
# TODO: Rewrite the following code by testing weights between
# starting weight of nc_In and weight of nc_Ret.
# Try weights less than and greater than starting weight.
for iDir, weightDelta in enumerate((-0.01, 0.01)):
weight_toTry = nc_In.Points[1].Weight + weightDelta
while True:
sc.escape_test()
nc_WIP = nc_In.Duplicate()
if bDebug:
sEval='weight_toTry'; print sEval+': ',eval(sEval)
nc_WIP.Points[1] = rg.ControlPoint(nc_WIP.Points[1].Location, weight=weight_toTry)
if bDebug: stopwatch.Restart()
fRadius_Min_WIP = getMinimumRadius(nc_WIP)
if bDebug:
stopwatch.Stop()
timeElapsed = stopwatch.Elapsed.TotalSeconds
s = "{:.2f} seconds for ".format(timeElapsed)
s += "getMinimumRadius"
print s
sEval='fRadius_Min_WIP'; print ' '+sEval+': ',eval(sEval),
if fRadius_Min_WIP <= fRadius_Min_In:
if bDebug:
sEval='fRadius_Min_WIP <= fRadius_Min_In'; print sEval+': ',eval(sEval)
print " Minimum radius is not increasing," \
" so break."
break
if fDevTol is not None and nc_forDevComp is not None:
if bDebug: stopwatch.Restart()
dev = getMaximumDeviation(nc_forDevComp, nc_WIP)
if bDebug:
stopwatch.Stop()
timeElapsed = stopwatch.Elapsed.TotalSeconds
s = "{:.2f} seconds for ".format(timeElapsed)
s += "getMaximumDeviation"
print s
sEval='dev'; print sEval+': ',eval(sEval),
sEval='dev > fDevTol'; print sEval+': ',eval(sEval)
if dev > fDevTol:
if bDebug:
print " Deviation is out of tolerance, so break."
break
if fRadius_AcceptableMin and fRadius_Min_WIP >= fRadius_AcceptableMin:
print "Curve's minimum radius, {} is >= {}.".format(
fRadius_Min_WIP, fRadius_AcceptableMin)
return (nc_WIP, fRadius_Min_WIP, fDevTol), None
if bDebug:
print "Curve minimum radius is larger than that of the starting curve."
if ncs_Winner_perScaleDir[iDir] is None:
ncs_Winner_perScaleDir[iDir] = nc_WIP
fRadii_MaxMin_perScaleDir[iDir] = fRadius_Min_WIP
fDev_perScaleDir[iDir] = dev
weight_toTry += weightDelta
continue
if fRadius_Min_WIP > fRadii_MaxMin_perScaleDir[iDir]:
if bDebug:
sEval='fRadius_Min_WIP > fRadii_MaxMin_perScaleDir[iDir]'; print sEval+': ',eval(sEval)
print "Minimum radius is increasing."
ncs_Winner_perScaleDir[iDir].Dispose()
ncs_Winner_perScaleDir[iDir] = nc_WIP
fRadii_MaxMin_perScaleDir[iDir] = fRadius_Min_WIP
fDev_perScaleDir[iDir] = dev
weight_toTry += weightDelta
continue
if bDebug:
print "Curve minimum radius is no longer increasing, so break"
nc_WIP.Dispose()
break
if not (ncs_Winner_perScaleDir[0] or ncs_Winner_perScaleDir[1]):
return None, "No curves with increased minimum radius found at given parameters."
if ncs_Winner_perScaleDir[0] and ncs_Winner_perScaleDir[1]:
iDir_Winner = fRadii_MaxMin_perScaleDir.index(max(fRadii_MaxMin_perScaleDir))
else:
iDir_Winner = 0 if ncs_Winner_perScaleDir[0] else 1
return (
(
ncs_Winner_perScaleDir[iDir_Winner],
fRadii_MaxMin_perScaleDir[iDir_Winner],
fDev_perScaleDir[iDir_Winner]
),
None)
def adjustTanCpSpread_OneEndOnly(nc_In, bT1WorkEnd, fRadius_AcceptableMin=None, fDevTol=None, nc_forDevComp=None, bDebug=False):
"""
Returns:
Success: rg.NurbsCurve(New), float(minRadius), float(deviation)
Fail: None, str(Feedback)
This is not the latest function.
"""
idxCp_Pos_A = (nc_In.Points.Count - 1) if bT1WorkEnd else 0
idxCp_Tan_A = (nc_In.Points.Count - 2) if bT1WorkEnd else 1
fRadius_Min_In = getMinimumRadius(nc_In)
if fRadius_Min_In is None:
return None, "Minimum radius could not be obtained."
if bDebug: sEval='fRadius_Min_In'; print sEval+': ',eval(sEval)
if fRadius_AcceptableMin and fRadius_Min_In >= fRadius_AcceptableMin:
return None, "Curve's minimum radius is already >= {}.".format(
fRadius_AcceptableMin)
ncs_Winner_perScaleDir = [None, None]
fRadii_MaxMin_perScaleDir = [None, None]
fDev_perScaleDir = [None, None]
dev = None
vTan = nc_In.Points[idxCp_Tan_A].Location - nc_In.Points[idxCp_Pos_A].Location
vTan.Unitize()
radius_epsilon = (1e-3) * sc.doc.ModelAbsoluteTolerance
# Try longer and shorter tangent control point spreads.
for iDir, scaleDelta in enumerate((-0.01, 0.01)):
#scale = 1.0 + scaleDelta
i = 1
while True:
sc.escape_test()
nc_WIP = nc_In.Duplicate()
#if bDebug: sEval='scale'; print sEval+': ',eval(sEval),
#xform = rg.Transform.Scale(
# anchor=nc_WIP.Points[idxCp_Pos_A].Location,
# scaleFactor=scale)
#pt_Target = nc_WIP.Points[idxCp_Tan_A].Location
#pt_Target.Transform(xform)
vTrans = float(i) * sc.doc.ModelAbsoluteTolerance * vTan
if iDir == 0:
vTrans = rg.Vector3d.Negate(vTrans)
xform = rg.Transform.Translation(vTrans)
pt_Target = nc_In.Points[idxCp_Tan_A].Location
pt_Target.Transform(xform)
nc_WIP.Points[idxCp_Tan_A] = pt_Target
if bDebug: stopwatch.Restart()
fRadius_Min_WIP = getMinimumRadius(nc_WIP)
if bDebug:
stopwatch.Stop()
timeElapsed = stopwatch.Elapsed.TotalSeconds
s = "{:.2f} seconds for ".format(timeElapsed)
s += "getMinimumRadius"
print s
sEval='fRadius_Min_WIP'; print ' '+sEval+': ',eval(sEval),
if (fRadius_Min_WIP - radius_epsilon) <= fRadius_Min_In:
#sc.doc.Objects.AddCurve(nc_WIP)#;1/0
if bDebug:
sEval='fRadius_Min_WIP <= fRadius_Min_In'; print sEval+': ',eval(sEval)
print " Minimum radius is not increasing," \
" so break."
break
if fDevTol is not None and nc_forDevComp is not None:
if bDebug: stopwatch.Restart()
dev = getMaximumDeviation(nc_forDevComp, nc_WIP)
if bDebug:
stopwatch.Stop()
timeElapsed = stopwatch.Elapsed.TotalSeconds
s = "{:.2f} seconds for ".format(timeElapsed)
s += "getMaximumDeviation"
print s
sEval='dev'; print sEval+': ',eval(sEval),
sEval='dev > fDevTol'; print sEval+': ',eval(sEval)
if dev > fDevTol:
if bDebug:
print " Deviation is out of tolerance, so break."
break
if fRadius_AcceptableMin:
if (fRadius_Min_WIP + radius_epsilon) >= fRadius_AcceptableMin:
print "Curve's minimum radius, {} is >= {}.".format(
fRadius_Min_WIP, fRadius_AcceptableMin)
return (nc_WIP, fRadius_Min_WIP, fDevTo), None
if bDebug:
print "Curve minimum radius is larger than that of the starting curve."
if ncs_Winner_perScaleDir[iDir] is None:
ncs_Winner_perScaleDir[iDir] = nc_WIP
fRadii_MaxMin_perScaleDir[iDir] = fRadius_Min_WIP
fDev_perScaleDir[iDir] = dev
#scale += scaleDelta
i += 1
continue
if (fRadius_Min_WIP - radius_epsilon) > fRadii_MaxMin_perScaleDir[iDir]:
if bDebug:
sEval='fRadius_Min_WIP > fRadii_MaxMin_perScaleDir[iDir]'; print sEval+': ',eval(sEval)
print "Minimum radius is increasing."
ncs_Winner_perScaleDir[iDir].Dispose()
ncs_Winner_perScaleDir[iDir] = nc_WIP
fRadii_MaxMin_perScaleDir[iDir] = fRadius_Min_WIP
fDev_perScaleDir[iDir] = dev
#scale += scaleDelta
i += 1
continue
if bDebug:
print "Curve minimum radius is no longer increasing, so break"
nc_WIP.Dispose()
break
if not (ncs_Winner_perScaleDir[0] or ncs_Winner_perScaleDir[1]):
return None, "No winner."
if ncs_Winner_perScaleDir[0] and ncs_Winner_perScaleDir[1]:
iDir_Winner = fRadii_MaxMin_perScaleDir.index(max(fRadii_MaxMin_perScaleDir))
else:
iDir_Winner = 0 if ncs_Winner_perScaleDir[0] else 1
return (
(
ncs_Winner_perScaleDir[iDir_Winner],
fRadii_MaxMin_perScaleDir[iDir_Winner],
fDev_perScaleDir[iDir_Winner]
),
None)
def adjustTanCpSpread_BothEndsSimultaneously(nc_In, fRadius_AcceptableMin=None, fDevTol=None, nc_forDevComp=None, bDebug=False):
"""
Returns:
Success: rg.NurbsCurve(New), float(minRadius), float(deviation)
Fail: None, str(Feedback)
210908: New.
"""
idx_G0_T0 = 0
idx_G1_T0 = 1
idx_G0_T1 = nc_In.Points.Count - 1
idx_G1_T1 = nc_In.Points.Count - 2
fRadius_Min_In = getMinimumRadius(nc_In)
if fRadius_Min_In is None:
return None, "Minimum radius could not be obtained."
if bDebug: sEval='fRadius_Min_In'; print sEval+': ',eval(sEval)
if fRadius_AcceptableMin and fRadius_Min_In >= fRadius_AcceptableMin:
return None, "Curve's minimum radius is already >= {}.".format(
fRadius_AcceptableMin)
ncs_Winner_perScaleDir = []
fRadii_MaxMin_perScaleDir = []
fDev_perScaleDir = []
dev = None
vTan_T0 = nc_In.Points[idx_G1_T0].Location - nc_In.Points[idx_G0_T0].Location
vTan_T0.Unitize()
vTan_T1 = nc_In.Points[idx_G0_T1].Location - nc_In.Points[idx_G1_T1].Location
vTan_T1.Unitize()
radius_epsilon = (1e-3) * sc.doc.ModelAbsoluteTolerance
# Try longer and shorter tangent control point spreads.
for iDir_T0, iDir_T1 in zip((0,0,1,1),(0,1,0,1)):
sc.escape_test()
ncs_Winner_thisScaleDir = None
fRadii_MaxMin_thisScaleDir = None
fDev_thisScaleDir = None
i = 1
while True:
sc.escape_test()
if bDebug: sEval='i'; print sEval+': ',eval(sEval)
nc_WIP = nc_In.Duplicate()
vTrans_T0 = float(i) * sc.doc.ModelAbsoluteTolerance * vTan_T0
vTrans_T1 = float(i) * sc.doc.ModelAbsoluteTolerance * vTan_T1
if iDir_T0 == 0:
vTrans_T0 = rg.Vector3d.Negate(vTrans_T0)