-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path_core.py
More file actions
1937 lines (1589 loc) · 60.5 KB
/
_core.py
File metadata and controls
1937 lines (1589 loc) · 60.5 KB
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
import copy
from abc import ABC, abstractmethod
from numbers import Number
import numpy as np
from scipy.integrate import trapezoid
from scipy.interpolate import interp2d
from scipy.special import gamma
def _robust_modulus(x, periodicity):
"""
Robust modulus operator.
Similar to ``x % periodicity``, but ensures that it is robust w.r.t. floating
point numbers.
"""
x = np.asarray_chkfinite(x % periodicity).copy()
return np.nextafter(x, -1, where=(x == periodicity), out=x)
def complex_to_polar(complex_vals, phase_degrees=False):
"""
Convert complex numbers to polar form (i.e., amplitude and phase).
Parameters
----------
complex_vals : array-like
Complex number values.
phase_degrees : bool
Whether the phase angles should be returned in 'degrees' (``True``) or
'radians' (``False``).
Returns
-------
amp : array
Amplitudes.
phase : array
Phase angles.
"""
complex_vals = np.asarray_chkfinite(complex_vals)
amp = np.abs(complex_vals)
phase = np.angle(complex_vals, deg=phase_degrees)
return amp, phase
def polar_to_complex(amp, phase, phase_degrees=False):
"""
Convert polar coordinates (i.e., amplitude and phase) to complex numbers.
Given as:
``A * exp(j * phi)``
where, ``A`` is the amplitude and ``phi`` is the phase.
Parameters
----------
amp : array-like
Amplitude values.
phase : array-like
Phase angle values.
phase_degrees : bool
Whether the phase angles are given in 'degrees'. If ``False``, 'radians'
is assumed.
Returns
-------
array :
Complex numbers.
"""
amp = np.asarray_chkfinite(amp)
phase = np.asarray_chkfinite(phase)
if phase_degrees:
phase = (np.pi / 180.0) * phase
if amp.shape != phase.shape:
raise ValueError()
return amp * np.exp(1j * phase)
def _check_is_similar(*grids, exact_type=True):
"""
Check if grid objects are similar.
"""
grids = list(grids)
grid_ref = grids.pop()
if exact_type:
type_ = type(grid_ref)
def check_type(grid, grid_type):
return type(grid) == grid_type
else:
type_ = Grid
check_type = isinstance
for grid_i in grids:
if not check_type(grid_i, type_):
raise TypeError("Object types are not similar.")
elif grid_ref._vals.shape != grid_i._vals.shape:
raise ValueError("Grid objects have different shape.")
elif np.any(grid_ref._freq != grid_i._freq) or np.any(
grid_ref._dirs != grid_i._dirs
):
raise ValueError(
"Grid objects have different frequency/direction coordinates."
)
elif grid_ref.wave_convention != grid_i.wave_convention:
raise ValueError("Grid objects have different wave conventions.")
def multiply(grid1, grid2, output_type="grid"):
"""
Multiply values (element-wise).
Parameters
----------
grid1 : obj
Grid object.
grid2 : obj
Grid object.
output_type : str {"grid", "rao", "directional_spectrum", "wave_spectrum"}
Output grid type.
"""
TYPE_MAP = {
"grid": Grid,
"rao": RAO,
"directional_spectrum": DirectionalSpectrum,
"wave_spectrum": WaveSpectrum,
}
if output_type not in TYPE_MAP:
raise ValueError("The given `output_type` is not valid.")
_check_is_similar(grid1, grid2, exact_type=False)
type_ = TYPE_MAP.get(output_type)
freq = grid1._freq
dirs = grid1._dirs
vals = np.multiply(grid1._vals, grid2._vals)
convention = grid1.wave_convention
new = Grid(
freq,
dirs,
vals,
freq_hz=False,
degrees=False,
**convention,
)
return type_.from_grid(new)
def _cast_to_grid(grid):
"""
Cast Grid-like object to ``Grid`` type.
Note that this type conversion may lead to loss of information/functionality
for derived classes.
"""
new = Grid(
*grid.grid(freq_hz=grid._freq_hz, degrees=grid._degrees),
freq_hz=grid._freq_hz,
degrees=grid._degrees,
**grid.wave_convention,
)
return new
def _check_foldable(dirs, degrees=False, sym_plane="xz"):
"""Checks that directions can be folded about a given symmetry plane"""
dirs = np.asarray_chkfinite(dirs).copy()
if len(dirs) == 0:
raise ValueError("`rao` is defined only at the bounds. Nothing to mirror.")
if degrees:
dirs = dirs * np.pi / 180.0
if sym_plane.lower() == "xz":
dirs_bools = np.sin(dirs) >= 0.0
error_msg = (
"`rao` must be defined in the range [0, 180] degrees or [180, 360) degrees."
)
elif sym_plane.lower() == "yz":
dirs_bools = np.cos(dirs) >= 0.0
error_msg = (
"`rao` must be defined in the range [90, 270] degrees or [270, 90] degrees."
)
else:
raise ValueError()
if not (all(dirs_bools) or all(~dirs_bools)):
raise ValueError(error_msg)
def _sort(dirs, vals):
"""
Sort directions and values according to (unsorted) directions.
"""
dirs = np.asarray_chkfinite(dirs)
vals = np.asarray_chkfinite(vals)
sorted_args = np.argsort(dirs)
return dirs[sorted_args], vals[:, sorted_args]
def mirror(rao, dof, sym_plane="xz"):
"""
Mirrors/folds an RAO object about a symmetry plane.
Requires that the RAO is defined for directions that allow folding with the
given symmetry plane. I.e., folding about the xz-plane requires that the RAO
is defined for directions in the range [0, 180] degrees or [180, 360] degrees.
Similarly, folding about the yz-plane requires that the RAO is defined for directions
in the range [90, 270] degrees or [270, 90] degrees.
Parameters
----------
rao : RAO
RAO object.
dof : {'surge', 'sway', 'heave', 'roll', 'pitch', 'yaw'}
Which degree-of-freedom the RAO object represents.
sym_plane : {'xz', 'yz'}
Symmetry plane, determining which axis to mirror the RAO about.
Returns
-------
rao : RAO
Extended (mirrored) RAO object.
Examples
--------
If you have an RAO defined only in half the directional domain (e.g., [0, 180] degrees),
you can mirror it once about a symmetry plane to obtain the 'full' RAO, defined over
the whole directional domain:
>>> # Symmetry about xz-plane
>>> rao_full = wr.mirror(rao, "heave", sym_plane="xz")
If you have an RAO defined only in one quadrant (e.g., [0, 90] degrees), you
can mirror it twise to obtain the 'full' RAO, defined over the whole directional
domain:
>>> # Symmetry about xz- and yz-plane
>>> rao_full = wr.mirror(
... wr.mirror(rao, "heave", sym_plane="xz"),
... "heave",
... sym_plane="yz"
... )
"""
sym_plane = sym_plane.lower()
dof = dof.lower()
freq, dirs, vals = rao.grid()
if dof not in ("surge", "sway", "heave", "roll", "pitch", "yaw"):
raise ValueError(
"`dof` must be 'surge', 'sway', 'heave', 'roll', 'pitch' or 'yaw'"
)
if rao._degrees:
periodicity = 360.0
else:
periodicity = 2 * np.pi
scale_phase = 1
if sym_plane == "xz":
bounds = (0.0, periodicity / 2.0)
if dof in ("sway", "roll", "yaw"):
scale_phase = -1
elif sym_plane == "yz":
bounds = (periodicity / 4.0, 3.0 * periodicity / 4.0)
if dof in ("surge", "pitch", "yaw"):
scale_phase = -1
else:
raise ValueError("`sym_plane` should be 'xz' or 'yz'")
lb_0, ub_0 = np.nextafter(bounds[0], (-periodicity, periodicity))
lb_1, ub_1 = np.nextafter(bounds[1], (-periodicity, periodicity))
exclude_bounds = ((dirs >= ub_0) | (dirs <= lb_0)) & (
((dirs >= ub_1) | (dirs <= lb_1))
)
_check_foldable(dirs[exclude_bounds], degrees=rao._degrees, sym_plane=sym_plane)
vals_folded = scale_phase * vals[:, exclude_bounds]
if sym_plane == "xz":
dirs_folded = -1 * dirs[exclude_bounds]
elif sym_plane == "yz":
dirs_folded = -1 * dirs[exclude_bounds] + periodicity / 2.0
vals_mirrored = np.concatenate((vals, vals_folded), axis=1)
dirs_mirrored = np.concatenate((dirs, dirs_folded))
dirs_mirrored = _robust_modulus(dirs_mirrored, periodicity)
dirs_mirrored, vals_mirrored = _sort(dirs_mirrored, vals_mirrored)
return RAO(
freq,
dirs_mirrored,
vals_mirrored,
degrees=rao._degrees,
freq_hz=rao._freq_hz,
**rao.wave_convention,
)
class Grid:
"""
Two-dimentional frequency/(wave)direction grid.
Parameters
----------
freq : array-like
1-D array of grid frequency coordinates. Positive and monotonically increasing.
dirs : array-like
1-D array of grid direction coordinates. Positive and monotonically increasing.
Must cover the directional range [0, 360) degrees (or [0, 2 * numpy.pi) radians).
vals : array-like (N, M)
Values associated with the grid. Should be a 2-D array of shape (N, M),
such that ``N=len(freq)`` and ``M=len(dirs)``.
freq_hz : bool
If frequency is given in 'Hz'. If ``False``, 'rad/s' is assumed.
degrees : bool
If direction is given in 'degrees'. If ``False``, 'radians' is assumed.
clockwise : bool
If positive directions are defined to be 'clockwise'. If ``False``, 'counterclockwise'
is assumed.
waves_coming_from : bool
If waves are 'coming from' the given directions. If ``False``, 'going towards'
convention is assumed.
"""
def __init__(
self,
freq,
dirs,
vals,
freq_hz=False,
degrees=False,
clockwise=False,
waves_coming_from=True,
):
self._freq = np.asarray_chkfinite(freq).copy()
self._dirs = np.asarray_chkfinite(dirs).copy()
self._vals = np.asarray_chkfinite(vals).copy()
self._clockwise = clockwise
self._waves_coming_from = waves_coming_from
self._freq_hz = freq_hz
self._degrees = degrees
if freq_hz:
self._freq = 2.0 * np.pi * self._freq
if degrees:
self._dirs = (np.pi / 180.0) * self._dirs
self._check_freq(self._freq)
self._check_dirs(self._dirs)
if self._vals.shape != (len(self._freq), len(self._dirs)):
raise ValueError(
"Values must have shape shape (N, M), such that ``N=len(freq)`` "
"and ``M=len(dirs)``."
)
@classmethod
def from_grid(cls, grid):
"""
Construct from a Grid object.
Parameters
----------
grid : obj
Grid object.
Returns
-------
cls :
Initialized object.
"""
return cls(
*grid.grid(freq_hz=grid._freq_hz, degrees=grid._degrees),
freq_hz=grid._freq_hz,
degrees=grid._degrees,
**grid.wave_convention,
)
def _check_freq(self, freq):
"""
Check frequency bins.
"""
if np.any(freq[:-1] >= freq[1:]) or freq[0] < 0:
raise ValueError(
"Frequencies must be positive and monotonically increasing."
)
def _check_dirs(self, dirs):
"""
Check direction bins.
"""
if np.any(dirs[:-1] >= dirs[1:]) or dirs[0] < 0 or dirs[-1] >= 2.0 * np.pi:
raise ValueError(
"Directions must be positive, monotonically increasing, and "
"be [0., 360.) degs (or [0., 2*pi) rads)."
)
def freq(self, freq_hz=None):
"""
Frequency coordinates.
Parameters
----------
freq_hz : bool
If frequencies should be returned in 'Hz'. If ``False``, 'rad/s' is used.
Defaults to original units used during initialization.
"""
freq = self._freq.copy()
if freq_hz is None:
freq_hz = self._freq_hz
if freq_hz:
freq = 1.0 / (2.0 * np.pi) * freq
return freq
def dirs(self, degrees=None):
"""
Direction coordinates.
Parameters
----------
degrees : bool
If directions should be returned in 'degrees'. If ``False``, 'radians'
is used. Defaults to original units used during initialization.
"""
dirs = self._dirs.copy()
if degrees is None:
degrees = self._degrees
if degrees:
dirs = (180.0 / np.pi) * dirs
return dirs
def grid(self, freq_hz=None, degrees=None):
"""
Return a copy of the object's frequency/direction coordinates and corresponding
grid values.
Parameters
----------
freq_hz : bool
If frequencies should be returned in 'Hz'. If ``False``, 'rad/s' is used.
Defaults to original units used during initialization.
degrees : bool
If directions should be returned in 'degrees'. If ``False``, 'radians'
is used. Defaults to original units used during initialization.
Returns
-------
freq : array
1-D array of grid frequency coordinates.
dirs : array
1-D array of grid direction coordinates.
vals : array (N, M)
Grid values as 2-D array of shape (N, M), such that ``N=len(freq)``
and ``M=len(dirs)``.
"""
freq = self.freq(freq_hz=freq_hz)
dirs = self.dirs(degrees=degrees)
vals = self._vals.copy()
return freq, dirs, vals
@property
def wave_convention(self):
"""
Wave direction convention.
"""
return {
"clockwise": self._clockwise,
"waves_coming_from": self._waves_coming_from,
}
def set_wave_convention(self, clockwise=True, waves_coming_from=True):
"""
Set wave direction convention.
Directions and values will be converted (in-place) to the given convention.
Parameters
----------
clockwise : bool
If positive directions are defined to be 'clockwise'. If ``False``,
'counterclockwise' is assumed.
waves_coming_from : bool
If waves are 'coming from' the given directions. If ``False``, 'going towards'
convention is assumed.
"""
conv_org = self.wave_convention
conv_new = {"clockwise": clockwise, "waves_coming_from": waves_coming_from}
self._freq, self._dirs, self._vals = self._convert(
self._freq, self._dirs, self._vals, conv_new, conv_org
)
self._clockwise = conv_new["clockwise"]
self._waves_coming_from = conv_new["waves_coming_from"]
def _convert(self, freq, dirs, vals, config_new, config_org):
"""
Convert grid from one wave convention to another.
"""
freq_org = np.asarray_chkfinite(freq).copy()
dirs_org = np.asarray_chkfinite(dirs).copy()
vals_org = np.asarray_chkfinite(vals).copy()
freq_new = freq_org
dirs_new = self._convert_dirs(dirs_org, config_new, config_org, degrees=False)
dirs_new, vals_new = _sort(dirs_new, vals_org)
return freq_new, dirs_new, vals_new
@staticmethod
def _convert_dirs(dirs, config_new, config_org, degrees=False):
"""
Convert wave directions from one convention to another.
Parameters
----------
dirs : float or array-like
Wave directions in 'radians' expressed according to 'original' convention.
config_new : dict
New wave direction convention.
config_org : dict
Original wave direction convention.
degrees : bool
If directions are given in 'degrees'. If ``False``, 'radians' is assumed.
Return
------
dirs : numpy.array
Wave directions in 'radians' expressed according to 'new' convention.
"""
dirs = np.asarray_chkfinite(dirs).copy()
if degrees:
periodicity = 360.0
else:
periodicity = 2.0 * np.pi
if config_new["waves_coming_from"] != config_org["waves_coming_from"]:
dirs -= periodicity / 2
if config_new["clockwise"] != config_org["clockwise"]:
dirs *= -1
return _robust_modulus(dirs, periodicity)
def copy(self):
"""Return a copy of the object."""
return copy.deepcopy(self)
def rotate(self, angle, degrees=False):
"""
Rotate the underlying grid coordinate system a given angle.
All directions are converted so that:
dirs_new = dirs_old - angle
Note that the direction of positive rotation follows the set 'wave convention'.
Parameters
----------
angle : float
Rotation angle.
degrees : bool
Whether the rotation angle is given in 'degrees'. If ``False``, 'radians'
is assumed.
Returns
-------
obj :
A copy of the object where the underlying coordinate system is rotated.
"""
if degrees:
angle = (np.pi / 180.0) * angle
new = self.copy()
dirs_new = _robust_modulus(new._dirs - angle, 2.0 * np.pi)
new._dirs, new._vals = _sort(dirs_new, new._vals)
return new
def _interpolate_function(self, complex_convert="rectangular", **kw):
"""
Interpolation function based on ``scipy.interpolate.interp2d``.
"""
xp = np.concatenate(
(self._dirs[-1:] - 2 * np.pi, self._dirs, self._dirs[:1] + 2.0 * np.pi)
)
yp = self._freq
zp = np.concatenate(
(
self._vals[:, -1:],
self._vals,
self._vals[:, :1],
),
axis=1,
)
if np.all(np.isreal(zp)):
return interp2d(xp, yp, zp, **kw)
elif complex_convert.lower() == "polar":
amp, phase = complex_to_polar(zp, phase_degrees=False)
interp_amp = interp2d(xp, yp, amp, **kw)
interp_phase = interp2d(xp, yp, phase, **kw)
return lambda *args, **kwargs: (
polar_to_complex(
interp_amp(*args, **kwargs),
interp_phase(*args, **kwargs),
phase_degrees=False,
)
)
elif complex_convert.lower() == "rectangular":
interp_real = interp2d(xp, yp, np.real(zp), **kw)
interp_imag = interp2d(xp, yp, np.imag(zp), **kw)
return lambda *args, **kwargs: (
interp_real(*args, **kwargs) + 1j * interp_imag(*args, **kwargs)
)
else:
raise ValueError("Unknown 'complex_convert' type")
def interpolate(
self,
freq,
dirs,
freq_hz=False,
degrees=False,
complex_convert="rectangular",
fill_value=0.0,
):
"""
Interpolate (linear) the grid values to match the given frequency and direction
coordinates.
A 'fill value' is used for extrapolation (i.e. `freq` outside the bounds
of the provided 2-D grid). Directions are treated as periodic.
Parameters
----------
freq : array-like
1-D array of grid frequency coordinates. Positive and monotonically increasing.
dirs : array-like
1-D array of grid direction coordinates. Positive and monotonically increasing.
freq_hz : bool
If frequency is given in 'Hz'. If ``False``, 'rad/s' is assumed.
degrees : bool
If direction is given in 'degrees'. If ``False``, 'radians' is assumed.
complex_convert : str, optional
How to convert complex number grid values before interpolating. Should
be 'rectangular' or 'polar'. If 'rectangular' (default), complex values
are converted to rectangular form (i.e., real and imaginary part) before
interpolating. If 'polar', the values are instead converted to polar
form (i.e., amplitude and phase) before interpolating. The values are
converted back to complex form after interpolation.
fill_value : float or None
The value used for extrapolation (i.e., `freq` outside the bounds of
the provided grid). If ``None``, values outside the frequency domain
are extrapolated via nearest-neighbor extrapolation. Note that directions
are treated as periodic (and will not need extrapolation).
Returns
-------
array :
Interpolated grid values.
Notes
-----
Apply 'polar' interpolation with caution as phase values are not "unwraped"
before interpolation. This may lead to some unexpected artifacts in the
results.
"""
freq = np.asarray_chkfinite(freq).reshape(-1)
dirs = np.asarray_chkfinite(dirs).reshape(-1)
if freq_hz:
freq = 2.0 * np.pi * freq
if degrees:
dirs = (np.pi / 180.0) * dirs
self._check_freq(freq)
self._check_dirs(dirs)
interp_fun = self._interpolate_function(
complex_convert=complex_convert, kind="linear", fill_value=fill_value
)
return interp_fun(dirs, freq, assume_sorted=True)
def reshape(
self,
freq,
dirs,
freq_hz=False,
degrees=False,
complex_convert="rectangular",
fill_value=0.0,
):
"""
Reshape the grid to match the given frequency/direction coordinates. Grid
values will be interpolated (linear).
Parameters
----------
freq : array-like
1-D array of new grid frequency coordinates. Positive and monotonically
increasing.
dirs : array-like
1-D array of new grid direction coordinates. Positive and monotonically increasing.
Must cover the directional range [0, 360) degrees (or [0, 2 * numpy.pi) radians).
freq_hz : bool
If frequency is given in 'Hz'. If ``False``, 'rad/s' is assumed.
degrees : bool
If direction is given in 'degrees'. If ``False``, 'radians' are assumed.
complex_convert : str, optional
How to convert complex number grid values before interpolating. Should
be 'rectangular' or 'polar'. If 'rectangular' (default), complex values
are converted to rectangular form (i.e., real and imaginary part) before
interpolating. If 'polar', the values are instead converted to polar
form (i.e., amplitude and phase) before interpolating. The values are
converted back to complex form after interpolation.
fill_value : float or None
The value used for extrapolation (i.e., `freq` outside the bounds of
the provided grid). If ``None``, values outside the frequency domain
are extrapolated via nearest-neighbor extrapolation. Note that directions
are treated as periodic (and will not need extrapolation).
Returns
-------
obj :
A copy of the object where the underlying coordinate system is reshaped.
"""
freq_new = np.asarray_chkfinite(freq).copy()
dirs_new = np.asarray_chkfinite(dirs).copy()
if freq_hz:
freq_new = 2.0 * np.pi * freq_new
if degrees:
dirs_new = (np.pi / 180.0) * dirs_new
self._check_freq(freq_new)
self._check_dirs(dirs_new)
vals_new = self.interpolate(
freq_new,
dirs_new,
freq_hz=False,
degrees=False,
complex_convert=complex_convert,
fill_value=fill_value,
)
new = self.copy()
new._freq, new._dirs, new._vals = freq_new, dirs_new, vals_new
return new
def bandpassed(self, freq_min = None, freq_max = None):
"""
Apply a bandpass filter to keep only the energy between the given frequencies [Hz].
A new object is returned where the grid is modified such that
- the bandpassed frequencies are included
- the frequencies outside the bandpass are removed
"""
freq_hz = self.freq(freq_hz=True)
if freq_min is None:
freq_min = min(freq_hz)
if freq_max is None:
freq_max = max(freq_hz)
assert freq_min < freq_max, "freq_min must be less than freq_max"
assert freq_min >= min(freq_hz), "freq_min must be greater than or equal to the minimum frequency in the grid"
assert freq_max <= max(freq_hz), "freq_max must be less than or equal to the maximum frequency in the grid"
new_freq = np.unique([*freq_hz, freq_min, freq_max])
new_freq.sort()
new_freq = new_freq[(new_freq >= freq_min) & (new_freq <= freq_max)]
return self.reshape(freq = new_freq,
dirs = self.dirs(degrees=True),
freq_hz = True,
degrees = True)
def __mul__(self, other):
"""
Multiply values (element-wise).
Both grids must have the same frequency/direction coordinates, and the same
'wave convention'.
Parameters
----------
other : obj or numeric
Grid object or number to be multiplied with.
Returns
-------
obj :
A copy of the object where the values are multiplied with values of
another grid.
"""
new = self.copy()
if isinstance(other, Number):
new._vals = new._vals * other
else:
_check_is_similar(self, other, exact_type=True)
new._vals = new._vals * other._vals
return new
def __rmul__(self, other):
return self.__mul__(other)
def __add__(self, other):
"""
Add values (element-wise).
Both grids must have the same frequency/direction coordinates, and the same
'wave convention'.
Parameters
----------
other : obj or numeric
Grid object or number to be added.
Returns
-------
obj :
A copy of the object where the values are added with another grid's values.
"""
new = self.copy()
if isinstance(other, Number):
new._vals = new._vals + other
else:
_check_is_similar(self, other, exact_type=True)
new._vals = new._vals + other._vals
return new
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
"""
Subtract values (element-wise).
Both grids must have the same frequency/direction coordinates, and the same
'wave convention'.
Parameters
----------
other : obj or numeric
Grid object or number to be subtracted.
Returns
-------
obj :
A copy of the object where the values are subtracted with another grid's values.
"""
new = self.copy()
if isinstance(other, Number):
new._vals = new._vals - other
else:
_check_is_similar(self, other, exact_type=True)
new._vals = new._vals - other._vals
return new
def __rsub__(self, other):
return self.__sub__(other)
def __repr__(self):
return "Grid"
def conjugate(self):
"""
Return a copy of the object with complex conjugate values.
"""
new = self.copy()
new._vals = new._vals.conjugate()
return new
@property
def real(self):
"""
Return a new Grid object where all values are converted to their real part.
"""
new = _cast_to_grid(self)
new._vals = new._vals.real
return new
@property
def imag(self):
"""
Return a new Grid object where all values are converted to their imaginary part.
"""
new = _cast_to_grid(self)
new._vals = new._vals.imag
return new
class DisableComplexMixin:
@property
def imag(self):
raise AttributeError(f"'{self}' object has no attribute 'imag'.")
@property
def real(self):
raise AttributeError(f"'{self}' object has no attribute 'real'.")
@property
def conjugate(self):
raise AttributeError(f"'{self}' object has no attribute 'conjugate'.")
class RAO(Grid):
"""
Response amplitude operator (RAO).
The ``RAO`` class extends the :class:`~waveresponse.Grid` class, and is a
two-dimensional frequency/(wave)direction grid. The RAO values represents a
transfer function that can be used to calculate a degree-of-freedom's response
based on a 2-D wave spectrum.
Parameters
----------
freq : array-like
1-D array of grid frequency coordinates. Positive and monotonically increasing.
dirs : array-like
1-D array of grid direction coordinates. Positive and monotonically increasing.
Should be within the directional range [0, 360) degrees (or [0, 2*pi) radians).
See Notes.
vals : array-like (N, M)
RAO values (complex) associated with the grid. Should be a 2-D array of shape (N, M),
such that ``N=len(freq)`` and ``M=len(dirs)``.
freq_hz : bool
If frequency is given in 'Hz'. If ``False``, 'rad/s' is assumed.
degrees : bool
If direction is given in 'degrees'. If ``False``, 'radians' is assumed.
clockwise : bool
If positive directions are defined to be 'clockwise'. If ``False``, 'counterclockwise'
is assumed.
waves_coming_from : bool
If waves are 'coming from' the given directions. If ``False``, 'going towards'
convention is assumed.
Notes
-----
If the RAO is going to be used in response calculation (where the RAO is combined
with a wave spectrum to form a response spectrum), it is important that the
RAO covers the full directional domain, i.e., [0, 360) degrees, with a sufficient
resolution. If the RAO object only partly covers the directional domain, you
can consider to use the :func:`mirror` function to 'expand' the RAO with values
that are folded about a symmetry plane.
"""
def __init__(
self,
freq,
dirs,
vals,
freq_hz=False,
degrees=False,
clockwise=False,
waves_coming_from=True,
):
super().__init__(
freq,
dirs,