DOLfYN

The DOLfYN module contains a set of functions to analyze binary Nortek or TRDI files. Instrument datafiles are processed and returned as MATLAB structures.

Note

DOLfYN support within MHKiT-MATLAB is a work in progress. Please submit any issues or improvements to the MHKiT-MATLAB GitHub Repository

Note

The names of the functions below are of the convention path.path.function. Only the function name is used when calling the function in MATLAB. For example, to call on mhkit.dolfyn.io.read_nortek simply use read_nortek.

IO

The io submodule contains the following functions to read binary Nortek (e.g., .VEC, .wpr, .ad2cp, etc.) or TRDI (.000, .PD0, .ENX, etc.) data files.

mhkit.dolfyn.io.read_h5(filename)

Read H5 data structure.

Parameters:

filename (string) – Filename of NetCDF file to read.

Returns:

ds (structure) – Structure from the binary instrument data

mhkit.dolfyn.io.read_rdi(filename, options)

Read a TRDI binary data file.

Parameters:
  • filename (string) – Filename of TRDI file to read.

  • userdata (bool or string (optional)) – true, false, or string of userdata.json filename (default true) Whether to read the ‘<base-filename>.userdata.json’ file.%

  • nens (nan, int, or 2-element array (optional)) – nan (default: read entire file), int, or 2-element tuple (start, stop) Number of pings to read from the file.

  • read_rdi(filename (call with options ->)

  • 'userdata'

  • false

  • 'do_checksum'

  • true

  • 'nens'

  • 12)

Returns:

ds (structure) – Structure from the binary instrument data

mhkit.dolfyn.io.nortek_defs

Run this file to generate the nortek_defs.mat file

mhkit.dolfyn.io.read_netcdf(filename)

Read NetCDF data structure.

Parameters:

filename (string) – Filename of NetCDF file to read.

Returns:

ds (structure) – Structure from the binary instrument data

mhkit.dolfyn.io.dolfyn_read(filename, options)

Read binary ADCP data files from Nortek or RDI instruments

This function reads binary ADCP data files in .VEC, .wpr, .ad2cp (Nortek)- and .000, .PD0, .ENX, (RDI) formats into MATLAB structures that can be saved as .nc files and used with MHKiT-MATLAB dolfyn ADCP analysis functions.

Parameters:
  • filename (string) – Path to instrument file to read

  • userdata (logical or string, optional (name-value)) – Whether to read ‘<base-filename>.userdata.json’ file - true: read userdata.json file (default) - false: skip userdata.json file - string: path to specific userdata.json file

  • nens (double or array, optional (name-value)) – Number of pings/ensembles to read - nan: read entire file (default) - scalar: read first N pings - [start, stop]: read pings from start to stop

Returns:

ds (structure) – ADCP dataset structure containing: ds.vel.data : Velocity data [range x time x beam] [m/s] ds.coords : Coordinate information (time, range, beam) ds.attrs : Instrument metadata and deployment information

Examples

Read entire ADCP file, may be slow for large (>1GB) files ds = dolfyn_read(‘deployment.ad2cp’);

Read first 1000 ensembles without userdata ds = dolfyn_read(‘deployment.ad2cp’, ‘userdata’, false, ‘nens’, 1000);

Read specific ensemble range ds = dolfyn_read(‘deployment.ad2cp’, ‘nens’, [500, 1500]);

mhkit.dolfyn.io.read_nortek(filename, options)

Read a classic Nortek (AWAC and Vector) datafile

Parameters:
  • filename (string) – Filename of Nortek file to read.

  • userdata (bool or string (optional)) – true, false, or string of userdata.json filename (default true) Whether to read the ‘<base-filename>.userdata.json’ file.

  • do_checksum (bool (optional)) – Whether to perform the checksum of each data block. (default false)

  • nens (nan, int, or 2-element array (optional)) – nan (default: read entire file), int, or 2-element tuple (start, stop) Number of pings to read from the file.

  • read_nortek(filename (call with options ->)

  • 'userdata'

  • false

  • 'do_checksum'

  • true

  • 'nens'

  • 12)

Returns:

ds (structure) – Structure from the binary instrument data

mhkit.dolfyn.io.read_signature(filename, options)

Read a Nortek Signature (.ad2cp) datafile

Parameters:
  • filename (string) – Filename of Nortek file to read.

  • userdata (bool or string (optional)) – true, false, or string of userdata.json filename (default true) Whether to read the ‘<base-filename>.userdata.json’ file.

  • nens (nan, int, or 2-element array (optional)) – nan (default: read entire file), int, or 2-element tuple (start, stop) Number of pings to read from the file.

  • read_signature(filename (call with options ->)

  • 'userdata'

  • false

  • 'nens'

  • 12)

Returns:

ds (structure) – Structure from the binary instrument data

mhkit.dolfyn.io.read_userdata(filename, userdata)

Reads a userdata.json file and returns the data it contains as a structure

Parameters:
  • filename (string) – Filename of Nortek file to read.

  • userdata (bool or string) – true, false, or string of userdata.json filename

Returns:

userdata (structure)

mhkit.dolfyn.io.write_netcdf(ds, filename)

Write Dolfyn data set to NetCDF data structure. Updated for MATLAB R2022b and later versions.

Parameters:
  • ds (structure) – Structure from the binary instrument data

  • filename (string) – Filename of NetCDF file to read.

ADP (Acoustic Doppler Profiler)

The ADP module contains routines for reading and working with ADP/ADCP data. It contains:

mhkit.dolfyn.adp.water_depth_from_pressure(ds, options)

Calculate water depth from pressure using seawater density

This function calculates the distance to the water surface using pressure ADCP sensor data. Temperature and salinity are used to calculate seawater density, which is then used with pressure data to calculate depth%

Parameters:
  • ds (structure) – ADCP dataset structure containing pressure and temperature data ds.pressure.data : Pressure measurements [dbar] ds.temp.data : Temperature measurements [°C] ds.attrs.h_deploy : Optional deployment height above seafloor [m]

  • salinity (double, optional (name-value)) – Water salinity [psu] (default: 35)

Returns:

out (structure) – Input dataset with added depth and density fields: out.depth.data : Water depth measurements [m] out.water_density.data : Seawater density [kg/m³] out.depth.long_name : Descriptive name out.depth.units : “m”

mhkit.dolfyn.adp.correlation_filter(ds, options)

Filters out velocity data where correlation is below a threshold in the beam correlation data.

Parameters:
  • ds (Dataset) – The adcp dataset to clean.

  • thresh (numeric) – The maximum value of correlation to screen, in counts or %, default is 50

  • val (numeric) – Value to set masked correlation data to, default is nan

Returns:

ds (xarray.Dataset) – Velocity data with low correlation values set to val

Notes

Does not edit correlation or amplitude data.

mhkit.dolfyn.adp.remove_surface_interference(ds, options)

Mask the values of 3D data (vel, amp, corr, echo) that are beyond the surface.

Parameters:
  • ds (Dataset) – The adcp dataset to clean

  • val (nan or numeric) – Specifies the value to set the bad values to (default nan).

Returns:

ds (Dataset) – The adcp dataset where relevant arrays with values greater than depth are set to NaN

Notes

Surface interference expected to happen at distance > range * cos(beam angle) - cell size

mhkit.dolfyn.adp.set_range_offset(ds, h_deploy)

Adds an instrument’s height above seafloor (for an up-facing instrument) or depth below water surface (for a down-facing instrument) to the range coordinate. Also adds an attribute to the Dataset with the current “h_deploy” distance.

Parameters:
  • ds (xarray.Dataset) – The adcp dataset to ajust ‘range’ on

  • h_deploy (numeric) – Deployment location in the water column, in [m]

Returns:

None, operates “in place”

Notes

Center of bin 1 = h_deploy + blank_dist + cell_size

Nortek doesn’t take h_deploy into account, so the range that DOLfYN calculates distance is from the ADCP transducers. TRDI asks for h_deploy input in their deployment software and is thereby known by DOLfYN.

If the ADCP is mounted on a tripod on the seafloor, h_deploy will be the height of the tripod +/- any extra distance to the transducer faces. If the instrument is vessel-mounted, h_deploy is the distance between the surface and downward-facing ADCP’s transducers.

Rotate

The rotate submodule contains tools to rotate a dataset to different coordinate systems. When a file is read into dolfyn, the data will be stored in the same coordinate system it was saved in. The different coordinate systems are “beam” <-> “inst” <-> “earth” <-> “principal”. “Beam” and “inst” are manufacturer/instrument specific and refer to the along-beam (either 3 or 4 beams) and instrument (XYZ) reference frame. Instrument reference frames differ across sensors, but the rotate code takes this into account when rotating into the “earth” frame, defined as East-North-Up (ENU). The earth frame can then be rotated to the principal axes, defined as streamwise-cross_stream-vertical.

mhkit.dolfyn.rotate.calc_tilt(pitch, roll, options)

Calculate instrument tilt from pitch and roll angles.

This function calculates the total tilt angle of an ADCP instrument from pitch and roll measurements. This function warns the user if the tilt is above 5° as tilts above this threshold are likely to have a negative affect on the accuracy of flow and turbulence calculations.

Parameters:
  • pitch (array) – time series of pitch angle (forward/backward tilt)

  • roll (array) – time series of roll angle (side-to-side tilt)

  • units (string) – Units of input angles: ‘degrees’, ‘deg’, ‘radians’ or ‘rad’ Default: ‘degrees’

  • output_units (string) – Units for output tilt: ‘degrees’, ‘deg’, ‘radians’ or ‘rad’ Default: same as input units

Returns:

tilt (array) – tilt angle in specified output units

Algorithm

tilt_rad = atan( √( tan(roll_rad)² + tan(pitch_rad)² ) )

Example

% Calculate a time series of tilt from pitch and roll time series in degrees tilt = calc_tilt(pitch_data, roll_data, ‘units’, ‘degrees’);

Notes

  • Large tilts (> 5°) can affect turbulence measurements

  • This function issues warnings for tilts > 5°

mhkit.dolfyn.rotate.tensorproduct_core(A, B, A_permute, B_permute, R_permute, A_reshape, B_reshape, R_reshape)

Rearrangement of input

mhkit.dolfyn.rotate.orient2euler(omat)

Calculate DOLfYN-defined euler angles from the orientation matrix.

Parameters:

omat (array) – The orientation matrix

Returns:

  • heading (|ndarray|) – The heading angle. Heading is defined as the direction the x-axis points, positive clockwise from North (this is opposite the right-hand-rule around the Z-axis), range 0-360 degrees.

  • pitch (ndarray) – The pitch angle (degrees). Pitch is positive when the x-axis pitches up (this is opposite the right-hand-rule around the Y-axis).

  • roll (ndarray) – The roll angle (degrees). Roll is positive according to the right-hand-rule around the instrument’s x-axis.

mhkit.dolfyn.rotate.calc_omat(hh, pp, rr, orientation_down)
mhkit.dolfyn.rotate.calc_principal_heading(vel, tidal_mode)

Compute the principal angle of the horizontal velocity.

Parameters:
  • vel (array) – The 2D or 3D velocity array

  • tidal_mode (bool)

Returns:

p_heading (float or ndarray) – The principal heading in degrees clockwise from North.

Notes

When tidal_mode=True, this tool calculates the heading that is aligned with the bidirectional flow. It does so following these steps:

  1. rotates vectors with negative velocity by 180 degrees

  2. then doubles those angles to make a complete circle again

  3. computes a mean direction from this, and halves that angle (to undo the doubled-angles in step 2)

  4. The returned angle is forced to be between 0 and 180. So, you may need to add 180 to this if you want your positive direction to be in the western-half of the plane.

Otherwise, this function simply computes the average direction using a vector method.

mhkit.dolfyn.rotate.inst2head(advo, reverse)
mhkit.dolfyn.rotate.euler2orient(heading, pitch, roll, options)

For Nortek data only. The heading, pitch, roll used here are from the Nortek binary files.

Parameters:
  • heading (array) – Heading input is clockwise from North

  • pitch (array)

  • roll (array)

  • units (string (optional)) – radians or degrees (default degrees) Whether heading, pitch, and roll are in degrees or radians.

Returns:

omat – a rotation matrix that rotates earth (ENU) -> inst. This is based on the Nortek Transforms.m file, available in the refs folder.

mhkit.dolfyn.rotate.inst2earth(advo, reverse, make)

Rotate data in an ADV object to the earth from the instrument frame (or vice-versa).

Parameters:
  • advo (The adv object containing the data.)

  • reverse (bool (default: False)) – If True, this function performs the inverse rotation (earth->inst).

  • make (char) – awac, vector, signature, rdi

mhkit.dolfyn.rotate.beam2inst(dat, reverse, rmod)

Rotate velocities from beam to instrument coordinates.

datThe adv object containing the data.

The ADCP dataset

reversebool

If True, this function performs the inverse rotation (inst->beam).

rmod: string

awac, vector, signature, rdi


mhkit.dolfyn.rotate.calc_orientmat(adcpo)

Calculate the orientation matrix using the raw heading, pitch, roll values from the RDI binary file.

Parameters:
  • adcpo (The ADP object containing the data.)

  • 08 (## RDI-ADCP-MANUAL (Jan)

  • 18) (section 5.6 page)

  • same (The internal tilt sensors do not measure exactly the)

  • in (pitch as a set of gimbals would (the roll is the same). Only)

  • (EZxxx1xxx) (the case of the internal pitch sensor being selected)

:param : :param the measured pitch is modified using the following algorithm.: P = arctan[tan(Tilt1)*cos(Tilt2)] (Equation 18) :param Where: :type Where: Tilt1 is the measured pitch from the internal sensor, and :param Tilt2 is the measured roll from the internal sensor The raw pitch: :param (Tilt 1) is recorded in the variable leader. P is set to 0 if the: :param “use tilt” bit of the EX command is not set.”””:

Returns:

rotmat (array) – orientation matrix

mhkit.dolfyn.rotate.tensorproduct_initialize(ind_A, ind_B, ind_R, sizeA, sizeB)

TENSORPRODUCT_INITIALIZE Part of the tensorproduct utility Copyright 2021 - by David Codony, PhD (dcodony@cimne.upc.edu) This software is distributed without any warranty. Permission is granted for anyone to copy, use, or modify this software for any uncommercial purposes, provided this copyright notice is retained, and note is made of any changes that have been made. Assert empty inputs

mhkit.dolfyn.rotate.quaternion2orient(quaternions)
Calculate orientation from Nortek AHRS quaternions, where

q = [W, X, Y, Z] instead of the standard q = [X, Y, Z, W] = [q1, q2, q3, q4]

Parameters:

quaternions (Structure) – Quaternion structure from the raw dataset

Returns:

orientmat (|ndarray|) – The inst2earth rotation maxtrix as calculated from the quaternions

See also

scipy.spatial.transform.Rotation

mhkit.dolfyn.rotate.calc_beam_orientmat(theta, convex, degrees)

Calculate the rotation matrix from beam coordinates to instrument head coordinates for an RDI ADCP.

Parameters:
  • theta (is the angle of the heads (usually 20 or 30 degrees))

  • convex (is a flag for convex or concave head configuration.)

  • degrees (is a flag which specifies whether theta is in degrees) – or radians (default: degrees=True)

Returns:

out (array) – orientation matrix

mhkit.dolfyn.rotate.set_declination(data_set, declin)

Set the magnetic declination

Parameters:

declination (float) – The value of the magnetic declination in degrees (positive values specify that Magnetic North is clockwise from True North)

Returns:

ds (dataset structure) – Dataset adjusted for the magnetic declination

Notes

This method modifies the data object in the following ways:

  • If the dataset is in the earth reference frame at the time of setting declination, it will be rotated into the “True-East, True-North, Up” (hereafter, ETU) coordinate system

  • dat[‘orientmat’] is modified to be an ETU to instrument (XYZ) rotation matrix (rather than the magnetic-ENU to XYZ rotation matrix). Therefore, all rotations to/from the ‘earth’ frame will now be to/from this ETU coordinate system.

  • The value of the specified declination will be stored in dat.attrs[‘declination’]

  • dat[‘heading’] is adjusted for declination (i.e., it is relative to True North).

  • If dat.attrs[‘principal_heading’] is set, it is adjusted to account for the orientation of the new ‘True’ earth coordinate system (i.e., calling set_declination on a data object in the principal coordinate system, then calling dat.rotate2(‘earth’) will yield a data object in the new ‘True’ earth coordinate system)

mhkit.dolfyn.rotate.set_inst2head_rotmat(ds, rotmat)

Set the instrument to head rotation matrix for cable head Nortek ADVs.

Parameters:

rotmat (float) – 3x3 rotation matrix

Returns:

data_set (structure) – Dataset with rotation matrix applied

mhkit.dolfyn.rotate.tensorproduct(A, B, subscripts) %ind_R, A, ind_A, B, ind_B)

TENSORPRODUCT Implementation of Einstein summation convention for multidimensional matlab arrays, where repeated indices sum over.

Call:

R = tensorproduct(ind_R,A,ind_A,B,ind_B);

Inputs:
ind_Rstring with indices of the output

A : (non-empty) (multidimensional) matlab array

ind_Astring with indices of array A

B : (non-empty) (multidimensional) matlab array

ind_B : string with indices of array B

Supports multiple: - Outer products - Inner products - Singleton dimensions - Pages

Does not support (yet): - Self-contraction

Example

A = rand(5, 1,4,8); B = rand(4,10,5 ); R = tensorproduct(‘jzgi’,A,’gxki’,B,’kjg’); % Outer: ‘i’,’j’

% Inner: ‘k’ % Page: ‘g’ % Singleton: ‘x’,’z’ % size(R) = [10,1,5,8]

Note

Provided indices in (ind_R), (ind_A) and (ind_B) are case-sensitive, i.e. ‘a’ and ‘A’ are different indices.

Version compatibility:

This implementation makes use of Matlab built-in function pagemtimes, introduced in Matlab version R2020b. To make use of this implementation in previous Matlab releases, comment out the statement:

R = pagemtimes(A,B);

and uncomment the following lines:

R = zeros(size(A,1),size(B,2),size(A,3)); for i = 1:size(A,3)

R(:,:,i) = A(:,:,i) * B(:,:,i);

end

While it will still work, performance (wall-clock time) might be degraded.

Benchmarking:

The performance of tensorproduct can be assessed by calling the function tensorproduct_benchmark.

mhkit.dolfyn.rotate.earth2principal(advo, reverse)

Rotate data in an ADV dataset to/from principal axes. Principal heading must be within the dataset.

All data in the advo.attrs[‘rotate_vars’] list will be rotated by the principal heading, and also if the data objet has an orientation matrix (orientmat) it will be rotated so that it represents the orientation of the ADV in the principal (reverse:earth) frame.

Parameters:
  • advo (The adv object containing the data.)

  • reverse (bool (default: False)) – If True, this function performs the inverse rotation (principal->earth).

mhkit.dolfyn.rotate.rotate2(data_set, out_frame)

Rotate a dataset to a new coordinate system.

Parameters:
  • ds (xr.Dataset) – The dolfyn dataset (ADV or ADCP) to rotate.

  • out_frame (string {'beam', 'inst', 'earth', 'principal'}) – The coordinate system to rotate the data into.

Returns:

ds (xarray.Dataset) – The rotated dataset

Notes

This function rotates all variables in ds.attrs.rotate_vars

Tools

The clean submodule contains basic quality control tools specific to ADCP and ADVs.

mhkit.dolfyn.tools.dolfyn_psd_1D(data, n_fft, fs, options)

Compute 1D power spectral density using Welch’s method

Uses same algorithm as MHKiT-MHKiT-Python psd_1D function

Parameters:
  • data (double) – 1D ADCP velocity time series data (column vector) [m/s]

  • n_fft (double) – Number of points in the FFT window [samples]

  • fs (double) – Sample rate [Hz]

  • window (char or double, optional (name-value)) – Window function {‘hann’, ‘hamming’, ‘rectwin’} or custom window vector (default: ‘hann’)

  • step (double, optional (name-value)) – Step size for segment overlap (default: auto-calculated) [samples]

Returns:

psd (double) – Power spectral density [m^2/s^2/Hz] Size: [n_freq x 1] where n_freq = floor(n_fft/2) Frequencies correspond to positive frequencies only (DC component excluded)

mhkit.dolfyn.tools.dolfyn_select(data_field, coord_name, target_value, options)

Select ADCP data along coordinates/dimensions with xarray-like functionality

This function provides data selection capabilities similar to xarray’s .sel() method, enabling efficient selection of velocity, range, time, or beam data along specified coordinate dimensions.

Parameters:
  • data_field (structure) –

    ADCP data structure containing:

    .data : Velocity or other data array [varies] .coords : Coordinate structure with dimension arrays

  • coord_name (string) – Name of coordinate dimension to select along

  • target_value (double) – Value(s) to select along coordinate (scalar or array)

  • method (string, optional (name-value)) – Selection method: ‘exact’, ‘nearest’, ‘pad’, ‘ffill’, ‘backfill’, ‘bfill’ Default: ‘exact’

  • tolerance (double, optional (name-value)) – Maximum distance for nearest method [same units as coordinate] Default: Inf

  • return_index (logical, optional (name-value)) – Return indices instead of data (default: false)

Returns:

  • selected_data (array or double) – Selected data array or coordinate indices [same units as input data]

  • selected_coords (structure) – Updated coordinate structure with selected coordinate values .{coord_name} : Selected coordinate array [same units as input]

mhkit.dolfyn.tools.py_struct_2_bytes_format(py_format, size_only)
mhkit.dolfyn.tools.fill_time_gaps(epoch, sample_rate_hz)

Fill gaps (NaN values) in the timeseries by simple linear interpolation. The ends are extrapolated by stepping forward/backward by 1/sample_rate_hz.

mhkit.dolfyn.tools.calculate_horizontal_speed_and_direction(ds)

Calculate horizontal speed and direction from velocity components

Parameters:

ds (structure) –

Dolfyn data structure containing velocity data. Must include:
  • vel: structure with fields:
    • data: array with velocity components

    • dims: cell array of dimension names

    • coords: structure with coordinate information including:
      • dir: cell array of direction labels (‘E’, ‘N’, ‘U1’, ‘U2’)

  • attrs: structure with metadata

  • coord_sys: string

    Coordinate system identifier (e.g., “earth”, “beam”, “inst”, “principal”)

Returns:

ds_out (structure) –

Input structure with additional fields:
  • U_mag: structure
    • data: array of velocity magnitudes (m/s)

    • dims: cell array of dimension names (excluding dir)

    • coords: coordinate information

    • units: “m s-1”

    • standard_name: “sea_water_speed”

    • long_name: “Water Speed”

  • U_dir: structure
    • data: array of flow directions

    • dims: cell array of dimension names (excluding dir)

    • coords: coordinate information

    • units: “degrees_CW_from_[REF]” where [REF] depends on coord_sys:
      • earth: “degrees_CW_from_N”

      • others: “degrees_CW_from_E” (or relevant streamwise component)

    • standard_name: “sea_water_to_direction”

    • long_name: “Water Direction”

    Note: Direction is NaN where velocity magnitude is zero Note: For earth coordinates, angles are CW from North [0, 360]

    For other coordinates, angles are CW from East/streamwise [0, 360]

mhkit.dolfyn.tools.dolfyn_plot(ds, field, varargin)

Plot fields from Dolfyn generated data structures

Parameters:
  • ds (structure) – Structure from the binary instrument data

  • field (string) – field from ds to be plotted (ex: ‘vel’)

  • dim (int or array (optional)) – for higher dimension fields, which dimension(s) should be plotted can be a single value or array (e.g., 1:3 or [1,3,5])

  • plotArgs (cell array (optional)) – Additional options to be passed to the plot function

  • cbar_min (double (optional)) – Minimum value for colorbar in 3D plots

  • cbar_max (double (optional)) – Maximum value for colorbar in 3D plots

  • width (double (optional)) – Width of figure in pixels (default: 400 per column)

  • height (double (optional)) – Height of figure in pixels (default: 300 per row)

mhkit.dolfyn.tools.subtract_mean_from_dimension(data_in, dim)

Subtract mean along specified dimension

Parameters:
  • data_in (array) – Input data array

  • dim (double) – Dimension index along which to subtract mean (typically time dimension)

Returns:

data_out (array) – Same dimensions as input data

mhkit.dolfyn.tools.set_coords(ds, ref_frame)

Checks the current reference frame and adjusts xarray coords/dims as necessary. Makes sure assigned dataarray coordinates match what DOLfYN is reading in.

mhkit.dolfyn.tools.fillgaps(a, extrapFlg)

Linearly fill NaN value in an array.

Parameters:
  • a (array) – The array to be filled.

  • extrapFlg (bool) – Whether to extrapolate if NaNs are found at the ends of the array.

Notes

This function interpolates assuming spacing/timestep between successive points is constant. If the spacing is not constant, use interpgaps.

mhkit.dolfyn.tools.bluewhitered(m)

BLUEWHITERED Blue, white, and red color map. BLUEWHITERED(M) returns an M-by-3 matrix containing a blue to white to red colormap, with white corresponding to the CAXIS value closest to zero. This colormap is most useful for images and surface plots with positive and negative values. BLUEWHITERED, by itself, is the same length as the current colormap.

Examples:

figure imagesc(peaks(250)); colormap(bluewhitered(256)), colorbar

figure imagesc(peaks(250), [0 8]) colormap(bluewhitered), colorbar

figure imagesc(peaks(250), [-6 0]) colormap(bluewhitered), colorbar

figure surf(peaks) colormap(bluewhitered) axis tight

See also HSV, HOT, COOL, BONE, COPPER, PINK, FLAG, COLORMAP, RGBPLOT.

mhkit.dolfyn.tools.dolfyn_stepsize(l, n_fft, n_segments, step)

Calculate step size for overlapping FFT segments

Use same algorithm as MHKiT-Python _stepsize function

Parameters:
  • l (double) – Length of input data array [samples]

  • n_fft (double) – Desired FFT window size [samples]

  • n_segments (double, optional) – Number of overlapping segments (default: auto-calculated)

  • step (double, optional) – Step size between segments (default: auto-calculated) [samples]

Returns:

  • step (double) – Step size for segment overlap [samples]

  • n_segments (double) – Number of overlapping segments [dimensionless]

  • n_fft_used (double) – Actual FFT size used (may be reduced if l < n_fft) [samples]

mhkit.dolfyn.tools.reshape_for_ensemble(data, n_bin)

Reshape dolfyn time series data into ensemble bins

This function takes continuous time series data and reshapes it into ensemble bins, enabling calculation of statistics within each ensemble.

Parameters:
  • data (array) – Input data with time as the last dimension Shape: (…, time)

  • n_bin (integer) – Number of time points per ensemble bin

Returns:

reshaped_data (array) – Reshaped data with ensemble structure Shape: (…, n_ensembles, n_bin) where n_ensembles = floor(time_length / n_bin)

Notes

  • Incomplete ensembles at the end are discarded

  • Time dimension must be last dimension of input data

  • Equivalent to MHKiT-Python: data[…, :length*n_bin].reshape(…, length, n_bin)

mhkit.dolfyn.tools.create_dataset(data)

Creates final dataset from structure created from binary readers. It is meant to try and approximate an xarray dataset Direction ‘dir’ coordinates get reset in set_coords

mhkit.dolfyn.tools.average_by_dimension(ds, n_samples, dim_to_find)

Averages data along a specified dimension in a dataset structure

Parameters:
  • ds (structure) –

    Dataset structure containing fields with:

    .data: N-dimensional array of data .dims: cell array of dimension names .coords (optional): structure of coordinate data

  • n_samples (integer) – Number of samples to average together. Must be positive. For uneven divisions, the function will use floor(dimension_length/n_samples) complete bins and discard remaining samples.

  • dim_to_find (string (optional, default='time')) – Name of the dimension along which to perform averaging. Must exist in at least one field’s .dims array.

Returns:

ds_out (structure) –

Output dataset with same structure as input but averaged data:
  • Data arrays will have reduced size along averaged dimension

  • Coordinate arrays will be subsampled to match new data size

  • All other fields and dimensions remain unchanged

Examples

% Average every 2 time points ds_averaged = average_by_dimension(ds, 2, ‘time’)

% Average every 5 points along spatial dimension ds_averaged = average_by_dimension(ds, 5, ‘space’)

Notes

  • If n_samples doesn’t divide evenly into the dimension length, the function will issue a warning and discard remaining samples

  • NaN values are handled appropriately in the averaging

  • Coordinates are subsampled rather than averaged