API reference#

API components that most users will interact with.

Attention

In echopype versions prior to 0.5.0, the API in this page focused on the convert and process subpackages. See the 0.4.1 API page if you’re using a previous release. That workflow is now removed.

EchoData class#

EchoData is an object that handles interfacing raw converted data. It is used for calibration and other processing.

class echopype.echodata.EchoData(converted_raw_path: PathHint | None = None, storage_options: Dict[str, Any] | None = None, source_file: PathHint | None = None, xml_path: PathHint | None = None, sonar_model: SonarModelsHint | None = None, open_kwargs: Dict[str, Any] | None = None)#

Echo data model class for handling raw converted data, including multiple files associated with the same data set.

chunk(chunk_dict: dict)#

Chunks each group in an Echodata object based on the provided chunking dictionary. Dimensions not specified in the chunking dictionary will be chunked into a single piece along that dimension.

Parameters:
chunk_dictdict

A dictionary specifying the chunk sizes for each dimension. Keys correspond to dimension names, and values specify the desired chunk size for that dimension.

cleanup_swap_files()#

Clean up only the swap files created during raw data conversion.

to_netcdf(save_path: PathHint | None = None, compress: bool = True, overwrite: bool = False, parallel: bool = False, output_storage_options: Dict[str, str] = {}, **kwargs)#

Save content of EchoData to netCDF.

Parameters:
save_pathstr

path that converted .nc file will be saved

compressbool

whether or not to perform compression on data variables Defaults to True

overwritebool

whether or not to overwrite existing files Defaults to False

parallelbool

whether or not to use parallel processing. (Not yet implemented)

output_storage_optionsdict

Additional keywords to pass to the filesystem class.

**kwargsdict, optional

Extra arguments to xr.Dataset.to_netcdf: refer to xarray’s documentation for a list of all possible arguments.

to_zarr(save_path: PathHint | None = None, compress: bool = True, overwrite: bool = False, parallel: bool = False, output_storage_options: Dict[str, str] = {}, **kwargs)#

Save content of EchoData to zarr.

Parameters:
save_pathstr

path that converted .nc file will be saved

compressbool

whether or not to perform compression on data variables Defaults to True

overwritebool

whether or not to overwrite existing files Defaults to False

parallelbool

whether or not to use parallel processing. (Not yet implemented)

output_storage_optionsdict

Additional keywords to pass to the filesystem class.

**kwargsdict, optional

Extra arguments to xr.Dataset.to_zarr: refer to xarray’s documentation for a list of all possible arguments.

update_platform(extra_platform_data: Dataset, variable_mappings=typing.Dict[str, str], extra_platform_data_file_name=None)#

Updates the EchoData[“Platform”] group with additional external platform data.

extra_platform_data must be an xarray Dataset. Data is extracted from extra_platform_data by variable name. Only data assigned to a pre-existing (but possibly all-nan) variable name in Platform will be processed. These Platform variables include latitude, longitude, pitch, roll, vertical_offset, etc. See the variables present in the EchoData object’s Platform group to obtain a complete list of possible variables. Different external variables may be dependent on different time dimensions, but latitude and longitude (if specified) must share the same time dimension. New time dimensions will be added as needed. For example, if variables to be added from the external data use two time dimensions and the Platform group has time dimensions time2 and time2, new dimensions time3 and time4 will be created.

Parameters:
extra_platform_dataxr.Dataset

An xr.Dataset containing the additional platform data to be added to the EchoData[“Platform”] group.

variable_mappings: Dict[str,str]

A dictionary mapping Platform variable names (dict key) to the external-data variable name (dict value).

extra_platform_data_file_name: str, default=None

File name for source of extra platform data, if read from a file

Examples

>>> ed = echopype.open_raw(raw_file, "EK60")
>>> extra_platform_data = xr.open_dataset(extra_platform_data_file_name)
>>> ed.update_platform(
>>>     extra_platform_data,
>>>     variable_mappings={"longitude": "lon", "latitude": "lat", "roll": "ROLL"},
>>>     extra_platform_data_file_name=extra_platform_data_file_name
>>> )

Open raw and converted files#

echopype.combine_echodata(echodata_list: List[EchoData] = None, channel_selection: List | Dict[str, list] | None = None) → EchoData#

Combines multiple EchoData objects into a single EchoData object.

Parameters:
echodata_listlist of EchoData object

The list of EchoData objects to be combined

channel_selection: list of str or dict, optional

Specifies what channels should be selected for an EchoData group with a channel dimension (before combination).

  • if a list is provided, then each EchoData group with a channel dimension will only contain the channels in the provided list

  • if a dictionary is provided, the dictionary should have keys specifying only beam groups (e.g. “Sonar/Beam_group1”) and values as a list of channel names to select within that beam group. The rest of the EchoData groups with a channel dimension will have their selected channels chosen automatically.

Returns:
EchoData

A lazy loaded EchoData object, with all data from the input EchoData objects combined.

Raises:
ValueError

If the provided zarr path does not point to a zarr file

TypeError

If a list of EchoData objects are not provided

ValueError

If any EchoData object’s sonar_model is None

ValueError

If any EchoData object does not have a file path

ValueError

If the provided EchoData objects have the same filenames

RuntimeError

If the first time value of each EchoData group is not less than the first time value of the subsequent corresponding EchoData group, with respect to the order in echodata_list

RuntimeError

If the same EchoData groups in echodata_list do not have the same number of channels and the same name for each of these channels.

RuntimeError

If any of the following attribute checks are not met amongst the combined EchoData groups:

  • the keys are not the same

  • the values are not identical

  • the keys date_created or conversion_time do not have the same types

RuntimeError

If any EchoData group has a channel dimension value with a duplicate value.

RuntimeError

If channel_selection=None and the channel dimensions are not the same across the same group under each object in echodata_list.

NotImplementedError

If channel_selection is a list and the listed channels are not contained in the EchoData group across all objects in echodata_list.

Notes

  • EchoData objects are combined by appending their groups individually.

  • All attributes (besides attributes whose values are arrays) from all groups before the combination will be stored in the Provenance group.

Examples

Combine lazy loaded EchoData objects:

>>> ed1 = echopype.open_converted("file1.zarr")
>>> ed2 = echopype.open_converted("file2.zarr")
>>> combined = echopype.combine_echodata(echodata_list=[ed1, ed2])

Combine in-memory EchoData objects:

>>> ed1 = echopype.open_raw(raw_file="EK60_file1.raw", sonar_model="EK60")
>>> ed2 = echopype.open_raw(raw_file="EK60_file2.raw", sonar_model="EK60")
>>> combined = echopype.combine_echodata(echodata_list=[ed1, ed2])
echopype.open_converted(converted_raw_path: PathHint, storage_options: Dict[str, str] = None, **kwargs)#

Create an EchoData object from a single converted netcdf or zarr file.

Parameters:
converted_raw_pathstr

path to converted data file

storage_optionsdict

options for cloud storage

kwargsdict

optional keyword arguments to be passed into xr.open_dataset

Returns:
EchoData object
echopype.open_raw(raw_file: PathHint, sonar_model: SonarModelsHint, xml_path: PathHint | None = None, include_bot: bool = False, include_idx: bool = False, convert_params: Dict[str, str] | None = None, storage_options: Dict[str, str] | None = None, use_swap: bool | Literal['auto'] = False, max_chunk_size: str = '100MB', channels: List[str] | None = None) → EchoData | Tuple[EchoData, Dataset]#

Create an EchoData object containing parsed data from a raw data source.

The EchoData object can be used for adding metadata and ancillary data as well as to serialize the parsed data to zarr or netcdf.

For BI500, this function returns (echodata, ds_cal), where ds_cal contains the calibrated products generated by the BI500 system.

Parameters:
raw_filestr

path to raw data file, or for BI500, the directory containing the associated BI500 file set

sonar_modelstr

model of the sonar instrument

  • EK60: Kongsberg Simrad EK60 echosounder

  • ES70: Kongsberg Simrad ES70 echosounder

  • EK80: Kongsberg Simrad EK80 echosounder

  • EA640: Kongsberg EA640 echosounder

  • AZFP: ASL Environmental Sciences AZFP echosounder (ULS5)

  • AZFP6: ASL Environmental Sciences AZFP echosounder (ULS6)

  • AD2CP: Nortek Signature series ADCP (tested with Signature 500 and Signature 1000)

  • BI500: Bergen Integrator BI500 data

xml_pathstr

path to XML config file used by AZFP (ULS5 only)

include_botbool, default False

Include bottom depth file in parsing. Only used by EK60/EK80.

include_indexbool, default False

Include index file in parsing. Only used by EK60/EK80.

convert_paramsdict

parameters (metadata) that may not exist in the raw file and need to be added to the converted file

storage_optionsdict, optional

options for cloud storage

use_swap: bool or “auto”, default False

Flag to use disk swap in case of a large memory footprint. When set to True (or when set to “auto” and large memory footprint is needed, this function will create a temporary zarr store at the operating system’s temporary directory.

max_chunk_sizestr, default “100MB”

The maximum data chunk size in Megabytes (MB), when offloading variables with a large memory footprint to a temporary zarr store

channelslist of str, optional

List of channel_id strings to parse and store. Only supported for EK60, ES70, EK80, ES80, and EA640. Includes all channels if not provided.

Returns:
EchoData object

For all sonar models except BI500.

tuple of EchoData and xarray.Dataset

For BI500, returns (echodata, ds_cal). ds_cal contains calibrated BI500 products including Sv, Sv_bottom, depth, depth_bottom, and single-target variables.

Raises:
ValueError

If sonar_model is None or sonar_model given is unsupported.

FileNotFoundError

If raw_file is None.

TypeError

If raw_file input is neither str or pathlib.Path type.

Notes

In case of a large memory footprint, the program will determine if using a temporary swap space is needed. If so, it will use that space during conversion to prevent out of memory errors.

Users can override this behaviour by either passing use_swap=True or use_swap=False. If a keyword “auto” is used for the use_swap parameter, echopype will determine the usage of swap space automatically.

This feature is only available for the following echosounders: EK60, ES70, EK80, ES80, EA640.

Data processing subpackages#

calibrate#

echopype.calibrate.compute_Sv(echodata: EchoData, **kwargs) → Dataset#

Compute volume backscattering strength (Sv) from raw data.

The calibration routine varies depending on the sonar type. Currently this operation is supported for the following sonar_model: EK60, AZFP, EK80 (see Notes below for detail).

Parameters:
echodataEchoData

An EchoData object created by using open_raw or open_converted

env_paramsdict, optional

Environmental parameters needed for calibration. Users can supply “sound speed” and “absorption” directly, or specify other variables that can be used to compute them, including “temperature”, “salinity”, and “pressure”.

For EK60 and EK80 echosounders, by default echopype uses environmental variables stored in the data files. For AZFP echosounder, all environmental parameters need to be supplied. AZFP echosounders typically are equipped with an internal temperature sensor, and some are equipped with a pressure sensor, but automatically using these pressure data is not currently supported.

cal_paramsdict, optional

Intrument-dependent calibration parameters.

For EK60, EK80, and AZFP echosounders, by default echopype uses environmental variables stored in the data files. Users can optionally pass in custom values shown below.

  • for EK60 echosounder, allowed parameters include: “sa_correction”, “gain_correction”, “equivalent_beam_angle”

  • for AZFP echosounder, allowed parameters include: “EL”, “DS”, “TVR”, “VTX0”, “equivalent_beam_angle”, “Sv_offset”

Passing in calibration parameters for other echosounders are not currently supported.

waveform_mode{“CW”, “BB”, “FM”}, optional

Type of transmit waveform. Required only for data from the EK80 echosounder and not used with any other echosounder.

  • “CW” for narrowband transmission, returned echoes recorded either as complex or power/angle samples

  • “BB” or “FM” for broadband transmission, returned echoes recorded as complex samples

encode_mode{“complex”, “power”}, optional

Type of encoded return echo data. Required only for data from the EK80 echosounder and not used with any other echosounder.

  • “complex” for complex samples

  • “power” for power/angle samples, only allowed when the echosounder is configured for narrowband transmission

assume_single_filter_timeboolean, optional

If true, filter coefficients and decimation values will be used from the first filter time. If false, all filter times will be used. This can only be used for complex EK80 calibration.

drop_last_hanning_zero: bool, default False

If true, uses the pyEcholab implementation of dropping the hanning window’s last index value (which is zero). Else, follows the CRIMAC implementation and keeps the last zero. This is here for CI test purposes.

Returns:
xr.Dataset

The calibrated Sv dataset, including calibration parameters and environmental variables used in the calibration operations.

Notes

The EK80 echosounder can be configured to transmit either broadband/frequency modulated (waveform_mode="BB" or waveform_mode="FM") or narrowband (waveform_mode="CW") signals. When transmitting in broadband mode, the returned echoes are encoded as complex samples (encode_mode="complex"). When transmitting in narrowband mode, the returned echoes can be encoded either as complex samples (encode_mode="complex") or as power/angle combinations (encode_mode="power") in a format similar to those recorded by EK60 echosounders.

The current calibration implemented for EK80 broadband complex data uses band-integrated Sv with the gain computed at the center frequency of the transmit signal.

The returned xr.Dataset will contain the variable water_level from the EchoData object provided, if it exists. If water_level is not returned, it must be set using EchoData.update_platform().

echopype.calibrate.compute_TS(echodata: EchoData, **kwargs)#

Compute target strength (TS) from raw data.

The calibration routine varies depending on the sonar type. Currently this operation is supported for the following sonar_model: EK60, AZFP, EK80 (see Notes below for detail).

Parameters:
echodataEchoData

An EchoData object created by using open_raw or open_converted

env_paramsdict, optional

Environmental parameters needed for calibration. Users can supply “sound speed” and “absorption” directly, or specify other variables that can be used to compute them, including “temperature”, “salinity”, and “pressure”.

For EK60 and EK80 echosounders, by default echopype uses environmental variables stored in the data files. For AZFP echosounder, all environmental parameters need to be supplied. AZFP echosounders typically are equipped with an internal temperature sensor, and some are equipped with a pressure sensor, but automatically using these pressure data is not currently supported.

cal_paramsdict, optional

Intrument-dependent calibration parameters.

For EK60, EK80, and AZFP echosounders, by default echopype uses environmental variables stored in the data files. Users can optionally pass in custom values shown below.

  • for EK60 echosounder, allowed parameters include: “sa_correction”, “gain_correction”, “equivalent_beam_angle”

  • for AZFP echosounder, allowed parameters include: “EL”, “DS”, “TVR”, “VTX0”, “equivalent_beam_angle”, “Sv_offset”

Passing in calibration parameters for other echosounders are not currently supported.

waveform_mode{“CW”, “BB”, “FM”}, optional

Type of transmit waveform. Required only for data from the EK80 echosounder and not used with any other echosounder.

  • “CW” for narrowband transmission, returned echoes recorded either as complex or power/angle samples

  • “BB” or “FM” for broadband transmission, returned echoes recorded as complex samples

encode_mode{“complex”, “power”}, optional

Type of encoded return echo data. Required only for data from the EK80 echosounder and not used with any other echosounder.

  • “complex” for complex samples

  • “power” for power/angle samples, only allowed when the echosounder is configured for narrowband transmission

assume_single_filter_timeboolean, optional

If true, filter coefficients and decimation values will be used from the first filter time. If false, all filter times will be used.

drop_last_hanning_zero: bool, default False

If true, uses the pyEcholab implementation of dropping the hanning window’s last index value (which is zero). Else, follows the CRIMAC implementation and keeps the last zero. This is here for CI test purposes.

Returns:
xr.Dataset

The calibrated TS dataset, including calibration parameters and environmental variables used in the calibration operations.

Notes

The EK80 echosounder can be configured to transmit either broadband/frequency modulated (waveform_mode="BB" or waveform_mode="FM") or narrowband (waveform_mode="CW") signals. When transmitting in broadband mode, the returned echoes are encoded as complex samples (encode_mode="complex"). When transmitting in narrowband mode, the returned echoes can be encoded either as complex samples (encode_mode="complex") or as power/angle combinations (encode_mode="power") in a format similar to those recorded by EK60 echosounders.

The current calibration implemented for EK80 broadband complex data uses band-integrated TS with the gain computed at the center frequency of the transmit signal.

Note that in the fisheries acoustics context, it is customary to associate TS to a single scatterer. TS is defined as: TS = 10 * np.log10 (sigma_bs), where sigma_bs is the backscattering cross-section.

For details, see: MacLennan et al. 2002. A consistent approach to definitions and symbols in fisheries acoustics. ICES J. Mar. Sci. 59: 365-369. https://doi.org/10.1006/jmsc.2001.1158

clean#

echopype.clean.detect_transient(ds: Dataset, method: str, params: dict) → DataArray#

Dispatch transient-noise detection to a chosen method and return a boolean mask.

This dispatcher forwards ds and params to the selected implementation (e.g. "fielding", "matecho"). Any optional arguments omitted in params are filled by that method’s own defaults.

Parameters:
dsxr.Dataset

Acoustic dataset with Sv and required coordinates. Must contain Sv in dB (default variable name "Sv") and include at least ping_time and a vertical/range coordinate (e.g. range_sample or a depth).

methodstr
Name of the detection method. Supported:
  • "fielding" → modified Fielding-style deep transient detector

  • "matecho" → Matecho-style column detector using local percentile

  • "ryan" → to be implemented TODO

paramsdict

Method-specific keyword arguments (see below). Omitted keys fall back to the method’s defaults.

When method == “fielding”, params can contain:
var_namestr, default “Sv”

Name of the Sv variable (dB).

range_varstr, default “depth”

Name of the vertical coordinate. Can be 1-D (range) or 2-D (time×range).

r0, r1float, default 900, 1000

Upper/lower bounds of the vertical window (m).

nint, default 30

Half-width of the temporal neighbourhood (pings) for the block median.

thr(float, float), default (3, 1)

Two-stage dB thresholds for detection/propagation.

rofffloat, default 20

Stop depth (m) for upward propagation (don’t propagate above this).

jumpsfloat, default 5

Vertical step (m) when iteratively moving the window upward.

maxtsfloat, default -35

Max 75th-percentile Sv (dB) for a ping to be considered “quiet”.

startint, default 0

Number of initial pings treated as uncomputable in the auxiliary mask (note: they are still kept/VALID unless you decide otherwise).

When method == “matecho”, params can contain:
var_namestr, default “Sv”

Name of the Sv variable (dB).

range_varstr, default “depth”

Vertical coordinate; reduced to 1-D per leading dim if 2-D.

time_varstr, default “ping_time”

Time/ping dimension name.

bottom_varstr | None, default None

Optional bottom depth per ping (m). If None/NaN, uses max range.

start_depthfloat, default 220

Top of the vertical detection window (m).

window_meterfloat, default 450

Vertical window thickness (m).

window_pingint, default 100

Temporal window width (pings) for local reference stats.

percentilefloat, default 25

Reference percentile (dB) of the local window.

delta_dbfloat, default 12

Excess over percentile (dB) required to flag a ping column.

extend_pingint, default 0

Optional horizontal dilation (pings) of flagged columns.

min_windowfloat, default 20

Minimum usable window height (m); skip if smaller.

When method == “ryan”, params can contain:

ryan (TODO)

Returns:
xr.DataArray

Boolean mask aligned to ds[var_name] (same dims and order), where True = VALID (keep) and False = transient noise. The name/attrs are set by the called method.

Raises:
ValueError

If method is not supported.

Examples

>>> from echopype.clean import detect_transient
>>> mask_fielding = detect_transient(
...     ds=ds_Sv_trimmed,
...     method="fielding",
...     params={
...         "var_name": "Sv",
...         "range_var": "depth",
...         "r0": 900,
...         "r1": 1000,
...         "n": 10,
...         "thr": (3, 1),
...         "roff": 20,
...         "jumps": 5,
...         "maxts": -35,
...         "start": 0,
...     },
... )

or

>>> from echopype.clean import detect_transient
>>> mask_matecho = detect_transient(
...     ds=ds_Sv,
...     method="matecho",
...     params={
...         "var_name": "Sv",
...         "range_var": "depth",
...         "bottom_var": None,
...         "start_depth": 700,
...         "window_meter": 300,
...         "window_ping": 50,
...         "percentile": 25,
...         "delta_db": 8,
...         "extend_ping": 0,
...         "min_window": 5,
...     },
... )
echopype.clean.estimate_background_noise(ds_Sv: Dataset, ping_num: int, range_sample_num: int, background_noise_max: str = None) → DataArray#

Estimate background noise by computing mean calibrated power of a collection of pings.

Parameters:
ds_Svxr.Dataset

Dataset containing Sv and echo_range [m].

ping_numint

Number of pings to obtain noise estimates

range_sample_numint

Number of samples along the range_sample dimension to obtain noise estimates.

background_noise_maxstr, default None

The upper limit (dB) for background noise expected under the operating conditions.

Returns:
A DataArray containing noise estimated from the input ds_Sv

Notes

This function’s implementation is based on the following text reference:

De Robertis & Higginbottom. 2007. A post-processing technique to estimate the signal-to-noise ratio and remove echosounder background noise. ICES Journal of Marine Sciences 64(6): 1282–1291.

echopype.clean.mask_attenuated_signal(ds_Sv: Dataset, upper_limit_sl: str = '400.0m', lower_limit_sl: str = '500.0m', num_side_pings: int = 15, attenuation_signal_threshold: str = '8.0dB', range_var: str = 'depth') → DataArray#

Locate attenuated signals and create an attenuated signal mask.

Parameters:
ds_Svxarray.Dataset

Calibrated Sv data with depth data variable.

upper_limit_slstr, default “400m”

Upper limit of deep scattering layer line (m).

lower_limit_slstr, default “500m”

Lower limit of deep scattering layer line (m).

num_side_pingsint, default 15

Number of preceding & subsequent pings defining the block.

attenuation_signal_thresholdstr, default “8.0dB”

Attenuation signal threshold value (dB) for the ping-block comparison.

range_varstr, default “depth”

Vertical Axis Range Variable. Can be either depth or echo_range.

Returns:
xr.Dataset

Xarray boolean array attenuated signal mask.

References

This function’s implementation is based on the following text reference:

Ryan et al. (2015) Reducing bias due to noise and attenuation in open-ocean echo integration data, ICES Journal of Marine Science, 72: 2482–2493.

Additionally, code was derived from echopy’s numpy single-channel implementation of attenuation signal masking and translated into xarray code: open-ocean-sounding/echopy

echopype.clean.mask_impulse_noise(ds_Sv: Dataset, depth_bin: str = '5m', num_side_pings: int = 2, impulse_noise_threshold: str = '10.0dB', range_var: str = 'depth', use_index_binning: bool = False) → DataArray#

Locate and create a mask for impulse noise using a ping-wise two-sided comparison.

Parameters:
ds_Svxarray.Dataset

Calibrated Sv data with depth data variable.

depth_binstr, default “5m”

Donwsampling bin size along vertical range variable (range_var) in meters.

num_side_pingsint, default 2

Number of side pings to look at for the two-side comparison.

impulse_noise_thresholdstr, default “10.0dB”

Impulse noise threshold value (dB) for the two-side comparison.

range_varstr, default “depth”

Vertical Axis Range Variable. Can be either “depth” or “echo_range”.

use_index_binningbool, default False

Speeds up aggregations by assuming depth is uniform and binning based on range_sample indices instead of depth values.

Returns:
xr.Dataset

Xarray boolean array impulse noise mask.

References

This function’s implementation is based on the following text reference:

Ryan et al. (2015) Reducing bias due to noise and attenuation in open-ocean echo integration data, ICES Journal of Marine Science, 72: 2482–2493.

Additionally, code was derived from echopy’s numpy single-channel implementation of impulse noise masking and translated into xarray code: open-ocean-sounding/echopy

echopype.clean.mask_transient_noise(ds_Sv: Dataset, func: str = 'nanmean', depth_bin: str = '10m', num_side_pings: int = 25, exclude_above: str = '250.0m', transient_noise_threshold: str = '12.0dB', range_var: str = 'depth', use_index_binning: bool = False, chunk_dict: dict = {}) → DataArray#

Locate and create a mask for transient noise using a pooling comparison.

Parameters:
ds_Svxarray.Dataset

Calibrated Sv data with depth data variable.

func: str, default “nanmedian”

Pooling function used in the pooled Sv aggregation.

depth_binstr, default “10m”

Pooling bin size vertically along the vertical range variable (range_var).

num_side_pingsint, default 25

Number of side pings to look at for the pooling.

exclude_abovestr, default “250m”

Exclude all depth above (closer to the surface than) this value.

transient_noise_thresholdstr, default “10.0dB”

Transient noise threshold value (dB) for the pooling comparison.

range_varstr, default “depth”

Vertical Range Variable. Can be either depth or echo_range.

use_index_binningbool, default False

Speeds up aggregations by assuming depth is uniform and binning based on range_sample indices instead of depth values.

chunk_dictdict, default {}

Dictionary containing chunk sizes for use in the Dask-Image pooling function. Only used when use_index_binning=True.

Returns:
xr.Dataset

Xarray boolean array transient noise mask.

References

This function’s implementation is based on the following text reference:

Ryan et al. (2015) Reducing bias due to noise and attenuation in open-ocean echo integration data, ICES Journal of Marine Science, 72: 2482–2493.

Additionally, this code was derived from echopy’s numpy single-channel implementation of transient noise masking and translated into xarray code: open-ocean-sounding/echopy

Examples

Default Transient Noise Mask Usage: Without using index binning along the vertical axis:

>>> mask_transient_noise(
>>>     ds_Sv
>>>     func="nanmean",
>>>     depth_bin = "10m",
>>>     num_side_pings = 25,
>>>     exclude_above = "250.0m",
>>>     transient_noise_threshold = "12.0dB",
>>>     range_var = "depth",
>>>     use_index_binning = False
>>> )

Vertical Index Binning Transient Noise Mask Usage with Chunking across Vertical and Horizontal Axis:

>>> mask_transient_noise(
>>>     ds_Sv
>>>     func="nanmean",
>>>     depth_bin = "10m",
>>>     num_side_pings = 25,
>>>     exclude_above = "250.0m",
>>>     transient_noise_threshold = "12.0dB",
>>>     range_var = "depth",
>>>     use_index_binning = True,
>>>     chunk_dict = {"ping_time": 1000, "range_sample": 50}
>>> )

To compute the pooled Sv, prior to the binning operation, the number of range sample indices needed to encapsulate “10m” will be calculated, and this number will be used to do a completely index based nanmean binning operation. This operation is exactly the same as applying a mean filter over an image, but in this case, it is applied to an Echogram.

echopype.clean.remove_background_noise(ds_Sv: Dataset, ping_num: int, range_sample_num: int, background_noise_max: str = None, SNR_threshold: str = '3.0dB') → Dataset#

Remove noise by using estimates of background noise from mean calibrated power of a collection of pings.

Parameters:
ds_Svxr.Dataset

dataset containing Sv and echo_range [m]

ping_numint

Number of pings to obtain noise estimates.

range_sample_numint

Number of samples along the range_sample dimension to obtain noise estimates.

background_noise_maxstr, default None

The upper limit for background noise expected under the operating conditions.

SNR_thresholdstr, default “3.0dB”

Acceptable signal-to-noise ratio, default to 3 dB.

Returns:
The input dataset with additional variables, including
the corrected Sv (Sv_corrected) and the noise estimates (Sv_noise)

Notes

This function’s implementation is based on the following text reference:

De Robertis & Higginbottom. 2007. A post-processing technique to estimate the signal-to-noise ratio and remove echosounder background noise. ICES Journal of Marine Sciences 64(6): 1282–1291.

commongrid#

echopype.commongrid.compute_MVBS(ds_Sv: Dataset, range_var: Literal['echo_range', 'depth'] = 'echo_range', range_bin: str = '20m', ping_time_bin: str = '20s', method: str = 'map-reduce', reindex: bool = False, skipna: bool = True, fill_value: float = nan, closed: Literal['left', 'right'] = 'left', range_var_max: str = None, **flox_kwargs)#

Compute Mean Volume Backscattering Strength (MVBS) based on intervals of range (echo_range) or depth (depth) and ping_time specified in physical units.

Output of this function differs from that of compute_MVBS_index_binning, which computes bin-averaged Sv according to intervals of echo_range and ping_time specified as index number.

Parameters:
ds_Svxr.Dataset

dataset containing Sv and echo_range [m]

range_var: {‘echo_range’, ‘depth’}, default ‘echo_range’

The variable to use for range binning. Must be one of echo_range or depth. Note that depth is only available if the input dataset contains depth as a data variable.

range_binstr, default ‘20m’

bin size along echo_range or depth in meters.

ping_time_binstr, default ’20s’

bin size along ping_time

method: str, default ‘map-reduce’

The flox strategy for reduction of dask arrays only. See flox documentation for more details.

reindex: bool, default False

If False, reindex after the blockwise stage. If True, reindex at the blockwise stage. Generally, reindex=False results in less memory at the cost of computation speed. Can only be used when method=’map-reduce’. See flox documentation for more details.

skipna: bool, default True

If true, the mean operation skips NaN values. Else, the mean operation includes NaN values.

fill_value: float, default np.nan

Fill value when no group data exists to aggregate.

closed: {‘left’, ‘right’}, default ‘left’

Which side of bin interval is closed.

range_var_max: str, default None

Range variable maximum. Can be true range variable maximum or the maximum depth the user wishes to regrid to. If known, users can pass in range variable maximum to ensure that compute_MVBS can lazily run without any computation.

**flox_kwargs

Additional keyword arguments to be passed to flox reduction function.

Returns:
A dataset containing bin-averaged Sv
echopype.commongrid.compute_MVBS_index_binning(ds_Sv, range_sample_num=100, ping_num=100)#

Compute Mean Volume Backscattering Strength (MVBS) based on intervals of range_sample and ping number (ping_num) specified in index number.

Output of this function differs from that of compute_MVBS, which computes bin-averaged Sv according to intervals of range (echo_range) and ping_time specified in physical units.

Parameters:
ds_Svxr.Dataset

dataset containing Sv and echo_range [m]

range_sample_numint

number of samples to average along the range_sample dimension, default to 100

ping_numint

number of pings to average, default to 100

Returns:
A dataset containing bin-averaged Sv
echopype.commongrid.compute_NASC(ds_Sv: Dataset, range_bin: str = '10m', dist_bin: str = '0.5nmi', method: str = 'map-reduce', skipna=True, closed: Literal['left', 'right'] = 'left', **flox_kwargs) → Dataset#

Compute Nautical Areal Scattering Coefficient (NASC) from an Sv dataset. TODO: Add range_var_max and reindex parameters to match compute_MVBS.

Parameters:
ds_Svxr.Dataset

A dataset containing Sv data. The Sv dataset must contain latitude, longitude, and depth as data variables.

range_binstr, default ‘10m’

bin size along depth in meters (m).

dist_binstr, default ‘0.5nmi’

bin size along distance in nautical miles (nmi).

method: str, default ‘map-reduce’

The flox strategy for reduction of dask arrays only. See flox documentation for more details.

skipna: bool, default True

If true, the mean operation skips NaN values. Else, the mean operation includes NaN values.

closed: {‘left’, ‘right’}, default ‘left’

Which side of bin interval is closed.

**flox_kwargs

Additional keyword arguments to be passed to flox reduction function.

Returns:
xr.Dataset

A dataset containing NASC

Notes

The NASC computation implemented here generally corresponds to the Echoview algorithm PRC_NASC https://support.echoview.com/WebHelp/Reference/Algorithms/Analysis_Variables/PRC_ABC_and_PRC_NASC.htm#PRC_NASC The difference is that since in echopype masking of the Sv dataset is done explicitly using functions in the mask subpackage, the computation only involves computing the mean Sv and the mean height within each cell, where some Sv “pixels” may have been masked as NaN.

In addition, in echopype the binning of pings into individual cells is based on the actual horizontal distance computed from the latitude and longitude coordinates of each ping in the Sv dataset. Therefore, both regular and irregular horizontal distance in the Sv dataset are allowed. This is different from Echoview’s assumption of constant ping rate, vessel speed, and sample thickness when computing mean Sv (see https://support.echoview.com/WebHelp/Reference/Algorithms/Analysis_Variables/Sv_mean.htm#Conversions).

echopype.commongrid.resample_to_geometry(ds_Sv, target_variable: str = 'Sv', is_log: bool = True, target_channel: str | None = None, target_grid: DataArray | None = None)#

Regrids a variable across all channels in an Sv or Sp dataset to a common range geometry specified by either a target channel or a custom target grid. Ping time is assumed identical for all input channels.

Parameters:
ds_Svxr.Dataset

Input Dataset containing Sv data

target_variablestr, default “Sv”

Name of the variable to resample. The variable must exist in ds_Sv.

is_logbool, default True

Whether target_variable contains logarithmic values. If True, values are converted to the linear domain before weighted averaging and converted back afterward.

target_channelstr, optional

Channel used as reference grid. Must be provided if target_grid is None.

target_gridxr.DataArray, optional

Custom range grid. Must be provided if target_channel is None. The grid may have dimension ("range_sample",) for a common grid across all pings, or ("ping_time", "range_sample") for a ping-dependent grid. Its range_sample length may differ from that of the input dataset.

Returns:
xr.Dataset

A new Dataset where all channels share the same ping_time, range_sample, and echo_range as the target. ping_time is assumed identical across all input channels and preserved throughout the resampling process. The resulting target geometry, whether specified using target_channel` or target_grid, can be retrieved with target_grid = regridded_ds[“echo_range”].

consolidate#

echopype.consolidate.add_depth(ds: Dataset | str | Path, echodata: EchoData | str | Path | None = None, depth_offset: Number | DataArray | None = None, tilt: Number | DataArray | None = None, downward: bool = True, use_platform_vertical_offsets: bool = False, use_platform_angles: bool = False, use_beam_angles: bool = False) → Dataset#

Create a depth data variable based on data in Sv dataset, Echodata object, and/or user input depth offset and tilt data.

Parameters:
dsxr.Dataset or str or pathlib.Path

Source Sv dataset to which a depth variable will be added.

echodataOptional[EchoData, str, pathlib.Path], default None

EchoData object from which the Sv dataset originated.

depth_offsetOptional[Union[Number, xr.DataArray]], default None

Offset along the vertical (depth) dimension to account for actual transducer position in water, since echo_range is counted from transducer surface. If provided as an xr.DataArray, it must have a single dimension corresponding to time. The data array should represent the depth offset in meters at each time step.

tiltOptional[Union[Number, xr.DataArray]], default None.

Transducer tilt angle [degree]. 0 corresponds to a transducer pointing vertically. If provided as an xr.DataArray, it must have a single dimension corresponding to time. The data array should represent the tilt angle in degrees at each time step.

downwardbool, default True

The transducers point downward.

use_platform_vertical_offsets: bool, default `False`

If True, use Echodata Platform group vertical offset values to compute transducer depth. Currently only implemented for EK60/EK80 sonar models. If depth_offset is specified, Platform vertical offset values will not be used.

use_platform_angles: bool, `False`

If True, use Echodata Platform group angle values to compute echo_range scaling values. Currently only implemented for EK60/EK80 sonar models. If tilt is specified, Platform group angle values will not be used. In the current implementation cannot be used in tandem with use_beam_angles.

use_beam_angles: bool `False`

If True, use Echodata Beam group angle values to compute echo_range scaling values. Currently only implemented for EK60/EK80 sonar models. If tilt is specified, Beam group angle values will not be used. In the current implementation cannot be used in tandem with use_platform_angles.

Returns:
The input dataset with a depth variable (in meters) added.
echopype.consolidate.add_location(ds: Dataset | str | Path, echodata: EchoData | str | Path, datagram_type: str | None = None, nmea_sentence: str | None = None)#

Add geographical location (latitude/longitude) to the Sv dataset.

This function interpolates the location from the Platform group in the original data file based on the time when the latitude/longitude data are recorded and the time the acoustic data are recorded (ping_time).

Parameters:
dsxr.Dataset or str or pathlib.Path

An Sv or MVBS dataset or path to a file containing the Sv or MVBS dataset for which the geographical locations will be added to

echodataEchoData or str or pathlib.Path

An EchoData object or path to a file containing the EchoData object holding the raw data

datagram_typeOptional[str], default None

Datagram type to use for latitude and longitude. If None (default), latitude and longitude derived from NMEA datagrams will be used. Can be “MRU1” or “IDX”. Can only be used for data for EK sonar models.

nmea_sentenceOptional[str], default None

NMEA sentence to select a subset of location data. Only applied if latitude and longitude derived from NMEA datagram are used (default).

Returns:
The input dataset with the location data added

Notes

If duplicated time values are found in the latitude/longitude data, only the first entry is kept for the interpolation operation, and a warning is issued.

echopype.consolidate.add_splitbeam_angle(source_Sv: Dataset | str | Path, echodata: EchoData | str | Path, waveform_mode: str, encode_mode: str, pulse_compression: bool = False, storage_options: dict = {}, to_disk: bool = True, drop_last_hanning_zero: bool = False) → Dataset#

Add split-beam (alongship/athwartship) angles into the Sv dataset. This function calculates the alongship/athwartship angle using data stored in the Sonar/Beam_groupX groups of an EchoData object.

In cases when angle data does not already exist or cannot be computed from the data, an error is issued and no angle variables are added to the dataset.

Parameters:
source_Sv: xr.Dataset or str or pathlib.Path

The Sv Dataset or path to a file containing the Sv Dataset, to which the split-beam angles will be added

echodata: EchoData or str or pathlib.Path

An EchoData object or path to a file containing the EchoData object holding the raw data

waveform_mode{“CW”, “BB”}

Type of transmit waveform

  • "CW" for narrowband transmission, returned echoes recorded either as complex or power/angle samples

  • "BB" for broadband transmission, returned echoes recorded as complex samples

encode_mode{“complex”, “power”}

Type of encoded return echo data

  • "complex" for complex samples

  • "power" for power/angle samples, only allowed when the echosounder is configured for narrowband transmission

pulse_compression: bool, False

Whether pulse compression should be used (only valid for waveform_mode="BB" and encode_mode="complex")

storage_options: dict, default={}

Any additional parameters for the storage backend, corresponding to the path provided for source_Sv

to_disk: bool, default=True

If False, to_disk with split-beam angles added will be returned. to_disk=True is useful when source_Sv is a path and users only want to write the split-beam angle data to this path.

drop_last_hanning_zero: bool, default False

If true, uses the pyEcholab implementation of dropping the hanning window’s last index value (which is zero). Else, follows the CRIMAC implementation and keeps the last zero. This is here for CI test purposes.

Returns:
xr.Dataset or None

If to_disk=False, nothing will be returned. If to_disk=True, either the input dataset source_Sv or a lazy-loaded Dataset (from the path source_Sv) with split-beam angles added will be returned.

Raises:
ValueError

If echodata has a sonar model that is not analogous to either EK60 or EK80

ValueError

If the input source_Sv does not have a channel dimension

ValueError

If source_Sv does not have appropriate dimension lengths in comparison to echodata data

ValueError

If the provided waveform_mode, encode_mode, and pulse_compression are not valid

NotImplementedError

If an unknown beam_type is encountered during the split-beam calculation

Notes

Split-beam angle data potentially exist for the Simrad EK60 or EK80 echosounders with split-beam transducers and configured to store angle data (along with power samples) or store raw complex samples.

In most cases where the type of samples collected by the echosounder (power/angle samples or complex samples) and the transmit waveform (broadband or narrowband) are identical across all channels, the channels existing in source_Sv and ` echodata` will be identical. If this is not the case, only angle data corresponding to channels existing in source_Sv will be added.

echopype.consolidate.swap_dims_channel_frequency(ds: Dataset | str | Path) → Dataset#

Use frequency_nominal in place of channel to be dataset dimension and coorindate.

This is useful because the nominal transducer frequencies are commonly used to refer to data collected from a specific transducer.

Parameters:
dsxr.Dataset or str or pathlib.Path

Dataset or path to a file containing the Dataset for which the dimension will be swapped

Returns:
The input dataset with the dimension swapped

Notes

This operation is only possible when there are no duplicated frequencies present in the file.

mask#

echopype.mask.apply_mask(source_ds: Dataset | str | Path, mask: DataArray | str | Path | List[DataArray | str | Path], var_name: str = 'Sv', fill_value: int | float | DataArray = nan, storage_options_ds: dict = {}, storage_options_mask: dict | List[dict] = {}) → Dataset#

Applies the provided mask(s) to the Sv variable var_name in the provided Dataset source_ds.

The code allows for these 3 cases of source_ds and mask dimensions:

1) No channel in both source_ds and mask, but they have matching ping_time and depth (or range_sample) dimensions. 2) source_ds and mask both have matching channel, ping_time, and depth (or range_sample) dimensions. 3) source_ds has the channel dimension and mask doesn’t, but they have matching ping_time and depth (or range_sample) dimensions.

If a user only wants to apply masks to a subset of the channels in source_ds, they could put 1s to allow all data entries in the other channels.

Parameters:
source_ds: xr.Dataset, str, or pathlib.Path

Points to a Dataset that contains the variable the mask should be applied to

mask: xr.DataArray, str, pathlib.Path, or a list of these datatypes
The mask(s) to be applied. Must contain only boolean values (True/False or 1/0).
If the mask contains numeric or NaN values, an error will be raised.

Can be a individual input or a list that corresponds to a DataArray or a path. Each individual input or entry in the list must contain dimensions ('ping_time', 'range_sample') or dimensions ('ping_time', 'depth'). The mask can also contain the dimension channel. If a path is provided this should point to a zarr or netcdf file with only one data variable in it. If the input mask is a list, a logical AND will be used to produce the final mask that will be applied to var_name.

var_name: str, default=”Sv”

The Sv variable name in source_ds that the mask should be applied to. This variable needs to have coordinates ('ping_time', 'range_sample') or coordinates ('ping_time', 'depth'), and can optionally also have coordinate channel. In the case of a multi-channel Sv data variable, the mask will be broadcast to all channels.

fill_value: int, float, or xr.DataArray, default=np.nan

Value(s) at masked indices. If fill_value is of type xr.DataArray it must have the same shape as each entry of mask.

storage_options_ds: dict, default={}

Any additional parameters for the storage backend, corresponding to the path provided for source_ds

storage_options_mask: dict or list of dict, default={}

Any additional parameters for the storage backend, corresponding to the path provided for mask. If mask is a list, then this input should either be a list of dictionaries or a single dictionary with storage options that correspond to all elements in mask that are paths.

Returns:
xr.Dataset

A Dataset with the same format of source_ds with the mask(s) applied to var_name

echopype.mask.detect_seafloor(ds: Dataset, method: str, params: Dict) → DataArray#

Dispatch seafloor detection to a chosen method and return a 1-D bottom line.

This function forwards ds and params to the selected implementation (e.g., "basic", "blackwell"). Any optional arguments omitted in params are filled by that method’s defaults.

Parameters:
dsxr.Dataset

Dataset containing calibrated Sv and required coordinates (at minimum ping_time and a vertical coordinate such as depth), plus any extra variables required by the chosen method.

methodstr
Name of the detection method to use. Supported:
  • "basic" → threshold-only detector

  • "blackwell" → Sv + split-beam angle detector

paramsdict

Method-specific keyword arguments (see below). Unspecified keys use the method’s defaults.

When method == “basic”, params can contain:
var_namestr

Name of Sv variable (dB), e.g. "Sv".

channelstr

Channel identifier to select (e.g., "GPT  38 kHz ...").

thresholdfloat, default -50.0

Sv threshold(s) in dB. If a single float is given, it is treated as the lower bound and the upper bound is set to 10 dB above the lower bound. If a 2-tuple (tmin, tmax) is provided, both the lower and upper bounds are used directly.

offset_mfloat, default 0.5

Meters subtracted from the detected crossing.

bin_skip_from_surfaceint, default 200

Number of shallow range bins to ignore before searching.

When method == “blackwell”, params can contain:
var_namestr

Name of the Sv variable to use (e.g., "Sv").

channelstr

Channel identifier to select.

thresholdfloat | list | tuple, default -75

Either a single Sv dB threshold (angle thresholds use defaults), or a 3-tuple/list (tSv_dB, ttheta, tphi) after angle smoothing.

offsetfloat, default 0.3

Meters subtracted from the detected bottom.

r0float, default 0

Shallow bound (m) of the detection range.

r1float, default 500

Deep bound (m) of the detection range.

wthetaint, default 28

Square smoothing window (pixels) for along-ship angle.

wphiint, default 52

Square smoothing window (pixels) for athwart-ship angle.

Returns:
xr.DataArray

1-D bottom depth per ping_time (no channel dimension). The output name and attributes are set by the called method.

Raises:
ValueError

If method is not supported.

Examples

>>> detect_seafloor(ds, "basic", {
...     "var_name": "Sv", "channel": "GPT  38 kHz ...",
...     "threshold": -50, "offset_m": 0.5, "bin_skip_from_surface": 200
... })
>>> detect_seafloor(ds, "blackwell", {
...     "channel": "GPT  38 kHz ...", "threshold": (-75, 0.02, 0.02),
...     "offset": 0.3, "r0": 0, "r1": 600, "wtheta": 28, "wphi": 52
... })
echopype.mask.detect_shoal(ds: Dataset, method: str, params: Dict) → DataArray#

Detect shoals using the selected method and return a 2D boolean mask.

Parameters:
dsxr.Dataset

Sv dataset including ping_time and range_sample.

methodstr

Name of the detection method to use (e.g., “echoview”, “weill”).

paramsdict

Parameters for the detection function (method-specific).

Returns:
xr.DataArray

2D boolean DataArray of shoal mask (True = inside).

echopype.mask.frequency_differencing(source_Sv: Dataset | str | Path, storage_options: dict | None = {}, freqABEq: str | None = None, chanABEq: str | None = None) → DataArray#

Create a mask based on the differences of Sv values using a pair of frequencies. This method is often referred to as the “frequency-differencing” or “dB-differencing” method.

Parameters:
source_Sv: xr.Dataset or str or pathlib.Path

If a Dataset this value contains the Sv data to create a mask for, else it specifies the path to a zarr or netcdf file containing a Dataset. This input must correspond to a Dataset that has the coordinate channel and variables frequency_nominal and Sv.

storage_options: dict, optional

Any additional parameters for the storage backend, corresponding to the path provided for source_Sv

freqABEq: string, optional

The frequency differencing criteria. Only one of freqAB and chanAB should be provided, and not both.

chanAB: string, optional

The frequency differencing criteria in terms of channel names where channel names in the criteria are enclosed in double quotes. Only one of freqAB and chanAB should be provided, and not both.

Returns:
xr.DataArray

A DataArray containing the mask for the Sv data. Regions satisfying the thresholding criteria are filled with True, else the regions are filled with False.

Raises:
ValueError

If neither freqABEq or chanABEq are given

ValueError

If both freqABEq and chanABEq are given

TypeError

If any input is not of the correct type

ValueError

If either freqABEq or chanABEq are provided and the extracted freqAB or chanAB does not contain 2 distinct elements

ValueError

If freqABEq contains values that are not contained in frequency_nominal

ValueError

If chanABEq contains values that not contained in channel

ValueError

If operator is not one of the following: ">", "<", "<=", ">=", "=="

ValueError

If the path provided for source_Sv is not a valid path

ValueError

If freqABEq or chanABEq is provided and the Dataset produced by source_Sv does not contain the coordinate channel and variable frequency_nominal

Notes

This function computes the frequency differencing as follows: Sv_freqA - Sv_freqB operator diff. Thus, if operator = "<" and diff = "5" the following would be calculated: Sv_freqA - Sv_freqB < 5.

Examples

Compute frequency-differencing mask using a mock Dataset and channel selection:

>>> n = 5 # set the number of ping times and range samples
...
>>> # create mock Sv data
>>> Sv_da = xr.DataArray(data=np.stack([np.arange(n**2).reshape(n,n), np.identity(n)]),
...                      coords={"channel": ['chan1', 'chan2'],
...                              "ping_time": np.arange(n), "range_sample":np.arange(n)})
...
>>> # obtain mock frequency_nominal data
>>> freq_nom = xr.DataArray(data=np.array([1.0, 2.0]),
...                         coords={"channel": ['chan1', 'chan2']})
...
>>> # construct mock Sv Dataset
>>> Sv_ds = xr.Dataset(data_vars={"Sv": Sv_da, "frequency_nominal": freq_nom})
...
>>> # compute frequency-differencing mask using channel names
>>> echopype.mask.frequency_differencing(source_Sv=Sv_ds, storage_options={},
...                                      freqABEq=None, chanABEq = '"chan1" - "chan2">=10.0dB')
<xarray.DataArray 'mask' (ping_time: 5, range_sample: 5)>
array([[False, False, False, False, False],
       [False, False, False, False, False],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True]])
Coordinates:
  * ping_time     (ping_time) int64 0 1 2 3 4
  * range_sample  (range_sample) int64 0 1 2 3 4
echopype.mask.regrid_mask(mask_da: DataArray, range_da: DataArray, range_bin: str = '20m', ping_time_bin: str = '20s', third_dim: str = None, func: Literal['logical-AND', 'logical-OR'] = 'logical-AND', method: str = 'map-reduce', reindex: bool = False, closed: Literal['left', 'right'] = 'left', range_var_max: str = None, **flox_kwargs) → DataArray#

Regrid mask through downsampling via a logical AND operation.

Parameters:
mask_daxr.DataArray

Mask DataArray. Must be binary 0/1 or True/False. Must have two dimensions: ‘depth’ and ‘ping_time’.

range_binstr, default ‘20m’

bin size along ‘range_sample’ or ‘depth’ in meters.

ping_time_binstr, default ’20s’

bin size along ‘ping_time’

third_dimstr, default None

Name for non-binned region. If None, use ‘xarray_reduce’ to operate on 2D array. Else, use ‘xarray_reduce’ to operate on 3D array with unbinned 3rd dimension.

func: {‘logical-AND’, ‘logical-OR’}, default ‘logical-AND’

When func == ‘logical-AND’, the output value is set to 1 or True only if all values in the regrid bin are 1 or True. When func == ‘logical-OR’, the output value is set to 1 or True if any value in the regrid bin is 1 or True.

method: str, default ‘map-reduce’

The flox strategy for reduction of dask arrays only. See flox documentation for more details.

reindex: bool, default False

If False, reindex after the blockwise stage. If True, reindex at the blockwise stage. Generally, reindex=False results in less memory usage at the cost of computation speed. Can only be used when method=’map-reduce’. See flox documentation for more details.

closed: {‘left’, ‘right’}, default ‘left’

Which side of bin interval is closed.

range_var_max: str, default None

Maximum value of the range variable. If this value is known, it is recommended to provide it as an input as it makes the underlying computation more efficient (by skipping a max computation and keeping the data lazily-loaded).

**flox_kwargs

Additional keyword arguments to be passed to flox reduction function.

Returns:
A DataArray containing a regridded mask.

metrics#

Functions to compute summary statistics from echo data.

echopype.metrics.abundance(ds: Dataset, range_label='echo_range') → DataArray#

Calculates the area-backscattering strength (Sa) [unit: dB re 1 m^2 m^-2].

This quantity is the integral of volumetric backscatter over range (echo_range).

Parameters:
dsxr.Dataset
range_labelstr

Name of an xarray DataArray in ds containing echo_range information.

Returns:
xr.DataArray
echopype.metrics.aggregation(ds: Dataset, range_label='echo_range') → DataArray#

Calculated the index of aggregation (IA) [unit: m^-1].

This quantity is reciprocal of the equivalent area. IA is high when small areas are much denser than the rest of the distribution.

Parameters:
dsxr.Dataset
range_labelstr

Name of an xarray DataArray in ds containing echo_range information.

Returns:
xr.DataArray
echopype.metrics.center_of_mass(ds: Dataset, range_label='echo_range') → DataArray#

Calculates the mean backscatter location [unit: m].

This quantity is the weighted average of backscatter along range (echo_range).

Parameters:
dsxr.Dataset
range_labelstr

Name of an xarray DataArray in ds containing echo_range information.

Returns:
xr.DataArray
echopype.metrics.dispersion(ds: Dataset, range_label='echo_range') → DataArray#

Calculates the inertia (I) [unit: m^-2].

This quantity measures dispersion or spread of backscatter from the center of mass.

Parameters:
dsxr.Dataset
range_labelstr

Name of an xarray DataArray in ds containing echo_range information.

Returns:
xr.DataArray
echopype.metrics.evenness(ds: Dataset, range_label='echo_range') → DataArray#

Calculates the equivalent area (EA) [unit: m].

This quantity represents the area that would be occupied if all datacells contained the mean density.

Parameters:
dsxr.Dataset
range_labelstr

Name of an xarray DataArray in ds containing echo_range information.

Returns:
xr.DataArray

qc#

echopype.qc.coerce_increasing_time(ds: Dataset, time_name: str = 'ping_time', win_len: int = 100) → None#

Coerce a time coordinate so that it always flows forward. If coercion is necessary, the input ds will be directly modified.

Parameters:
dsxr.Dataset

a dataset for which the time coordinate needs to be corrected

time_namestr

name of the time coordinate to be corrected

win_lenint

length of the local window before the reversed timestamp within which the median pinging interval is used to infer the next ping time

Returns:
the input dataset but with specified time coordinate coerced to flow forward

Notes

This is to correct for problems sometimes observed in EK60/80 data where a time coordinate (ping_time or time1) would suddenly go backward for one ping, but then the rest of the pinging interval would remain undisturbed.

Examples

>>> import xarray as xr
>>> from echopype.qc.api import exist_reversed_time, coerce_increasing_time
>>> ds = xr.open_dataset("my_dataset.nc")
>>> if exist_reversed_time(ds, "ping_time"):  # check for reversed time
...     coerce_increasing_time(ds, "ping_time")  # correct the time coordinate in place
echopype.qc.exist_reversed_time(ds, time_name)#

Test for occurrence of time reversal in specified datetime coordinate variable.

Parameters:
dsxr.Dataset

a dataset for which the time coordinate will be tested

time_namestr

name of the time coordinate to be tested

Returns:
True if at least one time reversal is found, False otherwise.

Utilities#

Seawater properties#

Utilities for calculating seawater acoustic properties.

echopype.utils.uwa.calc_absorption(frequency, temperature=27, salinity=35, pressure=10, pH=8.1, sound_speed=None, formula_source='AM')#

Calculate sea water absorption in units [dB/m].

Parameters:
frequency: int or numpy array

frequency [Hz]

temperature: num

temperature [deg C]

salinity: num

salinity [PSU, part per thousand]

pressure: num

pressure [dbars]

pH: num

pH of water

formula_source: str, {“AM”, “FG”, “AZFP”}

Source of formula used to calculate sound speed. “AM” (default) uses the formula from Ainslie and McColm (1998). “FG” uses the formula from Francois and Garrison (1982). “AZFP” uses the the formula supplied in the AZFP Matlab code. See Notes below for the references.

Returns:
Sea water absorption [dB/m].

Notes

Ainslie MA, McColm JG. (1998). A simplified formula for viscous and chemical absorption in sea water. The Journal of the Acoustical Society of America, 103(3), 1671–1672. https://doi.org/10.1121/1.421258

Francois RE, Garrison GR. (1982). Sound absorption based on ocean measurements. Part II: Boric acid contribution and equation for total absorption. The Journal of the Acoustical Society of America, 72(6), 1879–1890. https://doi.org/10.1121/1.388673

The accuracy of the simplified formula from Ainslie & McColm 1998 compared with the original complicated formula from Francois & Garrison 1982 was demonstrated between 100 Hz and 1 MHz.

echopype.utils.uwa.calc_sound_speed(temperature=27, salinity=35, pressure=10, formula_source='Mackenzie')#

Calculate sound speed in [m/s].

Parameters:
temperature: num

temperature [deg C]

salinity: num

salinity [PSU, part per thousand]

pressure: num

pressure [dbars]

formula_source: str, {“Mackenzie”, “AZFP”}

Source of formula used to calculate sound speed. “Mackenzie” (default) uses the formula from Mackenzie 1981 (see Notes below) as implemented in arlpy package. “AZFP” uses the formula supplied in the AZFP Matlab code.

Returns:
Sound speed [m/s] for each input temperature value.

Notes

Mackenzie KV (1981) Nine‐term equation for sound speed in the oceans. The Journal of the Acoustical Society of America, 70(3), 807–812. https://doi.org/10.1121/1.386920 The ranges of validity encompass the following: temperature −2 to 30 °C, salinity 30 to 40 ppt, and depth 0 to 8000 m.

Colormaps#

Colormaps for plotting echograms.

Importing this package (i.e., import echopype.colormaps) adds echogram-specific colormaps to Matplotlib’s existing colormaps. These always start with ep. and come in pairs (the colormap and a reversed version with a name ending in _r).

Echopype currently provides two colormaps, ep.ek500 and ep.ek500_r, based on the colormap that the Simrad EK500 echosounder used.

Notes#

To use this subpackage the matplotlib package must be installed.

Examples#

The list of colormaps added can be found with this code:

>>> import echopype.colormap
>>> from matplotlib import colormaps
>>> print([name for name in colormaps if name.startswith('ep.')])
['ep.ek500', 'ep.ek500_r']