Skip to content

Commit

Permalink
Fix: Handle unnamed index/dimension in wave.resource.surface_elevation (
Browse files Browse the repository at this point in the history
MHKiT-Software#341)

* Fix: If unnamed, set spectrum dim_0 name to "Frequency"

* Test: input spectrum without index name defined

* Fix: Use found frequency dimension name

* Test: input wave spectrum with unnamed index
  • Loading branch information
simmsa authored Aug 14, 2024
1 parent 09b9d7f commit e0d59c7
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
21 changes: 21 additions & 0 deletions mhkit/tests/wave/test_resource_spectrum.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,27 @@ def test_surface_elevation_rmse(self):

self.assertLess(rmse_sum, 0.02)

def test_mhkit_spectrum_without_frequency_index_name_defined(self):
S = wave.resource.jonswap_spectrum(self.f, self.Tp, self.Hs)
S.index.name = None

eta_ifft_xr = wave.resource.surface_elevation(S, self.t, seed=1, method="ifft")
eta_sos_xr = wave.resource.surface_elevation(
S, self.t, seed=1, method="sum_of_sines"
)

assert_allclose(eta_ifft_xr, eta_sos_xr)

def test_user_spectrum_without_frequency_index_name_defined(self):
spectra = pd.DataFrame({"magnitude": [1.0, 2.0, 3.0]}, index=[0.0, 1.0, 2.0])
time = [0.0, 1.0, 2.0]

result = wave.resource.surface_elevation(spectra, time, seed=1)

expected_magnitude = [-0.983917, 1.274248, -2.129812]

assert_allclose(result["magnitude"], expected_magnitude, atol=1e-6)

def test_ifft_sum_of_sines(self):
S = wave.resource.jonswap_spectrum(self.f, self.Tp, self.Hs)

Expand Down
9 changes: 5 additions & 4 deletions mhkit/wave/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ def surface_elevation(

if frequency_dimension == "":
frequency_dimension = list(S.coords)[0]

elif frequency_dimension not in list(S.dims):
raise ValueError(
f"frequency_dimension is not a dimension of S ({list(S.dims)}). Got: {frequency_dimension}."
Expand Down Expand Up @@ -366,8 +367,8 @@ def surface_elevation(
np.random.seed(seed)
phase = xr.DataArray(
data=2 * np.pi * np.random.rand(S[var].size),
dims="Frequency",
coords={"Frequency": f},
dims=frequency_dimension,
coords={frequency_dimension: f},
)
else:
phase = phases[var]
Expand All @@ -392,8 +393,8 @@ def surface_elevation(
B = B.reshape((len(time_index), len(omega)))
B = xr.DataArray(
data=B,
dims=["Time", "Frequency"],
coords={"Time": time_index, "Frequency": f},
dims=["Time", frequency_dimension],
coords={"Time": time_index, frequency_dimension: f},
)

# wave elevation
Expand Down

0 comments on commit e0d59c7

Please sign in to comment.