wavespectra 4.9.0__tar.gz → 4.10.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. {wavespectra-4.9.0/wavespectra.egg-info → wavespectra-4.10.0}/PKG-INFO +1 -5
  2. {wavespectra-4.9.0 → wavespectra-4.10.0}/README.rst +0 -4
  3. {wavespectra-4.9.0 → wavespectra-4.10.0}/pyproject.toml +7 -1
  4. {wavespectra-4.9.0 → wavespectra-4.10.0}/tests/test_partition.py +62 -0
  5. {wavespectra-4.9.0 → wavespectra-4.10.0}/tests/test_specarray.py +8 -0
  6. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/__init__.py +1 -1
  7. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/construct/__init__.py +1 -0
  8. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/construct/frequency.py +12 -14
  9. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/core/npstats.py +90 -13
  10. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/core/xrstats.py +54 -1
  11. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/partition/partition.py +29 -3
  12. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/specarray.py +127 -21
  13. {wavespectra-4.9.0 → wavespectra-4.10.0/wavespectra.egg-info}/PKG-INFO +1 -5
  14. {wavespectra-4.9.0 → wavespectra-4.10.0}/AUTHORS.rst +0 -0
  15. {wavespectra-4.9.0 → wavespectra-4.10.0}/LICENSE.txt +0 -0
  16. {wavespectra-4.9.0 → wavespectra-4.10.0}/setup.cfg +0 -0
  17. {wavespectra-4.9.0 → wavespectra-4.10.0}/setup.py +0 -0
  18. {wavespectra-4.9.0 → wavespectra-4.10.0}/tests/test_cli.py +0 -0
  19. {wavespectra-4.9.0 → wavespectra-4.10.0}/tests/test_combine_hp01.py +0 -0
  20. {wavespectra-4.9.0 → wavespectra-4.10.0}/tests/test_cookiecutter_template.py +0 -0
  21. {wavespectra-4.9.0 → wavespectra-4.10.0}/tests/test_reader_registry.py +0 -0
  22. {wavespectra-4.9.0 → wavespectra-4.10.0}/tests/test_specdataset.py +0 -0
  23. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/cli.py +0 -0
  24. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/construct/direction.py +0 -0
  25. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/core/__init__.py +0 -0
  26. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/core/attributes.py +0 -0
  27. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/core/attributes.yml +0 -0
  28. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/core/fitting.py +0 -0
  29. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/core/options.py +0 -0
  30. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/core/select.py +0 -0
  31. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/core/swan.py +0 -0
  32. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/core/utils.py +0 -0
  33. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/__init__.py +0 -0
  34. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/awac.py +0 -0
  35. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/dataset.py +0 -0
  36. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/datawell.py +0 -0
  37. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/era5.py +0 -0
  38. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/funwave.py +0 -0
  39. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/funwave_new.py +0 -0
  40. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/json.py +0 -0
  41. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/ncswan.py +0 -0
  42. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/ndbc.py +0 -0
  43. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/ndbc_ascii.py +0 -0
  44. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/netcdf.py +0 -0
  45. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/obscape.py +0 -0
  46. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/octopus.py +0 -0
  47. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/spotter.py +0 -0
  48. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/swan.py +0 -0
  49. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/triaxys.py +0 -0
  50. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/wavespectra.py +0 -0
  51. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/ww3.py +0 -0
  52. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/ww3_station.py +0 -0
  53. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/wwm.py +0 -0
  54. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/input/xwaves.py +0 -0
  55. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/output/__init__.py +0 -0
  56. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/output/funwave.py +0 -0
  57. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/output/json.py +0 -0
  58. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/output/netcdf.py +0 -0
  59. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/output/octopus.py +0 -0
  60. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/output/orcaflex.py +0 -0
  61. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/output/swan.py +0 -0
  62. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/output/ww3.py +0 -0
  63. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/output/ww3.yml +0 -0
  64. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/partition/__init__.py +0 -0
  65. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/partition/hanson_and_phillips_2001.py +0 -0
  66. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/partition/specpart/specpart.c +0 -0
  67. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/partition/specpart/specpart.h +0 -0
  68. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/partition/specpart/specpart_wrap.c +0 -0
  69. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/partition/tracking.py +0 -0
  70. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/plot.py +0 -0
  71. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra/specdataset.py +0 -0
  72. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra.egg-info/SOURCES.txt +0 -0
  73. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra.egg-info/dependency_links.txt +0 -0
  74. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra.egg-info/entry_points.txt +0 -0
  75. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra.egg-info/requires.txt +0 -0
  76. {wavespectra-4.9.0 → wavespectra-4.10.0}/wavespectra.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: wavespectra
3
- Version: 4.9.0
3
+ Version: 4.10.0
4
4
  Summary: Library for ocean wave spectra
5
5
  Author-email: Wavespectra Developers <r.guedes@oceanum.science>
6
6
  Maintainer-email: Rafael Guedes <r.guedes@oceanum.science>, Tom Durrant <t.durrant@oceanum.science>
@@ -85,10 +85,6 @@ Dynamic: license-file
85
85
  wavespectra
86
86
  ===========
87
87
 
88
- .. image:: https://deepwiki.com/badge.svg
89
- :target: https://deepwiki.com/wavespectra/wavespectra
90
- :alt: Ask DeepWiki
91
-
92
88
  .. image:: https://zenodo.org/badge/205463939.svg
93
89
  :target: https://zenodo.org/badge/latestdoi/205463939
94
90
  :alt: DOI
@@ -2,10 +2,6 @@
2
2
  wavespectra
3
3
  ===========
4
4
 
5
- .. image:: https://deepwiki.com/badge.svg
6
- :target: https://deepwiki.com/wavespectra/wavespectra
7
- :alt: Ask DeepWiki
8
-
9
5
  .. image:: https://zenodo.org/badge/205463939.svg
10
6
  :target: https://zenodo.org/badge/latestdoi/205463939
11
7
  :alt: DOI
@@ -125,6 +125,12 @@ filterwarnings = [
125
125
  "ignore:Setting the shape on a NumPy array has been deprecated:DeprecationWarning",
126
126
  ]
127
127
 
128
+ [tool.coverage.run]
129
+ # Measure the imported package rather than the `wavespectra/` directory so the
130
+ # reports name files relative to the repo root (wavespectra/specarray.py), which
131
+ # is what Coveralls needs to link them to the GitHub sources.
132
+ source_pkgs = ["wavespectra"]
133
+
128
134
  [tool.ruff]
129
135
  line-length = 88
130
136
 
@@ -164,7 +170,7 @@ select = ["E4", "E7", "E9", "F", "B015", "B018"]
164
170
  github_url = "https://github.com/wavespectra/wavespectra/"
165
171
 
166
172
  [tool.tbump.version]
167
- current = "4.9.0"
173
+ current = "4.10.0"
168
174
  regex = '''
169
175
  (?P<major>\d+)
170
176
  \.(?P<minor>\d+)
@@ -306,6 +306,68 @@ class TestPTM5(BasePTM):
306
306
  ds = self.pt.ptm5(fcut=0.1, interpolate=False)
307
307
  assert fcut not in ds.freq
308
308
 
309
+ @pytest.mark.parametrize("interpolate", [True, False])
310
+ @pytest.mark.parametrize("fcut", [None, 0.1, 0.2])
311
+ def test_partitions_add_up_to_spectra(self, fcut, interpolate):
312
+ """Energy at fcut must not be in both partitions, see issue #180."""
313
+ efth = self.dset.efth
314
+ if fcut is None:
315
+ fcut = float(efth.freq[5])
316
+ ds = Partition(efth).ptm5(fcut=fcut, interpolate=interpolate)
317
+ m0 = (ds.spec.hs() ** 2).sum("part")
318
+ np.testing.assert_allclose(m0, efth.spec.hs() ** 2, rtol=1e-5)
319
+
320
+ @pytest.mark.parametrize("interpolate", [True, False])
321
+ @pytest.mark.parametrize("fcut, part", [(0.01, 0), (1.0, 1)])
322
+ def test_fcut_outside_frequency_range(self, fcut, part, interpolate):
323
+ """All energy is in one partition and the frequencies are not changed."""
324
+ efth = self.dset.efth.sortby("dir")
325
+ ds = Partition(efth).ptm5(fcut=fcut, interpolate=interpolate)
326
+ xr.testing.assert_equal(ds.freq, efth.freq)
327
+ xr.testing.assert_allclose(ds.isel(part=part, drop=True), efth)
328
+ assert float(ds.isel(part=1 - part).max()) == 0
329
+
330
+ def test_bins_are_in_one_partition_if_not_interpolate(self):
331
+ """Bins at or below fcut are swell and those above are sea, as in WW3."""
332
+ efth = self.dset.efth.sortby("dir")
333
+ fcut = float(efth.freq[5])
334
+ ds = Partition(efth).ptm5(fcut=fcut, interpolate=False)
335
+ sea, swell = ds.isel(part=0, drop=True), ds.isel(part=1, drop=True)
336
+ assert float(sea.sel(freq=slice(None, fcut)).max()) == 0
337
+ assert float(swell.sel(freq=slice(fcut + 1e-6, None)).max()) == 0
338
+ xr.testing.assert_allclose(swell.sel(freq=fcut), efth.sel(freq=fcut))
339
+ xr.testing.assert_allclose(sea + swell, efth)
340
+
341
+ def test_bin_at_fcut_is_shared_if_interpolate(self):
342
+ """Bin at fcut is split in proportion to its width either side of fcut."""
343
+ efth = self.dset.efth.sortby("dir")
344
+ f0, fcut, f1 = efth.freq.values[4:7].astype("float64")
345
+ ds = Partition(efth).ptm5(fcut=float(efth.freq[5]), interpolate=True)
346
+ sea, swell = ds.isel(part=0, drop=True), ds.isel(part=1, drop=True)
347
+ ratio = sea.isel(freq=5) / efth.isel(freq=5)
348
+ np.testing.assert_allclose(ratio.max(), (f1 - fcut) / (f1 - f0), rtol=1e-5)
349
+ xr.testing.assert_allclose(sea + swell, efth)
350
+
351
+ def test_cutoff_is_closer_to_fcut_if_interpolate(self):
352
+ """Swell energy in a Pierson-Moskowitz spectrum against the exact value."""
353
+ fp, fcut = 0.1, 0.085
354
+ freq = 0.04 * 1.1 ** np.arange(25)
355
+ efth = xr.DataArray(
356
+ freq**-5 * np.exp(-1.25 * (fp / freq) ** 4),
357
+ coords={"freq": freq},
358
+ dims="freq",
359
+ name="efth",
360
+ ).expand_dims(dir=[0.0])
361
+ exact = np.exp(-1.25 * (fp / fcut) ** 4)
362
+ error = {}
363
+ for interpolate in [True, False]:
364
+ ds = efth.spec.partition.ptm5(fcut=fcut, interpolate=interpolate)
365
+ m0 = ds.spec.hs() ** 2
366
+ swell = float(m0.isel(part=1) / m0.sum("part"))
367
+ error[interpolate] = abs(swell / exact - 1)
368
+ assert error[True] < 0.05
369
+ assert error[False] > 0.2
370
+
309
371
 
310
372
  class TestHP01(BasePTM):
311
373
  def setup_class(self):
@@ -132,3 +132,11 @@ def test_partition_interface(dset_full):
132
132
  methods = ["ptm1", "ptm2", "ptm3", "ptm4", "ptm5"]
133
133
  for method in methods:
134
134
  assert method in dir(dset.spec.partition)
135
+
136
+
137
+ def test_dm_no_energy(dset):
138
+ ds = dset.isel(time=slice(0, 2)).copy(deep=True)
139
+ ds[{"time": 0}] = 0.0
140
+ dm = ds.spec.dm()
141
+ assert dm.isel(time=0).isnull().all()
142
+ assert dm.isel(time=1).values == pytest.approx(dset.isel(time=1).spec.dm().values)
@@ -16,7 +16,7 @@ except ImportError as exc:
16
16
  warnings.warn(f"Cannot import accessors at the main module level:\n{exc}")
17
17
 
18
18
 
19
- __version__ = "4.9.0"
19
+ __version__ = "4.10.0"
20
20
 
21
21
 
22
22
  def _import_functions(pkgname="input", prefix="read"):
@@ -79,6 +79,7 @@ def construct_partition(
79
79
 
80
80
  # Frequency-direction spectrum
81
81
  dset = efth1d * spread
82
+ dset.name = attrs.SPECNAME
82
83
  set_spec_attributes(dset)
83
84
 
84
85
  return dset.fillna(0.0)
@@ -9,6 +9,13 @@ from wavespectra.core.attributes import attrs
9
9
  from wavespectra.core import npstats
10
10
 
11
11
 
12
+ def _name_and_attrs(dsout):
13
+ """Name the 1D frequency spectrum and set its CF attributes (m2 s)."""
14
+ dsout.name = attrs.SPECNAME
15
+ dsout.attrs = dict(attrs.ATTRS[attrs.SPEC1DNAME])
16
+ return dsout
17
+
18
+
12
19
  def pierson_moskowitz(freq, fp, alpha=0.0081, hs=None, **kwargs):
13
20
  """Pierson and Moskowitz spectrum for fully developed seas (Pierson and Moskowitz, 1964).
14
21
 
@@ -38,9 +45,7 @@ def pierson_moskowitz(freq, fp, alpha=0.0081, hs=None, **kwargs):
38
45
  if hs is not None:
39
46
  dsout = scaled(dsout, hs)
40
47
 
41
- dsout.name = attrs.SPECNAME
42
-
43
- return dsout
48
+ return _name_and_attrs(dsout)
44
49
 
45
50
 
46
51
  def jonswap(
@@ -80,9 +85,7 @@ def jonswap(
80
85
  if hs is not None:
81
86
  dsout = scaled(dsout, hs)
82
87
 
83
- dsout.name = attrs.SPECNAME
84
-
85
- return dsout
88
+ return _name_and_attrs(dsout)
86
89
 
87
90
 
88
91
  def tma(
@@ -130,9 +133,7 @@ def tma(
130
133
  if hs is not None:
131
134
  dsout = scaled(dsout, hs)
132
135
 
133
- dsout.name = attrs.SPECNAME
134
-
135
- return dsout
136
+ return _name_and_attrs(dsout)
136
137
 
137
138
 
138
139
  def gaussian(freq, hs, fp, gw, **kwargs):
@@ -160,8 +161,7 @@ def gaussian(freq, hs, fp, gw, **kwargs):
160
161
  mo = (hs / 4) ** 2
161
162
  dsout = mo / (gw * np.sqrt(2 * pi)) * np.exp(-0.5 * ((freq - fp) / gw) ** 2)
162
163
  dsout = scaled(dsout, hs)
163
- dsout.name = attrs.SPECNAME
164
- return dsout
164
+ return _name_and_attrs(dsout)
165
165
 
166
166
 
167
167
  def conditional(
@@ -204,6 +204,4 @@ def conditional(
204
204
  ds_false = false_func(**arguments)
205
205
  dsout = xr.where(cond, ds_true, ds_false)
206
206
 
207
- dsout.name = attrs.SPECNAME
208
-
209
- return dsout
207
+ return _name_and_attrs(dsout)
@@ -43,7 +43,8 @@ def dm(spectrum, dir, freq):
43
43
  df = np.gradient(freq) if np.size(freq) > 1 else np.ones(1)
44
44
  dm = np.arctan2((moms * df).sum(axis=0), (momc * df).sum(axis=0))
45
45
  dm = (270 - R2D * dm) % 360.0
46
- return dm
46
+ e = (spectrum.sum(axis=1) * df).sum()
47
+ return dm if e > 0 else np.nan
47
48
 
48
49
 
49
50
  def hs(spectrum, freq, dir=None, tail=True):
@@ -176,13 +177,46 @@ def alpha(spectrum, freq, fp):
176
177
  return np.float32(term1 * term2)
177
178
 
178
179
 
179
- def tps(ipeak, spectrum, freq):
180
+ def _peak_parabola(ipeak, spectrum, freq, log=False):
181
+ """Coefficients of the parabola through the three bins around the spectral peak.
182
+
183
+ Args:
184
+ - ipeak (int): Index of the maximum energy density in frequency spectrum E(f).
185
+ - spectrum (1darray): Direction-integrated wave spectrum array E(f).
186
+ - freq (1darray): Wave frequency array.
187
+ - log (bool): Fit the parabola to the logarithm of the energy density as a
188
+ function of the logarithm of the frequency.
189
+
190
+ Returns:
191
+ - f1, f2 (float): Frequency of the bin before the peak and at the peak.
192
+ - e2 (float): Energy density at the peak bin.
193
+ - q12 (float): Slope between the bin before the peak and the peak bin.
194
+ - qa (float): Curvature of the parabola.
195
+ - log (bool): True if values are in logarithmic space, the linear space is
196
+ used if a bin around the peak has no energy.
197
+
198
+ """
199
+ f1, f2, f3 = freq[ipeak - 1 : ipeak + 2]
200
+ e1, e2, e3 = spectrum[ipeak - 1 : ipeak + 2]
201
+ log = log and e1 > 0 and e3 > 0 and f1 > 0
202
+ if log:
203
+ f1, f2, f3 = np.log(f1), np.log(f2), np.log(f3)
204
+ e1, e2, e3 = np.log(e1), np.log(e2), np.log(e3)
205
+ q12 = (e1 - e2) / (f1 - f2)
206
+ q13 = (e1 - e3) / (f1 - f3)
207
+ qa = (q13 - q12) / (f3 - f2)
208
+ return f1, f2, e2, q12, qa, log
209
+
210
+
211
+ def tps(ipeak, spectrum, freq, log=False):
180
212
  """Smooth peak wave period Tp.
181
213
 
182
214
  Args:
183
215
  - ipeak (int): Index of the maximum energy density in frequency spectrum E(f).
184
216
  - spectrum (1darray): Direction-integrated wave spectrum array E(f).
185
217
  - freq (1darray): Wave frequency array.
218
+ - log (bool): Fit the parabola to the logarithm of the energy density as a
219
+ function of the logarithm of the frequency.
186
220
 
187
221
  Returns:
188
222
  - tp (float): Period of the maximum energy density in the smooth spectrum.
@@ -195,17 +229,10 @@ def tps(ipeak, spectrum, freq):
195
229
  if not ipeak:
196
230
  return np.nan
197
231
  else:
198
- f1 = freq[ipeak - 1]
199
- f2 = freq[ipeak]
200
- f3 = freq[ipeak + 1]
201
- e1 = spectrum[ipeak - 1]
202
- e2 = spectrum[ipeak]
203
- e3 = spectrum[ipeak + 1]
204
- s12 = f1 + f2
205
- q12 = (e1 - e2) / (f1 - f2)
206
- q13 = (e1 - e3) / (f1 - f3)
207
- qa = (q13 - q12) / (f3 - f2)
208
- fp = (s12 - q12 / qa) / 2.0
232
+ f1, f2, e2, q12, qa, log = _peak_parabola(ipeak, spectrum, freq, log)
233
+ fp = (f1 + f2 - q12 / qa) / 2.0
234
+ if log:
235
+ fp = np.exp(fp)
209
236
  return np.float32(1.0 / fp)
210
237
 
211
238
 
@@ -230,6 +257,56 @@ def tp(ipeak, spectrum, freq):
230
257
  return np.float32(1.0 / freq[ipeak])
231
258
 
232
259
 
260
+ def eps(ipeak, spectrum, freq, log=False):
261
+ """Smooth peak energy density Ep.
262
+
263
+ Args:
264
+ - ipeak (int): Index of the maximum energy density in frequency spectrum E(f).
265
+ - spectrum (1darray): Direction-integrated wave spectrum array E(f).
266
+ - freq (1darray): Wave frequency array.
267
+ - log (bool): Fit the parabola to the logarithm of the energy density as a
268
+ function of the logarithm of the frequency.
269
+
270
+ Returns:
271
+ - ep (float): Maximum energy density in the smooth spectrum.
272
+
273
+ Note:
274
+ - The smooth peak energy density is the value at the peak of the parabolic
275
+ fit around the spectral peak that defines the smooth peak period `tps`.
276
+
277
+ """
278
+ if not ipeak:
279
+ return np.nan
280
+ else:
281
+ f1, f2, e2, q12, qa, log = _peak_parabola(ipeak, spectrum, freq, log)
282
+ q2 = q12 + qa * (f2 - f1)
283
+ ep = e2 - q2**2 / (4 * qa)
284
+ if log:
285
+ ep = np.exp(ep)
286
+ return ep
287
+
288
+
289
+ def ep(ipeak, spectrum, freq):
290
+ """Peak energy density Ep.
291
+
292
+ Args:
293
+ - ipeak (int): Index of the maximum energy density in frequency spectrum E(f).
294
+ - spectrum (1darray): Direction-integrated wave spectrum array E(f).
295
+ - freq (1darray): Wave frequency array.
296
+
297
+ Returns:
298
+ - ep (float): Maximum energy density in the frequency spectrum.
299
+
300
+ Note:
301
+ - Arg freq is only defined so the signature is consistent with eps function.
302
+
303
+ """
304
+ if not ipeak:
305
+ return np.nan
306
+ else:
307
+ return spectrum[ipeak]
308
+
309
+
233
310
  def dpspr(ipeak, fdspr):
234
311
  """Peak directional wave spread Dpspr.
235
312
 
@@ -141,12 +141,64 @@ def alpha(dset, smooth=True):
141
141
  return darr
142
142
 
143
143
 
144
- def peak_wave_period(dset, smooth=True):
144
+ def peak_energy(dset, smooth=True, log=False):
145
+ """Peak energy density in the frequency spectrum.
146
+
147
+ Args:
148
+ - dset (xr.DataArray, xr.Dataset): 1D spectra array or dataset in wavespectra
149
+ convention.
150
+ - smooth (bool): Choose between the smooth (eps) or the raw (ep) peak energy
151
+ density type.
152
+ - log (bool): Fit the parabola of the smooth type to the logarithm of the
153
+ energy density as a function of the logarithm of the frequency.
154
+
155
+ Returns:
156
+ - ep (xr.DataArray): Peak energy density data array.
157
+
158
+ Note:
159
+ - The peak is defined consistently with `peak_wave_period`: the smooth type
160
+ is the value at the peak of the parabolic fit that defines the smooth peak
161
+ period and the raw type is the value at the frequency of the raw one.
162
+
163
+ """
164
+ # Ensure DataArray
165
+ if isinstance(dset, xr.Dataset):
166
+ dset = dset[attrs.SPECNAME]
167
+
168
+ # Choose peak energy function
169
+ if smooth:
170
+ func = npstats.eps
171
+ else:
172
+ func = npstats.ep
173
+
174
+ # Ensure single chunk along input core dimensions
175
+ dset = dset.chunk({attrs.FREQNAME: None})
176
+
177
+ # Frequency Peaks
178
+ ipeak = dset.spec._peak(dset)
179
+
180
+ # Apply function over the full dataset
181
+ return xr.apply_ufunc(
182
+ func,
183
+ ipeak.astype("int64"),
184
+ dset.astype("float64"),
185
+ dset[attrs.FREQNAME].astype("float32"),
186
+ input_core_dims=[[], [attrs.FREQNAME], [attrs.FREQNAME]],
187
+ kwargs={"log": log} if smooth else {},
188
+ vectorize=True,
189
+ dask="parallelized",
190
+ output_dtypes=["float64"],
191
+ )
192
+
193
+
194
+ def peak_wave_period(dset, smooth=True, log=False):
145
195
  """Smooth Peak wave period Tp.
146
196
 
147
197
  Args:
148
198
  - dset (xr.DataArray, xr.Dataset): 1D spectra array or dataset in wavespectra convention.
149
199
  - smooth (bool): Choose between the smooth (tps) or the raw (tp) peak wave period type.
200
+ - log (bool): Fit the parabola of the smooth type to the logarithm of the
201
+ energy density as a function of the logarithm of the frequency.
150
202
 
151
203
  Returns:
152
204
  - tp (xr.DataArray): Peak wave period data array.
@@ -175,6 +227,7 @@ def peak_wave_period(dset, smooth=True):
175
227
  dset.astype("float64"),
176
228
  dset[attrs.FREQNAME].astype("float32"),
177
229
  input_core_dims=[[], [attrs.FREQNAME], [attrs.FREQNAME]],
230
+ kwargs={"log": log} if smooth else {},
178
231
  vectorize=True,
179
232
  dask="parallelized",
180
233
  output_dtypes=["float32"],
@@ -617,9 +617,23 @@ class Partition:
617
617
  where the 0th index is the wind sea and the 1st index is the swell.
618
618
 
619
619
  Note:
620
+ - The energy in each frequency bin is distributed between the sea and
621
+ the swell so the partitions add up to the spectra they are defined
622
+ from.
620
623
  - Spectra are interpolated at `fcut` if this frequency is not in `dset`
621
624
  and `interpolate` is set to True which implies the frequency coordinates
622
- will be different between the input and the output.
625
+ will be different between the input and the output. The energy in the
626
+ bin at `fcut` is shared between the sea and the swell in proportion
627
+ to the width of that bin above and below `fcut`, so that the spectra
628
+ are split at `fcut`.
629
+ - The frequency bins at or below `fcut` are entirely assigned to the
630
+ swell and those above it to the sea if `interpolate` is set to False,
631
+ as in WW3. The spectra are effectively split at the limit between two
632
+ frequency bins in this case rather than at `fcut`.
633
+ - Spectra are not interpolated if `fcut` is not within the frequency
634
+ range of `dset`, in which case all the energy is assigned to the sea
635
+ (`fcut` below the lowest frequency) or to the swell (`fcut` at or
636
+ above the highest frequency).
623
637
 
624
638
  References:
625
639
  - WW3 documentation (https://github.com/NOAA-EMC/WW3).
@@ -627,15 +641,27 @@ class Partition:
627
641
  """
628
642
  dsout = self.dset.sortby("dir").sortby("freq")
629
643
 
644
+ # Spectra are only split at fcut if it is within the frequency range
645
+ freq = dsout[attrs.FREQNAME]
646
+ interpolate = interpolate and float(freq[0]) < fcut < float(freq[-1])
647
+
630
648
  # Include cuttof if not in coordinates
631
649
  if interpolate:
632
650
  freqs = sorted(set(self.dset.freq.values).union([fcut]))
633
651
  if len(freqs) > self.dset.freq.size:
634
652
  dsout = regrid_spec(self.dset, freq=freqs)
653
+ freq = dsout[attrs.FREQNAME]
654
+
655
+ # Fraction of the energy in each frequency bin assigned to the sea
656
+ sea = (freq > fcut).astype(dsout.dtype)
657
+ if interpolate:
658
+ icut = int(np.abs(freq.values - fcut).argmin())
659
+ flow, fhigh = freq.values[[icut - 1, icut + 1]]
660
+ sea[icut] = (fhigh - fcut) / (fhigh - flow)
635
661
 
636
662
  # Zero data outside the domain of each partition
637
- hf = dsout.where((dsout.freq >= fcut))
638
- lf = dsout.where((dsout.freq <= fcut))
663
+ hf = dsout * sea
664
+ lf = dsout * (1 - sea)
639
665
 
640
666
  # Combining into part index
641
667
  dsout = xr.concat([hf, lf], dim="part")
@@ -420,19 +420,75 @@ class SpecArray(object):
420
420
  fp.attrs.update(self._get_cf_attributes(self._my_name()))
421
421
  return fp.rename(self._my_name())
422
422
 
423
- def momf(self, mom=0):
423
+ def momf(self, mom=0, tail=False, tail_power=4):
424
424
  """Frequency moment.
425
425
 
426
426
  Args:
427
427
  - mom (int): Moment to calculate.
428
+ - tail (bool): if True add the contribution of a diagnostic
429
+ high-frequency tail beyond the last frequency of the spectrum.
430
+ - tail_power (float): Power n of the :math:`f^{-n}` tail, only used
431
+ if `tail` is True. The default of 4 is the one used by SWAN with
432
+ its default physics.
428
433
 
429
434
  Returns:
430
- - mf (DataArray): The mth frequency moments for each direction.
435
+ - mf (DataArray): The mth frequency moment of the spectra.
436
+
437
+ Note:
438
+ - The tail is the power law :math:`E(f)=E(f_N)(f/f_N)^{-n}` fitted to
439
+ the energy density at the last frequency :math:`f_N` and integrated
440
+ analytically from the upper edge of the last frequency bin
441
+ :math:`f_e=f_N+\\Delta f_N/2`, where the discrete integration ends,
442
+ to infinity. It adds
443
+ :math:`E(f_N)f_N^{m+1}(f_e/f_N)^{-p}/p` to the mth moment, with
444
+ :math:`p=n-1-m`.
445
+ - This is the approach used in SWAN to integrate output parameters
446
+ such as Tm01 and Tm02. The tail power in SWAN is defined by the
447
+ `PWTAIL` parameter which is 4 by default (physics KOMEN, WESTH and
448
+ ST6) and 5 with physics JANSSEN, GEN1 and GEN2; use the same value
449
+ in `tail_power` to compare against SWAN integrated parameters.
450
+ - The default `tail_power` of 4 follows the SWAN default since
451
+ matching the mean periods integrated by the model is the main
452
+ use of the tail, and it corresponds to the equilibrium range of
453
+ wind sea spectra. Note it differs from the :math:`f^{-5}` tail
454
+ assumed in :meth:`hs`, for which the tail contribution is small.
455
+ - The tail is added regardless of the last frequency of the spectrum
456
+ and it is only meaningful if that frequency is well above the peak.
457
+ - The moment of the tail is only finite if `tail_power > mom + 1`.
431
458
 
432
459
  """
433
460
  fp = self.freq**mom
434
- mf = self.df * fp * self.oned()
435
- return mf.sum(dim=attrs.FREQNAME, skipna=False).rename(f"mom{mom:0.0f}")
461
+ Sf = self.oned()
462
+ mf = (self.df * fp * Sf).sum(dim=attrs.FREQNAME, skipna=False)
463
+ if tail:
464
+ mf = mf + self._momf_tail(Sf, mom, tail_power)
465
+ return mf.rename(f"mom{mom:0.0f}")
466
+
467
+ def _momf_tail(self, Sf, mom, tail_power):
468
+ """Contribution of a high-frequency power law tail to a frequency moment.
469
+
470
+ Args:
471
+ - Sf (DataArray): One-dimensional frequency spectra.
472
+ - mom (int): Moment to calculate.
473
+ - tail_power (float): Power n of the f^-n tail.
474
+
475
+ Returns:
476
+ - mf (DataArray): The mth frequency moment of the tail integrated
477
+ from the upper edge of the last frequency bin to infinity.
478
+
479
+ """
480
+ power = tail_power - 1 - mom
481
+ if power <= 0:
482
+ raise ValueError(
483
+ f"The moment {mom} of a f^-{tail_power} tail is not finite, "
484
+ f"tail_power must be greater than {mom + 1}"
485
+ )
486
+ if self.freq.size < 2:
487
+ raise ValueError("Cannot fit a tail to spectra with a single frequency")
488
+ fmax = float(self.freq[-1])
489
+ fedge = fmax + 0.5 * float(self.df[-1])
490
+ factor = fmax ** (mom + 1) * (fedge / fmax) ** -power / power
491
+ return factor * Sf.isel({attrs.FREQNAME: -1}, drop=True)
436
492
 
437
493
  def momd(self, mom=0, theta=90.0):
438
494
  """Directional moment.
@@ -454,26 +510,44 @@ class SpecArray(object):
454
510
  mcos = (self.dd * self._obj * cp).sum(dim=attrs.DIRNAME, skipna=False)
455
511
  return msin, mcos
456
512
 
457
- def tm01(self):
513
+ def tm01(self, tail=False, tail_power=4):
458
514
  """Mean absolute wave period Tm01.
459
515
 
460
516
  True average period from the 1st spectral moment.
461
517
 
518
+ Args:
519
+ - tail (bool): if True add the contribution of a diagnostic
520
+ high-frequency tail beyond the last frequency to the spectral
521
+ moments, see :meth:`momf`.
522
+ - tail_power (float): Power n of the :math:`f^{-n}` tail, only used
523
+ if `tail` is True. The default of 4 is the one used by SWAN with
524
+ its default physics so the result is comparable to the SWAN
525
+ integrated output, see :meth:`momf`.
526
+
462
527
  """
463
- m0 = self.momf(0)
464
- m1 = self.momf(1)
528
+ m0 = self.momf(0, tail=tail, tail_power=tail_power)
529
+ m1 = self.momf(1, tail=tail, tail_power=tail_power)
465
530
  tm01 = m0 / m1
466
531
  tm01.attrs.update(self._get_cf_attributes(self._my_name()))
467
532
  return tm01.rename(self._my_name())
468
533
 
469
- def tm02(self):
534
+ def tm02(self, tail=False, tail_power=4):
470
535
  """Mean absolute wave period Tm02.
471
536
 
472
537
  Average period of zero up-crossings (Zhang, 2011).
473
538
 
539
+ Args:
540
+ - tail (bool): if True add the contribution of a diagnostic
541
+ high-frequency tail beyond the last frequency to the spectral
542
+ moments, see :meth:`momf`.
543
+ - tail_power (float): Power n of the :math:`f^{-n}` tail, only used
544
+ if `tail` is True. The default of 4 is the one used by SWAN with
545
+ its default physics so the result is comparable to the SWAN
546
+ integrated output, see :meth:`momf`.
547
+
474
548
  """
475
- m0 = self.momf(0)
476
- m2 = self.momf(2)
549
+ m0 = self.momf(0, tail=tail, tail_power=tail_power)
550
+ m2 = self.momf(2, tail=tail, tail_power=tail_power)
477
551
  tm02 = np.sqrt(m0 / m2)
478
552
  tm02.attrs.update(self._get_cf_attributes(self._my_name()))
479
553
  return tm02.rename(self._my_name())
@@ -492,7 +566,8 @@ class SpecArray(object):
492
566
  (moms * self.df).sum(dim=attrs.FREQNAME, skipna=False),
493
567
  (momc * self.df).sum(dim=attrs.FREQNAME, skipna=False),
494
568
  )
495
- dm = (270 - R2D * dm) % 360.0
569
+ e = (self.oned() * self.df).sum(dim=attrs.FREQNAME)
570
+ dm = ((270 - R2D * dm) % 360.0).where(e > 0)
496
571
  dm.attrs.update(self._get_cf_attributes(self._my_name()))
497
572
  return dm.rename(self._my_name())
498
573
 
@@ -586,18 +661,27 @@ class SpecArray(object):
586
661
  swe.attrs.update(self._get_cf_attributes(self._my_name()))
587
662
  return swe.rename(self._my_name())
588
663
 
589
- def sw(self):
664
+ def sw(self, tail=False, tail_power=4):
590
665
  """Spectral width parameter by Longuet-Higgins (1975).
591
666
 
592
667
  Represents energy distribution over entire frequency range.
593
668
 
669
+ Args:
670
+ - tail (bool): if True add the contribution of a diagnostic
671
+ high-frequency tail beyond the last frequency to the spectral
672
+ moments, see :meth:`momf`.
673
+ - tail_power (float): Power n of the :math:`f^{-n}` tail, only used
674
+ if `tail` is True. The default of 4 is the one used by SWAN with
675
+ its default physics so the result is comparable to the SWAN
676
+ integrated output, see :meth:`momf`.
677
+
594
678
  Reference:
595
679
  - Longuet-Higgins (1975).
596
680
 
597
681
  """
598
- m0 = self.momf(0)
599
- m1 = self.momf(1)
600
- m2 = self.momf(2)
682
+ m0 = self.momf(0, tail=tail, tail_power=tail_power)
683
+ m1 = self.momf(1, tail=tail, tail_power=tail_power)
684
+ m2 = self.momf(2, tail=tail, tail_power=tail_power)
601
685
  sw = (m0 * m2 / m1**2 - 1.0) ** 0.5
602
686
  sw.attrs.update(self._get_cf_attributes(self._my_name()))
603
687
  return sw.where(self.hs() >= 0.001).rename(self._my_name())
@@ -629,22 +713,44 @@ class SpecArray(object):
629
713
  """
630
714
  return xrstats.alpha(self.oned(), smooth=smooth)
631
715
 
632
- def gamma(self, smooth=True, scaled=True):
716
+ def gamma(self, smooth=True, scaled=True, log_parabola=False):
633
717
  """Jonswap peak enhancement factor gamma.
634
718
 
635
719
  Represents the ratio between the peak in the frequency spectrum :math:`E(f)`
636
720
  and its associate Pierson-Moskowitz shape.
637
721
 
638
- Args:
639
- - smooth (bool): True for the smooth wave frequency, False for the discrete
640
- frequency corresponding to the peak in the frequency spectrum.
722
+ Args:
723
+ - smooth (bool): True to define the peak of the frequency spectrum, both
724
+ its frequency and its energy density, from a parabolic fit around the
725
+ largest frequency bin, False to define it from the largest bin itself.
641
726
  - scaled (bool): True to apply polynomial approximation to gamma.
727
+ - log_parabola (bool): True to fit the parabola to the logarithm of the
728
+ energy density as a function of the logarithm of the frequency, False
729
+ to fit it to the energy density as a function of frequency. Only
730
+ supported with `smooth=True`.
731
+
732
+ Note:
733
+ - Gamma depends on where the spectral peak lies relative to the frequency
734
+ bins because the peak is underestimated if it lies between two bins.
735
+ The parabolic fit reduces but does not remove this dependency which is
736
+ small in finely resolved spectra but may be large in the 10% frequency
737
+ grids typical of spectral wave models, where gamma may be up to about
738
+ 25% (:math:`\\gamma=3.3`) or 40% (:math:`\\gamma=7`) too low.
739
+ - The default parabolic fit follows the definition in WAVEWATCH III,
740
+ the ratio with `scaled=False` corresponds to its peak enhancement
741
+ parameter. The spectral peak is closer to a parabola in logarithmic
742
+ space so `log_parabola=True` is more accurate, reducing those errors
743
+ to about 15% and 30%.
744
+ - Consider :meth:`fit_jonswap` if the spectral resolution is coarse.
642
745
 
643
746
  """
644
- fp = self.fp(smooth=smooth)
747
+ if log_parabola and not smooth:
748
+ raise ValueError("log_parabola=True is only supported with smooth=True")
749
+ ef = self.oned()
750
+ fp = 1 / xrstats.peak_wave_period(ef, smooth=smooth, log=log_parabola)
645
751
  alpha_pm = 0.3125 * self.hs() ** 2 * fp**4
646
752
  epm_fp = alpha_pm * fp**-5 * 0.2865048
647
- gamma = self.oned().max(dim=attrs.FREQNAME) / epm_fp
753
+ gamma = xrstats.peak_energy(ef, smooth=smooth, log=log_parabola) / epm_fp
648
754
  if scaled:
649
755
  # polynomial approximation for gamma
650
756
  p = [0.0378375, -0.13543292, 0.64087366, 0.32524949, 0.12974958]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: wavespectra
3
- Version: 4.9.0
3
+ Version: 4.10.0
4
4
  Summary: Library for ocean wave spectra
5
5
  Author-email: Wavespectra Developers <r.guedes@oceanum.science>
6
6
  Maintainer-email: Rafael Guedes <r.guedes@oceanum.science>, Tom Durrant <t.durrant@oceanum.science>
@@ -85,10 +85,6 @@ Dynamic: license-file
85
85
  wavespectra
86
86
  ===========
87
87
 
88
- .. image:: https://deepwiki.com/badge.svg
89
- :target: https://deepwiki.com/wavespectra/wavespectra
90
- :alt: Ask DeepWiki
91
-
92
88
  .. image:: https://zenodo.org/badge/205463939.svg
93
89
  :target: https://zenodo.org/badge/latestdoi/205463939
94
90
  :alt: DOI
File without changes
File without changes
File without changes
File without changes