-
Notifications
You must be signed in to change notification settings - Fork 14
/
curve.py
859 lines (738 loc) · 27.3 KB
/
curve.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
"""Classes for parameterized 3D space curves."""
import numbers
import numpy as np
from desc.backend import jnp, put
from desc.basis import FourierSeries
from desc.compute import rpz2xyz
from desc.grid import LinearGrid
from desc.io import InputReader
from desc.optimizable import optimizable_parameter
from desc.transform import Transform
from desc.utils import copy_coeffs, errorif, isposint
from .core import Curve
__all__ = ["FourierRZCurve", "FourierXYZCurve", "FourierPlanarCurve", "SplineXYZCurve"]
class FourierRZCurve(Curve):
"""Curve parameterized by Fourier series for R,Z in terms of toroidal angle phi.
Parameters
----------
R_n, Z_n: array-like
Fourier coefficients for R, Z.
modes_R : array-like, optional
Mode numbers associated with R_n. If not given defaults to [-n:n].
modes_Z : array-like, optional
Mode numbers associated with Z_n, If not given defaults to [-n:n]].
NFP : int
Number of field periods.
sym : bool
Whether to enforce stellarator symmetry.
name : str
Name for this curve.
"""
_io_attrs_ = Curve._io_attrs_ + [
"_R_n",
"_Z_n",
"_R_basis",
"_Z_basis",
"_sym",
"_NFP",
]
def __init__(
self,
R_n=10,
Z_n=0,
modes_R=None,
modes_Z=None,
NFP=1,
sym="auto",
name="",
):
super().__init__(name)
R_n, Z_n = np.atleast_1d(R_n), np.atleast_1d(Z_n)
if modes_R is None:
modes_R = np.arange(-(R_n.size // 2), R_n.size // 2 + 1)
if modes_Z is None:
modes_Z = np.arange(-(Z_n.size // 2), Z_n.size // 2 + 1)
if R_n.size == 0:
raise ValueError("At least 1 coefficient for R must be supplied")
if Z_n.size == 0:
Z_n = np.array([0.0])
modes_Z = np.array([0])
modes_R, modes_Z = np.asarray(modes_R), np.asarray(modes_Z)
assert R_n.size == modes_R.size, "R_n size and modes_R must be the same size"
assert Z_n.size == modes_Z.size, "Z_n size and modes_Z must be the same size"
assert issubclass(modes_R.dtype.type, np.integer)
assert issubclass(modes_Z.dtype.type, np.integer)
assert isposint(NFP)
if sym == "auto":
if np.all(R_n[modes_R < 0] == 0) and np.all(Z_n[modes_Z >= 0] == 0):
sym = True
else:
sym = False
self._sym = sym
NR = np.max(abs(modes_R))
NZ = np.max(abs(modes_Z))
N = max(NR, NZ)
self._NFP = int(NFP)
self._R_basis = FourierSeries(N, int(NFP), sym="cos" if sym else False)
self._Z_basis = FourierSeries(N, int(NFP), sym="sin" if sym else False)
self._R_n = copy_coeffs(R_n, modes_R, self.R_basis.modes[:, 2])
self._Z_n = copy_coeffs(Z_n, modes_Z, self.Z_basis.modes[:, 2])
@property
def sym(self):
"""Whether this curve has stellarator symmetry."""
return self._sym
@property
def R_basis(self):
"""Spectral basis for R_Fourier series."""
return self._R_basis
@property
def Z_basis(self):
"""Spectral basis for Z_Fourier series."""
return self._Z_basis
@property
def NFP(self):
"""Number of field periods."""
return self._NFP
@NFP.setter
def NFP(self, new):
assert (
isinstance(new, numbers.Real) and int(new) == new and new > 0
), f"NFP should be a positive integer, got {type(new)}"
self.change_resolution(NFP=new)
@property
def N(self):
"""Maximum mode number."""
return max(self.R_basis.N, self.Z_basis.N)
def change_resolution(self, N=None, NFP=None, sym=None):
"""Change the maximum toroidal resolution."""
if (
((N is not None) and (N != self.N))
or ((NFP is not None) and (NFP != self.NFP))
or (sym is not None)
and (sym != self.sym)
):
self._NFP = int(NFP if NFP is not None else self.NFP)
self._sym = sym if sym is not None else self.sym
N = int(N if N is not None else self.N)
R_modes_old = self.R_basis.modes
Z_modes_old = self.Z_basis.modes
self.R_basis.change_resolution(
N=N, NFP=self.NFP, sym="cos" if self.sym else self.sym
)
self.Z_basis.change_resolution(
N=N, NFP=self.NFP, sym="sin" if self.sym else self.sym
)
self.R_n = copy_coeffs(self.R_n, R_modes_old, self.R_basis.modes)
self.Z_n = copy_coeffs(self.Z_n, Z_modes_old, self.Z_basis.modes)
def get_coeffs(self, n):
"""Get Fourier coefficients for given mode number(s)."""
n = np.atleast_1d(n).astype(int)
R = np.zeros_like(n).astype(float)
Z = np.zeros_like(n).astype(float)
idxR = np.where(n[:, np.newaxis] == self.R_basis.modes[:, 2])
idxZ = np.where(n[:, np.newaxis] == self.Z_basis.modes[:, 2])
R[idxR[0]] = self.R_n[idxR[1]]
Z[idxZ[0]] = self.Z_n[idxZ[1]]
return R, Z
def set_coeffs(self, n, R=None, Z=None):
"""Set specific Fourier coefficients."""
n, R, Z = np.atleast_1d(n), np.atleast_1d(R), np.atleast_1d(Z)
R = np.broadcast_to(R, n.shape)
Z = np.broadcast_to(Z, n.shape)
for nn, RR, ZZ in zip(n, R, Z):
if RR is not None:
idxR = self.R_basis.get_idx(0, 0, nn)
self.R_n = put(self.R_n, idxR, RR)
if ZZ is not None:
idxZ = self.Z_basis.get_idx(0, 0, nn)
self.Z_n = put(self.Z_n, idxZ, ZZ)
@optimizable_parameter
@property
def R_n(self):
"""Spectral coefficients for R."""
return self._R_n
@R_n.setter
def R_n(self, new):
if len(new) == self.R_basis.num_modes:
self._R_n = jnp.asarray(new)
else:
raise ValueError(
f"R_n should have the same size as the basis, got {len(new)} for "
+ f"basis with {self.R_basis.num_modes} modes."
)
@optimizable_parameter
@property
def Z_n(self):
"""Spectral coefficients for Z."""
return self._Z_n
@Z_n.setter
def Z_n(self, new):
if len(new) == self.Z_basis.num_modes:
self._Z_n = jnp.asarray(new)
else:
raise ValueError(
f"Z_n should have the same size as the basis, got {len(new)} for "
+ f"basis with {self.Z_basis.num_modes} modes"
)
@classmethod
def from_input_file(cls, path):
"""Create a axis curve from Fourier coefficients in a DESC or VMEC input file.
Parameters
----------
path : Path-like or str
Path to DESC or VMEC input file.
Returns
-------
curve : FourierRZToroidalCurve
Axis with given Fourier coefficients.
"""
inputs = InputReader().parse_inputs(path)[-1]
curve = FourierRZCurve(
inputs["axis"][:, 1],
inputs["axis"][:, 2],
inputs["axis"][:, 0].astype(int),
inputs["axis"][:, 0].astype(int),
inputs["NFP"],
inputs["sym"],
)
return curve
def _unclose_curve(X, Y, Z):
if np.allclose([X[0], Y[0], Z[0]], [X[-1], Y[-1], Z[-1]], atol=1e-14):
closedX, closedY, closedZ = X.copy(), Y.copy(), Z.copy()
X, Y, Z = X[:-1], Y[:-1], Z[:-1]
flag = True
else:
closedX, closedY, closedZ = (
np.append(X, X[0]),
np.append(Y, Y[0]),
np.append(Z, Z[0]),
)
flag = False
return X, Y, Z, closedX, closedY, closedZ, flag
class FourierXYZCurve(Curve):
"""Curve parameterized by Fourier series for X,Y,Z in terms of arbitrary angle s.
Parameters
----------
X_n, Y_n, Z_n: array-like
Fourier coefficients for X, Y, Z
modes : array-like
mode numbers associated with X_n etc.
name : str
name for this curve
"""
_io_attrs_ = Curve._io_attrs_ + [
"_X_n",
"_Y_n",
"_Z_n",
"_X_basis",
"_Y_basis",
"_Z_basis",
]
def __init__(
self,
X_n=[0, 10, 2],
Y_n=[0, 0, 0],
Z_n=[-2, 0, 0],
modes=None,
name="",
):
super().__init__(name)
X_n, Y_n, Z_n = np.atleast_1d(X_n), np.atleast_1d(Y_n), np.atleast_1d(Z_n)
if modes is None:
modes = np.arange(-(X_n.size // 2), X_n.size // 2 + 1)
else:
modes = np.asarray(modes)
assert issubclass(modes.dtype.type, np.integer)
assert X_n.size == modes.size, "X_n and modes must be the same size"
assert Y_n.size == modes.size, "Y_n and modes must be the same size"
assert Z_n.size == modes.size, "Z_n and modes must be the same size"
N = np.max(abs(modes))
self._X_basis = FourierSeries(N, NFP=1, sym=False)
self._Y_basis = FourierSeries(N, NFP=1, sym=False)
self._Z_basis = FourierSeries(N, NFP=1, sym=False)
self._X_n = copy_coeffs(X_n, modes, self.X_basis.modes[:, 2])
self._Y_n = copy_coeffs(Y_n, modes, self.Y_basis.modes[:, 2])
self._Z_n = copy_coeffs(Z_n, modes, self.Z_basis.modes[:, 2])
@property
def X_basis(self):
"""Spectral basis for X Fourier series."""
return self._X_basis
@property
def Y_basis(self):
"""Spectral basis for Y Fourier series."""
return self._Y_basis
@property
def Z_basis(self):
"""Spectral basis for Z Fourier series."""
return self._Z_basis
@property
def N(self):
"""Maximum mode number."""
return max(self.X_basis.N, self.Y_basis.N, self.Z_basis.N)
def change_resolution(self, N=None):
"""Change the maximum angular resolution."""
if (N is not None) and (N != self.N):
N = int(N)
Xmodes_old = self.X_basis.modes
Ymodes_old = self.Y_basis.modes
Zmodes_old = self.Z_basis.modes
self.X_basis.change_resolution(N=N)
self.Y_basis.change_resolution(N=N)
self.Z_basis.change_resolution(N=N)
self.X_n = copy_coeffs(self.X_n, Xmodes_old, self.X_basis.modes)
self.Y_n = copy_coeffs(self.Y_n, Ymodes_old, self.Y_basis.modes)
self.Z_n = copy_coeffs(self.Z_n, Zmodes_old, self.Z_basis.modes)
def get_coeffs(self, n):
"""Get Fourier coefficients for given mode number(s)."""
n = np.atleast_1d(n).astype(int)
X = np.zeros_like(n).astype(float)
Y = np.zeros_like(n).astype(float)
Z = np.zeros_like(n).astype(float)
Xidx = np.where(n[:, np.newaxis] == self.X_basis.modes[:, 2])
Yidx = np.where(n[:, np.newaxis] == self.Y_basis.modes[:, 2])
Zidx = np.where(n[:, np.newaxis] == self.Z_basis.modes[:, 2])
X[Xidx[0]] = self.X_n[Xidx[1]]
Y[Yidx[0]] = self.Y_n[Yidx[1]]
Z[Zidx[0]] = self.Z_n[Zidx[1]]
return X, Y, Z
def set_coeffs(self, n, X=None, Y=None, Z=None):
"""Set specific Fourier coefficients."""
n, X, Y, Z = (
np.atleast_1d(n),
np.atleast_1d(X),
np.atleast_1d(Y),
np.atleast_1d(Z),
)
X = np.broadcast_to(X, n.shape)
Y = np.broadcast_to(Y, n.shape)
Z = np.broadcast_to(Z, n.shape)
for nn, XX in zip(n, X):
idx = self.X_basis.get_idx(0, 0, nn)
if XX is not None:
self.X_n = put(self.X_n, idx, XX)
for nn, YY in zip(n, Y):
idx = self.Y_basis.get_idx(0, 0, nn)
if YY is not None:
self.Y_n = put(self.Y_n, idx, YY)
for nn, ZZ in zip(n, Z):
idx = self.Z_basis.get_idx(0, 0, nn)
if ZZ is not None:
self.Z_n = put(self.Z_n, idx, ZZ)
@optimizable_parameter
@property
def X_n(self):
"""Spectral coefficients for X."""
return self._X_n
@X_n.setter
def X_n(self, new):
if len(new) == self.X_basis.num_modes:
self._X_n = jnp.asarray(new)
else:
raise ValueError(
f"X_n should have the same size as the basis, got {len(new)} for "
+ f"basis with {self.X_basis.num_modes} modes."
)
@optimizable_parameter
@property
def Y_n(self):
"""Spectral coefficients for Y."""
return self._Y_n
@Y_n.setter
def Y_n(self, new):
if len(new) == self.Y_basis.num_modes:
self._Y_n = jnp.asarray(new)
else:
raise ValueError(
f"Y_n should have the same size as the basis, got {len(new)} for "
+ f"basis with {self.Y_basis.num_modes} modes."
)
@optimizable_parameter
@property
def Z_n(self):
"""Spectral coefficients for Z."""
return self._Z_n
@Z_n.setter
def Z_n(self, new):
if len(new) == self.Z_basis.num_modes:
self._Z_n = jnp.asarray(new)
else:
raise ValueError(
f"Z_n should have the same size as the basis, got {len(new)} for "
+ f"basis with {self.Z_basis.num_modes} modes."
)
@classmethod
def from_values(cls, coords, N=10, s=None, basis="xyz", name=""):
"""Fit coordinates to FourierXYZCurve representation.
Parameters
----------
coords: ndarray
coordinates to fit a FourierXYZCurve object with.
N : int
Fourier resolution of the new X,Y,Z representation.
default is 10
s : ndarray or "arclength"
arbitrary curve parameter to use for the fitting.
Should be monotonic, 1D array of same length as
coords. if None, defaults linearly spaced in [0,2pi)
Alternative, can pass "arclength" to use normalized distance between points.
basis : {"rpz", "xyz"}
basis for input coordinates. Defaults to "xyz"
Returns
-------
curve : FourierXYZCurve
New representation of the curve parameterized by Fourier series for X,Y,Z.
"""
if basis == "xyz":
coords_xyz = coords
else:
coords_xyz = rpz2xyz(coords, phi=coords[:, 1])
X = coords_xyz[:, 0]
Y = coords_xyz[:, 1]
Z = coords_xyz[:, 2]
X, Y, Z, closedX, closedY, closedZ, input_curve_was_closed = _unclose_curve(
X, Y, Z
)
if isinstance(s, str):
assert s == "arclength", f"got unknown specification for s {s}"
# find equal arclength angle-like variable, and use that as theta
# L_along_curve / L = theta / 2pi
lengths = np.sqrt(
np.diff(closedX) ** 2 + np.diff(closedY) ** 2 + np.diff(closedZ) ** 2
)
thetas = 2 * np.pi * np.cumsum(lengths) / np.sum(lengths)
thetas = np.insert(thetas, 0, 0)
s = thetas[:-1]
elif s is None:
s = np.linspace(0, 2 * np.pi, X.size, endpoint=False)
else:
s = np.atleast_1d(s)
s = s[:-1] if input_curve_was_closed else s
errorif(
not np.all(np.diff(s) > 0),
ValueError,
"supplied s must be monotonically increasing",
)
errorif(s[0] < 0, ValueError, "s must lie in [0, 2pi]")
errorif(s[-1] > 2 * np.pi, ValueError, "s must lie in [0, 2pi]")
grid = LinearGrid(zeta=s, NFP=1, sym=False)
basis = FourierSeries(N=N, NFP=1, sym=False)
transform = Transform(grid, basis, build_pinv=True)
X_n = transform.fit(X)
Y_n = transform.fit(Y)
Z_n = transform.fit(Z)
return FourierXYZCurve(X_n=X_n, Y_n=Y_n, Z_n=Z_n, name=name)
class FourierPlanarCurve(Curve):
"""Curve that lies in a plane.
Parameterized by a point (the center of the curve), a vector (normal to the plane),
and a Fourier series defining the radius from the center as a function of
a polar angle theta.
Parameters
----------
center : array-like, shape(3,)
x,y,z coordinates of center of curve
normal : array-like, shape(3,)
x,y,z components of normal vector to planar surface
r_n : array-like
Fourier coefficients for radius from center as function of polar angle
modes : array-like
mode numbers associated with r_n
name : str
name for this curve
"""
_io_attrs_ = Curve._io_attrs_ + [
"_r_n",
"_center",
"_normal",
"_r_basis",
]
# Reference frame is centered at the origin with normal in the +Z direction.
# The curve is computed in this frame and then shifted/rotated to the correct frame.
def __init__(
self,
center=[10, 0, 0],
normal=[0, 1, 0],
r_n=2,
modes=None,
name="",
):
super().__init__(name)
r_n = np.atleast_1d(r_n)
if modes is None:
modes = np.arange(-(r_n.size // 2), r_n.size // 2 + 1)
else:
modes = np.asarray(modes)
assert issubclass(modes.dtype.type, np.integer)
assert r_n.size == modes.size, "r_n size and modes must be the same size"
N = np.max(abs(modes))
self._r_basis = FourierSeries(N, NFP=1, sym=False)
self._r_n = copy_coeffs(r_n, modes, self.r_basis.modes[:, 2])
self.normal = normal
self.center = center
@property
def r_basis(self):
"""Spectral basis for Fourier series."""
return self._r_basis
@property
def N(self):
"""Maximum mode number."""
return self.r_basis.N
def change_resolution(self, N=None):
"""Change the maximum angular resolution."""
if (N is not None) and (N != self.N):
N = int(N)
modes_old = self.r_basis.modes
self.r_basis.change_resolution(N=N)
self.r_n = copy_coeffs(self.r_n, modes_old, self.r_basis.modes)
@optimizable_parameter
@property
def center(self):
"""Center of planar curve polar coordinates."""
return self._center
@center.setter
def center(self, new):
if len(new) == 3:
self._center = np.asarray(new)
else:
raise ValueError(
"center should be a 3 element vector [cx, cy, cz], got {}".format(new)
)
@optimizable_parameter
@property
def normal(self):
"""Normal vector to plane."""
return self._normal
@normal.setter
def normal(self, new):
if len(np.asarray(new)) == 3:
self._normal = np.asarray(new) / np.linalg.norm(new)
else:
raise ValueError(
"normal should be a 3 element vector [nx, ny, nz], got {}".format(new)
)
@optimizable_parameter
@property
def r_n(self):
"""Spectral coefficients for r."""
return self._r_n
@r_n.setter
def r_n(self, new):
if len(np.asarray(new)) == self.r_basis.num_modes:
self._r_n = jnp.asarray(new)
else:
raise ValueError(
f"r_n should have the same size as the basis, got {len(new)} for "
+ f"basis with {self.r_basis.num_modes} modes."
)
def get_coeffs(self, n):
"""Get Fourier coefficients for given mode number(s)."""
n = np.atleast_1d(n).astype(int)
r = np.zeros_like(n).astype(float)
idx = np.where(n[:, np.newaxis] == self.r_basis.modes[:, 2])
r[idx[0]] = self.r_n[idx[1]]
return r
def set_coeffs(self, n, r=None):
"""Set specific Fourier coefficients."""
n, r = np.atleast_1d(n), np.atleast_1d(r)
r = np.broadcast_to(r, n.shape)
for nn, rr in zip(n, r):
idx = self.r_basis.get_idx(0, 0, nn)
if rr is not None:
self.r_n = put(self.r_n, idx, rr)
class SplineXYZCurve(Curve):
"""Curve parameterized by spline knots in X,Y,Z.
Parameters
----------
X, Y, Z: array-like
Points for X, Y, Z describing the curve. If the endpoint is included
(ie, X[0] == X[-1]), then the final point will be dropped.
knots : ndarray or "arclength"
arbitrary curve parameter values to use for spline knots,
should be a monotonic, 1D ndarray of same length as the input X,Y,Z.
If None, defaults to using an linearly spaced points in [0, 2pi) as the knots.
If supplied, should lie in [0,2pi].
Alternatively, the string "arclength" can be supplied to use the normalized
distance between points.
method : str
method of interpolation
- ``'nearest'``: nearest neighbor interpolation
- ``'linear'``: linear interpolation
- ``'cubic'``: C1 cubic splines (aka local splines)
- ``'cubic2'``: C2 cubic splines (aka natural splines)
- ``'catmull-rom'``: C1 cubic centripetal "tension" splines
- ``'cardinal'``: C1 cubic general tension splines. If used, default tension of
c = 0 will be used
- ``'monotonic'``: C1 cubic splines that attempt to preserve monotonicity in the
data, and will not introduce new extrema in the interpolated points
- ``'monotonic-0'``: same as `'monotonic'` but with 0 first derivatives at both
endpoints
name : str
name for this curve
"""
_io_attrs_ = Curve._io_attrs_ + ["_X", "_Y", "_Z", "_knots", "_method"]
def __init__(
self,
X,
Y,
Z,
knots=None,
method="cubic",
name="",
):
super().__init__(name)
X, Y, Z = np.atleast_1d(X), np.atleast_1d(Y), np.atleast_1d(Z)
X, Y, Z = np.broadcast_arrays(X, Y, Z)
X, Y, Z, closedX, closedY, closedZ, closed_flag = _unclose_curve(X, Y, Z)
self._X = X
self._Y = Y
self._Z = Z
if isinstance(knots, str):
assert knots == "arclength", f"got unknown arclength specification {knots}"
# find equal arclength angle-like variable, and use that as theta
# L_along_curve / L = theta / 2pi
lengths = np.sqrt(
np.diff(closedX) ** 2 + np.diff(closedY) ** 2 + np.diff(closedZ) ** 2
)
thetas = 2 * np.pi * np.cumsum(lengths) / np.sum(lengths)
thetas = np.insert(thetas, 0, 0)
knots = thetas[:-1]
elif knots is None:
knots = np.linspace(0, 2 * np.pi, len(self._X), endpoint=False)
else:
knots = np.atleast_1d(knots)
errorif(
not np.all(np.diff(knots) > 0),
ValueError,
"supplied knots must be monotonically increasing",
)
errorif(knots[0] < 0, ValueError, "knots must lie in [0, 2pi]")
errorif(knots[-1] > 2 * np.pi, ValueError, "knots must lie in [0, 2pi]")
knots = knots[:-1] if closed_flag else knots
self._knots = knots
self.method = method
@optimizable_parameter
@property
def X(self):
"""Coordinates for X."""
return self._X
@X.setter
def X(self, new):
if len(new) == len(self.knots):
self._X = jnp.asarray(new)
else:
raise ValueError(
"X should have the same size as the knots, "
+ f"got {len(new)} X values for {len(self.knots)} knots"
)
@optimizable_parameter
@property
def Y(self):
"""Coordinates for Y."""
return self._Y
@Y.setter
def Y(self, new):
if len(new) == len(self.knots):
self._Y = jnp.asarray(new)
else:
raise ValueError(
"Y should have the same size as the knots, "
+ f"got {len(new)} Y values for {len(self.knots)} knots"
)
@optimizable_parameter
@property
def Z(self):
"""Coordinates for Z."""
return self._Z
@Z.setter
def Z(self, new):
if len(new) == len(self.knots):
self._Z = jnp.asarray(new)
else:
raise ValueError(
"Z should have the same size as the knots, "
+ f"got {len(new)} Z values for {len(self.knots)} knots"
)
@property
def knots(self):
"""Knots for spline."""
return self._knots
@knots.setter
def knots(self, new):
if len(new) == len(self.knots):
knots = jnp.atleast_1d(jnp.asarray(new))
errorif(
not np.all(np.diff(knots) > 0),
ValueError,
"supplied knots must be monotonically increasing",
)
errorif(knots[0] < 0, ValueError, "knots must lie in [0, 2pi]")
errorif(knots[-1] > 2 * np.pi, ValueError, "knots must lie in [0, 2pi]")
self._knots = jnp.asarray(knots)
else:
raise ValueError(
"new knots should have the same size as the current knots, "
+ f"got {len(new)} new knots, but expected {len(self.knots)} knots"
)
@property
def N(self):
"""Number of knots in the spline."""
return self.knots.size
@property
def method(self):
"""Method of interpolation to use."""
return self._method
@method.setter
def method(self, new):
possible_methods = [
"nearest",
"linear",
"cubic",
"cubic2",
"catmull-rom",
"monotonic",
"monotonic-0",
"cardinal",
]
if new in possible_methods:
self._method = new
else:
raise ValueError(
"Method must be one of {possible_methods}, "
+ f"instead got unknown method {new} "
)
@classmethod
def from_values(cls, coords, knots=None, method="cubic", name="", basis="xyz"):
"""Create SplineXYZCurve from coordinate values.
Parameters
----------
coords: ndarray
Points for X, Y, Z describing the curve. If the endpoint is included
(ie, X[0] == X[-1]), then the final point will be dropped.
knots : ndarray
arbitrary curve parameter values to use for spline knots,
should be an 1D ndarray of same length as the input.
(input length in this case is determined by grid argument, since
the input coordinates come from
Curve.compute("x",grid=grid))
If None, defaults to using an equal-arclength angle as the knots
If supplied, will be rescaled to lie in [0,2pi]
method : str
method of interpolation
- `'nearest'`: nearest neighbor interpolation
- `'linear'`: linear interpolation
- `'cubic'`: C1 cubic splines (aka local splines)
- `'cubic2'`: C2 cubic splines (aka natural splines)
- `'catmull-rom'`: C1 cubic centripetal "tension" splines
name : str
name for this curve
basis : {"rpz", "xyz"}
basis for input coordinates. Defaults to "xyz"
Returns
-------
curve: SplineXYZCurve
New representation of the curve parameterized by splines in X,Y,Z.
"""
if basis == "rpz":
coords = rpz2xyz(coords)
return SplineXYZCurve(
coords[:, 0], coords[:, 1], coords[:, 2], knots, method, name
)