Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,013 changes: 655 additions & 358 deletions examples/adcp_example.ipynb

Large diffs are not rendered by default.

80 changes: 40 additions & 40 deletions examples/adv_example.ipynb

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions mhkit/acoustics/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
import numpy as np
import xarray as xr

from mhkit.dolfyn import VelBinner
from mhkit.utils import Binner


def _check_numeric(value, name: str):
Expand Down Expand Up @@ -247,7 +247,7 @@ def sound_pressure_spectral_density(
nfft = nbin

# Use dolfyn PSD functionality
binner = VelBinner(fs=fs, n_bin=nbin, n_fft=nfft)
binner = Binner(fs=fs, n_bin=nbin, n_fft=nfft)
# Sound pressure spectral densities with 50% overlap between FFT windows
psd = binner.power_spectral_density(
pressure, freq_units="Hz", window="hann", pct_overlap=pct_overlap
Expand Down
6 changes: 3 additions & 3 deletions mhkit/acoustics/spsdl.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import numpy as np
import xarray as xr

from mhkit.dolfyn.time import epoch2dt64, dt642epoch
from mhkit.utils.time_utils import epoch_to_dt64, dt64_to_epoch
from .analysis import _check_numeric, _fmax_warning, create_frequency_bands


Expand Down Expand Up @@ -350,8 +350,8 @@ def time_aggregate(
)
time_bins_upper = time_bins_lower + window
time_bins = np.append(time_bins_lower, time_bins_upper[-1])
center_time = epoch2dt64(
0.5 * (dt642epoch(time_bins_lower) + dt642epoch(time_bins_upper))
center_time = epoch_to_dt64(
0.5 * (dt64_to_epoch(time_bins_lower) + dt64_to_epoch(time_bins_upper))
)

# Use xarray binning methods
Expand Down
4 changes: 2 additions & 2 deletions mhkit/dolfyn/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from .velocity import VelBinner
from mhkit.dolfyn import adv
from mhkit.dolfyn import adp
from mhkit.dolfyn import time
from mhkit.utils import time_utils as time
from mhkit.dolfyn import io
from mhkit.dolfyn import rotate
from mhkit.dolfyn import tools
from mhkit.utils.binning_tools import tools
2 changes: 1 addition & 1 deletion mhkit/dolfyn/adp/clean.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import numpy as np
import xarray as xr
from scipy.signal import medfilt
from ..tools import medfiltnan
from ...utils.binning_tools.tools import medfiltnan
from ..rotate.api import rotate2
from ..rotate.base import quaternion2orient

Expand Down
261 changes: 5 additions & 256 deletions mhkit/dolfyn/adp/turbulence.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@ def __init__(
Default = `n_fft_coh`=`n_fft`
noise : float or array-like
Instrument noise level in same units as velocity. Typically
found from `adp.turbulence.doppler_noise_level`.
found from
:func:`doppler_noise_level <mhkit.dolfyn.VelBinner.doppler_noise_level>`.
Default = None
orientation : str
Instrument's orientation, either 'up' or 'down'. Default = 'up'
Expand Down Expand Up @@ -305,82 +306,6 @@ def shear_squared(self, vel):

return shear2

def doppler_noise_level(self, psd, pct_fN=0.8):
"""
Calculate bias (in units of velocity) due to Doppler noise
using the noise floor of the velocity spectra.

Parameters
----------
psd : xarray.DataArray (time, freq)
The velocity spectra from a single depth bin (range), typically
in the mid-water range
pct_fN : float
Percent of Nyquist frequency to calculate characeristic frequency

Returns
-------
doppler_noise (xarray.DataArray):
Doppler noise level in units of m/s

Notes
-----
Approximates bias from

.. math:: \\sigma^{2}_{noise} = N * f_{c}

where :math:`\\sigma_{noise}` is the bias due to Doppler noise,
:math:`N` is the constant variance or spectral density, and :math:`f_{c}`
is the characteristic frequency.

The characteristic frequency is then found as

.. math:: f_{c} = pct_fN * (f_{s}/2)

where :math:`f_{s}/2` is the Nyquist frequency.


Richard, Jean-Baptiste, et al. "Method for identification of Doppler noise
levels in turbulent flow measurements dedicated to tidal energy." International
Journal of Marine Energy 3 (2013): 52-64.

Thiébaut, Maxime, et al. "Investigating the flow dynamics and turbulence at a
tidal-stream energy site in a highly energetic estuary." Renewable Energy 195
(2022): 252-262.
"""

if not isinstance(psd, xr.DataArray):
raise TypeError("`psd` must be an instance of `xarray.DataArray`.")
if not isinstance(pct_fN, float) or not 0 <= pct_fN <= 1:
raise ValueError("`pct_fN` must be a float within the range [0, 1].")
if len(psd.shape) != 2:
raise Exception("PSD should be 2-dimensional (time, frequency)")

# Characteristic frequency set to 80% of Nyquist frequency
fN = self.fs / 2
fc = pct_fN * fN

# Get units right
if psd.freq.units == "Hz":
f_range = slice(fc, fN)
else:
f_range = slice(2 * np.pi * fc, 2 * np.pi * fN)

# Noise floor
N2 = psd.sel(freq=f_range) * psd.freq.sel(freq=f_range)
noise_level = np.sqrt(N2.mean(dim="freq"))

time_dim = psd.dims[-2]
return xr.DataArray(
noise_level.values,
coords={time_dim: psd[time_dim]},
attrs={
"units": "m s-1",
"long_name": "Doppler Noise Level",
"description": "Doppler noise level calculated " "from PSD white noise",
},
)

def _stress_func_warnings(self, ds, beam_angle, noise, tilt_thresh):
"""
Performs a series of checks and raises warnings for ADCP stress calculations.
Expand Down Expand Up @@ -627,7 +552,7 @@ def reynolds_stress_4beam(self, ds, noise=None, orientation=None, beam_angle=Non
return xr.DataArray(
np.stack([upwp_ * np.nan, upwp_, vpwp_]),
coords={
"tau": ["upvp_", "upwp_", "vpwp_"],
"tau": self.tau,
"range": ds["range"],
"time": time,
},
Expand Down Expand Up @@ -745,7 +670,7 @@ def stress_tensor_5beam(
tke_vec = xr.DataArray(
np.stack([upup_, vpvp_, wpwp_]),
coords={
"tke": ["upup_", "vpvp_", "wpwp_"],
"tke": self.tke,
"range": ds["range"],
"time": time,
},
Expand Down Expand Up @@ -782,7 +707,7 @@ def stress_tensor_5beam(
stress_vec = xr.DataArray(
np.stack([upvp_, upwp_, vpwp_]),
coords={
"tau": ["upvp_", "upwp_", "vpwp_"],
"tau": self.tau,
"range": ds["range"],
"time": time,
},
Expand All @@ -794,182 +719,6 @@ def stress_tensor_5beam(

return tke_vec, stress_vec

def check_turbulence_cascade_slope(self, psd, freq_range=[0.2, 0.4]):
"""
This function calculates the slope of the PSD, the power spectra
of velocity, within the given frequency range. The purpose of this
function is to check that the region of the PSD containing the
isotropic turbulence cascade decreases at a rate of :math:`f^{-5/3}`.

Parameters
----------
psd : xarray.DataArray ([[range,] time,] freq)
The power spectral density (1D, 2D or 3D)
freq_range : iterable(2)
The range over which the isotropic turbulence cascade occurs, in
units of the psd frequency vector (Hz or rad/s).
Default = [6.28, 12.57]

Returns
-------
(m, b): tuple (slope, y-intercept)
A tuple containing the coefficients of the log-adjusted linear
regression between PSD and frequency

Notes
-----
Calculates slope based on the `standard` formula for dissipation:

.. math:: S(k) = \\alpha \\epsilon^{2/3} k^{-5/3} + N

The slope of the isotropic turbulence cascade, which should be
equal to :math:`k^{-5/3}` or :math:`f^{-5/3}`, where k and f are
the wavenumber and frequency vectors, is estimated using linear
regression with a log transformation:

.. math:: log10(y) = m*log10(x) + b

Which is equivalent to

.. math:: y = 10^{b} x^{m}

Where :math:`y` is S(k) or S(f), :math:`x` is k or f, :math:`m`
is the slope (ideally -5/3), and :math:`10^{b}` is the intercept of
:math:`y` at :math:`x^{m}=1'.
"""

if not isinstance(psd, xr.DataArray):
raise TypeError("`psd` must be an instance of `xarray.DataArray`.")
if not hasattr(freq_range, "__iter__") or len(freq_range) != 2:
raise ValueError("`freq_range` must be an iterable of length 2.")

idx = np.where((freq_range[0] < psd.freq) & (psd.freq < freq_range[1]))
idx = idx[0]

x = np.log10(psd["freq"].isel(freq=idx))
y = np.log10(psd.isel(freq=idx))

y_bar = y.mean("freq")
x_bar = x.mean("freq")

# using the formula to calculate the slope and intercept
n = np.sum((x - x_bar) * (y - y_bar), axis=0)
d = np.sum((x - x_bar) ** 2, axis=0)

m = n / d
b = y_bar - m * x_bar

return m, b

def dissipation_rate_LT83(
self, psd, U_mag, freq_range=[0.2, 0.4], k_constant=0.67, noise=None
):
"""
Calculate the TKE dissipation rate from the velocity spectra.

Parameters
----------
psd : xarray.DataArray (time, freq)
The power spectral density from the vertical beam and depth bin (range)
U_mag : xarray.DataArray (time)
The bin-averaged horizontal velocity (a.k.a. speed) from a single
depth bin (range) (i.e., computed using
:func:`mhkit.dolfyn.velocity.Velocity.U_mag`)
f_range : iterable(2)
The range over which to integrate/average the spectrum, in units
of the psd frequency vector (Hz or rad/s)
k_constant : float or iterable(3)
Kolmogorov Constant (\\alpha in Notes section below) to use. Default
\\alpha is 0.67.
noise : float or array-like
Instrument noise level in same units as velocity. Typically found from
:func:`doppler_noise_level <mhkit.dolfyn.adp.turbulence.ADPBinner.doppler_noise_level>`
Default = None

Returns
-------
dissipation_rate : xarray.DataArray (...,n_time)
Turbulent kinetic energy dissipation rate

Notes
-----
This uses the `standard` formula for dissipation:

.. math:: S(k) = \\alpha \\epsilon^{2/3} k^{-5/3} + N

where :math:`\\alpha` is the Kolmogorov constant (0.67 for vertical direction),
`k` is wavenumber, `S(k)` is the turbulent kinetic energy spectrum, and
`N' is the doppler noise level associated with the TKE spectrum.

With :math:`k \\rightarrow \\omega / U`, then -- to preserve variance --
:math:`S(k) = U S(\\omega)`, and so this becomes:

.. math:: S(\\omega) = \\alpha \\epsilon^{2/3} \\omega^{-5/3} U^{2/3} + N

With :math:`k \\rightarrow (2\\pi f) / U`, then

.. math:: S(\\omega) = \\alpha \\epsilon^{2/3} f^{-5/3} (U/(2*\\pi))^{2/3} + N

LT83 : Lumley and Terray, "Kinematics of turbulence convected
by a random wave field". JPO, 1983, vol13, pp2000-2007.
"""

if not isinstance(psd, xr.DataArray):
raise TypeError("`psd` must be an instance of `xarray.DataArray`.")
if len(psd.shape) != 2:
raise Exception("`psd` should be 2-dimensional (time, frequency)")
if len(U_mag.shape) != 1:
raise Exception("U_mag should be 1-dimensional (time)")
if not hasattr(freq_range, "__iter__") or len(freq_range) != 2:
raise ValueError("`freq_range` must be an iterable of length 2.")
if np.size(k_constant) != 1:
raise ValueError("`k_constant` should be a single value.")
if noise is not None:
if np.shape(noise)[0] != np.shape(psd)[0]:
raise Exception("Noise should have same first dimension as `psd`")
else:
noise = np.array(0)

# Noise subtraction from binner.TimeBinner._psd_base
psd = psd.copy()
if noise is not None:
psd -= noise**2 / (self.fs / 2)
psd = psd.where(psd > 0, np.min(np.abs(psd)) / 100)

freq = psd.freq
idx = np.where((freq_range[0] < freq) & (freq < freq_range[1]))
idx = idx[0]

# Interpolate U_mag to the same time dimension as PSD
umag_time_dim = U_mag.dims[-1]
# If overlap is not 0%
if psd["time_psd"].size != U_mag[umag_time_dim].size:
U_mag = U_mag.interp({umag_time_dim: psd["time_psd"].values}).values
else:
U_mag = U_mag.values

# Set the correct magnitude whether the frequency is in Hz or rad/s
if freq.units == "Hz":
U = U_mag / (2 * np.pi)
else:
U = U_mag

# Use the transverse value derived from the Kolmogorov constant
a = k_constant
# Calculate dissipation
out = (psd[:, idx] * freq[idx] ** (5 / 3) / a).mean(axis=-1) ** (3 / 2) / U

return xr.DataArray(
out,
attrs={
"units": "m2 s-3",
"long_name": "TKE Dissipation Rate",
"standard_name": "specific_turbulent_kinetic_energy_dissipation_in_sea_water",
"description": "TKE dissipation rate calculated using "
"the method from Lumley and Terray, 1983",
},
)

def dissipation_rate_SF(self, vel_raw, r_range=[1, 5]):
"""
Calculate TKE dissipation rate from ADCP along-beam velocity using the
Expand Down
Loading
Loading