forked from orbingol/NURBS-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathabstract.py
3099 lines (2413 loc) · 115 KB
/
abstract.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
"""
.. module:: abstract
:platform: Unix, Windows
:synopsis: Provides abstract base classes for representing the geometries
.. moduleauthor:: Onur Rauf Bingol <orbingol@gmail.com>
"""
import copy
import abc
import warnings
import math
from . import vis, helpers, knotvector, voxelize, utilities
from . import tessellate
from .evaluators import AbstractEvaluator
from .exceptions import GeomdlException
from . import _utilities as utl
@utl.add_metaclass(abc.ABCMeta)
class GeomdlBase(object):
""" Abstract base class for defining geomdl objects.
This class provides the following properties:
* :py:attr:`type`
* :py:attr:`id`
* :py:attr:`name`
* :py:attr:`dimension`
* :py:attr:`opt`
**Keyword Arguments:**
* ``id``: object ID (as integer)
* ``precision``: number of decimal places to round to. *Default: 18*
"""
# __slots__ = ('_precision', '_id', '_dimension', '_geometry_type', '_name', '_opt_data', '_cache')
def __init__(self, **kwargs):
self._dimension = 0 if not hasattr(self, '_dimension') else self._dimension # spatial dimension
self._geometry_type = "none" if not hasattr(self, '_geometry_type') else self._geometry_type # geometry type
self._name = "base object" if not hasattr(self, '_name') else self._name # object name
self._opt_data = dict() if not hasattr(self, '_opt_data') else self._opt_data # custom data dict
self._cache = dict() if not hasattr(self, '_cache') else self._cache # cache dict
self._precision = int(kwargs.get('precision', 18)) # number of decimal places to round to
self._id = int(kwargs.get('id', 0)) # object ID
def __copy__(self):
cls = self.__class__
result = cls.__new__(cls)
result.__dict__.update(self.__dict__)
return result
def __deepcopy__(self, memo):
# Don't copy self reference
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
# Don't copy the cache
memo[id(self._cache)] = self._cache.__new__(dict)
# Copy all other attributes
for k, v in self.__dict__.items():
setattr(result, k, copy.deepcopy(v, memo))
return result
def __str__(self):
return self.name
__repr__ = __str__
@property
def dimension(self):
""" Spatial dimension.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the spatial dimension, e.g. 2D, 3D, etc.
:type: int
"""
return self._dimension
@property
def type(self):
""" Geometry type
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the geometry type
:type: str
"""
return self._geometry_type
@property
def id(self):
""" Object ID (as an integer).
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the object ID
:setter: Sets the object ID
:type: int
"""
return self._id
@id.setter
def id(self, value):
if not isinstance(value, int):
raise GeomdlException("Identifier value must be an integer")
self._id = value
@id.deleter
def id(self):
self._id = 0
@property
def name(self):
""" Object name (as a string)
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the object name
:setter: Sets the object name
:type: str
"""
return self._name
@name.setter
def name(self, value):
self._name = str(value)
@name.deleter
def name(self):
self._name = ""
@property
def opt(self):
""" Dictionary for storing custom data in the current geometry object.
``opt`` is a wrapper to a dict in *key => value* format, where *key* is string, *value* is any Python object.
You can use ``opt`` property to store custom data inside the geometry object. For instance:
.. code-block:: python
geom.opt = ["face_id", 4] # creates "face_id" key and sets its value to an integer
geom.opt = ["contents", "data values"] # creates "face_id" key and sets its value to a string
print(geom.opt) # will print: {'face_id': 4, 'contents': 'data values'}
del geom.opt # deletes the contents of the hash map
print(geom.opt) # will print: {}
geom.opt = ["body_id", 1] # creates "body_id" key and sets its value to 1
geom.opt = ["body_id", 12] # changes the value of "body_id" to 12
print(geom.opt) # will print: {'body_id': 12}
geom.opt = ["body_id", None] # deletes "body_id"
print(geom.opt) # will print: {}
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the dict
:setter: Adds key and value pair to the dict
:deleter: Deletes the contents of the dict
"""
return self._opt_data
@opt.setter
def opt(self, key_value):
if not isinstance(key_value, (list, tuple)):
raise GeomdlException("opt input must be a list or a tuple")
if len(key_value) != 2:
raise GeomdlException("opt input must have a size of 2, corresponding to [0:key] => [1:value]")
if not isinstance(key_value[0], str):
raise GeomdlException("key must be string")
if key_value[1] is None:
self._opt_data.pop(*key_value)
else:
self._opt_data[key_value[0]] = key_value[1]
@opt.deleter
def opt(self):
self._opt_data = dict()
def opt_get(self, value):
""" Safely query for the value from the :py:attr:`opt` property.
:param value: a key in the :py:attr:`opt` property
:type value: str
:return: the corresponding value, if the key exists. ``None``, otherwise.
"""
try:
return self._opt_data[value]
except KeyError:
return None
@utl.add_metaclass(abc.ABCMeta)
class Geometry(GeomdlBase):
""" Abstract base class for defining geometry objects.
This class provides the following properties:
* :py:attr:`type`
* :py:attr:`id`
* :py:attr:`name`
* :py:attr:`dimension`
* :py:attr:`evalpts`
* :py:attr:`opt`
**Keyword Arguments:**
* ``id``: object ID (as integer)
* ``precision``: number of decimal places to round to. *Default: 18*
"""
# __slots__ = ('_iter_index', '_array_type', '_eval_points')
def __init__(self, **kwargs):
self._geometry_type = "default" if not hasattr(self, '_geometry_type') else self._geometry_type # geometry type
super(Geometry, self).__init__(**kwargs)
self._array_type = list if not hasattr(self, '_array_type') else self._array_type # array storage type
self._eval_points = self._init_array() # evaluated points
def __iter__(self):
self._iter_index = 0
return self
def next(self):
return self.__next__()
def __next__(self):
if self._iter_index > 0:
raise StopIteration
self._iter_index += 1
return self
def __len__(self):
return 1
def __getitem__(self, index):
return self
def _init_array(self):
""" Initializes the arrays. """
if callable(self._array_type):
return self._array_type()
return list()
@property
def evalpts(self):
""" Evaluated points.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the coordinates of the evaluated points
:type: list
"""
if self._eval_points is None or len(self._eval_points) == 0:
self.evaluate()
return self._eval_points
@abc.abstractmethod
def evaluate(self, **kwargs):
""" Abstract method for the implementation of evaluation algorithm.
.. note::
This is an abstract method and it must be implemented in the subclass.
"""
pass
@utl.add_metaclass(abc.ABCMeta)
class SplineGeometry(Geometry):
""" Abstract base class for defining spline geometry objects.
This class provides the following properties:
* :py:attr:`type` = spline
* :py:attr:`id`
* :py:attr:`name`
* :py:attr:`rational`
* :py:attr:`dimension`
* :py:attr:`pdimension`
* :py:attr:`degree`
* :py:attr:`knotvector`
* :py:attr:`ctrlpts`
* :py:attr:`ctrlpts_size`
* :py:attr:`weights` (for completeness with the rational spline implementations)
* :py:attr:`evalpts`
* :py:attr:`bbox`
* :py:attr:`evaluator`
* :py:attr:`vis`
* :py:attr:`opt`
**Keyword Arguments:**
* ``id``: object ID (as integer)
* ``precision``: number of decimal places to round to. *Default: 18*
* ``normalize_kv``: if True, knot vector(s) will be normalized to [0,1] domain. *Default: True*
* ``find_span_func``: default knot span finding algorithm. *Default:* :func:`.helpers.find_span_linear`
"""
# __slots__ = (
# '_pdim', '_dinit', '_rational', '_degree', '_knot_vector', '_control_points', '_control_points_size',
# '_delta', '_bounding_box', '_evaluator', '_vis_component', '_span_func', '_kv_normalize'
# )
def __init__(self, **kwargs):
self._geometry_type = "spline" if not hasattr(self, '_geometry_type') else self._geometry_type # geometry type
super(SplineGeometry, self).__init__(**kwargs)
self._pdim = 0 if not hasattr(self, '_pdim') else self._pdim # parametric dimension
self._dinit = 0.1 if not hasattr(self, '_dinit') else self._dinit # evaluation delta init value
self._rational = False # defines whether the B-spline object is rational or not
self._degree = [0 for _ in range(self._pdim)] # degree
self._knot_vector = [self._init_array() for _ in range(self._pdim)] # knot vector
self._control_points = self._init_array() # control points
self._control_points_size = [0 for _ in range(self._pdim)] # control points length
self._delta = [self._dinit for _ in range(self._pdim)] # evaluation delta
self._bounding_box = self._init_array() # bounding box
self._evaluator = None # evaluator instance
self._vis_component = None # visualization component
self._span_func = kwargs.get('find_span_func', helpers.find_span_linear) # default "find_span" function
self._kv_normalize = kwargs.get('normalize_kv', True) # flag to control knot vector normalization
def __eq__(self, other):
if not hasattr(other, '_pdim'):
return False
if not hasattr(other, '_degree') or not hasattr(other, '_knot_vector') or not hasattr(other, '_control_points'):
return False
if self.pdimension != other.pdimension:
return False
if self.rational != other.rational:
return False
try:
for s, o in zip(self._control_points_size, other._control_points_size):
if s != o:
return False
chk_degree = []
for s, o in zip(self._degree, other._degree):
tmp = True if s == o else False
chk_degree.append(tmp)
if not all(chk_degree):
return False
chk_kv = []
for sk, ok in zip(self._knot_vector, other._knot_vector):
if len(sk) != len(ok):
return False
chk = []
for s, o in zip(sk, ok):
tmp = True if abs(s - o) < self._precision else False
chk.append(tmp)
chk_kv.append(all(chk))
if not all(chk_kv):
return False
chk_ctrlpts = []
for sk, ok in zip(self._control_points, other._control_points):
if len(sk) != len(ok):
return False
chk = []
for s, o in zip(sk, ok):
tmp = True if abs(s - o) < self._precision else False
chk.append(tmp)
chk_ctrlpts.append(all(chk))
if not all(chk_kv):
return False
except Exception:
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
@property
def rational(self):
""" Defines the rational and non-rational B-spline shapes.
Rational shapes use homogeneous coordinates which includes a weight alongside with the Cartesian coordinates.
Rational B-splines are also named as NURBS (Non-uniform rational basis spline) and non-rational B-splines are
sometimes named as NUBS (Non-uniform basis spline) or directly as B-splines.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Returns True is the B-spline object is rational (NURBS)
:type: bool
"""
return self._rational
@property
def dimension(self):
""" Spatial dimension.
Spatial dimension will be automatically estimated from the first element of the control points array.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the spatial dimension, e.g. 2D, 3D, etc.
:type: int
"""
if self._rational:
return self._dimension - 1
return self._dimension
@property
def pdimension(self):
""" Parametric dimension.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the parametric dimension
:type: int
"""
return self._pdim
@property
def degree(self):
""" Degree
.. note::
This is an expert property for getting and setting the degree(s) of the geometry.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the degree
:setter: Sets the degree
:type: list
"""
return self._degree
@degree.setter
def degree(self, value):
self._degree = value
@property
def knotvector(self):
""" Knot vector
.. note::
This is an expert property for getting and setting the knot vector(s) of the geometry.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the knot vector
:setter: Sets the knot vector
:type: list
"""
return self._knot_vector
@knotvector.setter
def knotvector(self, value):
self._knot_vector = value
@property
def ctrlpts(self):
""" Control points.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the control points
:setter: Sets the control points
:type: list
"""
return self._control_points
@ctrlpts.setter
def ctrlpts(self, value):
self._control_points = value
@property
def weights(self):
""" Weights.
.. note::
Only available for rational spline geometries. Getter return ``None`` otherwise.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the weights
:setter: Sets the weights
"""
return None
@weights.setter
def weights(self, value):
pass
@property
def cpsize(self):
""" Number of control points in all parametric directions.
.. note::
This is an expert property for getting and setting control point size(s) of the geometry.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the number of control points
:setter: Sets the number of control points
:type: list
"""
return self._control_points_size
@cpsize.setter
def cpsize(self, value):
self._control_points_size = value
@property
def ctrlpts_size(self):
""" Total number of control points.
:getter: Gets the total number of control points
:type: int
"""
res = 1
for sz in self._control_points_size:
res *= sz
return res
@property
def domain(self):
""" Domain.
Domain is determined using the knot vector(s).
:getter: Gets the domain
"""
retval = []
for idx, kv in enumerate(self._knot_vector):
retval.append((kv[self._degree[idx]], kv[-(self._degree[idx] + 1)]))
return retval[0] if self._pdim == 1 else retval
@property
def range(self):
""" Domain range.
:getter: Gets the range
"""
retval = []
for idx, kv in enumerate(self._knot_vector):
retval.append(kv[-(self._degree[idx]) + 1] - kv[self._degree[idx]])
return retval[0] if self._pdim == 1 else retval
@property
def bbox(self):
""" Bounding box.
Evaluates the bounding box and returns the minimum and maximum coordinates.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the bounding box
:type: tuple
"""
if self._bounding_box is None or len(self._bounding_box) == 0:
self._bounding_box = utilities.evaluate_bounding_box(self.ctrlpts)
return self._bounding_box
@property
def evaluator(self):
""" Evaluator instance.
Evaluators allow users to use different algorithms for B-Spline and NURBS evaluations. Please see the
documentation on ``Evaluator`` classes.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the current Evaluator instance
:setter: Sets the Evaluator instance
:type: evaluators.AbstractEvaluator
"""
return self._evaluator
@evaluator.setter
def evaluator(self, value):
if not isinstance(value, AbstractEvaluator):
raise TypeError("The evaluator must be an instance of AbstractEvaluator")
value._span_func = self._span_func
self._evaluator = value
@property
def vis(self):
""" Visualization component.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the visualization component
:setter: Sets the visualization component
:type: vis.VisAbstract
"""
return self._vis_component
@vis.setter
def vis(self, value):
if not isinstance(value, vis.VisAbstract):
warnings.warn("Visualization component is NOT an instance of VisAbstract class")
return
self._vis_component = value
def set_ctrlpts(self, ctrlpts, *args, **kwargs):
""" Sets control points and checks if the data is consistent.
This method is designed to provide a consistent way to set control points whether they are weighted or not.
It directly sets the control points member of the class, and therefore it doesn't return any values.
The input will be an array of coordinates. If you are working in the 3-dimensional space, then your coordinates
will be an array of 3 elements representing *(x, y, z)* coordinates.
Keyword Arguments:
* ``array_init``: initializes the control points array in the instance
* ``array_check_for``: defines the types for input validation
* ``callback``: defines the callback function for processing input points
* ``dimension``: defines the spatial dimension of the input points
:param ctrlpts: input control points as a list of coordinates
:type ctrlpts: list
:param args: number of control points corresponding to each parametric dimension
:type args: tuple
"""
def validate_and_clean(pts_in, check_for, dimension, pts_out, **kws):
for idx, cpt in enumerate(pts_in):
if not isinstance(cpt, check_for):
raise ValueError("Element number " + str(idx) + " is not a valid input")
if len(cpt) != dimension:
raise ValueError("The input must be " + str(self._dimension) + " dimensional list - " + str(cpt) +
" is not a valid control point")
# Convert to list of floats
pts_out[idx] = [float(coord) for coord in cpt]
return pts_out
# Argument validation
if len(args) == 0:
args = [len(ctrlpts)]
if len(args) != self._pdim:
raise ValueError("Number of arguments after ctrlpts must be " + str(self._pdim))
# Keyword arguments
array_init = kwargs.get('array_init', [[] for _ in range(len(ctrlpts))])
array_check_for = kwargs.get('array_check_for', (list, tuple))
callback_func = kwargs.get('callback', validate_and_clean)
self._dimension = kwargs.get('dimension', len(ctrlpts[0]))
# Pop existing keywords from kwargs dict
existing_kws = ['array_init', 'array_check_for', 'callback', 'dimension']
for ekw in existing_kws:
if ekw in kwargs:
kwargs.pop(ekw)
# Set control points and sizes
self._control_points = callback_func(ctrlpts, array_check_for, self._dimension, array_init, **kwargs)
self._control_points_size = [int(arg) for arg in args]
@abc.abstractmethod
def render(self, **kwargs):
""" Abstract method for spline rendering and visualization.
.. note::
This is an abstract method and it must be implemented in the subclass.
"""
pass
@utl.add_metaclass(abc.ABCMeta)
class Curve(SplineGeometry):
""" Abstract base class for defining spline curves.
Curve ABC is inherited from abc.ABCMeta class which is included in Python standard library by default. Due to
differences between Python 2 and 3 on defining a metaclass, the compatibility module ``six`` is employed. Using
``six`` to set metaclass allows users to use the abstract classes in a correct way.
The abstract base classes in this module are implemented using a feature called Python Properties. This feature
allows users to use some of the functions as if they are class fields. You can also consider properties as a
pythonic way to set getters and setters. You will see "getter" and "setter" descriptions on the documentation of
these properties.
The Curve ABC allows users to set the *FindSpan* function to be used in evaluations with ``find_span_func`` keyword
as an input to the class constructor. NURBS-Python includes a binary and a linear search variation of the FindSpan
function in the ``helpers`` module.
You may also implement and use your own *FindSpan* function. Please see the ``helpers`` module for details.
Code segment below illustrates a possible implementation of Curve abstract base class:
.. code-block:: python
:linenos:
from geomdl import abstract
class MyCurveClass(abstract.Curve):
def __init__(self, **kwargs):
super(MyCurveClass, self).__init__(**kwargs)
# Add your constructor code here
def evaluate(self, **kwargs):
# Implement this function
pass
def evaluate_single(self, uv):
# Implement this function
pass
def evaluate_list(self, uv_list):
# Implement this function
pass
def derivatives(self, u, v, order, **kwargs):
# Implement this function
pass
The properties and functions defined in the abstract base class will be automatically available in the subclasses.
**Keyword Arguments:**
* ``id``: object ID (as integer)
* ``precision``: number of decimal places to round to. *Default: 18*
* ``normalize_kv``: if True, knot vector(s) will be normalized to [0,1] domain. *Default: True*
* ``find_span_func``: default knot span finding algorithm. *Default:* :func:`.helpers.find_span_linear`
"""
def __init__(self, **kwargs):
self._pdim = 1 # number of parametric directions
self._dinit = 0.01 # evaluation delta init value
self._name = "curve" # object name
super(Curve, self).__init__(**kwargs) # Call parent function
@property
def order(self):
""" Order.
Defined as ``order = degree + 1``
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the order
:setter: Sets the order
:type: int
"""
return self.degree + 1
@order.setter
def order(self, value):
self.degree = value - 1
@property
def degree(self):
""" Degree.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the degree
:setter: Sets the degree
:type: int
"""
return self._degree[0]
@degree.setter
def degree(self, value):
val = int(value)
if val < 0:
raise ValueError("Degree cannot be less than zero")
# Clean up the curve points list
self.reset(evalpts=True)
# Set degree
self._degree[0] = val
@property
def knotvector(self):
""" Knot vector.
The knot vector will be normalized to [0, 1] domain if the class is initialized with ``normalize_kv=True``
argument.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the knot vector
:setter: Sets the knot vector
:type: list
"""
return self._knot_vector[0]
@knotvector.setter
def knotvector(self, value):
if self.degree == 0 or self._control_points is None or len(self._control_points) == 0:
raise ValueError("Set degree and control points first")
# Check knot vector validity
if not knotvector.check(self.degree, value, len(self._control_points)):
raise ValueError("Input is not a valid knot vector")
# Clean up the curve points lists
self.reset(evalpts=True)
# Set knot vector
self._knot_vector[0] = knotvector.normalize(value, decimals=self._precision) if self._kv_normalize else value
@property
def ctrlpts(self):
""" Control points.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the control points
:setter: Sets the control points
:type: list
"""
return self._control_points
@ctrlpts.setter
def ctrlpts(self, value):
self.set_ctrlpts(value)
@property
def sample_size(self):
""" Sample size.
Sample size defines the number of evaluated points to generate. It also sets the ``delta`` property.
The following figure illustrates the working principles of sample size property:
.. math::
\\underbrace {\\left[ {{u_{start}}, \\ldots ,{u_{end}}} \\right]}_{{n_{sample}}}
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets sample size
:setter: Sets sample size
:type: int
"""
ss = math.floor((1.0 / self.delta) + 0.5)
return int(ss)
@sample_size.setter
def sample_size(self, value):
if not isinstance(value, int):
raise ValueError("Sample size must be an integer value")
if self.knotvector is None or len(self.knotvector) == 0 or self.degree == 0:
warnings.warn("Cannot determine the delta value. Please set knot vector and degree before sample size.")
return
# To make it operate like linspace, we have to know the starting and ending points.
start = self.knotvector[self.degree]
stop = self.knotvector[-(self.degree+1)]
# Set delta value
self.delta = (stop - start) / float(value)
@property
def delta(self):
""" Evaluation delta.
Evaluation delta corresponds to the *step size* while ``evaluate`` function iterates on the knot vector to
generate curve points. Decreasing step size results in generation of more curve points.
Therefore; smaller the delta value, smoother the curve.
The following figure illustrates the working principles of the delta property:
.. math::
\\left[{{u_{start}},{u_{start}} + \\delta ,({u_{start}} + \\delta ) + \\delta , \\ldots ,{u_{end}}} \\right]
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
:getter: Gets the delta value
:setter: Sets the delta value
:type: float
"""
return self._delta[0]
@delta.setter
def delta(self, value):
# Delta value for surface evaluation should be between 0 and 1
if float(value) <= 0 or float(value) >= 1:
raise ValueError("Curve evaluation delta should be between 0.0 and 1.0")
# Clean up the curve points list
self.reset(evalpts=True)
# Set new delta value
self._delta[0] = float(value)
@property
def data(self):
""" Returns a dict which contains the geometry data.
Please refer to the `wiki <https://github.com/orbingol/NURBS-Python/wiki/Using-Python-Properties>`_ for details
on using this class member.
"""
return dict(
type=self.type,
rational=self.rational,
dimension=self.dimension,
pdimension=self.pdimension,
delta=tuple(self._delta),
sample_size=(self.sample_size,),
precision=self._precision,
degree=tuple(self._degree),
knotvector=tuple(self._knot_vector),
size=(self.ctrlpts_size,),
control_points=tuple(self._control_points)
)
def reverse(self):
""" Reverses the curve """
self._control_points = list(reversed(self._control_points))
max_k = self.knotvector[-1]
new_kv = [max_k - k for k in self.knotvector]
self._knot_vector[0] = list(reversed(new_kv))
self.reset(evalpts=True)
def set_ctrlpts(self, ctrlpts, *args, **kwargs):
""" Sets control points and checks if the data is consistent.
This method is designed to provide a consistent way to set control points whether they are weighted or not.
It directly sets the control points member of the class, and therefore it doesn't return any values.
The input will be an array of coordinates. If you are working in the 3-dimensional space, then your coordinates
will be an array of 3 elements representing *(x, y, z)* coordinates.
:param ctrlpts: input control points as a list of coordinates
:type ctrlpts: list
"""
# It is not necessary to input args for curves
if not args:
args = [len(ctrlpts)]
# Validate input
for arg, degree in zip(args, self._degree):
if degree <= 0:
raise GeomdlException("Set the degree first")
if arg < degree + 1:
raise GeomdlException("Number of control points should be at least degree + 1")
if len(ctrlpts[0]) < 2:
raise GeomdlException("A curve should be at least 2-dimensional")
if self.rational and len(ctrlpts[0]) < 3:
raise GeomdlException("Rational curves expect weighted control points, e.g. (x * w, y * w, w)")
# Clean up the curve and control points lists
self.reset(ctrlpts=True, evalpts=True)
# Call parent function
super(Curve, self).set_ctrlpts(ctrlpts, **kwargs)
def render(self, **kwargs):
""" Renders the curve using the visualization component
The visualization component must be set using :py:attr:`~vis` property before calling this method.
Keyword Arguments:
* ``cpcolor``: sets the color of the control points polygon
* ``evalcolor``: sets the color of the curve
* ``bboxcolor``: sets the color of the bounding box
* ``filename``: saves the plot with the input name
* ``plot``: controls plot window visibility. *Default: True*
* ``animate``: activates animation (if supported). *Default: False*
* ``extras``: adds line plots to the figure. *Default: None*
``plot`` argument is useful when you would like to work on the command line without any window context.
If ``plot`` flag is False, this method saves the plot as an image file (.png file where possible) and disables
plot window popping out. If you don't provide a file name, the name of the image file will be pulled from the
configuration class.
``extras`` argument can be used to add extra line plots to the figure. This argument expects a list of dicts
in the format described below:
.. code-block:: python
:linenos:
[
dict( # line plot 1
points=[[1, 2, 3], [4, 5, 6]], # list of points
name="My line Plot 1", # name displayed on the legend
color="red", # color of the line plot