index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
73,762
DeRaafMedia/ProjectIRCInteractivity
refs/heads/master
/skills/template_serial_device.py
import sys import serial def main(arg_1, arg_2, arg_3, arg_4): serial_port = str(arg_1) baud_rate = int(arg_2) time_out = int(arg_3) parameter = int(arg_4) device = serial.Serial(serial_port, baud_rate, timeout=time_out) # Function here pass if __name__ == "__main__": main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]) pass
{"/Arduino.py": ["/SerialPort.py"]}
73,763
DeRaafMedia/ProjectIRCInteractivity
refs/heads/master
/Utilities.py
__author__ = 'DeRaaf' # TODO Clean up comments. Fix bugs. On going project! import os from os import system import sys import ConfigParser import threading import csv import time class Utilities (object): def __init__(self): self.preference_parser = ConfigParser.RawConfigParser() self.thread = threading.Thread() self.preference_file = 'pref/preferences.txt' self.initiate_preference() self.chat_log_enabled = self.read_preference('Log Settings', 'chat') self.voice_enabled = self.read_preference('Speak', 'voice_enabled') self.chat_voice_enabled = self.read_preference('Speak', 'chat_voice_enabled') self.announcement_voice_enabled = self.read_preference('Speak', 'announcement_voice_enabled') self.voice = self.read_preference('Voices', 'voice') self.chat_voice = self.read_preference('Voices', 'chat_voice') self.announcement_voice = self.read_preference('Voices', 'announcement_voice') self.chat_directory = 'logs/chat/' self.timestamp = time.strftime('%m%d%Y%H%M') self.chat_log_file = '' def __str__(self): return '\n\nCallable methods:\n\n' \ '.initiate_preferences : Creates a preference file\n' \ '.read_preferences : Reads from preferences file\n' \ '.write_preferences : Write to preferences file' \ '.get_preference_value : Get the value for a variable' \ '' \ '\n\n'.format() def __getattr__(self): return '{0}'.format('Not Found') def initiate_preference(self): """ Creates a preference file (i.e. .initiate("pref/preferences.txt")) :return: """ if not os.path.exists(self.preference_file): temp_file = open(self.preference_file, 'w+') self.preference_parser.add_section('Speak') self.preference_parser.set('Speak', 'voice_enabled', 'yes') self.preference_parser.set('Speak', 'chat_voice_enabled', 'yes') self.preference_parser.set('Speak', 'announcement_voice_enabled', 'yes') self.preference_parser.add_section('Voices') self.preference_parser.set('Voices', 'voice', 'Zarvox') self.preference_parser.set('Voices', 'chat_voice', 'Alex') self.preference_parser.set('Voices', 'announcement_voice', 'Whisper') self.preference_parser.add_section('Log Settings') self.preference_parser.set('Log Settings', 'chat', 'yes') self.preference_parser.write(open(self.preference_file, 'w')) temp_file.close() else: pass def read_preference(self, session, key): """ preference_file -> file to read/write from/to (i.e 'pref/preferences.txt') section -> Which section of preferences (i.e 'Speech') key -> Which key of preferences (i.e 'speech_enabled') Reads from preferences file (i.e. .read("pref/preferences.txt", "section", "key")) :param session: :param key: :return: """ temp_file = open(self.preference_file, 'r') self.preference_parser.readfp(temp_file) temp_value = self.preference_parser.get(session, key) temp_file.close() return temp_value def write_preference(self, section, key, value): """ preference_file -> file to read/write from/to (i.e 'pref/preferences.txt') section -> Which section of preferences (i.e 'Speech') key -> Which key of preferences (i.e 'speech_enabled') value -> The value to be writen (i.e 'yes') Write to preferences file (i.e .write("pref/preferences.txt", "section", "key", "value")) :param session: :param key: :param value: :return: """ temp_file = open(self.preference_file, 'r') self.preference_parser.readfp(temp_file) self.preference_parser.set(section, key, value) self.preference_parser.write(open(self.preference_file, 'w')) temp_file.close() def get_preference_value(self, preference): """ preference -> Value to return These can be returned 'chat_log_enabled' 'voice_enabled' 'chat_voice_enabled' 'announcement_voice_enabled' :param preference: :return: """ if preference == 'chat_log_enabled': return self.chat_log_enabled if preference == 'voice_enabled': return self.voice_enabled if preference == 'chat_voice_enabled': return self.chat_voice_enabled if preference == 'announcement_voice_enabled': return self.announcement_voice_enabled if preference == 'voice': return self.voice if preference == 'chat_voice': return self.chat_voice if preference == 'announcement_voice': return self.announcement_voice if preference == 'chat_log_file': return self.chat_log_file def create_chat_log(self, irc_bot_name): """ irc_bot_name -> The name of the IRCBot This creates a new chat log file for every session started :param irc_bot_name: :return: """ if self.chat_log_enabled == 'yes': if not os.path.exists(self.chat_directory): os.makedirs(self.chat_directory, mode=0755) self.chat_log_file = str(irc_bot_name + '.' + self.timestamp+'.txt') else: pass def write_chat_log(self, sentence): """ sentence -> String send from the IRCBot to log Write to the chat log :param sentence: :return: """ if self.chat_log_enabled == 'yes': log_file = open((self.chat_directory + self.chat_log_file), "a") # chat log file log_file.write(str(sentence[0] + ' : ' + sentence[1])) log_file.close() else: pass def new_thread(self, as_daemon, function, *parameters): """ as_daemon -> Yes if a function needs to be a Daemon process or not function -> The name of the function passed through from Brain.csv parameters -> The parameters the function needs :param as_daemon: :param function: :param parameters: """ if as_daemon == 'yes': self.thread.daemonSet = True self.thread.__init__(target=function, name=str(function), args=parameters) self.thread.start() # self.thread.join() else: self.thread.__init__(target=function, name=str(function), args=parameters) self.thread.start() # self.thread.join() def speak(self, voice, sentence): """ voice -> Name of the Mac OS X voice to be used (i.e Alex) :param voice: :param sentence: """ if 'darwin' in sys.platform: if voice: system('say -v ' + voice + ' ' + sentence) else: system('say ' + sentence) else: pass def parse_irc_chat(self, sentence): """ sentence -> Raw IRC strings type_of_return -> 'all' give back a tuple with all eh IRC info. text_only gives back senteces Takes in the raw string from the IRC chat and converts it to something more manageable :param sentence: :return: """ irc_prefix = '' irc_trailing = '' if sentence.startswith(':'): irc_prefix, sentence = sentence[1:].split(' ', 1) if ' :' in sentence: sentence, irc_trailing = sentence.split(' :', 1) irc_arguments = sentence.split() return irc_prefix, irc_arguments.pop(0), irc_arguments, irc_trailing def check_conversation(self, sentence, irc_bot_name): """ sentence -> Takes parsed (or raw) IRC communication and check it against the Brains.csv file irc_bot_name -> Helps if you want multiple IRCBots Walking around Check a cerain string against the Brin.csv :param sentence: :param irc_bot_name: :return: """ where_is_my_brain = os.path.join((os.getcwd()), 'brains', irc_bot_name.replace(' ', '_'), 'Brain.csv') with open(where_is_my_brain, 'rb') as brain: dialect = csv.Sniffer().sniff(brain.read(1024), delimiters=';,') brain.seek(0) deep_thoughts = csv.reader(brain, dialect) for thought in deep_thoughts: if sentence.lower().find(thought[0]) != -1: return thought def set_toggle_state(self, sentence, irc_bot_nick, check): """ sentence -> The sentence to check irc_the_nick -> For which IRCBot is this test check -> What to test takes in a number (i.e 1) check [0] -> Chat log check [1] -> IRCBot speech check [2] -> Chat room speech check [3] -> Nick announcement :param sentence: :param irc_bot_nick: :param check: """ checks_array = [['.toggleChatLog', self.chat_log_enabled, 'self.chat_log_enabled', 'Log Settings', 'chat'], ['.toggleVoice', self.voice_enabled, 'self.voice_enabled', 'Speak', 'voice_enabled'], ['.toggleChatVoice', self.chat_voice_enabled, 'self.chat_voice_enabled', 'Speak', 'chat_voice_enabled'], ['.toggleNickVoice', self.announcement_voice_enabled, 'self.announcement_voice_enabled', 'Speak', 'announcement_voice_enabled']] if sentence.find(irc_bot_nick + checks_array[check][0]) != -1: if checks_array[check][1] == 'yes': execute = checks_array[check][2] + ' = "no"' exec execute self.write_preference(checks_array[check][3], checks_array[check][4], 'no') return True else: execute = checks_array[check][2] + ' = "yes"' exec execute self.write_preference(checks_array[check][3], checks_array[check][4], 'yes') return True else: return False def load_skills_init(self, path_to_skills): """ path_to_skills -> Path to the skills directory (i.e 'skills/') This function takes in al of the skill script files and puts them into the __init__.py file so the directory (and all skills in it) can be imported for use. :param path_to_skills: """ files = os.listdir(path_to_skills) skill_scripts = [] for i in range(len(files)): name = files[i].split('.') if len(name) > 1: if name[1] == 'py' and name[0] != '__init__': name = name[0] skill_scripts.append(name) init_file = open(path_to_skills+'__init__.py', 'w') to_write = '__all__ = '+str(skill_scripts) init_file.write(to_write) init_file.close()
{"/Arduino.py": ["/SerialPort.py"]}
73,764
DeRaafMedia/ProjectIRCInteractivity
refs/heads/master
/skills/test_act_function.py
import sys import serial from time import sleep def test_act_function(arg_1, arg_2, arg_3, arg_4): serial_port = str(arg_1) baud_rate = int(arg_2) time_out = int(arg_3) parameter = int(arg_4) device = serial.Serial(serial_port, baud_rate, timeout=time_out) x = 0 for i in range(0, parameter): while x < 255: device.write('1/1/9/' + str(x) + '/') sleep(0.000005) x += 1 sleep(0.000005) sleep(0.000005) while x > 0: device.write('1/1/9/' + str(x) + '/') sleep(0.000005) x -= 1 sleep(0.000005) sleep(0.000005) device.write('1/1/9/0/') device.close() if __name__ == "test_act_function": test_act_function(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
{"/Arduino.py": ["/SerialPort.py"]}
73,765
DeRaafMedia/ProjectIRCInteractivity
refs/heads/master
/skills/test_feel_function.py
import sys import serial from time import sleep def test_feel(arg_1, arg_2, arg_3, arg_4): serial_port = str(arg_1) baud_rate = int(arg_2) time_out = int(arg_3) parameter = int(arg_4) device = serial.Serial(serial_port, baud_rate, timeout=time_out) for i in range(0, 10000): device.write('1/1/11/0/') device.write('1/2/22/1/') device.write('1/2/24/2/') device.write('2/2/23/') x = int(device.readline().strip()) print(x) if x == 1: device.write('1/2/9/2/') else: device.write('1/2/9/1/') device.write('1/1/9/0/') device.write('1/2/22/1/') device.write('1/1/24/1/') device.close() if __name__ == "__test_feel__": test_feel(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
{"/Arduino.py": ["/SerialPort.py"]}
73,767
OSOceanAcoustics/echopype
refs/heads/main
/echopype/convert/set_groups_ad2cp.py
from enum import Enum, auto, unique from importlib import resources from typing import Dict, List, Optional, Set, Tuple, Union import numpy as np import xarray as xr import yaml from .. import convert from ..utils.coding import set_time_encodings from .parse_ad2cp import DataType, Dimension, Field, HeaderOrDataRecordFormats from .set_groups_base import SetGroupsBase AHRS_COORDS: Dict[Dimension, np.ndarray] = { Dimension.MIJ: np.array(["11", "12", "13", "21", "22", "23", "31", "32", "33"]), Dimension.WXYZ: np.array(["w", "x", "y", "z"]), Dimension.XYZ: np.array(["x", "y", "z"]), } @unique class BeamGroup(Enum): AVERAGE = auto() BURST = auto() ECHOSOUNDER = auto() ECHOSOUNDER_RAW = auto() class SetGroupsAd2cp(SetGroupsBase): """Class for saving groups to netcdf or zarr from Ad2cp data files.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # TODO: bug: 0 if not exist in first string packet # resulting in index error in setting ds["pulse_compressed"] self.pulse_compressed = self.parser_obj.get_pulse_compressed() self._make_time_coords() with resources.open_text(convert, "ad2cp_fields.yaml") as f: self.field_attrs: Dict[str, Dict[str, Dict[str, str]]] = yaml.safe_load(f) # type: ignore # noqa def _make_time_coords(self): timestamps = [] times_idx = { Dimension.PING_TIME_AVERAGE: [], Dimension.PING_TIME_BURST: [], Dimension.PING_TIME_ECHOSOUNDER: [], Dimension.PING_TIME_ECHOSOUNDER_RAW: [], Dimension.PING_TIME_ECHOSOUNDER_RAW_TRANSMIT: [], } for packet in self.parser_obj.packets: if not packet.has_timestamp(): continue timestamps.append(packet.timestamp) i = len(timestamps) - 1 if packet.is_average(): times_idx[Dimension.PING_TIME_AVERAGE].append(i) elif packet.is_burst(): times_idx[Dimension.PING_TIME_BURST].append(i) elif packet.is_echosounder(): times_idx[Dimension.PING_TIME_ECHOSOUNDER].append(i) elif packet.is_echosounder_raw(): times_idx[Dimension.PING_TIME_ECHOSOUNDER_RAW].append(i) elif packet.is_echosounder_raw_transmit(): times_idx[Dimension.PING_TIME_ECHOSOUNDER_RAW_TRANSMIT].append(i) self.times_idx = { time_dim: np.array(time_values, dtype="u8") for time_dim, time_values in times_idx.items() } self.timestamps = np.array(timestamps) _, unique_ping_time_idx = np.unique(self.timestamps, return_index=True) self.times_idx[Dimension.PING_TIME] = unique_ping_time_idx def _make_dataset(self, var_names: Dict[str, str]) -> xr.Dataset: """ Constructs a dataset of the given variables using parser_obj data var_names maps parser_obj field names to output dataset variable names """ # {field_name: [field_value]} # [field_value] lines up with time_dim fields: Dict[str, List[np.ndarray]] = {field_name: [] for field_name in var_names.keys()} # {field_name: [Dimension]} dims: Dict[str, List[Dimension]] = dict() # {field_name: field dtype} dtypes: Dict[str, np.dtype] = dict() # {field_name: attrs} attrs: Dict[str, Dict[str, str]] = dict() # {field_name: [idx of padding]} pad_idx: Dict[str, List[int]] = {field_name: [] for field_name in var_names.keys()} # {field_name: field exists} field_exists: Dict[str, bool] = {field_name: False for field_name in var_names.keys()} beam_coords: Optional[np.ndarray] = None # separate by time dim for packet in self.parser_obj.packets: if not packet.has_timestamp(): continue if "beams" in packet.data: if beam_coords is None: beam_coords = packet.data["beams"] else: beam_coords = max(beam_coords, packet.data["beams"], key=lambda x: len(x)) data_record_format = HeaderOrDataRecordFormats.data_record_format( packet.data_record_type ) for field_name in var_names.keys(): field = data_record_format.get_field(field_name) if field is None: field_dimensions = Field.default_dimensions() # can't store in dims yet because there might be another data record format # which does have this field if field_name not in attrs: if field_name in self.field_attrs["POSTPROCESSED"]: attrs[field_name] = self.field_attrs["POSTPROCESSED"][field_name] else: field_dimensions = field.dimensions(packet.data_record_type) if field_name not in dims: dims[field_name] = field_dimensions if field_name not in dtypes: field_entry_size_bytes = field.field_entry_size_bytes if callable(field_entry_size_bytes): field_entry_size_bytes = field_entry_size_bytes(packet) dtypes[field_name] = field.field_entry_data_type.dtype( field_entry_size_bytes ) if field_name not in attrs: attrs[field_name] = self.field_attrs[data_record_format.name][field_name] if field_name in packet.data: # field is in this packet fields[field_name].append(packet.data[field_name]) field_exists[field_name] = True else: # field is not in this packet # pad the list of field values with an empty array so that # the time dimension still lines up with the field values fields[field_name].append(np.array(0)) pad_idx[field_name].append(len(fields[field_name]) - 1) for field_name in fields.keys(): # add dimensions to dims if they were not found # (the desired fields did not exist in any of the packet's data records # because they are in a different packet OR it is a field created by echopype # from a bitfield, etc.) if field_name not in dims: dims[field_name] = Field.default_dimensions() # add dtypes to dtypes if they were not found # (the desired fields did not exist in any of the packet's data records # because they are in a different packet OR it is a field created by echopype # from a bitfield, etc.) if field_name not in dtypes: dtypes[field_name] = DataType.default_dtype() # replace padding with correct shaped padding # (earlier we padded along the time dimension but we didn't necessarily know the shape # of the padding itself) for field_name, pad_idxs in pad_idx.items(): for i in pad_idxs: fields[field_name][i] = np.zeros( np.ones(len(dims[field_name]) - 1, dtype="u1"), # type: ignore dtype=dtypes[field_name], ) # {field_name: field_value} # field_value is now combined along time_dim combined_fields: Dict[str, np.ndarray] = dict() # pad to max shape and stack for field_name, field_values in fields.items(): if field_exists[field_name]: if len(dims[field_name]) > 1: shapes = [field_value.shape for field_value in field_values] max_shape = np.amax( np.stack(shapes), axis=0, ) field_values = [ np.pad( field_value, tuple( (0, max_axis_len - field_value.shape[i]) for i, max_axis_len in enumerate(max_shape) # type: ignore ), ) for field_value in field_values ] field_values = np.stack(field_values) combined_fields[field_name] = field_values # slice fields to time_dim for field_name, field_value in combined_fields.items(): combined_fields[field_name] = field_value[self.times_idx[dims[field_name][0]]] # make ds used_dims: Set[Dimension] = { dim for field_name, dims_list in dims.items() for dim in dims_list if field_exists[field_name] } data_vars: Dict[ str, Union[Tuple[List[str], np.ndarray, Dict[str, str]], Tuple[Tuple[()], None]], ] = { var_name: ( [dim.dimension_name() for dim in dims[field_name]], combined_fields[field_name], attrs.get(field_name, {}), ) if field_exists[field_name] else ((), None) for field_name, var_name in var_names.items() } # type: ignore coords: Dict[str, np.ndarray] = dict() for time_dim, time_idxs in self.times_idx.items(): if time_dim in used_dims: coords[time_dim.dimension_name()] = self.timestamps[time_idxs] for ahrs_dim, ahrs_coords in AHRS_COORDS.items(): if ahrs_dim in used_dims: coords[ahrs_dim.dimension_name()] = ahrs_coords if Dimension.BEAM in used_dims and beam_coords is not None: coords[Dimension.BEAM.dimension_name()] = beam_coords ds = xr.Dataset(data_vars=data_vars, coords=coords) # make arange coords for the remaining dims non_coord_dims = {dim.dimension_name() for dim in used_dims} - set(ds.coords.keys()) ds = ds.assign_coords({dim: np.arange(ds.dims[dim]) for dim in non_coord_dims}) return ds def set_env(self) -> xr.Dataset: ds = self._make_dataset( { "speed_of_sound": "sound_speed_indicative", "temperature": "temperature", "pressure": "pressure", } ) return set_time_encodings(ds) def set_platform(self) -> xr.Dataset: ds = self._make_dataset( { "heading": "heading", "pitch": "pitch", "roll": "roll", } ) return set_time_encodings(ds) def set_beam(self) -> List[xr.Dataset]: # TODO: should we divide beam into burst/average (e.g., beam_burst, beam_average) # like was done for range_bin (we have range_bin_burst, range_bin_average, # and range_bin_echosounder)? beam_groups = [] self._beamgroups = [] beam_groups_exist = set() for packet in self.parser_obj.packets: if packet.is_average(): beam_groups_exist.add(BeamGroup.AVERAGE) elif packet.is_burst(): beam_groups_exist.add(BeamGroup.BURST) elif packet.is_echosounder(): beam_groups_exist.add(BeamGroup.ECHOSOUNDER) elif packet.is_echosounder_raw(): beam_groups_exist.add(BeamGroup.ECHOSOUNDER_RAW) if len(beam_groups_exist) == len(BeamGroup): break # average if BeamGroup.AVERAGE in beam_groups_exist: beam_groups.append( self._make_dataset( { "num_beams": "number_of_beams", "coordinate_system": "coordinate_system", "num_cells": "number_of_cells", "blanking": "blanking", "cell_size": "cell_size", "velocity_range": "velocity_range", "echosounder_frequency": "echosounder_frequency", "ambiguity_velocity": "ambiguity_velocity", "dataset_description": "data_set_description", "transmit_energy": "transmit_energy", "velocity_scaling": "velocity_scaling", "velocity_data_average": "velocity", "amplitude_data_average": "amplitude", "correlation_data_average": "correlation", } ) ) self._beamgroups.append( { "name": f"Beam_group{len(self._beamgroups) + 1}", "descr": ( "contains echo intensity, velocity and correlation data " "as well as other configuration parameters from the Average mode." ), } ) # burst if BeamGroup.BURST in beam_groups_exist: beam_groups.append( self._make_dataset( { "num_beams": "number_of_beams", "coordinate_system": "coordinate_system", "num_cells": "number_of_cells", "blanking": "blanking", "cell_size": "cell_size", "velocity_range": "velocity_range", "echosounder_frequency": "echosounder_frequency", "ambiguity_velocity": "ambiguity_velocity", "dataset_description": "data_set_description", "transmit_energy": "transmit_energy", "velocity_scaling": "velocity_scaling", "velocity_data_burst": "velocity", "amplitude_data_burst": "amplitude", "correlation_data_burst": "correlation", } ) ) self._beamgroups.append( { "name": f"Beam_group{len(self._beamgroups) + 1}", "descr": ( "contains echo intensity, velocity and correlation data " "as well as other configuration parameters from the Burst mode." ), } ) # echosounder if BeamGroup.ECHOSOUNDER in beam_groups_exist: ds = self._make_dataset( { "num_beams": "number_of_beams", "coordinate_system": "coordinate_system", "num_cells": "number_of_cells", "blanking": "blanking", "cell_size": "cell_size", "velocity_range": "velocity_range", "echosounder_frequency": "echosounder_frequency", "ambiguity_velocity": "ambiguity_velocity", "dataset_description": "data_set_description", "transmit_energy": "transmit_energy", "velocity_scaling": "velocity_scaling", "correlation_data_echosounder": "correlation", "echosounder_data": "amplitude", } ) ds = ds.assign_coords({"echogram": np.arange(3)}) pulse_compressed = np.zeros(3) # TODO: bug: if self.pulse_compress=0 this will set the last index to 1 pulse_compressed[self.pulse_compressed - 1] = 1 ds["pulse_compressed"] = (("echogram",), pulse_compressed) beam_groups.append(ds) self._beamgroups.append( { "name": f"Beam_group{len(self._beamgroups) + 1}", "descr": ( "contains backscatter echo intensity and other configuration " "parameters from the Echosounder mode. " "Data can be pulse compressed or raw intensity." ), } ) # echosounder raw if BeamGroup.ECHOSOUNDER_RAW in beam_groups_exist: beam_groups.append( self._make_dataset( { "num_beams": "number_of_beams", "coordinate_system": "coordinate_system", "num_cells": "number_of_cells", "blanking": "blanking", "cell_size": "cell_size", "velocity_range": "velocity_range", "echosounder_frequency": "echosounder_frequency", "ambiguity_velocity": "ambiguity_velocity", "dataset_description": "data_set_description", "transmit_energy": "transmit_energy", "velocity_scaling": "velocity_scaling", "num_complex_samples": "num_complex_samples", "ind_start_samples": "ind_start_samples", "freq_raw_sample_data": "freq_raw_sample_data", "echosounder_raw_samples_i": "backscatter_r", "echosounder_raw_samples_q": "backscatter_i", "echosounder_raw_transmit_samples_i": "transmit_pulse_r", "echosounder_raw_transmit_samples_q": "transmit_pulse_i", } ) ) self._beamgroups.append( { "name": f"Beam_group{len(self._beamgroups) + 1}", "descr": ( "contains complex backscatter raw samples and other configuration " "parameters from the Echosounder mode, " "including complex data from the transmit pulse." ), } ) # FIXME: this is a hack because the current file saving # mechanism requires that the beam group have ping_time as a dimension, # but ping_time might not be a dimension if the dataset is completely # empty for i, ds in enumerate(beam_groups): if "ping_time" not in ds.dims: beam_groups[i] = ds.expand_dims(dim="ping_time") # remove time1 from beam groups for i, ds in enumerate(beam_groups): beam_groups[i] = ds.sel(time1=ds["ping_time"]).drop_vars("time1", errors="ignore") return [set_time_encodings(ds) for ds in beam_groups] def set_vendor(self) -> xr.Dataset: ds = self._make_dataset( { "version": "data_record_version", "pressure_sensor_valid": "pressure_sensor_valid", "temperature_sensor_valid": "temperature_sensor_valid", "compass_sensor_valid": "compass_sensor_valid", "tilt_sensor_valid": "tilt_sensor_valid", "velocity_data_included": "velocity_data_included", "amplitude_data_included": "amplitude_data_included", "correlation_data_included": "correlation_data_included", "altimeter_data_included": "altimeter_data_included", "altimeter_raw_data_included": "altimeter_raw_data_included", "ast_data_included": "ast_data_included", "echosounder_data_included": "echosounder_data_included", "ahrs_data_included": "ahrs_data_included", "percentage_good_data_included": "percentage_good_data_included", "std_dev_data_included": "std_dev_data_included", "distance_data_included": "distance_data_included", "figure_of_merit_data_included": "figure_of_merit_data_included", "error": "error", "status0": "status0", "procidle3": "procidle3", "procidle6": "procidle6", "procidle12": "procidle12", "status": "status", "wakeup_state": "wakeup_state", "orientation": "orientation", "autoorientation": "autoorientation", "previous_wakeup_state": "previous_wakeup_state", "last_measurement_low_voltage_skip": "last_measurement_low_voltage_skip", "active_configuration": "active_configuration", "echosounder_index": "echosounder_index", "telemetry_data": "telemetry_data", "boost_running": "boost_running", "echosounder_frequency_bin": "echosounder_frequency_bin", "bd_scaling": "bd_scaling", "battery_voltage": "battery_voltage", "power_level": "power_level", "temperature_from_pressure_sensor": "temperature_of_pressure_sensor", "nominal_correlation": "nominal_correlation", "magnetometer_temperature": "magnetometer_temperature", "real_time_clock_temperature": "real_time_clock_temperature", "ensemble_counter": "ensemble_counter", "ahrs_rotation_matrix": "ahrs_rotation_matrix_mij", "ahrs_quaternions": "ahrs_quaternions_wxyz", "ahrs_gyro": "ahrs_gyro_xyz", "percentage_good_data": "percentage_good_data", "std_dev_pitch": "std_dev_pitch", "std_dev_roll": "std_dev_roll", "std_dev_heading": "std_dev_heading", "std_dev_pressure": "std_dev_pressure", "pressure_sensor_valid": "pressure_sensor_valid", "temperature_sensor_valid": "temperature_sensor_valid", "compass_sensor_valid": "compass_sensor_valid", "tilt_sensor_valid": "tilt_sensor_valid", "figure_of_merit_data": "figure_of_merit", "altimeter_distance": "altimeter_distance", "altimeter_quality": "altimeter_quality", "ast_distance": "ast_distance", "ast_quality": "ast_quality", "ast_offset_100us": "ast_offset_100us", "ast_pressure": "ast_pressure", "altimeter_spare": "altimeter_spare", "altimeter_raw_data_num_samples": "altimeter_raw_data_num_samples", "altimeter_raw_data_sample_distance": "altimeter_raw_data_sample_distance", "altimeter_raw_data_samples": "altimeter_raw_data_samples", "magnetometer_raw": "magnetometer_raw", } ) return set_time_encodings(ds) def set_sonar(self) -> xr.Dataset: """Set the Sonar group.""" # Add beam_group and beam_group_descr variables sharing a common dimension # (beam_group), using the information from self._beamgroups beam_groups_vars, beam_groups_coord = self._beam_groups_vars() ds = xr.Dataset(beam_groups_vars, coords=beam_groups_coord) # Assemble sonar group global attribute dictionary sonar_attr_dict = { "sonar_manufacturer": "Nortek", "sonar_model": "AD2CP", "sonar_serial_number": ", ".join( np.unique( [ str(packet.data["serial_number"]) for packet in self.parser_obj.packets if "serial_number" in packet.data ] ) ), "sonar_software_name": "", "sonar_software_version": "", "sonar_firmware_version": "", "sonar_type": "acoustic Doppler current profiler (ADCP)", } firmware_version = self.parser_obj.get_firmware_version() if firmware_version is not None: sonar_attr_dict["sonar_firmware_version"] = ", ".join( [f"{k}:{v}" for k, v in firmware_version.items()] ) ds = ds.assign_attrs(sonar_attr_dict) return set_time_encodings(ds)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,768
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/utils/test_source_filenames.py
from pathlib import Path import numpy as np from echopype.utils.prov import _sanitize_source_files def test_scalars(): """One or more scalar values""" path1 = "/my/path1" path2 = Path("/my/path2") # Single scalars assert _sanitize_source_files(path1) == [path1] assert _sanitize_source_files(path2) == [str(path2)] # List of scalars assert _sanitize_source_files([path1, path2]) == [path1, str(path2)] def test_mixed(): """A scalar value and a list or ndarray""" path1 = "/my/path1" path2 = Path("/my/path2") # Mixed-type list path_list1 = [path1, path2] # String-type ndarray path_list2 = np.array([path1, str(path2)]) # A scalar and a list target_path_list = [path1, path1, str(path2)] assert _sanitize_source_files([path1, path_list1]) == target_path_list # A scalar and an ndarray assert _sanitize_source_files([path1, path_list2]) == target_path_list
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,769
OSOceanAcoustics/echopype
refs/heads/main
/echopype/echodata/convention/__init__.py
from .conv import _Convention # Instantiate the singleton sonarnetcdf_1 = _Convention(version="1.0") __all__ = ["sonarnetcdf_1"]
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,770
OSOceanAcoustics/echopype
refs/heads/main
/echopype/consolidate/split_beam_angle.py
""" Contains functions necessary to compute the split-beam (alongship/athwartship) angles and add them to a Dataset. """ from typing import List, Optional, Tuple import numpy as np import xarray as xr from ..calibrate.ek80_complex import compress_pulse, get_norm_fac, get_transmit_signal def _compute_angle_from_complex( bs: xr.DataArray, beam_type: int, sens: List[xr.DataArray], offset: List[xr.DataArray] ) -> Tuple[xr.DataArray, xr.DataArray]: """ Compute split-beam angles from raw data from transducer sectors. Can be used for data from a single channel or multiple channels, depending on what is in ``bs``. Parameters ---------- bs: xr.DataArray Complex backscatter samples from a single channel or multiple channels beam_type: int The type of beam being considered sens: list of xr.DataArray A list of length two where the first element corresponds to the angle sensitivity alongship and the second corresponds to the angle sensitivity athwartship offset: list of xr.DataArray A list of length two where the first element corresponds to the angle offset alongship and the second corresponds to the angle offset athwartship Returns ------- theta: xr.DataArray The calculated split-beam alongship angle for a specific channel phi: xr.DataArray The calculated split-beam athwartship angle for a specific channel Notes ----- This function should only be used for data with complex backscatter. """ # 4-sector transducer if beam_type == 1: bs_fore = (bs.isel(beam=2) + bs.isel(beam=3)) / 2 # forward bs_aft = (bs.isel(beam=0) + bs.isel(beam=1)) / 2 # aft bs_star = (bs.isel(beam=0) + bs.isel(beam=3)) / 2 # starboard bs_port = (bs.isel(beam=1) + bs.isel(beam=2)) / 2 # port bs_theta = bs_fore * np.conj(bs_aft) bs_phi = bs_star * np.conj(bs_port) theta = np.arctan2(np.imag(bs_theta), np.real(bs_theta)) / np.pi * 180 phi = np.arctan2(np.imag(bs_phi), np.real(bs_phi)) / np.pi * 180 # 3-sector transducer with or without center element elif beam_type in [17, 49, 65, 81]: # 3-sector if beam_type == 17: bs_star = bs.isel(beam=0) bs_port = bs.isel(beam=1) bs_fore = bs.isel(beam=2) else: # 3-sector + 1 center element bs_star = (bs.isel(beam=0) + bs.isel(beam=3)) / 2 bs_port = (bs.isel(beam=1) + bs.isel(beam=3)) / 2 bs_fore = (bs.isel(beam=2) + bs.isel(beam=3)) / 2 bs_fac1 = bs_fore * np.conj(bs_star) bs_fac2 = bs_fore * np.conj(bs_port) fac1 = np.arctan2(np.imag(bs_fac1), np.real(bs_fac1)) / np.pi * 180 fac2 = np.arctan2(np.imag(bs_fac2), np.real(bs_fac2)) / np.pi * 180 theta = (fac1 + fac2) / np.sqrt(3) phi = fac2 - fac1 # EC150–3C elif beam_type == 97: raise NotImplementedError else: raise ValueError("beam_type not recognized!") theta = theta / sens[0] - offset[0] phi = phi / sens[1] - offset[1] return theta, phi def get_angle_power_samples( ds_beam: xr.Dataset, angle_params: dict ) -> Tuple[xr.Dataset, xr.Dataset]: """ Obtain split-beam angle from CW mode power samples. Parameters ---------- ds_beam: xr.Dataset An ``EchoData`` Sonar/Beam_group1 group (complex samples always in Beam_group1) angle_params : dict A dictionary containing angle_offset/angle_sensitivity parameters from the calibrated dataset Returns ------- theta: xr.Dataset Split-beam alongship angle phi: xr.Dataset Split-beam athwartship angle Notes ----- Can be used on both EK60 and EK80 data Computation done for ``beam_type=1``: ``physical_angle = ((raw_angle * 180 / 128) / sensitivity) - offset`` """ # raw_angle scaling constant conversion_const = 180.0 / 128.0 def _e2f(angle_type: str) -> xr.Dataset: """Convert electric angle to physical angle for split-beam data""" return ( conversion_const * ds_beam[f"angle_{angle_type}"] / angle_params[f"angle_sensitivity_{angle_type}"] - angle_params[f"angle_offset_{angle_type}"] ) # add split-beam angle if at least one channel is split-beam # in the case when some channels are split-beam and some single-beam # the single-beam channels will be all NaNs and _e2f would run through and output NaNs if not np.all(ds_beam["beam_type"].data == 0): theta = _e2f(angle_type="alongship") # split-beam alongship angle phi = _e2f(angle_type="athwartship") # split-beam athwartship angle else: raise ValueError( "Computing physical split-beam angle is only available for data " "from split-beam transducers!" ) return theta, phi def get_angle_complex_samples( ds_beam: xr.Dataset, angle_params: dict, pc_params: dict = None ) -> Tuple[xr.DataArray, xr.DataArray]: """ Obtain split-beam angle from CW or BB mode complex samples. Parameters ---------- ds_beam : xr.Dataset An ``EchoData`` Sonar/Beam_group1 group (complex samples always in Beam_group1) angle_params : dict A dictionary containing angle_offset/angle_sensitivity parameters from the calibrated dataset pc_params : dict Parameters needed for pulse compression This dict also serves as a flag for whether to apply pulse compression Returns ------- theta : xr.Dataset Split-beam alongship angle phi : xr.Dataset Split-beam athwartship angle """ # Get complex backscatter samples bs = ds_beam["backscatter_r"] + 1j * ds_beam["backscatter_i"] # Pulse compression if pc_params exists if pc_params is not None: tx, tx_time = get_transmit_signal( beam=ds_beam, coeff=pc_params, # this is filter_coeff with fs added waveform_mode="BB", fs=pc_params["receiver_sampling_frequency"], # this is the added fs ) bs = compress_pulse(backscatter=bs, chirp=tx) # has beam dim bs = bs / get_norm_fac(chirp=tx) # normalization for each channel # Compute angles # unique beam_type existing in the dataset beam_type_all_ch = np.unique(ds_beam["beam_type"].data) if beam_type_all_ch.size == 1: # If beam_type is the same for all channels, process all channels at once theta, phi = _compute_angle_from_complex( bs=bs, beam_type=beam_type_all_ch[0], # beam_type for all channels sens=[ angle_params["angle_sensitivity_alongship"], angle_params["angle_sensitivity_athwartship"], ], offset=[ angle_params["angle_offset_alongship"], angle_params["angle_offset_athwartship"], ], ) else: # beam_type different for some channels, process each channel separately theta, phi = [], [] for ch_id in bs["channel"].data: theta_ch, phi_ch = _compute_angle_from_complex( bs=bs.sel(channel=ch_id), # beam_type is not time-varying beam_type=(ds_beam["beam_type"].sel(channel=ch_id)), sens=[ angle_params["angle_sensitivity_alongship"].sel(channel=ch_id), angle_params["angle_sensitivity_athwartship"].sel(channel=ch_id), ], offset=[ angle_params["angle_offset_alongship"].sel(channel=ch_id), angle_params["angle_offset_athwartship"].sel(channel=ch_id), ], ) theta.append(theta_ch) phi.append(phi_ch) # Combine angles from all channels theta = xr.DataArray( data=theta, coords={ "channel": bs["channel"], "ping_time": bs["ping_time"], "range_sample": bs["range_sample"], }, ) phi = xr.DataArray( data=phi, coords={ "channel": bs["channel"], "ping_time": bs["ping_time"], "range_sample": bs["range_sample"], }, ) return theta, phi def add_angle_to_ds( theta: xr.Dataset, phi: xr.Dataset, ds: xr.Dataset, return_dataset: bool, source_ds_path: Optional[str] = None, file_type: Optional[str] = None, storage_options: dict = {}, ) -> Optional[xr.Dataset]: """ Adds the split-beam angle data to the provided input ``ds``. Parameters ---------- theta: xr.Dataset The calculated split-beam alongship angle phi: xr.Dataset The calculated split-beam athwartship angle ds: xr.Dataset The Dataset that ``theta`` and ``phi`` will be added to return_dataset: bool Whether a dataset will be returned or not source_ds_path: str, optional The path to the file corresponding to ``ds``, if it exists file_type: {"netcdf4", "zarr"}, optional The file type corresponding to ``source_ds_path`` storage_options: dict, default={} Any additional parameters for the storage backend, corresponding to the path ``source_ds_path`` Returns ------- xr.Dataset or None If ``return_dataset=False``, nothing will be returned. If ``return_dataset=True`` either the input dataset ``ds`` or a lazy-loaded Dataset (obtained from the path provided by ``source_ds_path``) with the split-beam angle data added will be returned. """ # TODO: do we want to add anymore attributes to these variables? # add appropriate attributes to theta and phi theta.attrs["long_name"] = "split-beam alongship angle" phi.attrs["long_name"] = "split-beam athwartship angle" if source_ds_path is not None: # put the variables into a Dataset, so they can be written at the same time # add ds attributes to splitb_ds since they will be overwritten by to_netcdf/zarr splitb_ds = xr.Dataset( data_vars={"angle_alongship": theta, "angle_athwartship": phi}, coords=theta.coords, attrs=ds.attrs, ) # release any resources linked to ds (necessary for to_netcdf) ds.close() # write the split-beam angle data to the provided path if file_type == "netcdf4": splitb_ds.to_netcdf(path=source_ds_path, mode="a", **storage_options) else: splitb_ds.to_zarr(store=source_ds_path, mode="a", **storage_options) if return_dataset: # open up and return Dataset in source_ds_path return xr.open_dataset(source_ds_path, engine=file_type, chunks={}, **storage_options) else: # add the split-beam angles to the provided Dataset ds["angle_alongship"] = theta ds["angle_athwartship"] = phi if return_dataset: # return input dataset with split-beam angle data return ds
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,771
OSOceanAcoustics/echopype
refs/heads/main
/echopype/calibrate/ecs.py
import re from collections import defaultdict from datetime import datetime from typing import Dict, Literal, Optional, Tuple, Union import numpy as np import xarray as xr from ..utils.log import _init_logger logger = _init_logger(__name__) # String matcher for parser SEPARATOR = re.compile(r"#=+#\n") STATUS_CRUDE = re.compile(r"#\s*(?P<status>(.+))\s*#\n") # noqa STATUS_FINE = re.compile(r"#\s+(?P<status>\w+) SETTINGS\s*#\n") # noqa ECS_HEADER = re.compile( r"#\s*ECHOVIEW CALIBRATION SUPPLEMENT \(.ECS\) FILE \((?P<data_type>.+)\)\s*#\n" # noqa ) ECS_TIME = re.compile( r"#\s+(?P<date>\d{1,2}\/\d{1,2}\/\d{4}) (?P<time>\d{1,2}\:\d{1,2}\:\d{1,2})(.\d+)?\s+#\n" # noqa ) ECS_VERSION = re.compile(r"Version (?P<version>\d+\.\d+)\s*\n") # noqa PARAM_MATCHER = re.compile( # r"\s*(?P<skip>#?)\s*(?P<param>\w+)\s*=\s*(?P<val>((-?\d+(?:\.\d+))|\w+)?)?\s*#?(.*)\n" # noqa # can be multiple values separated by space r"\s*(?P<skip>#?)\s*(?P<param>\w+)\s*=\s*(?P<val>((-?\d+(?:\.\d+)\s*)+|\w+)?)?\s*#?(.*)\n" # noqa ) VAL_PATTERN = r"(-?\d+(?:\.\d+)\s*)\s+" CAL_HIERARCHY = re.compile( r"(SourceCal|LocalCal) (?P<source>\w+)\s*\n", re.I ) # ignore case # noqa # Convert dict from ECS to echopype format EV_EP_MAP = { # from Echoview-generated ECS template (unless noted otherwise) : EchoData variable name # Ex60 / Ex70 / EK15 "EK60": { "AbsorptionCoefficient": "sound_absorption", "Frequency": "frequency_nominal", # will use for checking channel and freq match "MajorAxis3dbBeamAngle": "beamwidth_athwartship", "MajorAxisAngleOffset": "angle_offset_athwartship", "MajorAxisAngleSensitivity": "angle_sensitivity_athwartship", "MinorAxis3dbBeamAngle": "beamwidth_alongship", "MinorAxisAngleOffset": "angle_offset_alongship", "MinorAxisAngleSensitivity": "angle_sensitivity_alongship", "PulseDuration": "transmit_duration_nominal", "SaCorrectionFactor": "sa_correction", "SoundSpeed": "sound_speed", "EK60SaCorrection": "sa_correction", # from NWFSC template "TransducerGain": "gain_correction", "Ek60TransducerGain": "gain_correction", # from NWFSC template "TransmittedPower": "transmit_power", # "TvgRangeCorrection": "tvg_range_correction", # not in EchoData # "TvgRangeCorrectionOffset": "tvg_range_correction_offset", # not in EchoData "TwoWayBeamAngle": "equivalent_beam_angle", }, # Additional on EK80, ES80, WBAT, EA640 # Note these should be concat after the EK60 dict "EK80": { "AbsorptionDepth": "pressure", "Acidity": "pH", "EffectivePulseDuration": "tau_effective", "Salinity": "salinity", "SamplingFrequency": "sampling_frequency", # does not exist in echopype.EchoData "Temperature": "temperature", "TransceiverImpedance": "impedance_transceiver", "TransceiverSamplingFrequency": "receiver_sampling_frequency", # "TransducerModeActive": "transducer_mode", # TODO: CHECK NAME IN ECHODATA "FrequencyTableWideband": "frequency_BB", # frequency axis for broadband cal params "GainTableWideband": "gain_correction", # freq-dep "MajorAxisAngleOffsetTableWideband": "angle_offset_athwartship", # freq-dep "MajorAxisBeamWidthTableWideband": "beamwidth_athwartship", # freq-dep "MinorAxisAngleOffsetTableWideband": "angle_offset_alongship", # freq-dep "MinorAxisBeamWidthTableWideband": "beamwidth_alongship", # freq-dep "NumberOfTransducerSegments": "n_sector", # TODO: CHECK IN ECHODATA "PulseCompressedEffectivePulseDuration": "tau_effective_pc", # TODO: not in EchoData }, # AZFP-specific # Note: not sure why it doesn't contain salinity and pressure required for computing absorption # "AZFP": { # AzfpDetectionSlope = 0.023400 # [0.000000..1.000000] # AzfpEchoLevelMax = 142.8 # (decibels) [0.0..9999.0] # AzfpTransmitVoltage = 53.0 # [0.0..999.0] # AzfpTransmitVoltageResponse = 170.9 # (decibels) [0.0..999.0] # Frequency = 38.00 # (kilohertz) [0.01..10000.00] # PulseDuration = 1.000 # (milliseconds) [0.001..200.000] # SoundSpeed = 1450.50 # (meters per second) [1400.00..1700.00] # TwoWayBeamAngle = -16.550186 # (decibels re 1 steradian) [-99.000000..11.000000] # TvgRangeCorrection = # [None, BySamples, SimradEx500, SimradEx60, BioSonics, Kaijo, PulseLength, Ex500Forced, SimradEK80, Standard] # noqa # TvgRangeCorrectionOffset = # (samples) [-10000.00..10000.00] # }, } ENV_PARAMS = [ "AbsorptionCoefficient", "SoundSpeed", "AbsorptionDepth", "Acidity", "Salinity", "Temperature", ] # Used in ecs_ev2ep to assemble xr.DataArray for freq-dep BB params CAL_PARAMS_BB = ( "FrequencyTableWideband", "GainTableWideband", "MajorAxisAngleOffsetTableWideband", "MajorAxisBeamWidthTableWideband", "MinorAxisAngleOffsetTableWideband", "MinorAxisBeamWidthTableWideband", ) class ECSParser: """ Class for parsing Echoview calibration supplement (ECS) files. """ TvgRangeCorrection_allowed_str = ( "None", "BySamples", "SimradEx500", "SimradEx60", "BioSonics", "Kaijo", "PulseLength", "Ex500Forced", "SimradEK80", "Standard", ) def __init__(self, input_file=None): self.input_file = input_file self.data_type = None self.version = None self.file_creation_time: Optional[datetime] = None self.parsed_params: Optional[dict] = None def _parse_header(self, fid) -> bool: """ Parse header block. """ tmp = ECS_TIME.match(fid.readline()) self.file_creation_time = datetime.strptime( tmp["date"] + " " + tmp["time"], "%m/%d/%Y %H:%M:%S" ) if SEPARATOR.match(fid.readline()) is None: # line 4: separator raise ValueError("Unexpected line in ECS file!") # line 5-10: skip [fid.readline() for ff in range(6)] if SEPARATOR.match(fid.readline()) is None: # line 11: separator raise ValueError("Unexpected line in ECS file!") # read lines until seeing version number line = "\n" while line == "\n": line = fid.readline() self.version = ECS_VERSION.match(line)["version"] return True def _parse_block(self, fid, status) -> dict: """ Parse the FileSet, SourceCal or LocalCal block. Parameters ---------- fid : File Object status : str {"sourcecal", "localcal"} """ param_val = dict() if SEPARATOR.match(fid.readline()) is None: # skip 1 separator line raise ValueError("Unexpected line in ECS file!") source = None cont = True while cont: curr_pos = fid.tell() # current position line = fid.readline() if SEPARATOR.match(line) is not None: # reverse to previous position and jump out fid.seek(curr_pos) cont = False elif line == "": # EOF break else: if status == "fileset" and source is None: source = "fileset" # force this for easy organization param_val[source] = dict() elif status in line.lower(): # {"sourcecal", "localcal"} source = CAL_HIERARCHY.match(line)["source"] param_val[source] = dict() else: if line != "\n" and source is not None: tmp = PARAM_MATCHER.match(line) if tmp["skip"] == "" or tmp["param"] == "Frequency": # not skipping param_val[source][tmp["param"]] = tmp["val"] return param_val def _convert_param_type(self): """ Convert data type for all parameters. """ def convert_type(input_dict): for k, v in input_dict.items(): if k == "TvgRangeCorrection": if v not in self.TvgRangeCorrection_allowed_str: raise ValueError("TvgRangeCorrection contains unexpected setting!") elif k == "TransducerModeActive": input_dict[k] = bool(v) else: val_rep = re.findall(VAL_PATTERN, v) # only match numbers if len(val_rep) > 1: # many values (ie a vector) input_dict[k] = np.array(val_rep).astype(float) else: input_dict[k] = float(v) for status, status_settings in self.parsed_params.items(): if status == "fileset": # fileset only has 1 layer of dict convert_type(status_settings) else: # sourcecal or localcal has another layer of dict for src_k, src_v in status_settings.items(): convert_type(src_v) def parse(self): """ Parse the entire ECS file. """ fid = open(self.input_file, encoding="utf-8-sig") line = fid.readline() parsed_params = dict() status = None # status = {"ecs", "fileset", "sourcecal", "localcal"} while line != "": # EOF: line="" if line != "\n": # skip empty line if SEPARATOR.match(line) is not None: if status is not None: # entering another block status = None elif status is None: # going into a block status_str = STATUS_CRUDE.match(line)["status"].lower() if "ecs" in status_str: status = "ecs" self.data_type = ECS_HEADER.match(line)["data_type"] # get data type self._parse_header(fid) elif ( "fileset" in status_str or "sourcecal" in status_str or "localcal" in status_str ): status = STATUS_FINE.match(line)["status"].lower() parsed_params[status] = self._parse_block(fid, status) else: raise ValueError("Expecting a new block but got something else!") line = fid.readline() # read next line # Make FileSet settings dict less awkward parsed_params["fileset"] = parsed_params["fileset"]["fileset"] # Store params self.parsed_params = parsed_params # Convert parameter type to float self._convert_param_type() def get_cal_params(self, localcal_name=None) -> dict(): """ Get a consolidated set of calibration parameters that is applied to data by Echoview. The calibration settings in Echoview have an overwriting hierarchy as documented `here <https://support.echoview.com/WebHelp/Reference/File_formats/Echoview_calibration_supplement_files.html>`_. # noqa Parameters ---------- localcal_name : str or None Name of the LocalCal settings selected in Echoview. Default is the first one read in the ECS file. Returns ------- A dictionary containing calibration parameters as interpreted by Echoview. """ # Create template based on sources sources = self.parsed_params["sourcecal"].keys() ev_cal_params = dict().fromkeys(sources) # FileSet settings: apply to all sources for src in sources: ev_cal_params[src] = self.parsed_params["fileset"].copy() # SourceCal settings: overwrite FileSet settings for each source for src in sources: for k, v in self.parsed_params["sourcecal"][src].items(): ev_cal_params[src][k] = v # LocalCal settings: overwrite the above settings for all sources if self.parsed_params["localcal"] != {}: if localcal_name is None: # use the first LocalCal setting by default localcal_name = list(self.parsed_params["localcal"].keys())[0] for k, v in self.parsed_params["localcal"][localcal_name].items(): for src in sources: ev_cal_params[src][k] = v return ev_cal_params def ecs_ev2ep( ev_dict: Dict[str, Union[int, float, str]], sonar_type: Literal["EK60", "EK80", "AZFP"], ) -> Tuple[xr.Dataset, xr.Dataset, Union[None, xr.Dataset]]: """ Convert dictionary from consolidated ECS form to xr.DataArray expected by echopype. Parameters ---------- ev_dict : dict A dictionary of the format parsed by the ECS parser sonar_type : str Type of sonar, must be one of {}"EK60", "EK80", "AZFP"} Returns ------- env_dict : xr.Dataset An xr.Dataset containing environmental parameters cal_dict : xr.Dataset An xr.Dataset containing calibration parameters cal_dict_BB : xr.Dataset or None An xr.Dataset containing frequency-dependent calibration parameters (EK80 only) """ # Set up allowable cal or env variables if sonar_type[:2] == "EK": PARAM_MAP = EV_EP_MAP["EK60"] if sonar_type == "EK80": PARAM_MAP = dict(PARAM_MAP, **EV_EP_MAP["EK80"]) # all params - env params = cal params CAL_PARAMS = set(PARAM_MAP.keys()).difference(set(ENV_PARAMS)) # remove freq-dep ones CAL_PARAMS = set(CAL_PARAMS).difference(CAL_PARAMS_BB) def get_param_ds(param_type): dict_out = defaultdict(list) for p_name in param_type: param_tmp = [] for source, source_dict in ev_dict.items(): # all transducers if p_name in source_dict: param_tmp.append(source_dict[p_name]) else: param_tmp.append(np.nan) if not np.isnan(param_tmp).all(): # only keep param if not all NaN dict_out[PARAM_MAP[p_name]] = (["channel"], param_tmp) return xr.Dataset(data_vars=dict_out, coords={"channel": np.arange(len(ev_dict))}) # Scalar params: add dimension to dict and assemble DataArray ds_env = get_param_ds(ENV_PARAMS) ds_cal = get_param_ds(CAL_PARAMS) ds_env["frequency_nominal"] = ds_cal["frequency_nominal"] # used for checking later # Vector params (frequency-dep params) ds_cal_BB = [] for source, source_dict in ev_dict.items(): if "FrequencyTableWideband" in source_dict: param_dict = {} for p_name in CAL_PARAMS_BB: if p_name in source_dict: # only for param that exists in dict param_dict[PARAM_MAP[p_name]] = (["cal_frequency"], source_dict[p_name]) ds_ch = xr.Dataset( data_vars=param_dict, coords={ "cal_frequency": ( ["cal_frequency"], source_dict["FrequencyTableWideband"], { "long_name": "Frequency of calibration parameter", "units": "Hz", }, ) }, ) ds_ch = ds_ch.drop_vars("frequency_BB") ds_ch = ds_ch.expand_dims({"frequency_nominal": [source_dict["Frequency"]]}) ds_cal_BB.append(ds_ch) ds_cal_BB = xr.merge(ds_cal_BB) if len(ds_cal_BB) != 0 else None # Convert frequency variables from kHz to Hz for p_name in ["frequency_nominal", "sampling_frequency", "receiver_sampling_frequency"]: for ds in [ds_env, ds_cal, ds_cal_BB]: if ds is not None and p_name in ds: ds[p_name] = ds[p_name] * 1000 return ds_env, ds_cal, ds_cal_BB def ecs_ds2dict(ds: xr.Dataset) -> Dict: """ Convert an xr.Dataset to a dictionary with each data variable being a key-value pair. """ dict_tmp = {} for data_var_name in ds.data_vars: dict_tmp[data_var_name] = ds[data_var_name] return dict_tmp def conform_channel_order(ds_in: xr.Dataset, freq_ref: xr.DataArray) -> xr.Dataset: """ Check the sequence of channels against a set of reference channels and reorder if necessary. Parameters ---------- ds_in : xr.Dataset An xr.Dataset generated by ``ev2ep_dict``. It must contain 'frequency_nominal' as a data variable and 'channel' as a dimension. freq_ref : xr.DataArray An xr.DataArray containing the nominal frequency in the order to be conformed with. It must contain 'channel' as a coordinate. Returns ------- xr.Dataset or None An xr.Dataset containing channels (frequencies) that are the intersection of ``freq_ref`` and ``ds_in``, with the channel aligned in the same order as the subset of ``freq_ref``. None is returned if there is no overlapping frequency between ``freq_ref`` and ``ds_in``. Notes ----- If ``ds_in`` contains more channels than ``freq_ref``, only those present in ``freq_ref`` are selected and retained. Raises ------ ValueError If ``freq_ref`` is not an xr.DataArray ValueError If ``freq_ref`` does not contain ``channel` as a coordinate """ # freq_ref must be an xr.DataArray with channel as a coordinate if not isinstance(freq_ref, xr.DataArray): raise ValueError("'freq_ref' has to be an xr.DataArray!") else: if "channel" not in freq_ref.coords: raise ValueError("'channel' has to be a coordinate 'freq_ref'!") # ds_in must be an xr.Dataset with either channel or frequency_nominal as a coordinate if "channel" not in ds_in.coords and "frequency_nominal" not in ds_in.coords: raise ValueError( "'ds_in' must be an xr.Dataset with either 'channel' or 'frequency_nominal' " "as a coordinate!" ) # Get frequencies that exist in both freq_req and ds_in freq_overlap = list(set(freq_ref.values) & set(ds_in["frequency_nominal"].values)) if len(freq_overlap) == 0: # no overlapping frequency return None else: # need to sort freq_overlap according to freq_ref order freq_overlap = [f for f in freq_ref.values if f in freq_overlap] # Set both freq_ref and ds_in to align with frequency freq_ref.name = "frequency_nominal" freq_ref = ( freq_ref.to_dataset() .set_coords("frequency_nominal") .swap_dims({"channel": "frequency_nominal"}) .sel(frequency_nominal=freq_overlap) # subset ) # channel is coordinate, swap to align with frequency_nominal if "frequency_nominal" not in ds_in.coords: ds_in = ds_in.set_coords("frequency_nominal").swap_dims( {"channel": "frequency_nominal"} ) ds_in = ds_in.sel(frequency_nominal=freq_overlap) # subset # Reorder according to the frequency dimension, this will subset ds_in as well ds_in = ds_in.reindex_like(freq_ref) ds_in["channel"] = freq_ref["channel"] return ds_in.swap_dims({"frequency_nominal": "channel"}).drop("frequency_nominal")
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,772
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/calibrate/test_ecs_integration.py
import pytest import numpy as np import xarray as xr import echopype as ep from echopype.calibrate.ecs import ECSParser, ecs_ev2ep, ecs_ds2dict, conform_channel_order from echopype.calibrate.env_params import get_env_params_EK from echopype.calibrate.cal_params import get_cal_params_EK # @pytest.fixture # def azfp_path(test_path): # return test_path['AZFP'] @pytest.fixture def ek60_path(test_path): return test_path['EK60'] @pytest.fixture def ecs_path(test_path): return test_path['ECS'] @pytest.fixture def ek80_path(test_path): return test_path['EK80'] # @pytest.fixture # def ek80_cal_path(test_path): # return test_path['EK80_CAL'] # @pytest.fixture # def ek80_ext_path(test_path): # return test_path['EK80_EXT'] def test_ecs_intake_ek60(ek60_path, ecs_path): # get EchoData object that has the water_level variable under platform and compute Sv of it ed = ep.open_raw(ek60_path / "ncei-wcsd" / "Summer2017-D20170620-T011027.raw", "EK60") ecs_file = ecs_path / "Summer2017_JuneCal_3freq_mod.ecs" ds_Sv = ep.calibrate.compute_Sv(ed, ecs_file=ecs_file) # Parse ECS separately ecs = ECSParser(ecs_file) ecs.parse() ecs_dict = ecs.get_cal_params() # apply ECS hierarchy ds_env_tmp, ds_cal_tmp, _ = ecs_ev2ep(ecs_dict, "EK60") env_params = ecs_ds2dict(conform_channel_order(ds_env_tmp, ed["Sonar/Beam_group1"]["frequency_nominal"])) cal_params = ecs_ds2dict(conform_channel_order(ds_cal_tmp, ed["Sonar/Beam_group1"]["frequency_nominal"])) # Check if the final stored params (which are those used in calibration operations) # are those parsed from ECS for p_name in ["sound_speed", "sound_absorption"]: assert "ping_time" not in ds_Sv[p_name] # only if pull from data will params have time coord assert ds_Sv[p_name].identical(env_params[p_name]) for p_name in [ "sa_correction", "gain_correction", "equivalent_beam_angle", "beamwidth_alongship", "beamwidth_athwartship", "angle_offset_alongship", "angle_offset_athwartship", "angle_sensitivity_alongship", "angle_sensitivity_athwartship" ]: assert ds_Sv[p_name].identical(cal_params[p_name]) # EK80 CW power def test_ecs_intake_ek80_CW_power(ek80_path, ecs_path): # get EchoData object that has the water_level variable under platform and compute Sv of it ed = ep.open_raw(ek80_path / "Summer2018--D20180905-T033113.raw", sonar_model="EK80") ecs_file = ecs_path / "Simrad_EK80_ES80_WBAT_EKAuto_Kongsberg_EA640_nohash.ecs" ds_Sv = ep.calibrate.compute_Sv(ed, ecs_file=ecs_file, waveform_mode="CW", encode_mode="power") # Parse ECS separately ecs = ECSParser(ecs_file) ecs.parse() ecs_dict = ecs.get_cal_params() # apply ECS hierarchy ds_env, ds_cal_NB, ds_cal_BB = ecs_ev2ep(ecs_dict, "EK80") beam = ed["Sonar/Beam_group2"] chan_sel = ["WBT 743366-15 ES38B_ES", "WBT 743367-15 ES18_ES"] ecs_env_params = ecs_ds2dict( conform_channel_order(ds_env, beam["frequency_nominal"].sel(channel=chan_sel)) ) ecs_cal_params = ecs_ds2dict( conform_channel_order(ds_cal_NB, beam["frequency_nominal"].sel(channel=chan_sel)) ) ecs_cal_tmp_BB_conform_freq = conform_channel_order( ds_cal_BB, beam["frequency_nominal"].sel(channel=chan_sel) ) assert ecs_cal_tmp_BB_conform_freq is None # Assimilate to standard env_params and cal_params in cal object assimilated_env_params = get_env_params_EK( sonar_type="EK80", beam=beam, env=ed["Environment"], user_dict=ecs_env_params, freq=beam["frequency_nominal"].sel(channel=chan_sel), ) # Check the final stored params (which are those used in calibration operations) # For those pulled from ECS for p_name in ["sound_speed", "temperature", "salinity", "pressure", "pH"]: assert ds_Sv[p_name].identical(ecs_env_params[p_name]) for p_name in [ "sa_correction", "gain_correction", "equivalent_beam_angle", "beamwidth_alongship", "beamwidth_athwartship", "angle_offset_alongship", "angle_offset_athwartship", "angle_sensitivity_alongship", "angle_sensitivity_athwartship" ]: assert ds_Sv[p_name].identical(ecs_cal_params[p_name]) # For those computed from values in ECS file assert np.all(ds_Sv["sound_absorption"].values == assimilated_env_params["sound_absorption"].values) # TODO: remove params that are only relevant to EK80 complex sample cals # `impedance_transducer`, `impedance_transceiver`, `receiver_sampling_frequency` # for p_name in ["impedance_transducer", "impedance_transceiver", "receiver_sampling_frequency"]: # assert p_name not in ds_Sv # EK80 BB complex def test_ecs_intake_ek80_BB_complex(ek80_path, ecs_path): # get EchoData object that has the water_level variable under platform and compute Sv of it ed = ep.open_raw(ek80_path / "Summer2018--D20180905-T033113.raw", sonar_model="EK80") ecs_file = ecs_path / "Simrad_EK80_ES80_WBAT_EKAuto_Kongsberg_EA640_nohash.ecs" ds_Sv = ep.calibrate.compute_Sv(ed, ecs_file=ecs_file, waveform_mode="BB", encode_mode="complex") # Parse ECS separately ecs = ECSParser(ecs_file) ecs.parse() ecs_dict = ecs.get_cal_params() # apply ECS hierarchy ecs_env, ecs_cal_NB, ecs_cal_BB = ecs_ev2ep(ecs_dict, "EK80") # chan_sel = ['WBT 545612-15 ES200-7C_ES', 'WBT 549762-15 ES70-7C_ES', 'WBT 743869-15 ES120-7C_ES'] ecs_env = conform_channel_order(ecs_env, ds_Sv["frequency_nominal"]) ecs_cal_NB = conform_channel_order(ecs_cal_NB, ds_Sv["frequency_nominal"]) ecs_cal_BB = conform_channel_order(ecs_cal_BB, ds_Sv["frequency_nominal"]) # Check the final stored params (which are those used in calibration operations) # For those pulled from ECS for p_name in ["sound_speed", "temperature", "salinity", "pressure", "pH"]: assert ds_Sv[p_name].identical(ecs_env[p_name]) for p_name in ["sa_correction", "receiver_sampling_frequency"]: assert ds_Sv[p_name].identical(ecs_cal_NB[p_name]) # Check interpolation was done correctly beam = ed["Sonar/Beam_group1"] chan_w_BB_param = "WBT 549762-15 ES70-7C_ES" freq_center = ( (beam["transmit_frequency_start"] + beam["transmit_frequency_stop"]) / 2 ).sel(channel=chan_w_BB_param).drop_vars(["channel"]) for p_name in [ "gain_correction", "angle_offset_alongship", "angle_offset_athwartship", "beamwidth_alongship", "beamwidth_athwartship", ]: assert ds_Sv[p_name].sel(channel=chan_w_BB_param).drop_vars("channel").identical( ecs_cal_BB[p_name].interp(cal_frequency=freq_center) .squeeze().drop_vars(["channel", "cal_frequency"]) ) # TODO: remove params that are only relevant to EK80 CW cals `sa_correction` # assert "sa_correction" not in ds_Sv
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,773
OSOceanAcoustics/echopype
refs/heads/main
/echopype/calibrate/api.py
import xarray as xr from ..echodata import EchoData from ..echodata.simrad import check_input_args_combination from ..utils.log import _init_logger from ..utils.prov import echopype_prov_attrs, source_files_vars from .calibrate_azfp import CalibrateAZFP from .calibrate_ek import CalibrateEK60, CalibrateEK80 CALIBRATOR = { "EK60": CalibrateEK60, "EK80": CalibrateEK80, "AZFP": CalibrateAZFP, "ES70": CalibrateEK60, "ES80": CalibrateEK80, "EA640": CalibrateEK80, } logger = _init_logger(__name__) def _compute_cal( cal_type, echodata: EchoData, env_params=None, cal_params=None, ecs_file=None, waveform_mode=None, encode_mode=None, ): # Check on waveform_mode and encode_mode inputs if echodata.sonar_model == "EK80": if waveform_mode is None or encode_mode is None: raise ValueError("waveform_mode and encode_mode must be specified for EK80 calibration") check_input_args_combination(waveform_mode, encode_mode) elif echodata.sonar_model in ("EK60", "AZFP"): if waveform_mode is not None and waveform_mode != "CW": logger.warning( "This sonar model transmits only narrowband signals (waveform_mode='CW'). " "Calibration will be in CW mode", ) if encode_mode is not None and encode_mode != "power": logger.warning( "This sonar model only record data as power or power/angle samples " "(encode_mode='power'). Calibration will be done on the power samples.", ) # Set up calibration object cal_obj = CALIBRATOR[echodata.sonar_model]( echodata, env_params=env_params, cal_params=cal_params, ecs_file=ecs_file, waveform_mode=waveform_mode, encode_mode=encode_mode, ) # Perform calibration if cal_type == "Sv": cal_ds = cal_obj.compute_Sv() elif cal_type == "TS": cal_ds = cal_obj.compute_TS() else: raise ValueError("cal_type must be Sv or TS") # Add attributes def add_attrs(cal_type, ds): """Add attributes to backscattering strength dataset. cal_type: Sv or TS """ ds["range_sample"].attrs = {"long_name": "Along-range sample number, base 0"} ds["echo_range"].attrs = {"long_name": "Range distance", "units": "m"} ds[cal_type].attrs = { "long_name": { "Sv": "Volume backscattering strength (Sv re 1 m-1)", "TS": "Target strength (TS re 1 m^2)", }[cal_type], "units": "dB", "actual_range": [ round(float(ds[cal_type].min().values), 2), round(float(ds[cal_type].max().values), 2), ], } if echodata.sonar_model == "EK80": ds[cal_type] = ds[cal_type].assign_attrs( { "waveform_mode": waveform_mode, "encode_mode": encode_mode, } ) add_attrs(cal_type, cal_ds) # Add provinance # Provenance source files may originate from raw files (echodata.source_files) # or converted files (echodata.converted_raw_path) if echodata.source_file is not None: source_file = echodata.source_file elif echodata.converted_raw_path is not None: source_file = echodata.converted_raw_path else: source_file = "SOURCE FILE NOT IDENTIFIED" prov_dict = echopype_prov_attrs(process_type="processing") prov_dict["processing_function"] = f"calibrate.compute_{cal_type}" files_vars = source_files_vars(source_file) cal_ds = ( cal_ds.assign(**files_vars["source_files_var"]) .assign_coords(**files_vars["source_files_coord"]) .assign_attrs(prov_dict) ) # Add water_level to the created xr.Dataset if "water_level" in echodata["Platform"].data_vars.keys(): cal_ds["water_level"] = echodata["Platform"].water_level return cal_ds def compute_Sv(echodata: EchoData, **kwargs) -> xr.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 ---------- echodata : EchoData An `EchoData` object created by using `open_raw` or `open_converted` env_params : dict, 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_params : dict, 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"`, `"VTX"`, `"equivalent_beam_angle"`, `"Sv_offset"` Passing in calibration parameters for other echosounders are not currently supported. waveform_mode : {"CW", "BB"}, 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"` 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 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 (``waveform_mode="BB"``) 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()`. """ return _compute_cal(cal_type="Sv", echodata=echodata, **kwargs) def 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 ---------- echodata : EchoData An `EchoData` object created by using `open_raw` or `open_converted` env_params : dict, 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_params : dict, 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"`, `"VTX"`, `"equivalent_beam_angle"`, `"Sv_offset"` Passing in calibration parameters for other echosounders are not currently supported. waveform_mode : {"CW", "BB"}, 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"` 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 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 (``waveform_mode="BB"``) 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 """ return _compute_cal(cal_type="TS", echodata=echodata, **kwargs)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,774
OSOceanAcoustics/echopype
refs/heads/main
/echopype/convert/parse_ad2cp.py
from collections import OrderedDict from enum import Enum, auto, unique from typing import Any, BinaryIO, Callable, Dict, Iterable, List, Optional, Tuple, Union import numpy as np from typing_extensions import Literal from .parse_base import ParseBase @unique class BurstAverageDataRecordVersion(Enum): """ Determines the version of the burst/average data record """ VERSION2 = auto() # Burst/Average Data Record Definition (DF2) VERSION3 = auto() # Burst/Average Data Record Definition (DF3) @unique class DataRecordType(Enum): """ Determines the type of data record """ BURST_VERSION2 = auto() BURST_VERSION3 = auto() AVERAGE_VERSION2 = auto() AVERAGE_VERSION3 = auto() ECHOSOUNDER = auto() ECHOSOUNDER_RAW = auto() ECHOSOUNDER_RAW_TRANSMIT = auto() BOTTOM_TRACK = auto() STRING = auto() @unique class DataType(Enum): """ Determines the data type of raw bytes """ RAW_BYTES = auto() STRING = auto() SIGNED_INTEGER = auto() UNSIGNED_INTEGER = auto() # UNSIGNED_LONG = auto() FLOAT = auto() SIGNED_FRACTION = auto() def dtype(self, size_bytes: int) -> np.dtype: if self in (SIGNED_INTEGER, UNSIGNED_INTEGER, FLOAT): return np.dtype(DTYPES[(self, size_bytes)]) # type: ignore elif self == RAW_BYTES: return np.dtype("<u1") elif self == STRING: return np.dtype("U") elif self == SIGNED_FRACTION: return np.dtype("<f8") else: raise ValueError("unrecognized data type") @staticmethod def default_dtype() -> np.dtype: return np.dtype("<u8") RAW_BYTES = DataType.RAW_BYTES STRING = DataType.STRING SIGNED_INTEGER = DataType.SIGNED_INTEGER UNSIGNED_INTEGER = DataType.UNSIGNED_INTEGER # UNSIGNED_LONG = DataType.UNSIGNED_LONG FLOAT = DataType.FLOAT SIGNED_FRACTION = DataType.SIGNED_FRACTION DtypesHint = Literal["<i1", "<i2", "<i4", "<i8", "<u1", "<u2", "<u4", "<u8", "<f2", "<f4", "<f8"] DTYPES: Dict[Tuple[DataType, int], DtypesHint] = { (SIGNED_INTEGER, 1): "<i1", (SIGNED_INTEGER, 2): "<i2", (SIGNED_INTEGER, 4): "<i4", (SIGNED_INTEGER, 8): "<i8", (UNSIGNED_INTEGER, 1): "<u1", (UNSIGNED_INTEGER, 2): "<u2", (UNSIGNED_INTEGER, 4): "<u4", (UNSIGNED_INTEGER, 8): "<u8", (FLOAT, 2): "<f2", (FLOAT, 4): "<f4", (FLOAT, 8): "<f8", (SIGNED_FRACTION, 1): "<i1", (SIGNED_FRACTION, 2): "<i2", (SIGNED_FRACTION, 4): "<i4", (SIGNED_FRACTION, 8): "<i8", } @unique class Dimension(Enum): """ Determines the dimensions of the data in the output dataset """ PING_TIME = auto() PING_TIME_AVERAGE = auto() PING_TIME_BURST = auto() PING_TIME_ECHOSOUNDER = auto() PING_TIME_ECHOSOUNDER_RAW = auto() PING_TIME_ECHOSOUNDER_RAW_TRANSMIT = auto() BEAM = auto() RANGE_SAMPLE_BURST = auto() RANGE_SAMPLE_AVERAGE = auto() RANGE_SAMPLE_ECHOSOUNDER = auto() NUM_ALTIMETER_SAMPLES = auto() SAMPLE = auto() SAMPLE_TRANSMIT = auto() MIJ = auto() XYZ = auto() WXYZ = auto() def dimension_name(self) -> str: return DIMENSION_NAMES[self] DIMENSION_NAMES = { Dimension.PING_TIME: "time1", Dimension.PING_TIME_AVERAGE: "ping_time", Dimension.PING_TIME_BURST: "ping_time", Dimension.PING_TIME_ECHOSOUNDER: "ping_time", Dimension.PING_TIME_ECHOSOUNDER_RAW: "ping_time", Dimension.PING_TIME_ECHOSOUNDER_RAW_TRANSMIT: "ping_time_transmit", Dimension.BEAM: "beam", Dimension.RANGE_SAMPLE_BURST: "range_sample", Dimension.RANGE_SAMPLE_AVERAGE: "range_sample", Dimension.RANGE_SAMPLE_ECHOSOUNDER: "range_sample", Dimension.NUM_ALTIMETER_SAMPLES: "num_altimeter_samples", Dimension.SAMPLE: "range_sample", Dimension.SAMPLE_TRANSMIT: "transmit_sample", Dimension.MIJ: "mij", Dimension.XYZ: "xyz", Dimension.WXYZ: "wxyz", } class Field: """ Represents a single field within a data record and controls the way the field will be parsed """ def __init__( self, field_name: Optional[str], field_entry_size_bytes: Union[int, Callable[["Ad2cpDataPacket"], int]], field_entry_data_type: DataType, # field_entry_data_type: Union[DataType, Callable[["Ad2cpDataPacket"], DataType]], *, field_shape: Union[List[int], Callable[["Ad2cpDataPacket"], List[int]]] = [], field_dimensions: Union[List[Dimension], Callable[[DataRecordType], List[Dimension]]] = [ Dimension.PING_TIME ], field_unit_conversion: Callable[ ["Ad2cpDataPacket", np.ndarray], np.ndarray ] = lambda _, x: x, field_exists_predicate: Callable[["Ad2cpDataPacket"], bool] = lambda _: True, ): """ field_name: Name of the field. If None, the field is parsed but ignored field_entry_size_bytes: Size of each entry within the field, in bytes. In most cases, the entry is the field itself, but sometimes the field contains a list of entries. field_entry_data_type: Data type of each entry in the field field_shape: Shape of entries within the field. [] (the default) means the entry is the field itself, [n] means the field consists of a list of n entries, [n, m] means the field consists of a two dimensional array with n number of m length arrays, etc. field_dimensions: Dimensions of the field in the output dataset field_unit_conversion: Unit conversion function on field field_exists_predicate: Tests to see whether the field should be parsed at all """ self.field_name = field_name self.field_entry_size_bytes = field_entry_size_bytes self.field_entry_data_type = field_entry_data_type self.field_shape = field_shape self.field_dimensions = field_dimensions self.field_unit_conversion = field_unit_conversion self.field_exists_predicate = field_exists_predicate def dimensions(self, data_record_type: DataRecordType) -> List[Dimension]: """ Returns the dimensions of the field given the data record type """ dims = self.field_dimensions if callable(dims): dims = dims(data_record_type) return dims @staticmethod def default_dimensions() -> List[Dimension]: """ Returns the default dimensions for fields """ return [Dimension.PING_TIME] F = Field # use F instead of Field to make the repeated fields easier to read class NoMorePackets(Exception): """ Indicates that there are no more packets to be parsed from the file """ pass class ParseAd2cp(ParseBase): def __init__(self, file, params, storage_options={}, dgram_zarr_vars={}): super().__init__(file, storage_options) self.config = None self.packets: List[Ad2cpDataPacket] = [] def parse_raw(self): """ Parses the source file into AD2CP packets """ with open(self.source_file, "rb") as f: while True: try: packet = Ad2cpDataPacket(f, self) self.packets.append(packet) except NoMorePackets: break else: if self.config is None and packet.is_string(): self.config = self.parse_config(packet.data["string_data"]) if self.config is not None and "GETCLOCKSTR" in self.config: self.ping_time.append(np.datetime64(self.config["GETCLOCKSTR"]["TIME"])) else: self.ping_time.append(np.datetime64()) @staticmethod def parse_config(data: np.ndarray) -> Dict[str, Dict[str, Any]]: """ Parses the configuration string for the ADCP, which will be the first string data record. The data is in the form: HEADING1,KEY1=VALUE1,KEY2=VALUE2 HEADING2,KEY3=VALUE3,KEY4=VALUE4,KEY5=VALUE5 ... where VALUEs can be strings: "foo" integers: 123 floats: 123.456 """ result = dict() for line in data[()].splitlines(): tokens = line.split(",") line_dict = dict() for token in tokens[1:]: k, v = token.split("=") if v.startswith('"'): v = v.strip('"') else: try: v = int(v) except ValueError: try: v = float(v) except ValueError: v = str(v) line_dict[k] = v result[tokens[0]] = line_dict return result def get_firmware_version(self) -> Optional[Dict[str, Any]]: return self.config.get("GETHW") # type: ignore def get_pulse_compressed(self) -> int: for i in range(1, 3 + 1): if "GETECHO" in self.config and self.config["GETECHO"][f"PULSECOMP{i}"] > 0: # type: ignore # noqa return i return 0 class Ad2cpDataPacket: """ Represents a single data packet. Each data packet consists of a header data record followed by a """ def __init__( self, f: BinaryIO, parser: ParseAd2cp, ): self.parser = parser self.data_record_type: Optional[DataRecordType] = None self.data = dict() self._read_header(f) self._read_data_record(f) @property def timestamp(self) -> np.datetime64: """ Calculates and returns the timestamp of the packet """ year = self.data["year"] + 1900 month = self.data["month"] + 1 day = self.data["day"] hour = self.data["hour"] minute = self.data["minute"] seconds = self.data["seconds"] microsec100 = self.data["microsec100"] try: return np.datetime64( f"{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{seconds:02}.{microsec100:04}" ) # type: ignore except ValueError: return np.datetime64("NaT") # type: ignore def is_burst(self) -> bool: """ Returns whether the current packet is a burst packet """ return self.data["id"] in (0x15, 0x18) def is_average(self) -> bool: """ Returns whether the current packet is an average packet """ return self.data["id"] == 0x16 def is_bottom_track(self) -> bool: """ Returns whether the current packet is a bottom track packet """ return self.data["id"] in (0x17, 0x1B) def is_echosounder(self) -> bool: """ Returns whether the current packet is an echosounder packet """ return self.data["id"] == 0x1C def is_echosounder_raw(self) -> bool: """ Returns whether the current packet is a raw echosounder packet """ return self.data["id"] == 0x23 def is_echosounder_raw_transmit(self) -> bool: """ Returns whether the current packet is a raw echosounder transmit packet """ return self.data["id"] == 0x24 def is_burst_altimeter(self) -> bool: return self.data["id"] == 0x1A def is_dvl_water_track(self) -> bool: return self.data["id"] == 0x1D def is_altimeter(self) -> bool: return self.data["id"] == 0x1E def is_average_altimeter(self) -> bool: return self.data["id"] == 0x1F def is_string(self) -> bool: """ Returns whether the current packet is a string packet """ return self.data["id"] == 0xA0 def has_timestamp(self) -> bool: """ Returns whether the packet has a timestamp (.timestamp can be called) """ return not self.is_string() def _read_header(self, f: BinaryIO): """ Reads the header part of the AD2CP packet from the given stream """ self.data_record_format = HeaderOrDataRecordFormats.HEADER_FORMAT raw_header = self._read_data(f, self.data_record_format) # don't include the last 2 bytes, which is the header checksum itself calculated_checksum = self.checksum(raw_header[:-2]) expected_checksum = self.data["header_checksum"] assert ( calculated_checksum == expected_checksum ), f"invalid header checksum: found {calculated_checksum}, expected {expected_checksum}" def _read_data_record(self, f: BinaryIO): """ Reads the data record part of the AD2CP packet from the stream """ if self.is_burst(): # burst self.data_record_type = DataRecordType.BURST_VERSION3 elif self.is_average(): # average self.data_record_type = DataRecordType.AVERAGE_VERSION3 elif self.is_bottom_track(): # bottom track self.data_record_type = DataRecordType.BOTTOM_TRACK elif self.is_echosounder_raw(): # echosounder raw self.data_record_type = DataRecordType.ECHOSOUNDER_RAW elif self.is_echosounder_raw_transmit(): # echosounder raw transmit self.data_record_type = DataRecordType.ECHOSOUNDER_RAW_TRANSMIT elif self.is_burst_altimeter(): # burst altimeter # altimeter is only supported by burst/average version 3 self.data_record_type = DataRecordType.BURST_VERSION3 elif self.is_echosounder(): # echosounder # echosounder is only supported by burst/average version 3 self.data_record_type = DataRecordType.ECHOSOUNDER elif self.is_dvl_water_track(): # dvl water track record # TODO: is this correct? self.data_record_type = DataRecordType.AVERAGE_VERSION3 elif self.is_altimeter(): # altimeter # altimeter is only supported by burst/average version 3 self.data_record_type = DataRecordType.AVERAGE_VERSION3 elif self.is_average_altimeter(): # average altimeter self.data_record_type = DataRecordType.AVERAGE_VERSION3 elif self.is_string(): # string data self.data_record_type = DataRecordType.STRING else: raise ValueError("invalid data record type id: 0x{:02x}".format(self.data["id"])) self.data_record_format = HeaderOrDataRecordFormats.data_record_format( self.data_record_type ) raw_data_record = self._read_data(f, self.data_record_format) calculated_checksum = self.checksum(raw_data_record) expected_checksum = self.data["data_record_checksum"] assert ( calculated_checksum == expected_checksum ), f"invalid data record checksum: found {calculated_checksum}, expected {expected_checksum}" # noqa def _read_data(self, f: BinaryIO, data_format: "HeaderOrDataRecordFormat") -> bytes: """ Reads data from the stream, interpreting the data using the given format """ raw_bytes = bytes() # combination of all raw fields for field_format in data_format.fields_iter(): field_name = field_format.field_name field_entry_size_bytes = field_format.field_entry_size_bytes field_entry_data_type = field_format.field_entry_data_type field_shape = field_format.field_shape field_unit_conversion = field_format.field_unit_conversion field_exists_predicate = field_format.field_exists_predicate if not field_exists_predicate(self): continue if callable(field_entry_size_bytes): field_entry_size_bytes = field_entry_size_bytes(self) # if callable(field_entry_data_type): # field_entry_data_type = field_entry_data_type(self) if callable(field_shape): field_shape = field_shape(self) raw_field = self._read_exact(f, field_entry_size_bytes * int(np.prod(field_shape))) raw_bytes += raw_field # we cannot check for this before reading because some fields are placeholder fields # which, if not read in the correct order with other fields, # will offset the rest of the data if field_name is not None: parsed_field = self._parse(raw_field, field_entry_data_type, field_entry_size_bytes) parsed_field = np.reshape(parsed_field, field_shape) parsed_field = field_unit_conversion(self, parsed_field) self.data[field_name] = parsed_field self._postprocess(field_name) return raw_bytes @staticmethod def _parse(value: bytes, data_type: DataType, size_bytes: int) -> np.ndarray: """ Parses raw bytes into a value given its data type """ if data_type in (SIGNED_INTEGER, UNSIGNED_INTEGER, FLOAT): dtype = np.dtype(DTYPES[(data_type, size_bytes)]) # type: ignore return np.frombuffer(value, dtype=dtype) elif data_type == RAW_BYTES: return np.frombuffer(value, dtype="<u1") elif data_type == STRING: return np.array(value.decode("utf-8")) elif data_type == SIGNED_FRACTION: # Although the specification states that the data is represented in a # signed-magnitude format, an email exchange with Nortek revealed that it is # actually in 2's complement form. dtype = np.dtype(DTYPES[(SIGNED_FRACTION, size_bytes)]) # type: ignore return (np.frombuffer(value, dtype=dtype) / (np.iinfo(dtype).max + 1)).astype("<f8") else: raise ValueError("unrecognized data type") @staticmethod def _read_exact(f: BinaryIO, total_num_bytes_to_read: int) -> bytes: """ Drives a stream until an exact amount of bytes is read from it. This is necessary because a single read may not return the correct number of bytes (see https://github.com/python/cpython/blob/5e437fb872279960992c9a07f1a4c051b4948c53/Python/fileutils.c#L1599-L1661 and https://github.com/python/cpython/blob/63298930fb531ba2bb4f23bc3b915dbf1e17e9e1/Modules/_io/fileio.c#L778-L835, note "Only makes one system call, so less data may be returned than requested") (see https://man7.org/linux/man-pages/man2/read.2.html#RETURN_VALUE, note "It is not an error if this number is smaller than the number of bytes requested") (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/read?view=msvc-160#return-value, note "_read returns the number of bytes read, which might be less than buffer_size...if the file was opened in text mode") """ # noqa all_bytes_read = bytes() if total_num_bytes_to_read <= 0: return all_bytes_read last_bytes_read = None while last_bytes_read is None or ( len(last_bytes_read) > 0 and len(all_bytes_read) < total_num_bytes_to_read ): last_bytes_read = f.read(total_num_bytes_to_read - len(all_bytes_read)) if len(last_bytes_read) == 0: # 0 bytes read with non-0 bytes requested means eof raise NoMorePackets else: all_bytes_read += last_bytes_read return all_bytes_read def _postprocess_bitfield( self, field_value: np.ndarray, bitfield_format: List[Tuple[str, int, int]], ): """ _postprocess helper; postprocesses a bitfield bitfield_format: [ (bit sequence name, start bit, end bit) ] e.g., with mask 0b00111100, start bit is 5 and end bit is 2 """ for bit_sequence_name, start_bit, end_bit in bitfield_format: self.data[bit_sequence_name] = np.array( (field_value >> end_bit) & ((1 << (start_bit - end_bit + 1)) - 1), dtype="<u8", ) def _postprocess_beams( self, field_value: np.ndarray, beams_format: List[Tuple[int, int]], ): """ _postprocess helper; postprocesses beams beams_format: [ (start bit, end bit) ] """ beams = [] for start_bit, end_bit in beams_format: beam = (field_value >> end_bit) & ((1 << (start_bit - end_bit + 1)) - 1) if beam > 0: beams.append(beam) self.data["beams"] = np.array(beams, dtype="<u8") def _postprocess(self, field_name): """ Calculates values based on parsed data. This should be called immediately after parsing each field in a data record. """ if ( self.data_record_format == HeaderOrDataRecordFormats.BURST_AVERAGE_VERSION2_DATA_RECORD_FORMAT ): if field_name == "version": if self.data["version"] == 3: self.data_record_format = ( HeaderOrDataRecordFormats.BURST_AVERAGE_VERSION3_DATA_RECORD_FORMAT ) elif field_name == "configuration": self._postprocess_bitfield( self.data["configuration"], [ ("pressure_sensor_valid", 0, 0), ("temperature_sensor_valid", 1, 1), ("compass_sensor_valid", 2, 2), ("tilt_sensor_valid", 3, 3), ("velocity_data_included", 5, 5), ("amplitude_data_included", 6, 6), ("correlation_data_included", 7, 7), ], ) elif field_name == "num_beams_and_coordinate_system_and_num_cells": self._postprocess_bitfield( self.data["num_beams_and_coordinate_system_and_num_cells"], [ ("num_cells", 9, 0), ("coordinate_system", 11, 10), ("num_beams", 15, 12), ], ) elif field_name == "dataset_description": self._postprocess_beams( self.data["dataset_description"], [(2, 0), (5, 3), (8, 6), (11, 9), (14, 12)], ) elif ( self.data_record_format == HeaderOrDataRecordFormats.BURST_AVERAGE_VERSION3_DATA_RECORD_FORMAT ): if field_name == "version": if self.data["version"] == 2: self.data_record_format = ( HeaderOrDataRecordFormats.BURST_AVERAGE_VERSION2_DATA_RECORD_FORMAT ) elif field_name == "configuration": self._postprocess_bitfield( self.data["configuration"], [ ("pressure_sensor_valid", 0, 0), ("temperature_sensor_valid", 1, 1), ("compass_sensor_valid", 2, 2), ("tilt_sensor_valid", 3, 3), ("velocity_data_included", 5, 5), ("amplitude_data_included", 6, 6), ("correlation_data_included", 7, 7), ("altimeter_data_included", 8, 8), ("altimeter_raw_data_included", 9, 9), ("ast_data_included", 10, 10), ("echosounder_data_included", 11, 11), ("ahrs_data_included", 12, 12), ("percentage_good_data_included", 13, 13), ("std_dev_data_included", 14, 14), ], ) elif field_name == "num_beams_and_coordinate_system_and_num_cells": if self.data["echosounder_data_included"]: self.data["num_echosounder_cells"] = self.data[ "num_beams_and_coordinate_system_and_num_cells" ] else: self._postprocess_bitfield( self.data["num_beams_and_coordinate_system_and_num_cells"], [ ("num_cells", 9, 0), ("coordinate_system", 11, 10), ("num_beams", 15, 12), ], ) elif field_name == "ambiguity_velocity_or_echosounder_frequency": if self.data["echosounder_data_included"]: # This is specified as "echo sounder frequency", but the description technically # says "number of echo sounder cells". # It is probably the frequency and not the number of cells # because the number of cells already replaces the data in # "num_beams_and_coordinate_system_and_num_cells" # when an echo sounder is present self.data["echosounder_frequency"] = self.data[ "ambiguity_velocity_or_echosounder_frequency" ] else: self.data["ambiguity_velocity"] = self.data[ "ambiguity_velocity_or_echosounder_frequency" ] elif field_name == "velocity_scaling": if not self.data["echosounder_data_included"]: # The unit conversion for ambiguity velocity is done here because it # requires the velocity_scaling, which is not known # when ambiguity velocity field is parsed self.data["ambiguity_velocity"] = self.data["ambiguity_velocity"] * ( 10.0 ** self.data["velocity_scaling"] ) elif field_name == "dataset_description": self._postprocess_beams( self.data["dataset_description"], [(3, 0), (7, 4), (11, 8), (16, 12)], ) if ( self.parser.packets[-1].is_echosounder_raw() or self.parser.packets[-1].is_echosounder_raw_transmit() ): self.parser.packets[-1].data["echosounder_raw_beam"] = self.data["beams"][0] elif field_name == "status0": if self.data["status0"] & 0b1000_0000_0000_0000: self._postprocess_bitfield( self.data["status0"], [ ("procidle3", 0, 0), ("procidle6", 1, 1), ("procidle12", 2, 2), ], ) elif field_name == "status": self._postprocess_bitfield( self.data["status"], [ ("wakeup_state", 31, 28), ("orientation", 27, 25), ("autoorientation", 24, 22), ("previous_wakeup_state", 21, 18), ("last_measurement_low_voltage_skip", 17, 17), ("active_configuration", 16, 16), ("echosounder_index", 15, 12), ("telemetry_data", 11, 11), ("boost_running", 10, 10), ("echosounder_frequency_bin", 9, 5), ("bd_scaling", 1, 1), ], ) elif self.data_record_format == HeaderOrDataRecordFormats.BOTTOM_TRACK_DATA_RECORD_FORMAT: if field_name == "configuration": self._postprocess_bitfield( self.data["configuration"], [ ("pressure_sensor_valid", 0, 0), ("temperature_sensor_valid", 1, 1), ("compass_sensor_valid", 2, 2), ("tilt_sensor_valid", 3, 3), ("velocity_data_included", 5, 5), ("distance_data_included", 8, 8), ("figure_of_merit_data_included", 9, 9), ("ahrs_data_included", 10, 10), ], ) elif field_name == "num_beams_and_coordinate_system_and_num_cells": self._postprocess_bitfield( self.data["num_beams_and_coordinate_system_and_num_cells"], [ ("num_cells", 9, 0), ("coordinate_system", 11, 10), ("num_beams", 15, 12), ], ) elif field_name == "dataset_description": self._postprocess_beams( self.data["dataset_description"], [(16, 12), (11, 8), (7, 4), (3, 0)], ) elif field_name == "velocity_scaling": # The unit conversion for ambiguity velocity is done here because it # requires the velocity_scaling, # which is not known when ambiguity velocity field is parsed self.data["ambiguity_velocity"] = self.data["ambiguity_velocity"] * ( 10.0 ** self.data["velocity_scaling"] ) elif ( self.data_record_format == HeaderOrDataRecordFormats.ECHOSOUNDER_RAW_DATA_RECORD_FORMAT ): if field_name == "echosounder_raw_samples": self.data["echosounder_raw_samples_i"] = self.data["echosounder_raw_samples"][:, 0] self.data["echosounder_raw_samples_q"] = self.data["echosounder_raw_samples"][:, 1] elif field_name == "echosounder_raw_transmit_samples": self.data["echosounder_raw_transmit_samples_i"] = self.data[ "echosounder_raw_transmit_samples" ][:, 0] self.data["echosounder_raw_transmit_samples_q"] = self.data[ "echosounder_raw_transmit_samples" ][:, 1] elif field_name == "status": self._postprocess_bitfield( self.data["status"], [ ("wakeup_state", 31, 28), ("orientation", 27, 25), ("autoorientation", 24, 22), ("previous_wakeup_state", 21, 18), ("last_measurement_low_voltage_skip", 17, 17), ("active_configuration", 16, 16), ("echosounder_index", 15, 12), ("telemetry_data", 11, 11), ("boost_running", 10, 10), ("echosounder_frequency_bin", 9, 5), ("bd_scaling", 1, 1), ], ) @staticmethod def checksum(data: bytes) -> int: """ Computes the checksum for the given data """ checksum = 0xB58C for i in range(0, len(data), 2): checksum += int.from_bytes(data[i : i + 2], byteorder="little") checksum %= 2**16 if len(data) % 2 == 1: checksum += data[-1] << 8 checksum %= 2**16 return checksum RANGE_SAMPLES = { DataRecordType.AVERAGE_VERSION2: Dimension.RANGE_SAMPLE_AVERAGE, DataRecordType.AVERAGE_VERSION3: Dimension.RANGE_SAMPLE_AVERAGE, DataRecordType.BURST_VERSION2: Dimension.RANGE_SAMPLE_BURST, DataRecordType.BURST_VERSION3: Dimension.RANGE_SAMPLE_BURST, DataRecordType.ECHOSOUNDER: Dimension.RANGE_SAMPLE_ECHOSOUNDER, } class HeaderOrDataRecordFormat: """ A collection of fields which represents the header format or a data record format """ def __init__(self, name: str, fields: List[Field]): self.name = name self.fields = OrderedDict([(f.field_name, f) for f in fields]) def get_field(self, field_name: str) -> Optional[Field]: """ Gets a field from the current packet based on its name. Since the field could also be in the packet's header, the header is searched in addition to this data record. """ if field_name in HeaderOrDataRecordFormats.HEADER_FORMAT.fields: return HeaderOrDataRecordFormats.HEADER_FORMAT.fields.get(field_name) return self.fields.get(field_name) def fields_iter(self) -> Iterable[Field]: """ Returns an iterable over the fields in this header or data record format """ return self.fields.values() class HeaderOrDataRecordFormats: @classmethod def data_record_format(cls, data_record_type: DataRecordType) -> HeaderOrDataRecordFormat: """ Returns data record format that should be used to parse the given data record type """ return cls.DATA_RECORD_FORMATS[data_record_type] HEADER_FORMAT: HeaderOrDataRecordFormat = HeaderOrDataRecordFormat( "HEADER_FORMAT", [ F("sync", 1, UNSIGNED_INTEGER), F("header_size", 1, UNSIGNED_INTEGER), F("id", 1, UNSIGNED_INTEGER), F("family", 1, UNSIGNED_INTEGER), F( "data_record_size", lambda packet: 4 if packet.data["id"] in (0x23, 0x24) else 2, UNSIGNED_INTEGER, ), # F("data_record_size", lambda packet: 4 if packet.raw_fields["id"] in ( # 0x23, 0x24) else 2, lambda packet: UNSIGNED_LONG if packet.raw_fields["id"] # in (0x23, 0x24) else UNSIGNED_INTEGER), F("data_record_checksum", 2, UNSIGNED_INTEGER), F("header_checksum", 2, UNSIGNED_INTEGER), ], ) STRING_DATA_RECORD_FORMAT: HeaderOrDataRecordFormat = HeaderOrDataRecordFormat( "STRING_DATA_RECORD_FORMAT", [ F("string_data_id", 1, UNSIGNED_INTEGER), F( "string_data", lambda packet: packet.data["data_record_size"] - 1, STRING, ), ], ) BURST_AVERAGE_VERSION2_DATA_RECORD_FORMAT: HeaderOrDataRecordFormat = HeaderOrDataRecordFormat( "BURST_AVERAGE_VERSION2_DATA_RECORD_FORMAT", [ F("version", 1, UNSIGNED_INTEGER), F("offset_of_data", 1, UNSIGNED_INTEGER), F("serial_number", 4, UNSIGNED_INTEGER), F("configuration", 2, UNSIGNED_INTEGER), F("year", 1, UNSIGNED_INTEGER), F("month", 1, UNSIGNED_INTEGER), F("day", 1, UNSIGNED_INTEGER), F("hour", 1, UNSIGNED_INTEGER), F("minute", 1, UNSIGNED_INTEGER), F("seconds", 1, UNSIGNED_INTEGER), F("microsec100", 2, UNSIGNED_INTEGER), F( "speed_of_sound", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 10, ), F( "temperature", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, ), F( "pressure", 4, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 1000, ), F( "heading", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, ), F( "pitch", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, ), F( "roll", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, ), F("error", 2, UNSIGNED_INTEGER), F("status", 2, UNSIGNED_INTEGER), F("num_beams_and_coordinate_system_and_num_cells", 2, UNSIGNED_INTEGER), F( "cell_size", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 1000, ), F( "blanking", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 1000, ), F( "velocity_range", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 1000, ), F( "battery_voltage", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 10, ), F( "magnetometer_raw", 2, SIGNED_INTEGER, field_shape=[3], field_dimensions=[Dimension.PING_TIME, Dimension.XYZ], ), F( "accelerometer_raw_x_axis", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 16384 * 9.819, ), F( "accelerometer_raw_y_axis", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 16384 * 9.819, ), F( "accelerometer_raw_z_axis", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 16384 * 9.819, ), F( "ambiguity_velocity", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 10000, ), F("dataset_description", 2, UNSIGNED_INTEGER), F("transmit_energy", 2, UNSIGNED_INTEGER), F("velocity_scaling", 1, SIGNED_INTEGER), F("power_level", 1, SIGNED_INTEGER), F(None, 4, UNSIGNED_INTEGER), F( # used when burst "velocity_data_burst", 2, SIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_BURST, Dimension.BEAM, Dimension.RANGE_SAMPLE_BURST, ], field_unit_conversion=lambda packet, x: x * (10.0 ** packet.data["velocity_scaling"]), field_exists_predicate=lambda packet: packet.is_burst() and packet.data["velocity_data_included"], ), F( # used when average "velocity_data_average", 2, SIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_AVERAGE, Dimension.BEAM, Dimension.RANGE_SAMPLE_AVERAGE, ], field_unit_conversion=lambda packet, x: x * (10.0 ** packet.data["velocity_scaling"]), field_exists_predicate=lambda packet: packet.is_average() and packet.data["velocity_data_included"], ), F( # used when echosounder "velocity_data_echosounder", 2, SIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_ECHOSOUNDER, Dimension.BEAM, Dimension.RANGE_SAMPLE_ECHOSOUNDER, ], field_unit_conversion=lambda packet, x: x * (10.0 ** packet.data["velocity_scaling"]), field_exists_predicate=lambda packet: packet.is_echosounder() and packet.data["velocity_data_included"], ), F( "amplitude_data_burst", 1, UNSIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_BURST, Dimension.BEAM, Dimension.RANGE_SAMPLE_BURST, ], field_unit_conversion=lambda packet, x: x / 2, field_exists_predicate=lambda packet: packet.is_burst() and packet.data["amplitude_data_included"], ), F( "amplitude_data_average", 1, UNSIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_AVERAGE, Dimension.BEAM, Dimension.RANGE_SAMPLE_AVERAGE, ], field_unit_conversion=lambda packet, x: x / 2, field_exists_predicate=lambda packet: packet.is_average() and packet.data["amplitude_data_included"], ), F( "amplitude_data_echosounder", 1, UNSIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_ECHOSOUNDER, Dimension.BEAM, Dimension.RANGE_SAMPLE_ECHOSOUNDER, ], field_unit_conversion=lambda packet, x: x / 2, field_exists_predicate=lambda packet: packet.is_echosounder() and packet.data["amplitude_data_included"], ), F( "correlation_data_burst", 1, UNSIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_BURST, Dimension.BEAM, Dimension.RANGE_SAMPLE_BURST, ], field_exists_predicate=lambda packet: packet.is_burst() and packet.data["correlation_data_included"], ), F( "correlation_data_average", 1, UNSIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_AVERAGE, Dimension.BEAM, Dimension.RANGE_SAMPLE_AVERAGE, ], field_exists_predicate=lambda packet: packet.is_average() and packet.data["correlation_data_included"], ), F( "correlation_data_echosounder", 1, UNSIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_ECHOSOUNDER, Dimension.BEAM, Dimension.RANGE_SAMPLE_ECHOSOUNDER, ], field_exists_predicate=lambda packet: packet.is_echosounder() and packet.data["correlation_data_included"], ), ], ) BURST_AVERAGE_VERSION3_DATA_RECORD_FORMAT: HeaderOrDataRecordFormat = HeaderOrDataRecordFormat( "BURST_AVERAGE_VERSION3_DATA_RECORD_FORMAT", [ F("version", 1, UNSIGNED_INTEGER), F("offset_of_data", 1, UNSIGNED_INTEGER), F("configuration", 2, UNSIGNED_INTEGER), F("serial_number", 4, UNSIGNED_INTEGER), F("year", 1, UNSIGNED_INTEGER), F("month", 1, UNSIGNED_INTEGER), F("day", 1, UNSIGNED_INTEGER), F("hour", 1, UNSIGNED_INTEGER), F("minute", 1, UNSIGNED_INTEGER), F("seconds", 1, UNSIGNED_INTEGER), F("microsec100", 2, UNSIGNED_INTEGER), F( "speed_of_sound", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 10, ), F( "temperature", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, ), F( "pressure", 4, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 1000, ), F( "heading", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, ), F( "pitch", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, ), F( "roll", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, ), F("num_beams_and_coordinate_system_and_num_cells", 2, UNSIGNED_INTEGER), F( "cell_size", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 1000, ), # This field is listed to be in cm, but testing has shown that it is actually in mm. # Being in mm would be consistent with the "blanking" field units in all other formats. F( "blanking", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 1000, ), F("nominal_correlation", 1, UNSIGNED_INTEGER), F( "temperature_from_pressure_sensor", 1, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x * 5, ), F( "battery_voltage", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 10, ), F( "magnetometer_raw", 2, SIGNED_INTEGER, field_shape=[3], field_dimensions=[Dimension.PING_TIME, Dimension.XYZ], ), F( "accelerometer_raw_x_axis", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 16384 * 9.819, ), F( "accelerometer_raw_y_axis", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 16384 * 9.819, ), F( "accelerometer_raw_z_axis", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 16384 * 9.819, ), # Unit conversions for this field are done in Ad2cpDataPacket._postprocess # because the ambiguity velocity unit conversion requires the velocity_scaling field, # which is not known when this field is parsed F("ambiguity_velocity_or_echosounder_frequency", 2, UNSIGNED_INTEGER), F("dataset_description", 2, UNSIGNED_INTEGER), F("transmit_energy", 2, UNSIGNED_INTEGER), F("velocity_scaling", 1, SIGNED_INTEGER), F("power_level", 1, SIGNED_INTEGER), F( "magnetometer_temperature", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x * 1000, ), F( "real_time_clock_temperature", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, ), F("error", 2, UNSIGNED_INTEGER), F("status0", 2, UNSIGNED_INTEGER), F("status", 4, UNSIGNED_INTEGER), F("ensemble_counter", 4, UNSIGNED_INTEGER), F( "velocity_data_burst", 2, SIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_BURST, Dimension.BEAM, Dimension.RANGE_SAMPLE_BURST, ], field_unit_conversion=lambda packet, x: x * (10.0 ** packet.data["velocity_scaling"]), field_exists_predicate=lambda packet: packet.is_burst() and packet.data["velocity_data_included"], ), F( "velocity_data_average", 2, SIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_AVERAGE, Dimension.BEAM, Dimension.RANGE_SAMPLE_AVERAGE, ], field_unit_conversion=lambda packet, x: x * (10.0 ** packet.data["velocity_scaling"]), field_exists_predicate=lambda packet: packet.is_average() and packet.data["velocity_data_included"], ), F( "velocity_data_echosounder", 2, SIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_ECHOSOUNDER, Dimension.BEAM, Dimension.RANGE_SAMPLE_ECHOSOUNDER, ], field_unit_conversion=lambda packet, x: x * (10.0 ** packet.data["velocity_scaling"]), field_exists_predicate=lambda packet: packet.is_echosounder() and packet.data["velocity_data_included"], ), F( "amplitude_data_burst", 1, UNSIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_BURST, Dimension.BEAM, Dimension.RANGE_SAMPLE_BURST, ], field_unit_conversion=lambda packet, x: x / 2, field_exists_predicate=lambda packet: packet.is_burst() and packet.data["amplitude_data_included"], ), F( "amplitude_data_average", 1, UNSIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_AVERAGE, Dimension.BEAM, Dimension.RANGE_SAMPLE_AVERAGE, ], field_unit_conversion=lambda packet, x: x / 2, field_exists_predicate=lambda packet: packet.is_average() and packet.data["amplitude_data_included"], ), F( "amplitude_data_echosounder", 1, UNSIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_ECHOSOUNDER, Dimension.BEAM, Dimension.RANGE_SAMPLE_ECHOSOUNDER, ], field_unit_conversion=lambda packet, x: x / 2, field_exists_predicate=lambda packet: packet.is_echosounder() and packet.data["amplitude_data_included"], ), F( "correlation_data_burst", 1, UNSIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_BURST, Dimension.BEAM, Dimension.RANGE_SAMPLE_BURST, ], field_exists_predicate=lambda packet: packet.is_burst() and packet.data["correlation_data_included"], ), F( "correlation_data_average", 1, UNSIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_AVERAGE, Dimension.BEAM, Dimension.RANGE_SAMPLE_AVERAGE, ], field_exists_predicate=lambda packet: packet.is_average() and packet.data["correlation_data_included"], ), F( "correlation_data_echosounder", 1, UNSIGNED_INTEGER, field_shape=lambda packet: [ packet.data.get("num_beams", 0), packet.data.get("num_cells", 0), ], field_dimensions=[ Dimension.PING_TIME_ECHOSOUNDER, Dimension.BEAM, Dimension.RANGE_SAMPLE_ECHOSOUNDER, ], field_exists_predicate=lambda packet: packet.is_echosounder() and packet.data["correlation_data_included"], ), F( "altimeter_distance", 4, FLOAT, field_exists_predicate=lambda packet: packet.data["altimeter_data_included"], ), F( "altimeter_quality", 2, UNSIGNED_INTEGER, field_exists_predicate=lambda packet: packet.data["altimeter_data_included"], ), F( "ast_distance", 4, FLOAT, field_exists_predicate=lambda packet: packet.data["ast_data_included"], ), F( "ast_quality", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, field_exists_predicate=lambda packet: packet.data["ast_data_included"], ), F( "ast_offset_100us", 2, SIGNED_INTEGER, field_exists_predicate=lambda packet: packet.data["ast_data_included"], ), F( "ast_pressure", 4, FLOAT, field_exists_predicate=lambda packet: packet.data["ast_data_included"], ), F( "altimeter_spare", 1, RAW_BYTES, field_shape=[8], field_exists_predicate=lambda packet: packet.data["ast_data_included"], ), F( "altimeter_raw_data_num_samples", # The field size of this field is technically specified as number of samples * 2, # but seeing as the field is called "num samples," and the field which is supposed # to contain the samples is specified as having a constant size of 2, these fields # sizes were likely incorrectly swapped. 2, UNSIGNED_INTEGER, field_exists_predicate=lambda packet: packet.data["altimeter_raw_data_included"], ), F( "altimeter_raw_data_sample_distance", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 10000, field_exists_predicate=lambda packet: packet.data["altimeter_raw_data_included"], ), F( "altimeter_raw_data_samples", 2, SIGNED_FRACTION, field_shape=lambda packet: [packet.data["altimeter_raw_data_num_samples"]], field_dimensions=[Dimension.PING_TIME, Dimension.NUM_ALTIMETER_SAMPLES], field_exists_predicate=lambda packet: packet.data["altimeter_raw_data_included"], ), F( "echosounder_data", 2, # Although the specification says that this should be an unsigned integer, # testing has shown that it should be a signed integer SIGNED_INTEGER, field_shape=lambda packet: [packet.data.get("num_echosounder_cells", 0)], field_dimensions=[ Dimension.PING_TIME_ECHOSOUNDER, Dimension.RANGE_SAMPLE_ECHOSOUNDER, ], field_unit_conversion=lambda packet, x: x / 100, field_exists_predicate=lambda packet: packet.data["echosounder_data_included"], ), F( "ahrs_rotation_matrix", 4, FLOAT, field_shape=[9], field_dimensions=[Dimension.PING_TIME, Dimension.MIJ], field_exists_predicate=lambda packet: packet.data["ahrs_data_included"], ), F( "ahrs_quaternions", 4, FLOAT, field_shape=[4], field_dimensions=[Dimension.PING_TIME, Dimension.WXYZ], field_exists_predicate=lambda packet: packet.data["ahrs_data_included"], ), F( "ahrs_gyro", 4, FLOAT, field_shape=[3], field_dimensions=[Dimension.PING_TIME, Dimension.XYZ], field_exists_predicate=lambda packet: packet.data["ahrs_data_included"], ), F( "percentage_good_data", 1, UNSIGNED_INTEGER, field_shape=lambda packet: [packet.data.get("num_cells", 0)], field_dimensions=lambda data_record_type: [ Dimension.PING_TIME, RANGE_SAMPLES[data_record_type], ], field_exists_predicate=lambda packet: packet.data["percentage_good_data_included"], ), # Only the pitch field is labeled as included when the "std dev data included" # bit is set, but this is likely a mistake F( "std_dev_pitch", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, field_exists_predicate=lambda packet: packet.data["std_dev_data_included"], ), F( "std_dev_roll", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, field_exists_predicate=lambda packet: packet.data["std_dev_data_included"], ), F( "std_dev_heading", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, field_exists_predicate=lambda packet: packet.data["std_dev_data_included"], ), F( "std_dev_pressure", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, field_exists_predicate=lambda packet: packet.data["std_dev_data_included"], ), F( None, 24, RAW_BYTES, field_exists_predicate=lambda packet: packet.data["std_dev_data_included"], ), ], ) BOTTOM_TRACK_DATA_RECORD_FORMAT: HeaderOrDataRecordFormat = HeaderOrDataRecordFormat( "BOTTOM_TRACK_DATA_RECORD_FORMAT", [ F("version", 1, UNSIGNED_INTEGER), F("offset_of_data", 1, UNSIGNED_INTEGER), F("configuration", 2, UNSIGNED_INTEGER), F("serial_number", 4, UNSIGNED_INTEGER), F("year", 1, UNSIGNED_INTEGER), F("month", 1, UNSIGNED_INTEGER), F("day", 1, UNSIGNED_INTEGER), F("hour", 1, UNSIGNED_INTEGER), F("minute", 1, UNSIGNED_INTEGER), F("seconds", 1, UNSIGNED_INTEGER), F("microsec100", 2, UNSIGNED_INTEGER), F( "speed_of_sound", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 10, ), F( "temperature", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, ), F( "pressure", 4, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 1000, ), F( "heading", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, ), F( "pitch", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, ), F( "roll", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, ), F("num_beams_and_coordinate_system_and_num_cells", 2, UNSIGNED_INTEGER), F( "cell_size", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 1000, ), F( "blanking", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 1000, ), F("nominal_correlation", 1, UNSIGNED_INTEGER), F(None, 1, RAW_BYTES), F( "battery_voltage", 2, UNSIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 10, ), F( "magnetometer_raw", 2, SIGNED_INTEGER, field_shape=[3], field_dimensions=[Dimension.PING_TIME, Dimension.XYZ], ), F( "accelerometer_raw_x_axis", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 16384 * 9.819, ), F( "accelerometer_raw_y_axis", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 16384 * 9.819, ), F( "accelerometer_raw_z_axis", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 16384 * 9.819, ), # Unit conversions for this field are done in Ad2cpDataPacket._postprocess # because the ambiguity velocity unit conversion requires the velocity_scaling field, # which is not known when this field is parsed F("ambiguity_velocity", 4, UNSIGNED_INTEGER), F("dataset_description", 2, UNSIGNED_INTEGER), F("transmit_energy", 2, UNSIGNED_INTEGER), F("velocity_scaling", 1, SIGNED_INTEGER), F("power_level", 1, SIGNED_INTEGER), F( "magnetometer_temperature", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x * 1000, ), F( "real_time_clock_temperature", 2, SIGNED_INTEGER, field_unit_conversion=lambda packet, x: x / 100, ), F("error", 4, UNSIGNED_INTEGER), F("status", 4, UNSIGNED_INTEGER), F("ensemble_counter", 4, UNSIGNED_INTEGER), F( "velocity_data", 4, SIGNED_INTEGER, field_shape=lambda packet: [packet.data.get("num_beams", 0)], field_dimensions=[Dimension.PING_TIME, Dimension.BEAM], field_unit_conversion=lambda packet, x: x * (10.0 ** packet.data["velocity_scaling"]), field_exists_predicate=lambda packet: packet.data["velocity_data_included"], ), F( "distance_data", 4, SIGNED_INTEGER, field_shape=lambda packet: [packet.data.get("num_beams", 0)], field_dimensions=[Dimension.PING_TIME, Dimension.BEAM], field_unit_conversion=lambda packet, x: x / 1000, field_exists_predicate=lambda packet: packet.data["distance_data_included"], ), F( "figure_of_merit_data", 2, UNSIGNED_INTEGER, field_shape=lambda packet: [packet.data.get("num_beams", 0)], field_dimensions=[Dimension.PING_TIME, Dimension.BEAM], field_exists_predicate=lambda packet: packet.data["figure_of_merit_data_included"], ), ], ) ECHOSOUNDER_RAW_DATA_RECORD_FORMAT: HeaderOrDataRecordFormat = HeaderOrDataRecordFormat( "ECHOSOUNDER_RAW_DATA_RECORD_FORMAT", [ F("version", 1, UNSIGNED_INTEGER), F("offset_of_data", 1, UNSIGNED_INTEGER), F("year", 1, UNSIGNED_INTEGER), F("month", 1, UNSIGNED_INTEGER), F("day", 1, UNSIGNED_INTEGER), F("hour", 1, UNSIGNED_INTEGER), F("minute", 1, UNSIGNED_INTEGER), F("seconds", 1, UNSIGNED_INTEGER), F("microsec100", 2, UNSIGNED_INTEGER), F("error", 2, UNSIGNED_INTEGER), F("status", 4, UNSIGNED_INTEGER), F("serial_number", 4, UNSIGNED_INTEGER), F("num_complex_samples", 4, UNSIGNED_INTEGER), F("ind_start_samples", 4, UNSIGNED_INTEGER), F("freq_raw_sample_data", 4, FLOAT), F(None, 208, RAW_BYTES), F( "echosounder_raw_samples", 4, SIGNED_FRACTION, field_shape=lambda packet: [ packet.data["num_complex_samples"], 2, ], field_dimensions=[ Dimension.PING_TIME_ECHOSOUNDER_RAW, Dimension.SAMPLE, ], field_exists_predicate=lambda packet: packet.is_echosounder_raw(), ), # These next 2 fields are included so that the dimensions for these fields # can be determined based on the field name. # They are actually constructed in _postprocess. F( "echosounder_raw_samples_i", 0, RAW_BYTES, field_dimensions=[ Dimension.PING_TIME_ECHOSOUNDER_RAW, Dimension.SAMPLE, ], field_exists_predicate=lambda packet: False, ), F( "echosounder_raw_samples_q", 0, RAW_BYTES, field_dimensions=[ Dimension.PING_TIME_ECHOSOUNDER_RAW, Dimension.SAMPLE, ], field_exists_predicate=lambda packet: False, ), F( "echosounder_raw_transmit_samples", 4, SIGNED_FRACTION, field_shape=lambda packet: [ packet.data["num_complex_samples"], 2, ], field_dimensions=[ Dimension.PING_TIME_ECHOSOUNDER_RAW_TRANSMIT, Dimension.SAMPLE_TRANSMIT, ], field_exists_predicate=lambda packet: packet.is_echosounder_raw_transmit(), ), # These next 2 fields are included so that the dimensions for these fields # can be determined based on the field name. # They are actually constructed in _postprocess. F( "echosounder_raw_transmit_samples_i", 0, RAW_BYTES, field_dimensions=[ Dimension.PING_TIME_ECHOSOUNDER_RAW_TRANSMIT, Dimension.SAMPLE_TRANSMIT, ], field_exists_predicate=lambda packet: False, ), F( "echosounder_raw_transmit_samples_q", 0, RAW_BYTES, field_dimensions=[ Dimension.PING_TIME_ECHOSOUNDER_RAW_TRANSMIT, Dimension.SAMPLE_TRANSMIT, ], field_exists_predicate=lambda packet: False, ), ], ) DATA_RECORD_FORMATS = { DataRecordType.BURST_VERSION2: BURST_AVERAGE_VERSION2_DATA_RECORD_FORMAT, DataRecordType.BURST_VERSION3: BURST_AVERAGE_VERSION3_DATA_RECORD_FORMAT, DataRecordType.AVERAGE_VERSION2: BURST_AVERAGE_VERSION2_DATA_RECORD_FORMAT, DataRecordType.AVERAGE_VERSION3: BURST_AVERAGE_VERSION3_DATA_RECORD_FORMAT, DataRecordType.BOTTOM_TRACK: BOTTOM_TRACK_DATA_RECORD_FORMAT, DataRecordType.ECHOSOUNDER: BURST_AVERAGE_VERSION3_DATA_RECORD_FORMAT, DataRecordType.ECHOSOUNDER_RAW: ECHOSOUNDER_RAW_DATA_RECORD_FORMAT, DataRecordType.ECHOSOUNDER_RAW_TRANSMIT: ECHOSOUNDER_RAW_DATA_RECORD_FORMAT, DataRecordType.STRING: STRING_DATA_RECORD_FORMAT, }
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,775
OSOceanAcoustics/echopype
refs/heads/main
/echopype/echodata/combine.py
import itertools import re from collections import ChainMap from pathlib import Path from typing import Any, Dict, List, Literal, Optional, Tuple, Union from warnings import warn import fsspec import numpy as np import pandas as pd import xarray as xr from datatree import DataTree from ..utils.io import validate_output_path from ..utils.log import _init_logger from ..utils.prov import echopype_prov_attrs from .echodata import EchoData logger = _init_logger(__name__) POSSIBLE_TIME_DIMS = {"time1", "time2", "time3", "ping_time"} APPEND_DIMS = {"filenames"}.union(POSSIBLE_TIME_DIMS) DATE_CREATED_ATTR = "date_created" CONVERSION_TIME_ATTR = "conversion_time" ED_GROUP = "echodata_group" ED_FILENAME = "echodata_filename" FILENAMES = "filenames" def check_zarr_path( zarr_path: Union[str, Path], storage_options: Dict[str, Any] = {}, overwrite: bool = False ) -> str: """ Checks that the zarr path provided to ``combine`` is valid. Parameters ---------- zarr_path: str or Path The full save path to the final combined zarr store storage_options: dict Any additional parameters for the storage backend (ignored for local paths) overwrite: bool If True, will overwrite the zarr store specified by ``zarr_path`` if it already exists, otherwise an error will be returned if the file already exists. Returns ------- str The validated zarr path Raises ------ ValueError If the provided zarr path does not point to a zarr file RuntimeError If ``zarr_path`` already exists and ``overwrite=False`` """ if zarr_path is not None: # ensure that zarr_path is a string or Path object, throw an error otherwise if not isinstance(zarr_path, (str, Path)): raise TypeError("The provided zarr_path input must be of type string or pathlib.Path!") # check that the appropriate suffix was provided if not (Path(zarr_path).suffix == ".zarr"): raise ValueError("The provided zarr_path input must have a '.zarr' suffix!") # set default source_file name (will be used only if zarr_path is None) source_file = "combined_echodata.zarr" validated_path = validate_output_path( source_file=source_file, engine="zarr", output_storage_options=storage_options, save_path=zarr_path, ) # convert created validated_path to a string if it is in other formats, # since fsspec only accepts strings if isinstance(validated_path, Path): validated_path = str(validated_path.absolute()) # check if validated_path already exists fs = fsspec.get_mapper(validated_path, **storage_options).fs # get file system exists = True if fs.exists(validated_path) else False if exists and not overwrite: raise RuntimeError( f"{validated_path} already exists, please provide a " "different path or set overwrite=True." ) elif exists and overwrite: logger.info(f"overwriting {validated_path}") # remove zarr file fs.rm(validated_path, recursive=True) return validated_path def _check_channel_selection_form( channel_selection: Optional[Union[List, Dict[str, list]]] = None ) -> None: """ Ensures that the provided user input ``channel_selection`` is in an acceptable form. Parameters ---------- channel_selection: list of str or dict, optional Specifies what channels should be selected for an ``EchoData`` group with a ``channel`` dimension (before combination). """ # check that channel selection is None, a list, or a dict if not isinstance(channel_selection, (type(None), list, dict)): raise TypeError("The input channel_selection does not have an acceptable type!") if isinstance(channel_selection, list): # make sure each element is a string are_elem_str = [isinstance(elem, str) for elem in channel_selection] if not all(are_elem_str): raise TypeError("Each element of channel_selection must be a string!") if isinstance(channel_selection, dict): # make sure all keys are strings are_keys_str = [isinstance(elem, str) for elem in channel_selection.keys()] if not all(are_keys_str): raise TypeError("Each key of channel_selection must be a string!") # make sure all keys are of the form Sonar/Beam_group using regular expression are_keys_right_form = [ True if re.match("Sonar/Beam_group(\d{1})", elem) else False # noqa for elem in channel_selection.keys() ] if not all(are_keys_right_form): raise TypeError( "Each key of channel_selection can only be a beam group path of " "the form Sonar/Beam_group!" ) # make sure all values are a list are_vals_list = [isinstance(elem, list) for elem in channel_selection.values()] if not all(are_vals_list): raise TypeError("Each value of channel_selection must be a list!") # make sure all values are a list of strings are_vals_list_str = [set(map(type, elem)) == {str} for elem in channel_selection] if not all(are_vals_list_str): raise TypeError("Each value of channel_selection must be a list of strings!") def check_eds(echodata_list: List[EchoData]) -> Tuple[str, List[str]]: """ Ensures that the input list of ``EchoData`` objects for ``combine_echodata`` is in the correct form and all necessary items exist. Parameters ---------- echodata_list: list of EchoData object The list of `EchoData` objects to be combined. Returns ------- sonar_model : str The sonar model used for all values in ``echodata_list`` echodata_filenames : list of str The source files names for all values in ``echodata_list`` Raises ------ TypeError If a list of ``EchoData`` objects are not provided ValueError If any ``EchoData`` object's ``sonar_model`` is ``None`` ValueError If and ``EchoData`` object does not have a file path ValueError If the provided ``EchoData`` objects have the same filenames """ # make sure that the input is a list of EchoData objects if not isinstance(echodata_list, list) and all( [isinstance(ed, EchoData) for ed in echodata_list] ): raise TypeError("The input, eds, must be a list of EchoData objects!") # get the sonar model for the combined object if echodata_list[0].sonar_model is None: raise ValueError("all EchoData objects must have non-None sonar_model values") else: sonar_model = echodata_list[0].sonar_model echodata_filenames = [] for ed in echodata_list: # check sonar model if ed.sonar_model is None: raise ValueError("all EchoData objects must have non-None sonar_model values") elif ed.sonar_model != sonar_model: raise ValueError("all EchoData objects must have the same sonar_model value") # check for file names and store them if ed.source_file is not None: filepath = ed.source_file elif ed.converted_raw_path is not None: filepath = ed.converted_raw_path else: # defaulting to none, must be from memory filepath = None # set default filename to internal memory filename = "internal-memory" if filepath is not None: filename = Path(filepath).name if filename in echodata_filenames: raise ValueError("EchoData objects have conflicting filenames") echodata_filenames.append(filename) return sonar_model, echodata_filenames def _check_channel_consistency( all_chan_list: List, ed_group: str, channel_selection: Optional[List[str]] = None ) -> None: """ If ``channel_selection = None``, checks that each element in ``all_chan_list`` are the same, else makes sure that each element in ``all_chan_list`` contains all channel names in ``channel_selection``. Parameters ---------- all_chan_list: list of list A list whose elements correspond to the Datasets to be combined with their values set as a list of the channel dimension names in the Dataset ed_group: str The EchoData group path that produced ``all_chan_list`` channel_selection: list of str, optional A list of channel names, which should be a subset of each element in ``all_chan_list`` Raises ------ RuntimeError If ``channel_selection=None`` and all ``channel`` dimensions are not the same across all Datasets. NotImplementedError If ``channel_selection`` is a list and the listed channels are not contained in the ``EchoData`` group for all Datasets and need to be created and padded with NaN. This "expansion" type of combination has not been implemented. """ if channel_selection is None: # sort each element in list, so correct comparison can be made all_chan_list = list(map(sorted, all_chan_list)) # determine if the channels are the same across all Datasets all_chans_equal = [all_chan_list[0]] * len(all_chan_list) == all_chan_list if not all_chans_equal: # obtain all unique channel names unique_channels = set(itertools.chain.from_iterable(all_chan_list)) # raise an error if we have varying channel lengths raise RuntimeError( f"For the EchoData group {ed_group} the channels: {unique_channels} are " f"not found in all EchoData objects being combined. Select which " f"channels should be included in the combination using the keyword argument " f"channel_selection in combine_echodata." ) else: # make channel_selection a set, so it is easier to use channel_selection = set(channel_selection) # TODO: if we will allow for expansion, then the below code should be # replaced with a code section that makes sure the selected channels # appear at least once in one of the other Datasets # determine if channel selection is in each element of all_chan_list eds_num_chan = [ channel_selection.intersection(set(ed_chans)) == channel_selection for ed_chans in all_chan_list ] if not all(eds_num_chan): # raise a not implemented error if expansion (i.e. padding is necessary) raise NotImplementedError( f"For the EchoData group {ed_group}, some EchoData objects do " f"not contain the selected channels. This type of combine is " f"not currently implemented." ) def _create_channel_selection_dict( sonar_model: str, has_chan_dim: Dict[str, bool], user_channel_selection: Optional[Union[List, Dict[str, list]]] = None, ) -> Dict[str, Optional[list]]: """ Constructs the dictionary ``channel_selection_dict``, which specifies the ``channel`` dimension names that should be selected for each ``EchoData`` group. If a group does not have a ``channel`` dimension the dictionary value will be set to ``None`` Parameters ---------- sonar_model: str The name of the sonar model corresponding to ``has_chan_dim`` has_chan_dim: dict A dictionary created using an ``EchoData`` object whose keys are the ``EchoData`` groups and whose values specify if that particular group has a ``channel`` dimension user_channel_selection: list or dict, optional A user provided input that will be used to construct the values of ``channel_selection_dict`` (see below for further details) Returns ------- channel_selection_dict : dict A dictionary with the same keys as ``has_chan_dim`` and values determined by ``sonar_model`` and ``user_channel_selection`` as follows: - If ``user_channel_selection=None``, then the values of the dictionary will be set to ``None`` - If ``user_channel_selection`` is a list, then all keys corresponding to an ``EchoData`` group with a ``channel`` dimension will have their values set to the provided list and all other groups will be set to ``None`` - If ``user_channel_selection`` is a dictionary, then all keys corresponding to an ``EchoData`` group without a ``channel`` dimension will have their values set as ``None`` and the other group's values will be set as follows: - If ``sonar_model`` is not EK80-like then all values will be set to the union of the values of ``user_channel_selection`` - If ``sonar_model`` is EK80-like then the groups ``Sonar, Platform, Vendor_specific`` will be set to the union of the values of ``user_channel_selection`` and the rest of the groups will be set to the same value in ``user_channel_selection`` with the same key Notes ----- See ``tests/echodata/test_echodata_combine.py::test_create_channel_selection_dict`` for example outputs from this function. """ # base case where the user did not provide selected channels (will be used downstream) if user_channel_selection is None: return {grp: None for grp in has_chan_dim.keys()} # obtain the union of all channels for each beam group if isinstance(user_channel_selection, list): union_beam_chans = user_channel_selection[:] else: union_beam_chans = list(set(itertools.chain.from_iterable(user_channel_selection.values()))) # make channel_selection dictionary where the keys are the EchoData groups and the # values are based on the user provided input user_channel_selection channel_selection_dict = dict() for ed_group, has_chan in has_chan_dim.items(): # if there are no channel dimensions in the group, set the value to None if has_chan: if ( (not isinstance(user_channel_selection, list)) and (sonar_model in ["EK80", "ES80", "EA640"]) and (ed_group not in ["Sonar", "Platform", "Vendor_specific"]) ): # set value to the user provided input with the same key channel_selection_dict[ed_group] = user_channel_selection[ed_group] else: # set value to the union of the values of user_channel_selection channel_selection_dict[ed_group] = union_beam_chans # sort channel names to produce consistent output (since we may be using sets) channel_selection_dict[ed_group].sort() else: channel_selection_dict[ed_group] = None return channel_selection_dict def _check_echodata_channels( echodata_list: List[EchoData], user_channel_selection: Optional[Union[List, Dict[str, list]]] = None, ) -> Dict[str, Optional[List[str]]]: """ Coordinates the routines that check to make sure each ``EchoData`` group with a ``channel`` dimension has consistent channels for all elements in ``echodata_list``, taking into account the input ``user_channel_selection``. Parameters ---------- echodata_list: list of EchoData object The list of ``EchoData`` objects to be combined user_channel_selection: list or dict, optional A user provided input that will be used to specify which channels will be selected for each ``EchoData`` group Returns ------- dict A dictionary with keys corresponding to the ``EchoData`` groups and values specifying the channels that should be selected within that group. For more information on this dictionary see the function ``_create_channel_selection_dict``. Raises ------ RuntimeError If any ``EchoData`` group has a ``channel`` dimension value with a duplicate value. Notes ----- For further information on what is deemed consistent, please see the function ``_check_channel_consistency``. """ # determine if the EchoData group contains a channel dimension has_chan_dim = { grp: "channel" in echodata_list[0][grp].dims for grp in echodata_list[0].group_paths } # create dictionary specifying the channels that should be selected for each group channel_selection = _create_channel_selection_dict( echodata_list[0].sonar_model, has_chan_dim, user_channel_selection ) for ed_group in echodata_list[0].group_paths: if "channel" in echodata_list[0][ed_group].dims: # get each EchoData's channels as a list of list all_chan_list = [list(ed[ed_group].channel.values) for ed in echodata_list] # make sure each EchoData does not have repeating channels all_chan_unique = [len(set(ed_chans)) == len(ed_chans) for ed_chans in all_chan_list] if not all(all_chan_unique): # get indices of EchoData objects with repeating channel names false_ind = [ind for ind, x in enumerate(all_chan_unique) if not x] # get files that produced the EchoData objects with repeated channels files_w_rep_chan = [ echodata_list[ind]["Provenance"].source_filenames.values[0] for ind in false_ind ] raise RuntimeError( f"The EchoData objects produced by the following files " f"have a channel dimension with repeating values, " f"combine cannot be used: {files_w_rep_chan}" ) # perform a consistency check for the channel dims across all Datasets _check_channel_consistency(all_chan_list, ed_group, channel_selection[ed_group]) return channel_selection def _check_ascending_ds_times(ds_list: List[xr.Dataset], ed_group: str) -> None: """ A minimal check that the first time value of each Dataset is less than the first time value of the subsequent Dataset. If each first time value is NaT, then this check is skipped. Parameters ---------- ds_list: list of xr.Dataset List of Datasets to be combined ed_group: str The name of the ``EchoData`` group being combined Returns ------- None Raises ------ RuntimeError If the timeX dimension is not in ascending order for the specified echodata group """ # get all time dimensions of the input Datasets ed_time_dim = set(ds_list[0].dims).intersection(POSSIBLE_TIME_DIMS) for time in ed_time_dim: # gather the first time of each Dataset first_times = [] for ds in ds_list: times = ds[time].values if isinstance(times, np.ndarray): # store first time if we have an array first_times.append(times[0]) else: # store first time if we have a single value first_times.append(times) first_times = np.array(first_times) # skip check if all first times are NaT if not np.isnan(first_times).all(): is_descending = (np.diff(first_times) < np.timedelta64(0, "ns")).any() if is_descending: raise RuntimeError( f"The coordinate {time} is not in ascending order for " f"group {ed_group}, combine cannot be used!" ) def _check_no_append_vendor_params( ds_list: List[xr.Dataset], ed_group: Literal["Vendor_specific"], ds_append_dims: set ) -> None: """ Check for identical params for all inputs without an appending dimension in Vendor specific group Parameters ---------- ds_list: list of xr.Dataset List of Datasets to be combined ed_group: "Vendor_specific" The name of the ``EchoData`` group being combined, this only works for "Vendor_specific" group. ds_append_dims: set A set of datasets append dimensions Returns ------- None Raises ------ ValueError If ``ed_group`` is not ``Vendor_specific``. RuntimeError If non identical filter parameters is found. """ if ed_group != "Vendor_specific": raise ValueError("Group must be `Vendor_specific`!") if len(ds_append_dims) > 0: # If there's a dataset appending dimension, drop for comparison # of the other values... everything else should be identical ds_list = [ds.drop_dims(ds_append_dims) for ds in ds_list] it = iter(ds_list) # Init as identical, must stay True. is_identical = True dataset = next(it) for next_dataset in it: is_identical = dataset.identical(next_dataset) if not is_identical: raise RuntimeError( f"Non identical filter parameters in {ed_group} group. " "Objects cannot be merged!" ) dataset = next_dataset def _merge_attributes(attributes: List[Dict[str, str]]) -> Dict[str, str]: """ Merge a list of attributes dictionary Parameters ---------- attributes : list of dict List of attributes dictionary E.g. [{'attr1': 'val1'}, {'attr2': 'val2'}, ...] Returns ------- dict The merged attribute dictionary """ merged_dict = {} for attribute in attributes: for key, value in attribute.items(): if key not in merged_dict: # if current key is not in merged attribute, # then save the value for that key merged_dict[key] = value elif merged_dict[key] == "": # if current key is already in merged attribute, # check if the value of that key is empty, # in this case overwrite the value with current value merged_dict[key] = value # By default the rest of the behavior # will keep the first non-empty value it sees # NOTE: @lsetiawan (6/2/2023) - Comment this out for now until # attributes are fully evaluated by @leewujung and @emiliom # if value == "" and key not in merged_dict: # # checks if current attr value is empty, # # and doesn't exist in merged attribute, # # saving the first non empty value only # merged_dict[key] = value # elif value != "": # # if current attr value is not empty, # # then overwrite the merged attribute, # # keeping attribute from latest value # merged_dict[key] = value return merged_dict def _capture_prov_attrs( attrs_dict: Dict[str, List[Dict[str, str]]], echodata_filenames: List[str], sonar_model: str ) -> xr.Dataset: """ Capture and create provenance dataset, from the combined attribute values. Parameters ---------- attrs_dict : dict of list Dictionary of attributes for each of the group. E.g. {'Group': [{'attr1': 'val1'}, {'attr2': 'val2'}, ...]} echodata_filenames : list of str The filenames of the echodata objects sonar_model : str The sonar model Returns ------- xr.Dataset The provenance dataset for all attribute values from the list of echodata objects that are combined. """ ds_list = [] for group, attributes in attrs_dict.items(): df = pd.DataFrame.from_records(attributes) df.loc[:, ED_FILENAME] = echodata_filenames df = df.set_index(ED_FILENAME) group_ds = df.to_xarray() for _, var in group_ds.data_vars.items(): var.attrs.update({ED_GROUP: group}) ds_list.append(group_ds) prov_ds = xr.merge(ds_list) # Set these provenance as string prov_ds = prov_ds.fillna("").astype(str) prov_ds[ED_FILENAME] = prov_ds[ED_FILENAME].astype(str) return prov_ds def _get_prov_attrs( ds: xr.Dataset, is_combined: bool = True ) -> Optional[Dict[str, List[Dict[str, str]]]]: """ Get the provenance attributes from the dataset. This function is meant to be used on an already combined dataset. Parameters ---------- ds : xr.Dataset The Provenance group dataset to get attributes from is_combined: bool The flag to indicate if it's combined Returns ------- Dict[str, List[Dict[str, str]]] The provenance attributes """ if is_combined: attrs_dict = {} for k, v in ds.data_vars.items(): # Go through each data variable and extract the attribute values # based on the echodata group as stored in the variable attribute if ED_GROUP in v.attrs: ed_group = v.attrs[ED_GROUP] if ed_group not in attrs_dict: attrs_dict[ed_group] = [] # Store the values as a list of dictionary for each group attrs_dict[ed_group].append([{k: i} for i in v.values]) # Merge the attributes for each group so it matches the # attributes dict for later merging return { ed_group: [ dict(ChainMap(*v)) for _, v in pd.DataFrame.from_dict(attrs).to_dict(orient="list").items() ] for ed_group, attrs in attrs_dict.items() } return None def _combine( sonar_model: str, eds: List[EchoData] = [], echodata_filenames: List[str] = [], ed_group_chan_sel: Dict[str, Optional[List[str]]] = {}, ) -> Dict[str, xr.Dataset]: """ Combines the echodata objects and export to a dictionary tree. Parameters ---------- sonar_model : str The sonar model used for all elements in ``eds`` eds: list of EchoData object The list of ``EchoData`` objects to be combined echodata_filenames : list of str The filenames of the echodata objects ed_group_chan_sel: dict A dictionary with keys corresponding to the ``EchoData`` groups and values specify what channels should be selected within that group. If a value is ``None``, then a subset of channels should not be selected. Returns ------- dict of xr.Dataset The dictionary tree containing the xarray dataset for each of the combined group """ all_group_paths = dict.fromkeys( itertools.chain.from_iterable([list(ed.group_paths) for ed in eds]) ).keys() # For dealing with attributes attrs_dict = {} # Check if input data are combined datasets # Create combined mapping for later use combined_mapping = [] for idx, ed in enumerate(eds): is_combined = ed["Provenance"].attrs.get("is_combined", False) combined_mapping.append( { "is_combined": is_combined, "attrs_dict": _get_prov_attrs(ed["Provenance"], is_combined), "echodata_filename": [str(s) for s in ed["Provenance"][ED_FILENAME].values] if is_combined else [echodata_filenames[idx]], } ) # Get single boolean value to see if there's any combined files any_combined = any(d["is_combined"] for d in combined_mapping) if any_combined: # Fetches the true echodata filenames if there are any combined files echodata_filenames = list( itertools.chain.from_iterable([d[ED_FILENAME] for d in combined_mapping]) ) # Create Echodata tree dict tree_dict = {} for ed_group in all_group_paths: # collect the group Dataset from all eds that have their channels unselected all_chan_ds_list = [ed[ed_group] for ed in eds] # select only the appropriate channels from each Dataset ds_list = [ ds.sel(channel=ed_group_chan_sel[ed_group]) if ed_group_chan_sel[ed_group] is not None else ds for ds in all_chan_ds_list ] if ds_list: if not any_combined: # Get all of the keys and attributes # for regular non combined echodata object ds_attrs = [ds.attrs for ds in ds_list] else: # If there are any combined files, # iterate through from mapping above ds_attrs = [] for idx, ds in enumerate(ds_list): # Retrieve the echodata attrs dict # parsed from provenance group above ed_attrs_dict = combined_mapping[idx]["attrs_dict"] if ed_attrs_dict is not None: # Set attributes to the appropriate group # from echodata attrs provenance, # set default empty dict for missing group attrs = ed_attrs_dict.get(ed_group, {}) else: # This is for non combined echodata object attrs = [ds.attrs] ds_attrs += attrs # Attribute holding attrs_dict[ed_group] = ds_attrs # Checks for ascending time in dataset list _check_ascending_ds_times(ds_list, ed_group) # get all dimensions in ds that are append dimensions ds_append_dims = set(ds_list[0].dims).intersection(APPEND_DIMS) # Checks for filter parameters for "Vendor_specific" ONLY if ed_group == "Vendor_specific": _check_no_append_vendor_params(ds_list, ed_group, ds_append_dims) if len(ds_append_dims) == 0: combined_ds = ds_list[0] else: combined_ds = xr.Dataset() for dim in ds_append_dims: drop_dims = [c_dim for c_dim in ds_append_dims if c_dim != dim] sub_ds = xr.concat( [ds.drop_dims(drop_dims) for ds in ds_list], dim=dim, coords="minimal", data_vars="minimal", compat="no_conflicts", ) combined_ds = combined_ds.assign(sub_ds.variables) # Modify default attrs if ed_group == "Top-level": ed_group = "/" # Merge attributes and set to dataset group_attrs = _merge_attributes(ds_attrs) # Empty out attributes for now, will be refilled later combined_ds.attrs = group_attrs # Add combined flag and update conversion time for Provenance if ed_group == "Provenance": combined_ds.attrs.update( { "is_combined": True, "conversion_software_name": group_attrs["conversion_software_name"], "conversion_software_version": group_attrs["conversion_software_version"], "conversion_time": group_attrs["conversion_time"], } ) prov_dict = echopype_prov_attrs(process_type="combination") combined_ds = combined_ds.assign_attrs(prov_dict) # Data holding tree_dict[ed_group] = combined_ds # Capture provenance for all the attributes prov_ds = _capture_prov_attrs(attrs_dict, echodata_filenames, sonar_model) if not any_combined: # Update the provenance dataset with the captured data prov_ds = tree_dict["Provenance"].assign(prov_ds) else: prov_ds = tree_dict["Provenance"].drop_dims(ED_FILENAME).assign(prov_ds) # Update filenames to iter integers prov_ds[FILENAMES] = prov_ds[FILENAMES].copy(data=np.arange(*prov_ds[FILENAMES].shape)) # noqa tree_dict["Provenance"] = prov_ds return tree_dict def combine_echodata( echodata_list: List[EchoData] = None, channel_selection: Optional[Union[List, Dict[str, list]]] = None, ) -> EchoData: """ Combines multiple ``EchoData`` objects into a single ``EchoData`` object. Parameters ---------- echodata_list : list 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]) """ # return empty EchoData object, if no EchoData objects are provided if echodata_list is None: warn("No EchoData objects were provided, returning an empty EchoData object.") return EchoData() # Ensure the list of all EchoData objects to be combined are valid sonar_model, echodata_filenames = check_eds(echodata_list) # make sure channel_selection is the appropriate type and only contains the beam groups _check_channel_selection_form(channel_selection) # perform channel check and get channel selection for each EchoData group ed_group_chan_sel = _check_echodata_channels(echodata_list, channel_selection) # combine the echodata objects and get the tree dict tree_dict = _combine( sonar_model=sonar_model, eds=echodata_list, echodata_filenames=echodata_filenames, ed_group_chan_sel=ed_group_chan_sel, ) # create datatree from tree dictionary tree = DataTree.from_dict(tree_dict, name="root") # create echodata object from datatree ed_comb = EchoData(sonar_model=sonar_model) ed_comb._set_tree(tree) ed_comb._load_tree() return ed_comb
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,776
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/consolidate/test_consolidate_integration.py
import math import os import pathlib import tempfile import pytest import numpy as np import pandas as pd import xarray as xr import scipy.io as io import echopype as ep from typing import List """ For future reference: For ``test_add_splitbeam_angle`` the test data is in the following locations: - the EK60 raw file is in `test_data/ek60/DY1801_EK60-D20180211-T164025.raw` and the associated echoview split-beam data is in `test_data/ek60/splitbeam`. - the EK80 raw file is in `test_data/ek80_bb_with_calibration/2018115-D20181213-T094600.raw` and the associated echoview split-beam data is in `test_data/ek80_bb_with_calibration/splitbeam` """ @pytest.fixture( params=[ ( ("EK60", "DY1002_EK60-D20100318-T023008_rep_freq.raw"), "EK60", None, {}, ), ( ("EK80_NEW", "D20211004-T233354.raw"), "EK80", None, {'waveform_mode': 'CW', 'encode_mode': 'power'}, ), ( ("AZFP", "17082117.01A"), "AZFP", ("AZFP", "17041823.XML"), {}, ), ], ids=[ "ek60_dup_freq", "ek80_cw_power", "azfp", ], ) def test_data_samples(request, test_path): ( filepath, sonar_model, azfp_xml_path, range_kwargs, ) = request.param path_model, *paths = filepath filepath = test_path[path_model].joinpath(*paths) if azfp_xml_path is not None: path_model, *paths = azfp_xml_path azfp_xml_path = test_path[path_model].joinpath(*paths) return ( filepath, sonar_model, azfp_xml_path, range_kwargs, ) def _check_swap(ds, ds_swap): assert "channel" in ds.dims assert "frequency_nominal" not in ds.dims assert "frequency_nominal" in ds_swap.dims assert "channel" not in ds_swap.dims def test_swap_dims_channel_frequency(test_data_samples): """ Test swapping dimension/coordinate from channel to frequency_nominal. """ ( filepath, sonar_model, azfp_xml_path, range_kwargs, ) = test_data_samples ed = ep.open_raw(filepath, sonar_model, azfp_xml_path) if ed.sonar_model.lower() == 'azfp': avg_temperature = ed['Environment']['temperature'].values.mean() env_params = { 'temperature': avg_temperature, 'salinity': 27.9, 'pressure': 59, } range_kwargs['env_params'] = env_params if 'azfp_cal_type' in range_kwargs: range_kwargs.pop('azfp_cal_type') dup_freq_valueerror = ( "Duplicated transducer nominal frequencies exist in the file. " "Operation is not valid." ) Sv = ep.calibrate.compute_Sv(ed, **range_kwargs) try: Sv_swapped = ep.consolidate.swap_dims_channel_frequency(Sv) _check_swap(Sv, Sv_swapped) except Exception as e: assert isinstance(e, ValueError) is True assert str(e) == dup_freq_valueerror MVBS = ep.commongrid.compute_MVBS(Sv) try: MVBS_swapped = ep.consolidate.swap_dims_channel_frequency(MVBS) _check_swap(Sv, MVBS_swapped) except Exception as e: assert isinstance(e, ValueError) is True assert str(e) == dup_freq_valueerror def _build_ds_Sv(channel, range_sample, ping_time, sample_interval): return xr.Dataset( data_vars={ "Sv": ( ("channel", "range_sample", "ping_time"), np.random.random((len(channel), range_sample.size, ping_time.size)), ), "echo_range": ( ("channel", "range_sample", "ping_time"), ( np.swapaxes(np.tile(range_sample, (len(channel), ping_time.size, 1)), 1, 2) * sample_interval ), ), }, coords={ "channel": channel, "range_sample": range_sample, "ping_time": ping_time, }, ) def test_add_depth(): # Build test Sv dataset channel = ["channel_0", "channel_1", "channel_2"] range_sample = np.arange(100) ping_time = pd.date_range(start="2022-08-10T10:00:00", end="2022-08-10T12:00:00", periods=121) sample_interval = 0.01 ds_Sv = _build_ds_Sv(channel, range_sample, ping_time, sample_interval) # # no water_level in ds # try: # ds_Sv_depth = ep.consolidate.add_depth(ds_Sv) # except ValueError: # ... # user input water_level water_level = 10 ds_Sv_depth = ep.consolidate.add_depth(ds_Sv, depth_offset=water_level) assert ds_Sv_depth["depth"].equals(ds_Sv["echo_range"] + water_level) # user input water_level and tilt tilt = 15 ds_Sv_depth = ep.consolidate.add_depth(ds_Sv, depth_offset=water_level, tilt=tilt) assert ds_Sv_depth["depth"].equals(ds_Sv["echo_range"] * np.cos(tilt / 180 * np.pi) + water_level) # inverted echosounder ds_Sv_depth = ep.consolidate.add_depth(ds_Sv, depth_offset=water_level, tilt=tilt, downward=False) assert ds_Sv_depth["depth"].equals(-1 * ds_Sv["echo_range"] * np.cos(tilt / 180 * np.pi) + water_level) # check attributes # assert ds_Sv_depth["depth"].attrs == {"long_name": "Depth", "standard_name": "depth"} def _create_array_list_from_echoview_mats(paths_to_echoview_mat: List[pathlib.Path]) -> List[np.ndarray]: """ Opens each mat file in ``paths_to_echoview_mat``, selects the first ``ping_time``, and then stores the array in a list. Parameters ---------- paths_to_echoview_mat: list of pathlib.Path A list of paths corresponding to mat files, where each mat file contains the echoview generated angle alongship and athwartship data for a channel Returns ------- list of np.ndarray A list of numpy arrays generated by choosing the appropriate data from the mat files. This list will have the same length as ``paths_to_echoview_mat`` """ list_of_mat_arrays = [] for mat_file in paths_to_echoview_mat: # open mat file and grab appropriate data list_of_mat_arrays.append(io.loadmat(file_name=mat_file)["P0"]["Data_values"][0][0]) return list_of_mat_arrays @pytest.mark.parametrize( ["location_type", "sonar_model", "path_model", "raw_and_xml_paths", "extras"], [ ( "empty-location", "EK60", "EK60", ("ooi/CE02SHBP-MJ01C-07-ZPLSCB101_OOI-D20191201-T000000.raw", None), None, ), ( "with-track-location", "EK60", "EK60", ("Winter2017-D20170115-T150122.raw", None), None, ), ( "fixed-location", "AZFP", "AZFP", ("17082117.01A", "17041823.XML"), {'longitude': -60.0, 'latitude': 45.0, 'salinity': 27.9, 'pressure': 59}, ), ], ) def test_add_location( location_type, sonar_model, path_model, raw_and_xml_paths, extras, test_path ): # Prepare the Sv dataset raw_path = test_path[path_model] / raw_and_xml_paths[0] if raw_and_xml_paths[1]: xml_path = test_path[path_model] / raw_and_xml_paths[1] else: xml_path = None ed = ep.open_raw(raw_path, xml_path=xml_path, sonar_model=sonar_model) if location_type == "fixed-location": point_ds = xr.Dataset( { "latitude": (["time"], np.array([float(extras['latitude'])])), "longitude": (["time"], np.array([float(extras['longitude'])])), }, coords={ "time": (["time"], np.array([ed["Sonar/Beam_group1"]["ping_time"].values.min()])) }, ) ed.update_platform(point_ds, variable_mappings={"latitude": "latitude", "longitude": "longitude"}) env_params = None # AZFP data require external salinity and pressure if sonar_model == "AZFP": env_params = { "temperature": ed["Environment"]["temperature"].values.mean(), "salinity": extras["salinity"], "pressure": extras["pressure"], } ds = ep.calibrate.compute_Sv(echodata=ed, env_params=env_params) # add_location tests if location_type == "empty-location": with pytest.raises(Exception) as exc: ep.consolidate.add_location(ds=ds, echodata=ed) assert exc.type is ValueError assert "Coordinate variables not present or all nan" in str(exc.value) else: def _tests(ds_test, location_type, nmea_sentence=None): # lat,lon & time1 existence assert "latitude" in ds_test assert "longitude" in ds_test assert "time1" not in ds_test # lat & lon have a single dimension: 'ping_time' assert len(ds_test["longitude"].dims) == 1 and ds_test["longitude"].dims[0] == "ping_time" # noqa assert len(ds_test["latitude"].dims) == 1 and ds_test["latitude"].dims[0] == "ping_time" # noqa # Check interpolated or broadcast values if location_type == "with-track-location": for position in ["longitude", "latitude"]: position_var = ed["Platform"][position] if nmea_sentence: position_var = position_var[ed["Platform"]["sentence_type"] == nmea_sentence] position_interp = position_var.interp(time1=ds_test["ping_time"]) # interpolated values are identical assert np.allclose(ds_test[position].values, position_interp.values, equal_nan=True) # noqa elif location_type == "fixed-location": for position in ["longitude", "latitude"]: position_uniq = set(ds_test[position].values) # contains a single repeated value equal to the value passed to update_platform assert ( len(position_uniq) == 1 and math.isclose(list(position_uniq)[0], extras[position]) ) ds_all = ep.consolidate.add_location(ds=ds, echodata=ed) _tests(ds_all, location_type) # the test for nmea_sentence="GGA" is limited to the with-track-location case if location_type == "with-track-location": ds_sel = ep.consolidate.add_location(ds=ds, echodata=ed, nmea_sentence="GGA") _tests(ds_sel, location_type, nmea_sentence="GGA") @pytest.mark.parametrize( ("sonar_model", "test_path_key", "raw_file_name", "paths_to_echoview_mat", "waveform_mode", "encode_mode", "pulse_compression", "write_Sv_to_file"), [ # ek60_CW_power ( "EK60", "EK60", "DY1801_EK60-D20180211-T164025.raw", [ 'splitbeam/DY1801_EK60-D20180211-T164025_angles_T1.mat', 'splitbeam/DY1801_EK60-D20180211-T164025_angles_T2.mat', 'splitbeam/DY1801_EK60-D20180211-T164025_angles_T3.mat', 'splitbeam/DY1801_EK60-D20180211-T164025_angles_T4.mat', 'splitbeam/DY1801_EK60-D20180211-T164025_angles_T5.mat' ], "CW", "power", False, False ), # ek60_CW_power_Sv_path ( "EK60", "EK60", "DY1801_EK60-D20180211-T164025.raw", [ 'splitbeam/DY1801_EK60-D20180211-T164025_angles_T1.mat', 'splitbeam/DY1801_EK60-D20180211-T164025_angles_T2.mat', 'splitbeam/DY1801_EK60-D20180211-T164025_angles_T3.mat', 'splitbeam/DY1801_EK60-D20180211-T164025_angles_T4.mat', 'splitbeam/DY1801_EK60-D20180211-T164025_angles_T5.mat' ], "CW", "power", False, True ), # ek80_CW_complex ( "EK80", "EK80_CAL", "2018115-D20181213-T094600.raw", [ 'splitbeam/2018115-D20181213-T094600_angles_T1.mat', 'splitbeam/2018115-D20181213-T094600_angles_T4.mat', 'splitbeam/2018115-D20181213-T094600_angles_T6.mat', 'splitbeam/2018115-D20181213-T094600_angles_T5.mat' ], "CW", "complex", False, False ), # ek80_BB_complex_no_pc ( "EK80", "EK80_CAL", "2018115-D20181213-T094600.raw", [ 'splitbeam/2018115-D20181213-T094600_angles_T3_nopc.mat', 'splitbeam/2018115-D20181213-T094600_angles_T2_nopc.mat', ], "BB", "complex", False, False, ), # ek80_CW_power ( "EK80", "EK80", "Summer2018--D20180905-T033113.raw", [ 'splitbeam/Summer2018--D20180905-T033113_angles_T2.mat', 'splitbeam/Summer2018--D20180905-T033113_angles_T1.mat', ], "CW", "power", False, False, ), ], ids=[ "ek60_CW_power", "ek60_CW_power_Sv_path", "ek80_CW_complex", "ek80_BB_complex_no_pc", "ek80_CW_power", ], ) def test_add_splitbeam_angle(sonar_model, test_path_key, raw_file_name, test_path, paths_to_echoview_mat, waveform_mode, encode_mode, pulse_compression, write_Sv_to_file): # obtain the EchoData object with the data needed for the calculation ed = ep.open_raw(test_path[test_path_key] / raw_file_name, sonar_model=sonar_model) # compute Sv as it is required for the split-beam angle calculation ds_Sv = ep.calibrate.compute_Sv(ed, waveform_mode=waveform_mode, encode_mode=encode_mode) # initialize temporary directory object temp_dir = None # allows us to test for the case when source_Sv is a path if write_Sv_to_file: # create temporary directory for mask_file temp_dir = tempfile.TemporaryDirectory() # write DataArray to temporary directory zarr_path = os.path.join(temp_dir.name, "Sv_data.zarr") ds_Sv.to_zarr(zarr_path) # assign input to a path ds_Sv = zarr_path # add the split-beam angles to Sv dataset ds_Sv = ep.consolidate.add_splitbeam_angle(source_Sv=ds_Sv, echodata=ed, waveform_mode=waveform_mode, encode_mode=encode_mode, pulse_compression=pulse_compression) # obtain corresponding echoview output full_echoview_path = [test_path[test_path_key] / path for path in paths_to_echoview_mat] echoview_arr_list = _create_array_list_from_echoview_mats(full_echoview_path) # compare echoview output against computed output for all channels for chan_ind in range(len(echoview_arr_list)): # grabs the appropriate ds data to compare against reduced_angle_alongship = ds_Sv.isel(channel=chan_ind, ping_time=0).angle_alongship.dropna("range_sample") reduced_angle_athwartship = ds_Sv.isel(channel=chan_ind, ping_time=0).angle_athwartship.dropna("range_sample") # TODO: make "start" below a parameter in the input so that this is not ad-hoc but something known # for some files the echoview data is shifted by one index, here we account for that if reduced_angle_alongship.shape == (echoview_arr_list[chan_ind].shape[1], ): start = 0 else: start = 1 # note for the checks below: # - angles from CW power data are similar down to 1e-7 # - angles computed from complex samples deviates a lot more # check the computed angle_alongship values against the echoview output assert np.allclose(reduced_angle_alongship.values[start:], echoview_arr_list[chan_ind][0, :], rtol=1e-1, atol=1e-2) # check the computed angle_alongship values against the echoview output assert np.allclose(reduced_angle_athwartship.values[start:], echoview_arr_list[chan_ind][1, :], rtol=1e-1, atol=1e-2) if temp_dir: # remove the temporary directory, if it was created temp_dir.cleanup() def test_add_splitbeam_angle_BB_pc(test_path): # obtain the EchoData object with the data needed for the calculation ed = ep.open_raw(test_path["EK80_CAL"] / "2018115-D20181213-T094600.raw", sonar_model="EK80") # compute Sv as it is required for the split-beam angle calculation ds_Sv = ep.calibrate.compute_Sv(ed, waveform_mode="BB", encode_mode="complex") # add the split-beam angles to Sv dataset ds_Sv = ep.consolidate.add_splitbeam_angle( source_Sv=ds_Sv, echodata=ed, waveform_mode="BB", encode_mode="complex", pulse_compression=True ) # Load pyecholab pickle import pickle with open(test_path["EK80_EXT"] / "pyecholab/pyel_BB_splitbeam.pickle", 'rb') as handle: pyel_BB_p_data = pickle.load(handle) # Compare 70kHz channel chan_sel = "WBT 714590-15 ES70-7C" # Compare cal params # dict mappgin: {pyecholab : echopype} cal_params_dict = { "angle_sensitivity_alongship": "angle_sensitivity_alongship", "angle_sensitivity_athwartship": "angle_sensitivity_athwartship", "beam_width_alongship": "beamwidth_alongship", "beam_width_athwartship": "beamwidth_athwartship", } for p_pyel, p_ep in cal_params_dict.items(): assert np.allclose(pyel_BB_p_data["cal_parms"][p_pyel], ds_Sv[p_ep].sel(channel=chan_sel).values) # alongship angle pyel_vals = pyel_BB_p_data["alongship_physical"] ep_vals = ds_Sv["angle_alongship"].sel(channel=chan_sel).values assert pyel_vals.shape == ep_vals.shape assert np.allclose(pyel_vals, ep_vals, atol=1e-5) # athwartship angle pyel_vals = pyel_BB_p_data["athwartship_physical"] ep_vals = ds_Sv["angle_athwartship"].sel(channel=chan_sel).values assert pyel_vals.shape == ep_vals.shape assert np.allclose(pyel_vals, ep_vals, atol=1e-6) # TODO: need a test for power/angle data, with mock EchoData object # containing some channels with single-beam data and some channels with split-beam data
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,777
OSOceanAcoustics/echopype
refs/heads/main
/echopype/echodata/api.py
from typing import TYPE_CHECKING, Dict if TYPE_CHECKING: from ..core import PathHint from .echodata import EchoData def open_converted( converted_raw_path: "PathHint", storage_options: Dict[str, str] = None, **kwargs # kwargs: Dict[str, Any] = {'chunks': 'auto'} # TODO: do we need this? ): """Create an EchoData object from a single converted netcdf or zarr file. Parameters ---------- converted_raw_path : str path to converted data file storage_options : dict options for cloud storage kwargs : dict optional keyword arguments to be passed into xr.open_dataset Returns ------- EchoData object """ # TODO: combine multiple files when opening return EchoData.from_file( converted_raw_path=converted_raw_path, storage_options=storage_options, open_kwargs=kwargs, )
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,778
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/utils/test_utils_io.py
import os import fsspec from pathlib import Path import pytest from typing import Tuple import tempfile import platform import xarray as xr from echopype.utils.io import ( sanitize_file_path, validate_output_path, env_indep_joinpath, validate_source_ds_da, init_ep_dir ) import echopype.utils.io @pytest.mark.parametrize( "file_path, should_fail, file_type", [ ('https://example.com/test.nc', True, 'nc'), ('https://example.com/test.zarr', False, 'zarr'), (os.path.join('folder', 'test.nc'), False, 'nc'), (os.path.join('folder', 'test.zarr'), False, 'zarr'), (Path('https:/example.com/test.nc'), True, 'nc'), (Path('https:/example.com/test.zarr'), True, 'zarr'), (Path('folder/test.nc'), False, 'nc'), (Path('folder/test.zarr'), False, 'zarr'), (fsspec.get_mapper('https://example.com/test.nc'), True, 'nc'), (fsspec.get_mapper('https:/example.com/test.zarr'), False, 'zarr'), (fsspec.get_mapper('folder/test.nc'), False, 'nc'), (fsspec.get_mapper('folder/test.zarr'), False, 'zarr'), ('https://example.com/test.jpeg', True, 'jpeg'), (Path('https://example.com/test.jpeg'), True, 'jpeg'), (fsspec.get_mapper('https://example.com/test.jpeg'), True, 'jpeg'), ], ) def test_sanitize_file_path(file_path, should_fail, file_type): try: sanitized = sanitize_file_path(file_path) if not should_fail: if file_type == 'nc': assert isinstance(sanitized, Path) is True elif file_type == 'zarr': assert isinstance(sanitized, fsspec.FSMap) is True except Exception as e: assert isinstance(e, ValueError) is True @pytest.mark.parametrize( "save_path, engine", [ # Netcdf tests (os.path.join('folder', 'new_test.nc'), 'netcdf4'), (os.path.join('folder', 'new_test.nc'), 'zarr'), (os.path.join('folder', 'path', 'new_test.nc'), 'netcdf4'), ('folder/', 'netcdf4'), ('s3://ooi-raw-data/', 'netcdf4'), (Path('folder/'), 'netcdf4'), (Path('folder/new_test.nc'), 'netcdf4'), # Zarr tests (os.path.join('folder', 'new_test.zarr'), 'zarr'), (os.path.join('folder', 'new_test.zarr'), 'netcdf4'), (os.path.join('folder', 'path', 'new_test.zarr'), 'zarr'), ('folder/', 'zarr'), # Empty tests (None, 'netcdf4'), (None, 'zarr'), # Remotes ('https://example.com/test.zarr', 'zarr'), ('https://example.com/', 'zarr'), ('https://example.com/test.nc', 'netcdf4'), ('s3://ooi-raw-data/new_test.zarr', 'zarr'), ('s3://ooi-raw-data/new_test.nc', 'netcdf4'), ], ) def test_validate_output_path(save_path, engine, minio_bucket): output_root_path = os.path.join('.', 'echopype', 'test_data', 'dump') source_file = 'test.raw' if engine == 'netcdf4': ext = '.nc' else: ext = '.zarr' if save_path is not None: if '://' not in str(save_path): save_path = os.path.join(output_root_path, save_path) is_dir = True if Path(save_path).suffix == '' else False else: is_dir = True save_path = output_root_path output_storage_options = {} if save_path and save_path.startswith("s3://"): output_storage_options = dict( client_kwargs=dict(endpoint_url="http://localhost:9000/"), key="minioadmin", secret="minioadmin", ) try: output_path = validate_output_path( source_file, engine, output_storage_options, save_path ) assert isinstance(output_path, str) is True assert Path(output_path).suffix == ext if is_dir: assert Path(output_path).name == source_file.replace('.raw', '') + ext else: output_file = Path(save_path) assert Path(output_path).name == output_file.name.replace(output_file.suffix, '') + ext except Exception as e: if 'https://' in save_path: if save_path == 'https://example.com/': assert isinstance(e, ValueError) is True assert str(e) == 'Input file type not supported!' elif save_path == 'https://example.com/test.nc': assert isinstance(e, ValueError) is True assert str(e) == 'Only local netcdf4 is supported.' else: assert isinstance(e, PermissionError) is True elif save_path == 's3://ooi-raw-data/new_test.nc': assert isinstance(e, ValueError) is True assert str(e) == 'Only local netcdf4 is supported.' def mock_windows_return(*args: Tuple[str, ...]): """ A function to mock what ``os.path.join`` should return on a Windows machine. Parameters ---------- args: tuple of str A variable number of strings to join Returns ------- str The input strings joined using Windows syntax """ return "\\".join(args) def mock_unix_return(*args: Tuple[str, ...]): """ A function to mock what ``os.path.join`` should return on a Unix based machine. Parameters ---------- args: tuple of str A variable number of strings to join Returns ------- str The input strings joined using Unix syntax Notes ----- This function is necessary just in case the tests are being run on a Windows machine. """ return r"/".join(args) @pytest.mark.parametrize( "save_path, is_windows, is_cloud", [ (r"/folder", False, False), (r"C:\folder", True, False), (r"s3://folder", False, True), (r"s3://folder", True, True), ] ) def test_env_indep_joinpath_mock_return(save_path: str, is_windows: bool, is_cloud: bool, monkeypatch): """ Tests the function ``env_indep_joinpath`` using a mock return on varying OS and cloud path scenarios by adding a folder and a file to the input ``save_path``. Parameters ---------- save_path: str The save path that we want to add a folder and a file to. is_windows: bool If True, signifies that we are "working" on a Windows machine, otherwise on a Unix based machine is_cloud: bool If True, signifies that ``save_path`` corresponds to a cloud path, otherwise it does not Notes ----- This test uses a monkeypatch for ``os.path.join`` to mimic the join we expect from the function. This allows us to test ``env_indep_joinpath`` on any OS. """ # assign the appropriate mock return for os.path.join if is_windows: monkeypatch.setattr(os.path, 'join', mock_windows_return) else: monkeypatch.setattr(os.path, 'join', mock_unix_return) # add folder and file to path joined_path = env_indep_joinpath(save_path, "output", "data.zarr") if is_cloud or (not is_windows): assert joined_path == (save_path + r"/output/data.zarr") else: assert joined_path == (save_path + r"\output\data.zarr") @pytest.mark.parametrize( "save_path, is_windows, is_cloud", [ (r"/root/folder", False, False), (r"C:\root\folder", True, False), (r"s3://root/folder", False, True), (r"s3://root/folder", True, True), ] ) def test_env_indep_joinpath_os_dependent(save_path: str, is_windows: bool, is_cloud: bool): """ Tests the true output of the function ``env_indep_joinpath`` on varying OS and cloud path scenarios by adding a folder and a file to the input ``save_path``. Parameters ---------- save_path: str The save path that we want to add a folder and a file to. is_windows: bool If True, signifies that we are working on a Windows machine, otherwise on a Unix based machine is_cloud: bool If True, signifies that ``save_path`` corresponds to a cloud path, otherwise it does not Notes ----- This test is OS dependent and the testing of parameters will be skipped if they do not correspond to the OS they are being run on. """ # add folder and file to path joined_path = env_indep_joinpath(save_path, "output", "data.zarr") if is_cloud: assert joined_path == r"s3://root/folder/output/data.zarr" elif is_windows: if platform.system() == "Windows": assert joined_path == r"C:\root\folder\output\data.zarr" else: pytest.skip("Skipping Windows parameters because we are not on a Windows machine.") else: if platform.system() != "Windows": assert joined_path == r"/root/folder/output/data.zarr" else: pytest.skip("Skipping Unix parameters because we are not on a Unix machine.") @pytest.mark.parametrize( ("source_ds_da_input", "storage_options_input", "true_file_type"), [ pytest.param(42, {}, None, marks=pytest.mark.xfail( strict=True, reason='This test should fail because source_ds is not of the correct type.') ), pytest.param(xr.DataArray(), {}, None), pytest.param({}, 42, None, marks=pytest.mark.xfail( strict=True, reason='This test should fail because storage_options is not of the correct type.') ), (xr.Dataset(attrs={"test": 42}), {}, None), (os.path.join('folder', 'new_test.nc'), {}, 'netcdf4'), (os.path.join('folder', 'new_test.zarr'), {}, 'zarr') ] ) def test_validate_source_ds_da(source_ds_da_input, storage_options_input, true_file_type): """ Tests that ``validate_source_ds_da`` has the appropriate outputs. An exhaustive list of combinations of ``source_ds_da`` and ``storage_options`` are tested in ``test_validate_output_path`` and are therefore not included here. """ source_ds_output, file_type_output = validate_source_ds_da(source_ds_da_input, storage_options_input) if isinstance(source_ds_da_input, (xr.Dataset, xr.DataArray)): assert source_ds_output.identical(source_ds_da_input) assert file_type_output is None else: assert isinstance(source_ds_output, str) assert file_type_output == true_file_type def test_init_ep_dir(monkeypatch): temp_user_dir = tempfile.TemporaryDirectory() echopype_dir = Path(temp_user_dir.name) / ".echopype" # Create the .echopype in a temp dir instead of user space. # Doing this will avoid accidentally deleting current # working directory monkeypatch.setattr(echopype.utils.io, "ECHOPYPE_DIR", echopype_dir) assert echopype.utils.io.ECHOPYPE_DIR.exists() is False init_ep_dir() assert echopype.utils.io.ECHOPYPE_DIR.exists() is True temp_user_dir.cleanup()
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,779
OSOceanAcoustics/echopype
refs/heads/main
/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py
from _echopype_version import version as __version__ # noqa from .v05x_to_v06x import convert_v05x_to_v06x def map_ep_version(echodata_obj): """ Function that coordinates the conversion between echopype versions Parameters ---------- echodata_obj : EchoData EchoData object that may need to be converted Notes ----- The function directly modifies the input EchoData object. """ if (0, 5, 0) <= echodata_obj.version_info < (0, 6, 0): convert_v05x_to_v06x(echodata_obj) elif (0, 6, 0) <= echodata_obj.version_info < (0, 8, 0): pass else: str_version = ".".join(map(str, echodata_obj.version_info)) raise NotImplementedError( f"Conversion of data from echopype v{str_version} format to" + f" v{__version__} format is not available. Please use open_raw" + f" to convert data to version {__version__} format." )
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,780
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/mask/test_mask.py
import pathlib import pytest import numpy as np import xarray as xr import dask.array import tempfile import os import echopype as ep import echopype.mask from echopype.mask.api import ( _check_source_Sv_freq_diff, _validate_and_collect_mask_input, _check_var_name_fill_value ) from typing import List, Union, Optional def get_mock_freq_diff_data(n: int, n_chan_freq: int, add_chan: bool, add_freq_nom: bool) -> xr.Dataset: """ Creates an in-memory mock Sv Dataset. Parameters ---------- n: int The number of rows (``ping_time``) and columns (``range_sample``) of each channel matrix n_chan_freq: int Determines the size of the ``channel`` coordinate and ``frequency_nominal`` variable. To create mock data with known outcomes for ``frequency_differencing``, this value must be greater than or equal to 3. add_chan: bool If True the ``channel`` dimension will be named "channel", else it will be named "data_coord" add_freq_nom: bool If True the ``frequency_nominal`` variable will be added to the Dataset Returns ------- mock_Sv_ds: xr.Dataset A mock Sv dataset to be used for ``frequency_differencing`` tests. The Sv data values for the channel coordinate ``chan1`` will be equal to ``mat_A``, ``chan3`` will be equal to ``mat_B``, and all other channel coordinates will retain the value of ``np.identity(n)``. Notes ----- The mock Sv Data is created in such a way where ``mat_A - mat_B`` will be the identity matrix. """ if n_chan_freq < 3: raise RuntimeError("The input n_chan_freq must be greater than or equal to 3!") # matrix representing freqB mat_B = np.arange(n ** 2).reshape(n, n) - np.identity(n) # matrix representing freqA mat_A = np.arange(n ** 2).reshape(n, n) # construct channel values chan_vals = ['chan' + str(i) for i in range(1, n_chan_freq + 1)] # construct mock Sv data mock_Sv_data = [mat_A, np.identity(n), mat_B] + [np.identity(n) for i in range(3, n_chan_freq)] # set channel coordinate name (used for testing purposes) if not add_chan: channel_coord_name = "data_coord" else: channel_coord_name = "channel" # create mock Sv DataArray mock_Sv_da = xr.DataArray(data=np.stack(mock_Sv_data), coords={channel_coord_name: chan_vals, "ping_time": np.arange(n), "range_sample": np.arange(n)}) # create data variables for the Dataset data_vars = {"Sv": mock_Sv_da} if add_freq_nom: # construct frequency_values freq_vals = [float(i) for i in range(1, n_chan_freq + 1)] # create mock frequency_nominal and add it to the Dataset variables mock_freq_nom = xr.DataArray(data=freq_vals, coords={channel_coord_name: chan_vals}) data_vars["frequency_nominal"] = mock_freq_nom # create mock Dataset with Sv and frequency_nominal mock_Sv_ds = xr.Dataset(data_vars=data_vars) return mock_Sv_ds def get_mock_source_ds_apply_mask(n: int, n_chan: int, is_delayed: bool) -> xr.Dataset: """ Constructs a mock ``source_ds`` Dataset input for the ``apply_mask`` function. Parameters ---------- n: int The ``ping_time`` and ``range_sample`` dimensions of each channel matrix n_chan: int Size of the ``channel`` coordinate is_delayed: bool If True, the returned Dataset variables ``var1`` and ``var2`` will be a Dask arrays, else they will be in-memory arrays Returns ------- xr.Dataset A Dataset containing data variables ``var1, var2`` with coordinates ``('channel', 'ping_time', 'range_sample')``. The variables are square matrices of ones for each ``channel``. """ # construct channel values chan_vals = ['chan' + str(i) for i in range(1, n_chan + 1)] # construct mock variable data for each channel if is_delayed: mock_var_data = [dask.array.ones((n, n)) for i in range(n_chan)] else: mock_var_data = [np.ones((n, n)) for i in range(n_chan)] # create mock var1 and var2 DataArrays mock_var1_da = xr.DataArray(data=np.stack(mock_var_data), coords={"channel": ("channel", chan_vals, {"long_name": "channel name"}), "ping_time": np.arange(n), "range_sample": np.arange(n)}, attrs={"long_name": "variable 1"}) mock_var2_da = xr.DataArray(data=np.stack(mock_var_data), coords={"channel": ("channel", chan_vals, {"long_name": "channel name"}), "ping_time": np.arange(n), "range_sample": np.arange(n)}, attrs={"long_name": "variable 2"}) # create mock Dataset mock_ds = xr.Dataset(data_vars={"var1": mock_var1_da, "var2": mock_var2_da}) return mock_ds def create_input_mask( mask: Union[np.ndarray, List[np.ndarray]], mask_file: Optional[Union[str, List[str]]], mask_coords: Union[xr.core.coordinates.DataArrayCoordinates, dict], ): """ A helper function that correctly constructs the mask input, so it can be used for ``apply_mask`` related tests. Parameters ---------- mask: np.ndarray or list of np.ndarray The mask(s) that should be applied to ``var_name`` mask_file: str or list of str, optional If provided, the ``mask`` input will be written to a temporary directory with file name ``mask_file``. This will then be used in ``apply_mask``. mask_coords: xr.core.coordinates.DataArrayCoordinates or dict The DataArray coordinates that should be used for each mask DataArray created """ # initialize temp_dir temp_dir = None # make input numpy array masks into DataArrays if isinstance(mask, list): # initialize final mask mask_out = [] # create temporary directory if mask_file is provided if any([isinstance(elem, str) for elem in mask_file]): # create temporary directory for mask_file temp_dir = tempfile.TemporaryDirectory() for mask_ind in range(len(mask)): # form DataArray from given mask data mask_da = xr.DataArray(data=[mask[mask_ind]], coords=mask_coords, name='mask_' + str(mask_ind)) if mask_file[mask_ind] is None: # set mask value to the DataArray given mask_out.append(mask_da) else: # write DataArray to temporary directory zarr_path = os.path.join(temp_dir.name, mask_file[mask_ind]) mask_da.to_dataset().to_zarr(zarr_path) if isinstance(mask_file[mask_ind], pathlib.Path): # make zarr_path into a Path object zarr_path = pathlib.Path(zarr_path) # set mask value to created path mask_out.append(zarr_path) elif isinstance(mask, np.ndarray): # form DataArray from given mask data mask_da = xr.DataArray(data=[mask], coords=mask_coords, name='mask_0') if mask_file is None: # set mask to the DataArray formed mask_out = mask_da else: # create temporary directory for mask_file temp_dir = tempfile.TemporaryDirectory() # write DataArray to temporary directory zarr_path = os.path.join(temp_dir.name, mask_file) mask_da.to_dataset().to_zarr(zarr_path) if isinstance(mask_file, pathlib.Path): # make zarr_path into a Path object zarr_path = pathlib.Path(zarr_path) # set mask index to path mask_out = zarr_path return mask_out, temp_dir @pytest.mark.parametrize( ("n", "n_chan_freq", "add_chan", "add_freq_nom", "freqAB", "chanAB"), [ (5, 3, True, True, [1.0, 3.0], None), (5, 3, True, True, None, ['chan1', 'chan3']), pytest.param(5, 3, False, True, [1.0, 3.0], None, marks=pytest.mark.xfail(strict=True, reason="This should fail because the Dataset " "will not have the channel coordinate.")), pytest.param(5, 3, True, False, [1.0, 3.0], None, marks=pytest.mark.xfail(strict=True, reason="This should fail because the Dataset " "will not have the frequency_nominal variable.")), pytest.param(5, 3, True, True, [1.0, 4.0], None, marks=pytest.mark.xfail(strict=True, reason="This should fail because not all selected frequencies" "are in the frequency_nominal variable.")), pytest.param(5, 3, True, True, None, ['chan1', 'chan4'], marks=pytest.mark.xfail(strict=True, reason="This should fail because not all selected channels" "are in the channel coordinate.")), ], ids=["dataset_input_freqAB_provided", "dataset_input_chanAB_provided", "dataset_no_channel", "dataset_no_frequency_nominal", "dataset_missing_freqAB_in_freq_nom", "dataset_missing_chanAB_in_channel"] ) def test_check_source_Sv_freq_diff(n: int, n_chan_freq: int, add_chan: bool, add_freq_nom: bool, freqAB: List[float], chanAB: List[str]): """ Test the inputs ``source_Sv, freqAB, chanAB`` for ``_check_source_Sv_freq_diff``. Parameters ---------- n: int The number of rows (``ping_time``) and columns (``range_sample``) of each channel matrix n_chan_freq: int Determines the size of the ``channel`` coordinate and ``frequency_nominal`` variable. To create mock data with known outcomes for ``frequency_differencing``, this value must be greater than or equal to 3. add_chan: bool If True the ``channel`` dimension will be named "channel", else it will be named "data_coord" add_freq_nom: bool If True the ``frequency_nominal`` variable will be added to the Dataset freqAB: list of float, optional The pair of nominal frequencies to be used for frequency-differencing, where the first element corresponds to ``freqA`` and the second element corresponds to ``freqB`` chanAB: list of float, optional The pair of channels that will be used to select the nominal frequencies to be used for frequency-differencing, where the first element corresponds to ``freqA`` and the second element corresponds to ``freqB`` """ source_Sv = get_mock_freq_diff_data(n, n_chan_freq, add_chan, add_freq_nom) _check_source_Sv_freq_diff(source_Sv, freqAB=freqAB, chanAB=chanAB) @pytest.mark.parametrize( ("n", "n_chan_freq", "freqAB", "chanAB", "diff", "operator", "mask_truth"), [ (5, 4, [1.0, 3.0], None, 1.0, "==", np.identity(5)), (5, 4, None, ['chan1', 'chan3'], 1.0, "==", np.identity(5)), (5, 4, [3.0, 1.0], None, 1.0, "==", np.zeros((5, 5))), (5, 4, None, ['chan3', 'chan1'], 1.0, "==", np.zeros((5, 5))), (5, 4, [1.0, 3.0], None, 1.0, ">=", np.identity(5)), (5, 4, None, ['chan1', 'chan3'], 1.0, ">=", np.identity(5)), (5, 4, [1.0, 3.0], None, 1.0, ">", np.zeros((5, 5))), (5, 4, None, ['chan1', 'chan3'], 1.0, ">", np.zeros((5, 5))), (5, 4, [1.0, 3.0], None, 1.0, "<=", np.ones((5, 5))), (5, 4, None, ['chan1', 'chan3'], 1.0, "<=", np.ones((5, 5))), (5, 4, [1.0, 3.0], None, 1.0, "<", np.ones((5, 5)) - np.identity(5)), (5, 4, None, ['chan1', 'chan3'], 1.0, "<", np.ones((5, 5)) - np.identity(5)), ], ids=["freqAB_sel_op_equals", "chanAB_sel_op_equals", "reverse_freqAB_sel_op_equals", "reverse_chanAB_sel_op_equals", "freqAB_sel_op_ge", "chanAB_sel_op_ge", "freqAB_sel_op_greater", "chanAB_sel_op_greater", "freqAB_sel_op_le", "chanAB_sel_op_le", "freqAB_sel_op_less", "chanAB_sel_op_less"] ) def test_frequency_differencing(n: int, n_chan_freq: int, freqAB: List[float], chanAB: List[str], diff: Union[float, int], operator: str, mask_truth: np.ndarray): """ Tests that the output values of ``frequency_differencing`` are what we expect, the output is a DataArray, and that the name of the DataArray is correct. Parameters ---------- n: int The number of rows (``ping_time``) and columns (``range_sample``) of each channel matrix n_chan_freq: int Determines the size of the ``channel`` coordinate and ``frequency_nominal`` variable. To create mock data with known outcomes for ``frequency_differencing``, this value must be greater than or equal to 3. freqAB: list of float, optional The pair of nominal frequencies to be used for frequency-differencing, where the first element corresponds to ``freqA`` and the second element corresponds to ``freqB`` chanAB: list of float, optional The pair of channels that will be used to select the nominal frequencies to be used for frequency-differencing, where the first element corresponds to ``freqA`` and the second element corresponds to ``freqB`` diff: float or int The threshold of Sv difference between frequencies operator: {">", "<", "<=", ">=", "=="} The operator for the frequency-differencing mask_truth: np.ndarray The truth value for the output mask, provided the given inputs """ # obtain mock Sv Dataset mock_Sv_ds = get_mock_freq_diff_data(n, n_chan_freq, add_chan=True, add_freq_nom=True) # obtain the frequency-difference mask for mock_Sv_ds out = ep.mask.frequency_differencing(source_Sv=mock_Sv_ds, storage_options={}, freqAB=freqAB, chanAB=chanAB, operator=operator, diff=diff) # ensure that the output values are correct assert np.all(out == mask_truth) # ensure that the output is a DataArray assert isinstance(out, xr.DataArray) # test that the output DataArray is correctly names assert out.name == "mask" @pytest.mark.parametrize( ("n", "n_chan", "mask_np", "mask_file", "storage_options_mask"), [ (5, 1, np.identity(5), None, {}), (5, 1, [np.identity(5), np.identity(5)], [None, None], {}), (5, 1, [np.identity(5), np.identity(5)], [None, None], [{}, {}]), (5, 1, np.identity(5), "path/to/mask.zarr", {}), (5, 1, [np.identity(5), np.identity(5)], ["path/to/mask0.zarr", "path/to/mask1.zarr"], {}), (5, 1, np.identity(5), pathlib.Path("path/to/mask.zarr"), {}), (5, 1, [np.identity(5), np.identity(5), np.identity(5)], [None, "path/to/mask0.zarr", pathlib.Path("path/to/mask1.zarr")], {}) ], ids=["mask_da", "mask_list_da_single_storage", "mask_list_da_list_storage", "mask_str_path", "mask_list_str_path", "mask_pathlib", "mask_mixed_da_str_pathlib"] ) def test_validate_and_collect_mask_input( n: int, n_chan: int, mask_np: Union[np.ndarray, List[np.ndarray]], mask_file: Optional[Union[str, pathlib.Path, List[Union[str, pathlib.Path]]]], storage_options_mask: Union[dict, List[dict]]): """ Tests the allowable types for the mask input and corresponding storage options. Parameters ---------- n: int The number of rows (``x``) and columns (``y``) of each channel matrix n_chan: int Determines the size of the ``channel`` coordinate mask_np: np.ndarray or list of np.ndarray The mask(s) that should be applied to ``var_name`` mask_file: str or list of str, optional If provided, the ``mask`` input will be written to a temporary directory with file name ``mask_file``. This will then be used in ``apply_mask``. storage_options_mask: dict or list of dict, default={} Any additional parameters for the storage backend, corresponding to the path provided for ``mask`` Notes ----- The input for ``storage_options_mask`` will only contain the value `{}` or a list of empty dictionaries as other options are already tested in ``test_utils_io.py::test_validate_output_path`` and are therefore not included here. """ # construct channel values chan_vals = ['chan' + str(i) for i in range(1, n_chan + 1)] # create coordinates that will be used by all DataArrays created coords = {"channel": ("channel", chan_vals, {"long_name": "channel name"}), "ping_time": np.arange(n), "range_sample": np.arange(n)} # create input mask and obtain temporary directory, if it was created mask, _ = create_input_mask(mask_np, mask_file, coords) mask_out = _validate_and_collect_mask_input(mask=mask, storage_options_mask=storage_options_mask) if isinstance(mask_out, list): for ind, da in enumerate(mask_out): # create known solution for mask mask_da = xr.DataArray(data=[mask_np[ind] for i in range(n_chan)], coords=coords, name='mask_' + str(ind)) assert da.identical(mask_da) else: # create known solution for mask mask_da = xr.DataArray(data=[mask_np for i in range(n_chan)], coords=coords, name='mask_0') assert mask_out.identical(mask_da) @pytest.mark.parametrize( ("n", "n_chan", "var_name", "fill_value"), [ pytest.param(4, 2, 2.0, np.nan, marks=pytest.mark.xfail(strict=True, reason="This should fail because the var_name is not a string.")), pytest.param(4, 2, "var3", np.nan, marks=pytest.mark.xfail(strict=True, reason="This should fail because mock_ds will " "not have var_name=var3 in it.")), pytest.param(4, 2, "var1", "1.0", marks=pytest.mark.xfail(strict=True, reason="This should fail because fill_value is an incorrect type.")), (4, 2, "var1", 1), (4, 2, "var1", 1.0), (2, 1, "var1", np.identity(2)[None, :]), (2, 1, "var1", xr.DataArray(data=np.array([[[1.0, 0], [0, 1]]]), coords={"channel": ["chan1"], "ping_time": [0, 1], "range_sample": [0, 1]}) ), pytest.param(4, 2, "var1", np.identity(2), marks=pytest.mark.xfail(strict=True, reason="This should fail because fill_value is not the right shape.")), pytest.param(4, 2, "var1", xr.DataArray(data=np.array([[1.0, 0], [0, 1]]), coords={"ping_time": [0, 1], "range_sample": [0, 1]}), marks=pytest.mark.xfail(strict=True, reason="This should fail because fill_value is not the right shape.")), ], ids=["wrong_var_name_type", "no_var_name_ds", "wrong_fill_value_type", "fill_value_int", "fill_value_float", "fill_value_np_array", "fill_value_DataArray", "fill_value_np_array_wrong_shape", "fill_value_DataArray_wrong_shape"] ) def test_check_var_name_fill_value(n: int, n_chan: int, var_name: str, fill_value: Union[int, float, np.ndarray, xr.DataArray]): """ Ensures that the function ``_check_var_name_fill_value`` is behaving as expected. Parameters ---------- n: int The number of rows (``x``) and columns (``y``) of each channel matrix n_chan: int Determines the size of the ``channel`` coordinate var_name: {"var1", "var2"} The variable name in the mock Dataset to apply the mask to fill_value: int, float, np.ndarray, or xr.DataArray Value(s) at masked indices """ # obtain mock Dataset containing var_name mock_ds = get_mock_source_ds_apply_mask(n, n_chan, is_delayed=False) _check_var_name_fill_value(source_ds=mock_ds, var_name=var_name, fill_value=fill_value) @pytest.mark.parametrize( ("n", "n_chan", "var_name", "mask", "mask_file", "fill_value", "is_delayed", "var_masked_truth", "no_channel"), [ # single_mask_default_fill (2, 1, "var1", np.identity(2), None, np.nan, False, np.array([[1, np.nan], [np.nan, 1]]), False), # single_mask_default_fill_no_channel (2, 1, "var1", np.identity(2), None, np.nan, False, np.array([[1, np.nan], [np.nan, 1]]), True), # single_mask_float_fill (2, 1, "var1", np.identity(2), None, 2.0, False, np.array([[1, 2.0], [2.0, 1]]), False), # single_mask_np_array_fill (2, 1, "var1", np.identity(2), None, np.array([[[np.nan, np.nan], [np.nan, np.nan]]]), False, np.array([[1, np.nan], [np.nan, 1]]), False), # single_mask_DataArray_fill (2, 1, "var1", np.identity(2), None, xr.DataArray(data=np.array([[[np.nan, np.nan], [np.nan, np.nan]]]), coords={"channel": ["chan1"], "ping_time": [0, 1], "range_sample": [0, 1]}), False, np.array([[1, np.nan], [np.nan, 1]]), False), # list_mask_all_np (2, 1, "var1", [np.identity(2), np.array([[0, 1], [0, 1]])], [None, None], 2.0, False, np.array([[2.0, 2.0], [2.0, 1]]), False), # single_mask_ds_delayed (2, 1, "var1", np.identity(2), None, 2.0, True, np.array([[1, 2.0], [2.0, 1]]), False), # single_mask_as_path (2, 1, "var1", np.identity(2), "test.zarr", 2.0, True, np.array([[1, 2.0], [2.0, 1]]), False), # list_mask_all_path (2, 1, "var1", [np.identity(2), np.array([[0, 1], [0, 1]])], ["test0.zarr", "test1.zarr"], 2.0, False, np.array([[2.0, 2.0], [2.0, 1]]), False), # list_mask_some_path (2, 1, "var1", [np.identity(2), np.array([[0, 1], [0, 1]])], ["test0.zarr", None], 2.0, False, np.array([[2.0, 2.0], [2.0, 1]]), False), ], ids=[ "single_mask_default_fill", "single_mask_default_fill_no_channel", "single_mask_float_fill", "single_mask_np_array_fill", "single_mask_DataArray_fill", "list_mask_all_np", "single_mask_ds_delayed", "single_mask_as_path", "list_mask_all_path", "list_mask_some_path" ] ) def test_apply_mask(n: int, n_chan: int, var_name: str, mask: Union[np.ndarray, List[np.ndarray]], mask_file: Optional[Union[str, List[str]]], fill_value: Union[int, float, np.ndarray, xr.DataArray], is_delayed: bool, var_masked_truth: np.ndarray, no_channel: bool): """ Ensures that ``apply_mask`` functions correctly. Parameters ---------- n: int The number of rows (``x``) and columns (``y``) of each channel matrix n_chan: int Determines the size of the ``channel`` coordinate var_name: {"var1", "var2"} The variable name in the mock Dataset to apply the mask to mask: np.ndarray or list of np.ndarray The mask(s) that should be applied to ``var_name`` mask_file: str or list of str, optional If provided, the ``mask`` input will be written to a temporary directory with file name ``mask_file``. This will then be used in ``apply_mask``. fill_value: int, float, np.ndarray, or xr.DataArray Value(s) at masked indices var_masked_truth: np.ndarray The true value of ``var_name`` values after the mask has been applied is_delayed: bool If True, makes all variables in constructed mock Dataset Dask arrays, else they will be in-memory arrays """ # obtain mock Dataset containing var_name mock_ds = get_mock_source_ds_apply_mask(n, n_chan, is_delayed) # create input mask and obtain temporary directory, if it was created mask, temp_dir = create_input_mask(mask, mask_file, mock_ds.coords) # create DataArray form of the known truth value var_masked_truth = xr.DataArray(data=np.stack([var_masked_truth for i in range(n_chan)]), coords=mock_ds[var_name].coords, attrs=mock_ds[var_name].attrs) var_masked_truth.name = mock_ds[var_name].name if no_channel: mock_ds = mock_ds.isel(channel=0) mask = mask.isel(channel=0) var_masked_truth = var_masked_truth.isel(channel=0) # apply the mask to var_name masked_ds = echopype.mask.apply_mask(source_ds=mock_ds, var_name=var_name, mask=mask, fill_value=fill_value, storage_options_ds={}, storage_options_mask={}) # check that masked_ds[var_name] == var_masked_truth assert masked_ds[var_name].equals(var_masked_truth) # check that the output Dataset has lazy elements, if the input was lazy if is_delayed: assert isinstance(masked_ds[var_name].data, dask.array.Array) if temp_dir: # remove the temporary directory, if it was created temp_dir.cleanup() @pytest.mark.parametrize( ("source_has_ch", "mask_has_ch"), [ (True, True), (False, True), (True, False), (False, False), ], ids=[ "source_with_ch_mask_with_ch", "source_no_ch_mask_with_ch", "source_with_ch_mask_no_ch", "source_no_ch_mask_no_ch", ] ) def test_apply_mask_channel_variation(source_has_ch, mask_has_ch): source_ds = get_mock_source_ds_apply_mask(2, 3, False) var_name = "var1" if mask_has_ch: mask = xr.DataArray( np.array([np.identity(2)]), coords={"channel": ["chA"], "ping_time": np.arange(2), "range_sample": np.arange(2)}, attrs={"long_name": "mask_with_channel"}, ) else: mask = xr.DataArray( np.identity(2), coords={"ping_time": np.arange(2), "range_sample": np.arange(2)}, attrs={"long_name": "mask_no_channel"}, ) if source_has_ch: masked_ds = echopype.mask.apply_mask(source_ds, mask, var_name) else: source_ds[f"{var_name}_ch0"] = source_ds[var_name].isel(channel=0).squeeze() var_name = f"{var_name}_ch0" masked_ds = echopype.mask.apply_mask(source_ds, mask, var_name) # Output dimension will be the same as source if source_has_ch: truth_da = xr.DataArray( np.array([[[1, np.nan], [np.nan, 1]]] * 3), coords={"channel": ["chan1", "chan2", "chan3"], "ping_time": np.arange(2), "range_sample": np.arange(2)}, attrs=source_ds[var_name].attrs ) else: truth_da = xr.DataArray( [[1, np.nan], [np.nan, 1]], coords={"ping_time": np.arange(2), "range_sample": np.arange(2)}, attrs=source_ds[var_name].attrs ) assert masked_ds[var_name].equals(truth_da)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,781
OSOceanAcoustics/echopype
refs/heads/main
/echopype/visualize/cm.py
import numpy as np import matplotlib as mpl __cmap_colors = { 'ek500': { 'rgb': ( np.array( [ [159, 159, 159], # light grey [95, 95, 95], # grey [0, 0, 255], # dark blue [0, 0, 127], # blue [0, 191, 0], # green [0, 127, 0], # dark green [255, 255, 0], # yellow [255, 127, 0], # orange [255, 0, 191], # pink [255, 0, 0], # red [166, 83, 60], # light brown ] ) / 255 ), 'under': '1', # white 'over': np.array([120, 60, 40]) / 255, # dark brown } } def _create_cmap(rgb, under=None, over=None): cmap = mpl.colors.ListedColormap(rgb) if under is not None: cmap.set_under(under) if over is not None: cmap.set_over(over) return cmap cmap_d = {} cmapnames = ['ek500'] # add colormaps and reversed to dictionary for cmapname in cmapnames: colors_d = __cmap_colors[cmapname] rgb = colors_d['rgb'] cmap_d[cmapname] = _create_cmap( rgb, under=colors_d.get('under', None), over=colors_d.get('over', None) ) cmap_d[cmapname].name = cmapname cmap_d[cmapname + '_r'] = _create_cmap( rgb[::-1, :], under=colors_d.get('over', None), over=colors_d.get('under', None), ) cmap_d[cmapname + '_r'].name = cmapname + '_r' # Register the cmap with matplotlib rgb_with_alpha = np.zeros((rgb.shape[0], 4)) rgb_with_alpha[:, :3] = rgb rgb_with_alpha[:, 3] = 1.0 # set alpha channel to 1 reg_map = mpl.colors.ListedColormap( rgb_with_alpha, 'ep.' + cmapname, rgb.shape[0] ) if 'under' in colors_d: reg_map.set_under(colors_d['under']) if 'over' in colors_d: reg_map.set_over(colors_d['over']) mpl.colormaps.register(cmap=reg_map) # Register the reversed map reg_map_r = mpl.colors.ListedColormap( rgb_with_alpha[::-1, :], 'ep.' + cmapname + '_r', rgb.shape[0] ) if 'under' in colors_d: reg_map_r.set_over(colors_d['under']) if 'over' in colors_d: reg_map_r.set_under(colors_d['over']) mpl.colormaps.register(cmap=reg_map_r) # make colormaps available to call locals().update(cmap_d)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,782
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/conftest.py
"""``pytest`` configuration.""" import pytest import fsspec from echopype.testing import TEST_DATA_FOLDER @pytest.fixture(scope="session") def dump_output_dir(): return TEST_DATA_FOLDER / "dump" @pytest.fixture(scope="session") def test_path(): return { 'ROOT': TEST_DATA_FOLDER, 'EA640': TEST_DATA_FOLDER / "ea640", 'EK60': TEST_DATA_FOLDER / "ek60", 'EK80': TEST_DATA_FOLDER / "ek80", 'EK80_NEW': TEST_DATA_FOLDER / "ek80_new", 'ES70': TEST_DATA_FOLDER / "es70", 'ES80': TEST_DATA_FOLDER / "es80", 'AZFP': TEST_DATA_FOLDER / "azfp", 'AD2CP': TEST_DATA_FOLDER / "ad2cp", 'EK80_CAL': TEST_DATA_FOLDER / "ek80_bb_with_calibration", 'EK80_EXT': TEST_DATA_FOLDER / "ek80_ext", 'ECS': TEST_DATA_FOLDER / "ecs", } @pytest.fixture(scope="session") def minio_bucket(): return dict( client_kwargs=dict(endpoint_url="http://localhost:9000/"), key="minioadmin", secret="minioadmin", )
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,783
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/echodata/utils.py
import os import json from pathlib import Path import xarray as xr from datatree import DataTree import numpy as np from echopype.convert.set_groups_base import SetGroupsBase from echopype.echodata.echodata import EchoData class SetGroupsTest(SetGroupsBase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def set_beam(self) -> xr.Dataset: ds = xr.Dataset( attrs={"beam_mode": "vertical", "conversion_equation_t": "type_3"} ) return ds def set_env(self) -> xr.Dataset: # TODO: add mock data ds = xr.Dataset() env_attr_dict = { "notes": "This is a mock env dataset, hence no data is found!" } ds = ds.assign_attrs(env_attr_dict) return ds def set_platform(self) -> xr.Dataset: # TODO: add mock data ds = xr.Dataset( attrs={ "platform_code_ICES": 315, "platform_name": "My mock boat", "platform_type": "Research vessel", } ) return ds def set_nmea(self) -> xr.Dataset: # TODO: add mock data ds = xr.Dataset( attrs={ "description": "All Mock NMEA datagrams", } ) return ds def set_sonar(self) -> xr.Dataset: # TODO: add mock data ds = xr.Dataset() # Assemble sonar group global attribute dictionary sonar_attr_dict = { "sonar_manufacturer": "Simrad", "sonar_model": self.sonar_model, # transducer (sonar) serial number is not stored in the EK60 raw data file, # so sonar_serial_number can't be populated from the raw datagrams "sonar_serial_number": "", "sonar_software_name": "", "sonar_software_version": "0.1.0", "sonar_type": "echosounder", } ds = ds.assign_attrs(sonar_attr_dict) return ds def set_vendor(self) -> xr.Dataset: # TODO: add mock data ds = xr.Dataset(attrs={"created_by": "Mock test"}) return ds def get_mock_echodata( sonar_model='TEST', file_chk='./test.raw', xml_chk=None, ): # Setup tree dictionary tree_dict = {} setgrouper = SetGroupsTest( parser_obj=None, input_file=file_chk, xml_path=xml_chk, output_path=None, sonar_model=sonar_model, params={"survey_name": "mock_survey"}, ) tree_dict["/"] = setgrouper.set_toplevel( sonar_model, date_created=np.datetime64("1970-01-01") ) tree_dict["Environment"] = setgrouper.set_env() tree_dict["Platform"] = setgrouper.set_platform() tree_dict["Platform/NMEA"] = setgrouper.set_nmea() tree_dict["Provenance"] = setgrouper.set_provenance() tree_dict["Sonar"] = None tree_dict["Sonar/Beam_group1"] = setgrouper.set_beam() tree_dict["Sonar"] = setgrouper.set_sonar() tree_dict["Vendor_specific"] = setgrouper.set_vendor() tree = DataTree.from_dict(tree_dict, name="root") echodata = EchoData( source_file=file_chk, xml_path=xml_chk, sonar_model=sonar_model ) echodata._set_tree(tree) echodata._load_tree() return echodata def check_consolidated(echodata: EchoData, zmeta_path: Path) -> None: """ Checks for the presence of `.zgroup` for every group in echodata within the `.zmetadata` file. Parameters ---------- echodata : EchoData The echodata object to be checked. zmeta_path : pathlib.Path The path to the .zmetadata for the zarr file. """ # Check that every group is in # the zmetadata if consolidated expected_zgroups = [ os.path.join(p, '.zgroup') if p != 'Top-level' else '.zgroup' for p in echodata.group_paths ] with open(zmeta_path) as f: meta_json = json.load(f) file_groups = [ k for k in meta_json['metadata'].keys() if k.endswith('.zgroup') ] for g in expected_zgroups: assert g in file_groups, f"{g} not Found!"
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,784
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/commongrid/test_mvbs.py
import dask.array import numpy as np from numpy.random import default_rng import pandas as pd import pytest from typing import Tuple, Iterable, Union import xarray as xr import echopype as ep from echopype.commongrid.mvbs import bin_and_mean_2d @pytest.fixture( params=[ ( ("EK60", "ncei-wcsd", "Summer2017-D20170719-T211347.raw"), "EK60", None, {}, ), ( ("EK80_NEW", "echopype-test-D20211004-T235930.raw"), "EK80", None, {'waveform_mode': 'BB', 'encode_mode': 'complex'}, ), ( ("EK80_NEW", "D20211004-T233354.raw"), "EK80", None, {'waveform_mode': 'CW', 'encode_mode': 'power'}, ), ( ("EK80_NEW", "D20211004-T233115.raw"), "EK80", None, {'waveform_mode': 'CW', 'encode_mode': 'complex'}, ), (("ES70", "D20151202-T020259.raw"), "ES70", None, {}), (("AZFP", "17082117.01A"), "AZFP", ("AZFP", "17041823.XML"), {}), ( ("AD2CP", "raw", "090", "rawtest.090.00001.ad2cp"), "AD2CP", None, {}, ), ], ids=[ "ek60_cw_power", "ek80_bb_complex", "ek80_cw_power", "ek80_cw_complex", "es70", "azfp", "ad2cp", ], ) def test_data_samples(request, test_path): ( filepath, sonar_model, azfp_xml_path, range_kwargs, ) = request.param if sonar_model.lower() in ['es70', 'ad2cp']: pytest.xfail( reason="Not supported at the moment", ) path_model, *paths = filepath filepath = test_path[path_model].joinpath(*paths) if azfp_xml_path is not None: path_model, *paths = azfp_xml_path azfp_xml_path = test_path[path_model].joinpath(*paths) return ( filepath, sonar_model, azfp_xml_path, range_kwargs, ) def _construct_MVBS_toy_data( nchan, npings, nrange_samples, ping_size, range_sample_size ): """Construct data with values that increase every ping_num and ``range_sample_num`` so that the result of computing MVBS is a smaller array that increases regularly for each resampled ``ping_time`` and ``range_sample`` Parameters ---------- nchan : int number of channels npings : int number of pings nrange_samples : int number of range samples ping_size : int number of pings with the same value range_sample_size : int number of range samples with the same value Returns ------- np.ndarray Array with blocks of ``ping_time`` and ``range_sample`` with the same value, so that computing the MVBS will result in regularly increasing values every row and column """ data = np.ones((nchan, npings, nrange_samples)) for p_i, ping in enumerate(range(0, npings, ping_size)): for r_i, rb in enumerate(range(0, nrange_samples, range_sample_size)): data[0, ping : ping + ping_size, rb : rb + range_sample_size] += ( r_i + p_i ) # First channel increases by 1 each row and column, second increases by 2, third by 3, etc. for f in range(nchan): data[f] = data[0] * (f + 1) return data def _construct_MVBS_test_data(nchan, npings, nrange_samples): """Construct data for testing the toy data from `_construct_MVBS_toy_data` after it has gone through the MVBS calculation. Parameters ---------- nchan : int number of channels npings : int number of pings nrange_samples : int number of range samples Returns ------- np.ndarray Array with values that increases regularly every ping and range sample """ # Construct test array test_array = np.add(*np.indices((npings, nrange_samples))) return np.array([(test_array + 1) * (f + 1) for f in range(nchan)]) def test_compute_MVBS_index_binning(): """Test compute_MVBS_index_binning on toy data""" # Parameters for toy data nchan, npings, nrange_samples = 4, 40, 400 ping_num = 3 # number of pings to average over range_sample_num = 7 # number of range_samples to average over # Construct toy data that increases regularly every ping_num and range_sample_num data = _construct_MVBS_toy_data( nchan=nchan, npings=npings, nrange_samples=nrange_samples, ping_size=ping_num, range_sample_size=range_sample_num, ) data_log = 10 * np.log10(data) # Convert to log domain chan_index = np.arange(nchan).astype(str) ping_index = np.arange(npings) range_sample = np.arange(nrange_samples) Sv = xr.DataArray( data_log, coords=[ ('channel', chan_index), ('ping_time', ping_index), ('range_sample', range_sample), ], ) Sv.name = "Sv" ds_Sv = Sv.to_dataset() ds_Sv["frequency_nominal"] = chan_index # just so there's value in freq_nominal ds_Sv = ds_Sv.assign( echo_range=xr.DataArray( np.array([[np.linspace(0, 10, nrange_samples)] * npings] * nchan), coords=Sv.coords, ) ) # Binned MVBS test ds_MVBS = ep.commongrid.compute_MVBS_index_binning( ds_Sv, range_sample_num=range_sample_num, ping_num=ping_num ) data_test = 10 ** (ds_MVBS.Sv / 10) # Convert to linear domain # Shape test data_binned_shape = np.ceil( (nchan, npings / ping_num, nrange_samples / range_sample_num) ).astype(int) assert np.all(data_test.shape == data_binned_shape) # Construct test array that increases by 1 for each range_sample and ping_time test_array = _construct_MVBS_test_data( nchan, data_binned_shape[1], data_binned_shape[2] ) # Test all values in MVBS assert np.allclose(data_test, test_array, rtol=0, atol=1e-12) def _coll_test_comp_MVBS(ds_Sv, nchan, ping_num, range_sample_num, ping_time_bin, total_range, range_meter_bin): """A collection of tests for test_compute_MVBS""" ds_MVBS = ep.commongrid.compute_MVBS( ds_Sv, range_meter_bin=range_meter_bin, ping_time_bin=f'{ping_time_bin}S', ) data_test = 10 ** (ds_MVBS.Sv / 10) # Convert to linear domain # Shape test data_binned_shape = np.ceil((nchan, ping_num, range_sample_num)).astype(int) assert np.all(data_test.shape == data_binned_shape) # Construct test array that increases by 1 for each range_sample and ping_time test_array = _construct_MVBS_test_data( nchan, data_binned_shape[1], data_binned_shape[2] ) # Test all values in MVBS assert np.allclose(data_test, test_array, rtol=0, atol=1e-12) # Test to see if ping_time was resampled correctly test_ping_time = pd.date_range( '1/1/2020', periods=np.ceil(ping_num), freq=f'{ping_time_bin}S' ) assert np.array_equal(data_test.ping_time, test_ping_time) # Test to see if range was resampled correctly test_range = np.arange(0, total_range, range_meter_bin) assert np.array_equal(data_test.echo_range, test_range) def _fill_w_nans(narr, nan_ping_time, nan_range_sample): """ A routine that fills a numpy array with nans. Parameters ---------- narr : numpy array Array of dimensions (ping_time, range_sample) nan_ping_time : list ping times to fill with nans nan_range_sample: list range samples to fill with nans """ if len(nan_ping_time) != len(nan_range_sample): raise ValueError('These lists must be the same size!') # fill in nans according to the provided lists for i, j in zip(nan_ping_time, nan_range_sample): narr[i, j] = np.nan return narr def _nan_cases_comp_MVBS(ds_Sv, chan): """ For a single channel, obtains numpy array filled with nans for various cases """ # get echo_range values for a single channel one_chan_er = ds_Sv.echo_range.sel(channel=chan).copy().values # ping times to fill with NaNs nan_ping_time_1 = [slice(None), slice(None)] # range samples to fill with NaNs nan_range_sample_1 = [3, 4] # pad all ping_times with nans for a certain range_sample case_1 = _fill_w_nans(one_chan_er, nan_ping_time_1, nan_range_sample_1) # get echo_range values for a single channel one_chan_er = ds_Sv.echo_range.sel(channel=chan).copy().values # ping times to fill with NaNs nan_ping_time_2 = [1, 3, 5, 9] # range samples to fill with NaNs nan_range_sample_2 = [slice(None), slice(None), slice(None), slice(None)] # pad all range_samples of certain ping_times case_2 = _fill_w_nans(one_chan_er, nan_ping_time_2, nan_range_sample_2) # get echo_range values for a single channel one_chan_er = ds_Sv.echo_range.sel(channel=chan).copy().values # ping times to fill with NaNs nan_ping_time_3 = [0, 2, 5, 7] # range samples to fill with NaNs nan_range_sample_3 = [slice(0, 2), slice(None), slice(None), slice(0, 3)] # pad all range_samples of certain ping_times and # pad some ping_times with nans for a certain range_sample case_3 = _fill_w_nans(one_chan_er, nan_ping_time_3, nan_range_sample_3) return case_1, case_2, case_3 def test_compute_MVBS(): """Test compute_MVBS on toy data""" # Parameters for fake data nchan, npings, nrange_samples = 4, 100, 4000 range_meter_bin = 7 # range in meters to average over ping_time_bin = 3 # number of seconds to average over ping_rate = 2 # Number of pings per second range_sample_per_meter = 30 # Number of range_samples per meter # Useful conversions ping_num = ( npings / ping_rate / ping_time_bin ) # number of pings to average over range_sample_num = ( nrange_samples / range_sample_per_meter / range_meter_bin ) # number of range_samples to average over total_range = nrange_samples / range_sample_per_meter # total range in meters # Construct data with values that increase with range and time # so that when compute_MVBS is performed, the result is a smaller array # that increases by a constant for each meter_bin and time_bin data = _construct_MVBS_toy_data( nchan=nchan, npings=npings, nrange_samples=nrange_samples, ping_size=ping_rate * ping_time_bin, range_sample_size=range_sample_per_meter * range_meter_bin, ) data_log = 10 * np.log10(data) # Convert to log domain chan_index = np.arange(nchan).astype(str) freq_nom = np.arange(nchan) # Generate a date range with `npings` number of pings with the frequency of the ping_rate ping_time = pd.date_range( '1/1/2020', periods=npings, freq=f'{1/ping_rate}S' ) range_sample = np.arange(nrange_samples) Sv = xr.DataArray( data_log, coords=[ ('channel', chan_index), ('ping_time', ping_time), ('range_sample', range_sample), ], ) Sv.name = "Sv" ds_Sv = Sv.to_dataset() ds_Sv = ds_Sv.assign( frequency_nominal=xr.DataArray(freq_nom, coords={'channel': chan_index}), echo_range=xr.DataArray( np.array( [[np.linspace(0, total_range, nrange_samples)] * npings] * nchan ), coords=Sv.coords, ) ) # initial test of compute_MVBS _coll_test_comp_MVBS(ds_Sv, nchan, ping_num, range_sample_num, ping_time_bin, total_range, range_meter_bin) # TODO: use @pytest.fixture params/ids # for multiple similar tests using the same set of parameters # different nan cases for a single channel case_1, case_2, case_3 = _nan_cases_comp_MVBS(ds_Sv, chan='0') # pad all ping_times with nans for a certain range_sample ds_Sv['echo_range'].loc[{'channel': '0'}] = case_1 _coll_test_comp_MVBS(ds_Sv, nchan, ping_num, range_sample_num, ping_time_bin, total_range, range_meter_bin) # pad all range_samples of certain ping_times ds_Sv['echo_range'].loc[{'channel': '0'}] = case_2 _coll_test_comp_MVBS(ds_Sv, nchan, ping_num, range_sample_num, ping_time_bin, total_range, range_meter_bin) # pad all range_samples of certain ping_times and # pad some ping_times with nans for a certain range_sample ds_Sv['echo_range'].loc[{'channel': '0'}] = case_3 _coll_test_comp_MVBS(ds_Sv, nchan, ping_num, range_sample_num, ping_time_bin, total_range, range_meter_bin) def test_commongrid_mvbs(test_data_samples): """ Test running through from open_raw to compute_MVBS. """ ( filepath, sonar_model, azfp_xml_path, range_kwargs, ) = test_data_samples ed = ep.open_raw(filepath, sonar_model, azfp_xml_path) if ed.sonar_model.lower() == 'azfp': avg_temperature = ed["Environment"]['temperature'].values.mean() env_params = { 'temperature': avg_temperature, 'salinity': 27.9, 'pressure': 59, } range_kwargs['env_params'] = env_params if 'azfp_cal_type' in range_kwargs: range_kwargs.pop('azfp_cal_type') Sv = ep.calibrate.compute_Sv(ed, **range_kwargs) assert ep.commongrid.compute_MVBS(Sv) is not None def create_bins(csum_array: np.ndarray) -> Iterable: """ Constructs bin ranges based off of a cumulative sum array. Parameters ---------- csum_array: np.ndarray 1D array representing a cumulative sum Returns ------- bins: list A list whose elements are the lower and upper bin ranges """ bins = [] # construct bins for count, csum in enumerate(csum_array): if count == 0: bins.append([0, csum]) else: # add 0.01 so that left bins don't overlap bins.append([csum_array[count-1] + 0.01, csum]) return bins def create_echo_range_related_data(ping_bins: Iterable, num_pings_in_bin: np.ndarray, er_range: list, er_bins: Iterable, final_num_er_bins: int, create_dask: bool, rng: np.random.Generator, ping_bin_nan_ind: int) -> Tuple[list, list, list]: """ Creates ``echo_range`` values and associated bin information. Parameters ---------- ping_bins: list A list whose elements are the lower and upper ping time bin ranges num_pings_in_bin: np.ndarray Specifies the number of pings in each ping time bin er_range: list A list whose first element is the lowest and second element is the highest possible number of echo range values in a given bin er_bins: list A list whose elements are the lower and upper echo range bin ranges final_num_er_bins: int The total number of echo range bins create_dask: bool If True ``final_arrays`` values will be dask arrays, else they will be numpy arrays rng: np.random.Generator The generator for random values ping_bin_nan_ind: int The ping bin index to fill with NaNs Returns ------- all_er_bin_nums: list of np.ndarray A list whose elements are the number of values in each echo_range bin, for each ping bin ping_times_in_bin: list of np.ndarray A list whose elements are the ping_time values for each corresponding bin final_arrays: list of np.ndarray or dask.array.Array A list whose elements are the echo_range values for a given ping and echo range bin block """ final_arrays = [] all_er_bin_nums = [] ping_times_in_bin = [] # build echo_range array for ping_ind, ping_bin in enumerate(ping_bins): # create the ping times associated with each ping bin ping_times_in_bin.append(rng.uniform(ping_bin[0], ping_bin[1], (num_pings_in_bin[ping_ind],))) # randomly determine the number of values in each echo_range bin num_er_in_bin = rng.integers(low=er_range[0], high=er_range[1], size=final_num_er_bins) # store the number of values in each echo_range bin all_er_bin_nums.append(num_er_in_bin) er_row_block = [] for count, bin_val in enumerate(er_bins): # create a block of echo_range values if create_dask: a = dask.array.random.uniform(bin_val[0], bin_val[1], (num_pings_in_bin[ping_ind], num_er_in_bin[count])) else: a = rng.uniform(bin_val[0], bin_val[1], (num_pings_in_bin[ping_ind], num_er_in_bin[count])) # store the block of echo_range values er_row_block.append(a) # set all echo_range values at ping index to NaN if ping_ind == ping_bin_nan_ind: a[:, :] = np.nan # collect and construct echo_range row block final_arrays.append(np.concatenate(er_row_block, axis=1)) return all_er_bin_nums, ping_times_in_bin, final_arrays def construct_2d_echo_range_array(final_arrays: Iterable[np.ndarray], ping_csum: np.ndarray, create_dask: bool) -> Tuple[Union[np.ndarray, dask.array.Array], int]: """ Creates the final 2D ``echo_range`` array with appropriate padding. Parameters ---------- final_arrays: list of np.ndarray A list whose elements are the echo_range values for a given ping and echo range bin block ping_csum: np.ndarray 1D array representing the cumulative sum for the number of ping times in each ping bin create_dask: bool If True ``final_er`` will be a dask array, else it will be a numpy array Returns ------- final_er: np.ndarray or dask.array.Array The final 2D ``echo_range`` array max_num_er_elem: int The maximum number of ``echo_range`` elements amongst all times """ # get maximum number of echo_range elements amongst all times max_num_er_elem = max([arr.shape[1] for arr in final_arrays]) # total number of ping times tot_num_times = ping_csum[-1] # pad echo_range dimension with nans and create final echo_range if create_dask: final_er = dask.array.ones(shape=(tot_num_times, max_num_er_elem)) * np.nan else: final_er = np.empty((tot_num_times, max_num_er_elem)) final_er[:] = np.nan for count, arr in enumerate(final_arrays): if count == 0: final_er[0:ping_csum[count], 0:arr.shape[1]] = arr else: final_er[ping_csum[count - 1]:ping_csum[count], 0:arr.shape[1]] = arr return final_er, max_num_er_elem def construct_2d_sv_array(max_num_er_elem: int, ping_csum: np.ndarray, all_er_bin_nums: Iterable[np.ndarray], num_pings_in_bin: np.ndarray, create_dask: bool, ping_bin_nan_ind: int) -> Tuple[Union[np.ndarray, dask.array.Array], np.ndarray]: """ Creates the final 2D Sv array with appropriate padding. Parameters ---------- max_num_er_elem: int The maximum number of ``echo_range`` elements amongst all times ping_csum: np.ndarray 1D array representing the cumulative sum for the number of ping times in each ping bin all_er_bin_nums: list of np.ndarray A list whose elements are the number of values in each echo_range bin, for each ping bin num_pings_in_bin: np.ndarray Specifies the number of pings in each ping time bin create_dask: bool If True ``final_sv`` will be a dask array, else it will be a numpy array ping_bin_nan_ind: int The ping bin index to fill with NaNs Returns ------- final_sv: np.ndarray or dask.array.Array The final 2D Sv array final_MVBS: np.ndarray The final 2D known MVBS array """ # total number of ping times tot_num_times = ping_csum[-1] # pad echo_range dimension with nans and create final sv if create_dask: final_sv = dask.array.ones(shape=(tot_num_times, max_num_er_elem)) * np.nan else: final_sv = np.empty((tot_num_times, max_num_er_elem)) final_sv[:] = np.nan final_means = [] for count, arr in enumerate(all_er_bin_nums): # create sv row values using natural numbers sv_row_list = [np.arange(1, num_elem + 1, 1, dtype=np.float64) for num_elem in arr] # create final sv row sv_row = np.concatenate(sv_row_list) # get final mean which is n+1/2 (since we are using natural numbers) ping_mean = [(len(elem) + 1) / 2.0 for elem in sv_row_list] # create sv row block sv_row_block = np.tile(sv_row, (num_pings_in_bin[count], 1)) if count == ping_bin_nan_ind: # fill values with NaNs ping_mean = [np.nan]*len(sv_row_list) sv_row_block[:, :] = np.nan # store means for ping final_means.append(ping_mean) if count == 0: final_sv[0:ping_csum[count], 0:sv_row_block.shape[1]] = sv_row_block else: final_sv[ping_csum[count - 1]:ping_csum[count], 0:sv_row_block.shape[1]] = sv_row_block # create final sv MVBS final_MVBS = np.vstack(final_means) return final_sv, final_MVBS def create_known_mean_data(final_num_ping_bins: int, final_num_er_bins: int, ping_range: list, er_range: list, create_dask: bool, rng: np.random.Generator) -> Tuple[np.ndarray, np.ndarray, Iterable, Iterable, np.ndarray, np.ndarray]: """ Orchestrates the creation of ``echo_range``, ``ping_time``, and ``Sv`` arrays where the MVBS is known. Parameters ---------- final_num_ping_bins: int The total number of ping time bins final_num_er_bins: int The total number of echo range bins ping_range: list A list whose first element is the lowest and second element is the highest possible number of ping time values in a given bin er_range: list A list whose first element is the lowest and second element is the highest possible number of echo range values in a given bin create_dask: bool If True the ``Sv`` and ``echo_range`` values produced will be dask arrays, else they will be numpy arrays. rng: np.random.Generator generator for random integers Returns ------- final_MVBS: np.ndarray The final 2D known MVBS array final_sv: np.ndarray The final 2D Sv array ping_bins: Iterable A list whose elements are the lower and upper ping time bin ranges er_bins: Iterable A list whose elements are the lower and upper echo range bin ranges final_er: np.ndarray The final 2D ``echo_range`` array final_ping_time: np.ndarray The final 1D ``ping_time`` array """ # randomly generate the number of pings in each ping bin num_pings_in_bin = rng.integers(low=ping_range[0], high=ping_range[1], size=final_num_ping_bins) # create bins for ping_time dimension ping_csum = np.cumsum(num_pings_in_bin) ping_bins = create_bins(ping_csum) # create bins for echo_range dimension num_er_in_bin = rng.integers(low=er_range[0], high=er_range[1], size=final_num_er_bins) er_csum = np.cumsum(num_er_in_bin) er_bins = create_bins(er_csum) # randomly select one ping bin to fill with NaNs ping_bin_nan_ind = rng.choice(len(ping_bins)) # create the echo_range data and associated bin information all_er_bin_nums, ping_times_in_bin, final_er_arrays = create_echo_range_related_data(ping_bins, num_pings_in_bin, er_range, er_bins, final_num_er_bins, create_dask, rng, ping_bin_nan_ind) # create the final echo_range array using created data and padding final_er, max_num_er_elem = construct_2d_echo_range_array(final_er_arrays, ping_csum, create_dask) # get final ping_time dimension final_ping_time = np.concatenate(ping_times_in_bin).astype('datetime64[ns]') # create the final sv array final_sv, final_MVBS = construct_2d_sv_array(max_num_er_elem, ping_csum, all_er_bin_nums, num_pings_in_bin, create_dask, ping_bin_nan_ind) return final_MVBS, final_sv, ping_bins, er_bins, final_er, final_ping_time @pytest.fixture( params=[ { "create_dask": True, "final_num_ping_bins": 10, "final_num_er_bins": 10, "ping_range": [10, 1000], "er_range": [10, 1000] }, { "create_dask": False, "final_num_ping_bins": 10, "final_num_er_bins": 10, "ping_range": [10, 1000], "er_range": [10, 1000] }, ], ids=[ "delayed_data", "in_memory_data" ], ) def bin_and_mean_2d_params(request): """ Obtains all necessary parameters for ``test_bin_and_mean_2d``. """ return list(request.param.values()) def test_bin_and_mean_2d(bin_and_mean_2d_params) -> None: """ Tests the function ``bin_and_mean_2d``, which is the core method for ``compute_MVBS``. This is done by creating mock data (which can have varying number of ``echo_range`` values for each ``ping_time``) with known means. Parameters ---------- create_dask: bool If True the ``Sv`` and ``echo_range`` values produced will be dask arrays, else they will be numpy arrays. final_num_ping_bins: int The total number of ping time bins final_num_er_bins: int The total number of echo range bins ping_range: list A list whose first element is the lowest and second element is the highest possible number of ping time values in a given bin er_range: list A list whose first element is the lowest and second element is the highest possible number of echo range values in a given bin """ # get all parameters needed to create the mock data create_dask, final_num_ping_bins, final_num_er_bins, ping_range, er_range = bin_and_mean_2d_params # randomly generate a seed seed = np.random.randint(low=10, high=100000, size=1)[0] print(f"seed used to generate mock data: {seed}") # establish generator for random integers rng = default_rng(seed=seed) # seed dask random generator if create_dask: dask.array.random.seed(seed=seed) # create echo_range, ping_time, and Sv arrays where the MVBS is known known_MVBS, final_sv, ping_bins, er_bins, final_er, final_ping_time = create_known_mean_data(final_num_ping_bins, final_num_er_bins, ping_range, er_range, create_dask, rng) # put the created ping bins into a form that works with bin_and_mean_2d digitize_ping_bin = np.array([*ping_bins[0]] + [bin_val[1] for bin_val in ping_bins[1:-1]]) digitize_ping_bin = digitize_ping_bin.astype('datetime64[ns]') # put the created echo range bins into a form that works with bin_and_mean_2d digitize_er_bin = np.array([*er_bins[0]] + [bin_val[1] for bin_val in er_bins[1:]]) # calculate MVBS for mock data set calc_MVBS = bin_and_mean_2d(arr=final_sv, bins_time=digitize_ping_bin, bins_er=digitize_er_bin, times=final_ping_time, echo_range=final_er, comprehensive_er_check=True) # compare known MVBS solution against its calculated counterpart assert np.allclose(calc_MVBS, known_MVBS, atol=1e-10, rtol=1e-10, equal_nan=True)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,785
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/calibrate/test_cal_params_integration.py
import pytest import numpy as np import xarray as xr import echopype as ep @pytest.fixture def azfp_path(test_path): return test_path['AZFP'] @pytest.fixture def ek60_path(test_path): return test_path['EK60'] @pytest.fixture def ek80_cal_path(test_path): return test_path['EK80_CAL'] def test_cal_params_intake_AZFP(azfp_path): """ Test cal param intake for AZFP calibration. """ azfp_01a_path = str(azfp_path.joinpath('17082117.01A')) azfp_xml_path = str(azfp_path.joinpath('17041823.XML')) ed = ep.open_raw(azfp_01a_path, sonar_model='AZFP', xml_path=azfp_xml_path) # Assemble external cal param and env params chan = ed["Sonar/Beam_group1"]["channel"] EL_ext = xr.DataArray([100, 200, 300, 400], dims=["channel"], coords={"channel": chan}, name="EL") env_ext = {"salinity": 30, "pressure": 10} # salinity and pressure required for AZFP cal # Manually go through cal params intake cal_params_manual = ep.calibrate.cal_params.get_cal_params_AZFP( beam=ed["Sonar/Beam_group1"], vend=ed["Vendor_specific"], user_dict={"EL": EL_ext} ) # Manually add cal params in Vendor group and construct cal object cal_obj = ep.calibrate.calibrate_azfp.CalibrateAZFP( echodata=ed, cal_params={"EL": EL_ext}, env_params=env_ext ) # Check cal params ingested from both ways assert cal_obj.cal_params["EL"].identical(cal_params_manual["EL"]) # Check against the final cal params in the calibration output ds_Sv = ep.calibrate.compute_Sv(ed, cal_params={"EL": EL_ext}, env_params=env_ext) assert ds_Sv["EL"].identical(cal_params_manual["EL"]) def test_cal_params_intake_EK60(ek60_path): """ Test cal param intake for EK60 calibration. """ ed = ep.open_raw(ek60_path / "ncei-wcsd" / "Summer2017-D20170620-T011027.raw", sonar_model="EK60") # Assemble external cal param chan = ed["Sonar/Beam_group1"]["channel"] gain_ext = xr.DataArray([100, 200, 300], dims=["channel"], coords={"channel": chan}, name="gain_correction") # Manually go through cal params intake cal_params_manual = ep.calibrate.cal_params.get_cal_params_EK( waveform_mode="CW", freq_center=ed["Sonar/Beam_group1"]["frequency_nominal"], beam=ed["Sonar/Beam_group1"], vend=ed["Vendor_specific"], user_dict={"gain_correction": gain_ext}, sonar_type="EK60", ) # Manually add cal params in Vendor group and construct cal object ed["Vendor_specific"]["gain_correction"].data[0, 1] = gain_ext.data[0] # GPT 18 kHz 009072058c8d 1-1 ES18-11 ed["Vendor_specific"]["gain_correction"].data[1, 2] = gain_ext.data[1] # GPT 38 kHz 009072058146 2-1 ES38B ed["Vendor_specific"]["gain_correction"].data[2, 4] = gain_ext.data[2] # GPT 120 kHz 00907205a6d0 4-1 ES120-7C cal_obj = ep.calibrate.calibrate_ek.CalibrateEK60(echodata=ed, env_params=None, cal_params=None, ecs_file=None) # Check cal params ingested from both ways # Need to drop ping_time for cal_obj.cal_params since get_vend_cal_params_power # retrieves sa_correction or gain_correction based on transmit_duration_nominal, # which can vary cross ping_time assert cal_obj.cal_params["gain_correction"].isel(ping_time=0).drop("ping_time").identical(cal_params_manual["gain_correction"]) # Check against the final cal params in the calibration output ds_Sv = ep.calibrate.compute_Sv(ed, cal_params={"gain_correction": gain_ext}) assert ds_Sv["gain_correction"].identical(cal_params_manual["gain_correction"]) def test_cal_params_intake_EK80_BB_complex(ek80_cal_path): """ Test frequency-dependent cal param intake for EK80 BB complex calibration. """ ed = ep.open_raw(ek80_cal_path / "2018115-D20181213-T094600.raw", sonar_model="EK80") # BB channels chan_sel = ["WBT 714590-15 ES70-7C", "WBT 714596-15 ES38-7"] # Assemble external freq-dependent cal param len_cal_frequency = ed["Vendor_specific"]["cal_frequency"].size gain_freq_dep = xr.DataArray( np.array([np.arange(len_cal_frequency), (np.arange(len_cal_frequency) + 1000)[::-1]]), dims=["cal_channel_id", "cal_frequency"], coords={ "cal_channel_id": chan_sel, "cal_frequency": ed["Vendor_specific"]["cal_frequency"], }, ) # Manually go through cal params intake beam = ed["Sonar/Beam_group1"].sel(channel=chan_sel) vend = ed["Vendor_specific"].sel(channel=chan_sel) freq_center = ( (beam["transmit_frequency_start"] + beam["transmit_frequency_stop"]).sel(channel=chan_sel) / 2) cal_params_manual = ep.calibrate.cal_params.get_cal_params_EK( "BB", freq_center, beam, vend, {"gain_correction": gain_freq_dep} ) # Manually add freq-dependent cal params in Vendor group # and construct cal object ed["Vendor_specific"]["gain"].data[1, :] = gain_freq_dep[0, :] # WBT 714590-15 ES70-7C ed["Vendor_specific"]["gain"].data[2, :] = gain_freq_dep[1, :] # WBT 714596-15 ES38-7 cal_obj = ep.calibrate.calibrate_ek.CalibrateEK80( echodata=ed, waveform_mode="BB", encode_mode="complex", cal_params=None, env_params=None ) # Check cal params ingested from both ways assert cal_obj.cal_params["gain_correction"].identical(cal_params_manual["gain_correction"]) # Check against the final cal params in the calibration output ds_Sv = ep.calibrate.compute_Sv( ed, waveform_mode="BB", encode_mode="complex", cal_params={"gain_correction": gain_freq_dep} ) cal_params_manual["gain_correction"].name = "gain_correction" assert ds_Sv["gain_correction"].identical(cal_params_manual["gain_correction"]) def test_cal_params_intake_EK80_CW_complex(ek80_cal_path): """ Test frequency-dependent cal param intake for EK80 CW complex calibration. """ ed = ep.open_raw(ek80_cal_path / "2018115-D20181213-T094600.raw", sonar_model="EK80") # CW channels chan_sel = ["WBT 714581-15 ES18", "WBT 714583-15 ES120-7C", "WBT 714597-15 ES333-7C", "WBT 714605-15 ES200-7C"] # Assemble external freq-dependent cal param len_cal_frequency = ed["Vendor_specific"]["cal_frequency"].size gain_freq_dep = xr.DataArray( np.array([ np.arange(len_cal_frequency), (np.arange(len_cal_frequency) + 1000)[::-1], (np.arange(len_cal_frequency) + 2000)[::-1], (np.arange(len_cal_frequency) + 3000)[::-1], ]), dims=["cal_channel_id", "cal_frequency"], coords={ "cal_channel_id": chan_sel, "cal_frequency": ed["Vendor_specific"]["cal_frequency"], }, ) # Manually go through cal params intake beam = ed["Sonar/Beam_group1"].sel(channel=chan_sel) vend = ed["Vendor_specific"].sel(channel=chan_sel) freq_center = beam["frequency_nominal"].sel(channel=chan_sel) cal_params_manual = ep.calibrate.cal_params.get_cal_params_EK( "CW", freq_center, beam, vend, {"gain_correction": gain_freq_dep} ) cal_params_manual["gain_correction"].name = "gain_correction" # Manually add cal params in Vendor group construct cal object ed["Vendor_specific"]["gain_correction"].data[0, 1] = cal_params_manual["gain_correction"].data[0] # WBT 714581-15 ES18 ed["Vendor_specific"]["gain_correction"].data[1, 4] = cal_params_manual["gain_correction"].data[1] # WBT 714583-15 ES120-7C ed["Vendor_specific"]["gain_correction"].data[4, 4] = cal_params_manual["gain_correction"].data[2] # WBT 714597-15 ES333-7C ed["Vendor_specific"]["gain_correction"].data[5, 4] = cal_params_manual["gain_correction"].data[3] # WBT 714605-15 ES200-7C cal_obj = ep.calibrate.calibrate_ek.CalibrateEK80( echodata=ed, waveform_mode="CW", encode_mode="complex", cal_params=None, env_params=None ) # Check cal params ingested from both ways # Need to drop ping_time for cal_obj.cal_params since get_vend_cal_params_power # retrieves sa_correction or gain_correction based on transmit_duration_nominal, # which can vary cross ping_time assert cal_obj.cal_params["gain_correction"].isel(ping_time=0).drop("ping_time").identical(cal_params_manual["gain_correction"]) # Check against the final cal params in the calibration output ds_Sv = ep.calibrate.compute_Sv( ed, waveform_mode="CW", encode_mode="complex", cal_params={"gain_correction": gain_freq_dep} ) assert ds_Sv["gain_correction"].identical(cal_params_manual["gain_correction"])
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,786
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/test_core.py
from typing import TYPE_CHECKING import tempfile from pathlib import Path import pytest if TYPE_CHECKING: from echopype.core import SonarModelsHint from echopype.core import SONAR_MODELS import echopype.core @pytest.mark.parametrize( ["sonar_model", "ext"], [ ("AZFP", ".01A"), ("AZFP", ".01a"), ("AZFP", ".05C"), ("AZFP", ".12q"), ("EK60", ".raw"), ("EK60", ".RAW"), ("EK80", ".raw"), ("EK80", ".RAW"), ("EA640", ".raw"), ("EA640", ".RAW"), ("AD2CP", ".ad2cp"), ("AD2CP", ".AD2CP"), ], ) def test_file_extension_validation(sonar_model: "SonarModelsHint", ext: str): SONAR_MODELS[sonar_model]["validate_ext"](ext) @pytest.mark.parametrize( ["sonar_model", "ext"], [ ("AZFP", ".001A"), ("AZFP", ".01AA"), ("AZFP", ".01aa"), ("AZFP", ".05AA"), ("AZFP", ".07!"), ("AZFP", ".01!"), ("AZFP", ".0!A"), ("AZFP", ".012"), ("AZFP", ".0AA"), ("AZFP", ".AAA"), ("AZFP", "01A"), ("EK60", "raw"), ("EK60", ".foo"), ("EK80", "raw"), ("EK80", ".foo"), ("EA640", "raw"), ("EA640", ".foo"), ("AD2CP", "ad2cp"), ("AD2CP", ".foo"), ], ) def test_file_extension_validation_should_fail( sonar_model: "SonarModelsHint", ext: str ): try: SONAR_MODELS[sonar_model]["validate_ext"](ext) except ValueError: pass else: raise ValueError( f"\"{ext}\" should have been rejected for sonar model {sonar_model}" )
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,787
OSOceanAcoustics/echopype
refs/heads/main
/echopype/calibrate/calibrate_azfp.py
import numpy as np from ..echodata import EchoData from .cal_params import get_cal_params_AZFP from .calibrate_ek import CalibrateBase from .env_params import get_env_params_AZFP from .range import compute_range_AZFP class CalibrateAZFP(CalibrateBase): def __init__( self, echodata: EchoData, env_params=None, cal_params=None, ecs_file=None, **kwargs ): super().__init__(echodata, env_params, cal_params, ecs_file) # Set sonar_type self.sonar_type = "AZFP" # Screen for ECS file: currently not support if self.ecs_file is not None: raise ValueError("Using ECS file for calibration is not currently supported for AZFP!") # load env and cal parameters self.env_params = get_env_params_AZFP(echodata=self.echodata, user_dict=self.env_params) self.cal_params = get_cal_params_AZFP( beam=self.echodata["Sonar/Beam_group1"], vend=self.echodata["Vendor_specific"], user_dict=self.cal_params, ) # self.range_meter computed under self._cal_power_samples() # because the implementation is different for Sv and TS def compute_echo_range(self, cal_type): """Calculate range (``echo_range``) in meter using AZFP formula. Note the range calculation differs for Sv and TS per AZFP matlab code. Parameters ---------- cal_type : str 'Sv' for calculating volume backscattering strength, or 'TS' for calculating target strength """ self.range_meter = compute_range_AZFP( echodata=self.echodata, env_params=self.env_params, cal_type=cal_type ) def _cal_power_samples(self, cal_type, **kwargs): """Calibrate to get volume backscattering strength (Sv) from AZFP power data. The calibration formulae used here is based on Appendix G in the GU-100-AZFP-01-R50 Operator's Manual. Note a Sv_offset factor that varies depending on frequency is used in the calibration as documented on p.90. See calc_Sv_offset() in convert/azfp.py """ # Compute range in meters # range computation different for Sv and TS per AZFP matlab code self.compute_echo_range(cal_type=cal_type) # Compute derived params # TODO: take care of dividing by zero encountered in log10 spreading_loss = 20 * np.log10(self.range_meter) absorption_loss = 2 * self.env_params["sound_absorption"] * self.range_meter SL = self.cal_params["TVR"] + 20 * np.log10(self.cal_params["VTX"]) # eq.(2) # scaling factor (slope) in Fig.G-1, units Volts/dB], see p.84 a = self.cal_params["DS"] EL = ( self.cal_params["EL"] - 2.5 / a + self.echodata["Sonar/Beam_group1"]["backscatter_r"] / (26214 * a) ) # eq.(5) if cal_type == "Sv": # eq.(9) out = ( EL - SL + spreading_loss + absorption_loss - 10 * np.log10( 0.5 * self.env_params["sound_speed"] * self.echodata["Sonar/Beam_group1"]["transmit_duration_nominal"] * self.cal_params["equivalent_beam_angle"] ) + self.cal_params["Sv_offset"] ) # see p.90-91 for this correction to Sv out.name = "Sv" elif cal_type == "TS": # eq.(10) out = EL - SL + 2 * spreading_loss + absorption_loss out.name = "TS" else: raise ValueError("cal_type not recognized!") # Attach calculated range (with units meter) into data set out = out.to_dataset() out = out.merge(self.range_meter) # Add frequency_nominal to data set out["frequency_nominal"] = self.echodata["Sonar/Beam_group1"]["frequency_nominal"] # Add env and cal parameters out = self._add_params_to_output(out) return out def compute_Sv(self, **kwargs): return self._cal_power_samples(cal_type="Sv") def compute_TS(self, **kwargs): return self._cal_power_samples(cal_type="TS")
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,788
OSOceanAcoustics/echopype
refs/heads/main
/echopype/echodata/widgets/utils.py
import uuid from hashlib import md5 from datatree import DataTree from datatree.render import RenderTree from ..convention.utils import _get_sonar_groups SONAR_GROUPS = _get_sonar_groups() def html_repr(value) -> str: return value._repr_html_() def hash_value(value: str) -> str: byte_string = value.encode("utf-8") hashed = md5(byte_string) return hashed.hexdigest() def make_key(value: str) -> str: return value + str(uuid.uuid4()) def _single_node_repr(node: DataTree) -> str: """ Obtains the string repr for a single node in a ``RenderTree`` or ``DataTree``. Parameters ---------- node: DataTree A single node obtained from a ``RenderTree`` or ``DataTree`` Returns ------- node_info: str string representation of repr for the input ``node`` """ # initialize node_pathstr node_pathstr = "Top-level" # obtain the appropriate group name and get its descriptions from the yaml if node.name != "root": node_pathstr = node.path[1:] sonar_group = SONAR_GROUPS[node_pathstr] if "Beam_group" in sonar_group["name"]: # get description of Beam_group directly from the Sonar group group_descr = str( node.parent["/Sonar"].ds.beam_group_descr.sel(beam_group=sonar_group["name"]).values ) else: # get description of group from yaml file group_descr = sonar_group["description"] # construct the final node information string for repr node_info = f"{sonar_group['name']}: {group_descr}" return node_info def tree_repr(tree: DataTree) -> str: renderer = RenderTree(tree) lines = [] for pre, _, node in renderer: if node.has_data or node.has_attrs: node_repr = _single_node_repr(node) node_line = f"{pre}{node_repr.splitlines()[0]}" lines.append(node_line) return "\n".join(lines)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,789
OSOceanAcoustics/echopype
refs/heads/main
/echopype/echodata/simrad.py
""" Contains functions that are specific to Simrad echo sounders """ from typing import Optional, Tuple import numpy as np from .echodata import EchoData def check_input_args_combination( waveform_mode: str, encode_mode: str, pulse_compression: bool = None ) -> None: """ Checks that the ``waveform_mode`` and ``encode_mode`` have the correct values and that the combination of input arguments are valid, without considering the actual data. Parameters ---------- waveform_mode: str Type of transmit waveform encode_mode: str Type of encoded return echo data pulse_compression: bool States whether pulse compression should be used """ if waveform_mode not in ["CW", "BB"]: raise ValueError("The input waveform_mode must be either 'CW' or 'BB'!") if encode_mode not in ["complex", "power"]: raise ValueError("The input encode_mode must be either 'complex' or 'power'!") # BB has complex data only, but CW can have complex or power data if (waveform_mode == "BB") and (encode_mode == "power"): raise ValueError( "Data from broadband ('BB') transmission must be recorded as complex samples" ) # make sure that we have BB and complex inputs, if pulse compression is selected if pulse_compression is not None: if pulse_compression and ((waveform_mode != "BB") or (encode_mode != "complex")): raise RuntimeError( "Pulse compression can only be used with " "waveform_mode='BB' and encode_mode='complex'" ) def _retrieve_correct_beam_group_EK60( echodata: EchoData, waveform_mode: str, encode_mode: str ) -> Optional[str]: """ Ensures that the provided ``waveform_mode`` and ``encode_mode`` are consistent with the EK60-like data supplied by ``echodata``. Additionally, select the appropriate beam group corresponding to this input. Parameters ---------- echodata: EchoData An ``EchoData`` object holding the data waveform_mode : {"CW", "BB"} Type of transmit waveform encode_mode : {"complex", "power"} Type of encoded return echo data Returns ------- power_ed_group: str, optional The ``EchoData`` beam group path containing the power data """ # initialize power EchoData group value power_ed_group = None # EK60-like sensors must have 'power' and 'CW' modes only if waveform_mode != "CW": raise RuntimeError("Incorrect waveform_mode input provided!") if encode_mode != "power": raise RuntimeError("Incorrect encode_mode input provided!") # ensure that no complex data exists (this should never be triggered) if "backscatter_i" in echodata["Sonar/Beam_group1"].variables: raise RuntimeError( "Provided echodata object does not correspond to an EK60-like " "sensor, but is labeled as data from an EK60-like sensor!" ) else: power_ed_group = "Sonar/Beam_group1" return power_ed_group def _retrieve_correct_beam_group_EK80( echodata: EchoData, waveform_mode: str, encode_mode: str ) -> Tuple[Optional[str], Optional[str]]: """ Ensures that the provided ``waveform_mode`` and ``encode_mode`` are consistent with the EK80-like data supplied by ``echodata``. Additionally, select the appropriate beam group corresponding to this input. Parameters ---------- echodata: EchoData An ``EchoData`` object holding the data waveform_mode : {"CW", "BB"} Type of transmit waveform encode_mode : {"complex", "power"} Type of encoded return echo data Returns ------- power_ed_group: str, optional The ``EchoData`` beam group path containing the power data complex_ed_group: str, optional The ``EchoData`` beam group path containing the complex data """ # initialize power and complex EchoData group values power_ed_group = None complex_ed_group = None transmit_type = echodata["Sonar/Beam_group1"]["transmit_type"] # assume transmit_type identical for all pings in a channel # TODO: change when allowing within-channel CW-BB switch first_ping_transmit_type = transmit_type.isel(ping_time=0) if waveform_mode == "BB": # check BB waveform_mode, BB must always have complex data, can have 2 beam groups # when echodata contains CW power and BB complex samples if np.all(first_ping_transmit_type == "CW"): raise ValueError("waveform_mode='BB', but complex data does not exist!") elif echodata["Sonar/Beam_group2"] is not None: power_ed_group = "Sonar/Beam_group2" complex_ed_group = "Sonar/Beam_group1" else: complex_ed_group = "Sonar/Beam_group1" else: # CW can have complex or power data, so we just need to make sure that # 1) complex samples always exist in Sonar/Beam_group1 # 2) power samples are in Sonar/Beam_group1 if only one beam group exists # 3) power samples are in Sonar/Beam_group2 if two beam groups exist # Raise error if waveform_mode="CW" but CW data does not exist (not a single ping is CW) # TODO: change when allowing within-channel CW-BB switch if encode_mode == "complex" and np.all(first_ping_transmit_type != "CW"): raise ValueError("waveform_mode='CW', but all data are broadband (BB)!") if echodata["Sonar/Beam_group2"] is None: if encode_mode == "power": # power samples must be in Sonar/Beam_group1 (thus no complex samples) if "backscatter_i" in echodata["Sonar/Beam_group1"].variables: raise RuntimeError("Data provided does not correspond to encode_mode='power'!") else: power_ed_group = "Sonar/Beam_group1" elif encode_mode == "complex": # complex samples must be in Sonar/Beam_group1 if "backscatter_i" not in echodata["Sonar/Beam_group1"].variables: raise RuntimeError( "Data provided does not correspond to encode_mode='complex'!" ) else: complex_ed_group = "Sonar/Beam_group1" else: # complex should be in Sonar/Beam_group1 and power in Sonar/Beam_group2 # the RuntimeErrors below should never be triggered if "backscatter_i" not in echodata["Sonar/Beam_group1"].variables: raise RuntimeError( "Complex data does not exist in Sonar/Beam_group1, " "input echodata object must have been incorrectly constructed!" ) elif "backscatter_r" not in echodata["Sonar/Beam_group2"].variables: raise RuntimeError( "Power data does not exist in Sonar/Beam_group2, " "input echodata object must have been incorrectly constructed!" ) else: complex_ed_group = "Sonar/Beam_group1" power_ed_group = "Sonar/Beam_group2" return power_ed_group, complex_ed_group def retrieve_correct_beam_group(echodata: EchoData, waveform_mode: str, encode_mode: str) -> str: """ A function to make sure that the user has provided the correct ``waveform_mode`` and ``encode_mode`` inputs based off of the supplied ``echodata`` object. Additionally, determine the ``EchoData`` beam group corresponding to ``encode_mode``. Parameters ---------- echodata: EchoData An ``EchoData`` object holding the data corresponding to the waveform and encode modes waveform_mode : {"CW", "BB"} Type of transmit waveform encode_mode : {"complex", "power"} Type of encoded return echo data pulse_compression: bool States whether pulse compression should be used Returns ------- str The ``EchoData`` beam group path corresponding to the ``encode_mode`` input """ if echodata.sonar_model in ["EK60", "ES70"]: # initialize complex_data_location (needed only for EK60) complex_ed_group = None # check modes against data for EK60 and get power EchoData group power_ed_group = _retrieve_correct_beam_group_EK60(echodata, waveform_mode, encode_mode) elif echodata.sonar_model in ["EK80", "ES80", "EA640"]: # check modes against data for EK80 and get power/complex EchoData groups power_ed_group, complex_ed_group = _retrieve_correct_beam_group_EK80( echodata, waveform_mode, encode_mode ) else: # raise error for unknown or unaccounted for sonar model raise RuntimeError("EchoData was produced by a non-Simrad or unknown Simrad echo sounder!") if encode_mode == "complex": return complex_ed_group else: return power_ed_group
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,790
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/convert/test_convert_ek60.py
import numpy as np import pandas as pd from scipy.io import loadmat from echopype import open_raw import pytest @pytest.fixture def ek60_path(test_path): return test_path["EK60"] # raw_paths = ['./echopype/test_data/ek60/set1/' + file # for file in os.listdir('./echopype/test_data/ek60/set1')] # 2 range lengths # raw_path = ['./echopype/test_data/ek60/set2/' + file # for file in os.listdir('./echopype/test_data/ek60/set2')] # 3 range lengths # Other data files # raw_filename = 'data_zplsc/OceanStarr_2017-D20170725-T004612.raw' # OceanStarr 2 channel EK60 # raw_filename = '../data/DY1801_EK60-D20180211-T164025.raw' # Dyson 5 channel EK60 # raw_filename = 'data_zplsc/D20180206-T000625.raw # EK80 def test_convert_ek60_matlab_raw(ek60_path): """Compare parsed Beam group data with Matlab outputs.""" ek60_raw_path = str( ek60_path.joinpath('DY1801_EK60-D20180211-T164025.raw') ) ek60_matlab_path = str( ek60_path.joinpath( 'from_matlab', 'DY1801_EK60-D20180211-T164025_rawData.mat' ) ) # Convert file echodata = open_raw(raw_file=ek60_raw_path, sonar_model='EK60') # Compare with matlab outputs ds_matlab = loadmat(ek60_matlab_path) # check platform nan_plat_vars = [ "MRU_offset_x", "MRU_offset_y", "MRU_offset_z", "MRU_rotation_x", "MRU_rotation_y", "MRU_rotation_z", "position_offset_x", "position_offset_y", "position_offset_z" ] for plat_var in nan_plat_vars: assert plat_var in echodata["Platform"] assert np.isnan(echodata["Platform"][plat_var]).all() zero_plat_vars = [ "transducer_offset_x", "transducer_offset_y", "transducer_offset_z", ] for plat_var in zero_plat_vars: assert plat_var in echodata["Platform"] assert (echodata["Platform"][plat_var] == 0).all() # check water_level assert np.allclose(echodata["Platform"]["water_level"], 9.14999962, rtol=0) # power assert np.allclose( [ ds_matlab['rawData'][0]['pings'][0]['power'][0][fidx] for fidx in range(5) ], echodata["Sonar/Beam_group1"].backscatter_r.transpose( 'channel', 'range_sample', 'ping_time' ), rtol=0, atol=1.6e-5, ) # angle: alongship and athwartship for angle in ['alongship', 'athwartship']: assert np.array_equal( [ ds_matlab['rawData'][0]['pings'][0][angle][0][fidx] for fidx in range(5) ], echodata["Sonar/Beam_group1"]['angle_' + angle].transpose( 'channel', 'range_sample', 'ping_time' ), ) def test_convert_ek60_echoview_raw(ek60_path): """Compare parsed power data (count) with csv exported by EchoView.""" ek60_raw_path = str( ek60_path.joinpath('DY1801_EK60-D20180211-T164025.raw') ) ek60_csv_path = [ ek60_path.joinpath( 'from_echoview', 'DY1801_EK60-D20180211-T164025-Power%d.csv' % freq ) for freq in [18, 38, 70, 120, 200] ] # Read csv files exported by EchoView channels = [] for file in ek60_csv_path: channels.append( pd.read_csv(file, header=None, skiprows=[0]).iloc[:, 13:] ) test_power = np.stack(channels) # Convert to netCDF and check echodata = open_raw(raw_file=ek60_raw_path, sonar_model='EK60') # get indices of sorted frequency_nominal values. This is necessary # because the frequency_nominal values are not always in ascending order. sorted_freq_ind = np.argsort(echodata["Sonar/Beam_group1"].frequency_nominal) for fidx, atol in zip(range(5), [1e-5, 1.1e-5, 1.1e-5, 1e-5, 1e-5]): assert np.allclose( test_power[fidx, :, :], echodata["Sonar/Beam_group1"].backscatter_r.isel( channel=sorted_freq_ind[fidx], ping_time=slice(None, 10), range_sample=slice(1, None) ), atol=9e-6, rtol=atol, ) # check platform nan_plat_vars = [ "MRU_offset_x", "MRU_offset_y", "MRU_offset_z", "MRU_rotation_x", "MRU_rotation_y", "MRU_rotation_z", "position_offset_x", "position_offset_y", "position_offset_z" ] for plat_var in nan_plat_vars: assert plat_var in echodata["Platform"] assert np.isnan(echodata["Platform"][plat_var]).all() zero_plat_vars = [ "transducer_offset_x", "transducer_offset_y", "transducer_offset_z", ] for plat_var in zero_plat_vars: assert plat_var in echodata["Platform"] assert (echodata["Platform"][plat_var] == 0).all() # check water_level assert np.allclose(echodata["Platform"]["water_level"], 9.14999962, rtol=0) def test_convert_ek60_duplicate_frequencies(ek60_path): """Convert a file with duplicate frequencies""" raw_path = ( ek60_path / "DY1002_EK60-D20100318-T023008_rep_freq.raw" ) ed = open_raw(raw_path, "EK60") truth_chan_vals = np.array(['GPT 18 kHz 009072034d45 1-1 ES18-11', 'GPT 38 kHz 009072033fa2 2-1 ES38B', 'GPT 70 kHz 009072058c6c 3-1 ES70-7C', 'GPT 70 kHz 009072058c6c 3-2 ES70-7C', 'GPT 120 kHz 00907205794e 4-1 ES120-7C', 'GPT 200 kHz 0090720346a8 5-1 ES200-7C'], dtype='<U37') truth_freq_nom_vals = np.array([18000., 38000., 70000., 70000., 120000., 200000.], dtype=np.float64) assert np.allclose(ed['Sonar/Beam_group1'].frequency_nominal, truth_freq_nom_vals, rtol=1e-05, atol=1e-08) assert np.all(ed['Sonar/Beam_group1'].channel.values == truth_chan_vals) def test_convert_ek60_splitbeam_no_angle(ek60_path): """Convert a file from a split-beam setup that does not record angle data.""" raw_path = ( ek60_path / "NBP_B050N-D20180118-T090228.raw" ) ed = open_raw(raw_path, "EK60") assert "angle_athwartship" not in ed["Sonar/Beam_group1"] assert "angle_alongship" not in ed["Sonar/Beam_group1"]
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,791
OSOceanAcoustics/echopype
refs/heads/main
/echopype/convert/parsed_to_zarr_ek60.py
import numpy as np import pandas as pd import psutil from .parsed_to_zarr import Parsed2Zarr class Parsed2ZarrEK60(Parsed2Zarr): """ Facilitates the writing of parsed data to a zarr file for the EK60 sensor. """ def __init__(self, parser_obj): super().__init__(parser_obj) self.power_dims = ["timestamp", "channel"] self.angle_dims = ["timestamp", "channel"] self.p2z_ch_ids = {} # channel ids for power, angle, complex self.datagram_df = None # df created from zarr variables # get the channel sort rule for EK60 type sensors if "transceivers" in self.parser_obj.config_datagram: # get channel and channel_id association and sort by channel_id channels_old = list(self.parser_obj.config_datagram["transceivers"].keys()) # sort the channels in ascending order channels_new = channels_old[:] channels_new.sort(reverse=False) # obtain sort rule for the channel index self.channel_sort_rule = {str(ch): channels_new.index(ch) for ch in channels_old} @staticmethod def _get_string_dtype(pd_series: pd.Index) -> str: """ Returns the string dtype in a format that works for zarr. Parameters ---------- pd_series: pd.Index A series where all of the elements are strings """ if all(pd_series.map(type) == str): max_len = pd_series.map(len).max() dtype = f"<U{max_len}" else: raise ValueError("All elements of pd_series must be strings!") return dtype def _write_power(self, df: pd.DataFrame, max_mb: int) -> None: """ Writes the power data and associated indices to a zarr group. Parameters ---------- df : pd.DataFrame DataFrame that contains power data max_mb : int Maximum MB allowed for each chunk """ # obtain power data power_series = df.set_index(self.power_dims)["power"].copy() # get unique indices times = power_series.index.get_level_values(0).unique() channels = power_series.index.get_level_values(1).unique() # sort the channels based on rule _, indexer = channels.map(self.channel_sort_rule).sort_values( ascending=True, return_indexer=True ) channels = channels[indexer] self.p2z_ch_ids["power"] = channels.values # store channel ids for variable # create multi index using the product of the unique dims unique_dims = [times, channels] power_series = self.set_multi_index(power_series, unique_dims) # write power data to the power group zarr_grp = self.zarr_root.create_group("power") self.write_df_column( pd_series=power_series, zarr_grp=zarr_grp, is_array=True, unique_time_ind=times, max_mb=max_mb, ) # write the unique indices to the power group zarr_grp.array( name=self.power_dims[0], data=times.values, dtype=times.dtype.str, fill_value="NaT" ) dtype = self._get_string_dtype(channels) zarr_grp.array(name=self.power_dims[1], data=channels.values, dtype=dtype, fill_value=None) @staticmethod def _split_angle_data(angle_series: pd.Series) -> pd.DataFrame: """ Splits the 2D angle data into two 1D arrays representing angle_athwartship and angle_alongship, for each element in ``angle_series``. Parameters ---------- angle_series : pd.Series Series representing the angle data Returns ------- DataFrame with columns angle_athwartship and angle_alongship obtained from splitting the 2D angle data, with that same index as ``angle_series`` """ # split each angle element into angle_athwartship and angle_alongship angle_split = angle_series.apply( lambda x: [x[:, 0], x[:, 1]] if isinstance(x, np.ndarray) else [None, None] ) return pd.DataFrame( data=angle_split.to_list(), columns=["angle_athwartship", "angle_alongship"], index=angle_series.index, ) def _write_angle(self, df: pd.DataFrame, max_mb: int) -> None: """ Writes the angle data and associated indices to a zarr group. Parameters ---------- df : pd.DataFrame DataFrame that contains angle data max_mb : int Maximum MB allowed for each chunk """ # obtain angle data angle_series = df.set_index(self.angle_dims)["angle"].copy() angle_df = self._split_angle_data(angle_series) # get unique indices times = angle_df.index.get_level_values(0).unique() channels = angle_df.index.get_level_values(1).unique() # sort the channels based on rule _, indexer = channels.map(self.channel_sort_rule).sort_values( ascending=True, return_indexer=True ) channels = channels[indexer] self.p2z_ch_ids["angle"] = channels.values # store channel ids for variable # create multi index using the product of the unique dims unique_dims = [times, channels] angle_df = self.set_multi_index(angle_df, unique_dims) # write angle data to the angle group zarr_grp = self.zarr_root.create_group("angle") for column in angle_df: self.write_df_column( pd_series=angle_df[column], zarr_grp=zarr_grp, is_array=True, unique_time_ind=times, max_mb=max_mb, ) # write the unique indices to the angle group zarr_grp.array( name=self.angle_dims[0], data=times.values, dtype=times.dtype.str, fill_value="NaT" ) dtype = self._get_string_dtype(channels) zarr_grp.array(name=self.angle_dims[1], data=channels.values, dtype=dtype, fill_value=None) def _get_power_angle_size(self, df: pd.DataFrame) -> int: """ Returns the total memory in bytes required to store the expanded power and angle data. Parameters ---------- df: pd.DataFrame DataFrame containing the power, angle, and the appropriate dimension data """ # get unique indices times = df[self.power_dims[0]].unique() channels = df[self.power_dims[1]].unique() # get final form of index multi_index = pd.MultiIndex.from_product([times, channels]) # get the total memory required for expanded zarr variables pow_mem = self.array_series_bytes(df["power"], multi_index.shape[0]) angle_mem = self.array_series_bytes(df["angle"], multi_index.shape[0]) return pow_mem + angle_mem def whether_write_to_zarr(self, mem_mult: float = 0.3) -> bool: """ Determines if the zarr data provided will expand into a form that is larger than a percentage of the total physical RAM. Parameters ---------- mem_mult : float Multiplier for total physical RAM Notes ----- If ``mem_mult`` times the total RAM is less than the total memory required to store the expanded zarr variables, this function will return True, otherwise False. """ # create datagram df, if it does not exist if not isinstance(self.datagram_df, pd.DataFrame): self.datagram_df = pd.DataFrame.from_dict(self.parser_obj.zarr_datagrams) total_mem = self._get_power_angle_size(self.datagram_df) # get statistics about system memory usage mem = psutil.virtual_memory() zarr_dgram_size = self._get_zarr_dgrams_size() # approx. the amount of memory that will be used after expansion req_mem = mem.used - zarr_dgram_size + total_mem # free memory, if we no longer need it if mem.total * mem_mult > req_mem: del self.datagram_df else: del self.parser_obj.zarr_datagrams return mem.total * mem_mult < req_mem def datagram_to_zarr(self, max_mb: int) -> None: """ Facilitates the conversion of a list of datagrams to a form that can be written to a zarr store. Parameters ---------- max_mb : int Maximum MB allowed for each chunk Notes ----- This function specifically writes chunks along the time index. The chunking routine evenly distributes the times such that each chunk differs by at most one time. This makes it so that the memory required for each chunk is approximately the same. """ self._create_zarr_info() # create datagram df, if it does not exist if not isinstance(self.datagram_df, pd.DataFrame): self.datagram_df = pd.DataFrame.from_dict(self.parser_obj.zarr_datagrams) del self.parser_obj.zarr_datagrams # free memory # convert channel column to a string self.datagram_df["channel"] = self.datagram_df["channel"].astype(str) if not self.datagram_df.empty: self._write_power(df=self.datagram_df, max_mb=max_mb) del self.datagram_df["power"] # free memory if not self.datagram_df.empty: self._write_angle(df=self.datagram_df, max_mb=max_mb) del self.datagram_df # free memory self._close_store()
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,792
OSOceanAcoustics/echopype
refs/heads/main
/echopype/mask/api.py
import datetime import operator as op import pathlib from typing import List, Optional, Union import numpy as np import xarray as xr from ..utils.io import validate_source_ds_da from ..utils.prov import add_processing_level, echopype_prov_attrs, insert_input_processing_level # lookup table with key string operator and value as corresponding Python operator str2ops = { ">": op.gt, "<": op.lt, "<=": op.le, ">=": op.ge, "==": op.eq, } def _validate_source_ds(source_ds, storage_options_ds): """ Validate the input ``source_ds`` and the associated ``storage_options_mask``. """ # Validate the source_ds type or path (if it is provided) source_ds, file_type = validate_source_ds_da(source_ds, storage_options_ds) if isinstance(source_ds, str): # open up Dataset using source_ds path source_ds = xr.open_dataset(source_ds, engine=file_type, chunks={}, **storage_options_ds) # Check source_ds coordinates if "ping_time" not in source_ds or "range_sample" not in source_ds: raise ValueError("'source_ds' must have coordinates 'ping_time' and 'range_sample'!") return source_ds def _validate_and_collect_mask_input( mask: Union[ Union[xr.DataArray, str, pathlib.Path], List[Union[xr.DataArray, str, pathlib.Path]] ], storage_options_mask: Union[dict, List[dict]], ) -> Union[xr.DataArray, List[xr.DataArray]]: """ Validate that the input ``mask`` and associated ``storage_options_mask`` are correctly provided to ``apply_mask``. Additionally, form the mask input that should be used in the core routine of ``apply_mask``. Parameters ---------- mask: xr.DataArray, str, pathlib.Path, or a list of these datatypes The mask(s) to be applied. Can be a single input or list that corresponds to a DataArray or a path. If a path is provided this should point to a zarr or netcdf file with only one data variable in it. 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.DataArray or list of xr.DataArray If the ``mask`` input is a single value, then the corresponding DataArray will be returned, else a list of DataArrays corresponding to the input masks will be returned Raises ------ ValueError If ``mask`` is a single-element and ``storage_options_mask`` is not a single dict TypeError If ``storage_options_mask`` is not a list of dict or a dict """ if isinstance(mask, list): # if storage_options_mask is not a list create a list of # length len(mask) with elements storage_options_mask if not isinstance(storage_options_mask, list): if not isinstance(storage_options_mask, dict): raise TypeError("storage_options_mask must be a list of dict or a dict!") storage_options_mask = [storage_options_mask] * len(mask) else: # ensure all element of storage_options_mask are a dict if not all([isinstance(elem, dict) for elem in storage_options_mask]): raise TypeError("storage_options_mask must be a list of dict or a dict!") for mask_ind in range(len(mask)): # validate the mask type or path (if it is provided) mask_val, file_type = validate_source_ds_da( mask[mask_ind], storage_options_mask[mask_ind] ) # replace mask element path with its corresponding DataArray if isinstance(mask_val, (str, pathlib.Path)): # open up DataArray using mask path mask[mask_ind] = xr.open_dataarray( mask_val, engine=file_type, chunks={}, **storage_options_mask[mask_ind] ) # check mask coordinates # the coordinate sequence matters, so fix the tuple form allowed_dims = [ ("ping_time", "range_sample"), ("channel", "ping_time", "range_sample"), ] if mask[mask_ind].dims not in allowed_dims: raise ValueError("All masks must have dimensions ('ping_time', 'range_sample')!") else: if not isinstance(storage_options_mask, dict): raise ValueError( "The provided input storage_options_mask should be a single " "dict because mask is a single value!" ) # validate the mask type or path (if it is provided) mask, file_type = validate_source_ds_da(mask, storage_options_mask) if isinstance(mask, (str, pathlib.Path)): # open up DataArray using mask path mask = xr.open_dataarray(mask, engine=file_type, chunks={}, **storage_options_mask) return mask def _check_var_name_fill_value( source_ds: xr.Dataset, var_name: str, fill_value: Union[int, float, np.ndarray, xr.DataArray] ) -> Union[int, float, np.ndarray, xr.DataArray]: """ Ensures that the inputs ``var_name`` and ``fill_value`` for the function ``apply_mask`` were appropriately provided. Parameters ---------- source_ds: xr.Dataset A Dataset that contains the variable ``var_name`` var_name: str The variable name in ``source_ds`` that the mask should be applied to fill_value: int or float or np.ndarray or xr.DataArray Specifies the value(s) at false indices Returns ------- fill_value: int or float or np.ndarray or xr.DataArray fill_value with sanitized dimensions Raises ------ TypeError If ``var_name`` or ``fill_value`` are not an accepted type ValueError If the Dataset ``source_ds`` does not contain ``var_name`` ValueError If ``fill_value`` is an array and not the same shape as ``var_name`` """ # check the type of var_name if not isinstance(var_name, str): raise TypeError("The input var_name must be a string!") # ensure var_name is in source_ds if var_name not in source_ds.variables: raise ValueError("The Dataset source_ds does not contain the variable var_name!") # check the type of fill_value if not isinstance(fill_value, (int, float, np.ndarray, xr.DataArray)): raise TypeError( "The input fill_value must be of type int or " "float or np.ndarray or xr.DataArray!" ) # make sure that fill_values is the same shape as var_name if isinstance(fill_value, (np.ndarray, xr.DataArray)): if isinstance(fill_value, xr.DataArray): fill_value = fill_value.data.squeeze() # squeeze out length=1 channel dimension elif isinstance(fill_value, np.ndarray): fill_value = fill_value.squeeze() # squeeze out length=1 channel dimension source_ds_shape = ( source_ds[var_name].isel(channel=0).shape if "channel" in source_ds[var_name].coords else source_ds[var_name].shape ) if fill_value.shape != source_ds_shape: raise ValueError( f"If fill_value is an array it must be of the same shape as {var_name}!" ) return fill_value def _variable_prov_attrs( masked_da: xr.DataArray, source_mask: Union[xr.DataArray, List[xr.DataArray]] ) -> dict: """ Extract and compose masked Sv provenance attributes from the masked Sv and the masks used to generate it. Parameters ---------- masked_da: xr.DataArray Masked Sv source_mask: Union[xr.DataArray, List[xr.DataArray]] Individual mask or list of masks used to create the masked Sv Returns ------- dict Dictionary of provenance attributes (attribute name and value) for the intended variable. """ # Modify core variable attributes attrs = { "long_name": "Volume backscattering strength, masked (Sv re 1 m-1)", "actual_range": [ round(float(masked_da.min().values), 2), round(float(masked_da.max().values), 2), ], } # Add history attribute history_attr = f"{datetime.datetime.utcnow()} +00:00. " "Created masked Sv dataarray." # noqa attrs = {**attrs, **{"history": history_attr}} # Add attributes from the mask DataArray, if present # Handle only a single mask. If not passed to apply_mask as a single DataArray, # will use the first mask of the list passed to apply_mask # TODO: Expand it to handle attributes from multiple masks if isinstance(source_mask, xr.DataArray) or ( isinstance(source_mask, list) and isinstance(source_mask[0], xr.DataArray) ): use_mask = source_mask[0] if isinstance(source_mask, list) else source_mask if len(use_mask.attrs) > 0: mask_attrs = use_mask.attrs.copy() if "history" in mask_attrs: # concatenate the history string as new line attrs["history"] += f"\n{mask_attrs['history']}" mask_attrs.pop("history") attrs = {**attrs, **mask_attrs} return attrs @add_processing_level("L3*") def apply_mask( source_ds: Union[xr.Dataset, str, pathlib.Path], mask: Union[xr.DataArray, str, pathlib.Path, List[Union[xr.DataArray, str, pathlib.Path]]], var_name: str = "Sv", fill_value: Union[int, float, np.ndarray, xr.DataArray] = np.nan, storage_options_ds: dict = {}, storage_options_mask: Union[dict, List[dict]] = {}, ) -> xr.Dataset: """ Applies the provided mask(s) to the Sv variable ``var_name`` in the provided Dataset ``source_ds``. 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. Can be a single input or list that corresponds to a DataArray or a path. Each entry in the list must have dimensions ``('ping_time', 'range_sample')``. Multi-channel masks are not currently supported. 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`` and ``range_sample``, 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, np.ndarray, or xr.DataArray, default=np.nan Value(s) at masked indices. If ``fill_value`` is of type ``np.ndarray`` or ``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`` """ # Validate the source_ds source_ds = _validate_source_ds(source_ds, storage_options_ds) # Validate and form the mask input to be used downstream mask = _validate_and_collect_mask_input(mask, storage_options_mask) # Check var_name and sanitize fill_value dimensions if an array fill_value = _check_var_name_fill_value(source_ds, var_name, fill_value) # Obtain final mask to be applied to var_name if isinstance(mask, list): # perform a logical AND element-wise operation across the masks final_mask = np.logical_and.reduce(mask) # xr.where has issues with attrs when final_mask is an array, so we make it a DataArray final_mask = xr.DataArray(final_mask, coords=mask[0].coords) else: final_mask = mask # Sanity check: final_mask should be of the same shape as source_ds[var_name] # along the ping_time and range_sample dimensions def get_ch_shape(da): return da.isel(channel=0).shape if "channel" in da.dims else da.shape # Below operate on the actual data array to be masked source_da = source_ds[var_name] source_da_shape = get_ch_shape(source_da) final_mask_shape = get_ch_shape(final_mask) if final_mask_shape != source_da_shape: raise ValueError( f"The final constructed mask is not of the same shape as source_ds[{var_name}] " "along the ping_time and range_sample dimensions!" ) # final_mask is always an xr.DataArray with at most length=1 channel dimension if "channel" in final_mask.dims: final_mask = final_mask.isel(channel=0) # Make sure fill_value and final_mask are expanded in dimensions if "channel" in source_da.dims: if isinstance(fill_value, np.ndarray): fill_value = np.array([fill_value] * source_da["channel"].size) final_mask = np.array([final_mask.data] * source_da["channel"].size) # Apply the mask to var_name # Somehow keep_attrs=True errors out here, so will attach later var_name_masked = xr.where(final_mask, x=source_da, y=fill_value) # Obtain a shallow copy of source_ds output_ds = source_ds.copy(deep=False) # Replace var_name with var_name_masked output_ds[var_name] = var_name_masked output_ds[var_name] = output_ds[var_name].assign_attrs(source_da.attrs) # Add or modify variable and global (dataset) provenance attributes output_ds[var_name] = output_ds[var_name].assign_attrs( _variable_prov_attrs(output_ds[var_name], mask) ) process_type = "mask" prov_dict = echopype_prov_attrs(process_type=process_type) prov_dict[f"{process_type}_function"] = "mask.apply_mask" output_ds = output_ds.assign_attrs(prov_dict) output_ds = insert_input_processing_level(output_ds, input_ds=source_ds) return output_ds def _check_freq_diff_non_data_inputs( freqAB: Optional[List[float]] = None, chanAB: Optional[List[str]] = None, operator: str = ">", diff: Union[float, int] = None, ) -> None: """ Checks that the non-data related inputs of ``frequency_differencing`` (i.e. ``freqAB``, ``chanAB``, ``operator``, ``diff``) were correctly provided. Parameters ---------- freqAB: list of float, optional The pair of nominal frequencies to be used for frequency-differencing, where the first element corresponds to ``freqA`` and the second element corresponds to ``freqB`` chanAB: list of float, optional The pair of channels that will be used to select the nominal frequencies to be used for frequency-differencing, where the first element corresponds to ``freqA`` and the second element corresponds to ``freqB`` operator: {">", "<", "<=", ">=", "=="} The operator for the frequency-differencing diff: float or int The threshold of Sv difference between frequencies """ # check that either freqAB or chanAB are provided and they are a list of length 2 if (freqAB is None) and (chanAB is None): raise ValueError("Either freqAB or chanAB must be given!") elif (freqAB is not None) and (chanAB is not None): raise ValueError("Only freqAB or chanAB must be given, but not both!") elif freqAB is not None: if not isinstance(freqAB, list): raise TypeError("freqAB must be a list!") elif len(set(freqAB)) != 2: raise ValueError("freqAB must be a list of length 2 with unique elements!") else: if not isinstance(chanAB, list): raise TypeError("chanAB must be a list!") elif len(set(chanAB)) != 2: raise ValueError("chanAB must be a list of length 2 with unique elements!") # check that operator is a string and a valid operator if not isinstance(operator, str): raise TypeError("operator must be a string!") else: if operator not in [">", "<", "<=", ">=", "=="]: raise ValueError("Invalid operator!") # ensure that diff is a float or an int if not isinstance(diff, (float, int)): raise TypeError("diff must be a float or int!") def _check_source_Sv_freq_diff( source_Sv: xr.Dataset, freqAB: Optional[List[float]] = None, chanAB: Optional[List[str]] = None, ) -> None: """ Ensures that ``source_Sv`` contains ``channel`` as a coordinate and ``frequency_nominal`` as a variable, the provided list input (``freqAB`` or ``chanAB``) are contained in the coordinate ``channel`` or variable ``frequency_nominal``, and ``source_Sv`` does not have repeated values for ``channel`` and ``frequency_nominal``. Parameters ---------- source_Sv: xr.Dataset A Dataset that contains the Sv data to create a mask for freqAB: list of float, optional The pair of nominal frequencies to be used for frequency-differencing, where the first element corresponds to ``freqA`` and the second element corresponds to ``freqB`` chanAB: list of float, optional The pair of channels that will be used to select the nominal frequencies to be used for frequency-differencing, where the first element corresponds to ``freqA`` and the second element corresponds to ``freqB`` """ # check that channel and frequency nominal are in source_Sv if "channel" not in source_Sv.coords: raise ValueError("The Dataset defined by source_Sv must have channel as a coordinate!") elif "frequency_nominal" not in source_Sv.variables: raise ValueError( "The Dataset defined by source_Sv must have frequency_nominal as a variable!" ) # make sure that the channel and frequency_nominal values are not repeated in source_Sv if len(set(source_Sv.channel.values)) < source_Sv.channel.size: raise ValueError( "The provided source_Sv contains repeated channel values, this is not allowed!" ) if len(set(source_Sv.frequency_nominal.values)) < source_Sv.frequency_nominal.size: raise ValueError( "The provided source_Sv contains repeated frequency_nominal " "values, this is not allowed!" ) # check that the elements of freqAB are in frequency_nominal if (freqAB is not None) and (not all([freq in source_Sv.frequency_nominal for freq in freqAB])): raise ValueError( "The provided list input freqAB contains values that " "are not in the frequency_nominal variable!" ) # check that the elements of chanAB are in channel if (chanAB is not None) and (not all([chan in source_Sv.channel for chan in chanAB])): raise ValueError( "The provided list input chanAB contains values that are " "not in the channel coordinate!" ) def frequency_differencing( source_Sv: Union[xr.Dataset, str, pathlib.Path], storage_options: Optional[dict] = {}, freqAB: Optional[List[float]] = None, chanAB: Optional[List[str]] = None, operator: str = ">", diff: Union[float, int] = None, ) -> xr.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`` freqAB: list of float, optional The pair of nominal frequencies to be used for frequency-differencing, where the first element corresponds to ``freqA`` and the second element corresponds to ``freqB``. Only one of ``freqAB`` and ``chanAB`` should be provided, and not both. chanAB: list of strings, optional The pair of channels that will be used to select the nominal frequencies to be used for frequency-differencing, where the first element corresponds to ``freqA`` and the second element corresponds to ``freqB``. Only one of ``freqAB`` and ``chanAB`` should be provided, and not both. operator: {">", "<", "<=", ">=", "=="} The operator for the frequency-differencing diff: float or int The threshold of Sv difference between frequencies 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 ``freqAB`` or ``chanAB`` are given ValueError If both ``freqAB`` and ``chanAB`` are given TypeError If any input is not of the correct type ValueError If either ``freqAB`` or ``chanAB`` are provided and the list does not contain 2 distinct elements ValueError If ``freqAB`` contains values that are not contained in ``frequency_nominal`` ValueError If ``chanAB`` 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 ``freqAB`` or ``chanAB`` 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=mock_Sv_ds, storage_options={}, freqAB=None, ... chanAB = ['chan1', 'chan2'], ... operator = ">=", diff=10.0) <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 """ # check that non-data related inputs were correctly provided _check_freq_diff_non_data_inputs(freqAB, chanAB, operator, diff) # validate the source_Sv type or path (if it is provided) source_Sv, file_type = validate_source_ds_da(source_Sv, storage_options) if isinstance(source_Sv, str): # open up Dataset using source_Sv path source_Sv = xr.open_dataset(source_Sv, engine=file_type, chunks={}, **storage_options) # check the source_Sv with respect to channel and frequency_nominal _check_source_Sv_freq_diff(source_Sv, freqAB, chanAB) # determine chanA and chanB if freqAB is not None: # obtain position of frequency provided in frequency_nominal freqA_pos = np.argwhere(source_Sv.frequency_nominal.values == freqAB[0]).flatten()[0] freqB_pos = np.argwhere(source_Sv.frequency_nominal.values == freqAB[1]).flatten()[0] # get channels corresponding to frequencies provided chanA = str(source_Sv.channel.isel(channel=freqA_pos).values) chanB = str(source_Sv.channel.isel(channel=freqB_pos).values) else: # get individual channels chanA = chanAB[0] chanB = chanAB[1] # get the left-hand side of condition lhs = source_Sv["Sv"].sel(channel=chanA) - source_Sv["Sv"].sel(channel=chanB) # create mask using operator lookup table da = xr.where(str2ops[operator](lhs, diff), True, False) # assign a name to DataArray da.name = "mask" # assign provenance attributes mask_attrs = {"mask_type": "frequency differencing"} history_attr = ( f"{datetime.datetime.utcnow()} +00:00. " "Mask created by mask.frequency_differencing. " f"Operation: Sv['{chanA}'] - Sv['{chanB}'] {operator} {diff}" ) da = da.assign_attrs({**mask_attrs, **{"history": history_attr}}) return da
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,793
OSOceanAcoustics/echopype
refs/heads/main
/echopype/clean/noise_est.py
import numpy as np from ..utils import uwa class NoiseEst: """ Attributes ---------- ds_Sv : xr.Dataset dataset containing ``Sv`` and ``echo_range`` [m] ping_num : int number of pings to obtain noise estimates range_sample_num : int number of samples along ``echo_range`` to obtain noise estimates """ def __init__(self, ds_Sv, ping_num, range_sample_num): self.ds_Sv = ds_Sv self.ping_num = ping_num self.range_sample_num = range_sample_num self.spreading_loss = None self.absorption_loss = None self.Sv_noise = None self._compute_transmission_loss() self._compute_power_cal() def _compute_transmission_loss(self): """Compute transmission loss""" if "sound_absorption" not in self.ds_Sv: sound_absorption = uwa.calc_absorption( frequency=self.ds_Sv.frequency_nominal, temperature=self.ds_Sv["temperature"], salinity=self.ds_Sv["salinity"], pressure=self.ds_Sv["pressure"], ) else: sound_absorption = self.ds_Sv["sound_absorption"] # Transmission loss self.spreading_loss = 20 * np.log10( self.ds_Sv["echo_range"].where(self.ds_Sv["echo_range"] >= 1, other=1) ) self.absorption_loss = 2 * sound_absorption * self.ds_Sv["echo_range"] def _compute_power_cal(self): """Compute calibrated power without TVG, linear domain""" self.power_cal = 10 ** ( (self.ds_Sv["Sv"] - self.spreading_loss - self.absorption_loss) / 10 ) def estimate_noise(self, noise_max=None): """Estimate noise from a collected of pings Parameters ---------- noise_max : Union[int, float] the upper limit for background noise expected under the operating conditions """ power_cal_binned_avg = 10 * np.log10( # binned averages of calibrated power self.power_cal.coarsen( ping_time=self.ping_num, range_sample=self.range_sample_num, boundary="pad", ).mean() ) noise = power_cal_binned_avg.min(dim="range_sample", skipna=True) # align ping_time to first of each ping collection noise["ping_time"] = self.power_cal["ping_time"][:: self.ping_num] if noise_max is not None: noise = noise.where(noise < noise_max, noise_max) # limit max noise level self.Sv_noise = ( noise.reindex( {"ping_time": self.power_cal["ping_time"]}, method="ffill" ) # forward fill empty index + self.spreading_loss + self.absorption_loss ) def remove_noise(self, noise_max=None, SNR_threshold=3): """ Remove noise by using estimates of background noise from mean calibrated power of a collection of pings. This method adds two data variables to the input ``ds_Sv``: - corrected Sv (``Sv_corrected``) - noise estimates (``Sv_noise``) 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. Parameters ---------- noise_max : float the upper limit for background noise expected under the operating conditions SNR_threshold : float acceptable signal-to-noise ratio, default to 3 dB """ # Compute Sv_noise self.estimate_noise(noise_max=noise_max) # Sv corrected for noise # linear domain fac = 10 ** (self.ds_Sv["Sv"] / 10) - 10 ** (self.Sv_noise / 10) Sv_corr = 10 * np.log10(fac.where(fac > 0, other=np.nan)) Sv_corr = Sv_corr.where( Sv_corr - self.Sv_noise > SNR_threshold, other=np.nan ) # other=-999 (from paper) # Assemble output dataset def add_attrs(sv_type, da): da.attrs = { "long_name": f"Volume backscattering strength, {sv_type} (Sv re 1 m-1)", "units": "dB", "actual_range": [ round(float(da.min().values), 2), round(float(da.max().values), 2), ], "noise_ping_num": self.ping_num, "noise_range_sample_num": self.range_sample_num, "SNR_threshold": SNR_threshold, "noise_max": noise_max, } self.ds_Sv["Sv_noise"] = self.Sv_noise add_attrs("noise", self.ds_Sv["Sv_noise"]) self.ds_Sv["Sv_corrected"] = Sv_corr add_attrs("corrected", self.ds_Sv["Sv_corrected"])
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,794
OSOceanAcoustics/echopype
refs/heads/main
/echopype/qc/__init__.py
from .api import coerce_increasing_time, exist_reversed_time __all__ = ["coerce_increasing_time", "exist_reversed_time"]
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,795
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/utils/test_processinglevels_integration.py
import sys import pytest import numpy as np import xarray as xr import echopype as ep pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="Test data not available on windows tests") @pytest.mark.parametrize( ["sonar_model", "path_model", "raw_and_xml_paths", "extras"], [ pytest.param( "EK60", "EK60", ("Winter2017-D20170115-T150122.raw", None), {}, # marks=pytest.mark.skipif(sys.platform == "win32", reason="Test data not available on windows tests"), ), pytest.param( "AZFP", "AZFP", ("17082117.01A", "17041823.XML"), {"longitude": -60.0, "latitude": 45.0, "salinity": 27.9, "pressure": 59}, # marks=pytest.mark.skipif(sys.platform == "win32", reason="Test data not available on windows tests"), ), ], ) def test_raw_to_mvbs( sonar_model, path_model, raw_and_xml_paths, extras, test_path ): # Prepare the Sv dataset raw_path = test_path[path_model] / raw_and_xml_paths[0] if raw_and_xml_paths[1]: xml_path = test_path[path_model] / raw_and_xml_paths[1] else: xml_path = None def _presence_test(test_ds, processing_level): assert "processing_level" in test_ds.attrs assert "processing_level_url" in test_ds.attrs assert test_ds.attrs["processing_level"] == processing_level def _absence_test(test_ds): assert "processing_level" not in test_ds.attrs assert "processing_level_url" not in test_ds.attrs # ---- Convert raw file and update_platform def _var_presence_notnan_test(name): if name in ed['Platform'].data_vars and not ed["Platform"][name].isnull().all(): return True else: return False ed = ep.open_raw(raw_path, xml_path=xml_path, sonar_model=sonar_model) if _var_presence_notnan_test("longitude") and _var_presence_notnan_test("latitude"): _presence_test(ed["Top-level"], "Level 1A") elif "longitude" in extras and "latitude" in extras: _absence_test(ed["Top-level"]) point_ds = xr.Dataset( { "latitude": (["time"], np.array([float(extras["latitude"])])), "longitude": (["time"], np.array([float(extras["longitude"])])), }, coords={ "time": (["time"], np.array([ed["Sonar/Beam_group1"]["ping_time"].values.min()])) }, ) ed.update_platform(point_ds, variable_mappings={"latitude": "latitude", "longitude": "longitude"}) _presence_test(ed["Top-level"], "Level 1A") else: _absence_test(ed["Top-level"]) raise RuntimeError( "Platform latitude and longitude are not present and cannot be added " "using update_platform based on test raw file and included parameters." ) # ---- Calibrate and add_latlon env_params = None if sonar_model == "AZFP": # AZFP data require external salinity and pressure env_params = { "temperature": ed["Environment"]["temperature"].values.mean(), "salinity": extras["salinity"], "pressure": extras["pressure"], } ds = ep.calibrate.compute_Sv(echodata=ed, env_params=env_params) _absence_test(ds) Sv_ds = ep.consolidate.add_location(ds=ds, echodata=ed) assert "longitude" in Sv_ds.data_vars and "latitude" in Sv_ds.data_vars _presence_test(Sv_ds, "Level 2A") # ---- Noise removal denoised_ds = ep.clean.remove_noise(Sv_ds, ping_num=10, range_sample_num=20) _presence_test(denoised_ds, "Level 2B") # ---- apply_mask based on frequency differencing def _freqdiff_applymask(test_ds): # frequency_differencing expects a dataarray variable named "Sv". For denoised Sv, # rename Sv to Sv_raw and Sv_corrected to Sv before passing ds to frequency_differencing if "Sv_corrected" in test_ds.data_vars: out_ds = test_ds.rename_vars(name_dict={"Sv": "Sv_raw", "Sv_corrected": "Sv"}) else: out_ds = test_ds freqAB = list(out_ds.frequency_nominal.values[:2]) freqdiff_da = ep.mask.frequency_differencing(source_Sv=out_ds, freqAB=freqAB, operator=">", diff=5) # Apply mask to multi-channel Sv return ep.mask.apply_mask(source_ds=out_ds, var_name="Sv", mask=freqdiff_da) # On Sv w/o noise removal ds = _freqdiff_applymask(Sv_ds) _presence_test(ds, "Level 3A") # On denoised Sv ds = _freqdiff_applymask(denoised_ds) _presence_test(ds, "Level 3B") # ---- Compute MVBS # compute_MVBS expects a variable named "Sv" # No product level is assigned because at present compute_MVBS drops the lat/lon data # associated with the input Sv dataset # ds = ds.rename_vars(name_dict={"Sv": "Sv_unmasked", "Sv_ch0": "Sv"}) mvbs_ds = ep.commongrid.compute_MVBS(ds, range_meter_bin=30, ping_time_bin='1min') _absence_test(mvbs_ds)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,796
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/metrics/test_metrics_summary_statistics.py
import xarray as xr import numpy as np import pandas as pd from echopype.metrics.summary_statistics import ( delta_z, convert_to_linear, abundance, center_of_mass, dispersion, evenness, aggregation, ) # Utility Function def create_test_ds(Sv, echo_range): freq = [30] time = pd.date_range("2021-08-28", periods=2) reference_time = pd.Timestamp("2021-08-27") r_b = [0, 1, 2] testDS = xr.Dataset( data_vars=dict( Sv=(["frequency", "ping_time", "range_sample"], Sv), echo_range=(["frequency", "ping_time", "range_sample"], echo_range), ), coords={ 'frequency': xr.DataArray( freq, name='frequency', dims=['frequency'], attrs={'units': 'kHz'}, ), 'ping_time': xr.DataArray( time, name='ping_time', dims=['ping_time'], ), 'range_sample': xr.DataArray( r_b, name='range_sample', dims=['range_sample'], ), }, ) return testDS # Test Functions def test_abundance(): """Compares summary_statistics.py calculation of abundance with verified outcomes""" Sv = np.array([[[20, 40, 60], [50, 20, 30]]]) echo_range = np.array([[[1, 2, 3], [2, 3, 4]]]) ab_ds1 = create_test_ds(Sv, echo_range) ab_ds1_SOL = np.array([[60.04321374, 30.41392685]]) assert np.allclose( abundance(ab_ds1), ab_ds1_SOL, rtol=1e-09 ), 'Calculated output does not match expected output' def test_center_of_mass(): """Compares summary_statistics.py calculation of center_of_mass with verified outcomes""" Sv = np.array([[[20, 40, 60], [50, 20, 30]]]) echo_range = np.array([[[1, 2, 3], [2, 3, 4]]]) cm_ds1 = create_test_ds(Sv, echo_range) cm_ds1_SOL = np.array([[2.99009901, 3.90909090]]) assert np.allclose( center_of_mass(cm_ds1), cm_ds1_SOL, rtol=1e-09 ), 'Calculated output does not match expected output' def test_inertia(): """Compares summary_statistics.py calculation of inertia with verified outcomes""" Sv = np.array([[[20, 40, 60], [50, 20, 30]]]) echo_range = np.array([[[1, 2, 3], [2, 3, 4]]]) in_ds1 = create_test_ds(Sv, echo_range) in_ds1_SOL = np.array([[0.00980296, 0.08264463]]) assert np.allclose( dispersion(in_ds1), in_ds1_SOL, rtol=1e-09 ), 'Calculated output does not match expected output' def test_evenness(): """Compares summary_statistics.py calculation of evenness with verified outcomes""" Sv = np.array([[[20, 40, 60], [50, 20, 30]]]) echo_range = np.array([[[1, 2, 3], [2, 3, 4]]]) ev_ds1 = create_test_ds(Sv, echo_range) ev_ds1_SOL = np.array([[1.019998, 1.198019802]]) assert np.allclose( evenness(ev_ds1), ev_ds1_SOL, rtol=1e-09 ), 'Calculated output does not match expected output' def test_aggregation(): """Compares summary_statistics.py calculation of aggregation with verified outcomes""" Sv = np.array([[[20, 40, 60], [50, 20, 30]]]) echo_range = np.array([[[1, 2, 3], [2, 3, 4]]]) ag_ds1 = create_test_ds(Sv, echo_range) ag_ds1_SOL = np.array([[0.9803940792, 0.8347107438]]) assert np.allclose( aggregation(ag_ds1), ag_ds1_SOL, rtol=1e-09 ), 'Calculated output does not match expected output'
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,797
OSOceanAcoustics/echopype
refs/heads/main
/echopype/testing.py
from pathlib import Path HERE = Path(__file__).parent.absolute() TEST_DATA_FOLDER = HERE / "test_data"
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,798
OSOceanAcoustics/echopype
refs/heads/main
/echopype/__init__.py
from __future__ import absolute_import, division, print_function from _echopype_version import version as __version__ # noqa from . import calibrate, clean, commongrid, consolidate, mask, utils from .convert.api import open_raw from .echodata.api import open_converted from .echodata.combine import combine_echodata from .utils.io import init_ep_dir from .utils.log import verbose # Turn off verbosity for echopype verbose(override=True) init_ep_dir() __all__ = [ "calibrate", "clean", "combine_echodata", "commongrid", "consolidate", "mask", "metrics", "open_converted", "open_raw", "utils", "verbose", ]
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,799
OSOceanAcoustics/echopype
refs/heads/main
/echopype/calibrate/env_params_old.py
from typing import Dict, List import numpy as np import scipy.interpolate import xarray as xr from typing_extensions import Literal DataKind = Literal["stationary", "mobile", "organized"] InterpMethod = Literal["linear", "nearest", "zero", "slinear", "quadratic", "cubic"] ExtrapMethod = Literal["linear", "nearest"] VALID_INTERP_METHODS: Dict[DataKind, List[InterpMethod]] = { "stationary": ["linear", "nearest", "zero", "slinear", "quadratic", "cubic"], "mobile": ["linear", "nearest", "cubic"], "organized": ["linear", "nearest"], } class EnvParams: def __init__( self, env_params: xr.Dataset, data_kind: DataKind, interp_method: InterpMethod = "linear", extrap_method: ExtrapMethod = "linear", ): """ Class to hold and interpolate external environmental data for calibration purposes. This class can be used as the `env_params` parameter in `echopype.calibrate.compute_Sv` or `echopype.calibrate.compute_TS`. It is intended to be used with environmental parameters indexed by time. Environmental parameters will be interpolated onto dimensions within the Platform group of the `EchoData` object being used for calibration. Parameters ---------- env_params : xr.Dataset The environmental parameters to use for calibration. This data will be interpolated with a provided `EchoData` object. When `data_kind` is `"stationary"`, env_params must have a coordinate `"time3"`. When `data_kind` is `"mobile"`, env_params must have coordinates `"latitude"` and `"longitude"`. When `data_kind` is `"organized"`, env_params must have coordinates `"time"`, `"latitude"`, and `"longitude"`. This `data_kind` is not currently supported. data_kind : {"stationary", "mobile", "organized"} The type of the environmental parameters. `"stationary"`: environmental parameters from a fixed location (for example, a single CTD). `"mobile"` environmental parameters from a moving location (for example, a ship). `"organized"`: environmental parameters from many fixed locations (for example, multiple CTDs). interp_method: {"linear", "nearest", "zero", "slinear", "quadratic", "cubic"} Method for interpolation of environmental parameters with the data from the provided `EchoData` object. When `data_kind` is `"stationary"`, valid `interp_method`s are `"linear"`, `"nearest"`, `"zero"`, `"slinear"`, `"quadratic"`, and `"cubic"` (see <https://docs.scipy.org/doc/scipy/reference/reference/generated/scipy.interpolate.interp1d.html>). When `data_kind` is `"mobile"`, valid `interp_method`s are `"linear"`, `"nearest"`, and `"cubic"` (see <https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html>). When `data_kind` is `"organized"`, valid `interp_method`s are `"linear"` and `"nearest"` (see <https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interpn.html>). extrap_method: {"linear", "nearest"} Method for extrapolation of environmental parameters with the data from the provided `EchoData` object. Currently only supported when `data_kind` is `"stationary"`. Notes ----- Currently cases where `data_kind` is `"organized"` are not supported; support will be added in a future version. Examples -------- >>> env_params = xr.open_dataset("env_params.nc") >>> EnvParams(env_params, data_kind="mobile", interp_method="linear") >>> echopype.calibrate.compute_Sv(echodata, env_params=env_params) """ # noqa if interp_method not in VALID_INTERP_METHODS[data_kind]: raise ValueError(f"invalid interp_method {interp_method} for data_kind {data_kind}") self.env_params = env_params self.data_kind = data_kind self.interp_method = interp_method self.extrap_method = extrap_method def _apply(self, echodata) -> Dict[str, xr.DataArray]: if self.data_kind == "stationary": dims = ["time3"] elif self.data_kind == "mobile": dims = ["latitude", "longitude"] elif self.data_kind == "organized": dims = ["time", "latitude", "longitude"] else: raise ValueError("invalid data_kind") for dim in dims: if dim not in echodata["Platform"]: raise ValueError( f"could not interpolate env_params; EchoData is missing dimension {dim}" ) env_params = self.env_params if self.data_kind == "mobile": if np.isnan(echodata["Platform"]["time1"]).all(): raise ValueError("cannot perform mobile interpolation without time1") # only grab needed variables for the interpolation platform_data = echodata["Platform"][["latitude", "longitude"]] # compute_range needs indexing by ping_time interp_plat = platform_data.interp( {"time1": echodata["Sonar/Beam_group1"]["ping_time"]} ) result = {} for var, values in env_params.data_vars.items(): points = np.column_stack( (env_params["latitude"].data, env_params["longitude"].data) ) values = values.data xi = np.column_stack( ( interp_plat["latitude"].data, interp_plat["longitude"].data, ) ) interp = scipy.interpolate.griddata(points, values, xi, method=self.interp_method) result[var] = ("time1", interp) env_params = xr.Dataset( # we expect env_params to have coordinate time1 data_vars=result, coords={"time1": interp_plat["ping_time"].data}, ) else: # TODO: organized case min_max = { dim: {"min": env_params[dim].min(), "max": env_params[dim].max()} for dim in dims } extrap = env_params.interp( {dim: echodata["Platform"][dim].data for dim in dims}, method=self.extrap_method, # scipy interp uses "extrapolate" but scipy interpn uses None kwargs={"fill_value": "extrapolate" if len(dims) == 1 else None}, ) # only keep unique indexes; xarray requires that indexes be unique extrap_unique_idx = {dim: np.unique(extrap[dim], return_index=True)[1] for dim in dims} extrap = extrap.isel(**extrap_unique_idx) interp = env_params.interp( {dim: echodata["Platform"][dim].data for dim in dims}, method=self.interp_method, ) interp_unique_idx = {dim: np.unique(interp[dim], return_index=True)[1] for dim in dims} interp = interp.isel(**interp_unique_idx) if self.extrap_method is not None: less = extrap.sel( {dim: extrap[dim][extrap[dim] < min_max[dim]["min"]] for dim in dims} ) middle = interp.sel( { dim: interp[dim][ np.logical_and( interp[dim] >= min_max[dim]["min"], interp[dim] <= min_max[dim]["max"], ) ] for dim in dims } ) greater = extrap.sel( {dim: extrap[dim][extrap[dim] > min_max[dim]["max"]] for dim in dims} ) # remove empty datasets (xarray does not allow any dims from any datasets # to be length 0 in combine_by_coords) non_zero_dims = [ ds for ds in (less, middle, greater) if all(dim_len > 0 for dim_len in ds.dims.values()) ] env_params = xr.combine_by_coords(non_zero_dims) # if self.data_kind == "organized": # # get platform latitude and longitude indexed by ping_time # interp_plat = echodata["Platform"].interp( # {"time": echodata["Platform"]["ping_time"]} # ) # # get env_params latitude and longitude indexed by ping_time # env_params = env_params.interp( # { # "latitude": interp_plat["latitude"], # "longitude": interp_plat["longitude"], # } # ) if self.data_kind == "stationary": # renaming time3 (from Platform group) to time1 because we expect # environmental parameters to have dimension time1 return { var: env_params[var].rename({"time3": "time1"}) for var in ("temperature", "salinity", "pressure") } else: return {var: env_params[var] for var in ("temperature", "salinity", "pressure")}
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,800
OSOceanAcoustics/echopype
refs/heads/main
/.ci_helpers/check-version.py
import argparse import sys import echopype if __name__ == "__main__": parser = argparse.ArgumentParser(description="Check current echopype version.") parser.add_argument( "expected_version", type=str, nargs="?", default="0.5.0", help="Expected Echopype Version to check", ) args = parser.parse_args() expected_version = args.expected_version installed_version = echopype.__version__ if installed_version != expected_version: print( f"!! Installed version {installed_version} does not match expected version {expected_version}." # noqa ) sys.exit(1) else: print(f"Installed version {installed_version} is expected.") sys.exit(0)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,801
OSOceanAcoustics/echopype
refs/heads/main
/echopype/utils/coding.py
from re import search from typing import Any, Dict, Tuple import numpy as np import xarray as xr import zarr from dask.array.core import auto_chunks from dask.utils import parse_bytes from xarray import coding DEFAULT_TIME_ENCODING = { "units": "seconds since 1900-01-01T00:00:00+00:00", "calendar": "gregorian", "_FillValue": np.nan, "dtype": np.dtype("float64"), } COMPRESSION_SETTINGS = { "netcdf4": {"zlib": True, "complevel": 4}, # zarr compressors were chosen based on xarray results "zarr": { "float": {"compressor": zarr.Blosc(cname="zstd", clevel=3, shuffle=2)}, "int": {"compressor": zarr.Blosc(cname="lz4", clevel=5, shuffle=1, blocksize=0)}, "string": {"compressor": zarr.Blosc(cname="lz4", clevel=5, shuffle=1, blocksize=0)}, "time": {"compressor": zarr.Blosc(cname="lz4", clevel=5, shuffle=1, blocksize=0)}, }, } DEFAULT_ENCODINGS = { "ping_time": DEFAULT_TIME_ENCODING, "ping_time_transmit": DEFAULT_TIME_ENCODING, "time1": DEFAULT_TIME_ENCODING, "time2": DEFAULT_TIME_ENCODING, "time3": DEFAULT_TIME_ENCODING, "time4": DEFAULT_TIME_ENCODING, "time5": DEFAULT_TIME_ENCODING, } EXPECTED_VAR_DTYPE = { "channel": np.str_, "cal_channel_id": np.str_, "beam": np.str_, "channel_mode": np.byte, "beam_stabilisation": np.byte, "non_quantitative_processing": np.int16, } # channel name # beam name PREFERRED_CHUNKS = "preferred_chunks" def sanitize_dtypes(ds: xr.Dataset) -> xr.Dataset: """ Validates and fixes data type for expected variables """ if isinstance(ds, xr.Dataset): for name, var in ds.variables.items(): if name in EXPECTED_VAR_DTYPE: expected_dtype = EXPECTED_VAR_DTYPE[name] elif np.issubdtype(var.dtype, np.object_): # Defaulting to strings dtype for object data types expected_dtype = np.str_ else: # For everything else, this should be the same expected_dtype = var.dtype if not np.issubdtype(var.dtype, expected_dtype): ds[name] = var.astype(expected_dtype) return ds def _encode_dataarray(da, dtype): """Encodes and decode datetime64 array similar to writing to file""" if da.size == 0: return da read_encoding = { "units": "seconds since 1900-01-01T00:00:00+00:00", "calendar": "gregorian", } if dtype in [np.float64, np.int64]: encoded_data = da else: # fmt: off encoded_data, _, _ = coding.times.encode_cf_datetime( da, **read_encoding ) # fmt: on return coding.times.decode_cf_datetime(encoded_data, **read_encoding) def _get_auto_chunk( variable: xr.DataArray, chunk_size: "int | str | float" = "100MB" ) -> Tuple[int]: """ Calculate default chunks for a data array based on desired chunk size Parameters ---------- variable : xr.DataArray The data array variable to be calculated chunk_size : int or str or float The desired max chunk size for the array. Default is 100MB Returns ------- tuple The chunks """ auto_tuple = tuple(["auto" for i in variable.shape]) chunks = auto_chunks(auto_tuple, variable.shape, chunk_size, variable.dtype) return tuple([c[0] if isinstance(c, tuple) else c for c in chunks]) def set_time_encodings(ds: xr.Dataset) -> xr.Dataset: """ Set the default encoding for variables. """ new_ds = ds.copy(deep=True) for var, encoding in DEFAULT_ENCODINGS.items(): if var in new_ds: da = new_ds[var].copy() # Process all variable names matching the patterns *_time* or time<digits> # Examples: ping_time, ping_time_2, time1, time2 if bool(search(r"_time|^time[\d]+$", var)): new_ds[var] = xr.apply_ufunc( _encode_dataarray, da, keep_attrs=True, kwargs={"dtype": da.dtype}, ) new_ds[var].encoding = encoding return new_ds def get_zarr_compression(var: xr.Variable, compression_settings: dict) -> dict: """Returns the proper zarr compressor for a given variable type""" if np.issubdtype(var.dtype, np.floating): return compression_settings["float"] elif np.issubdtype(var.dtype, np.integer): return compression_settings["int"] elif np.issubdtype(var.dtype, np.str_): return compression_settings["string"] elif np.issubdtype(var.dtype, np.datetime64): return compression_settings["time"] else: raise NotImplementedError(f"Zarr Encoding for dtype = {var.dtype} has not been set!") def set_zarr_encodings( ds: xr.Dataset, compression_settings: dict, chunk_size: str = "100MB", ctol: str = "10MB" ) -> dict: """ Obtains all variable encodings based on zarr default values Parameters ---------- ds : xr.Dataset The dataset object to generate encoding for compression_settings : dict The compression settings dictionary chunk_size : dict The desired chunk size ctol : dict The chunk size tolerance before rechunking Returns ------- dict The encoding dictionary """ # create zarr specific encoding encoding = dict() for name, val in ds.variables.items(): encoding[name] = {**val.encoding} encoding[name].update(get_zarr_compression(val, compression_settings)) # Always optimize chunk if not specified already # user can specify desired chunk in encoding existing_chunks = encoding[name].get("chunks", None) optimal_chunk_size = parse_bytes(chunk_size) chunk_size_tolerance = parse_bytes(ctol) if len(val.shape) > 0: rechunk = True if existing_chunks is not None: # Perform chunk optimization # 1. Get the chunk total from existing chunks chunk_total = np.prod(existing_chunks) * val.dtype.itemsize # 2. Get chunk size difference from the optimal chunk size chunk_diff = optimal_chunk_size - chunk_total # 3. Check difference from tolerance, if diff is less than # tolerance then no need to rechunk if chunk_diff < chunk_size_tolerance: rechunk = False chunks = existing_chunks if rechunk: # Use dask auto chunk to determine the optimal chunk # spread for optimal chunk size chunks = _get_auto_chunk(val, chunk_size=chunk_size) encoding[name]["chunks"] = chunks return encoding def set_netcdf_encodings( ds: xr.Dataset, compression_settings: Dict[str, Any] = {}, ) -> Dict[str, Dict[str, Any]]: """ Obtains all variables encodings based on netcdf default values Parameters ---------- ds : xr.Dataset The dataset object to generate encoding for compression_settings : dict The compression settings dictionary Returns ------- dict The final encoding values for dataset variables """ encoding = dict() for name, val in ds.variables.items(): encoding[name] = {**val.encoding} if np.issubdtype(val.dtype, np.str_): encoding[name].update( { "zlib": False, } ) elif compression_settings: encoding[name].update(compression_settings) else: encoding[name].update(COMPRESSION_SETTINGS["netcdf4"]) return encoding def set_storage_encodings(ds: xr.Dataset, compression_settings: dict, engine: str) -> dict: """ Obtains the appropriate zarr or netcdf specific encodings for each variable in ``ds``. """ if compression_settings is not None: if engine == "zarr": encoding = set_zarr_encodings(ds, compression_settings) elif engine == "netcdf4": encoding = set_netcdf_encodings(ds, compression_settings) else: raise RuntimeError(f"Obtaining encodings for the engine {engine} is not allowed.") else: encoding = dict() return encoding
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,802
OSOceanAcoustics/echopype
refs/heads/main
/echopype/calibrate/ek80_complex.py
from collections import defaultdict from typing import Dict, Literal, Optional, Union import numpy as np import xarray as xr from scipy import signal from ..convert.set_groups_ek80 import DECIMATION, FILTER_IMAG, FILTER_REAL def tapered_chirp( fs, transmit_duration_nominal, slope, transmit_frequency_start, transmit_frequency_stop, ): """ Create the chirp replica following implementation from Lars Anderson. Ref source: https://github.com/CRIMAC-WP4-Machine-learning/CRIMAC-Raw-To-Svf-TSf/blob/main/Core/Calculation.py # noqa """ tau = transmit_duration_nominal f0 = transmit_frequency_start f1 = transmit_frequency_stop nsamples = int(np.floor(tau * fs)) t = np.linspace(0, nsamples - 1, num=nsamples) * 1 / fs a = np.pi * (f1 - f0) / tau b = 2 * np.pi * f0 y = np.cos(a * t * t + b * t) L = int(np.round(tau * fs * slope * 2.0)) # Length of hanning window w = 0.5 * (1.0 - np.cos(2.0 * np.pi * np.arange(0, L, 1) / (L - 1))) N = len(y) w1 = w[0 : int(len(w) / 2)] w2 = w[int(len(w) / 2) : -1] i0 = 0 i1 = len(w1) i2 = N - len(w2) i3 = N y[i0:i1] = y[i0:i1] * w1 y[i2:i3] = y[i2:i3] * w2 return y / np.max(y), t # amplitude needs to be normalized def filter_decimate_chirp(coeff_ch: Dict, y_ch: np.array, fs: float): """Filter and decimate the transmit replica for one channel. Parameters ---------- coeff_ch : dict a dictionary containing filter coefficients and decimation factors for ``ch_id`` y_ch : np.array chirp from _tapered_chirp fs : float system sampling frequency [Hz] """ # Get values # WBT filter and decimation ytx_wbt = signal.convolve(y_ch, coeff_ch["wbt_fil"]) ytx_wbt_deci = ytx_wbt[0 :: coeff_ch["wbt_decifac"]] # PC filter and decimation ytx_pc = signal.convolve(ytx_wbt_deci, coeff_ch["pc_fil"]) ytx_pc_deci = ytx_pc[0 :: coeff_ch["pc_decifac"]] ytx_pc_deci_time = ( np.arange(ytx_pc_deci.size) * 1 / fs * coeff_ch["wbt_decifac"] * coeff_ch["pc_decifac"] ) return ytx_pc_deci, ytx_pc_deci_time def get_vend_filter_EK80( vend: xr.Dataset, channel_id: str, filter_name: Literal["WBT", "PC"], param_type: Literal["coeff", "decimation"], ) -> Optional[Union[np.ndarray, int]]: """ Get filter coefficients stored in the Vendor_specific group attributes. Parameters ---------- vend: xr.Dataset An xr.Dataset from EchoData["Vendor_specific"] channel_id : str channel id for which the param to be retrieved filter_name : str name of filter coefficients to retrieve param_type : str 'coeff' or 'decimation' Returns ------- np.ndarray or int or None The filter coefficient or the decimation factor """ var_imag = f"{filter_name}_{FILTER_IMAG}" var_real = f"{filter_name}_{FILTER_REAL}" var_df = f"{filter_name}_{DECIMATION}" # if the variables are not in the dataset, simply return None if not all([var in vend for var in [var_imag, var_real, var_df]]): return None # Select the channel requested sel_vend = vend.sel(channel=channel_id) if param_type == "coeff": # Compute complex number from imaginary and real parts v_complex = sel_vend[var_real] + 1j * sel_vend[var_imag] # Drop nan fillers and get the values v = v_complex.dropna(dim=f"{filter_name}_filter_n").values return v else: # Get the decimation value return sel_vend[var_df].values def get_filter_coeff(vend: xr.Dataset) -> Dict: """ Get WBT and PC filter coefficients for constructing the transmit replica. Parameters ---------- vend: xr.Dataset An xr.Dataset from EchoData["Vendor_specific"] Returns ------- dict A dictionary indexed by ``channel`` and values being dictionaries containing filter coefficients and decimation factors for constructing the transmit replica. """ coeff = defaultdict(dict) for ch_id in vend["channel"].values: # filter coefficients and decimation factor coeff[ch_id]["wbt_fil"] = get_vend_filter_EK80(vend, ch_id, "WBT", "coeff") coeff[ch_id]["pc_fil"] = get_vend_filter_EK80(vend, ch_id, "PC", "coeff") coeff[ch_id]["wbt_decifac"] = get_vend_filter_EK80(vend, ch_id, "WBT", "decimation") coeff[ch_id]["pc_decifac"] = get_vend_filter_EK80(vend, ch_id, "PC", "decimation") return coeff def get_tau_effective( ytx_dict: Dict[str, np.array], fs_deci_dict: Dict[str, float], waveform_mode: str, channel: xr.DataArray, ping_time: xr.DataArray, ): """Compute effective pulse length. Parameters ---------- ytx_dict : dict A dict of transmit signals, with keys being the ``channel`` and values being either a vector when the transmit signals are identical across all pings or a 2D array when the transmit signals vary across ping fs_deci_dict : dict A dict of sampling frequency of the decimated (recorded) signal, with keys being the ``channel`` waveform_mode : str ``CW`` for CW-mode samples, either recorded as complex or power samples ``BB`` for BB-mode samples, recorded as complex samples """ tau_effective = {} for ch, ytx in ytx_dict.items(): if waveform_mode == "BB": ytxa = signal.convolve(ytx, np.flip(np.conj(ytx))) / np.linalg.norm(ytx) ** 2 ptxa = np.abs(ytxa) ** 2 elif waveform_mode == "CW": ptxa = np.abs(ytx) ** 2 # energy of transmit signal tau_effective[ch] = ptxa.sum() / (ptxa.max() * fs_deci_dict[ch]) # set up coordinates if len(ytx.shape) == 1: # ytx is a vector (transmit signals are identical across pings) coords = {"channel": channel} elif len(ytx.shape) == 2: # ytx is a matrix (transmit signals vary across pings) coords = {"channel": channel, "ping_time": ping_time} vals = np.array(list(tau_effective.values())).squeeze() if vals.size == 1: vals = np.expand_dims(vals, axis=0) tau_effective = xr.DataArray( data=vals, coords=coords, ) return tau_effective def get_transmit_signal( beam: xr.Dataset, coeff: Dict, waveform_mode: str, fs: Union[float, xr.DataArray], ): """Reconstruct transmit signal and compute effective pulse length. Parameters ---------- beam : xr.Dataset EchoData["Sonar/Beam_group1"] selected with channel subset coeff : dict a dictionary indexed by ``channel`` and values being dictionaries containing filter coefficients and decimation factors for constructing the transmit replica. waveform_mode : str ``CW`` for CW-mode samples, either recorded as complex or power samples ``BB`` for BB-mode samples, recorded as complex samples Return ------ y_all Transmit replica (BB: broadband chirp, CW: constant frequency sinusoid) y_time_all Timestamp for the transmit replica """ # Make sure it is BB mode data # This is already checked in calibrate_ek # but keeping this here for use as standalone function if waveform_mode == "BB" and np.all(beam["transmit_type"] == "CW"): raise TypeError("File does not contain BB mode complex samples!") # Generate all transmit replica y_all = {} y_time_all = {} # TODO: expand to deal with the case with varying tx param across ping_time tx_param_names = [ "transmit_duration_nominal", "slope", "transmit_frequency_start", "transmit_frequency_stop", ] for ch in beam["channel"].values: tx_params = {} for p in tx_param_names: tx_params[p] = np.unique(beam[p].sel(channel=ch)) if tx_params[p].size != 1: raise TypeError("File contains changing %s!" % p) fs_chan = fs.sel(channel=ch).data if isinstance(fs, xr.DataArray) else fs tx_params["fs"] = fs_chan y_ch, _ = tapered_chirp(**tx_params) # Filter and decimate chirp template y_ch, y_tmp_time = filter_decimate_chirp(coeff_ch=coeff[ch], y_ch=y_ch, fs=fs_chan) # Fill into output dict y_all[ch] = y_ch y_time_all[ch] = y_tmp_time return y_all, y_time_all def compress_pulse(backscatter: xr.DataArray, chirp: Dict) -> xr.DataArray: """Perform pulse compression on the backscatter data. Parameters ---------- backscatter : xr.DataArray complex backscatter samples chirp : dict transmit chirp replica indexed by ``channel`` Returns ------- xr.DataArray A data array containing pulse compression output. """ pc_all = [] for chan in backscatter["channel"]: backscatter_chan = backscatter.sel(channel=chan).dropna(dim="beam", how="all") tx = chirp[str(chan.values)] replica = np.flipud(np.conj(tx)) pc = xr.apply_ufunc( lambda m: np.apply_along_axis( lambda m: (signal.convolve(m, replica, mode="full")[tx.size - 1 :]), axis=2, arr=m, ), backscatter_chan, input_core_dims=[["range_sample"]], output_core_dims=[["range_sample"]], # exclude_dims={"range_sample"}, ) pc_all.append(pc) pc_all = xr.DataArray( pc_all, coords={ "channel": backscatter["channel"], "ping_time": backscatter["ping_time"], "beam": backscatter["beam"], "range_sample": backscatter["range_sample"], }, ) return pc_all def get_norm_fac(chirp: Dict) -> xr.DataArray: """ Get normalization factor from the chirp dictionary. Parameters ---------- chirp : dict transmit chirp replica indexed by ``channel`` Returns ------- xr.DataArray A data array containing the normalization factor, with channel coordinate """ norm_fac = [] ch_all = [] for ch, tx in chirp.items(): norm_fac.append(np.linalg.norm(tx) ** 2) ch_all.append(ch) return xr.DataArray(norm_fac, coords={"channel": ch_all})
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,803
OSOceanAcoustics/echopype
refs/heads/main
/echopype/consolidate/__init__.py
from .api import add_depth, add_location, add_splitbeam_angle, swap_dims_channel_frequency __all__ = ["swap_dims_channel_frequency", "add_depth", "add_location", "add_splitbeam_angle"]
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,804
OSOceanAcoustics/echopype
refs/heads/main
/echopype/commongrid/api.py
""" Functions for enhancing the spatial and temporal coherence of data. """ import numpy as np import pandas as pd import xarray as xr from ..utils.prov import add_processing_level, echopype_prov_attrs, insert_input_processing_level from .mvbs import get_MVBS_along_channels def _set_var_attrs(da, long_name, units, round_digits, standard_name=None): """ Attach common attributes to DataArray variable. Parameters ---------- da : xr.DataArray DataArray that will receive attributes long_name : str Variable long_name attribute units : str Variable units attribute round_digits : int Number of digits after decimal point for rounding off actual_range standard_name : str CF standard_name, if available (optional) """ da.attrs = { "long_name": long_name, "units": units, "actual_range": [ round(float(da.min().values), round_digits), round(float(da.max().values), round_digits), ], } if standard_name: da.attrs["standard_name"] = standard_name def _set_MVBS_attrs(ds): """ Attach common attributes. Parameters ---------- ds : xr.Dataset dataset containing MVBS """ ds["ping_time"].attrs = { "long_name": "Ping time", "standard_name": "time", "axis": "T", } _set_var_attrs( ds["Sv"], long_name="Mean volume backscattering strength (MVBS, mean Sv re 1 m-1)", units="dB", round_digits=2, ) @add_processing_level("L3*") def compute_MVBS(ds_Sv, range_meter_bin=20, ping_time_bin="20S"): """ Compute Mean Volume Backscattering Strength (MVBS) based on intervals of range (``echo_range``) 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_Sv : xr.Dataset dataset containing Sv and ``echo_range`` [m] range_meter_bin : Union[int, float] bin size along ``echo_range`` in meters, default to ``20`` ping_time_bin : str bin size along ``ping_time``, default to ``20S`` Returns ------- A dataset containing bin-averaged Sv """ # create bin information for echo_range range_interval = np.arange(0, ds_Sv["echo_range"].max() + range_meter_bin, range_meter_bin) # create bin information needed for ping_time ping_interval = ( ds_Sv.ping_time.resample(ping_time=ping_time_bin, skipna=True).asfreq().ping_time.values ) # calculate the MVBS along each channel MVBS_values = get_MVBS_along_channels(ds_Sv, range_interval, ping_interval) # create MVBS dataset ds_MVBS = xr.Dataset( data_vars={"Sv": (["channel", "ping_time", "echo_range"], MVBS_values)}, coords={ "ping_time": ping_interval, "channel": ds_Sv.channel, "echo_range": range_interval[:-1], }, ) # TODO: look into why 'filenames' exist here as a variable # Added this check to support the test in test_process.py::test_compute_MVBS if "filenames" in ds_MVBS.variables: ds_MVBS = ds_MVBS.drop_vars("filenames") # ping_time_bin parsing and conversions # Need to convert between pd.Timedelta and np.timedelta64 offsets/frequency strings # https://xarray.pydata.org/en/stable/generated/xarray.Dataset.resample.html # https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.resample.html # https://pandas.pydata.org/docs/reference/api/pandas.Timedelta.html # https://pandas.pydata.org/docs/reference/api/pandas.Timedelta.resolution_string.html # https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects # https://numpy.org/devdocs/reference/arrays.datetime.html#datetime-units timedelta_units = { "d": {"nptd64": "D", "unitstr": "day"}, "h": {"nptd64": "h", "unitstr": "hour"}, "t": {"nptd64": "m", "unitstr": "minute"}, "min": {"nptd64": "m", "unitstr": "minute"}, "s": {"nptd64": "s", "unitstr": "second"}, "l": {"nptd64": "ms", "unitstr": "millisecond"}, "ms": {"nptd64": "ms", "unitstr": "millisecond"}, "u": {"nptd64": "us", "unitstr": "microsecond"}, "us": {"nptd64": "ms", "unitstr": "millisecond"}, "n": {"nptd64": "ns", "unitstr": "nanosecond"}, "ns": {"nptd64": "ms", "unitstr": "millisecond"}, } ping_time_bin_td = pd.Timedelta(ping_time_bin) # res = resolution (most granular time unit) ping_time_bin_resunit = ping_time_bin_td.resolution_string.lower() ping_time_bin_resvalue = int( ping_time_bin_td / np.timedelta64(1, timedelta_units[ping_time_bin_resunit]["nptd64"]) ) ping_time_bin_resunit_label = timedelta_units[ping_time_bin_resunit]["unitstr"] # Attach attributes _set_MVBS_attrs(ds_MVBS) ds_MVBS["echo_range"].attrs = {"long_name": "Range distance", "units": "m"} ds_MVBS["Sv"] = ds_MVBS["Sv"].assign_attrs( { "cell_methods": ( f"ping_time: mean (interval: {ping_time_bin_resvalue} {ping_time_bin_resunit_label} " # noqa "comment: ping_time is the interval start) " f"echo_range: mean (interval: {range_meter_bin} meter " "comment: echo_range is the interval start)" ), "binning_mode": "physical units", "range_meter_interval": str(range_meter_bin) + "m", "ping_time_interval": ping_time_bin, "actual_range": [ round(float(ds_MVBS["Sv"].min().values), 2), round(float(ds_MVBS["Sv"].max().values), 2), ], } ) prov_dict = echopype_prov_attrs(process_type="processing") prov_dict["processing_function"] = "commongrid.compute_MVBS" ds_MVBS = ds_MVBS.assign_attrs(prov_dict) ds_MVBS["frequency_nominal"] = ds_Sv["frequency_nominal"] # re-attach frequency_nominal ds_MVBS = insert_input_processing_level(ds_MVBS, input_ds=ds_Sv) return ds_MVBS @add_processing_level("L3*") def 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_Sv : xr.Dataset dataset containing ``Sv`` and ``echo_range`` [m] range_sample_num : int number of samples to average along the ``range_sample`` dimension, default to 100 ping_num : int number of pings to average, default to 100 Returns ------- A dataset containing bin-averaged Sv """ da_sv = 10 ** (ds_Sv["Sv"] / 10) # average should be done in linear domain da = 10 * np.log10( da_sv.coarsen(ping_time=ping_num, range_sample=range_sample_num, boundary="pad").mean( skipna=True ) ) # Attach attributes and coarsened echo_range da.name = "Sv" ds_MVBS = da.to_dataset() ds_MVBS.coords["range_sample"] = ( "range_sample", np.arange(ds_MVBS["range_sample"].size), {"long_name": "Along-range sample number, base 0"}, ) # reset range_sample to start from 0 ds_MVBS["echo_range"] = ( ds_Sv["echo_range"] .coarsen( # binned echo_range (use first value in each average bin) ping_time=ping_num, range_sample=range_sample_num, boundary="pad" ) .min(skipna=True) ) _set_MVBS_attrs(ds_MVBS) ds_MVBS["Sv"] = ds_MVBS["Sv"].assign_attrs( { "cell_methods": ( f"ping_time: mean (interval: {ping_num} pings " "comment: ping_time is the interval start) " f"range_sample: mean (interval: {range_sample_num} samples along range " "comment: range_sample is the interval start)" ), "comment": "MVBS binned on the basis of range_sample and ping number specified as index numbers", # noqa "binning_mode": "sample number", "range_sample_interval": f"{range_sample_num} samples along range", "ping_interval": f"{ping_num} pings", "actual_range": [ round(float(ds_MVBS["Sv"].min().values), 2), round(float(ds_MVBS["Sv"].max().values), 2), ], } ) prov_dict = echopype_prov_attrs(process_type="processing") prov_dict["processing_function"] = "commongrid.compute_MVBS_index_binning" ds_MVBS = ds_MVBS.assign_attrs(prov_dict) ds_MVBS["frequency_nominal"] = ds_Sv["frequency_nominal"] # re-attach frequency_nominal ds_MVBS = insert_input_processing_level(ds_MVBS, input_ds=ds_Sv) return ds_MVBS # def compute_NASC( # ds_Sv: xr.Dataset, # cell_dist: Union[int, float], # TODO: allow xr.DataArray # cell_depth: Union[int, float], # TODO: allow xr.DataArray # ) -> xr.Dataset: # """ # Compute Nautical Areal Scattering Coefficient (NASC) from an Sv dataset. # Parameters # ---------- # ds_Sv : xr.Dataset # A dataset containing Sv data. # The Sv dataset must contain ``latitude``, ``longitude``, and ``depth`` as data variables. # cell_dist: int, float # The horizontal size of each NASC cell, in nautical miles [nmi] # cell_depth: int, float # The vertical size of each NASC cell, in meters [m] # Returns # ------- # xr.Dataset # A dataset containing NASC # Notes # ----- # The NASC computation implemented here corresponds to the Echoview algorithm PRC_NASC # https://support.echoview.com/WebHelp/Reference/Algorithms/Analysis_Variables/PRC_ABC_and_PRC_NASC.htm#PRC_NASC # noqa # The difference is that since in echopype masking of the Sv dataset is done explicitly using # functions in the ``mask`` subpackage so the computation only involves computing the # mean Sv and the mean height within each cell. # In addition, here 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. # """ # # Check Sv contains lat/lon # if "latitude" not in ds_Sv or "longitude" not in ds_Sv: # raise ValueError("Both 'latitude' and 'longitude' must exist in the input Sv dataset.") # # Check if depth vectors are identical within each channel # if not ds_Sv["depth"].groupby("channel").map(check_identical_depth).all(): # raise ValueError( # "Only Sv data with identical depth vectors across all pings " # "are allowed in the current compute_NASC implementation." # ) # # Get distance from lat/lon in nautical miles # dist_nmi = get_distance_from_latlon(ds_Sv) # # Find binning indices along distance # bin_num_dist, dist_bin_idx = get_dist_bin_info(dist_nmi, cell_dist) # dist_bin_idx is 1-based # # Find binning indices along depth: channel-dependent # bin_num_depth, depth_bin_idx = get_depth_bin_info(ds_Sv, cell_depth) # depth_bin_idx is 1-based # noqa # # Compute mean sv (volume backscattering coefficient, linear scale) # # This is essentially to compute MVBS over a the cell defined here, # # which are typically larger than those used for MVBS. # # The implementation below is brute force looping, but can be optimized # # by experimenting with different delayed schemes. # # The optimized routines can then be used here and # # in commongrid.compute_MVBS and clean.estimate_noise # sv_mean = [] # for ch_seq in np.arange(ds_Sv["channel"].size): # # TODO: .compute each channel sequentially? # # dask.delay within each channel? # ds_Sv_ch = ds_Sv["Sv"].isel(channel=ch_seq).data # preserve the underlying type # sv_mean_dist_depth = [] # for dist_idx in np.arange(bin_num_dist) + 1: # along ping_time # sv_mean_depth = [] # for depth_idx in np.arange(bin_num_depth) + 1: # along depth # # Sv dim: ping_time x depth # Sv_cut = ds_Sv_ch[dist_idx == dist_bin_idx, :][ # :, depth_idx == depth_bin_idx[ch_seq] # ] # sv_mean_depth.append(np.nanmean(10 ** (Sv_cut / 10))) # sv_mean_dist_depth.append(sv_mean_depth) # sv_mean.append(sv_mean_dist_depth) # # Compute mean height # # For data with uniform depth step size, mean height = vertical size of cell # height_mean = cell_depth # # TODO: generalize to variable depth step size # ds_NASC = xr.DataArray( # np.array(sv_mean) * height_mean, # dims=["channel", "distance", "depth"], # coords={ # "channel": ds_Sv["channel"].values, # "distance": np.arange(bin_num_dist) * cell_dist, # "depth": np.arange(bin_num_depth) * cell_depth, # }, # name="NASC", # ).to_dataset() # ds_NASC["frequency_nominal"] = ds_Sv["frequency_nominal"] # re-attach frequency_nominal # # Attach attributes # _set_var_attrs( # ds_NASC["NASC"], # long_name="Nautical Areal Scattering Coefficient (NASC, m2 nmi-2)", # units="m2 nmi-2", # round_digits=3, # ) # _set_var_attrs(ds_NASC["distance"], "Cumulative distance", "m", 3) # _set_var_attrs(ds_NASC["depth"], "Cell depth", "m", 3, standard_name="depth") # # Calculate and add ACDD bounding box global attributes # ds_NASC.attrs["Conventions"] = "CF-1.7,ACDD-1.3" # ds_NASC.attrs["time_coverage_start"] = np.datetime_as_string( # ds_Sv["ping_time"].min().values, timezone="UTC" # ) # ds_NASC.attrs["time_coverage_end"] = np.datetime_as_string( # ds_Sv["ping_time"].max().values, timezone="UTC" # ) # ds_NASC.attrs["geospatial_lat_min"] = round(float(ds_Sv["latitude"].min().values), 5) # ds_NASC.attrs["geospatial_lat_max"] = round(float(ds_Sv["latitude"].max().values), 5) # ds_NASC.attrs["geospatial_lon_min"] = round(float(ds_Sv["longitude"].min().values), 5) # ds_NASC.attrs["geospatial_lon_max"] = round(float(ds_Sv["longitude"].max().values), 5) # return ds_NASC def regrid(): return 1
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,805
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/echodata/test_echodata_combine.py
from datetime import datetime from textwrap import dedent from pathlib import Path import tempfile import numpy as np import pytest import xarray as xr import echopype from echopype.utils.coding import DEFAULT_ENCODINGS from echopype.echodata import EchoData from echopype.echodata.combine import ( _create_channel_selection_dict, _check_channel_consistency, _merge_attributes ) @pytest.fixture def ek60_diff_range_sample_test_data(test_path): files = [ ("ncei-wcsd", "SH1701", "TEST-D20170114-T202932.raw"), ("ncei-wcsd", "SH1701", "TEST-D20170114-T203337.raw"), ("ncei-wcsd", "SH1701", "TEST-D20170114-T203853.raw"), ] return [test_path["EK60"].joinpath(*f) for f in files] @pytest.fixture(scope="module") def ek60_test_data(test_path): files = [ ("ncei-wcsd", "Summer2017-D20170620-T011027.raw"), ("ncei-wcsd", "Summer2017-D20170620-T014302.raw"), ("ncei-wcsd", "Summer2017-D20170620-T021537.raw"), ] return [test_path["EK60"].joinpath(*f) for f in files] @pytest.fixture(scope="module") def ek60_multi_test_data(test_path): files = [ ("ncei-wcsd", "Summer2017-D20170620-T011027.raw"), ("ncei-wcsd", "Summer2017-D20170620-T014302.raw"), ("ncei-wcsd", "Summer2017-D20170620-T021537.raw"), ("ncei-wcsd", "Summer2017-D20170620-T024811.raw") ] return [test_path["EK60"].joinpath(*f) for f in files] @pytest.fixture def ek80_test_data(test_path): files = [ ("echopype-test-D20211005-T000706.raw",), ("echopype-test-D20211005-T000737.raw",), ("echopype-test-D20211005-T000810.raw",), ("echopype-test-D20211005-T000843.raw",), ] return [test_path["EK80_NEW"].joinpath(*f) for f in files] @pytest.fixture def ek80_broadband_same_range_sample_test_data(test_path): files = [ ("ncei-wcsd", "SH1707", "Reduced_D20170826-T205615.raw"), ("ncei-wcsd", "SH1707", "Reduced_D20170826-T205659.raw"), ("ncei-wcsd", "SH1707", "Reduced_D20170826-T205742.raw"), ] return [test_path["EK80"].joinpath(*f) for f in files] @pytest.fixture def ek80_narrowband_diff_range_sample_test_data(test_path): files = [ ("ncei-wcsd", "SH2106", "EK80", "Reduced_Hake-D20210701-T130426.raw"), ("ncei-wcsd", "SH2106", "EK80", "Reduced_Hake-D20210701-T131325.raw"), ("ncei-wcsd", "SH2106", "EK80", "Reduced_Hake-D20210701-T131621.raw"), ] return [test_path["EK80"].joinpath(*f) for f in files] @pytest.fixture def azfp_test_data(test_path): # TODO: in the future we should replace these files with another set of # similarly small set of files, for example the files from the location below: # "https://rawdata.oceanobservatories.org/files/CE01ISSM/R00015/instrmts/dcl37/ZPLSC_sn55076/DATA/202109/*" # This is because we have lost track of where the current files came from, # since the filenames does not contain the site identifier. files = [ ("ooi", "18100407.01A"), ("ooi", "18100408.01A"), ("ooi", "18100409.01A"), ] return [test_path["AZFP"].joinpath(*f) for f in files] @pytest.fixture def azfp_test_xml(test_path): return test_path["AZFP"].joinpath(*("ooi", "18092920.XML")) @pytest.fixture( params=[ { "sonar_model": "EK60", "xml_file": None, "files": "ek60_test_data" }, { "sonar_model": "EK60", "xml_file": None, "files": "ek60_diff_range_sample_test_data" }, { "sonar_model": "AZFP", "xml_file": "azfp_test_xml", "files": "azfp_test_data" }, { "sonar_model": "EK80", "xml_file": None, "files": "ek80_broadband_same_range_sample_test_data" }, { "sonar_model": "EK80", "xml_file": None, "files": "ek80_narrowband_diff_range_sample_test_data" } ], ids=["ek60", "ek60_diff_range_sample", "azfp", "ek80_bb_same_range_sample", "ek80_nb_diff_range_sample"] ) def raw_datasets(request): files = request.param["files"] xml_file = request.param["xml_file"] if xml_file is not None: xml_file = request.getfixturevalue(xml_file) files = request.getfixturevalue(files) return ( files, request.param['sonar_model'], xml_file, request.node.callspec.id ) def test_combine_echodata(raw_datasets): ( files, sonar_model, xml_file, param_id, ) = raw_datasets eds = [echopype.open_raw(file, sonar_model, xml_file) for file in files] append_dims = {"filenames", "time1", "time2", "time3", "ping_time"} combined = echopype.combine_echodata(eds) # Test Provenance conversion and combination attributes for attr_token in ["software_name", "software_version", "time"]: assert f"conversion_{attr_token}" in combined['Provenance'].attrs assert f"combination_{attr_token}" in combined['Provenance'].attrs def attr_time_to_dt(time_str): return datetime.strptime(time_str, '%Y-%m-%dT%H:%M:%SZ') assert ( attr_time_to_dt(combined['Provenance'].attrs['conversion_time']) <= attr_time_to_dt(combined['Provenance'].attrs['combination_time']) ) # get all possible dimensions that should be dropped # these correspond to the attribute arrays created all_drop_dims = [] for grp in combined.group_paths: # format group name appropriately ed_name = grp.replace("-", "_").replace("/", "_").lower() # create and append attribute array dimension all_drop_dims.append(ed_name + "_attr_key") # add dimension for Provenance group all_drop_dims.append("echodata_filename") for group_name in combined.group_paths: # get all Datasets to be combined combined_group: xr.Dataset = combined[group_name] eds_groups = [ ed[group_name] for ed in eds if ed[group_name] is not None ] # all grp dimensions that are in all_drop_dims if combined_group is None: grp_drop_dims = [] concat_dims = [] else: grp_drop_dims = list(set(combined_group.dims).intersection(set(all_drop_dims))) concat_dims = list(set(combined_group.dims).intersection(append_dims)) # concat all Datasets along each concat dimension diff_concats = [] for dim in concat_dims: drop_dims = [c_dim for c_dim in concat_dims if c_dim != dim] diff_concats.append(xr.concat([ed_subset.drop_dims(drop_dims) for ed_subset in eds_groups], dim=dim, coords="minimal", data_vars="minimal")) if len(diff_concats) < 1: test_ds = eds_groups[0] # needed for groups that do not have append dims else: # create the full combined Dataset test_ds = xr.merge(diff_concats, compat="override") # correctly set filenames values for constructed combined Dataset if "filenames" in test_ds: test_ds.filenames.values[:] = np.arange(len(test_ds.filenames), dtype=int) # correctly modify Provenance attributes, so we can do a direct compare if group_name == "Provenance": del test_ds.attrs["conversion_time"] del combined_group.attrs["conversion_time"] if group_name != "Provenance": # TODO: Skip for Provenance group for now, need to figure out how to test this properly if (combined_group is not None) and (test_ds is not None): assert test_ds.identical(combined_group.drop_dims(grp_drop_dims)) def _check_prov_ds(prov_ds, eds): """Checks the Provenance dataset against source_filenames variable and global attributes in the original echodata object""" for i in range(prov_ds.dims["echodata_filename"]): ed_ds = eds[i] one_ds = prov_ds.isel(echodata_filename=i, filenames=i) for key, value in one_ds.data_vars.items(): if key == "source_filenames": ed_group = "Provenance" assert np.array_equal( ed_ds[ed_group][key].isel(filenames=0).values, value.values ) else: ed_group = value.attrs.get("echodata_group") expected_val = ed_ds[ed_group].attrs[key] if not isinstance(expected_val, str): expected_val = str(expected_val) assert str(value.values) == expected_val @pytest.mark.parametrize("test_param", [ "single", "multi", "combined" ] ) def test_combine_echodata_combined_append(ek60_multi_test_data, test_param, sonar_model="EK60"): """ Integration test for combine_echodata with the following cases: - a single combined echodata object and a single echodata object - a single combined echodata object and 2 single echodata objects - a single combined echodata object and another combined single echodata object """ eds = [ echopype.open_raw(raw_file=file, sonar_model=sonar_model) for file in ek60_multi_test_data ] # create temporary directory for zarr store temp_zarr_dir = tempfile.TemporaryDirectory() first_zarr = ( temp_zarr_dir.name + f"/combined_echodata.zarr" ) second_zarr = ( temp_zarr_dir.name + f"/combined_echodata2.zarr" ) # First combined file combined_ed = echopype.combine_echodata(eds[:2]) combined_ed.to_zarr(first_zarr, overwrite=True) def _check_prov_ds_and_dims(sel_comb_ed, n_val_expected): prov_ds = sel_comb_ed["Provenance"] for _, n_val in prov_ds.dims.items(): assert n_val == n_val_expected _check_prov_ds(prov_ds, eds) # Checks for Provenance group # Both dims of filenames and echodata filename should be 2 expected_n_vals = 2 _check_prov_ds_and_dims(combined_ed, expected_n_vals) # Second combined file combined_ed_other = echopype.combine_echodata(eds[2:]) combined_ed_other.to_zarr(second_zarr, overwrite=True) combined_ed = echopype.open_converted(first_zarr) combined_ed_other = echopype.open_converted(second_zarr) # Set expected values for Provenance if test_param == "single": data_inputs = [combined_ed, eds[2]] expected_n_vals = 3 elif test_param == "multi": data_inputs = [combined_ed, eds[2], eds[3]] expected_n_vals = 4 else: data_inputs = [combined_ed, combined_ed_other] expected_n_vals = 4 combined_ed2 = echopype.combine_echodata(data_inputs) # Verify that combined objects are all EchoData objects assert isinstance(combined_ed, EchoData) assert isinstance(combined_ed_other, EchoData) assert isinstance(combined_ed2, EchoData) # Ensure that they're from the same file source group_path = "Provenance" for i in range(4): ds_i = eds[i][group_path] select_comb_ds = combined_ed[group_path] if i < 2 else combined_ed2[group_path] if i < 3 or (i == 3 and test_param != "single"): assert ds_i.source_filenames[0].values == select_comb_ds.source_filenames[i].values # Check beam_group1. Should be exactly same xr dataset group_path = "Sonar/Beam_group1" for i in range(4): ds_i = eds[i][group_path] select_comb_ds = combined_ed[group_path] if i < 2 else combined_ed2[group_path] if i < 3 or (i == 3 and test_param != "single"): filt_ds_i = select_comb_ds.sel(ping_time=ds_i.ping_time) assert filt_ds_i.identical(ds_i) is True filt_combined = combined_ed2[group_path].sel(ping_time=combined_ed[group_path].ping_time) assert filt_combined.identical(combined_ed[group_path]) is True # Checks for Provenance group # Both dims of filenames and echodata filename should be expected_n_vals _check_prov_ds_and_dims(combined_ed2, expected_n_vals) def test_combine_echodata_channel_selection(): """ This test ensures that the ``channel_selection`` input of ``combine_echodata`` is producing the correct output for all sonar models except AD2CP. """ # TODO: Once a mock EchoData structure can be easily formed, # we should implement this test. pytest.skip("This test will not be implemented until after a mock EchoData object can be created.") def test_attr_storage(ek60_test_data): # check storage of attributes before combination in provenance group eds = [echopype.open_raw(file, "EK60") for file in ek60_test_data] combined = echopype.combine_echodata(eds) for group, value in combined.group_map.items(): if value['ep_group'] is None: group_path = 'Top-level' else: group_path = value['ep_group'] if f"{group}_attrs" in combined["Provenance"]: group_attrs = combined["Provenance"][f"{group}_attrs"] for i, ed in enumerate(eds): for attr, value in ed[group_path].attrs.items(): assert str( group_attrs.isel(echodata_filename=i) .sel({f"{group}_attr_key": attr}) .values[()] ) == str(value) # check selection by echodata_filename for file in ek60_test_data: assert Path(file).name in combined["Provenance"]["echodata_filename"] for group in combined.group_map: if f"{group}_attrs" in combined["Provenance"]: group_attrs = combined["Provenance"][f"{group}_attrs"] assert np.array_equal( group_attrs.sel( echodata_filename=Path(ek60_test_data[0]).name ), group_attrs.isel(echodata_filename=0), ) def test_combined_encodings(ek60_test_data): eds = [echopype.open_raw(file, "EK60") for file in ek60_test_data] combined = echopype.combine_echodata(eds) encodings_to_drop = {'chunks', 'preferred_chunks', 'compressor', 'filters'} group_checks = [] for _, value in combined.group_map.items(): if value['ep_group'] is None: ds = combined['Top-level'] else: ds = combined[value['ep_group']] if ds is not None: for k, v in ds.variables.items(): if k in DEFAULT_ENCODINGS: encoding = ds[k].encoding # remove any encoding relating to lazy loading lazy_encodings = set(encoding.keys()).intersection(encodings_to_drop) for encod_name in lazy_encodings: del encoding[encod_name] if encoding != DEFAULT_ENCODINGS[k]: group_checks.append( f" {value['name']}::{k}" ) if len(group_checks) > 0: all_messages = ['Encoding mismatch found!'] + group_checks message_text = '\n'.join(all_messages) raise AssertionError(message_text) def test_combined_echodata_repr(ek60_test_data): eds = [echopype.open_raw(file, "EK60") for file in ek60_test_data] combined = echopype.combine_echodata(eds) expected_repr = dedent( f"""\ <EchoData: standardized raw data from Internal Memory> Top-level: contains metadata about the SONAR-netCDF4 file format. ├── Environment: contains information relevant to acoustic propagation through water. ├── Platform: contains information about the platform on which the sonar is installed. │ └── NMEA: contains information specific to the NMEA protocol. ├── Provenance: contains metadata about how the SONAR-netCDF4 version of the data were obtained. ├── Sonar: contains sonar system metadata and sonar beam groups. │ └── Beam_group1: contains backscatter power (uncalibrated) and other beam or channel-specific data, including split-beam angle data when they exist. └── Vendor_specific: contains vendor-specific information about the sonar and the data.""" ) assert isinstance(repr(combined), str) is True actual = "\n".join(x.rstrip() for x in repr(combined).split("\n")) assert actual == expected_repr @pytest.mark.parametrize( ("all_chan_list", "channel_selection"), [ ( [['a', 'b', 'c'], ['a', 'b', 'c']], None ), pytest.param( [['a', 'b', 'c'], ['a', 'b']], None, marks=pytest.mark.xfail(strict=True, reason="This test should not pass because the channels are not consistent") ), ( [['a', 'b', 'c'], ['a', 'b', 'c']], ['a', 'b', 'c'] ), ( [['a', 'b', 'c'], ['a', 'b', 'c']], ['a', 'b'] ), ( [['a', 'b', 'c'], ['a', 'b']], ['a', 'b'] ), pytest.param( [['a', 'c'], ['a', 'b', 'c']], ['a', 'b'], marks=pytest.mark.xfail(strict=True, reason="This test should not pass because we are selecting " "channels that do not occur in each Dataset") ), ], ids=["chan_sel_none_pass", "chan_sel_none_fail", "chan_sel_same_as_given_chans", "chan_sel_subset_of_given_chans", "chan_sel_subset_of_given_chans_uneven", "chan_sel_diff_from_some_given_chans"] ) def test_check_channel_consistency(all_chan_list, channel_selection): """ Ensures that the channel consistency check for combine works as expected using mock data. """ _check_channel_consistency(all_chan_list, "test_group", channel_selection) # create duplicated dictionaries used within pytest parameterize has_chan_dim_1_beam = {'Top-level': False, 'Environment': False, 'Platform': True, 'Platform/NMEA': False, 'Provenance': False, 'Sonar': True, 'Sonar/Beam_group1': True, 'Vendor_specific': True} has_chan_dim_2_beam = {'Top-level': False, 'Environment': False, 'Platform': True, 'Platform/NMEA': False, 'Provenance': False, 'Sonar': True, 'Sonar/Beam_group1': True, 'Sonar/Beam_group2': True, 'Vendor_specific': True} expected_1_beam_none = {'Top-level': None, 'Environment': None, 'Platform': None, 'Platform/NMEA': None, 'Provenance': None, 'Sonar': None, 'Sonar/Beam_group1': None, 'Vendor_specific': None} expected_1_beam_a_b_sel = {'Top-level': None, 'Environment': None, 'Platform': ['a', 'b'], 'Platform/NMEA': None, 'Provenance': None, 'Sonar': ['a', 'b'], 'Sonar/Beam_group1': ['a', 'b'], 'Vendor_specific': ['a', 'b']} @pytest.mark.parametrize( ("sonar_model", "has_chan_dim", "user_channel_selection", "expected_dict"), [ ( ["EK60", "ES70", "AZFP"], has_chan_dim_1_beam, [None], expected_1_beam_none ), ( ["EK80", "ES80", "EA640"], has_chan_dim_1_beam, [None], expected_1_beam_none ), ( ["EK80", "ES80", "EA640"], has_chan_dim_2_beam, [None], {'Top-level': None, 'Environment': None, 'Platform': None, 'Platform/NMEA': None, 'Provenance': None, 'Sonar': None, 'Sonar/Beam_group1': None, 'Sonar/Beam_group2': None, 'Vendor_specific': None} ), ( ["EK60", "ES70", "AZFP"], has_chan_dim_1_beam, [['a', 'b'], {'Sonar/Beam_group1': ['a', 'b']}], expected_1_beam_a_b_sel ), ( ["EK80", "ES80", "EA640"], has_chan_dim_1_beam, [['a', 'b'], {'Sonar/Beam_group1': ['a', 'b']}], expected_1_beam_a_b_sel ), ( ["EK80", "ES80", "EA640"], has_chan_dim_2_beam, [['a', 'b']], {'Top-level': None, 'Environment': None, 'Platform': ['a', 'b'], 'Platform/NMEA': None, 'Provenance': None, 'Sonar': ['a', 'b'], 'Sonar/Beam_group1': ['a', 'b'], 'Sonar/Beam_group2': ['a', 'b'], 'Vendor_specific': ['a', 'b']} ), ( ["EK80", "ES80", "EA640"], has_chan_dim_2_beam, [{'Sonar/Beam_group1': ['a', 'b'], 'Sonar/Beam_group2': ['c', 'd']}], {'Top-level': None, 'Environment': None, 'Platform': ['a', 'b', 'c', 'd'], 'Platform/NMEA': None, 'Provenance': None, 'Sonar': ['a', 'b', 'c', 'd'], 'Sonar/Beam_group1': ['a', 'b'], 'Sonar/Beam_group2': ['c', 'd'], 'Vendor_specific': ['a', 'b', 'c', 'd']} ), ( ["EK80", "ES80", "EA640"], has_chan_dim_2_beam, [{'Sonar/Beam_group1': ['a', 'b'], 'Sonar/Beam_group2': ['b', 'c', 'd']}], {'Top-level': None, 'Environment': None, 'Platform': ['a', 'b', 'c', 'd'], 'Platform/NMEA': None, 'Provenance': None, 'Sonar': ['a', 'b', 'c', 'd'], 'Sonar/Beam_group1': ['a', 'b'], 'Sonar/Beam_group2': ['b', 'c', 'd'], 'Vendor_specific': ['a', 'b', 'c', 'd']} ), ], ids=["EK60_no_sel", "EK80_no_sel_1_beam", "EK80_no_sel_2_beam", "EK60_chan_sel", "EK80_chan_sel_1_beam", "EK80_list_chan_sel_2_beam", "EK80_dict_chan_sel_2_beam_diff_beam_group_chans", "EK80_dict_chan_sel_2_beam_overlap_beam_group_chans"] ) def test_create_channel_selection_dict(sonar_model, has_chan_dim, user_channel_selection, expected_dict): """ Ensures that ``create_channel_selction_dict`` is constructing the correct output for the sonar models ``EK60, EK80, AZFP`` and varying inputs for the input ``user_channel_selection``. Notes ----- The input ``has_chan_dim`` is unchanged except for the case where we are considering an EK80 sonar model with two beam groups. """ for model in sonar_model: for usr_sel_chan in user_channel_selection: channel_selection_dict = _create_channel_selection_dict(model, has_chan_dim, usr_sel_chan) assert channel_selection_dict == expected_dict @pytest.mark.parametrize( ["attributes", "expected"], [ ([{"key1": ""}, {"key1": "test2"}, {"key1": "test1"}], {"key1": "test2"}), ( [{"key1": "test1"}, {"key1": ""}, {"key1": "test2"}, {"key2": ""}], {"key1": "test1", "key2": ""}, ), ( [ {"key1": ""}, {"key2": "test1", "key1": "test2"}, {"key2": "test3"}, ], {"key2": "test1", "key1": "test2"}, ), ], ) def test__merge_attributes(attributes, expected): merged = _merge_attributes(attributes) assert merged == expected
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,806
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/utils/test_utils_log.py
import pytest import os.path import platform EXPECTED_MESSAGE = "Testing log function" def logging_func(logger): logger.info("Testing log function") @pytest.fixture(params=[False, True]) def verbose(request): return request.param def test_init_logger(): import logging from echopype.utils import log logger = log._init_logger('echopype.testing0') handlers = [h.name for h in logger.handlers] assert isinstance(logger, logging.Logger) is True assert logger.name == 'echopype.testing0' assert len(logger.handlers) == 2 assert log.STDERR_NAME in handlers assert log.STDOUT_NAME in handlers def test_set_log_file(): from echopype.utils import log logger = log._init_logger('echopype.testing1') from tempfile import TemporaryDirectory tmpdir = TemporaryDirectory() tmpfile = os.path.join(tmpdir.name, "testfile.log") log._set_logfile(logger, tmpfile) handlers = [h.name for h in logger.handlers] assert log.LOGFILE_HANDLE_NAME in handlers # when done with temporary directory # see: https://www.scivision.dev/python-tempfile-permission-error-windows/ try: tmpdir.cleanup() except Exception as e: if platform.system() == "Windows": pass else: raise e def test_set_verbose(verbose, capsys): from echopype.utils import log logger = log._init_logger(f'echopype.testing_{str(verbose).lower()}') # To pass through in caplog need to propagate # logger.propagate = True log._set_verbose(verbose) logging_func(logger) captured = capsys.readouterr() if verbose: assert EXPECTED_MESSAGE in captured.out else: assert "" in captured.out def test_get_all_loggers(): import logging from echopype.utils import log all_loggers = log._get_all_loggers() loggers = [logging.getLogger()] # get the root logger loggers = loggers + [logging.getLogger(name) for name in logging.root.manager.loggerDict] assert all_loggers == loggers def run_verbose_test(logger, override, logfile, capsys): import echopype as ep import os ep.verbose(logfile=logfile, override=override) logging_func(logger) captured = capsys.readouterr() if override is True: assert captured.out == "" else: assert EXPECTED_MESSAGE in captured.out if logfile is not None: assert os.path.exists(logfile) with open(logfile) as f: assert EXPECTED_MESSAGE in f.read() @pytest.mark.parametrize(["id", "override", "logfile"], [ ("fn", True, None), ("tn", False, None), ("tf", False, 'test.log') ]) def test_verbose(id, override, logfile, capsys): from echopype.utils import log logger = log._init_logger(f'echopype.testing_{id}') if logfile is not None: from tempfile import TemporaryDirectory tmpdir = TemporaryDirectory() tmpfile = os.path.join(tmpdir.name, logfile) run_verbose_test(logger, override, tmpfile, capsys) # when done with temporary directory # see: https://www.scivision.dev/python-tempfile-permission-error-windows/ try: tmpdir.cleanup() except Exception as e: if platform.system() == "Windows": pass else: raise e else: run_verbose_test(logger, override, logfile, capsys)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,807
OSOceanAcoustics/echopype
refs/heads/main
/echopype/mask/__init__.py
from .api import apply_mask, frequency_differencing __all__ = ["frequency_differencing", "apply_mask"]
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,808
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/convert/test_convert_ad2cp.py
"""test_convert_ad2cp.py This module test conversion of two sets of .ad2cp files. Files under "normal" contain default data variables, whereas files under "raw" additionally contain the IQ samples. """ import xarray as xr import numpy as np import netCDF4 import pytest from tempfile import TemporaryDirectory from pathlib import Path from echopype import open_raw, open_converted from echopype.testing import TEST_DATA_FOLDER @pytest.fixture def ocean_contour_export_dir(test_path): return test_path["AD2CP"] / "ocean-contour" @pytest.fixture def ocean_contour_export_076_dir(ocean_contour_export_dir): return ocean_contour_export_dir / "076" @pytest.fixture def ocean_contour_export_090_dir(ocean_contour_export_dir): return ocean_contour_export_dir / "090" @pytest.fixture def output_dir(): return "/echopype_test-export" def pytest_generate_tests(metafunc): ad2cp_path = TEST_DATA_FOLDER / "ad2cp" test_file_dir = ( ad2cp_path / "normal" ) # "normal" files do not have IQ samples raw_test_file_dir = ad2cp_path / "raw" # "raw" files contain IQ samples ad2cp_files = test_file_dir.glob("**/*.ad2cp") raw_ad2cp_files = raw_test_file_dir.glob("**/*.ad2cp") if "filepath" in metafunc.fixturenames: metafunc.parametrize( argnames="filepath", argvalues=ad2cp_files, ids=lambda f: str(f.name), ) if "filepath_raw" in metafunc.fixturenames: metafunc.parametrize( argnames="filepath_raw", argvalues=raw_ad2cp_files, ids=lambda f: str(f.name), ) @pytest.fixture def filepath(request): return request.param @pytest.fixture def filepath_raw(request): return request.param @pytest.fixture def absolute_tolerance(): return 1e-6 def test_convert(filepath, output_dir): with TemporaryDirectory() as tmpdir: output_dir = Path(tmpdir + output_dir) print("converting", filepath) echodata = open_raw(raw_file=str(filepath), sonar_model="AD2CP") echodata.to_netcdf(save_path=output_dir) def test_convert_raw( filepath_raw, output_dir, ocean_contour_export_090_dir, ocean_contour_export_076_dir, absolute_tolerance, ): with TemporaryDirectory() as tmpdir: output_dir = Path(tmpdir + output_dir) print("converting raw", filepath_raw) echodata = open_raw(raw_file=str(filepath_raw), sonar_model="AD2CP") echodata.to_netcdf(save_path=output_dir) _check_raw_output( filepath_raw, output_dir, ocean_contour_export_090_dir, ocean_contour_export_076_dir, absolute_tolerance, ) def _check_raw_output( filepath_raw, output_dir, ocean_contour_export_090_dir, ocean_contour_export_076_dir, absolute_tolerance, ): print("checking raw", filepath_raw) echodata = open_converted( converted_raw_path=output_dir.joinpath( filepath_raw.with_suffix(".nc").name ) ) if "090" in filepath_raw.parts: ocean_contour_converted_config_path = ( ocean_contour_export_090_dir.joinpath( filepath_raw.with_suffix( filepath_raw.suffix + ".00000.nc" ).name ) ) ocean_contour_converted_transmit_data_path = ( ocean_contour_converted_config_path ) ocean_contour_converted_data_path = ocean_contour_converted_config_path else: ocean_contour_converted_config_path = ( ocean_contour_export_076_dir / filepath_raw.with_suffix("").name / "Raw Echo 1_1000 kHz_001.nc" ) ocean_contour_converted_transmit_data_path = ( ocean_contour_export_076_dir / filepath_raw.with_suffix("").name / "Raw Echo 1_1000 kHz Tx_001.nc" ) ocean_contour_converted_data_path = ( ocean_contour_export_076_dir / filepath_raw.with_suffix("").name / "Raw Echo 1_1000 kHz_001.nc" ) if not all( ( ocean_contour_converted_config_path.exists(), ocean_contour_converted_transmit_data_path.exists(), ocean_contour_converted_data_path.exists(), ) ): pass else: # check pulse compression base = xr.open_dataset( str(ocean_contour_converted_config_path), group="Config" ) pulse_compressed = 0 for i in range(1, 4): if "090" in filepath_raw.parts: if base.attrs[f"echo_pulseComp{i}"]: pulse_compressed = i break else: if base.attrs[f"Instrument_echo_pulseComp{i}"]: pulse_compressed = i break for i in range(1, len(echodata["Sonar"]["beam_group"]) + 1): if "pulse_compressed" in echodata[f"Sonar/Beam_group{i}"]: pulse_compressed_vector = np.zeros(3) pulse_compressed_vector[pulse_compressed - 1] = 1 assert (echodata[f"Sonar/Beam_group{i}"]["pulse_compressed"] == pulse_compressed_vector).all() base.close() # check raw data transmit samples try: netCDF4.Dataset(str(ocean_contour_converted_transmit_data_path))[ "Data/RawEcho1_1000kHzTx" ] except IndexError: # no transmit data in this dataset pass else: base = xr.open_dataset( str(ocean_contour_converted_transmit_data_path), group="Data/RawEcho1_1000kHzTx", ) if "090" in filepath_raw.parts: for i in range(1, len(echodata["Sonar"]["beam_group"]) + 1): if "transmit_pulse_r" in echodata[f"Sonar/Beam_group{i}"]: assert np.allclose( echodata[f"Sonar/Beam_group{i}"][ "transmit_pulse_r" ].data.flatten(), base["DataI"].data.flatten(), atol=absolute_tolerance, ) assert np.allclose( echodata[f"Sonar/Beam_group{i}"][ "transmit_pulse_i" ].data.flatten(), base["DataQ"].data.flatten(), atol=absolute_tolerance, ) else: for i in range(1, len(echodata["Sonar"]["beam_group"]) + 1): if "transmit_pulse_r" in echodata[f"Sonar/Beam_group{i}"]: # note the underscore assert np.allclose( echodata[f"Sonar/Beam_group{i}"][ "transmit_pulse_r" ].data.flatten(), base["Data_I"].data.flatten(), atol=absolute_tolerance, ) assert np.allclose( echodata[f"Sonar/Beam_group{i}"][ "transmit_pulse_i" ].data.flatten(), base["Data_Q"].data.flatten(), atol=absolute_tolerance, ) base.close() # check raw data samples base = xr.open_dataset( str(ocean_contour_converted_data_path), group="Data/RawEcho1_1000kHz", ) if "090" in filepath_raw.parts: for i in range(1, len(echodata["Sonar"]["beam_group"]) + 1): if "backscatter_r" in echodata[f"Sonar/Beam_group{i}"]: assert np.allclose( echodata[f"Sonar/Beam_group{i}"]["backscatter_r"].data.flatten(), base["DataI"].data.flatten(), atol=absolute_tolerance, ) assert np.allclose( echodata[f"Sonar/Beam_group{i}"]["backscatter_i"].data.flatten(), base["DataQ"].data.flatten(), atol=absolute_tolerance, ) else: for i in range(1, len(echodata["Sonar"]["beam_group"]) + 1): if "transmit_pulse_r" in echodata[f"Sonar/Beam_group{i}"]: # note the transpose assert np.allclose( echodata[f"Sonar/Beam_group{i}"]["backscatter_r"].data.flatten(), base["Data_I"].data.T.flatten(), atol=absolute_tolerance, ) assert np.allclose( echodata[f"Sonar/Beam_group{i}"]["backscatter_i"].data.flatten(), base["Data_Q"].data.T.flatten(), atol=absolute_tolerance, ) base.close()
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,809
OSOceanAcoustics/echopype
refs/heads/main
/echopype/convert/parsed_to_zarr_ek80.py
import numpy as np import pandas as pd import psutil from .parsed_to_zarr_ek60 import Parsed2ZarrEK60 class Parsed2ZarrEK80(Parsed2ZarrEK60): """ Facilitates the writing of parsed data to a zarr file for the EK80 sensor. """ def __init__(self, parser_obj): super().__init__(parser_obj) self.power_dims = ["timestamp", "channel_id"] self.angle_dims = ["timestamp", "channel_id"] self.complex_dims = ["timestamp", "channel_id"] self.p2z_ch_ids = {} # channel ids for power, angle, complex self.pow_ang_df = None # df that holds power and angle data self.complex_df = None # df that holds complex data # get channel and channel_id association and sort by channel_id channels_old = list(self.parser_obj.config_datagram["configuration"].keys()) # sort the channels in ascending order channels_new = channels_old[:] channels_new.sort(reverse=False) # obtain sort rule for the channel index self.channel_sort_rule = {ch: channels_new.index(ch) for ch in channels_old} def _get_num_transd_sec(self, x: pd.DataFrame): """ Returns the number of transducer sectors. Parameters ---------- x : pd.DataFrame DataFrame representing the complex series """ num_transducer_sectors = np.unique( np.array(self.parser_obj.ping_data_dict["n_complex"][x.name[1]]) ) if num_transducer_sectors.size > 1: # this is not supposed to happen raise ValueError("Transducer sector number changes in the middle of the file!") else: num_transducer_sectors = num_transducer_sectors[0] return num_transducer_sectors def _reshape_series(self, complex_series: pd.Series) -> pd.Series: """ Reshapes complex series into the correct form, taking into account the beam dimension. The new shape of each element of ``complex_series`` will be (element length, num_transducer_sectors). Parameters ---------- complex_series: pd.Series Series representing the complex data """ # get dimension 2, which represents the number of transducer elements dim_2 = pd.DataFrame(complex_series).apply(self._get_num_transd_sec, axis=1) dim_2.name = "dim_2" range_sample_len = complex_series.apply( lambda x: x.shape[0] if isinstance(x, np.ndarray) else 0 ) # get dimension 1, which represents the new range_sample length dim_1 = (range_sample_len / dim_2).astype("int") dim_1.name = "dim_1" comp_shape_df = pd.concat([complex_series, dim_1, dim_2], axis=1) return comp_shape_df.apply( lambda x: x.values[0].reshape((x.dim_1, x.dim_2)) if isinstance(x.values[0], np.ndarray) else None, axis=1, ) @staticmethod def _split_complex_data(complex_series: pd.Series) -> pd.DataFrame: """ Splits the 1D complex data into two 1D arrays representing the real and imaginary parts of the complex data, for each element in ``complex_series``. Parameters ---------- complex_series : pd.Series Series representing the complex data Returns ------- DataFrame with columns backscatter_r and backscatter_i obtained from splitting the complex data into real and imaginary parts, respectively. The DataFrame will have the same index as ``complex_series``. """ complex_split = complex_series.apply( lambda x: [np.real(x), np.imag(x)] if isinstance(x, np.ndarray) else [None, None] ) return pd.DataFrame( data=complex_split.to_list(), columns=["backscatter_r", "backscatter_i"], index=complex_series.index, ) def _write_complex(self, df: pd.DataFrame, max_mb: int): """ Writes the complex data and associated indices to a zarr group. Parameters ---------- df : pd.DataFrame DataFrame that contains angle data max_mb : int Maximum MB allowed for each chunk """ # obtain complex data and drop NaNs complex_series = df.set_index(self.complex_dims)["complex"].copy() # get unique indices times = complex_series.index.get_level_values(0).unique() channels = complex_series.index.get_level_values(1).unique() # sort the channels based on rule _, indexer = channels.map(self.channel_sort_rule).sort_values( ascending=True, return_indexer=True ) channels = channels[indexer] complex_series = self._reshape_series(complex_series) complex_df = self._split_complex_data(complex_series) self.p2z_ch_ids["complex"] = channels.values # store channel ids for variable # create multi index using the product of the unique dims unique_dims = [times, channels] complex_df = self.set_multi_index(complex_df, unique_dims) # write complex data to the complex group zarr_grp = self.zarr_root.create_group("complex") for column in complex_df: self.write_df_column( pd_series=complex_df[column], zarr_grp=zarr_grp, is_array=True, unique_time_ind=times, max_mb=max_mb, ) # write the unique indices to the complex group zarr_grp.array( name=self.complex_dims[0], data=times.values, dtype=times.dtype.str, fill_value="NaT" ) dtype = self._get_string_dtype(channels) zarr_grp.array( name=self.complex_dims[1], data=channels.values, dtype=dtype, fill_value=None ) def _get_complex_size(self, df: pd.DataFrame) -> int: """ Returns the total memory in bytes required to store the expanded complex data. Parameters ---------- df: pd.DataFrame DataFrame containing the complex and the appropriate dimension data """ # get unique indices times = df[self.complex_dims[0]].unique() channels = df[self.complex_dims[1]].unique() # get final form of index multi_index = pd.MultiIndex.from_product([times, channels]) # get the total memory required for expanded zarr variables complex_mem = self.array_series_bytes(df["complex"], multi_index.shape[0]) # multiply by 2 because we store both the complex and real parts return 2 * complex_mem def _get_zarr_dfs(self): """ Creates the DataFrames that hold the power, angle, and complex data, which are needed for downstream computation. """ datagram_df = pd.DataFrame.from_dict(self.parser_obj.zarr_datagrams) # get df corresponding to power and angle only self.pow_ang_df = datagram_df[["power", "angle", "timestamp", "channel_id"]].copy() # remove power and angle to conserve memory del datagram_df["power"] del datagram_df["angle"] # drop rows with missing power and angle data self.pow_ang_df.dropna(how="all", subset=["power", "angle"], inplace=True) self.complex_df = datagram_df.dropna().copy() def whether_write_to_zarr(self, mem_mult: float = 0.3) -> bool: """ Determines if the zarr data provided will expand into a form that is larger than a percentage of the total physical RAM. Parameters ---------- mem_mult : float Multiplier for total physical RAM Notes ----- If ``mem_mult`` times the total RAM is less than the total memory required to store the expanded zarr variables, this function will return True, otherwise False. """ isinstance(self.datagram_df, pd.DataFrame) # create zarr dfs, if they do not exist if not isinstance(self.pow_ang_df, pd.DataFrame) and not isinstance( self.complex_df, pd.DataFrame ): self._get_zarr_dfs() # get memory required for zarr data pow_ang_total_mem = self._get_power_angle_size(self.pow_ang_df) comp_total_mem = self._get_complex_size(self.complex_df) total_mem = pow_ang_total_mem + comp_total_mem # get statistics about system memory usage mem = psutil.virtual_memory() zarr_dgram_size = self._get_zarr_dgrams_size() # approx. the amount of memory that will be used after expansion req_mem = mem.used - zarr_dgram_size + total_mem # free memory, if we no longer need it if mem.total * mem_mult > req_mem: del self.pow_ang_df del self.complex_df else: del self.parser_obj.zarr_datagrams return mem.total * mem_mult < req_mem def datagram_to_zarr(self, max_mb: int) -> None: """ Facilitates the conversion of a list of datagrams to a form that can be written to a zarr store. Parameters ---------- max_mb : int Maximum MB allowed for each chunk Notes ----- This function specifically writes chunks along the time index. The chunking routine evenly distributes the times such that each chunk differs by at most one time. This makes it so that the memory required for each chunk is approximately the same. """ self._create_zarr_info() # create zarr dfs, if they do not exist if not isinstance(self.pow_ang_df, pd.DataFrame) and not isinstance( self.complex_df, pd.DataFrame ): self._get_zarr_dfs() del self.parser_obj.zarr_datagrams # free memory if not self.pow_ang_df.empty: self._write_power(df=self.pow_ang_df, max_mb=max_mb) self._write_angle(df=self.pow_ang_df, max_mb=max_mb) del self.pow_ang_df # free memory if not self.complex_df.empty: self._write_complex(df=self.complex_df, max_mb=max_mb) del self.complex_df # free memory self._close_store()
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,810
OSOceanAcoustics/echopype
refs/heads/main
/setup.py
from __future__ import absolute_import, division, print_function from setuptools import setup # Dynamically read dependencies from requirements file with open("requirements.txt") as f: requirements = f.readlines() if __name__ == "__main__": setup(install_requires=requirements)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,811
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/visualize/test_plot.py
import echopype import echopype.visualize from echopype.testing import TEST_DATA_FOLDER from echopype.calibrate.calibrate_ek import CalibrateEK60 import pytest from xarray.plot.facetgrid import FacetGrid from matplotlib.collections import QuadMesh import xarray as xr import numpy as np ek60_path = TEST_DATA_FOLDER / "ek60" ek80_path = TEST_DATA_FOLDER / "ek80_new" azfp_path = TEST_DATA_FOLDER / "azfp" ad2cp_path = TEST_DATA_FOLDER / "ad2cp" param_args = ("filepath", "sonar_model", "azfp_xml_path", "range_kwargs") param_testdata = [ ( ek60_path / "ncei-wcsd" / "Summer2017-D20170719-T211347.raw", "EK60", None, {}, ), ( ek60_path / "DY1002_EK60-D20100318-T023008_rep_freq.raw", "EK60", None, {}, ), ( ek80_path / "echopype-test-D20211004-T235930.raw", "EK80", None, {'waveform_mode': 'BB', 'encode_mode': 'complex'}, ), ( ek80_path / "D20211004-T233354.raw", "EK80", None, {'waveform_mode': 'CW', 'encode_mode': 'power'}, ), ( ek80_path / "D20211004-T233115.raw", "EK80", None, {'waveform_mode': 'CW', 'encode_mode': 'complex'}, ), ( azfp_path / "17082117.01A", "AZFP", azfp_path / "17041823.XML", {}, ), # Will always need env variables pytest.param( ad2cp_path / "raw" / "090" / "rawtest.090.00001.ad2cp", "AD2CP", None, {}, marks=pytest.mark.xfail( run=False, reason="Not supported at the moment", ), ), ] @pytest.mark.parametrize(param_args, param_testdata) def test_plot_multi( filepath, sonar_model, azfp_xml_path, range_kwargs, ): # TODO: Need to figure out how to compare the actual rendered plots ed = echopype.open_raw(filepath, sonar_model, azfp_xml_path) plots = echopype.visualize.create_echogram(ed) assert isinstance(plots, list) is True assert all(isinstance(plot, FacetGrid) for plot in plots) is True @pytest.mark.parametrize(param_args, param_testdata) def test_plot_single( filepath, sonar_model, azfp_xml_path, range_kwargs, ): # TODO: Need to figure out how to compare the actual rendered plots ed = echopype.open_raw(filepath, sonar_model, azfp_xml_path) plots = echopype.visualize.create_echogram( ed, channel=ed["Sonar/Beam_group1"].channel[0].values ) assert isinstance(plots, list) is True if ( sonar_model.lower() == 'ek80' and range_kwargs['encode_mode'] == 'complex' ): assert all(isinstance(plot, FacetGrid) for plot in plots) is True else: assert all(isinstance(plot, QuadMesh) for plot in plots) is True @pytest.mark.parametrize(param_args, param_testdata) def test_plot_multi_get_range( filepath, sonar_model, azfp_xml_path, range_kwargs, ): # TODO: Need to figure out how to compare the actual rendered plots ed = echopype.open_raw(filepath, sonar_model, azfp_xml_path) if ed.sonar_model.lower() == 'azfp': avg_temperature = ed["Environment"]['temperature'].values.mean() env_params = { 'temperature': avg_temperature, 'salinity': 27.9, 'pressure': 59, } range_kwargs['env_params'] = env_params plots = echopype.visualize.create_echogram( ed, get_range=True, range_kwargs=range_kwargs ) assert isinstance(plots, list) is True assert all(isinstance(plot, FacetGrid) for plot in plots) is True # Beam shape check if ( sonar_model.lower() == 'ek80' and range_kwargs['encode_mode'] == 'complex' ): assert plots[0].axes.shape[-1] > 1 else: assert plots[0].axes.shape[-1] == 1 # Channel shape check assert ed["Sonar/Beam_group1"].channel.shape[0] == len(plots) @pytest.mark.parametrize(param_args, param_testdata) def test_plot_Sv( filepath, sonar_model, azfp_xml_path, range_kwargs, ): # TODO: Need to figure out how to compare the actual rendered plots ed = echopype.open_raw(filepath, sonar_model, azfp_xml_path) if ed.sonar_model.lower() == 'azfp': avg_temperature = ed["Environment"]['temperature'].values.mean() env_params = { 'temperature': avg_temperature, 'salinity': 27.9, 'pressure': 59, } range_kwargs['env_params'] = env_params if 'azfp_cal_type' in range_kwargs: range_kwargs.pop('azfp_cal_type') Sv = echopype.calibrate.compute_Sv(ed, **range_kwargs) plots = echopype.visualize.create_echogram(Sv) assert isinstance(plots, list) is True assert all(isinstance(plot, FacetGrid) for plot in plots) is True @pytest.mark.parametrize(param_args, param_testdata) def test_plot_mvbs( filepath, sonar_model, azfp_xml_path, range_kwargs, ): # TODO: Need to figure out how to compare the actual rendered plots ed = echopype.open_raw(filepath, sonar_model, azfp_xml_path) if ed.sonar_model.lower() == 'azfp': avg_temperature = ed["Environment"]['temperature'].values.mean() env_params = { 'temperature': avg_temperature, 'salinity': 27.9, 'pressure': 59, } range_kwargs['env_params'] = env_params if 'azfp_cal_type' in range_kwargs: range_kwargs.pop('azfp_cal_type') Sv = echopype.calibrate.compute_Sv(ed, **range_kwargs) mvbs = echopype.commongrid.compute_MVBS(Sv, ping_time_bin='10S') plots = [] try: plots = echopype.visualize.create_echogram(mvbs) except Exception as e: assert isinstance(e, ValueError) assert str(e) == "Ping time must have a length that is greater or equal to 2" # noqa if len(plots) > 0: assert all(isinstance(plot, FacetGrid) for plot in plots) is True @pytest.mark.parametrize( ("vertical_offset", "expect_warning"), [ (True, False), ([True], True), (False, True), (xr.DataArray(np.array(50.0)), False), ([10, 30.5], False), (10, False), (30.5, False), ], ) def test_vertical_offset_echodata(vertical_offset, expect_warning, caplog): from echopype.echodata import EchoData from echopype.visualize.api import _add_vertical_offset echopype.verbose() filepath = ek60_path / "ncei-wcsd" / "Summer2017-D20170719-T211347.raw" sonar_model = "EK60" range_kwargs = {} echodata = echopype.open_raw( sonar_model=sonar_model, raw_file=filepath, xml_path=None ) cal_obj = CalibrateEK60( echodata=echodata, env_params=range_kwargs.get("env_params", {}), cal_params=None, ecs_file=None, ) range_in_meter = cal_obj.range_meter single_array = range_in_meter.sel(channel='GPT 18 kHz 009072058c8d 1-1 ES18-11').isel(ping_time=0).values no_input_vertical_offset = False if isinstance(vertical_offset, list): vertical_offset = vertical_offset[0] echodata["Platform"] = echodata["Platform"].drop_vars('vertical_offset') no_input_vertical_offset = True if isinstance(vertical_offset, xr.DataArray): original_array = single_array + vertical_offset.values elif isinstance(vertical_offset, bool) and vertical_offset is True: if not no_input_vertical_offset: original_array = ( single_array + echodata["Platform"].vertical_offset.isel(time2=0).values ) else: original_array = single_array elif vertical_offset is not False and isinstance(vertical_offset, (int, float)): original_array = single_array + vertical_offset else: original_array = single_array results = None try: results = _add_vertical_offset( range_in_meter=range_in_meter, vertical_offset=vertical_offset, data_type=EchoData, platform_data=echodata["Platform"], ) if expect_warning: assert 'WARNING' in caplog.text except Exception as e: assert isinstance(e, ValueError) assert str(e) == 'vertical_offset must have any of these dimensions: ping_time, range_sample' # noqa if isinstance(results, xr.DataArray): final_array = results.sel(channel='GPT 18 kHz 009072058c8d 1-1 ES18-11').isel(ping_time=0).values print(f"original_array = {original_array}") print(f"results = {results}") assert np.array_equal(original_array, final_array) @pytest.mark.parametrize( ("vertical_offset", "expect_warning"), [ (True, True), (False, True), (xr.DataArray(np.array(50.0)), False), (10, False), (30.5, False), ], ) def test_vertical_offset_Sv_dataset(vertical_offset, expect_warning, caplog): from echopype.visualize.api import _add_vertical_offset echopype.verbose() filepath = ek60_path / "ncei-wcsd" / "Summer2017-D20170719-T211347.raw" sonar_model = "EK60" range_kwargs = {} echodata = echopype.open_raw( sonar_model=sonar_model, raw_file=filepath, xml_path=None ) Sv = echopype.calibrate.compute_Sv(echodata, **range_kwargs) ds = Sv.set_coords('echo_range') range_in_meter = ds.echo_range single_array = range_in_meter.sel(channel='GPT 18 kHz 009072058c8d 1-1 ES18-11').isel(ping_time=0).values if isinstance(vertical_offset, xr.DataArray): original_array = single_array + vertical_offset.values elif not isinstance(vertical_offset, bool) and isinstance(vertical_offset, (int, float)): original_array = single_array + vertical_offset else: original_array = single_array results = None try: results = _add_vertical_offset( range_in_meter=range_in_meter, vertical_offset=vertical_offset, data_type=xr.Dataset, ) if expect_warning: assert 'WARNING' in caplog.text except Exception as e: assert isinstance(e, ValueError) assert str(e) == 'vertical_offset must have any of these dimensions: ping_time, range_sample' # noqa if isinstance(results, xr.DataArray): final_array = results.sel(channel='GPT 18 kHz 009072058c8d 1-1 ES18-11').isel(ping_time=0).values assert np.array_equal(original_array, final_array)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,812
OSOceanAcoustics/echopype
refs/heads/main
/echopype/calibrate/env_params.py
import datetime from typing import Dict, List, Literal, Optional, Union import numpy as np import xarray as xr from ..echodata import EchoData from ..utils import uwa from .cal_params import param2da ENV_PARAMS = ( "sound_speed", "sound_absorption", "temperature", "salinity", "pressure", "pH", "formula_sound_speed", "formula_absorption", ) def harmonize_env_param_time( p: Union[int, float, xr.DataArray], ping_time: Optional[Union[xr.DataArray, datetime.datetime]] = None, ): """ Harmonize time coordinate between Beam_groupX data and env_params to make sure the timestamps are broadcast correctly in calibration and range calculations. Regardless of the source, if `p` is an xr.DataArray, the time coordinate name needs to be `time1` to be consistent with the time coordinate in EchoData["Environment"]. If `time1` is of length=1, the dimension `time1` is dropped. Otherwise, `p` is interpolated to `ping_time`. If `p` is not an xr.DataArray it is returned directly. Parameters ---------- p The environment parameter for timestamp check/correction ping_time Beam_groupX ping_time to interpolate env_params timestamps to. Only used if p.time1 has length >1 Returns ------- Environment parameter with correctly broadcasted timestamps """ if isinstance(p, xr.DataArray): if "time1" not in p.coords: return p else: # If there's only 1 time1 value, # or if after dropping NaN there's only 1 time1 value if p["time1"].size == 1 or p.dropna(dim="time1").size == 1: return p.dropna(dim="time1").squeeze(dim="time1").drop("time1") # Direct assignment if all timestamps are identical (EK60 data) elif np.all(p["time1"].values == ping_time.values): return p.rename({"time1": "ping_time"}) elif ping_time is None: raise ValueError(f"ping_time needs to be provided for interpolating {p.name}") else: return p.dropna(dim="time1").interp(time1=ping_time) else: return p def sanitize_user_env_dict( user_dict: Dict[str, Union[int, float, List, xr.DataArray]], channel: Union[List, xr.DataArray], ) -> Dict[str, Union[int, float, xr.DataArray]]: """ Creates a blueprint for ``env_params`` dictionary and check the format/organize user-provided parameters. This function is very similar to ``sanitize_user_cal_dict`` but much simpler, without the interpolation routines needed for calibration parameters. Parameters ---------- user_dict : dict A dictionary containing user input calibration parameters as {parameter name: parameter value}. Parameter value has to be a scalar (int or float), a list or an ``xr.DataArray``. If parameter value is an ``xr.DataArray``, it has to have a'channel' as a coordinate. channel : list or xr.DataArray A list of channels to be calibrated. For EK80 data, this list has to corresponds with the subset of channels selected based on waveform_mode and encode_mode Returns ------- dict A dictionary containing sanitized user-provided environmental parameters. Notes ----- The user-provided 'sound_absorption' parameter has to be a list or an xr.DataArray, because this parameter is frequency-dependen. """ # Make channel a sorted list if not isinstance(channel, (list, xr.DataArray)): raise ValueError("'channel' has to be a list or an xr.DataArray") if isinstance(channel, xr.DataArray): channel_sorted = sorted(channel.values) else: channel_sorted = sorted(channel) # Screen parameters: only retain those defined in ENV_PARAMS # -- transform params in list to xr.DataArray # -- directly pass through params that are scalar or str # -- check channel coordinate if params are xr.DataArray and pass it through out_dict = dict.fromkeys(ENV_PARAMS) for p_name, p_val in user_dict.items(): if p_name in out_dict: # Param "sound_absorption" has to be an xr.DataArray or a list because it is freq-dep if p_name == "sound_absorption" and not isinstance(p_val, (xr.DataArray, list)): raise ValueError( "The 'sound_absorption' parameter has to be a list or an xr.DataArray, " "with 'channel' as an coordinate." ) # If p_val an xr.DataArray, check existence and coordinates if isinstance(p_val, xr.DataArray): # if 'channel' is a coordinate, it has to match that of the data if "channel" in p_val.coords: if not (sorted(p_val.coords["channel"].values) == channel_sorted): raise ValueError( f"The 'channel' coordinate of {p_name} has to match " "that of the data to be calibrated" ) else: raise ValueError(f"{p_name} has to have 'channel' as a coordinate") out_dict[p_name] = p_val # If p_val a scalar or str, do nothing elif isinstance(p_val, (int, float, str)): out_dict[p_name] = p_val # If p_val a list, make it xr.DataArray elif isinstance(p_val, list): # check for list dimension happens within param2da() out_dict[p_name] = param2da(p_val, channel) # p_val has to be one of int, float, xr.DataArray else: raise ValueError(f"{p_name} has to be a scalar, list, or an xr.DataArray") return out_dict def get_env_params_AZFP(echodata: EchoData, user_dict: Optional[dict] = None): """Get env params using user inputs or values from data file. Parameters ---------- echodata : EchoData an echodata object containing the env params to be pulled from user_dict : dict user input dict containing env params Returns ------- dict A dictionary containing the environmental parameters. """ # AZFP only has 1 beam group beam = echodata["Sonar/Beam_group1"] # Use sanitized user dict as blueprint # out_dict contains only and all of the allowable cal params out_dict = sanitize_user_env_dict(user_dict=user_dict, channel=beam["channel"]) out_dict.pop("pH") # AZFP formulae do not use pH # For AZFP, salinity and pressure always come from user input if ("salinity" not in out_dict) or ("pressure" not in out_dict): raise ReferenceError("Please supply both salinity and pressure in env_params.") # Needs to fill in temperature first before sound speed and absorption can be calculated if out_dict["temperature"] is None: out_dict["temperature"] = echodata["Environment"]["temperature"] # Set sound speed and absorption formula source if not in user_dict if out_dict["formula_sound_speed"] is None: out_dict["formula_sound_speed"] = "AZFP" if out_dict["formula_absorption"] is None: out_dict["formula_absorption"] = "AZFP" # Only fill in params that are None for p, v in out_dict.items(): if v is None: if p == "sound_speed": out_dict[p] = uwa.calc_sound_speed( temperature=out_dict["temperature"], salinity=out_dict["salinity"], pressure=out_dict["pressure"], formula_source=out_dict["formula_sound_speed"], ) elif p == "sound_absorption": out_dict[p] = uwa.calc_absorption( frequency=beam["frequency_nominal"], temperature=out_dict["temperature"], salinity=out_dict["salinity"], pressure=out_dict["pressure"], formula_source=out_dict["formula_absorption"], ) # Harmonize time coordinate between Beam_groupX (ping_time) and env_params (time1) # Note for AZFP data is always in Sonar/Beam_group1 for p in out_dict.keys(): out_dict[p] = harmonize_env_param_time(out_dict[p], ping_time=beam["ping_time"]) return out_dict def get_env_params_EK( sonar_type: Literal["EK60", "EK80"], beam: xr.Dataset, env: xr.Dataset, user_dict: Optional[Dict] = None, freq: xr.DataArray = None, ) -> Dict: """ Get env params using user inputs or values from data file. Parameters ---------- sonar_type : str Type of sonar, one of "EK60" or "EK80" beam : xr.Dataset A subset of Sonar/Beam_groupX that contains only the channels specified for calibration env : xr.Dataset A subset of Environment group that contains only the channels specified for calibration user_dict : dict User input dict containing env params freq : xr.DataArray Center frequency for the selected channels. Required for EK80 calibration. If provided for EK60 calibration, it will be overwritten by the values in ``beam['frequency_nominal']`` Returns ------- A dictionary containing the environmental parameters. Notes ----- EK60 file by default contains only sound speed and absorption. In cases when temperature, salinity, and pressure values are supplied by the user simultaneously, the sound speed and absorption are re-calculated. EK80 file by default contains sound speed, temperature, depth, salinity, and acidity, therefore absorption is always calculated unless it is supplied by the user. In cases when temperature, salinity, and pressure values are supplied by the user simultaneously, both the sound speed and absorption are re-calculated. """ if sonar_type not in ["EK60", "EK80"]: raise ValueError("'sonar_type' has to be 'EK60' or 'EK80'") # EK80 calibration requires freq, which is the channel center frequency if sonar_type == "EK80": if freq is None: raise ValueError("'freq' is required for calibrating EK80-style data.") else: # EK60 freq = beam["frequency_nominal"] # overwriting input if exists # Use sanitized user dict as blueprint # out_dict contains only and all of the allowable cal params out_dict = sanitize_user_env_dict(user_dict=user_dict, channel=beam["channel"]) # Check absorption and sound speed formula if out_dict["formula_absorption"] not in [None, "AM", "FG"]: raise ValueError("'formula_absorption' has to be None, 'FG' or 'AM' for EK echosounders.") if out_dict["formula_sound_speed"] not in (None, "Mackenzie"): raise ValueError("'formula_absorption' has to be None or 'Mackenzie' for EK echosounders.") # Calculation sound speed and absorption requires at least T, S, P # tsp_all_exist controls wherher to calculate sound speed and absorption tspa_all_exist = np.all( [out_dict[p] is not None for p in ["temperature", "salinity", "pressure", "pH"]] ) # If EK80, get env parameters from data if not provided in user dict # All T, S, P, pH are needed because we always have to compute sound absorption for EK80 data if not tspa_all_exist and sonar_type == "EK80": for p_user, p_data in zip( ["temperature", "salinity", "pressure", "pH"], # name in defined env params ["temperature", "salinity", "depth", "acidity"], # name in EK80 data ): out_dict[p_user] = user_dict.get(p_user, env[p_data]) # Sound speed if out_dict["sound_speed"] is None: if not tspa_all_exist: # sounds speed always exist in EK60 and EK80 data out_dict["sound_speed"] = env["sound_speed_indicative"] out_dict.pop("formula_sound_speed") else: # default to Mackenzie sound speed formula if not in user dict if out_dict["formula_sound_speed"] is None: out_dict["formula_sound_speed"] = "Mackenzie" out_dict["sound_speed"] = uwa.calc_sound_speed( temperature=out_dict["temperature"], salinity=out_dict["salinity"], pressure=out_dict["pressure"], formula_source=out_dict["formula_sound_speed"], ) else: out_dict.pop("formula_sound_speed") # remove this since no calculation # Sound absorption if out_dict["sound_absorption"] is None: if not tspa_all_exist and sonar_type != "EK80": # this should not happen for EK80 # absorption always exist in EK60 data out_dict["sound_absorption"] = env["absorption_indicative"] out_dict.pop("formula_absorption") else: # default to FG absorption if not in user dict if out_dict["formula_absorption"] is None: out_dict["formula_absorption"] = "FG" out_dict["sound_absorption"] = uwa.calc_absorption( frequency=freq, temperature=out_dict["temperature"], salinity=out_dict["salinity"], pressure=out_dict["pressure"], pH=out_dict["pH"], sound_speed=out_dict["sound_speed"], formula_source=out_dict["formula_absorption"], ) else: out_dict.pop("formula_absorption") # remove this since no calculation # Remove params if calculation for both sound speed and absorption didn't happen if not ("formula_sound_speed" in out_dict or "formula_absorption" in out_dict): [out_dict.pop(p) for p in ["temperature", "salinity", "pressure", "pH"]] # Harmonize time coordinate between Beam_groupX (ping_time) and env_params (time1) # Note for EK60 data is always in Sonar/Beam_group1 for p in out_dict.keys(): out_dict[p] = harmonize_env_param_time(out_dict[p], ping_time=beam["ping_time"]) return out_dict
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,813
OSOceanAcoustics/echopype
refs/heads/main
/echopype/convert/utils/ek_raw_parsers.py
""" Code originally developed for pyEcholab (https://github.com/CI-CMG/pyEcholab) by Rick Towler <rick.towler@noaa.gov> at NOAA AFSC. The code has been modified to handle split-beam data and channel-transducer structure from different EK80 setups. """ import re import struct import sys import xml.etree.ElementTree as ET from collections import Counter import numpy as np from ...utils.log import _init_logger from .ek_date_conversion import nt_to_unix TCVR_CH_NUM_MATCHER = re.compile(r"\d{6}-\w{1,2}|\w{12}-\w{1,2}") __all__ = [ "SimradNMEAParser", "SimradDepthParser", "SimradBottomParser", "SimradAnnotationParser", "SimradConfigParser", "SimradRawParser", ] logger = _init_logger(__name__) class _SimradDatagramParser(object): """""" def __init__(self, header_type, header_formats): self._id = header_type self._headers = header_formats self._versions = list(header_formats.keys()) def header_fmt(self, version=0): return "=" + "".join([x[1] for x in self._headers[version]]) def header_size(self, version=0): return struct.calcsize(self.header_fmt(version)) def header_fields(self, version=0): return [x[0] for x in self._headers[version]] def header(self, version=0): return self._headers[version][:] def validate_data_header(self, data): if isinstance(data, dict): type_ = data["type"][:3] version = int(data["type"][3]) elif isinstance(data, str): type_ = data[:3] version = int(data[3]) else: raise TypeError("Expected a dict or str") if type_ != self._id: raise ValueError("Expected data of type %s, not %s" % (self._id, type_)) if version not in self._versions: raise ValueError("No parser available for type %s version %d" % (self._id, version)) return type_, version def from_string(self, raw_string, bytes_read): header = raw_string[:4] if sys.version_info.major > 2: header = header.decode() id_, version = self.validate_data_header(header) return self._unpack_contents(raw_string, bytes_read, version=version) def to_string(self, data={}): id_, version = self.validate_data_header(data) datagram_content_str = self._pack_contents(data, version=version) return self.finalize_datagram(datagram_content_str) def _unpack_contents(self, raw_string="", version=0): raise NotImplementedError def _pack_contents(self, data={}, version=0): raise NotImplementedError @classmethod def finalize_datagram(cls, datagram_content_str): datagram_size = len(datagram_content_str) final_fmt = "=l%dsl" % (datagram_size) return struct.pack(final_fmt, datagram_size, datagram_content_str, datagram_size) class SimradDepthParser(_SimradDatagramParser): """ ER60 Depth Detection datagram (from .bot files) contain the following keys: type: string == 'DEP0' low_date: long uint representing LSBytes of 64bit NT date high_date: long uint representing MSBytes of 64bit NT date timestamp: datetime.datetime object of NT date, assumed to be UTC transceiver_count: [long uint] with number of transceivers depth: [float], one value for each active channel reflectivity: [float], one value for each active channel unused: [float], unused value for each active channel The following methods are defined: from_string(str): parse a raw ER60 Depth datagram (with leading/trailing datagram size stripped) to_string(): Returns the datagram as a raw string (including leading/trailing size fields) ready for writing to disk """ def __init__(self): headers = { 0: [ ("type", "4s"), ("low_date", "L"), ("high_date", "L"), ("transceiver_count", "L"), ] } _SimradDatagramParser.__init__(self, "DEP", headers) def _unpack_contents(self, raw_string, bytes_read, version): """""" header_values = struct.unpack( self.header_fmt(version), raw_string[: self.header_size(version)] ) data = {} for indx, field in enumerate(self.header_fields(version)): data[field] = header_values[indx] if isinstance(data[field], bytes): data[field] = data[field].decode() data["timestamp"] = nt_to_unix((data["low_date"], data["high_date"])) data["bytes_read"] = bytes_read if version == 0: data_fmt = "=3f" data_size = struct.calcsize(data_fmt) data["depth"] = np.zeros((data["transceiver_count"],)) data["reflectivity"] = np.zeros((data["transceiver_count"],)) data["unused"] = np.zeros((data["transceiver_count"],)) buf_indx = self.header_size(version) for indx in range(data["transceiver_count"]): d, r, u = struct.unpack( data_fmt, raw_string[buf_indx : buf_indx + data_size] # noqa ) data["depth"][indx] = d data["reflectivity"][indx] = r data["unused"][indx] = u buf_indx += data_size return data def _pack_contents(self, data, version): datagram_fmt = self.header_fmt(version) datagram_contents = [] if version == 0: lengths = [ len(data["depth"]), len(data["reflectivity"]), len(data["unused"]), data["transceiver_count"], ] if len(set(lengths)) != 1: min_indx = min(lengths) logger.warning("Data lengths mismatched: d:%d, r:%d, u:%d, t:%d", *lengths) logger.warning(" Using minimum value: %d", min_indx) data["transceiver_count"] = min_indx else: min_indx = data["transceiver_count"] for field in self.header_fields(version): datagram_contents.append(data[field]) datagram_fmt += "%df" % (3 * data["transceiver_count"]) for indx in range(data["transceiver_count"]): datagram_contents.extend( [ data["depth"][indx], data["reflectivity"][indx], data["unused"][indx], ] ) return struct.pack(datagram_fmt, *datagram_contents) class SimradBottomParser(_SimradDatagramParser): """ Bottom Detection datagram contains the following keys: type: string == 'BOT0' low_date: long uint representing LSBytes of 64bit NT date high_date: long uint representing MSBytes of 64bit NT date datetime: datetime.datetime object of NT date converted to UTC transceiver_count: long uint with number of transceivers depth: [float], one value for each active channel The following methods are defined: from_string(str): parse a raw ER60 Bottom datagram (with leading/trailing datagram size stripped) to_string(): Returns the datagram as a raw string (including leading/trailing size fields) ready for writing to disk """ def __init__(self): headers = { 0: [ ("type", "4s"), ("low_date", "L"), ("high_date", "L"), ("transceiver_count", "L"), ] } _SimradDatagramParser.__init__(self, "BOT", headers) def _unpack_contents(self, raw_string, bytes_read, version): """""" header_values = struct.unpack( self.header_fmt(version), raw_string[: self.header_size(version)] ) data = {} for indx, field in enumerate(self.header_fields(version)): data[field] = header_values[indx] if isinstance(data[field], bytes): data[field] = data[field].decode() data["timestamp"] = nt_to_unix((data["low_date"], data["high_date"])) data["bytes_read"] = bytes_read if version == 0: depth_fmt = "=%dd" % (data["transceiver_count"],) depth_size = struct.calcsize(depth_fmt) buf_indx = self.header_size(version) data["depth"] = np.fromiter( struct.unpack(depth_fmt, raw_string[buf_indx : buf_indx + depth_size]), # noqa "float", ) return data def _pack_contents(self, data, version): datagram_fmt = self.header_fmt(version) datagram_contents = [] if version == 0: if len(data["depth"]) != data["transceiver_count"]: logger.warning( "# of depth values %d does not match transceiver count %d", len(data["depth"]), data["transceiver_count"], ) data["transceiver_count"] = len(data["depth"]) for field in self.header_fields(version): datagram_contents.append(data[field]) datagram_fmt += "%dd" % (data["transceiver_count"]) datagram_contents.extend(data["depth"]) return struct.pack(datagram_fmt, *datagram_contents) class SimradAnnotationParser(_SimradDatagramParser): """ ER60 Annotation datagram contains the following keys: type: string == 'TAG0' low_date: long uint representing LSBytes of 64bit NT date high_date: long uint representing MSBytes of 64bit NT date timestamp: datetime.datetime object of NT date, assumed to be UTC text: Annotation The following methods are defined: from_string(str): parse a raw ER60 Annotation datagram (with leading/trailing datagram size stripped) to_string(): Returns the datagram as a raw string (including leading/trailing size fields) ready for writing to disk """ def __init__(self): headers = {0: [("type", "4s"), ("low_date", "L"), ("high_date", "L")]} _SimradDatagramParser.__init__(self, "TAG", headers) def _unpack_contents(self, raw_string, bytes_read, version): """""" header_values = struct.unpack( self.header_fmt(version), raw_string[: self.header_size(version)] ) data = {} for indx, field in enumerate(self.header_fields(version)): data[field] = header_values[indx] if isinstance(data[field], bytes): data[field] = data[field].decode() data["timestamp"] = nt_to_unix((data["low_date"], data["high_date"])) data["bytes_read"] = bytes_read # if version == 0: # data['text'] = raw_string[self.header_size(version):].strip('\x00') # if isinstance(data['text'], bytes): # data['text'] = data['text'].decode() if version == 0: if sys.version_info.major > 2: data["text"] = str( raw_string[self.header_size(version) :].strip(b"\x00"), "ascii", errors="replace", ) else: data["text"] = unicode( # noqa raw_string[self.header_size(version) :].strip("\x00"), "ascii", errors="replace", ) return data def _pack_contents(self, data, version): datagram_fmt = self.header_fmt(version) datagram_contents = [] if version == 0: for field in self.header_fields(version): datagram_contents.append(data[field]) if data["text"][-1] != "\x00": tmp_string = data["text"] + "\x00" else: tmp_string = data["text"] # Pad with more nulls to 4-byte word boundary if necessary if len(tmp_string) % 4: tmp_string += "\x00" * (4 - (len(tmp_string) % 4)) datagram_fmt += "%ds" % (len(tmp_string)) datagram_contents.append(tmp_string) return struct.pack(datagram_fmt, *datagram_contents) class SimradNMEAParser(_SimradDatagramParser): """ ER60 NMEA datagram contains the following keys: type: string == 'NME0' low_date: long uint representing LSBytes of 64bit NT date high_date: long uint representing MSBytes of 64bit NT date timestamp: datetime.datetime object of NT date, assumed to be UTC nmea_string: full (original) NMEA string The following methods are defined: from_string(str): parse a raw ER60 NMEA datagram (with leading/trailing datagram size stripped) to_string(): Returns the datagram as a raw string (including leading/trailing size fields) ready for writing to disk """ nmea_head_re = re.compile(r"\$[A-Za-z]{5},") # noqa def __init__(self): headers = { 0: [("type", "4s"), ("low_date", "L"), ("high_date", "L")], 1: [("type", "4s"), ("low_date", "L"), ("high_date", "L"), ("port", "32s")], } _SimradDatagramParser.__init__(self, "NME", headers) def _unpack_contents(self, raw_string, bytes_read, version): """ Parses the NMEA string provided in raw_string :param raw_string: Raw NMEA string (i.e. '$GPZDA,160012.71,11,03,2004,-1,00*7D') :type raw_string: str :returns: None """ header_values = struct.unpack( self.header_fmt(version), raw_string[: self.header_size(version)] ) data = {} for indx, field in enumerate(self.header_fields(version)): data[field] = header_values[indx] if isinstance(data[field], bytes): data[field] = data[field].decode() data["timestamp"] = nt_to_unix((data["low_date"], data["high_date"])) data["bytes_read"] = bytes_read # Remove trailing \x00 from the PORT field for NME1, rest of the datagram identical to NME0 if version == 1: data["port"] = data["port"].strip("\x00") if version == 0 or version == 1: if sys.version_info.major > 2: data["nmea_string"] = str( raw_string[self.header_size(version) :].strip(b"\x00"), "ascii", errors="replace", ) else: data["nmea_string"] = unicode( # noqa raw_string[self.header_size(version) :].strip("\x00"), "ascii", errors="replace", ) if self.nmea_head_re.match(data["nmea_string"][:7]) is not None: data["nmea_talker"] = data["nmea_string"][1:3] data["nmea_type"] = data["nmea_string"][3:6] else: data["nmea_talker"] = "" data["nmea_type"] = "UNKNOWN" return data def _pack_contents(self, data, version): datagram_fmt = self.header_fmt(version) datagram_contents = [] if version == 0: for field in self.header_fields(version): datagram_contents.append(data[field]) if data["nmea_string"][-1] != "\x00": tmp_string = data["nmea_string"] + "\x00" else: tmp_string = data["nmea_string"] # Pad with more nulls to 4-byte word boundary if necessary if len(tmp_string) % 4: tmp_string += "\x00" * (4 - (len(tmp_string) % 4)) datagram_fmt += "%ds" % (len(tmp_string)) # Convert to python string if needed if isinstance(tmp_string, str): tmp_string = tmp_string.encode("ascii", errors="replace") datagram_contents.append(tmp_string) return struct.pack(datagram_fmt, *datagram_contents) class SimradMRUParser(_SimradDatagramParser): """ EK80 MRU datagram contains the following keys: type: string == 'MRU0' low_date: long uint representing LSBytes of 64bit NT date high_date: long uint representing MSBytes of 64bit NT date timestamp: datetime.datetime object of NT date, assumed to be UTC heave: float roll : float pitch: float heading: float The following methods are defined: from_string(str): parse a raw ER60 NMEA datagram (with leading/trailing datagram size stripped) to_string(): Returns the datagram as a raw string (including leading/trailing size fields) ready for writing to disk """ def __init__(self): headers = { 0: [ ("type", "4s"), ("low_date", "L"), ("high_date", "L"), ("heave", "f"), ("roll", "f"), ("pitch", "f"), ("heading", "f"), ] } _SimradDatagramParser.__init__(self, "MRU", headers) def _unpack_contents(self, raw_string, bytes_read, version): """ Unpacks the data in raw_string into dictionary containing MRU data :param raw_string: :type raw_string: str :returns: None """ header_values = struct.unpack( self.header_fmt(version), raw_string[: self.header_size(version)] ) data = {} for indx, field in enumerate(self.header_fields(version)): data[field] = header_values[indx] if isinstance(data[field], bytes): data[field] = data[field].decode() data["timestamp"] = nt_to_unix((data["low_date"], data["high_date"])) data["bytes_read"] = bytes_read return data def _pack_contents(self, data, version): datagram_fmt = self.header_fmt(version) datagram_contents = [] if version == 0: for field in self.header_fields(version): datagram_contents.append(data[field]) if data["nmea_string"][-1] != "\x00": tmp_string = data["nmea_string"] + "\x00" else: tmp_string = data["nmea_string"] # Pad with more nulls to 4-byte word boundary if necessary if len(tmp_string) % 4: tmp_string += "\x00" * (4 - (len(tmp_string) % 4)) datagram_fmt += "%ds" % (len(tmp_string)) # Convert to python string if needed if isinstance(tmp_string, str): tmp_string = tmp_string.encode("ascii", errors="replace") datagram_contents.append(tmp_string) return struct.pack(datagram_fmt, *datagram_contents) class SimradXMLParser(_SimradDatagramParser): """ EK80 XML datagram contains the following keys: type: string == 'XML0' low_date: long uint representing LSBytes of 64bit NT date high_date: long uint representing MSBytes of 64bit NT date timestamp: datetime.datetime object of NT date, assumed to be UTC subtype: string representing Simrad XML datagram type: configuration, environment, or parameter [subtype]: dict containing the data specific to the XML subtype. The following methods are defined: from_string(str): parse a raw EK80 XML datagram (with leading/trailing datagram size stripped) to_string(): Returns the datagram as a raw string (including leading/trailing size fields) ready for writing to disk """ # define the XML parsing options - here we define dictionaries for various xml datagram # types. When parsing that xml datagram, these dictionaries are used to inform the parser about # type conversion, name wrangling, and delimiter. If a field is missing, the parser # assumes no conversion: type will be string, default mangling, and that there is only 1 # element. # # the dicts are in the form: # 'XMLParamName':[converted type,'fieldname', 'parse char'] # # For example: 'PulseDurationFM':[float,'pulse_duration_fm',';'] # # will result in a return dictionary field named 'pulse_duration_fm' that contains a list # of float values parsed from a string that uses ';' to separate values. Empty strings # for fieldname and/or parse char result in the default action for those parsing steps. channel_parsing_options = { "MaxTxPowerTransceiver": [int, "", ""], "PulseDuration": [float, "", ";"], "PulseDurationFM": [float, "pulse_duration_fm", ";"], "SampleInterval": [float, "", ";"], "ChannelID": [str, "channel_id", ""], "HWChannelConfiguration": [str, "hw_channel_configuration", ""], } transceiver_parsing_options = { "TransceiverNumber": [int, "", ""], "Version": [str, "transceiver_version", ""], "IPAddress": [str, "ip_address", ""], "Impedance": [int, "", ""], } transducer_parsing_options = { "SerialNumber": [str, "transducer_serial_number", ""], "Frequency": [float, "transducer_frequency", ""], "FrequencyMinimum": [float, "transducer_frequency_minimum", ""], "FrequencyMaximum": [float, "transducer_frequency_maximum", ""], "BeamType": [int, "transducer_beam_type", ""], "Gain": [float, "", ";"], "SaCorrection": [float, "", ";"], "MaxTxPowerTransducer": [float, "", ""], "EquivalentBeamAngle": [float, "", ""], "BeamWidthAlongship": [float, "", ""], "BeamWidthAthwartship": [float, "", ""], "AngleSensitivityAlongship": [float, "", ""], "AngleSensitivityAthwartship": [float, "", ""], "AngleOffsetAlongship": [float, "", ""], "AngleOffsetAthwartship": [float, "", ""], "DirectivityDropAt2XBeamWidth": [ float, "directivity_drop_at_2x_beam_width", "", ], "TransducerOffsetX": [float, "", ""], "TransducerOffsetY": [float, "", ""], "TransducerOffsetZ": [float, "", ""], "TransducerAlphaX": [float, "", ""], "TransducerAlphaY": [float, "", ""], "TransducerAlphaZ": [float, "", ""], } header_parsing_options = {"Version": [str, "application_version", ""]} envxdcr_parsing_options = {"SoundSpeed": [float, "transducer_sound_speed", ""]} environment_parsing_options = { "Depth": [float, "", ""], "Acidity": [float, "", ""], "Salinity": [float, "", ""], "SoundSpeed": [float, "", ""], "Temperature": [float, "", ""], "Latitude": [float, "", ""], "SoundVelocityProfile": [float, "", ";"], "DropKeelOffset": [float, "", ""], "DropKeelOffsetIsManual": [int, "", ""], "WaterLevelDraft": [float, "", ""], "WaterLevelDraftIsManual": [int, "", ""], } parameter_parsing_options = { "ChannelID": [str, "channel_id", ""], "ChannelMode": [int, "", ""], "PulseForm": [int, "", ""], "Frequency": [float, "", ""], "PulseDuration": [float, "", ""], "SampleInterval": [float, "", ""], "TransmitPower": [float, "", ""], "Slope": [float, "", ""], } def __init__(self): headers = {0: [("type", "4s"), ("low_date", "L"), ("high_date", "L")]} _SimradDatagramParser.__init__(self, "XML", headers) def _unpack_contents(self, raw_string, bytes_read, version): """ Parses the NMEA string provided in raw_string :param raw_string: Raw NMEA string (i.e. '$GPZDA,160012.71,11,03,2004,-1,00*7D') :type raw_string: str :returns: None """ def from_CamelCase(xml_param): """ convert name from CamelCase to fit with existing naming convention by inserting an underscore before each capital and then lowering the caps e.g. CamelCase becomes camel_case. """ idx = list(reversed([i for i, c in enumerate(xml_param) if c.isupper()])) param_len = len(xml_param) for i in idx: # check if we should insert an underscore if i > 0 and i < param_len: xml_param = xml_param[:i] + "_" + xml_param[i:] xml_param = xml_param.lower() return xml_param def dict_to_dict(xml_dict, data_dict, parse_opts): """ dict_to_dict appends the ETree xml value dicts to a provided dictionary and along the way converts the key name to conform to the project's naming convention and optionally parses and or converts values as specified in the parse_opts dictionary. """ for k in xml_dict: # check if we're parsing this key/value if k in parse_opts: # try to parse the string if parse_opts[k][2]: try: data = xml_dict[k].split(parse_opts[k][2]) except: # bad or empty parse character(s) provided data = xml_dict[k] else: # no parse char provided - nothing to parse data = xml_dict[k] # try to convert to specified type if isinstance(data, list): for i in range(len(data)): try: data[i] = parse_opts[k][0](data[i]) except: pass else: data = parse_opts[k][0](data) # and add the value to the provided dict if parse_opts[k][1]: # add using the specified key name data_dict[parse_opts[k][1]] = data else: # add using the default key name wrangling data_dict[from_CamelCase(k)] = data else: # nothing to do with the value string data = xml_dict[k] # add the parameter to the provided dictionary data_dict[from_CamelCase(k)] = data header_values = struct.unpack( self.header_fmt(version), raw_string[: self.header_size(version)] ) data = {} for indx, field in enumerate(self.header_fields(version)): data[field] = header_values[indx] if isinstance(data[field], bytes): data[field] = data[field].decode() data["timestamp"] = nt_to_unix((data["low_date"], data["high_date"])) data["bytes_read"] = bytes_read if version == 0: if sys.version_info.major > 2: xml_string = str( raw_string[self.header_size(version) :].strip(b"\x00"), "ascii", errors="replace", ) else: xml_string = unicode( # noqa raw_string[self.header_size(version) :].strip("\x00"), "ascii", errors="replace", ) # get the ElementTree element root = ET.fromstring(xml_string) # get the XML message type data["subtype"] = root.tag.lower() # create the dictionary that contains the message data data[data["subtype"]] = {} # parse it if data["subtype"] == "configuration": # parse the Transceiver section for tcvr in root.iter("Transceiver"): # parse the Transceiver section tcvr_xml = tcvr.attrib # parse the Channel section -- this works with multiple channels # under 1 transceiver for tcvr_ch in tcvr.iter("Channel"): tcvr_ch_xml = tcvr_ch.attrib channel_id = tcvr_ch_xml["ChannelID"] # create the configuration dict for this channel data["configuration"][channel_id] = {} # add the transceiver data to the config dict (this is # replicated for all channels) dict_to_dict( tcvr_xml, data["configuration"][channel_id], self.transceiver_parsing_options, ) # add the general channel data to the config dict dict_to_dict( tcvr_ch_xml, data["configuration"][channel_id], self.channel_parsing_options, ) # check if there are >1 transducer under a single transceiver channel if len(list(tcvr_ch)) > 1: ValueError("Found >1 transducer under a single transceiver channel!") else: # should only have 1 transducer tcvr_ch_xducer = tcvr_ch.find( "Transducer" ) # get Element of this xducer f_par = tcvr_ch_xducer.findall("FrequencyPar") # Save calibration parameters if f_par: cal_par = { "frequency": np.array( [int(f.attrib["Frequency"]) for f in f_par] ), "gain": np.array([float(f.attrib["Gain"]) for f in f_par]), "impedance": np.array( [float(f.attrib["Impedance"]) for f in f_par] ), "phase": np.array([float(f.attrib["Phase"]) for f in f_par]), "beamwidth_alongship": np.array( [float(f.attrib["BeamWidthAlongship"]) for f in f_par] ), "beamwidth_athwartship": np.array( [float(f.attrib["BeamWidthAthwartship"]) for f in f_par] ), "angle_offset_alongship": np.array( [float(f.attrib["AngleOffsetAlongship"]) for f in f_par] ), "angle_offset_athwartship": np.array( [float(f.attrib["AngleOffsetAthwartship"]) for f in f_par] ), } data["configuration"][channel_id]["calibration"] = cal_par # add the transducer data to the config dict dict_to_dict( tcvr_ch_xducer.attrib, data["configuration"][channel_id], self.transducer_parsing_options, ) # get unique transceiver channel number stored in channel_id tcvr_ch_num = TCVR_CH_NUM_MATCHER.search(channel_id)[0] # parse the Transducers section from the root # TODO Remove Transducers if doesn't exist xducer = root.find("Transducers") if xducer is not None: # built occurrence lookup table for transducer name xducer_name_list = [] for xducer_ch in xducer.iter("Transducer"): xducer_name_list.append(xducer_ch.attrib["TransducerName"]) # find matching transducer for this channel_id match_found = False for xducer_ch in xducer.iter("Transducer"): if not match_found: xducer_ch_xml = xducer_ch.attrib match_name = ( xducer_ch.attrib["TransducerName"] == tcvr_ch_xducer.attrib["TransducerName"] ) if xducer_ch.attrib["TransducerSerialNumber"] == "": match_sn = False else: match_sn = ( xducer_ch.attrib["TransducerSerialNumber"] == tcvr_ch_xducer.attrib["SerialNumber"] ) match_tcvr = ( tcvr_ch_num in xducer_ch.attrib["TransducerCustomName"] ) # if find match add the transducer mounting details if ( Counter(xducer_name_list)[ xducer_ch.attrib["TransducerName"] ] > 1 ): # if more than one transducer has the same name # only check sn and transceiver unique number match_found = match_sn or match_tcvr else: match_found = match_name or match_sn or match_tcvr # add transducer mounting details if match_found: dict_to_dict( xducer_ch_xml, data["configuration"][channel_id], self.transducer_parsing_options, ) # add the header data to the config dict h = root.find("Header") dict_to_dict( h.attrib, data["configuration"][channel_id], self.header_parsing_options, ) elif data["subtype"] == "parameter": # parse the parameter XML datagram for h in root.iter("Channel"): parm_xml = h.attrib # add the data to the environment dict dict_to_dict(parm_xml, data["parameter"], self.parameter_parsing_options) elif data["subtype"] == "environment": # parse the environment XML datagram for h in root.iter("Environment"): env_xml = h.attrib # add the data to the environment dict dict_to_dict(env_xml, data["environment"], self.environment_parsing_options) for h in root.iter("Transducer"): transducer_xml = h.attrib # add the data to the environment dict dict_to_dict( transducer_xml, data["environment"], self.envxdcr_parsing_options, ) data["xml"] = xml_string return data def _pack_contents(self, data, version): def to_CamelCase(xml_param): """ convert name from project's convention to CamelCase for converting back to XML to in Kongsberg's convention. """ idx = list(reversed([i for i, c in enumerate(xml_param) if c.isupper()])) param_len = len(xml_param) for i in idx: # check if we should insert an underscore if idx > 0 and idx < param_len - 1: xml_param = xml_param[:idx] + "_" + xml_param[idx:] xml_param = xml_param.lower() return xml_param datagram_fmt = self.header_fmt(version) datagram_contents = [] if version == 0: for field in self.header_fields(version): datagram_contents.append(data[field]) if data["nmea_string"][-1] != "\x00": tmp_string = data["nmea_string"] + "\x00" else: tmp_string = data["nmea_string"] # Pad with more nulls to 4-byte word boundary if necessary if len(tmp_string) % 4: tmp_string += "\x00" * (4 - (len(tmp_string) % 4)) datagram_fmt += "%ds" % (len(tmp_string)) # Convert to python string if needed if isinstance(tmp_string, str): tmp_string = tmp_string.encode("ascii", errors="replace") datagram_contents.append(tmp_string) return struct.pack(datagram_fmt, *datagram_contents) class SimradFILParser(_SimradDatagramParser): """ EK80 FIL datagram contains the following keys: type: string == 'FIL1' low_date: long uint representing LSBytes of 64bit NT date high_date: long uint representing MSBytes of 64bit NT date timestamp: datetime.datetime object of NT date, assumed to be UTC stage: int channel_id: string n_coefficients: int decimation_factor: int coefficients: np.complex64 The following methods are defined: from_string(str): parse a raw EK80 FIL datagram (with leading/trailing datagram size stripped) to_string(): Returns the datagram as a raw string (including leading/trailing size fields) ready for writing to disk """ def __init__(self): headers = { 1: [ ("type", "4s"), ("low_date", "L"), ("high_date", "L"), ("stage", "h"), ("spare", "2s"), ("channel_id", "128s"), ("n_coefficients", "h"), ("decimation_factor", "h"), ] } _SimradDatagramParser.__init__(self, "FIL", headers) def _unpack_contents(self, raw_string, bytes_read, version): data = {} header_values = struct.unpack( self.header_fmt(version), raw_string[: self.header_size(version)] ) for indx, field in enumerate(self.header_fields(version)): data[field] = header_values[indx] # handle Python 3 strings if (sys.version_info.major > 2) and isinstance(data[field], bytes): data[field] = data[field].decode("latin_1") data["timestamp"] = nt_to_unix((data["low_date"], data["high_date"])) data["bytes_read"] = bytes_read if version == 1: # clean up the channel ID data["channel_id"] = data["channel_id"].strip("\x00") # unpack the coefficients indx = self.header_size(version) block_size = data["n_coefficients"] * 8 data["coefficients"] = np.frombuffer( raw_string[indx : indx + block_size], dtype="complex64" # noqa ) return data def _pack_contents(self, data, version): datagram_fmt = self.header_fmt(version) datagram_contents = [] if version == 0: pass elif version == 1: for field in self.header_fields(version): datagram_contents.append(data[field]) datagram_fmt += "%ds" % (len(data["beam_config"])) datagram_contents.append(data["beam_config"]) return struct.pack(datagram_fmt, *datagram_contents) class SimradConfigParser(_SimradDatagramParser): """ Simrad Configuration Datagram parser operates on dictionaries with the following keys: type: string == 'CON0' low_date: long uint representing LSBytes of 64bit NT date high_date: long uint representing MSBytes of 64bit NT date timestamp: datetime.datetime object of NT date, assumed to be UTC survey_name [str] transect_name [str] sounder_name [str] version [str] spare0 [str] transceiver_count [long] transceivers [list] List of dicts representing Transducer Configs: ME70 Data contains the following additional values (data contained w/in first 14 bytes of the spare0 field) multiplexing [short] Always 0 time_bias [long] difference between UTC and local time in min. sound_velocity_avg [float] [m/s] sound_velocity_transducer [float] [m/s] beam_config [str] Raw XML string containing beam config. info Transducer Config Keys (ER60/ES60/ES70 sounders): channel_id [str] channel ident string beam_type [long] Type of channel (0 = Single, 1 = Split) frequency [float] channel frequency equivalent_beam_angle [float] dB beamwidth_alongship [float] beamwidth_athwartship [float] angle_sensitivity_alongship [float] angle_sensitivity_athwartship [float] angle_offset_alongship [float] angle_offset_athwartship [float] pos_x [float] pos_y [float] pos_z [float] dir_x [float] dir_y [float] dir_z [float] pulse_length_table [float[5]] spare1 [str] gain_table [float[5]] spare2 [str] sa_correction_table [float[5]] spare3 [str] gpt_software_version [str] spare4 [str] Transducer Config Keys (ME70 sounders): channel_id [str] channel ident string beam_type [long] Type of channel (0 = Single, 1 = Split) reserved1 [float] channel frequency equivalent_beam_angle [float] dB beamwidth_alongship [float] beamwidth_athwartship [float] angle_sensitivity_alongship [float] angle_sensitivity_athwartship [float] angle_offset_alongship [float] angle_offset_athwartship [float] pos_x [float] pos_y [float] pos_z [float] beam_steering_angle_alongship [float] beam_steering_angle_athwartship [float] beam_steering_angle_unused [float] pulse_length [float] reserved2 [float] spare1 [str] gain [float] reserved3 [float] spare2 [str] sa_correction [float] reserved4 [float] spare3 [str] gpt_software_version [str] spare4 [str] from_string(str): parse a raw config datagram (with leading/trailing datagram size stripped) to_string(dict): Returns raw string (including leading/trailing size fields) ready for writing to disk """ COMMON_KEYS = [ ("channel_id", "128s"), ("beam_type", "l"), ("frequency", "f"), ("gain", "f"), ("equivalent_beam_angle", "f"), ("beamwidth_alongship", "f"), ("beamwidth_athwartship", "f"), ("angle_sensitivity_alongship", "f"), ("angle_sensitivity_athwartship", "f"), ("angle_offset_alongship", "f"), ("angle_offset_athwartship", "f"), ("pos_x", "f"), ("pos_y", "f"), ("pos_z", "f"), ("dir_x", "f"), ("dir_y", "f"), ("dir_z", "f"), ("pulse_length_table", "5f"), ("spare1", "8s"), ("gain_table", "5f"), ("spare2", "8s"), ("sa_correction_table", "5f"), ("spare3", "8s"), ("gpt_software_version", "16s"), ("spare4", "28s"), ] def __init__(self): headers = { 0: [ ("type", "4s"), ("low_date", "L"), ("high_date", "L"), ("survey_name", "128s"), ("transect_name", "128s"), ("sounder_name", "128s"), ("version", "30s"), ("spare0", "98s"), ("transceiver_count", "l"), ], 1: [("type", "4s"), ("low_date", "L"), ("high_date", "L")], } _SimradDatagramParser.__init__(self, "CON", headers) self._transducer_headers = { "ER60": self.COMMON_KEYS, "ES60": self.COMMON_KEYS, "ES70": self.COMMON_KEYS, "MBES": [ ("channel_id", "128s"), ("beam_type", "l"), ("frequency", "f"), ("reserved1", "f"), ("equivalent_beam_angle", "f"), ("beamwidth_alongship", "f"), ("beamwidth_athwartship", "f"), ("angle_sensitivity_alongship", "f"), ("angle_sensitivity_athwartship", "f"), ("angle_offset_alongship", "f"), ("angle_offset_athwartship", "f"), ("pos_x", "f"), ("pos_y", "f"), ("pos_z", "f"), ("beam_steering_angle_alongship", "f"), ("beam_steering_angle_athwartship", "f"), ("beam_steering_angle_unused", "f"), ("pulse_length", "f"), ("reserved2", "f"), ("spare1", "20s"), ("gain", "f"), ("reserved3", "f"), ("spare2", "20s"), ("sa_correction", "f"), ("reserved4", "f"), ("spare3", "20s"), ("gpt_software_version", "16s"), ("spare4", "28s"), ], } def _unpack_contents(self, raw_string, bytes_read, version): data = {} round6 = lambda x: round(x, ndigits=6) # noqa header_values = struct.unpack( self.header_fmt(version), raw_string[: self.header_size(version)] ) for indx, field in enumerate(self.header_fields(version)): data[field] = header_values[indx] # handle Python 3 strings if (sys.version_info.major > 2) and isinstance(data[field], bytes): data[field] = data[field].decode("latin_1") data["timestamp"] = nt_to_unix((data["low_date"], data["high_date"])) data["bytes_read"] = bytes_read if version == 0: data["transceivers"] = {} for field in ["transect_name", "version", "survey_name", "sounder_name"]: data[field] = data[field].strip("\x00") sounder_name = data["sounder_name"] if sounder_name == "MBES": _me70_extra_values = struct.unpack("=hLff", data["spare0"][:14]) data["multiplexing"] = _me70_extra_values[0] data["time_bias"] = _me70_extra_values[1] data["sound_velocity_avg"] = _me70_extra_values[2] data["sound_velocity_transducer"] = _me70_extra_values[3] data["spare0"] = data["spare0"][:14] + data["spare0"][14:].strip("\x00") else: data["spare0"] = data["spare0"].strip("\x00") buf_indx = self.header_size(version) try: transducer_header = self._transducer_headers[sounder_name] _sounder_name_used = sounder_name except KeyError: logger.warning( "Unknown sounder_name: %s, (no one of %s)", sounder_name, list(self._transducer_headers.keys()), ) logger.warning("Will use ER60 transducer config fields as default") transducer_header = self._transducer_headers["ER60"] _sounder_name_used = "ER60" txcvr_header_fields = [x[0] for x in transducer_header] txcvr_header_fmt = "=" + "".join([x[1] for x in transducer_header]) txcvr_header_size = struct.calcsize(txcvr_header_fmt) for txcvr_indx in range(1, data["transceiver_count"] + 1): txcvr_header_values_encoded = struct.unpack( txcvr_header_fmt, raw_string[buf_indx : buf_indx + txcvr_header_size], # noqa ) txcvr_header_values = list(txcvr_header_values_encoded) for tx_idx, tx_val in enumerate(txcvr_header_values_encoded): if isinstance(tx_val, bytes): txcvr_header_values[tx_idx] = tx_val.decode("latin_1") txcvr = data["transceivers"].setdefault(txcvr_indx, {}) if _sounder_name_used in ["ER60", "ES60", "ES70"]: for txcvr_field_indx, field in enumerate(txcvr_header_fields[:17]): txcvr[field] = txcvr_header_values[txcvr_field_indx] txcvr["pulse_length_table"] = np.fromiter( list(map(round6, txcvr_header_values[17:22])), "float" ) txcvr["spare1"] = txcvr_header_values[22] txcvr["gain_table"] = np.fromiter( list(map(round6, txcvr_header_values[23:28])), "float" ) txcvr["spare2"] = txcvr_header_values[28] txcvr["sa_correction_table"] = np.fromiter( list(map(round6, txcvr_header_values[29:34])), "float" ) txcvr["spare3"] = txcvr_header_values[34] txcvr["gpt_software_version"] = txcvr_header_values[35] txcvr["spare4"] = txcvr_header_values[36] elif _sounder_name_used == "MBES": for txcvr_field_indx, field in enumerate(txcvr_header_fields): txcvr[field] = txcvr_header_values[txcvr_field_indx] else: raise RuntimeError( "Unknown _sounder_name_used (Should not happen, this is a bug!)" ) txcvr["channel_id"] = txcvr["channel_id"].strip("\x00") txcvr["spare1"] = txcvr["spare1"].strip("\x00") txcvr["spare2"] = txcvr["spare2"].strip("\x00") txcvr["spare3"] = txcvr["spare3"].strip("\x00") txcvr["spare4"] = txcvr["spare4"].strip("\x00") txcvr["gpt_software_version"] = txcvr["gpt_software_version"].strip("\x00") buf_indx += txcvr_header_size elif version == 1: # CON1 only has a single data field: beam_config, holding an xml string data["beam_config"] = raw_string[self.header_size(version) :].strip("\x00") return data def _pack_contents(self, data, version): datagram_fmt = self.header_fmt(version) datagram_contents = [] if version == 0: if data["transceiver_count"] != len(data["transceivers"]): logger.warning("Mismatch between 'transceiver_count' and actual # of transceivers") data["transceiver_count"] = len(data["transceivers"]) sounder_name = data["sounder_name"] if sounder_name == "MBES": _packed_me70_values = struct.pack( "=hLff", data["multiplexing"], data["time_bias"], data["sound_velocity_avg"], data["sound_velocity_transducer"], ) data["spare0"] = _packed_me70_values + data["spare0"][14:] for field in self.header_fields(version): datagram_contents.append(data[field]) try: transducer_header = self._transducer_headers[sounder_name] _sounder_name_used = sounder_name except KeyError: logger.warning( "Unknown sounder_name: %s, (no one of %s)", sounder_name, list(self._transducer_headers.keys()), ) logger.warning("Will use ER60 transducer config fields as default") transducer_header = self._transducer_headers["ER60"] _sounder_name_used = "ER60" txcvr_header_fields = [x[0] for x in transducer_header] txcvr_header_fmt = "=" + "".join([x[1] for x in transducer_header]) txcvr_header_size = struct.calcsize(txcvr_header_fmt) # noqa for txcvr_indx, txcvr in list(data["transceivers"].items()): txcvr_contents = [] if _sounder_name_used in ["ER60", "ES60", "ES70"]: for field in txcvr_header_fields[:17]: txcvr_contents.append(txcvr[field]) txcvr_contents.extend(txcvr["pulse_length_table"]) txcvr_contents.append(txcvr["spare1"]) txcvr_contents.extend(txcvr["gain_table"]) txcvr_contents.append(txcvr["spare2"]) txcvr_contents.extend(txcvr["sa_correction_table"]) txcvr_contents.append(txcvr["spare3"]) txcvr_contents.extend([txcvr["gpt_software_version"], txcvr["spare4"]]) txcvr_contents_str = struct.pack(txcvr_header_fmt, *txcvr_contents) elif _sounder_name_used == "MBES": for field in txcvr_header_fields: txcvr_contents.append(txcvr[field]) txcvr_contents_str = struct.pack(txcvr_header_fmt, *txcvr_contents) else: raise RuntimeError( "Unknown _sounder_name_used (Should not happen, this is a bug!)" ) datagram_fmt += "%ds" % (len(txcvr_contents_str)) datagram_contents.append(txcvr_contents_str) elif version == 1: for field in self.header_fields(version): datagram_contents.append(data[field]) datagram_fmt += "%ds" % (len(data["beam_config"])) datagram_contents.append(data["beam_config"]) return struct.pack(datagram_fmt, *datagram_contents) class SimradRawParser(_SimradDatagramParser): """ Sample Data Datagram parser operates on dictionaries with the following keys: type: string == 'RAW0' low_date: long uint representing LSBytes of 64bit NT date high_date: long uint representing MSBytes of 64bit NT date timestamp: datetime.datetime object of NT date, assumed to be UTC channel [short] Channel number mode [short] 1 = Power only, 2 = Angle only 3 = Power & Angle transducer_depth [float] frequency [float] transmit_power [float] pulse_length [float] bandwidth [float] sample_interval [float] sound_velocity [float] absorption_coefficient [float] heave [float] roll [float] pitch [float] temperature [float] heading [float] transmit_mode [short] 0 = Active, 1 = Passive, 2 = Test, -1 = Unknown spare0 [str] offset [long] count [long] power [numpy array] Unconverted power values (if present) angle [numpy array] Unconverted angle values (if present) from_string(str): parse a raw sample datagram (with leading/trailing datagram size stripped) to_string(dict): Returns raw string (including leading/trailing size fields) ready for writing to disk """ def __init__(self): headers = { 0: [ ("type", "4s"), ("low_date", "L"), ("high_date", "L"), ("channel", "h"), ("mode", "h"), ("transducer_depth", "f"), ("frequency", "f"), ("transmit_power", "f"), ("pulse_length", "f"), ("bandwidth", "f"), ("sample_interval", "f"), ("sound_velocity", "f"), ("absorption_coefficient", "f"), ("heave", "f"), ("roll", "f"), ("pitch", "f"), ("temperature", "f"), ("heading", "f"), ("transmit_mode", "h"), ("spare0", "6s"), ("offset", "l"), ("count", "l"), ], 3: [ ("type", "4s"), ("low_date", "L"), ("high_date", "L"), ("channel_id", "128s"), ("data_type", "h"), ("spare", "2s"), ("offset", "l"), ("count", "l"), ], 4: [ ("type", "4s"), ("low_date", "L"), ("high_date", "L"), ("channel_id", "128s"), ("data_type", "h"), ("spare", "2s"), ("offset", "l"), ("count", "l"), ], } _SimradDatagramParser.__init__(self, "RAW", headers) def _unpack_contents(self, raw_string, bytes_read, version): header_values = struct.unpack( self.header_fmt(version), raw_string[: self.header_size(version)] ) data = {} for indx, field in enumerate(self.header_fields(version)): data[field] = header_values[indx] if isinstance(data[field], bytes): data[field] = data[field].decode() data["timestamp"] = nt_to_unix((data["low_date"], data["high_date"])) data["bytes_read"] = bytes_read if version == 0: if data["count"] > 0: block_size = data["count"] * 2 indx = self.header_size(version) if int(data["mode"]) & 0x1: data["power"] = np.frombuffer( raw_string[indx : indx + block_size], dtype="int16" # noqa ) indx += block_size else: data["power"] = None if int(data["mode"]) & 0x2: data["angle"] = np.frombuffer( raw_string[indx : indx + block_size], dtype="int8" # noqa ) data["angle"] = data["angle"].reshape((-1, 2)) else: data["angle"] = None else: data["power"] = np.empty((0,), dtype="int16") data["angle"] = np.empty((0, 2), dtype="int8") # RAW3 and RAW4 have the same format, only Datatype Bit 0-1 not used in RAW4 elif version == 3 or version == 4: # result = 1j*Data[...,1]; result += Data[...,0] # clean up the channel ID data["channel_id"] = data["channel_id"].strip("\x00") if data["count"] > 0: # set the initial block size and indx value. block_size = data["count"] * 2 indx = self.header_size(version) if data["data_type"] & 0b1: data["power"] = np.frombuffer( raw_string[indx : indx + block_size], dtype="int16" # noqa ) indx += block_size else: data["power"] = None if data["data_type"] & 0b10: data["angle"] = np.frombuffer( raw_string[indx : indx + block_size], dtype="int8" # noqa ) data["angle"] = data["angle"].reshape((-1, 2)) indx += block_size else: data["angle"] = None # determine the complex sample data type - this is contained in bits 2 and 3 # of the datatype <short> value. I'm assuming the types are exclusive... data["complex_dtype"] = np.float16 type_bytes = 2 if data["data_type"] & 0b1000: data["complex_dtype"] = np.float32 type_bytes = 8 # determine the number of complex samples data["n_complex"] = data["data_type"] >> 8 # unpack the complex samples if data["n_complex"] > 0: # determine the block size block_size = data["count"] * data["n_complex"] * type_bytes data["complex"] = np.frombuffer( raw_string[indx : indx + block_size], # noqa dtype=data["complex_dtype"], ) data["complex"].dtype = np.complex64 else: data["complex"] = None else: data["power"] = np.empty((0,), dtype="int16") data["angle"] = np.empty((0,), dtype="int8") data["complex"] = np.empty((0,), dtype="complex64") data["n_complex"] = 0 return data def _pack_contents(self, data, version): datagram_fmt = self.header_fmt(version) datagram_contents = [] if version == 0: if data["count"] > 0: if (int(data["mode"]) & 0x1) and (len(data.get("power", [])) != data["count"]): logger.warning( "Data 'count' = %d, but contains %d power samples. Ignoring power." ) data["mode"] &= ~(1 << 0) if (int(data["mode"]) & 0x2) and (len(data.get("angle", [])) != data["count"]): logger.warning( "Data 'count' = %d, but contains %d angle samples. Ignoring angle." ) data["mode"] &= ~(1 << 1) if data["mode"] == 0: logger.warning( "Data 'count' = %d, but mode == 0. Setting count to 0", data["count"], ) data["count"] = 0 for field in self.header_fields(version): datagram_contents.append(data[field]) if data["count"] > 0: if int(data["mode"]) & 0x1: datagram_fmt += "%dh" % (data["count"]) datagram_contents.extend(data["power"]) if int(data["mode"]) & 0x2: datagram_fmt += "%dH" % (data["count"]) datagram_contents.extend(data["angle"]) return struct.pack(datagram_fmt, *datagram_contents)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,814
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/convert/test_convert_azfp.py
"""test_convert_azfp.py This module contains tests that: - verify echopype converted files against those from AZFP Matlab scripts and EchoView - convert AZFP file with different range settings across frequency """ import numpy as np import pandas as pd from scipy.io import loadmat from echopype import open_raw import pytest @pytest.fixture def azfp_path(test_path): return test_path["AZFP"] def check_platform_required_scalar_vars(echodata): # check convention-required variables in the Platform group for var in [ "MRU_offset_x", "MRU_offset_y", "MRU_offset_z", "MRU_rotation_x", "MRU_rotation_y", "MRU_rotation_z", "position_offset_x", "position_offset_y", "position_offset_z", ]: assert var in echodata["Platform"] assert np.isnan(echodata["Platform"][var]) def test_convert_azfp_01a_matlab_raw(azfp_path): """Compare parsed raw data with Matlab outputs.""" azfp_01a_path = azfp_path / '17082117.01A' azfp_xml_path = azfp_path / '17041823.XML' azfp_matlab_data_path = azfp_path / 'from_matlab/17082117_matlab_Data.mat' azfp_matlab_output_path = azfp_path / 'from_matlab/17082117_matlab_Output_Sv.mat' # Convert file echodata = open_raw( raw_file=azfp_01a_path, sonar_model='AZFP', xml_path=azfp_xml_path ) # Read in the dataset that will be used to confirm working conversions. (Generated by Matlab) ds_matlab = loadmat(azfp_matlab_data_path) ds_matlab_output = loadmat(azfp_matlab_output_path) # Test beam group # frequency assert np.array_equal( ds_matlab['Data']['Freq'][0][0].squeeze(), echodata["Sonar/Beam_group1"].frequency_nominal / 1000, ) # matlab file in kHz # backscatter count assert np.array_equal( np.array( [ds_matlab_output['Output'][0]['N'][fidx] for fidx in range(4)] ), echodata["Sonar/Beam_group1"].backscatter_r.values, ) # Test vendor group # Test temperature assert np.array_equal( np.array([d[4] for d in ds_matlab['Data']['Ancillary'][0]]).squeeze(), echodata["Vendor_specific"].ancillary.isel(ancillary_len=4).values, ) assert np.array_equal( np.array([d[0] for d in ds_matlab['Data']['BatteryTx'][0]]).squeeze(), echodata["Vendor_specific"].battery_tx, ) assert np.array_equal( np.array( [d[0] for d in ds_matlab['Data']['BatteryMain'][0]] ).squeeze(), echodata["Vendor_specific"].battery_main, ) # tilt x-y assert np.array_equal( np.array([d[0] for d in ds_matlab['Data']['Ancillary'][0]]).squeeze(), echodata["Vendor_specific"].tilt_x_count, ) assert np.array_equal( np.array([d[1] for d in ds_matlab['Data']['Ancillary'][0]]).squeeze(), echodata["Vendor_specific"].tilt_y_count, ) # check convention-required variables in the Platform group check_platform_required_scalar_vars(echodata) def test_convert_azfp_01a_matlab_derived(): """Compare variables derived from raw parsed data with Matlab outputs.""" # TODO: test derived data # - ds_beam.ping_time from 01A raw data records # - investigate why ds_beam.tilt_x/y are different from ds_matlab['Data']['Tx']/['Ty'] # - derived temperature # # check convention-required variables in the Platform group # check_platform_required_scalar_vars(echodata) pytest.xfail("Tests for converting AZFP and comparing it" + " against Matlab derived data have not been implemented yet.") def test_convert_azfp_01a_raw_echoview(azfp_path): """Compare parsed power data (count) with csv exported by EchoView.""" azfp_01a_path = azfp_path / '17082117.01A' azfp_xml_path = azfp_path / '17041823.XML' # Read csv files exported by EchoView azfp_csv_path = [ azfp_path / f"from_echoview/17082117-raw{freq}.csv" for freq in [38, 125, 200, 455] ] channels = [] for file in azfp_csv_path: channels.append( pd.read_csv(file, header=None, skiprows=[0]).iloc[:, 6:] ) test_power = np.stack(channels) # Convert to netCDF and check echodata = open_raw( raw_file=azfp_01a_path, sonar_model='AZFP', xml_path=azfp_xml_path ) assert np.array_equal(test_power, echodata["Sonar/Beam_group1"].backscatter_r) # check convention-required variables in the Platform group check_platform_required_scalar_vars(echodata) def test_convert_azfp_01a_different_ranges(azfp_path): """Test converting files with different range settings across frequency.""" azfp_01a_path = azfp_path / '17031001.01A' azfp_xml_path = azfp_path / '17030815.XML' # Convert file echodata = open_raw( raw_file=azfp_01a_path, sonar_model='AZFP', xml_path=azfp_xml_path ) assert echodata["Sonar/Beam_group1"].backscatter_r.sel(channel='55030-125-1').dropna( 'range_sample' ).shape == (360, 438) assert echodata["Sonar/Beam_group1"].backscatter_r.sel(channel='55030-769-4').dropna( 'range_sample' ).shape == (360, 135) # check convention-required variables in the Platform group check_platform_required_scalar_vars(echodata) def test_convert_azfp_01a_notemperature_notilt(azfp_path): """Test converting file with no valid temperature or tilt data.""" azfp_01a_path = azfp_path / 'rutgers_glider_notemperature/22052500.01A' azfp_xml_path = azfp_path / 'rutgers_glider_notemperature/22052501.XML' echodata = open_raw( raw_file=azfp_01a_path, sonar_model='AZFP', xml_path=azfp_xml_path ) # Temperature variable is present in the Environment group and its values are all nan assert "temperature" in echodata["Environment"] assert echodata["Environment"]["temperature"].isnull().all() # Tilt variables are present in the Platform group and their values are all nan assert "tilt_x" in echodata["Platform"] assert "tilt_y" in echodata["Platform"] assert echodata["Platform"]["tilt_x"].isnull().all() assert echodata["Platform"]["tilt_y"].isnull().all()
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,815
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/calibrate/test_calibrate.py
import numpy as np import pandas as pd import pytest from scipy.io import loadmat import echopype as ep from echopype.calibrate.env_params_old import EnvParams import xarray as xr @pytest.fixture def azfp_path(test_path): return test_path['AZFP'] @pytest.fixture def ek60_path(test_path): return test_path['EK60'] @pytest.fixture def ek80_path(test_path): return test_path['EK80'] @pytest.fixture def ek80_cal_path(test_path): return test_path['EK80_CAL'] @pytest.fixture def ek80_ext_path(test_path): return test_path['EK80_EXT'] def test_compute_Sv_returns_water_level(ek60_path): # get EchoData object that has the water_level variable under platform and compute Sv of it ed = ep.open_raw(ek60_path / "ncei-wcsd" / "Summer2017-D20170620-T011027.raw", "EK60") ds_Sv = ep.calibrate.compute_Sv(ed) # make sure the returned Dataset has water_level and throw an assertion error if the # EchoData object does not have water_level (just in case we remove it from the file # used in the future) assert 'water_level' in ed["Platform"].data_vars.keys() assert 'water_level' in ds_Sv.data_vars def test_compute_Sv_ek60_echoview(ek60_path): # constant range_sample ek60_raw_path = str( ek60_path.joinpath('DY1801_EK60-D20180211-T164025.raw') ) ek60_echoview_path = ek60_path.joinpath('from_echoview') # Convert file echodata = ep.open_raw(ek60_raw_path, sonar_model='EK60') # Calibrate to get Sv ds_Sv = ep.calibrate.compute_Sv(echodata) # Compare with EchoView outputs channels = [] for freq in [18, 38, 70, 120, 200]: fname = str( ek60_echoview_path.joinpath( 'DY1801_EK60-D20180211-T164025-Sv%d.csv' % freq ) ) channels.append( pd.read_csv(fname, header=None, skiprows=[0]).iloc[:, 13:] ) test_Sv = np.stack(channels) # Echoview data is shifted by 1 sample along range (missing the first sample) # TODO: resolve: pydevd warning: Computing repr of channels (list) was slow (took 0.29s) assert np.allclose( test_Sv[:, :, 7:], ds_Sv.Sv.isel(ping_time=slice(None, 10), range_sample=slice(8, None)), atol=1e-8 ) def test_compute_Sv_ek60_matlab(ek60_path): ek60_raw_path = str( ek60_path.joinpath('DY1801_EK60-D20180211-T164025.raw') ) ek60_matlab_path = str( ek60_path.joinpath('from_matlab', 'DY1801_EK60-D20180211-T164025.mat') ) # Convert file echodata = ep.open_raw(ek60_raw_path, sonar_model='EK60') # Calibrate to get Sv ds_Sv = ep.calibrate.compute_Sv(echodata) ds_TS = ep.calibrate.compute_TS(echodata) # Load matlab outputs and test # matlab outputs were saved using # save('from_matlab/DY1801_EK60-D20180211-T164025.mat', 'data') ds_base = loadmat(ek60_matlab_path) def check_output(da_cmp, cal_type): # ds_base["data"]["pings"][0][0]["Sv"].shape = (1, 5) [5 channels] for seq, ch in enumerate(ds_base["data"]["config"][0][0]["channelid"][0]): ep_vals = da_cmp.sel(channel=ch).squeeze().data[:, 8:] # ignore the first 8 samples pyel_vals = ds_base['data']['pings'][0][0][cal_type][0, seq].T[:, 8:] assert np.allclose(pyel_vals, ep_vals) # Check Sv check_output(ds_Sv['Sv'], 'Sv') # Check TS check_output(ds_TS['TS'], 'Sp') def test_compute_Sv_ek60_duplicated_freq(ek60_path): # TODO: add comparison of actual values in this test ek60_raw_path = str( ek60_path.joinpath('DY1002_EK60-D20100318-T023008_rep_freq.raw') ) # Convert file echodata = ep.open_raw(ek60_raw_path, sonar_model='EK60') # Calibrate to get Sv ds_Sv = ep.calibrate.compute_Sv(echodata) ds_TS = ep.calibrate.compute_TS(echodata) assert isinstance(ds_Sv, xr.Dataset) assert isinstance(ds_TS, xr.Dataset) def test_compute_Sv_azfp(azfp_path): azfp_01a_path = str(azfp_path.joinpath('17082117.01A')) azfp_xml_path = str(azfp_path.joinpath('17041823.XML')) azfp_matlab_Sv_path = str( azfp_path.joinpath('from_matlab', '17082117_matlab_Output_Sv.mat') ) azfp_matlab_TS_path = str( azfp_path.joinpath('from_matlab', '17082117_matlab_Output_TS.mat') ) # Convert to .nc file echodata = ep.open_raw( raw_file=azfp_01a_path, sonar_model='AZFP', xml_path=azfp_xml_path ) # Calibrate using identical env params as in Matlab ParametersAZFP.m # AZFP Matlab code uses average temperature avg_temperature = echodata["Environment"]['temperature'].values.mean() env_params = { 'temperature': avg_temperature, 'salinity': 27.9, 'pressure': 59, } ds_Sv = ep.calibrate.compute_Sv(echodata=echodata, env_params=env_params) ds_TS = ep.calibrate.compute_TS(echodata=echodata, env_params=env_params) # Load matlab outputs and test # matlab outputs were saved using # save('from_matlab/17082117_matlab_Output.mat', 'Output') # data variables # save('from_matlab/17082117_matlab_Par.mat', 'Par') # parameters def check_output(base_path, ds_cmp, cal_type): ds_base = loadmat(base_path) # print(f"ds_base = {ds_base}") cal_type_in_ds_cmp = { 'Sv': 'Sv', 'TS': 'TS', # TS here is TS in matlab outputs } for fidx in range(4): # loop through all freq assert np.alltrue( ds_cmp.echo_range.isel(channel=fidx, ping_time=0).values[None, :] == ds_base['Output'][0]['Range'][fidx] ) assert np.allclose( ds_cmp[cal_type_in_ds_cmp[cal_type]].isel(channel=fidx).values, ds_base['Output'][0][cal_type][fidx], atol=1e-13, rtol=0, ) # Check Sv check_output(base_path=azfp_matlab_Sv_path, ds_cmp=ds_Sv, cal_type='Sv') # Check TS check_output(base_path=azfp_matlab_TS_path, ds_cmp=ds_TS, cal_type='TS') def test_compute_Sv_ek80_CW_complex(ek80_path): """Test calibrate CW mode data encoded as complex samples.""" ek80_raw_path = str( ek80_path.joinpath('ar2.0-D20201210-T000409.raw') ) # CW complex echodata = ep.open_raw(ek80_raw_path, sonar_model='EK80') ds_Sv = ep.calibrate.compute_Sv( echodata, waveform_mode='CW', encode_mode='complex' ) assert isinstance(ds_Sv, xr.Dataset) is True ds_TS = ep.calibrate.compute_TS( echodata, waveform_mode='CW', encode_mode='complex' ) assert isinstance(ds_TS, xr.Dataset) is True def test_compute_Sv_ek80_BB_complex(ek80_path): """Test calibrate BB mode data encoded as complex samples.""" ek80_raw_path = str( ek80_path.joinpath('ar2.0-D20201209-T235955.raw') ) # CW complex echodata = ep.open_raw(ek80_raw_path, sonar_model='EK80') ds_Sv = ep.calibrate.compute_Sv( echodata, waveform_mode='BB', encode_mode='complex' ) assert isinstance(ds_Sv, xr.Dataset) is True ds_TS = ep.calibrate.compute_TS( echodata, waveform_mode='BB', encode_mode='complex' ) assert isinstance(ds_TS, xr.Dataset) is True def test_compute_Sv_ek80_CW_power_BB_complex(ek80_path): """ Tests calibration in CW mode data encoded as power samples and calibration in BB mode data encoded as complex samples, while the file contains both CW power and BB complex samples. """ ek80_raw_path = ek80_path / "Summer2018--D20180905-T033113.raw" ed = ep.open_raw(ek80_raw_path, sonar_model="EK80") ds_Sv = ep.calibrate.compute_Sv( ed, waveform_mode="CW", encode_mode="power" ) assert isinstance(ds_Sv, xr.Dataset) ds_Sv = ep.calibrate.compute_Sv( ed, waveform_mode="BB", encode_mode="complex" ) assert isinstance(ds_Sv, xr.Dataset) def test_compute_Sv_ek80_CW_complex_BB_complex(ek80_cal_path, ek80_path): """ Tests calibration for file containing both BB and CW mode data with both encoded as complex samples. """ ek80_raw_path = ek80_cal_path / "2018115-D20181213-T094600.raw" # rx impedance / rx fs / tcvr type # ek80_raw_path = ek80_path / "D20170912-T234910.raw" # rx impedance / rx fs / tcvr type # ek80_raw_path = ek80_path / "Summer2018--D20180905-T033113.raw" # BB only, rx impedance / rx fs / tcvr type # ek80_raw_path = ek80_path / "ar2.0-D20201210-T000409.raw" # CW only, rx impedance / rx fs / tcvr type # ek80_raw_path = ek80_path / "saildrone/SD2019_WCS_v05-Phase0-D20190617-T125959-0.raw" # rx impedance / tcvr type # ek80_raw_path = ek80_path / "D20200528-T125932.raw" # CW only, WBT MINI, rx impedance / rx fs / tcvr type ed = ep.open_raw(ek80_raw_path, sonar_model="EK80") # ds_Sv = ep.calibrate.compute_Sv( # ed, waveform_mode="CW", encode_mode="complex" # ) # assert isinstance(ds_Sv, xr.Dataset) ds_Sv = ep.calibrate.compute_Sv( ed, waveform_mode="BB", encode_mode="complex" ) assert isinstance(ds_Sv, xr.Dataset)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,816
OSOceanAcoustics/echopype
refs/heads/main
/echopype/calibrate/range.py
from typing import Dict import xarray as xr from ..echodata import EchoData from ..echodata.simrad import retrieve_correct_beam_group from .env_params import harmonize_env_param_time DIMENSION_ORDER = ["channel", "ping_time", "range_sample"] def compute_range_AZFP(echodata: EchoData, env_params: Dict, cal_type: str) -> xr.DataArray: """ Computes the range (``echo_range``) of AZFP backscatter data in meters. Parameters ---------- echodata : EchoData An EchoData object holding data from an AZFP echosounder env_params : dict A dictionary holding environmental parameters needed for computing range See echopype.calibrate.env_params.get_env_params_AZFP() cal_type : {"Sv", "TS"} - `"Sv"` for calculating volume backscattering strength - `"TS"` for calculating target strength. This parameter needs to be specified for data from the AZFP echosounder due to a difference in the range computation given by the manufacturer Returns ------- xr.DataArray The range (``echo_range``) of the data in meters. Notes ----- For AZFP echosounder, the returned ``echo_range`` is duplicated along ``ping_time`` to conform with outputs from other echosounders, even though within each data file the range is held constant. """ # sound_speed should exist already if "sound_speed" not in env_params: raise RuntimeError( "sounds_speed not included in env_params, " "use echopype.calibrate.env_params.get_env_params_AZFP() to compute env_params " "by supplying temperature, salinity, and pressure." ) else: sound_speed = env_params["sound_speed"] # Check cal_type if cal_type is None: raise ValueError('cal_type must be "Sv" or "TS"') # Groups to use vend = echodata["Vendor_specific"] beam = echodata["Sonar/Beam_group1"] # Notation below follows p.86 of user manual N = vend["number_of_samples_per_average_bin"] # samples per bin f = vend["digitization_rate"] # digitization rate L = vend["lockout_index"] # number of lockout samples # keep this in ref of AZFP matlab code, # set to 1 since we want to calculate from raw data bins_to_avg = 1 # Harmonize sound_speed time1 and Beam_group1 ping_time sound_speed = harmonize_env_param_time( p=sound_speed, ping_time=beam.ping_time, ) # Calculate range using parameters for each freq # This is "the range to the centre of the sampling volume # for bin m" from p.86 of user manual if cal_type == "Sv": range_offset = 0 else: range_offset = sound_speed * beam["transmit_duration_nominal"] / 4 # from matlab code range_meter = ( sound_speed * L / (2 * f) + (sound_speed / 4) * ( ((2 * (beam["range_sample"] + 1) - 1) * N * bins_to_avg - 1) / f + beam["transmit_duration_nominal"] ) - range_offset ) # add name to facilitate xr.merge range_meter.name = "echo_range" # make order of dims conform with the order of backscatter data return range_meter.transpose(*DIMENSION_ORDER) def compute_range_EK( echodata: EchoData, env_params: Dict, waveform_mode: str = "CW", encode_mode: str = "power", chan_sel=None, ): """ Computes the range (``echo_range``) of EK backscatter data in meters. Parameters ---------- echodata : EchoData An EchoData object holding data from an AZFP echosounder env_params : dict A dictionary holding environmental parameters needed for computing range See echopype.calibrate.env_params.get_env_params_EK waveform_mode : {"CW", "BB"} Type of transmit waveform. Required only for data from the EK80 echosounder. - `"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 data format. Required only for data from the EK80 echosounder. - `"complex"` for complex samples - `"power"` for power/angle samples, only allowed when the echosounder is configured for narrowband transmission Returns ------- xr.DataArray The range (``echo_range``) of the data in meters. Notes ----- The EK80 echosounder can be configured to transmit either broadband (``waveform_mode="BB"``) or narrowband (``waveform_mode="CW"``) signals. When transmitting in broadband mode, the returned echoes must be 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 "power/angle" format). """ # sound_speed should exist already if echodata.sonar_model in ("EK60", "ES70"): ek_str = "EK60" elif echodata.sonar_model in ("EK80", "ES80", "EA640"): ek_str = "EK80" else: raise ValueError("The specified sonar_model is not supported!") if "sound_speed" not in env_params: raise RuntimeError( "sounds_speed not included in env_params, " f"use echopype.calibrate.env_params.get_env_params_{ek_str}() to compute env_params " ) else: sound_speed = env_params["sound_speed"] # Get the right Sonar/Beam_groupX group according to encode_mode ed_beam_group = retrieve_correct_beam_group(echodata, waveform_mode, encode_mode) beam = ( echodata[ed_beam_group] if chan_sel is None else echodata[ed_beam_group].sel(channel=chan_sel) ) # Harmonize sound_speed time1 and Beam_groupX ping_time sound_speed = harmonize_env_param_time( p=sound_speed, ping_time=beam.ping_time, ) # Range in meters, not modified for TVG compensation range_meter = beam["range_sample"] * beam["sample_interval"] * sound_speed / 2 # make order of dims conform with the order of backscatter data range_meter = range_meter.transpose(*DIMENSION_ORDER) # set entries with NaN backscatter data to NaN if "beam" in beam["backscatter_r"].dims: # Drop beam because echo_range should not have a beam dimension valid_idx = ~beam["backscatter_r"].isel(beam=0).drop("beam").isnull() else: valid_idx = ~beam["backscatter_r"].isnull() range_meter = range_meter.where(valid_idx) # remove time1 if exists as a coordinate if "time1" in range_meter.coords: range_meter = range_meter.drop("time1") # add name to facilitate xr.merge range_meter.name = "echo_range" return range_meter def range_mod_TVG_EK( echodata: EchoData, ed_beam_group: str, range_meter: xr.DataArray, sound_speed: xr.DataArray ) -> xr.DataArray: """ Modify range for TVG calculation. TVG correction factor changes depending when the echo recording starts wrt when the transmit signal is sent out. This depends on whether it is Ex60 or Ex80 style hardware ref: https://github.com/CI-CMG/pyEcholab/blob/RHT-EK80-Svf/echolab2/instruments/EK80.py#L4297-L4308 # noqa """ def mod_Ex60(): # 2-sample shift in the beginning return 2 * beam["sample_interval"] * sound_speed / 2 # [frequency x range_sample] def mod_Ex80(): mod = sound_speed * beam["transmit_duration_nominal"] / 4 if isinstance(mod, xr.DataArray) and "time1" in mod.coords: mod = mod.squeeze().drop("time1") return mod beam = echodata[ed_beam_group] vend = echodata["Vendor_specific"] # If EK60 if echodata.sonar_model in ["EK60", "ES70"]: range_meter = range_meter - mod_Ex60() # If EK80: # - compute range first assuming all channels have Ex80 style hardware # - change range for channels with Ex60 style hardware (GPT) elif echodata.sonar_model in ["EK80", "ES80", "EA640"]: range_meter = range_meter - mod_Ex80() # Change range for all channels with GPT if "GPT" in vend["transceiver_type"]: ch_GPT = vend["transceiver_type"] == "GPT" range_meter.loc[dict(channel=ch_GPT)] = range_meter.sel(channel=ch_GPT) - mod_Ex60() return range_meter
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,817
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/calibrate/test_env_params.py
import pytest import numpy as np import xarray as xr import echopype as ep from echopype.calibrate.env_params import ( harmonize_env_param_time, sanitize_user_env_dict, ENV_PARAMS, get_env_params_AZFP, get_env_params_EK, ) @pytest.fixture def azfp_path(test_path): return test_path['AZFP'] @pytest.fixture def ek60_path(test_path): return test_path['EK60'] @pytest.fixture def ek80_cal_path(test_path): return test_path['EK80_CAL'] def test_harmonize_env_param_time(): # Scalar p = 10.05 assert harmonize_env_param_time(p=p) == 10.05 # time1 length=1, should return length=1 numpy array p = xr.DataArray( data=[1], coords={ "time1": np.array(["2017-06-20T01:00:00"], dtype="datetime64[ns]") }, dims=["time1"] ) assert harmonize_env_param_time(p=p) == 1 # time1 length>1, interpolate to tareget ping_time p = xr.DataArray( data=np.array([0, 1]), coords={ "time1": np.arange("2017-06-20T01:00:00", "2017-06-20T01:00:31", np.timedelta64(30, "s"), dtype="datetime64[ns]") }, dims=["time1"] ) # ping_time target is identical to time1 ping_time_target = p["time1"].rename({"time1": "ping_time"}) p_new = harmonize_env_param_time(p=p, ping_time=ping_time_target) assert (p_new["ping_time"] == ping_time_target).all() assert (p_new.data == p.data).all() # ping_time target requires actual interpolation ping_time_target = xr.DataArray( data=[1], coords={ "ping_time": np.array(["2017-06-20T01:00:15"], dtype="datetime64[ns]") }, dims=["ping_time"] ) p_new = harmonize_env_param_time(p=p, ping_time=ping_time_target["ping_time"]) assert p_new["ping_time"] == ping_time_target["ping_time"] assert p_new.data == 0.5 @pytest.mark.parametrize( ("user_dict", "channel", "out_dict"), [ # dict all scalars, channel a list, output should be all scalars # - this behavior departs from sanitize_user_cal_dict, which will make scalars into xr.DataArray ( {"temperature": 10, "salinity": 20}, ["chA", "chB"], dict( dict.fromkeys(ENV_PARAMS), **{"temperature": 10, "salinity": 20} ) ), # dict has xr.DataArray, channel a list with matching values with those in dict ( {"temperature": 10, "sound_absorption": xr.DataArray([10, 20], coords={"channel": ["chA", "chB"]})}, ["chA", "chB"], dict( dict.fromkeys(ENV_PARAMS), **{"temperature": 10, "sound_absorption": xr.DataArray([10, 20], coords={"channel": ["chA", "chB"]})} ) ), # dict has xr.DataArray, channel a list with non-matching values with those in dict: XFAIL pytest.param( {"temperature": 10, "sound_absorption": xr.DataArray([10, 20], coords={"channel": ["chA", "chB"]})}, ["chA", "chC"], None, marks=pytest.mark.xfail(strict=True, reason="channel coordinate in param xr.DataArray mismatches that in the channel list"), ), # dict has xr.DataArray, channel a xr.DataArray ( {"temperature": 10, "sound_absorption": xr.DataArray([10, 20], coords={"channel": ["chA", "chB"]})}, xr.DataArray(["chA", "chB"], coords={"channel": ["chA", "chB"]}), dict( dict.fromkeys(ENV_PARAMS), **{"temperature": 10, "sound_absorption": xr.DataArray([10, 20], coords={"channel": ["chA", "chB"]})} ) ), # dict has sound_absorption as a scalar: XFAIL pytest.param( {"temperature": 10, "sound_absorption": 0.02}, ["chA", "chB"], None, marks=pytest.mark.xfail(strict=True, reason="sound_absorption should be a list or an xr.DataArray"), ), ], ids=[ "in_scalar_channel_list_out_scalar", "in_da_channel_list_out_da", "in_da_channel_list_mismatch", "in_da_channel_da", "in_absorption_scalae" ] ) def test_sanitize_user_env_dict(user_dict, channel, out_dict): """ Only test the case where the input sound_absorption is not an xr.DataArray nor a list, since other cases are tested under test_cal_params::test_sanitize_user_cal_dict """ env_dict = sanitize_user_env_dict(user_dict, channel) for p, v in env_dict.items(): if isinstance(v, xr.DataArray): assert v.identical(out_dict[p]) else: assert v == out_dict[p] @pytest.mark.parametrize( ("env_ext", "out_dict"), [ # pH should not exist in the output Sv dataset, formula sources should both be AZFP ( {"temperature": 10, "salinity": 20, "pressure": 100, "pH": 8.1}, dict( dict.fromkeys(ENV_PARAMS), **{"temperature": 10, "salinity": 20, "pressure": 100} ) ), # not including salinity or pressure: XFAIL pytest.param( {"temperature": 10, "pressure": 100, "pH": 8.1}, None, marks=pytest.mark.xfail(strict=True, reason="Fail since cal_channel_id in input param does not match channel of data"), ), ], ids=[ "default", "no_salinity", ] ) def test_get_env_params_AZFP(azfp_path, env_ext, out_dict): azfp_01a_path = str(azfp_path.joinpath('17082117.01A')) azfp_xml_path = str(azfp_path.joinpath('17041823.XML')) ed = ep.open_raw(azfp_01a_path, sonar_model='AZFP', xml_path=azfp_xml_path) env_dict = get_env_params_AZFP(echodata=ed, user_dict=env_ext) out_dict = dict( out_dict, **{ "sound_speed": ep.utils.uwa.calc_sound_speed( temperature=env_dict["temperature"], salinity=env_dict["salinity"], pressure=env_dict["pressure"], formula_source="AZFP" ), "sound_absorption": ep.utils.uwa.calc_absorption( frequency=ed["Sonar/Beam_group1"]["frequency_nominal"], temperature=env_dict["temperature"], salinity=env_dict["salinity"], pressure=env_dict["pressure"], formula_source="AZFP", ), "formula_sound_speed": "AZFP", "formula_absorption": "AZFP", } ) assert "pH" not in env_dict assert env_dict["formula_absorption"] == "AZFP" assert env_dict["formula_sound_speed"] == "AZFP" for p, v in env_dict.items(): if isinstance(v, xr.DataArray): assert v.identical(out_dict[p]) else: assert v == out_dict[p] @pytest.mark.parametrize( ("env_ext", "ref_formula_sound_speed", "ref_formula_absorption"), [ # T, S, P, pH all exist so will trigger calculation, check default formula sources ( {"temperature": 10, "salinity": 30, "pressure": 100, "pH": 8.1}, "Mackenzie", "FG", ), # T, S, P, pH all exist, will calculate; has absorption formula passed in, check using the correct formula ( {"temperature": 10, "salinity": 30, "pressure": 100, "pH": 8.1, "formula_absorption": "AM"}, "Mackenzie", "AM", ), ], ids=[ "calc_no_formula", "calc_with_formula", ] ) def test_get_env_params_EK60_calculate(ek60_path, env_ext, ref_formula_sound_speed, ref_formula_absorption): ed = ep.open_raw(ek60_path / "ncei-wcsd" / "Summer2017-D20170620-T011027.raw", sonar_model="EK60") env_dict = get_env_params_EK( sonar_type="EK60", beam=ed["Sonar/Beam_group1"], env=ed["Environment"], user_dict=env_ext, ) # Check formula sources assert env_dict["formula_sound_speed"] == ref_formula_sound_speed assert env_dict["formula_absorption"] == ref_formula_absorption # Check computation results sound_speed_ref = ep.utils.uwa.calc_sound_speed( temperature=env_ext["temperature"], salinity=env_ext["salinity"], pressure=env_ext["pressure"], formula_source=ref_formula_sound_speed, ) sound_speed_ref = ep.calibrate.env_params.harmonize_env_param_time( sound_speed_ref, ping_time=ed["Sonar/Beam_group1"]["ping_time"] ) absorption_ref = ep.utils.uwa.calc_absorption( frequency=ed["Sonar/Beam_group1"]["frequency_nominal"], temperature=env_ext["temperature"], salinity=env_ext["salinity"], pressure=env_ext["pressure"], pH=env_ext["pH"], sound_speed=sound_speed_ref, formula_source=ref_formula_absorption, ) absorption_ref = ep.calibrate.env_params.harmonize_env_param_time( absorption_ref, ping_time=ed["Sonar/Beam_group1"]["ping_time"] ) assert env_dict["sound_speed"] == sound_speed_ref assert env_dict["sound_absorption"].identical(absorption_ref) def test_get_env_params_EK60_from_data(ek60_path): """ If one of T, S, P, pH does not exist, use values from data file """ ed = ep.open_raw(ek60_path / "ncei-wcsd" / "Summer2017-D20170620-T011027.raw", sonar_model="EK60") env_dict = get_env_params_EK( sonar_type="EK60", beam=ed["Sonar/Beam_group1"], env=ed["Environment"], user_dict={"temperature": 10}, ) # Check default formula sources assert "formula_sound_speed" not in env_dict assert "formula_absorption" not in env_dict # Check params from data file: need to make time1 --> ping_time ref_sound_speed = ed["Environment"]["sound_speed_indicative"].copy() ref_sound_speed.coords["ping_time"] = ref_sound_speed["time1"] ref_sound_speed = ref_sound_speed.swap_dims({"time1": "ping_time"}).drop_vars("time1") assert env_dict["sound_speed"].identical(ref_sound_speed) ref_absorption = ed["Environment"]["absorption_indicative"].copy() ref_absorption.coords["ping_time"] = ref_absorption["time1"] ref_absorption = ref_absorption.swap_dims({"time1": "ping_time"}).drop_vars("time1") assert env_dict["sound_absorption"].identical(ref_absorption) @pytest.mark.parametrize( ("env_ext", "ref_formula_sound_speed", "ref_formula_absorption"), [ # T, S, P, pH all exist, check default formula sources ( {"temperature": 10, "salinity": 30, "pressure": 100, "pH": 8.1}, "Mackenzie", "FG", ), # T, S, P, pH all exist; has absorption formula passed in, check using the correct formula ( {"temperature": 10, "salinity": 30, "pressure": 100, "pH": 8.1, "formula_absorption": "AM"}, "Mackenzie", "AM", ), ], ids=[ "calc_no_formula", "calc_with_formula", ] ) def test_get_env_params_EK80_calculate(ek80_cal_path, env_ext, ref_formula_sound_speed, ref_formula_absorption): ed = ep.open_raw(ek80_cal_path / "2018115-D20181213-T094600.raw", sonar_model="EK80") env_dict = get_env_params_EK( sonar_type="EK60", beam=ed["Sonar/Beam_group1"], env=ed["Environment"], user_dict=env_ext, ) # Check formula sources assert env_dict["formula_sound_speed"] == ref_formula_sound_speed assert env_dict["formula_absorption"] == ref_formula_absorption # Check computation results sound_speed_ref = ep.utils.uwa.calc_sound_speed( temperature=env_ext["temperature"], salinity=env_ext["salinity"], pressure=env_ext["pressure"], formula_source=ref_formula_sound_speed, ) sound_speed_ref = ep.calibrate.env_params.harmonize_env_param_time( sound_speed_ref, ping_time=ed["Sonar/Beam_group1"]["ping_time"] ) absorption_ref = ep.utils.uwa.calc_absorption( frequency=ed["Sonar/Beam_group1"]["frequency_nominal"], temperature=env_ext["temperature"], salinity=env_ext["salinity"], pressure=env_ext["pressure"], pH=env_ext["pH"], sound_speed=sound_speed_ref, formula_source=ref_formula_absorption, ) absorption_ref = ep.calibrate.env_params.harmonize_env_param_time( absorption_ref, ping_time=ed["Sonar/Beam_group1"]["ping_time"] ) assert env_dict["sound_speed"] == sound_speed_ref assert env_dict["sound_absorption"].identical(absorption_ref) @pytest.mark.parametrize( ("env_ext", "ref_formula_sound_speed", "ref_formula_absorption"), [ # Only T exists, so use S, P, pH from data; # check default formula sources ( {"temperature": 10}, "Mackenzie", "FG", ), # Only T exists, so use S, P, pH from data; # has absorption formula passed in, check using the correct formula ( {"temperature": 10, "formula_absorption": "AM"}, "Mackenzie", "AM", ), ], ids=[ "calc_no_formula", "calc_with_formula", ] ) def test_get_env_params_EK80_from_data(ek80_cal_path, env_ext, ref_formula_sound_speed, ref_formula_absorption): ed = ep.open_raw(ek80_cal_path / "2018115-D20181213-T094600.raw", sonar_model="EK80") env_dict = get_env_params_EK( sonar_type="EK80", beam=ed["Sonar/Beam_group1"], env=ed["Environment"], user_dict=env_ext, # technically should use center freq, use frequency nominal here for convenience freq=ed["Sonar/Beam_group1"]["frequency_nominal"], ) # Check formula sources assert "formula_sound_speed" not in env_dict assert env_dict["formula_absorption"] == ref_formula_absorption # Check computation results # Use sound speed from data when T, S, P, pH are not all provided sound_speed_ref = ed["Environment"]["sound_speed_indicative"] # Always compute absorption for EK80 absorption_ref = ep.utils.uwa.calc_absorption( frequency=ed["Sonar/Beam_group1"]["frequency_nominal"], temperature=env_ext["temperature"], # use user-provided value if exists salinity=ed["Environment"]["salinity"], pressure=ed["Environment"]["depth"], pH=ed["Environment"]["acidity"], sound_speed=sound_speed_ref, formula_source=ref_formula_absorption, ) absorption_ref = ep.calibrate.env_params.harmonize_env_param_time( absorption_ref, ping_time=ed["Sonar/Beam_group1"]["ping_time"] ) assert env_dict["sound_speed"] == sound_speed_ref assert env_dict["sound_absorption"].identical(absorption_ref)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,818
OSOceanAcoustics/echopype
refs/heads/main
/echopype/convert/set_groups_base.py
import abc import warnings from typing import List, Set, Tuple import dask.array import numpy as np import pynmea2 import xarray as xr from ..echodata.convention import sonarnetcdf_1 from ..utils.coding import COMPRESSION_SETTINGS, set_time_encodings from ..utils.prov import echopype_prov_attrs, source_files_vars NMEA_SENTENCE_DEFAULT = ["GGA", "GLL", "RMC"] class SetGroupsBase(abc.ABC): """Base class for saving groups to netcdf or zarr from echosounder data files.""" def __init__( self, parser_obj, input_file, xml_path, output_path, sonar_model=None, engine="zarr", compress=True, overwrite=True, params=None, parsed2zarr_obj=None, ): # parser object ParseEK60/ParseAZFP/etc... self.parser_obj = parser_obj # Used for when a sonar that is not AZFP/EK60/EK80 can still be saved self.sonar_model = sonar_model self.input_file = input_file self.xml_path = xml_path self.output_path = output_path self.engine = engine self.compress = compress self.overwrite = overwrite # parsed data written directly to zarr object self.parsed2zarr_obj = parsed2zarr_obj if not self.compress: self.compression_settings = None else: self.compression_settings = COMPRESSION_SETTINGS[self.engine] self._varattrs = sonarnetcdf_1.yaml_dict["variable_and_varattributes"] # self._beamgroups must be a list of dicts, eg: # [{"name":"Beam_group1", "descr":"contains complex backscatter data # and other beam or channel-specific data."}] self._beamgroups = [] # TODO: change the set_XXX methods to return a dataset to be saved # in the overarching save method def set_toplevel(self, sonar_model, date_created=None) -> xr.Dataset: """Set the top-level group.""" # Collect variables tl_dict = { "conventions": "CF-1.7, SONAR-netCDF4-1.0, ACDD-1.3", "keywords": sonar_model, "sonar_convention_authority": "ICES", "sonar_convention_name": "SONAR-netCDF4", "sonar_convention_version": "1.0", "summary": "", "title": "", "date_created": np.datetime_as_string(date_created, "s") + "Z", } # Save ds = xr.Dataset() ds = ds.assign_attrs(tl_dict) return ds def set_provenance(self) -> xr.Dataset: """Set the Provenance group.""" prov_dict = echopype_prov_attrs(process_type="conversion") files_vars = source_files_vars(self.input_file, self.xml_path) if files_vars["meta_source_files_var"] is None: source_vars = files_vars["source_files_var"] else: source_vars = {**files_vars["source_files_var"], **files_vars["meta_source_files_var"]} ds = xr.Dataset( data_vars=source_vars, coords=files_vars["source_files_coord"], attrs=prov_dict ) return ds @abc.abstractmethod def set_env(self) -> xr.Dataset: """Set the Environment group.""" raise NotImplementedError @abc.abstractmethod def set_sonar(self) -> xr.Dataset: """Set the Sonar group.""" raise NotImplementedError @abc.abstractmethod def set_beam(self) -> xr.Dataset: """Set the /Sonar/Beam group.""" raise NotImplementedError @abc.abstractmethod def set_platform(self) -> xr.Dataset: """Set the Platform group.""" raise NotImplementedError def set_nmea(self) -> xr.Dataset: """Set the Platform/NMEA group.""" # Save nan if nmea data is not encoded in the raw file if len(self.parser_obj.nmea["nmea_string"]) != 0: # Convert np.datetime64 numbers to seconds since 1900-01-01 00:00:00Z # due to xarray.to_netcdf() error on encoding np.datetime64 objects directly time = ( self.parser_obj.nmea["timestamp"] - np.datetime64("1900-01-01T00:00:00") ) / np.timedelta64(1, "s") raw_nmea = self.parser_obj.nmea["nmea_string"] else: time = [np.nan] raw_nmea = [np.nan] ds = xr.Dataset( { "NMEA_datagram": ( ["time1"], raw_nmea, {"long_name": "NMEA datagram"}, ) }, coords={ "time1": ( ["time1"], time, { "axis": "T", "long_name": "Timestamps for NMEA datagrams", "standard_name": "time", "comment": "Time coordinate corresponding to NMEA sensor data.", }, ) }, attrs={"description": "All NMEA sensor datagrams"}, ) return set_time_encodings(ds) @abc.abstractmethod def set_vendor(self) -> xr.Dataset: """Set the Vendor_specific group.""" raise NotImplementedError # TODO: move this to be part of parser as it is not a "set" operation def _extract_NMEA_latlon(self): """Get the lat and lon values from the raw nmea data""" messages = [string[3:6] for string in self.parser_obj.nmea["nmea_string"]] idx_loc = np.argwhere(np.isin(messages, NMEA_SENTENCE_DEFAULT)).squeeze() if idx_loc.size == 1: # in case of only 1 matching message idx_loc = np.expand_dims(idx_loc, axis=0) nmea_msg = [] for x in idx_loc: try: nmea_msg.append(pynmea2.parse(self.parser_obj.nmea["nmea_string"][x])) except ( pynmea2.ChecksumError, pynmea2.SentenceTypeError, AttributeError, pynmea2.ParseError, ): nmea_msg.append(None) if nmea_msg: lat, lon = [], [] for x in nmea_msg: try: lat.append(x.latitude if hasattr(x, "latitude") else np.nan) except ValueError as ve: lat.append(np.nan) warnings.warn( "At least one latitude entry is problematic and " f"are assigned None in the converted data: {str(ve)}" ) try: lon.append(x.longitude if hasattr(x, "longitude") else np.nan) except ValueError as ve: lon.append(np.nan) warnings.warn( f"At least one longitude entry is problematic and " f"are assigned None in the converted data: {str(ve)}" ) else: lat, lon = [np.nan], [np.nan] msg_type = ( [x.sentence_type if hasattr(x, "sentence_type") else np.nan for x in nmea_msg] if nmea_msg else [np.nan] ) time1 = ( ( np.array(self.parser_obj.nmea["timestamp"])[idx_loc] - np.datetime64("1900-01-01T00:00:00") ) / np.timedelta64(1, "s") if nmea_msg else [np.nan] ) return time1, msg_type, lat, lon def _beam_groups_vars(self): """Stage beam_group coordinate and beam_group_descr variables sharing a common dimension, beam_group, to be inserted in the Sonar group""" beam_groups_vars = { "beam_group_descr": ( ["beam_group"], [di["descr"] for di in self._beamgroups], {"long_name": "Beam group description"}, ), } beam_groups_coord = { "beam_group": ( ["beam_group"], [di["name"] for di in self._beamgroups], {"long_name": "Beam group name"}, ), } return beam_groups_vars, beam_groups_coord @staticmethod def _add_beam_dim(ds: xr.Dataset, beam_only_names: Set[str], beam_ping_time_names: Set[str]): """ Adds ``beam`` as the last dimension to the appropriate variables in ``Sonar/Beam_groupX`` groups when necessary. Notes ----- When expanding the dimension of a Dataarray, it is necessary to copy the array (hence the .copy()). This allows the array to be writable downstream (i.e. we can assign values to certain indices). To retain the attributes and encoding of ``beam`` it is necessary to use .assign_coords() with ``beam`` from ds. """ # variables to add beam to add_beam_names = set(ds.variables).intersection(beam_only_names.union(beam_ping_time_names)) for var_name in add_beam_names: if "beam" in ds.dims: if "beam" not in ds[var_name].dims: ds[var_name] = ( ds[var_name] .expand_dims(dim={"beam": ds.beam}, axis=ds[var_name].ndim) .assign_coords(beam=ds.beam) .copy() ) else: # Add a single-value beam dimension and its attributes ds[var_name] = ( ds[var_name] .expand_dims(dim={"beam": np.array(["1"], dtype=str)}, axis=ds[var_name].ndim) .copy() ) ds[var_name].beam.attrs = sonarnetcdf_1.yaml_dict["variable_and_varattributes"][ "beam_coord_default" ]["beam"] @staticmethod def _add_ping_time_dim( ds: xr.Dataset, beam_ping_time_names: Set[str], ping_time_only_names: Set[str] ): """ Adds ``ping_time`` as the last dimension to the appropriate variables in ``Sonar/Beam_group1`` and ``Sonar/Beam_group2`` (when necessary). Notes ----- When expanding the dimension of a Dataarray, it is necessary to copy the array (hence the .copy()). This allows the array to be writable downstream (i.e. we can assign values to certain indices). To retain the attributes and encoding of ``ping_time`` it is necessary to use .assign_coords() with ``ping_time`` from ds. """ # variables to add ping_time to add_ping_time_names = ( set(ds.variables).intersection(beam_ping_time_names).union(ping_time_only_names) ) for var_name in add_ping_time_names: ds[var_name] = ( ds[var_name] .expand_dims(dim={"ping_time": ds.ping_time}, axis=ds[var_name].ndim) .assign_coords(ping_time=ds.ping_time) .copy() ) def beam_groups_to_convention( self, ds: xr.Dataset, beam_only_names: Set[str], beam_ping_time_names: Set[str], ping_time_only_names: Set[str], ): """ Manipulates variables in ``Sonar/Beam_groupX`` to adhere to SONAR-netCDF4 vers. 1 with respect to the use of ``ping_time`` and ``beam`` dimensions. This does several things: 1. Creates ``beam`` dimension and coordinate variable when not present. 2. Adds ``beam`` dimension to several variables when missing. 3. Adds ``ping_time`` dimension to several variables when missing. Parameters ---------- ds : xr.Dataset Dataset corresponding to ``Beam_groupX``. beam_only_names : Set[str] Variables that need only the beam dimension added to them. beam_ping_time_names : Set[str] Variables that need beam and ping_time dimensions added to them. ping_time_only_names : Set[str] Variables that need only the ping_time dimension added to them. """ self._add_ping_time_dim(ds, beam_ping_time_names, ping_time_only_names) self._add_beam_dim(ds, beam_only_names, beam_ping_time_names) def _get_channel_ids(self, chan_str: np.ndarray) -> List[str]: """ Obtains the channel IDs associated with ``chan_str``. Parameters ---------- chan_str : np.ndarray A numpy array of strings corresponding to the keys of ``config_datagram["transceivers"]`` Returns ------- A list of strings representing the channel IDS """ if self.sonar_model in ["EK60", "ES70"]: return [ self.parser_obj.config_datagram["transceivers"][int(i)]["channel_id"] for i in chan_str ] else: return [ self.parser_obj.config_datagram["configuration"][i]["channel_id"] for i in chan_str ] def _get_power_dataarray(self, zarr_path: str) -> xr.DataArray: """ Constructs a DataArray from a Dask array for the power data. Parameters ---------- zarr_path: str Path to the zarr file that contain the power data Returns ------- DataArray named "backscatter_r" representing the power data. """ # collect variables associated with the power data power = dask.array.from_zarr(zarr_path, component="power/power") pow_time_path = "power/" + self.parsed2zarr_obj.power_dims[0] pow_chan_path = "power/" + self.parsed2zarr_obj.power_dims[1] power_time = dask.array.from_zarr(zarr_path, component=pow_time_path).compute() power_channel = dask.array.from_zarr(zarr_path, component=pow_chan_path).compute() # obtain channel names for power data pow_chan_names = self._get_channel_ids(power_channel) backscatter_r = xr.DataArray( data=power, coords={ "ping_time": ( ["ping_time"], power_time, self._varattrs["beam_coord_default"]["ping_time"], ), "channel": ( ["channel"], pow_chan_names, self._varattrs["beam_coord_default"]["channel"], ), "range_sample": ( ["range_sample"], np.arange(power.shape[2]), self._varattrs["beam_coord_default"]["range_sample"], ), }, name="backscatter_r", attrs={ "long_name": self._varattrs["beam_var_default"]["backscatter_r"]["long_name"], "units": "dB", }, ) return backscatter_r def _get_angle_dataarrays(self, zarr_path: str) -> Tuple[xr.DataArray, xr.DataArray]: """ Constructs the DataArrays from Dask arrays associated with the angle data. Parameters ---------- zarr_path: str Path to the zarr file that contains the angle data Returns ------- DataArrays named "angle_athwartship" and "angle_alongship", respectively, representing the angle data. """ # collect variables associated with the angle data angle_along = dask.array.from_zarr(zarr_path, component="angle/angle_alongship") angle_athwart = dask.array.from_zarr(zarr_path, component="angle/angle_athwartship") ang_time_path = "angle/" + self.parsed2zarr_obj.angle_dims[0] ang_chan_path = "angle/" + self.parsed2zarr_obj.angle_dims[1] angle_time = dask.array.from_zarr(zarr_path, component=ang_time_path).compute() angle_channel = dask.array.from_zarr(zarr_path, component=ang_chan_path).compute() # obtain channel names for angle data ang_chan_names = self._get_channel_ids(angle_channel) array_coords = { "ping_time": ( ["ping_time"], angle_time, self._varattrs["beam_coord_default"]["ping_time"], ), "channel": ( ["channel"], ang_chan_names, self._varattrs["beam_coord_default"]["channel"], ), "range_sample": ( ["range_sample"], np.arange(angle_athwart.shape[2]), self._varattrs["beam_coord_default"]["range_sample"], ), } angle_athwartship = xr.DataArray( data=angle_athwart, coords=array_coords, name="angle_athwartship", attrs={ "long_name": "electrical athwartship angle", "comment": ( "Introduced in echopype for Simrad echosounders. " # noqa + "The athwartship angle corresponds to the major angle in SONAR-netCDF4 vers 2. " # noqa ), }, ) angle_alongship = xr.DataArray( data=angle_along, coords=array_coords, name="angle_alongship", attrs={ "long_name": "electrical alongship angle", "comment": ( "Introduced in echopype for Simrad echosounders. " # noqa + "The alongship angle corresponds to the minor angle in SONAR-netCDF4 vers 2. " # noqa ), }, ) return angle_athwartship, angle_alongship def _get_complex_dataarrays(self, zarr_path: str) -> Tuple[xr.DataArray, xr.DataArray]: """ Constructs the DataArrays from Dask arrays associated with the complex data. Parameters ---------- zarr_path: str Path to the zarr file that contains the complex data Returns ------- DataArrays named "backscatter_r" and "backscatter_i", respectively, representing the complex data. """ # collect variables associated with the complex data complex_r = dask.array.from_zarr(zarr_path, component="complex/backscatter_r") complex_i = dask.array.from_zarr(zarr_path, component="complex/backscatter_i") comp_time_path = "complex/" + self.parsed2zarr_obj.complex_dims[0] comp_chan_path = "complex/" + self.parsed2zarr_obj.complex_dims[1] complex_time = dask.array.from_zarr(zarr_path, component=comp_time_path).compute() complex_channel = dask.array.from_zarr(zarr_path, component=comp_chan_path).compute() # obtain channel names for complex data comp_chan_names = self._get_channel_ids(complex_channel) array_coords = { "ping_time": ( ["ping_time"], complex_time, self._varattrs["beam_coord_default"]["ping_time"], ), "channel": ( ["channel"], comp_chan_names, self._varattrs["beam_coord_default"]["channel"], ), "range_sample": ( ["range_sample"], np.arange(complex_r.shape[2]), self._varattrs["beam_coord_default"]["range_sample"], ), "beam": ( ["beam"], np.arange(start=1, stop=complex_r.shape[3] + 1).astype(str), self._varattrs["beam_coord_default"]["beam"], ), } backscatter_r = xr.DataArray( data=complex_r, coords=array_coords, name="backscatter_r", attrs={ "long_name": self._varattrs["beam_var_default"]["backscatter_r"]["long_name"], "units": "dB", }, ) backscatter_i = xr.DataArray( data=complex_i, coords=array_coords, name="backscatter_i", attrs={ "long_name": self._varattrs["beam_var_default"]["backscatter_i"]["long_name"], "units": "dB", }, ) return backscatter_r, backscatter_i
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,819
OSOceanAcoustics/echopype
refs/heads/main
/echopype/clean/api.py
""" Functions for reducing variabilities in backscatter data. """ from ..utils.prov import add_processing_level, echopype_prov_attrs, insert_input_processing_level from .noise_est import NoiseEst def estimate_noise(ds_Sv, ping_num, range_sample_num, noise_max=None): """ Estimate background noise by computing mean calibrated power of a collection of pings. See ``remove_noise`` for reference. Parameters ---------- ds_Sv : xr.Dataset dataset containing ``Sv`` and ``echo_range`` [m] ping_num : int number of pings to obtain noise estimates range_sample_num : int number of samples along the ``range_sample`` dimension to obtain noise estimates noise_max : float the upper limit for background noise expected under the operating conditions Returns ------- A DataArray containing noise estimated from the input ``ds_Sv`` """ noise_obj = NoiseEst(ds_Sv=ds_Sv.copy(), ping_num=ping_num, range_sample_num=range_sample_num) noise_obj.estimate_noise(noise_max=noise_max) return noise_obj.Sv_noise @add_processing_level("L*B") def remove_noise(ds_Sv, ping_num, range_sample_num, noise_max=None, SNR_threshold=3): """ Remove noise by using estimates of background noise from mean calibrated power of a collection of pings. 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. Parameters ---------- ds_Sv : xr.Dataset dataset containing ``Sv`` and ``echo_range`` [m] ping_num : int number of pings to obtain noise estimates range_sample_num : int number of samples along the ``range_sample`` dimension to obtain noise estimates noise_max : float the upper limit for background noise expected under the operating conditions SNR_threshold : float 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``) """ noise_obj = NoiseEst(ds_Sv=ds_Sv.copy(), ping_num=ping_num, range_sample_num=range_sample_num) noise_obj.remove_noise(noise_max=noise_max, SNR_threshold=SNR_threshold) ds_Sv = noise_obj.ds_Sv prov_dict = echopype_prov_attrs(process_type="processing") prov_dict["processing_function"] = "clean.remove_noise" ds_Sv = ds_Sv.assign_attrs(prov_dict) # The output ds_Sv is built as a copy of the input ds_Sv, so the step below is # not needed, strictly speaking. But doing makes the decorator function more generic ds_Sv = insert_input_processing_level(ds_Sv, input_ds=ds_Sv) return ds_Sv
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,820
OSOceanAcoustics/echopype
refs/heads/main
/echopype/calibrate/calibrate_ek.py
from typing import Dict import numpy as np import xarray as xr from ..echodata import EchoData from ..echodata.simrad import retrieve_correct_beam_group from ..utils.log import _init_logger from .cal_params import _get_interp_da, get_cal_params_EK from .calibrate_base import CalibrateBase from .ecs import conform_channel_order, ecs_ds2dict, ecs_ev2ep from .ek80_complex import ( compress_pulse, get_filter_coeff, get_norm_fac, get_tau_effective, get_transmit_signal, ) from .env_params import get_env_params_EK from .range import compute_range_EK, range_mod_TVG_EK logger = _init_logger(__name__) class CalibrateEK(CalibrateBase): def __init__(self, echodata: EchoData, env_params, cal_params, ecs_file, **kwargs): super().__init__(echodata, env_params, cal_params, ecs_file) self.ed_beam_group = None # will be assigned in child class self.ed_beam_group = None # will be assigned in child class def compute_echo_range(self, chan_sel: xr.DataArray = None): """ Compute echo range for EK echosounders. Returns ------- range_meter : xr.DataArray range in units meter """ self.range_meter = compute_range_EK( echodata=self.echodata, env_params=self.env_params, waveform_mode=self.waveform_mode, encode_mode=self.encode_mode, chan_sel=chan_sel, ) def _cal_power_samples(self, cal_type: str) -> xr.Dataset: """Calibrate power data from EK60 and EK80. Parameters ---------- cal_type: str 'Sv' for calculating volume backscattering strength, or 'TS' for calculating target strength Returns ------- xr.Dataset The calibrated dataset containing Sv or TS """ # Select source of backscatter data beam = self.echodata[self.ed_beam_group] # Derived params wavelength = self.env_params["sound_speed"] / beam["frequency_nominal"] # wavelength # range_meter = self.range_meter # TVG compensation with modified range sound_speed = self.env_params["sound_speed"] absorption = self.env_params["sound_absorption"] tvg_mod_range = range_mod_TVG_EK( self.echodata, self.ed_beam_group, self.range_meter, sound_speed ) tvg_mod_range = tvg_mod_range.where(tvg_mod_range > 0, np.nan) spreading_loss = 20 * np.log10(tvg_mod_range) absorption_loss = 2 * absorption * tvg_mod_range if cal_type == "Sv": # Calc gain CSv = ( 10 * np.log10(beam["transmit_power"]) + 2 * self.cal_params["gain_correction"] + self.cal_params["equivalent_beam_angle"] + 10 * np.log10( wavelength**2 * beam["transmit_duration_nominal"] * self.env_params["sound_speed"] / (32 * np.pi**2) ) ) # Calibration and echo integration out = ( beam["backscatter_r"] # has beam dim + spreading_loss + absorption_loss - CSv - 2 * self.cal_params["sa_correction"] ) out.name = "Sv" elif cal_type == "TS": # Calc gain CSp = ( 10 * np.log10(beam["transmit_power"]) + 2 * self.cal_params["gain_correction"] + 10 * np.log10(wavelength**2 / (16 * np.pi**2)) ) # Calibration and echo integration out = beam["backscatter_r"] + spreading_loss * 2 + absorption_loss - CSp out.name = "TS" # Attach calculated range (with units meter) into data set out = out.to_dataset() out = out.merge(self.range_meter) # Add frequency_nominal to data set out["frequency_nominal"] = beam["frequency_nominal"] # Add env and cal parameters out = self._add_params_to_output(out) # Remove time1 if exist as a coordinate if "time1" in out.coords: out = out.drop("time1") return out class CalibrateEK60(CalibrateEK): def __init__(self, echodata: EchoData, env_params, cal_params, ecs_file, **kwargs): super().__init__(echodata, env_params, cal_params, ecs_file) # Set sonar_type and waveform/encode mode self.sonar_type = "EK60" # Set cal type self.waveform_mode = "CW" self.encode_mode = "power" # Get the right ed_beam_group for CW power samples self.ed_beam_group = retrieve_correct_beam_group( echodata=self.echodata, waveform_mode=self.waveform_mode, encode_mode=self.encode_mode ) # Set the channels to calibrate # For EK60 this is all channels self.chan_sel = self.echodata[self.ed_beam_group]["channel"] beam = self.echodata[self.ed_beam_group] # Convert env_params and cal_params if self.ecs_file exists # Note a warning if thrown out in CalibrateBase.__init__ # to let user know cal_params and env_params are ignored if ecs_file is provided if self.ecs_file is not None: # also means self.ecs_dict != {} ds_env_tmp, ds_cal_tmp, _ = ecs_ev2ep(self.ecs_dict, "EK60") self.cal_params = ecs_ds2dict( conform_channel_order(ds_cal_tmp, beam["frequency_nominal"]) ) self.env_params = ecs_ds2dict( conform_channel_order(ds_env_tmp, beam["frequency_nominal"]) ) # Regardless of the source cal and env params, # go through the same sanitization and organization process self.env_params = get_env_params_EK( sonar_type=self.sonar_type, beam=self.echodata[self.ed_beam_group], env=self.echodata["Environment"], user_dict=self.env_params, ) self.cal_params = get_cal_params_EK( waveform_mode=self.waveform_mode, freq_center=beam["frequency_nominal"], beam=beam, vend=self.echodata["Vendor_specific"], user_dict=self.cal_params, sonar_type=self.sonar_type, ) # Compute range self.compute_echo_range() def compute_Sv(self, **kwargs): return self._cal_power_samples(cal_type="Sv") def compute_TS(self, **kwargs): return self._cal_power_samples(cal_type="TS") class CalibrateEK80(CalibrateEK): # Default EK80 params: these parameters are only recorded in later versions of EK80 software EK80_params = {} EK80_params["z_et"] = 75 # transducer impedance EK80_params["z_er"] = 1000 # transceiver impedance EK80_params["fs"] = { # default full sampling frequency [Hz] "default": 1500000, "GPT": 500000, "SBT": 50000, "WBAT": 1500000, "WBT TUBE": 1500000, "WBT MINI": 1500000, "WBT": 1500000, "WBT HP": 187500, "WBT LF": 93750, } def __init__( self, echodata: EchoData, env_params, cal_params, waveform_mode, encode_mode, ecs_file=None, **kwargs, ): super().__init__(echodata, env_params, cal_params, ecs_file) # Set sonar_type self.sonar_type = "EK80" # The waveform and encode mode combination checked in calibrate/api.py::_compute_cal # so just doing assignment here self.waveform_mode = waveform_mode self.encode_mode = encode_mode self.echodata = echodata # Get the right ed_beam_group given waveform and encode mode self.ed_beam_group = retrieve_correct_beam_group( echodata=self.echodata, waveform_mode=self.waveform_mode, encode_mode=self.encode_mode ) # Select the channels to calibrate if self.encode_mode == "power": # Power sample only possible under CW mode, # and all power samples will live in the same group self.chan_sel = self.echodata[self.ed_beam_group]["channel"] else: # Complex samples can be CW or BB, so select based on waveform mode chan_dict = self._get_chan_dict(self.echodata[self.ed_beam_group]) self.chan_sel = chan_dict[self.waveform_mode] # Subset of the right Sonar/Beam_groupX group given the selected channels beam = self.echodata[self.ed_beam_group].sel(channel=self.chan_sel) # Use center frequency if in BB mode, else use nominal channel frequency if self.waveform_mode == "BB": # use true center frequency to interpolate for various cal params self.freq_center = ( beam["transmit_frequency_start"] + beam["transmit_frequency_stop"] ).sel(channel=self.chan_sel) / 2 else: # use nominal channel frequency for CW pulse self.freq_center = beam["frequency_nominal"].sel(channel=self.chan_sel) # Convert env_params and cal_params if self.ecs_file exists # Note a warning if thrown out in CalibrateBase.__init__ # to let user know cal_params and env_params are ignored if ecs_file is provided if self.ecs_file is not None: # also means self.ecs_dict != {} ds_env, ds_cal_NB, ds_cal_BB = ecs_ev2ep(self.ecs_dict, "EK80") self.env_params = ecs_ds2dict( conform_channel_order(ds_env, beam["frequency_nominal"].sel(channel=self.chan_sel)) ) ds_cal_BB = conform_channel_order( ds_cal_BB, beam["frequency_nominal"].sel(channel=self.chan_sel) ) ds_cal_NB = self._scale_ecs_cal_params_NB( conform_channel_order( ds_cal_NB, beam["frequency_nominal"].sel(channel=self.chan_sel) ), beam, ) cal_params_dict = ecs_ds2dict(ds_cal_NB) if ds_cal_BB is not None: # get_cal_params_EK fill in empty params at param level, not channel level, # so need to do freq-dep interpolation here self.cal_params = self._assimilate_ecs_cal_params(cal_params_dict, ds_cal_BB) else: self.cal_params = cal_params_dict # Get env_params: depends on waveform mode self.env_params = get_env_params_EK( sonar_type=self.sonar_type, beam=beam, env=self.echodata["Environment"], user_dict=self.env_params, freq=self.freq_center, ) # Get cal_params: depends on waveform and encode mode self.cal_params = get_cal_params_EK( waveform_mode=self.waveform_mode, freq_center=self.freq_center, beam=beam, # already subset above vend=self.echodata["Vendor_specific"].sel(channel=self.chan_sel), user_dict=self.cal_params, sonar_type="EK80", ) # Compute echo range in meters self.compute_echo_range(chan_sel=self.chan_sel) @staticmethod def _get_chan_dict(beam: xr.Dataset) -> Dict: """ Build dict to select BB and CW channels from complex samples where data from both waveform modes may co-exist. """ # Use center frequency for each ping to select BB or CW channels # when all samples are encoded as complex samples if not np.all(beam["transmit_type"] == "CW"): # At least 1 BB ping exists -- this is analogous to what we had from before # Before: when at least 1 BB ping exists, frequency_start and frequency_end will exist # assume transmit_type identical for all pings in a channel first_ping_transmit_type = ( beam["transmit_type"].isel(ping_time=0).drop_vars("ping_time") ) # noqa return { # For BB: Keep only non-CW channels (LFM or FMD) based on transmit_type "BB": first_ping_transmit_type.where( first_ping_transmit_type != "CW", drop=True ).channel, # noqa # For CW: Keep only CW channels based on transmit_type "CW": first_ping_transmit_type.where( first_ping_transmit_type == "CW", drop=True ).channel, # noqa } else: # All channels are CW return {"BB": None, "CW": beam.channel} def _scale_ecs_cal_params_NB(self, ds_cal_NB: xr.Dataset, beam: xr.Dataset) -> xr.Dataset: """ Scale narrowband parameters based on center frequency of each ping with respect to channel nominal frequency. """ for p in ds_cal_NB: if p in ["angle_sensitivity_alongship", "angle_sensitivity_athwartship"]: ds_cal_NB[p] = ds_cal_NB[p] * self.freq_center / beam["frequency_nominal"] elif p in ["beamwidth_alongship", "beamwidth_athwartship"]: ds_cal_NB[p] = ds_cal_NB[p] * beam["frequency_nominal"] / self.freq_center elif p == "equivalent_beam_angle": ds_cal_NB[p] = ds_cal_NB[p] + 20 * np.log10( beam["frequency_nominal"] / self.freq_center ) return ds_cal_NB def _assimilate_ecs_cal_params(self, cal_params_dict: Dict, ds_cal_BB: xr.Dataset): """ Combine narrowband and broadband parameters derived from ECS. """ if ds_cal_BB is not None: ds_cal_BB = ds_cal_BB.rename({"channel": "cal_channel_id"}) for p in ds_cal_BB.data_vars: # For parameters where there is frequency-dependent values, # the corresponding narrowband (CW mode) values should exist for all channels if not np.all( [ ch in cal_params_dict[p]["channel"].values for ch in ds_cal_BB["cal_channel_id"].values ] ): raise ValueError( f"Narrowband (CW mode) parameter {p} should exist " "for all channels with frequency-dependent parameter values." ) # Assemble parameter data array with all channels # Either interpolate or pull from narrowband input # The ping_time dimension has to persist for BB case, # because center frequency may change across ping if "ping_time" in cal_params_dict[p].coords: ds_cal_BB[p] = _get_interp_da( da_param=ds_cal_BB[p], # freq-dep xr.DataArray freq_center=self.freq_center, alternative=cal_params_dict[p], ) else: ds_cal_BB[p] = _get_interp_da( da_param=ds_cal_BB[p], # freq-dep xr.DataArray freq_center=self.freq_center, alternative=cal_params_dict[p].expand_dims( dim={"ping_time": self.freq_center["ping_time"].size}, axis=1 ), ) # Keep only 'channel' and 'ping_time' coorindates ds_cal_BB = ds_cal_BB.drop_dims(["cal_frequency", "cal_channel_id"]) # Substitute params in narrowband dict return dict(cal_params_dict, **ecs_ds2dict(ds_cal_BB)) else: # Do nothing if ds_cal_BB is None return cal_params_dict def _get_power_from_complex( self, beam: xr.Dataset, chirp: Dict, z_et: float, z_er: float, ) -> xr.DataArray: """ Get power from complex samples. Parameters ---------- beam : xr.Dataset EchoData["Sonar/Beam_group1"] with selected channel subset chirp : dict a dictionary containing transmit chirp for BB channels z_et : float impedance of transducer [ohm] z_er : float impedance of transceiver [ohm] Returns ------- prx : xr.DataArray Power computed from complex samples """ def _get_prx(sig): return ( beam["beam"].size # number of transducer sectors * np.abs(sig.mean(dim="beam")) ** 2 / (2 * np.sqrt(2)) ** 2 * (np.abs(z_er + z_et) / z_er) ** 2 / z_et ) # Compute power if self.waveform_mode == "BB": pc = compress_pulse( backscatter=beam["backscatter_r"] + 1j * beam["backscatter_i"], chirp=chirp ) # has beam dim pc = pc / get_norm_fac(chirp=chirp) # normalization for each channel prx = _get_prx(pc) # ensure prx is xr.DataArray else: bs_cw = beam["backscatter_r"] + 1j * beam["backscatter_i"] prx = _get_prx(bs_cw) prx.name = "received_power" return prx def _get_B_theta_phi_m(self): """ Get transceiver gain compensation for BB mode. Source: https://github.com/CRIMAC-WP4-Machine-learning/CRIMAC-Raw-To-Svf-TSf/blob/abd01f9c271bb2dbe558c80893dbd7eb0d06fe38/Core/EK80DataContainer.py#L261-L273 # noqa From conversation with Lars Andersen, this correction is based on a longstanding empirical formula used for fitting beampattern during calibration, based on physically meaningful parameters such as the angle offset and beamwidth. """ fac_along = ( np.abs(-self.cal_params["angle_offset_alongship"]) / (self.cal_params["beamwidth_alongship"] / 2) ) ** 2 fac_athwart = ( np.abs(-self.cal_params["angle_offset_athwartship"]) / (self.cal_params["beamwidth_athwartship"] / 2) ) ** 2 B_theta_phi_m = 0.5 * 6.0206 * (fac_along + fac_athwart - 0.18 * fac_along * fac_athwart) return B_theta_phi_m def _cal_complex_samples(self, cal_type: str) -> xr.Dataset: """Calibrate complex data from EK80. Parameters ---------- cal_type : str 'Sv' for calculating volume backscattering strength, or 'TS' for calculating target strength Returns ------- xr.Dataset The calibrated dataset containing Sv or TS """ # Select source of backscatter data beam = self.echodata[self.ed_beam_group].sel(channel=self.chan_sel) vend = self.echodata["Vendor_specific"].sel(channel=self.chan_sel) # Get transmit signal tx_coeff = get_filter_coeff(vend) fs = self.cal_params["receiver_sampling_frequency"] # Switch to use Andersen implementation for transmit chirp starting v0.6.4 tx, tx_time = get_transmit_signal(beam, tx_coeff, self.waveform_mode, fs) # Params to clarity in use below z_er = self.cal_params["impedance_transceiver"] z_et = self.cal_params["impedance_transducer"] gain = self.cal_params["gain_correction"] # Transceiver gain compensation for BB mode if self.waveform_mode == "BB": gain = gain - self._get_B_theta_phi_m() absorption = self.env_params["sound_absorption"] range_meter = self.range_meter sound_speed = self.env_params["sound_speed"] wavelength = sound_speed / self.freq_center transmit_power = beam["transmit_power"] # TVG compensation with modified range tvg_mod_range = range_mod_TVG_EK( self.echodata, self.ed_beam_group, range_meter, sound_speed ) tvg_mod_range = tvg_mod_range.where(tvg_mod_range > 0, np.nan) spreading_loss = 20 * np.log10(tvg_mod_range) absorption_loss = 2 * absorption * tvg_mod_range # Get power from complex samples prx = self._get_power_from_complex(beam=beam, chirp=tx, z_et=z_et, z_er=z_er) prx = prx.where(prx > 0, np.nan) # Compute based on cal_type if cal_type == "Sv": # Effective pulse length # compute first assuming all channels are not GPT tau_effective = get_tau_effective( ytx_dict=tx, fs_deci_dict={k: 1 / np.diff(v[:2]) for (k, v) in tx_time.items()}, # decimated fs waveform_mode=self.waveform_mode, channel=self.chan_sel, ping_time=beam["ping_time"], ) # Use pulse_duration in place of tau_effective for GPT channels # below assumesthat all transmit parameters are identical # and needs to be changed when allowing transmit parameters to vary by ping ch_GPT = vend["transceiver_type"] == "GPT" tau_effective[ch_GPT] = beam["transmit_duration_nominal"][ch_GPT].isel(ping_time=0) # equivalent_beam_angle # TODO: THIS ONE CARRIES THE BEAM DIMENSION AROUND psifc = self.cal_params["equivalent_beam_angle"] out = ( 10 * np.log10(prx) + spreading_loss + absorption_loss - 10 * np.log10(wavelength**2 * transmit_power * sound_speed / (32 * np.pi**2)) - 2 * gain - 10 * np.log10(tau_effective) - psifc ) # Correct for sa_correction if CW mode if self.waveform_mode == "CW": out = out - 2 * self.cal_params["sa_correction"] out.name = "Sv" # out = out.rename_vars({list(out.data_vars.keys())[0]: "Sv"}) elif cal_type == "TS": out = ( 10 * np.log10(prx) + 2 * spreading_loss + absorption_loss - 10 * np.log10(wavelength**2 * transmit_power / (16 * np.pi**2)) - 2 * gain ) out.name = "TS" # Attach calculated range (with units meter) into data set out = out.to_dataset().merge(range_meter) # Add frequency_nominal to data set out["frequency_nominal"] = beam["frequency_nominal"] # Add env and cal parameters out = self._add_params_to_output(out) return out def _compute_cal(self, cal_type) -> xr.Dataset: """ Private method to compute Sv or TS from EK80 data, called by compute_Sv or compute_TS. Parameters ---------- cal_type : str 'Sv' for calculating volume backscattering strength, or 'TS' for calculating target strength Returns ------- xr.Dataset An xarray Dataset containing either Sv or TS. """ # Set flag_complex: True-complex cal, False-power cal flag_complex = ( True if self.waveform_mode == "BB" or self.encode_mode == "complex" else False ) if flag_complex: # Complex samples can be BB or CW ds_cal = self._cal_complex_samples(cal_type=cal_type) else: # Power samples only make sense for CW mode data ds_cal = self._cal_power_samples(cal_type=cal_type) return ds_cal def compute_Sv(self): """Compute volume backscattering strength (Sv). Returns ------- Sv : xr.DataSet A DataSet containing volume backscattering strength (``Sv``) and the corresponding range (``echo_range``) in units meter. """ return self._compute_cal(cal_type="Sv") def compute_TS(self): """Compute target strength (TS). Returns ------- TS : xr.DataSet A DataSet containing target strength (``TS``) and the corresponding range (``echo_range``) in units meter. """ return self._compute_cal(cal_type="TS")
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,821
OSOceanAcoustics/echopype
refs/heads/main
/echopype/calibrate/cal_params.py
from typing import Dict, List, Literal, Union import numpy as np import xarray as xr CAL_PARAMS = { "EK60": ( "sa_correction", "gain_correction", "equivalent_beam_angle", "angle_offset_alongship", "angle_offset_athwartship", "angle_sensitivity_alongship", "angle_sensitivity_athwartship", "beamwidth_alongship", "beamwidth_athwartship", ), "EK80": ( "sa_correction", "gain_correction", "equivalent_beam_angle", "angle_offset_alongship", "angle_offset_athwartship", "angle_sensitivity_alongship", "angle_sensitivity_athwartship", "beamwidth_alongship", "beamwidth_athwartship", "impedance_transducer", # z_et "impedance_transceiver", # z_er "receiver_sampling_frequency", ), "AZFP": ("EL", "DS", "TVR", "VTX", "equivalent_beam_angle", "Sv_offset"), } EK80_DEFAULT_PARAMS = { "impedance_transducer": 75, "impedance_transceiver": 1000, "receiver_sampling_frequency": { # default full sampling frequency [Hz] "default": 1500000, "GPT": 500000, "SBT": 50000, "WBAT": 1500000, "WBT TUBE": 1500000, "WBT MINI": 1500000, "WBT": 1500000, "WBT HP": 187500, "WBT LF": 93750, }, } def param2da(p_val: Union[int, float, list], channel: Union[list, xr.DataArray]) -> xr.DataArray: """ Organize individual parameter in scalar or list to xr.DataArray with channel coordinate. Parameters ---------- p_val : int, float, or list A scalar or list holding calibration params for one or more channels. Each param has to be a scalar. channel : list or xr.DataArray Values to use for the output channel coordinate Returns ------- xr.DataArray A data array with channel coordinate """ # TODO: allow passing in np.array as dict values to assemble a frequency-dependent cal da if not isinstance(p_val, (int, float, list)): raise ValueError("'p_val' needs to be one of type int, float, or list") if isinstance(p_val, list): # Check length if p_val a list if len(p_val) != len(channel): raise ValueError("The lengths of 'p_val' and 'channel' should be identical") return xr.DataArray(p_val, dims=["channel"], coords={"channel": channel}) else: # if scalar, make a list to form data array return xr.DataArray([p_val] * len(channel), dims=["channel"], coords={"channel": channel}) def sanitize_user_cal_dict( sonar_type: Literal["EK60", "EK80", "AZFP"], user_dict: Dict[str, Union[int, float, list, xr.DataArray]], channel: Union[List, xr.DataArray], ) -> Dict[str, Union[int, float, xr.DataArray]]: """ Creates a blueprint for ``cal_params`` dictionary and check the format/organize user-provided parameters. Parameters ---------- sonar_type : str Type of sonar, one of "EK60", "EK80", or "AZFP" user_dict : dict A dictionary containing user input calibration parameters as {parameter name: parameter value}. Parameter value has to be a scalar (int or float) or an ``xr.DataArray``. If parameter value is an ``xr.DataArray``, it has to either have 'channel' as a coordinate or have both ``cal_channel_id`` and ``cal_frequency`` as coordinates. channel : list or xr.DataArray A list of channels to be calibrated. For EK80 data, this list has to corresponds with the subset of channels selected based on waveform_mode and encode_mode """ # Check sonar type if sonar_type not in ["EK60", "EK80", "AZFP"]: raise ValueError("'sonar_type' has to be one of: 'EK60', 'EK80', or 'AZFP'") # Make channel a sorted list if not isinstance(channel, (list, xr.DataArray)): raise ValueError("'channel' has to be a list or an xr.DataArray") if isinstance(channel, xr.DataArray): channel_sorted = sorted(channel.values) else: channel_sorted = sorted(channel) # Screen parameters: only retain those defined in CAL_PARAMS # -- transform params in scalar or list to xr.DataArray # -- directly pass through those that are xr.DataArray and pass the check for coordinates out_dict = dict.fromkeys(CAL_PARAMS[sonar_type]) for p_name, p_val in user_dict.items(): if p_name in out_dict: # if p_val an xr.DataArray, check existence and coordinates if isinstance(p_val, xr.DataArray): # if 'channel' is a coordinate, it has to match that of the data if "channel" in p_val.coords: if not (sorted(p_val.coords["channel"].values) == channel_sorted): raise ValueError( f"The 'channel' coordinate of {p_name} has to match " "that of the data to be calibrated" ) elif "cal_channel_id" in p_val.coords and "cal_frequency" in p_val.coords: if not (sorted(p_val.coords["cal_channel_id"].values) == channel_sorted): raise ValueError( f"The 'cal_channel_id' coordinate of {p_name} has to match " "that of the data to be calibrated" ) else: raise ValueError( f"{p_name} has to either have 'channel' as a coordinate " "or have both 'cal_channel_id' and 'cal_frequency' as coordinates" ) out_dict[p_name] = p_val # If p_val a scalar or list, make it xr.DataArray elif isinstance(p_val, (int, float, list)): # check for list dimension happens within param2da() out_dict[p_name] = param2da(p_val, channel) # p_val has to be one of int, float, xr.DataArray else: raise ValueError(f"{p_name} has to be a scalar, list, or an xr.DataArray") # TODO: Consider pre-sort the param xr.DataArray? return out_dict def _get_interp_da( da_param: Union[None, xr.DataArray], freq_center: xr.DataArray, alternative: Union[int, float, xr.DataArray], BB_factor: float = 1, ) -> xr.DataArray: """ Get interpolated xr.DataArray aligned with the channel coordinate. Interpolation at freq_center when da_param contains frequency-dependent xr.DataArray. When da_param is None or does not contain frequency-dependent xr.DataArray, the alternative (a const or an xr.DataArray with coordinate channel) is used. Parameters ---------- da_param : xr.DataArray or None A data array from the Vendor group or user dict with freq-dependent param values freq_center : xr.DataArray Center frequency (BB) or nominal frequency (CW) alternative : xr.DataArray or int or float Alternative for when freq-dep values do not exist BB_factor : float scaling factor due to BB transmit signal with different center frequency with respect to nominal channel frequency; only applies when ``alternative`` from the Sonar/Beam_groupX group is used for params ``angle_sensitivity_alongship/athwartship`` and ``beamwidth_alongship/athwartship`` (``see get_cal_params_EK`` for detail) Returns ------- xr.DataArray Data array aligned with the channel coordinate. Note ---- ``da_param`` is always an xr.DataArray from the Vendor-specific group. It is possible that only a subset of the channels have frequency-dependent parameter values. The output xr.DataArray here is constructed channel-by-channel to allow for this flexibility. ``alternative`` can be one of the following: - scalar (int or float): this is the case for impedance_transducer - xr.DataArray with coordinates channel, ping_time, and beam: this is the case for parameters angle_offset_alongship, angle_offset_athwartship, beamwidth_alongship, beamwidth_athwartship - xr.DataArray with coordinates channel, ping_time: this is the case for sa_correction and gain_correction, which will be direct output of get_vend_cal_params_power() """ param = [] for ch_id in freq_center["channel"].values: # if frequency-dependent param exists as a data array with desired channel if ( da_param is not None and "cal_channel_id" in da_param.coords and ch_id in da_param["cal_channel_id"] ): # interp variable has ping_time dimension from freq_center param.append( da_param.sel(cal_channel_id=ch_id) .interp(cal_frequency=freq_center.sel(channel=ch_id)) .data ) # if no frequency-dependent param exists, use alternative else: BB_factor_ch = ( BB_factor.sel(channel=ch_id) if isinstance(BB_factor, xr.DataArray) else BB_factor ) if isinstance(alternative, xr.DataArray): alt = (alternative.sel(channel=ch_id) * BB_factor_ch).data.squeeze() elif isinstance(alternative, (int, float)): alt = ( np.array([alternative] * freq_center.sel(channel=ch_id).size).squeeze() * BB_factor_ch ) else: raise ValueError("'alternative' has to be of the type int, float, or xr.DataArray") if alt.size == 1 and "ping_time" in freq_center.coords: # expand to size of ping_time coordinate alt = np.array([alt] * freq_center.sel(channel=ch_id).size) param.append(alt) param = np.array(param) if "ping_time" in freq_center.coords: if len(param.shape) == 1: # this means param has only the channel but not the ping_time dim param = np.expand_dims(param, axis=1) return xr.DataArray( param, dims=["channel", "ping_time"], coords={"channel": freq_center["channel"], "ping_time": freq_center["ping_time"]}, ) else: return xr.DataArray(param, dims=["channel"], coords={"channel": freq_center["channel"]}) def get_vend_cal_params_power(beam: xr.Dataset, vend: xr.Dataset, param: str) -> xr.DataArray: """ Get cal parameters stored in the Vendor_specific group by matching the transmit_duration_nominal with allowable pulse_length. Parameters ---------- beam : xr.Dataset A subset of Sonar/Beam_groupX that contains only the channels specified for calibration vend : xr.Dataset A subset of Vendor_specific that contains only the channels specified for calibration param : str {"sa_correction", "gain_correction"} Name of parameter to retrieve Returns ------- An xr.DataArray containing the matched ``param`` """ # Check parameter is among those allowed if param not in ["sa_correction", "gain_correction"]: raise ValueError(f"Unknown parameter {param}") # Check parameter exists if param not in vend: raise ValueError(f"{param} does not exist in the Vendor_specific group!") # Find idx to select the corresponding param value # by matching beam["transmit_duration_nominal"] with ds_vend["pulse_length"] transmit_isnull = beam["transmit_duration_nominal"].isnull() idxmin = np.abs(beam["transmit_duration_nominal"] - vend["pulse_length"]).idxmin( dim="pulse_length_bin" ) # fill nan position with 0 (will remove before return) # and convert to int for indexing idxmin = idxmin.where(~transmit_isnull, 0).astype(int) # Get param dataarray into correct shape da_param = ( vend[param] .expand_dims(dim={"ping_time": idxmin["ping_time"]}) # expand dims for direct indexing .sortby(idxmin.channel) # sortby in case channel sequence differs in vend and beam ) # Select corresponding index and clean up the original nan elements da_param = da_param.sel(pulse_length_bin=idxmin, drop=True) # Set the nan elements back to nan. # Doing the `.where` will result in float64, # which is fine since we're dealing with nan da_param = da_param.where(~transmit_isnull, np.nan) # Clean up for leftover plb variable # if exists plb_var = "pulse_length_bin" if plb_var in da_param.coords: da_param = da_param.drop(plb_var) return da_param def get_cal_params_AZFP(beam: xr.DataArray, vend: xr.DataArray, user_dict: dict) -> dict: """ Get cal params using user inputs or values from data file. Parameters ---------- beam : xr.Dataset A subset of Sonar/Beam_groupX that contains only the channels to be calibrated vend : xr.Dataset A subset of Vendor_specific that contains only the channels to be calibrated user_dict : dict A dictionary containing user-defined calibration parameters. The user-defined calibration parameters will overwrite values in the data file. Returns ------- A dictionary containing the calibration parameters for the AZFP echosounder """ # Use sanitized user dict as blueprint # out_dict contains only and all of the allowable cal params out_dict = sanitize_user_cal_dict( user_dict=user_dict, channel=beam["channel"], sonar_type="AZFP" ) # Only fill in params that are None for p, v in out_dict.items(): if v is None: # Params from Sonar/Beam_group1 if p == "equivalent_beam_angle": out_dict[p] = beam[p] # has only channel dim # Params from Vendor_specific group elif p in ["EL", "DS", "TVR", "VTX", "Sv_offset"]: out_dict[p] = vend[p] # these params only have the channel dimension return out_dict def get_cal_params_EK( waveform_mode: Literal["CW", "BB"], freq_center: xr.DataArray, beam: xr.Dataset, vend: xr.Dataset, user_dict: Dict[str, Union[int, float, xr.DataArray]], default_params: Dict[str, Union[int, float]] = EK80_DEFAULT_PARAMS, sonar_type: str = "EK80", ) -> Dict: """ Get cal parameters from user input, data file, or a set of default values. Parameters ---------- waveform_mode : str Transmit waveform mode, either "CW" or "BB" freq_center : xr.DataArray Center frequency (BB mode) or nominal frequency (CW mode) beam : xr.Dataset A subset of Sonar/Beam_groupX that contains only the channels to be calibrated vend : xr.Dataset A subset of Vendor_specific that contains only the channels to be calibrated user_dict : dict A dictionary containing user-defined parameters. User-defined parameters take precedance over values in the data file or in default dict. default_params : dict A dictionary containing default parameters sonar_type : str Type of EK sonar, either "EK60" or "EK80" """ if not isinstance(waveform_mode, str): raise TypeError("waveform_mode is not type string") elif waveform_mode not in ["CW", "BB"]: raise ValueError("waveform_mode must be 'CW' or 'BB'") # Private function to get fs def _get_fs(): # If receiver_sampling_frequency recorded, use it if "receiver_sampling_frequency" in vend: return vend["receiver_sampling_frequency"] else: # If receiver_sampling_frequency not recorded, use default value # loop through channel since transceiver can vary fs = [] for ch in vend["channel"]: tcvr_type = vend["transceiver_type"].sel(channel=ch).data.tolist().upper() fs.append(default_params["receiver_sampling_frequency"][tcvr_type]) return xr.DataArray(fs, dims=["channel"], coords={"channel": vend["channel"]}) # Mapping between desired param name with Beam group data variable name PARAM_BEAM_NAME_MAP = { "angle_offset_alongship": "angle_offset_alongship", "angle_offset_athwartship": "angle_offset_athwartship", "angle_sensitivity_alongship": "angle_sensitivity_alongship", "angle_sensitivity_athwartship": "angle_sensitivity_athwartship", "beamwidth_alongship": "beamwidth_twoway_alongship", "beamwidth_athwartship": "beamwidth_twoway_athwartship", "equivalent_beam_angle": "equivalent_beam_angle", } if waveform_mode == "BB": # for BB data equivalent_beam_angle needs to be scaled wrt freq_center PARAM_BEAM_NAME_MAP.pop("equivalent_beam_angle") # Use sanitized user dict as blueprint # out_dict contains only and all of the allowable cal params out_dict = sanitize_user_cal_dict( user_dict=user_dict, channel=beam["channel"], sonar_type=sonar_type ) # Interpolate user-input params that contain freq-dependent info # ie those that has coordinate combination (cal_channel_id, cal_frequency) # TODO: this will need to change for computing frequency-dependent TS for p, v in out_dict.items(): if v is not None: if "cal_channel_id" in v.coords: out_dict[p] = _get_interp_da(v, freq_center, np.nan) # Only fill in params that are None for p, v in out_dict.items(): if v is None: # Those without CW or BB complications if p == "sa_correction": # pull from data file out_dict[p] = get_vend_cal_params_power(beam=beam, vend=vend, param=p) elif p == "impedance_transceiver": # from data file or default dict out_dict[p] = default_params[p] if p not in vend else vend["impedance_transceiver"] elif p == "receiver_sampling_frequency": # from data file or default_params out_dict[p] = _get_fs() else: # CW: params do not require interpolation, except for impedance_transducer if waveform_mode == "CW": if p in PARAM_BEAM_NAME_MAP.keys(): # pull from data file, these should always exist out_dict[p] = beam[PARAM_BEAM_NAME_MAP[p]] elif p == "gain_correction": # pull from data file narrowband table out_dict[p] = get_vend_cal_params_power(beam=beam, vend=vend, param=p) elif p == "impedance_transducer": # assemble each channel from data file or default dict out_dict[p] = _get_interp_da( da_param=None if p not in vend else vend[p], freq_center=freq_center, alternative=default_params[p], # pull from default dict ) else: raise ValueError(f"{p} not in the defined set of calibration parameters.") # BB mode: params require interpolation else: # interpolate for center frequency or use CW values if p in PARAM_BEAM_NAME_MAP.keys(): # only scale these params if alternative is used if p in [ "angle_sensitivity_alongship", "angle_sensitivity_athwartship", ]: BB_factor = freq_center / beam["frequency_nominal"] elif p in [ "beamwidth_alongship", "beamwidth_athwartship", ]: BB_factor = beam["frequency_nominal"] / freq_center else: BB_factor = 1 p_beam = PARAM_BEAM_NAME_MAP[p] # Beam_groupX data variable name out_dict[p] = _get_interp_da( da_param=None if p not in vend else vend[p], freq_center=freq_center, alternative=beam[p_beam], # these should always exist BB_factor=BB_factor, ) elif p == "equivalent_beam_angle": # scaled according to frequency ratio out_dict[p] = beam[p] + 20 * np.log10( beam["frequency_nominal"] / freq_center ) elif p == "gain_correction": # interpolate or pull from narrowband table out_dict[p] = _get_interp_da( da_param=None if "gain" not in vend else vend["gain"], # freq-dep values freq_center=freq_center, alternative=get_vend_cal_params_power(beam=beam, vend=vend, param=p), ) elif p == "impedance_transducer": out_dict[p] = _get_interp_da( da_param=None if p not in vend else vend[p], freq_center=freq_center, alternative=default_params[p], # pull from default dict ) else: raise ValueError(f"{p} not in the defined set of calibration parameters.") return out_dict
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,822
OSOceanAcoustics/echopype
refs/heads/main
/echopype/calibrate/calibrate_base.py
import abc from ..echodata import EchoData from ..utils.log import _init_logger from .ecs import ECSParser logger = _init_logger(__name__) class CalibrateBase(abc.ABC): """Class to handle calibration for all sonar models.""" def __init__(self, echodata: EchoData, env_params=None, cal_params=None, ecs_file=None): self.echodata = echodata self.sonar_type = None self.ecs_file = ecs_file self.ecs_dict = {} # Set ECS to overwrite user-provided dict if self.ecs_file is not None: if env_params is not None or cal_params is not None: logger.warning( "The ECS file takes precedence when it is provided. " "Parameter values provided in 'env_params' and 'cal_params' will not be used!" ) # Parse ECS file to a dict ecs = ECSParser(self.ecs_file) ecs.parse() self.ecs_dict = ecs.get_cal_params() # apply ECS hierarchy self.env_params = {} self.cal_params = {} else: if env_params is None: self.env_params = {} elif isinstance(env_params, dict): self.env_params = env_params else: raise ValueError("'env_params' has to be None or a dict") if cal_params is None: self.cal_params = {} elif isinstance(cal_params, dict): self.cal_params = cal_params else: raise ValueError("'cal_params' has to be None or a dict") # range_meter is computed in compute_Sv/TS in child class self.range_meter = None @abc.abstractmethod def compute_echo_range(self, **kwargs): """Calculate range (``echo_range``) in units meter. Returns ------- range_meter : xr.DataArray range in units meter """ pass @abc.abstractmethod def _cal_power_samples(self, cal_type, **kwargs): """Calibrate power data for EK60, EK80, and AZFP. Parameters ---------- cal_type : str 'Sv' for calculating volume backscattering strength, or 'TS' for calculating target strength """ pass @abc.abstractmethod def compute_Sv(self, **kwargs): pass @abc.abstractmethod def compute_TS(self, **kwargs): pass def _add_params_to_output(self, ds_out): """Add all cal and env parameters to output Sv dataset.""" # Add env_params for key, val in self.env_params.items(): ds_out[key] = val # Add cal_params for key, val in self.cal_params.items(): ds_out[key] = val return ds_out
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,823
OSOceanAcoustics/echopype
refs/heads/main
/echopype/commongrid/nasc.py
""" An overhaul is required for the below compute_NASC implementation, to: - increase the computational efficiency - debug the current code of any discrepancy against Echoview implementation - potentially provide an alternative based on ping-by-ping Sv This script contains functions used by commongrid.compute_NASC, but a subset of these overlap with operations needed for commongrid.compute_MVBS and clean.estimate_noise. The compute_MVBS and remove_noise code needs to be refactored, and the compute_NASC needs to be optimized. The plan is to create a common util set of functions for use in these functions in an upcoming release. """ import numpy as np import xarray as xr from geopy import distance def check_identical_depth(ds_ch): """ Check if all pings have the same depth vector. """ # Depth vector are identical for all pings, if: # - the number of non-NaN range_sample is the same for all pings, AND # - all pings have the same max range num_nan = np.isnan(ds_ch.values).sum(axis=1) nan_check = True if np.all(num_nan == 0) or np.unique(num_nan).size == 1 else False if not nan_check: return xr.DataArray(False, coords={"channel": ds_ch["channel"]}) else: # max range of each ping should be identical max_range_ping = ds_ch.values[np.arange(ds_ch.shape[0]), ds_ch.shape[1] - num_nan - 1] if np.unique(max_range_ping).size == 1: return xr.DataArray(True, coords={"channel": ds_ch["channel"]}) else: return xr.DataArray(False, coords={"channel": ds_ch["channel"]}) def get_depth_bin_info(ds_Sv, cell_depth): """ Find binning indices along depth """ depth_ping1 = ds_Sv["depth"].isel(ping_time=0) num_nan = np.isnan(depth_ping1.values).sum(axis=1) # ping 1 max range of each channel max_range_ch = depth_ping1.values[ np.arange(depth_ping1.shape[0]), depth_ping1.shape[1] - num_nan - 1 ] bin_num_depth = np.ceil(max_range_ch.max() / cell_depth) # use max range of all channel depth_bin_idx = [ np.digitize(dp1, np.arange(bin_num_depth + 1) * cell_depth, right=False) for dp1 in depth_ping1 ] return bin_num_depth, depth_bin_idx def get_distance_from_latlon(ds_Sv): # Get distance from lat/lon in nautical miles df_pos = ds_Sv["latitude"].to_dataframe().join(ds_Sv["longitude"].to_dataframe()) df_pos["latitude_prev"] = df_pos["latitude"].shift(-1) df_pos["longitude_prev"] = df_pos["longitude"].shift(-1) df_latlon_nonan = df_pos.dropna().copy() df_latlon_nonan["dist"] = df_latlon_nonan.apply( lambda x: distance.distance( (x["latitude"], x["longitude"]), (x["latitude_prev"], x["longitude_prev"]), ).nm, axis=1, ) df_pos = df_pos.join(df_latlon_nonan["dist"], how="left") df_pos["dist"] = df_pos["dist"].cumsum() df_pos["dist"] = df_pos["dist"].fillna(method="ffill").fillna(method="bfill") return df_pos["dist"].values def get_dist_bin_info(dist_nmi, cell_dist): bin_num_dist = np.ceil(dist_nmi.max() / cell_dist) if np.mod(dist_nmi.max(), cell_dist) == 0: # increment bin num if last element coincides with bin edge bin_num_dist = bin_num_dist + 1 dist_bin_idx = np.digitize(dist_nmi, np.arange(bin_num_dist + 1) * cell_dist, right=False) return bin_num_dist, dist_bin_idx
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,824
OSOceanAcoustics/echopype
refs/heads/main
/echopype/echodata/echodata.py
import datetime import shutil import warnings from html import escape from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Tuple, Union import fsspec import numpy as np import xarray as xr from datatree import DataTree, open_datatree from zarr.errors import GroupNotFoundError, PathNotFoundError if TYPE_CHECKING: from ..core import EngineHint, FileFormatHint, PathHint, SonarModelsHint from ..utils.coding import sanitize_dtypes, set_time_encodings from ..utils.io import check_file_existence, sanitize_file_path from ..utils.log import _init_logger from ..utils.prov import add_processing_level from .convention import sonarnetcdf_1 from .sensor_ep_version_mapping import ep_version_mapper from .widgets.utils import tree_repr from .widgets.widgets import _load_static_files, get_template XARRAY_ENGINE_MAP: Dict["FileFormatHint", "EngineHint"] = { ".nc": "netcdf4", ".zarr": "zarr", } TVG_CORRECTION_FACTOR = { "EK60": 2, "ES70": 2, "EK80": 0, "ES80": 0, "EA640": 0, } logger = _init_logger(__name__) class EchoData: """Echo data model class for handling raw converted data, including multiple files associated with the same data set. """ group_map: Dict[str, Any] = sonarnetcdf_1.yaml_dict["groups"] def __init__( self, converted_raw_path: Optional["PathHint"] = None, storage_options: Optional[Dict[str, Any]] = None, source_file: Optional["PathHint"] = None, xml_path: Optional["PathHint"] = None, sonar_model: Optional["SonarModelsHint"] = None, open_kwargs: Optional[Dict[str, Any]] = None, parsed2zarr_obj=None, ): # TODO: consider if should open datasets in init # or within each function call when echodata is used. Need to benchmark. self.storage_options: Dict[str, Any] = ( storage_options if storage_options is not None else {} ) self.open_kwargs: Dict[str, Any] = open_kwargs if open_kwargs is not None else {} self.source_file: Optional["PathHint"] = source_file self.xml_path: Optional["PathHint"] = xml_path self.sonar_model: Optional["SonarModelsHint"] = sonar_model self.converted_raw_path: Optional["PathHint"] = converted_raw_path self._tree: Optional["DataTree"] = None # object associated with directly writing to a zarr file self.parsed2zarr_obj = parsed2zarr_obj self.__setup_groups() # self.__read_converted(converted_raw_path) self._varattrs = sonarnetcdf_1.yaml_dict["variable_and_varattributes"] def __del__(self): # TODO: this destructor seems to not work in Jupyter Lab if restart or # even clear all outputs is used. It will work if you explicitly delete the object if (self.parsed2zarr_obj is not None) and (self.parsed2zarr_obj.zarr_file_name is not None): # get Path object of temporary zarr file created by Parsed2Zarr p2z_temp_file = Path(self.parsed2zarr_obj.zarr_file_name) # remove temporary directory created by Parsed2Zarr, if it exists if p2z_temp_file.exists(): # TODO: do we need to check file permissions here? shutil.rmtree(p2z_temp_file) def __str__(self) -> str: fpath = "Internal Memory" if self.converted_raw_path: fpath = self.converted_raw_path repr_str = "No data found." if self._tree is not None: repr_str = tree_repr(self._tree) return f"<EchoData: standardized raw data from {fpath}>\n{repr_str}" def __repr__(self) -> str: return str(self) def _repr_html_(self) -> str: """Make html representation of InferenceData object.""" _, css_style = _load_static_files() try: from xarray.core.options import OPTIONS display_style = OPTIONS["display_style"] if display_style == "text": html_repr = f"<pre>{escape(repr(self))}</pre>" else: return get_template("echodata.html.j2").render(echodata=self, css_style=css_style) except: # noqa html_repr = f"<pre>{escape(repr(self))}</pre>" return html_repr def __setup_groups(self): for group in self.group_map.keys(): setattr(self, group, None) def __read_converted(self, converted_raw_path: Optional["PathHint"]): if converted_raw_path is not None: self._check_path(converted_raw_path) converted_raw_path = self._sanitize_path(converted_raw_path) self._load_file(converted_raw_path) if isinstance(converted_raw_path, fsspec.FSMap): # Convert fsmap to Path so it can be used # for retrieving the path strings converted_raw_path = Path(converted_raw_path.root) self.converted_raw_path = converted_raw_path def _set_tree(self, tree: DataTree): self._tree = tree @classmethod def from_file( cls, converted_raw_path: str, storage_options: Optional[Dict[str, Any]] = None, open_kwargs: Dict[str, Any] = {}, ) -> "EchoData": echodata = cls( converted_raw_path=converted_raw_path, storage_options=storage_options, open_kwargs=open_kwargs, ) echodata._check_path(converted_raw_path) converted_raw_path = echodata._sanitize_path(converted_raw_path) suffix = echodata._check_suffix(converted_raw_path) tree = open_datatree( converted_raw_path, engine=XARRAY_ENGINE_MAP[suffix], **echodata.open_kwargs, ) tree.name = "root" echodata._set_tree(tree) # convert to newest echopype version structure, if necessary ep_version_mapper.map_ep_version(echodata) if isinstance(converted_raw_path, fsspec.FSMap): # Convert fsmap to Path so it can be used # for retrieving the path strings converted_raw_path = Path(converted_raw_path.root) echodata.converted_raw_path = converted_raw_path echodata._load_tree() return echodata def _load_tree(self) -> None: if self._tree is None: raise ValueError("Datatree not found!") for group, value in self.group_map.items(): # EK80 data may have a Beam_power group if both complex and power data exist. ds = None try: if value["ep_group"] is None: node = self._tree else: node = self._tree[value["ep_group"]] ds = self.__get_dataset(node) except KeyError: # Skips group not found errors for EK80 and ADCP ... if group == "top" and hasattr(ds, "keywords"): self.sonar_model = ds.keywords.upper() # type: ignore if isinstance(ds, xr.Dataset): setattr(self, group, node) @property def version_info(self) -> Union[Tuple[int], None]: def _get_version_tuple(provenance_type): """ Parameters ---------- provenance_type : str Either conversion or combination """ version_str = self["Provenance"].attrs.get(f"{provenance_type}_software_version", None) if version_str is not None: if version_str.startswith("v"): # Removes v in case of v0.4.x or less version_str = version_str.strip("v") version_num = version_str.split(".")[:3] return tuple([int(i) for i in version_num]) if self["Provenance"].attrs.get("combination_software_name", None) == "echopype": return _get_version_tuple("combination") elif self["Provenance"].attrs.get("conversion_software_name", None) == "echopype": return _get_version_tuple("conversion") else: return None @property def nbytes(self) -> float: return float(sum(self[p].nbytes for p in self.group_paths)) @property def group_paths(self) -> Set[str]: return tuple(i[1:] if i != "/" else "Top-level" for i in self._tree.groups) @staticmethod def __get_dataset(node: DataTree) -> Optional[xr.Dataset]: if node.has_data or node.has_attrs: # validate and clean dtypes return sanitize_dtypes(node.ds) return None def __get_node(self, key: Optional[str]) -> DataTree: if key in ["Top-level", "/"]: # Access to root return self._tree return self._tree[key] def __getitem__(self, __key: Optional[str]) -> Optional[xr.Dataset]: if self._tree: try: node = self.__get_node(__key) return self.__get_dataset(node) except KeyError: return None else: raise ValueError("Datatree not found!") def __setitem__(self, __key: Optional[str], __newvalue: Any) -> Optional[xr.Dataset]: if self._tree: try: node = self.__get_node(__key) node.ds = __newvalue return self.__get_dataset(node) except KeyError: raise GroupNotFoundError(__key) else: raise ValueError("Datatree not found!") def __setattr__(self, __name: str, __value: Any) -> None: attr_value = __value if isinstance(__value, DataTree) and __name != "_tree": attr_value = self.__get_dataset(__value) elif isinstance(__value, xr.Dataset): group_map = sonarnetcdf_1.yaml_dict["groups"] if __name in group_map: group = group_map.get(__name) group_path = group["ep_group"] if self._tree: if __name == "top": self._tree.ds = __value else: self._tree[group_path].ds = __value super().__setattr__(__name, attr_value) @add_processing_level("L1A") def update_platform( self, extra_platform_data: xr.Dataset, variable_mappings=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_data : xr.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 >>> ) """ # Handle data stored as a CF Trajectory Discrete Sampling Geometry # http://cfconventions.org/Data/cf-conventions/cf-conventions-1.8/cf-conventions.html#trajectory-data # The Saildrone sample data file follows this convention if ( "featureType" in extra_platform_data.attrs and extra_platform_data.attrs["featureType"].lower() == "trajectory" ): for coordvar in extra_platform_data.coords: coordvar_attrs = extra_platform_data[coordvar].attrs if "cf_role" in coordvar_attrs and coordvar_attrs["cf_role"] == "trajectory_id": trajectory_var = coordvar if "standard_name" in coordvar_attrs and coordvar_attrs["standard_name"] == "time": time_dim = coordvar # assumes there's only one trajectory in the dataset (index 0) extra_platform_data = extra_platform_data.sel( {trajectory_var: extra_platform_data[trajectory_var][0]} ) extra_platform_data = extra_platform_data.drop_vars(trajectory_var) obs_dim = list(extra_platform_data[time_dim].dims)[0] extra_platform_data = extra_platform_data.swap_dims({obs_dim: time_dim}) def _extvar_properties(ds, name): """Test the external variable for presence and all-nan values, and extract its time dimension name. Returns <presence>, <valid values>, <time dim name> """ if name in ds: # Assumes the only dimension in the variable is a time dimension time_dim_name = ds[name].dims[0] if len(ds[name].dims) > 0 else "scalar" if not ds[name].isnull().all(): return True, True, time_dim_name else: return True, False, time_dim_name else: return False, False, None # clip incoming time to 1 less than min of EchoData["Sonar/Beam_group1"]["ping_time"] and # 1 greater than max of EchoData["Sonar/Beam_group1"]["ping_time"] # account for unsorted external time by checking whether each time value is between # min and max ping_time instead of finding the 2 external times corresponding to the # min and max ping_time and taking all the times between those indices def _clip_by_time_dim(external_ds, ext_time_dim_name): # external_ds is extra_platform_data[vars-list-on-time_dim_name] sorted_external_time = external_ds[ext_time_dim_name].data sorted_external_time.sort() # fmt: off min_index = max( np.searchsorted( sorted_external_time, self["Sonar/Beam_group1"]["ping_time"].min(), side="left" ) - 1, 0, ) # fmt: on max_index = min( np.searchsorted( sorted_external_time, self["Sonar/Beam_group1"]["ping_time"].max(), side="right", ), len(sorted_external_time) - 1, ) # TODO: this element-wise comparison is expensive and seems an ad-hoc patch # to deal with potentially reversed timestamps in the external dataset. # Review at workflow stage to see if to clean up timestamp reversals # and just find start/end timestamp for slicing. return external_ds.sel( { ext_time_dim_name: np.logical_and( sorted_external_time[min_index] <= external_ds[ext_time_dim_name], external_ds[ext_time_dim_name] <= sorted_external_time[max_index], ) } ) # History attribute to be included in each updated variable history_attr = f"{datetime.datetime.utcnow()} +00:00. Added from external platform data" if extra_platform_data_file_name: history_attr += ", from file " + extra_platform_data_file_name platform = self["Platform"] # Retain only variable_mappings items where # either the Platform group or extra_platform_data # contain the corresponding variables or contain valid (not all nan) data mappings_expanded = {} for platform_var, external_var in variable_mappings.items(): # TODO: instead of using existing Platform group variables, a better practice is to # define a set of allowable Platform variables (sonar_model dependent) for this check. # This set can be dynamically generated from an external source like a CDL or yaml. if platform_var in platform: platform_validvalues = not platform[platform_var].isnull().all() ext_present, ext_validvalues, ext_time_dim_name = _extvar_properties( extra_platform_data, external_var ) if ext_present and ext_validvalues: mappings_expanded[platform_var] = dict( external_var=external_var, ext_time_dim_name=ext_time_dim_name, platform_validvalues=platform_validvalues, ) # Generate warning if mappings_expanded is empty if not mappings_expanded: logger.warning( "No variables will be updated, " "check variable_mappings to ensure variable names are correctly specified!" ) # If longitude or latitude are requested, verify that both are present # and they share the same external time dimension if "longitude" in mappings_expanded or "latitude" in mappings_expanded: if "longitude" not in mappings_expanded or "latitude" not in mappings_expanded: raise ValueError( "Only one of latitude and longitude are specified. Please include both, or neither." # noqa ) if ( mappings_expanded["longitude"]["ext_time_dim_name"] != mappings_expanded["latitude"]["ext_time_dim_name"] ): raise ValueError( "The external latitude and longitude use different time dimensions. " "They must share the same time dimension." ) # Generate warnings regarding variables that will be updated vars_not_handled = set(variable_mappings.keys()).difference(mappings_expanded.keys()) if len(vars_not_handled) > 0: logger.warning( f"The following requested variables will not be updated: {', '.join(vars_not_handled)}" # noqa ) vars_notnan_replaced = [ platform_var for platform_var, v in mappings_expanded.items() if v["platform_validvalues"] ] if len(vars_notnan_replaced) > 0: logger.warning( f"Some variables with valid data in the original Platform group will be overwritten: {', '.join(vars_notnan_replaced)}" # noqa ) # Create names for required new time dimensions ext_time_dims = list( { v["ext_time_dim_name"] for v in mappings_expanded.values() if v["ext_time_dim_name"] != "scalar" } ) time_dims_max = max([int(dim[-1]) for dim in platform.dims if dim.startswith("time")]) new_time_dims = [f"time{time_dims_max+i+1}" for i in range(len(ext_time_dims))] # Map each new time dim name to the external time dim name: new_time_dims_mappings = {new: ext for new, ext in zip(new_time_dims, ext_time_dims)} # Process variable updates by corresponding new time dimensions for time_dim in new_time_dims: ext_time_dim = new_time_dims_mappings[time_dim] mappings_selected = { k: v for k, v in mappings_expanded.items() if v["ext_time_dim_name"] == ext_time_dim } ext_vars = [v["external_var"] for v in mappings_selected.values()] ext_ds = _clip_by_time_dim(extra_platform_data[ext_vars], ext_time_dim) # Create new time coordinate and dimension platform = platform.assign_coords(**{time_dim: ext_ds[ext_time_dim].values}) time_attrs = { "axis": "T", "standard_name": "time", "long_name": "Timestamps from an external dataset", "comment": "Time coordinate originated from a dataset " "external to the sonar data files.", "history": f"{history_attr}. From external {ext_time_dim} variable.", } platform[time_dim] = platform[time_dim].assign_attrs(**time_attrs) # Process each platform variable that will be replaced for platform_var in mappings_selected.keys(): ext_var = mappings_expanded[platform_var]["external_var"] platform_var_attrs = platform[platform_var].attrs.copy() # Create new (replaced) variable using dataset "update" # With update, dropping the variable first is not needed platform = platform.update({platform_var: (time_dim, ext_ds[ext_var].data)}) # Assign attributes to newly created (replaced) variables var_attrs = platform_var_attrs var_attrs["history"] = f"{history_attr}. From external {ext_var} variable." platform[platform_var] = platform[platform_var].assign_attrs(**var_attrs) # Update scalar variables, if any scalar_vars = [ platform_var for platform_var, v in mappings_expanded.items() if v["ext_time_dim_name"] == "scalar" ] for platform_var in scalar_vars: ext_var = mappings_expanded[platform_var]["external_var"] # Replace the scalar value and add a history attribute platform[platform_var].data = float(extra_platform_data[ext_var].data) platform[platform_var] = platform[platform_var].assign_attrs( **{"history": f"{history_attr}. From external {ext_var} variable."} ) # Drop pre-existing time dimensions that are no longer being used used_dims = { platform[platform_var].dims[0] for platform_var in platform.data_vars if len(platform[platform_var].dims) > 0 } platform = platform.drop_dims(set(platform.dims).difference(used_dims), errors="ignore") self["Platform"] = set_time_encodings(platform) @classmethod def _load_convert(cls, convert_obj): new_cls = cls() for group in new_cls.group_map.keys(): if hasattr(convert_obj, group): setattr(new_cls, group, getattr(convert_obj, group)) setattr(new_cls, "sonar_model", getattr(convert_obj, "sonar_model")) setattr(new_cls, "source_file", getattr(convert_obj, "source_file")) return new_cls def _load_file(self, raw_path: "PathHint"): """Lazy load all groups and subgroups from raw file.""" for group, value in self.group_map.items(): # EK80 data may have a Beam_power group if both complex and power data exist. ds = None try: ds = self._load_group( raw_path, group=value["ep_group"], ) except (OSError, GroupNotFoundError, PathNotFoundError): # Skips group not found errors for EK80 and ADCP ... if group == "top" and hasattr(ds, "keywords"): self.sonar_model = ds.keywords.upper() # type: ignore if isinstance(ds, xr.Dataset): setattr(self, group, ds) def _check_path(self, filepath: "PathHint"): """Check if converted_raw_path exists""" file_exists = check_file_existence(filepath, self.storage_options) if not file_exists: raise FileNotFoundError(f"There is no file named {filepath}") def _sanitize_path(self, filepath: "PathHint") -> "PathHint": filepath = sanitize_file_path(filepath, self.storage_options) return filepath def _check_suffix(self, filepath: "PathHint") -> "FileFormatHint": """Check if file type is supported.""" # TODO: handle multiple files through the same set of checks for combining files if isinstance(filepath, fsspec.FSMap): suffix = Path(filepath.root).suffix else: suffix = Path(filepath).suffix if suffix not in XARRAY_ENGINE_MAP: raise ValueError("Input file type not supported!") return suffix # type: ignore def _load_group(self, filepath: "PathHint", group: Optional[str] = None): """Loads each echodata group""" suffix = self._check_suffix(filepath) return xr.open_dataset( filepath, group=group, engine=XARRAY_ENGINE_MAP[suffix], **self.open_kwargs, ) def to_netcdf( self, save_path: Optional["PathHint"] = 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_path : str path that converted .nc file will be saved compress : bool whether or not to perform compression on data variables Defaults to ``True`` overwrite : bool whether or not to overwrite existing files Defaults to ``False`` parallel : bool whether or not to use parallel processing. (Not yet implemented) output_storage_options : dict Additional keywords to pass to the filesystem class. **kwargs : dict, optional Extra arguments to `xr.Dataset.to_netcdf`: refer to xarray's documentation for a list of all possible arguments. """ from ..convert.api import to_file return to_file( echodata=self, engine="netcdf4", save_path=save_path, compress=compress, overwrite=overwrite, parallel=parallel, output_storage_options=output_storage_options, **kwargs, ) def to_zarr( self, save_path: Optional["PathHint"] = None, compress: bool = True, overwrite: bool = False, parallel: bool = False, output_storage_options: Dict[str, str] = {}, consolidated: bool = True, **kwargs, ): """Save content of EchoData to zarr. Parameters ---------- save_path : str path that converted .nc file will be saved compress : bool whether or not to perform compression on data variables Defaults to ``True`` overwrite : bool whether or not to overwrite existing files Defaults to ``False`` parallel : bool whether or not to use parallel processing. (Not yet implemented) output_storage_options : dict Additional keywords to pass to the filesystem class. consolidated : bool Flag to consolidate zarr metadata. Defaults to ``True`` **kwargs : dict, optional Extra arguments to `xr.Dataset.to_zarr`: refer to xarray's documentation for a list of all possible arguments. """ from ..convert.api import to_file return to_file( echodata=self, engine="zarr", save_path=save_path, compress=compress, overwrite=overwrite, parallel=parallel, output_storage_options=output_storage_options, consolidated=consolidated, **kwargs, ) # TODO: Remove below in future versions. They are for supporting old API calls. @property def nc_path(self) -> Optional["PathHint"]: warnings.warn( "`nc_path` is deprecated, Use `converted_raw_path` instead.", DeprecationWarning, 2, ) if self.converted_raw_path.endswith(".nc"): return self.converted_raw_path else: path = Path(self.converted_raw_path) return str(path.parent / (path.stem + ".nc")) @property def zarr_path(self) -> Optional["PathHint"]: warnings.warn( "`zarr_path` is deprecated, Use `converted_raw_path` instead.", DeprecationWarning, 2, ) if self.converted_raw_path.endswith(".zarr"): return self.converted_raw_path else: path = Path(self.converted_raw_path) return str(path.parent / (path.stem + ".zarr"))
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,825
OSOceanAcoustics/echopype
refs/heads/main
/echopype/visualize/api.py
from typing import Optional, Union, List, Type import xarray as xr from .plot import _plot_echogram, FacetGrid, QuadMesh from ..echodata import EchoData from ..calibrate.calibrate_ek import CalibrateEK60, CalibrateEK80 from ..calibrate.calibrate_azfp import CalibrateAZFP from ..utils.log import _init_logger logger = _init_logger(__name__) def create_echogram( data: Union[EchoData, xr.Dataset], channel: Union[str, List[str], None] = None, frequency: Union[str, List[str], None] = None, get_range: Optional[bool] = None, range_kwargs: dict = {}, vertical_offset: Union[int, float, xr.DataArray, bool, None] = None, **kwargs, ) -> List[Union[FacetGrid, QuadMesh]]: """Create an Echogram from an EchoData object or Sv and MVBS Dataset. Parameters ---------- data : EchoData or xr.Dataset Echodata or Xarray Dataset to be plotted channel : str or list of str, optional The channel to be plotted. Otherwise all channels will be plotted. frequency : int, float, or list of float or ints, optional The frequency to be plotted. If not specified, all frequency will be plotted. get_range : bool, optional Flag as to whether range (``echo_range``) should be computed or not, by default it will just plot `range_sample`` as the yaxis. Note that for data that is "Sv" xarray dataset, `get_range` defaults to `True`. range_kwargs : dict Keyword arguments dictionary for computing range (``echo_range``). Keys are `env_params`, `waveform_mode`, and `encode_mode`. vertical_offset : int, float, xr.DataArray, or bool, optional Water level data array for platform water level correction. Note that auto addition of water level can be performed when data is an EchoData object by setting this argument to `True`. Currently because the water level information is not available as part of the Sv dataset, a warning is issued when `vertical_offset=True` in this case and no correction is performed. This behavior will change in the future when the default content of Sv dataset is updated to include this information. **kwargs: optional Additional keyword arguments for xarray plot pcolormesh. Notes ----- The EK80 echosounder can be configured to transmit either broadband (``waveform_mode="BB"``) 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. """ range_attrs = { 'long_name': 'Range', 'units': 'm', } if channel and frequency: logger.warning( "Both channel and frequency are specified. Channel filtering will be used." ) if isinstance(channel, list) and len(channel) == 1: channel = channel[0] elif isinstance(frequency, list) and len(frequency) == 1: frequency = frequency[0] if isinstance(data, EchoData): if data.sonar_model.lower() == 'ad2cp': raise ValueError( "Visualization for AD2CP sonar model is currently unsupported." ) yaxis = 'range_sample' variable = 'backscatter_r' ds = data["Sonar/Beam_group1"] if 'ping_time' in ds: _check_ping_time(ds.ping_time) if get_range is True: yaxis = 'echo_range' if data.sonar_model.lower() == 'azfp': if 'azfp_cal_type' not in range_kwargs: range_kwargs['azfp_cal_type'] = 'Sv' if 'env_params' not in range_kwargs: raise ValueError( "Please provide env_params in range_kwargs!" ) elif data.sonar_model.lower() == 'ek60': if 'waveform_mode' not in range_kwargs: range_kwargs['waveform_mode'] = 'CW' elif range_kwargs['waveform_mode'] != 'CW': raise ValueError( f"waveform_mode {range_kwargs['waveform_mode']} is invalid. EK60 waveform_mode must be 'CW'." # noqa ) if 'encode_mode' not in range_kwargs: range_kwargs['encode_mode'] = 'power' elif range_kwargs['encode_mode'] != 'power': raise ValueError( f"encode_mode {range_kwargs['encode_mode']} is invalid. EK60 encode_mode must be 'power'." # noqa ) elif data.sonar_model.lower() == 'ek80': if not all( True if mode in range_kwargs else False for mode in ['waveform_mode', 'encode_mode'] ): raise ValueError( "Please provide waveform_mode and encode_mode in range_kwargs for EK80 sonar model." # noqa ) waveform_mode = range_kwargs['waveform_mode'] encode_mode = range_kwargs['encode_mode'] if waveform_mode not in ("BB", "CW"): raise ValueError( f"waveform_mode {waveform_mode} is invalid. EK80 waveform_mode must be 'BB' or 'CW'." # noqa ) elif encode_mode not in ("complex", "power"): raise ValueError( f"encode_mode {encode_mode} is invalid. EK80 waveform_mode must be 'complex' or 'power'." # noqa ) elif waveform_mode == "BB" and encode_mode == "power": raise ValueError( "Data from broadband ('BB') transmission must be recorded as complex samples" # noqa ) # Compute range via calibration objects if data.sonar_model == "AZFP": cal_obj = CalibrateAZFP( echodata=data, env_params=range_kwargs.get("env_params", {}), cal_params=None, waveform_mode=None, encode_mode=None, ) if range_kwargs["azfp_cal_type"] is None: raise ValueError("azfp_cal_type must be specified when sonar_model is AZFP") cal_obj.compute_echo_range(cal_type=range_kwargs["azfp_cal_type"]) elif data.sonar_model in ("EK60", "EK80", "ES70", "ES80", "EA640"): if data.sonar_model in ["EK60", "ES70"]: cal_obj = CalibrateEK60( echodata=data, env_params=range_kwargs.get("env_params", {}), cal_params=None, ecs_file=None, ) else: cal_obj = CalibrateEK80( echodata=data, env_params=range_kwargs.get("env_params", {}), cal_params=None, ecs_file=None, waveform_mode=range_kwargs.get("waveform_mode", "CW"), encode_mode=range_kwargs.get("encode_mode", "power"), ) range_in_meter = cal_obj.range_meter range_in_meter.attrs = range_attrs if vertical_offset is not None: range_in_meter = _add_vertical_offset( range_in_meter=range_in_meter, vertical_offset=vertical_offset, data_type=EchoData, platform_data=data["Platform"], ) ds = ds.assign_coords({'echo_range': range_in_meter}) ds.echo_range.attrs = range_attrs elif isinstance(data, xr.Dataset): if 'ping_time' in data: _check_ping_time(data.ping_time) variable = 'Sv' ds = data yaxis = 'echo_range' if 'echo_range' not in data.dims and get_range is False: # Range in dims indicates that data is MVBS. yaxis = 'range_sample' # If depth is available in ds, use it. ds = ds.set_coords('echo_range') if vertical_offset is not None: ds['echo_range'] = _add_vertical_offset( range_in_meter=ds.echo_range, vertical_offset=vertical_offset, data_type=xr.Dataset, ) ds.echo_range.attrs = range_attrs else: raise ValueError(f"Unsupported data type: {type(data)}") return _plot_echogram( ds, xaxis='ping_time', yaxis=yaxis, variable=variable, channel=channel, frequency=frequency, **kwargs, ) def _check_ping_time(ping_time): if ping_time.shape[0] < 2: raise ValueError("Ping time must have a length that is greater or equal to 2") def _add_vertical_offset( range_in_meter: xr.DataArray, vertical_offset: Union[int, float, xr.DataArray, bool], data_type: Union[Type[xr.Dataset], Type[EchoData]], platform_data: Optional[xr.Dataset] = None, ) -> xr.DataArray: # Below, we rename time2 to ping_time because range_in_meter is in ping_time if isinstance(vertical_offset, bool): if vertical_offset is True: if data_type == xr.Dataset: logger.warning( "Boolean type found for vertical_offset. Ignored since data is an xarray dataset." ) return range_in_meter elif data_type == EchoData: if ( isinstance(platform_data, xr.Dataset) and 'vertical_offset' in platform_data ): return range_in_meter + platform_data.vertical_offset.rename({'time2': 'ping_time'}) else: logger.warning( "Boolean type found for vertical_offset. Please provide platform data with vertical_offset in it or provide a separate vertical_offset data." # noqa ) return range_in_meter logger.warning(f"vertical_offset value of {vertical_offset} is ignored.") return range_in_meter if isinstance(vertical_offset, xr.DataArray): check_dims = list(range_in_meter.dims) check_dims.remove('channel') if 'time2' in vertical_offset: vertical_offset = vertical_offset.rename({'time2': 'ping_time'}) if not any( True if d in vertical_offset.dims else False for d in check_dims ): raise ValueError( f"vertical_offset must have any of these dimensions: {', '.join(check_dims)}" ) # Adds vertical_offset to range if it exists return range_in_meter + vertical_offset elif isinstance(vertical_offset, (int, float)): return range_in_meter + vertical_offset
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,826
OSOceanAcoustics/echopype
refs/heads/main
/.ci_helpers/docker/setup-services.py
"""setup-services.py Script to help bring up docker services for testing. """ import argparse import logging import shutil import subprocess import sys from pathlib import Path from typing import Dict, List import fsspec logger = logging.getLogger("setup-services") streamHandler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter("%(message)s") streamHandler.setFormatter(formatter) logger.addHandler(streamHandler) logger.setLevel(level=logging.INFO) HERE = Path(".").absolute() BASE = Path(__file__).parent.absolute() COMPOSE_FILE = BASE / "docker-compose.yaml" TEST_DATA_PATH = HERE / "echopype" / "test_data" def parse_args(): parser = argparse.ArgumentParser(description="Setup services for testing") parser.add_argument("--deploy", action="store_true", help="Flag to setup docker services") parser.add_argument( "--http-server", default="docker_httpserver_1", help="Flag for specifying docker http server id.", ) parser.add_argument( "--no-pull", action="store_true", help="Optional flag to skip pulling the latest images from dockerhub", ) parser.add_argument( "--data-only", action="store_true", help="""Optional flag to only copy over data to http server, and setup minio bucket and not deploy any services. NOTE: MUST HAVE SERVICES RUNNING!""", ) parser.add_argument( "--tear-down", action="store_true", help="Flag to tear down docker services", ) parser.add_argument( "--images", action="store_true", help="Optional flag to remove images also during tear down", ) return parser.parse_args() def run_commands(commands: List[Dict]) -> None: for idx, command in enumerate(commands, start=1): msg = command.get("msg") cmd = command.get("cmd") args = command.get("args", None) logger.info(f"{idx}) {msg}") if cmd is None: continue elif isinstance(cmd, list): subprocess.run(cmd) elif callable(cmd): cmd(args) else: raise ValueError(f"command of {type(cmd)} is invalid.") def load_s3(*args, **kwargs) -> None: common_storage_options = dict( client_kwargs=dict(endpoint_url="http://localhost:9000/"), key="minioadmin", secret="minioadmin", ) bucket_name = "ooi-raw-data" fs = fsspec.filesystem( "s3", **common_storage_options, ) test_data = "data" if not fs.exists(test_data): fs.mkdir(test_data) if not fs.exists(bucket_name): fs.mkdir(bucket_name) # Load test data into bucket for d in TEST_DATA_PATH.iterdir(): source_path = f"echopype/test_data/{d.name}" fs.put(source_path, f"{test_data}/{d.name}", recursive=True) if __name__ == "__main__": args = parse_args() commands = [] if all([args.deploy, args.tear_down]): print("Cannot have both --deploy and --tear-down. Exiting.") sys.exit(1) if not any([args.deploy, args.tear_down]): print("Please provide either --deploy or --tear-down flags. For more help use --help flag.") sys.exit(0) if args.deploy: commands.append({"msg": "Starting test services deployment ...", "cmd": None}) if not args.data_only: if not args.no_pull: commands.append( { "msg": "Pulling latest images ...", "cmd": ["docker-compose", "-f", COMPOSE_FILE, "pull"], } ) commands.append( { "msg": "Bringing up services ...", "cmd": [ "docker-compose", "-f", COMPOSE_FILE, "up", "-d", "--remove-orphans", "--force-recreate", ], } ) if TEST_DATA_PATH.exists(): commands.append( { "msg": f"Deleting old test folder at {TEST_DATA_PATH} ...", "cmd": shutil.rmtree, "args": TEST_DATA_PATH, } ) commands.append( { "msg": "Copying new test folder from http service ...", "cmd": [ "docker", "cp", "-L", f"{args.http_server}:/usr/local/apache2/htdocs/data", TEST_DATA_PATH, ], } ) commands.append({"msg": "Setting up minio s3 bucket ...", "cmd": load_s3}) if args.tear_down: command = ["docker-compose", "-f", COMPOSE_FILE, "down", "--remove-orphans", "--volumes"] if args.images: command = command + ["--rmi", "all"] commands.append({"msg": "Stopping test services deployment ...", "cmd": command}) commands.append({"msg": "Done.", "cmd": ["docker", "ps", "--last", "2"]}) run_commands(commands)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,827
OSOceanAcoustics/echopype
refs/heads/main
/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py
import xml.etree.ElementTree as ET import numpy as np import xarray as xr # TODO: turn this into an absolute import! from ...core import SONAR_MODELS from ...utils.log import _init_logger from ..convention import sonarnetcdf_1 _varattrs = sonarnetcdf_1.yaml_dict["variable_and_varattributes"] logger = _init_logger(__name__) def _get_sensor(sensor_model): """ This function returns the sensor name corresponding to the ``set_groups_X.py`` that was used to create the v0.5.x file's EchoData structure. Parameters ---------- sensor_model : str Sensor model name provided in ``ed['Top-level'].keywords`` """ if sensor_model in ["EK60", "ES70"]: return "EK60" elif sensor_model in ["EK80", "ES80", "EA640"]: return "EK80" else: return sensor_model def _range_bin_to_range_sample(ed_obj): """ Renames the coordinate range_bin to range_sample. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x Notes ----- The function directly modifies the input EchoData object. """ for grp_path in ed_obj.group_paths: if "range_bin" in list(ed_obj[grp_path].coords): # renames range_bin in the dataset ed_obj[grp_path] = ed_obj[grp_path].rename(name_dict={"range_bin": "range_sample"}) ed_obj[grp_path].range_sample.attrs["long_name"] = "Along-range sample number, base 0" def _add_attrs_to_freq(ed_obj): """ Makes the attributes of the ``frequency`` variable consistent for all groups. This is necessary because not all groups have the same attributes (some are missing them too) for the ``frequency`` variable. This variable is used to set the variable ``frequency_nominal`` later on. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x Notes ----- The function directly modifies the input EchoData object. """ for grp_path in ed_obj.group_paths: if "frequency" in list(ed_obj[grp_path].coords): # creates consistent frequency attributes ed_obj[grp_path]["frequency"] = ed_obj[grp_path].frequency.assign_attrs( { "long_name": "Transducer frequency", "standard_name": "sound_frequency", "units": "Hz", "valid_min": 0.0, } ) def _reorganize_beam_groups(ed_obj): """ Maps Beam --> Sonar/Beam_group1 and Beam_power --> Sonar/Beam_group2. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x Notes ----- The function directly modifies the input EchoData object. """ # Map Beam --> Sonar/Beam_group1 if "Beam" in ed_obj.group_paths: ed_obj._tree["Sonar/Beam_group1"] = ed_obj._tree["Beam"] # Map Beam_power --> Sonar/Beam_group2 if "Beam_power" in ed_obj.group_paths: ed_obj._tree["Sonar/Beam_group2"] = ed_obj._tree["Beam_power"] def get_channel_id(ed_obj, sensor): """ Returns the channel_id for all non-unique frequencies. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. sensor : str The sensor used to create the v0.5.x file. Returns ------- A datarray specifying the channel_ids with dimension frequency. """ if sensor == "AZFP": # create frequency_nominal variable freq_nom = ed_obj["Sonar/Beam_group1"].frequency # create unique channel_id for AZFP freq_as_str = (freq_nom / 1000.0).astype(int).astype(str).values channel_id_str = [ str(ed_obj["Sonar"].sonar_serial_number) + "-" + freq_as_str[i] + "-" + str(i + 1) for i in range(len(freq_as_str)) ] channel_id = xr.DataArray( data=channel_id_str, dims=["frequency"], coords={"frequency": freq_nom} ) else: # in the case of EK80 we cannot infer the correct frequency # for each channel id, but we can obtain this information # from the XML string in the Vendor attribute if "config_xml" in ed_obj._tree["Vendor"].ds.attrs: xmlstring = ed_obj._tree["Vendor"].ds.attrs["config_xml"] root = ET.fromstring(xmlstring) channel_ids = [] freq = [] for i in root.findall("./Transceivers/Transceiver"): [channel_ids.append(j.attrib["ChannelID"]) for j in i.findall(".//Channel")] [freq.append(np.float64(j.attrib["Frequency"])) for j in i.findall(".//Transducer")] channel_id = xr.DataArray(data=channel_ids, coords={"frequency": (["frequency"], freq)}) else: # collect all beam group channel ids and associated frequencies channel_id = xr.concat( [child.ds.channel_id for child in ed_obj._tree["Sonar"].children.values()], dim="frequency", ) return channel_id def _frequency_to_channel(ed_obj, sensor): """ 1. In all groups that it appears, changes the dimension ``frequency`` to ``channel`` whose values are based on ``channel_id`` for EK60/EK80 and are a custom string for AZFP. 2. Removes channel_id if it appears as a variable 3. Adds the variable ``frequency_nominal`` to all Datasets that have dimension ``channel`` Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. sensor : str The sensor used to create the v0.5.x file. Notes ----- The function directly modifies the input EchoData object. """ channel_id = get_channel_id(ed_obj, sensor) # all channel ids for grp_path in ed_obj.group_paths: if "frequency" in ed_obj[grp_path]: # add frequency_nominal ed_obj[grp_path]["frequency_nominal"] = ed_obj[grp_path].frequency ed_obj[grp_path] = ed_obj[grp_path].rename({"frequency": "channel"}) # set values for channel if "channel_id" in ed_obj[grp_path]: ed_obj[grp_path]["channel"] = ed_obj[grp_path].channel_id.values ed_obj[grp_path] = ed_obj._tree[grp_path].ds.drop("channel_id") else: ed_obj[grp_path]["channel"] = channel_id.sel( frequency=ed_obj[grp_path].frequency_nominal ).values # set attributes for channel ed_obj[grp_path]["channel"] = ed_obj[grp_path]["channel"].assign_attrs( _varattrs["beam_coord_default"]["channel"] ) def _change_beam_var_names(ed_obj, sensor): """ For EK60 ``Beam_group1`` 1. Rename ``beamwidth_receive_alongship`` to ``beamwidth_twoway_alongship`` and change the attribute ``long_name`` 2. Rename ``beamwidth_transmit_athwartship`` to ``beamwidth_twoway_athwartship`` and change the attribute ``long_name`` 3. Remove the variables ``beamwidth_receive_athwartship`` and ``beamwidth_transmit_alongship`` 4. Change the attribute ``long_name`` in the variables ``angle_offset_alongship/athwartship`` and ``angle_sensitivity_alongship/athwartship`` For EK80 ``Beam_group1`` 1. Change the attribute ``long_name`` in the variables ``angle_offset_alongship/athwartship`` Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. sensor : str Variable specifying the sensor that created the file. Notes ----- The function directly modifies the input EchoData object. """ if sensor == "EK60": ed_obj["Sonar/Beam_group1"] = ed_obj["Sonar/Beam_group1"].rename( {"beamwidth_receive_alongship": "beamwidth_twoway_alongship"} ) ed_obj["Sonar/Beam_group1"].beamwidth_twoway_alongship.attrs[ "long_name" ] = "Half power two-way beam width along alongship axis of beam" ed_obj["Sonar/Beam_group1"] = ed_obj["Sonar/Beam_group1"].rename( {"beamwidth_transmit_athwartship": "beamwidth_twoway_athwartship"} ) ed_obj["Sonar/Beam_group1"].beamwidth_twoway_athwartship.attrs[ "long_name" ] = "Half power two-way beam width along athwartship axis of beam" ed_obj["Sonar/Beam_group1"] = ed_obj["Sonar/Beam_group1"].drop( ["beamwidth_receive_athwartship", "beamwidth_transmit_alongship"] ) if sensor in ["EK60", "EK80"]: for beam_group in ed_obj._tree["Sonar"].children.values(): beam_group.ds.angle_sensitivity_alongship.attrs[ "long_name" ] = "alongship angle sensitivity of the transducer" beam_group.ds.angle_sensitivity_athwartship.attrs[ "long_name" ] = "athwartship angle sensitivity of the transducer" beam_group.ds.angle_offset_alongship.attrs[ "long_name" ] = "electrical alongship angle offset of the transducer" beam_group.ds.angle_offset_athwartship.attrs[ "long_name" ] = "electrical athwartship angle offset of the transducer" def _add_comment_to_beam_vars(ed_obj, sensor): """ For EK60 and EK80 Add the ``comment`` attribute to the variables ``beamwidth_twoway_alongship/athwartship``, ``angle_offset_alongship/athwartship``, ``angle_sensitivity_alongship/athwartship``, ``angle_athwartship/alongship``, ``beamwidth_twoway_alongship/athwartship``, ``angle_athwartship/alongship`` Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. sensor : str Variable specifying the sensor that created the file. Notes ----- The function directly modifies the input EchoData object. """ if sensor in ["EK60", "EK80"]: for beam_group in ed_obj._tree["Sonar"].children.values(): beam_group.ds.beamwidth_twoway_alongship.attrs["comment"] = ( "Introduced in echopype for Simrad echosounders to avoid " "potential confusion with convention definitions. The alongship " "angle corresponds to the minor angle in SONAR-netCDF4 vers 2. The " "convention defines one-way transmit or receive beamwidth " "(beamwidth_receive_minor and beamwidth_transmit_minor), but Simrad " "echosounders record two-way beamwidth in the data." ) beam_group.ds.beamwidth_twoway_athwartship.attrs["comment"] = ( "Introduced in echopype for Simrad echosounders to avoid " "potential confusion with convention definitions. The athwartship " "angle corresponds to the major angle in SONAR-netCDF4 vers 2. The " "convention defines one-way transmit or receive beamwidth " "(beamwidth_receive_major and beamwidth_transmit_major), but Simrad " "echosounders record two-way beamwidth in the data." ) beam_group.ds.angle_offset_alongship.attrs["comment"] = ( "Introduced in echopype for Simrad echosounders. The alongship " "angle corresponds to the minor angle in SONAR-netCDF4 vers 2. " ) beam_group.ds.angle_offset_athwartship.attrs["comment"] = ( "Introduced in echopype for Simrad echosounders. The athwartship " "angle corresponds to the major angle in SONAR-netCDF4 vers 2. " ) beam_group.ds.angle_sensitivity_alongship.attrs[ "comment" ] = beam_group.ds.angle_offset_alongship.attrs["comment"] beam_group.ds.angle_sensitivity_athwartship.attrs[ "comment" ] = beam_group.ds.angle_offset_athwartship.attrs["comment"] if "angle_alongship" in beam_group.ds: beam_group.ds.angle_alongship.attrs[ "comment" ] = beam_group.ds.angle_offset_alongship.attrs["comment"] if "angle_athwartship" in beam_group.ds: beam_group.ds.angle_athwartship.attrs[ "comment" ] = beam_group.ds.angle_offset_athwartship.attrs["comment"] def _beam_groups_to_convention(ed_obj, set_grp_cls): """ Adds ``beam`` and ``ping_time`` dimensions to variables in ``Beam_groupX`` so that they comply with the convention. For beam groups containing the ``quadrant``, changes the ``quadrant`` dimension to ``beam`` with string values starting at 1 and sets its attributes before adding the `beam` and `ping_time` dimensions. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x set_grp_cls : SetGroupsBase object The set groups class of the sensor being considered Notes ----- The function directly modifies the input EchoData object. """ for beam_group in ed_obj._tree["Sonar"].children.values(): if "quadrant" in beam_group.ds: # change quadrant to beam, assign its values # to a string starting at 1, and set attributes beam_group.ds = beam_group.ds.rename({"quadrant": "beam"}) beam_group.ds["beam"] = (beam_group.ds.beam + 1).astype(str) beam_group.ds.beam.attrs["long_name"] = "Beam name" set_grp_cls.beam_groups_to_convention( set_grp_cls, beam_group.ds, set_grp_cls.beam_only_names, set_grp_cls.beam_ping_time_names, set_grp_cls.ping_time_only_names, ) def _modify_sonar_group(ed_obj, sensor): """ 1. Renames ``quadrant`` to ``beam``, sets the values to strings starting at 1, and sets attributes, if necessary. 2. Adds ``beam_group`` coordinate to ``Sonar`` group for all sensors 3. Adds the variable ``beam_group_descr`` to the ``Sonar`` group for all sensors 4. Adds the variable ``sonar_serial_number`` to the ``Sonar`` group and fills it with NaNs (it is missing information) for the EK80 sensor only. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. sensor : str The sensor used to create the v0.5.x file. Notes ----- The function directly modifies the input EchoData object. """ set_groups_cls = SONAR_MODELS[sensor]["set_groups"] _beam_groups_to_convention(ed_obj, set_groups_cls) # add beam_group coordinate and beam_group_descr variable num_beams = len(ed_obj._tree["Sonar"].children.values()) set_groups_cls._beamgroups = set_groups_cls.beamgroups_possible[:num_beams] beam_groups_vars, beam_groups_coord = set_groups_cls._beam_groups_vars(set_groups_cls) ed_obj["Sonar"] = ed_obj["Sonar"].assign_coords(beam_groups_coord) ed_obj["Sonar"] = ed_obj["Sonar"].assign(**beam_groups_vars) # add sonar_serial_number to EK80 Sonar group if sensor == "EK80": ed_obj["Sonar"] = ed_obj["Sonar"].assign( { "sonar_serial_number": ( ["channel"], np.full_like(ed_obj["Sonar"].frequency_nominal.values, np.nan), ) } ) def _move_transducer_offset_vars(ed_obj, sensor): """ Moves transducer_offset_x/y/z from beam groups to Platform group for EK60 and EK80. If more than one beam group exists, then the variables are first collected and then moved to Platform. Additionally, adds ``frequency_nominal`` to Platform for the EK80 sensor. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. sensor : str Variable specifying the sensor that created the file. Notes ----- The function directly modifies the input EchoData object. """ if sensor in ["EK60", "EK80"]: full_transducer_vars = {"x": [], "y": [], "z": []} # collect transducser_offset_x/y/z from the beam groups for beam_group in ed_obj._tree["Sonar"].children.values(): for spatial in full_transducer_vars.keys(): full_transducer_vars[spatial].append(beam_group.ds["transducer_offset_" + spatial]) # remove transducer_offset_x/y/z from the beam group beam_group.ds = beam_group.ds.drop("transducer_offset_" + spatial) # transfer transducser_offset_x/y/z to Platform for spatial in full_transducer_vars.keys(): ed_obj["Platform"]["transducer_offset_" + spatial] = xr.concat( full_transducer_vars[spatial], dim="channel" ) if sensor == "EK80": ed_obj["Platform"]["frequency_nominal"] = ed_obj["Vendor"].frequency_nominal.sel( channel=ed_obj["Platform"].channel ) def _add_vars_to_platform(ed_obj, sensor): """ 1.Adds ``MRU_offset_x/y/z``, ``MRU_rotation_x/y/z``, and ``position_offset_x/y/z`` to the ``Platform`` group for the EK60/EK80/AZFP sensors. 2. Renames ``heave`` to ``vertical_offset`` for the EK60 and EK80. 3. Adds ``transducer_offset_x/y/z``, ``vertical_offset``, ``water_level`` to the ``Platform`` group for the AZFP sensor only. 4. Adds the coordinate ``time3`` to the ``Platform`` group for the EK80 sensor only. 5. Adds the variables ``drop_keel_offset(time3)`` (currently in the attribute), ``drop_keel_offset_is_manual(time3)``, and ``water_level_draft_is_manual(time3)`` to the ``Platform`` group for the EK80 sensor only. 6. Adds the coordinate ``time3`` to the variable ``water_level`` in the ``Platform`` group for the EK80 sensor only. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. sensor : str Variable specifying the sensor that created the file. Notes ----- The function directly modifies the input EchoData object. """ ds_tmp = xr.Dataset( { var: ([], np.nan, _varattrs["platform_var_default"][var]) for var in [ "MRU_offset_x", "MRU_offset_y", "MRU_offset_z", "MRU_rotation_x", "MRU_rotation_y", "MRU_rotation_z", "position_offset_x", "position_offset_y", "position_offset_z", ] } ) if sensor == "EK60": ds_tmp = ds_tmp.expand_dims({"channel": ed_obj["Platform"].channel}) ds_tmp["channel"] = ds_tmp["channel"].assign_attrs( _varattrs["beam_coord_default"]["channel"] ) ed_obj["Platform"] = xr.merge([ed_obj["Platform"], ds_tmp]) if sensor != "AZFP": # this variable was missing for AZFP v0.5.x ed_obj["Platform"] = ed_obj["Platform"].rename({"heave": "vertical_offset"}) if sensor == "EK80": ed_obj["Platform"]["drop_keel_offset"] = xr.DataArray( data=[ed_obj["Platform"].attrs["drop_keel_offset"]], dims=["time3"] ) del ed_obj["Platform"].attrs["drop_keel_offset"] ed_obj["Platform"]["drop_keel_offset_is_manual"] = xr.DataArray( data=[np.nan], dims=["time3"] ) ed_obj["Platform"]["water_level_draft_is_manual"] = xr.DataArray( data=[np.nan], dims=["time3"] ) ed_obj["Platform"]["water_level"] = ed_obj["Platform"]["water_level"].expand_dims( dim=["time3"] ) ed_obj["Platform"] = ed_obj["Platform"].assign_coords( { "time3": ( ["time3"], ed_obj["Environment"].ping_time.values, { "axis": "T", "standard_name": "time", }, ) } ) if sensor == "AZFP": ds_tmp = xr.Dataset( { var: ([], np.nan, _varattrs["platform_var_default"][var]) for var in [ "transducer_offset_x", "transducer_offset_y", "transducer_offset_z", "vertical_offset", "water_level", ] } ) ed_obj["Platform"] = xr.merge([ed_obj["Platform"], ds_tmp]) def _add_vars_coords_to_environment(ed_obj, sensor): """ For EK80 1. Adds the length one NaN coordinate ``sound_velocity_profile_depth`` to the ``Environment`` group (this data is missing in v0.5.x). 2. Adds the variables ``sound_velocity_profile(time1, sound_velocity_profile_depth)``, ``sound_velocity_source(time1)``, ``transducer_name(time1)``, ``transducer_sound_speed(time1) to the ``Environment`` group. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. sensor : str Variable specifying the sensor that created the file. Notes ----- The function directly modifies the input EchoData object. """ if sensor == "EK80": ed_obj["Environment"]["sound_velocity_source"] = ( ["ping_time"], np.array(len(ed_obj["Environment"].ping_time) * ["None"]), ) ed_obj["Environment"]["transducer_name"] = ( ["ping_time"], np.array(len(ed_obj["Environment"].ping_time) * ["None"]), ) ed_obj["Environment"]["transducer_sound_speed"] = ( ["ping_time"], np.array(len(ed_obj["Environment"].ping_time) * [np.nan]), ) ed_obj["Environment"]["sound_velocity_profile"] = ( ["ping_time", "sound_velocity_profile_depth"], np.nan * np.ones((len(ed_obj["Environment"].ping_time), 1)), { "long_name": "sound velocity profile", "standard_name": "speed_of_sound_in_sea_water", "units": "m/s", "valid_min": 0.0, "comment": "parsed from raw data files as (depth, sound_speed) value pairs", }, ) ed_obj["Environment"] = ed_obj["Environment"].assign_coords( { "sound_velocity_profile_depth": ( ["sound_velocity_profile_depth"], [np.nan], { "standard_name": "depth", "units": "m", "axis": "Z", "positive": "down", "valid_min": 0.0, }, ) } ) def _rearrange_azfp_attrs_vars(ed_obj, sensor): """ Makes alterations to AZFP variables. Specifically, variables in ``Beam_group1``. 1. Moves ``tilt_x/y(ping_time)`` to the `Platform` group. 2. Moves ``temperature_counts(ping_time)``, ``tilt_x/y_count(ping_time)``, ``DS(channel)``, ``EL(channel)``, ``TVR(channel)``, ``VTX(channel)``, ``Sv_offset(channel)``, ``number_of_samples_digitized_per_pings(channel)``, ``number_of_digitized_samples_averaged_per_pings(channel)`` to the `Vendor` group: 3. Removes the variable `cos_tilt_mag(ping_time)` 4. Moves the following attributes to the ``Vendor`` group: ``tilt_X_a/b/c/d``, ``tilt_Y_a/b/c/d``, ``temperature_ka/kb/kc/A/B/C``, ``number_of_frequency``, ``number_of_pings_per_burst``, ``average_burst_pings_flag`` Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. sensor : str Variable specifying the sensor that created the file. Notes ----- The function directly modifies the input EchoData object. """ if sensor == "AZFP": beam_to_plat_vars = ["tilt_x", "tilt_y"] for var_name in beam_to_plat_vars: ed_obj["Platform"][var_name] = ed_obj["Sonar/Beam_group1"][var_name] beam_to_vendor_vars = [ "temperature_counts", "tilt_x_count", "tilt_y_count", "DS", "EL", "TVR", "VTX", "Sv_offset", "number_of_samples_digitized_per_pings", "number_of_digitized_samples_averaged_per_pings", ] for var_name in beam_to_vendor_vars: ed_obj["Vendor"][var_name] = ed_obj["Sonar/Beam_group1"][var_name] beam_to_vendor_attrs = ed_obj["Sonar/Beam_group1"].attrs.copy() del beam_to_vendor_attrs["beam_mode"] del beam_to_vendor_attrs["conversion_equation_t"] for key, val in beam_to_vendor_attrs.items(): ed_obj["Vendor"].attrs[key] = val del ed_obj["Sonar/Beam_group1"].attrs[key] ed_obj["Sonar/Beam_group1"] = ed_obj["Sonar/Beam_group1"].drop( ["cos_tilt_mag"] + beam_to_plat_vars + beam_to_vendor_vars ) def _rename_mru_time_location_time(ed_obj): """ Renames location_time to time1 and mru_time to time2 wherever it occurs. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. Notes ----- The function directly modifies the input EchoData object. """ for grp_path in ed_obj.group_paths: if "location_time" in list(ed_obj[grp_path].coords): # renames location_time to time1 ed_obj[grp_path] = ed_obj[grp_path].rename(name_dict={"location_time": "time1"}) if "mru_time" in list(ed_obj[grp_path].coords): # renames mru_time to time2 ed_obj[grp_path] = ed_obj[grp_path].rename(name_dict={"mru_time": "time2"}) def _rename_and_add_time_vars_ek60(ed_obj): """ 1. For EK60's ``Platform`` group this function adds the variable time3, renames the variable ``water_level`` time coordinate to time3, and changes ``ping_time`` to ``time2`` for the variables ``pitch/roll/vertical_offset``. 2. For EK60's ``Envrionment`` group this function renames ``ping_time`` to ``time1``. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. Notes ----- The function directly modifies the input EchoData object. """ ed_obj["Platform"]["water_level"] = ed_obj["Platform"]["water_level"].rename( {"ping_time": "time3"} ) ed_obj["Platform"] = ed_obj["Platform"].rename({"ping_time": "time2"}) ed_obj["Environment"] = ed_obj["Environment"].rename({"ping_time": "time1"}) ed_obj["Platform"] = ed_obj["Platform"].assign_coords( { "time3": ( ["time3"], ed_obj["Platform"].time3.values, { "axis": "T", "standard_name": "time", }, ) } ) def _add_time_attrs_in_platform(ed_obj, sensor): """ Adds attributes to ``time1``, ``time2``, and ``time3`` in the ``Platform`` group. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. sensor : str Variable specifying the sensor that created the file. Notes ----- The function directly modifies the input EchoData object. """ if "time1" in ed_obj["Platform"]: ed_obj["Platform"].time1.attrs[ "comment" ] = "Time coordinate corresponding to NMEA position data." ed_obj["Platform"].time2.attrs[ "long_name" ] = "Timestamps for platform motion and orientation data" ed_obj["Platform"].time2.attrs[ "comment" ] = "Time coordinate corresponding to platform motion and orientation data." if sensor in ["EK80", "EK60"]: ed_obj["Platform"].time3.attrs[ "long_name" ] = "Timestamps for platform-related sampling environment" ed_obj["Platform"].time3.attrs[ "comment" ] = "Time coordinate corresponding to platform-related sampling environment." if sensor == "EK80": ed_obj["Platform"].time3.attrs["comment"] = ( ed_obj["Platform"].time3.attrs["comment"] + " Note that Platform.time3 is the same as Environment.time1." ) def _add_time_attrs_in_environment(ed_obj, sensor): """ Adds attributes to ``time1`` in the ``Environment`` group. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. sensor : str Variable specifying the sensor that created the file. Notes ----- The function directly modifies the input EchoData object. """ if sensor in ["EK80", "EK60"]: ed_obj["Environment"].time1.attrs["long_name"] = "Timestamps for NMEA position datagrams" if sensor == "EK80": ed_obj["Environment"].time1.attrs["comment"] = ( "Time coordinate corresponding to " "environmental variables. Note that " "Platform.time3 is the same as Environment.time1." ) else: ed_obj["Environment"].time1.attrs[ "comment" ] = "Time coordinate corresponding to environmental variables." def _make_time_coords_consistent(ed_obj, sensor): """ 1. Renames location_time to time1 and mru_time to time2 wherever it occurs. 2. For EK60 adds and modifies the ``Platform`` group's time variables. 3. For EK80 renames ``ping_time`` to ``time1`` in the ``Environment`` group. 4. For AZFP renames ``ping_time`` to ``time2`` in the ``Platform`` group and ``ping_time`` to ``time1`` in the ``Environment`` group. 5. Adds time comments to the ``Platform``, ``Platform/NMEA``, and ``Environment`` groups. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. sensor : str Variable specifying the sensor that created the file. Notes ----- The function directly modifies the input EchoData object. """ _rename_mru_time_location_time(ed_obj) if sensor == "EK60": _rename_and_add_time_vars_ek60(ed_obj) if sensor == "EK80": ed_obj["Environment"] = ed_obj["Environment"].rename({"ping_time": "time1"}) if sensor == "AZFP": ed_obj["Platform"] = ed_obj["Platform"].rename({"ping_time": "time2"}) ed_obj["Environment"] = ed_obj["Environment"].rename({"ping_time": "time1"}) _add_time_attrs_in_platform(ed_obj, sensor) _add_time_attrs_in_environment(ed_obj, sensor) if "Platform/NMEA" in ed_obj.group_paths: ed_obj["Platform/NMEA"].time1.attrs[ "comment" ] = "Time coordinate corresponding to NMEA sensor data." def _add_source_filenames_var(ed_obj): """ Make the attribute ``src_filenames`` into the variable ``source_filenames`` in the ``Provenance`` group. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. Notes ----- The function directly modifies the input EchoData object. """ # this statement only applies for a combined file if "src_filenames" in ed_obj["Provenance"]: ed_obj["Provenance"]["source_filenames"] = ( ["filenames"], ed_obj["Provenance"].src_filenames.values, {"long_name": "Source filenames"}, ) ed_obj["Provenance"].drop("src_filenames") else: ed_obj["Provenance"]["source_filenames"] = ( ["filenames"], [ed_obj["Provenance"].attrs["src_filenames"]], {"long_name": "Source filenames"}, ) del ed_obj["Provenance"].attrs["src_filenames"] def _rename_vendor_group(ed_obj): """ Renames the `Vendor` group to `Vendor_specific` for all sonar sensors. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. Notes ----- The function directly modifies the input EchoData object. """ node = ed_obj._tree["Vendor"] ed_obj._tree["Vendor"].orphan() ed_obj._tree["Vendor_specific"] = node def _change_list_attrs_to_str(ed_obj): """ If the attribute ``valid_range`` of a variable in the ``Platform`` group is not a string, turn it into a string. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. Notes ----- The function directly modifies the input EchoData object. """ for var in ed_obj["Platform"]: if "valid_range" in ed_obj["Platform"][var].attrs.keys(): attr_val = ed_obj["Platform"][var].attrs["valid_range"] if not isinstance(attr_val, str): ed_obj["Platform"][var].attrs["valid_range"] = f"({attr_val[0]}, {attr_val[1]})" def _change_vertical_offset_attrs(ed_obj): """ Changes the attributes of the variable ``Platform.vertical_offset``. Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. Notes ----- The function directly modifies the input EchoData object. """ if "vertical_offset" in ed_obj["Platform"]: ed_obj["Platform"]["vertical_offset"].attrs = { "long_name": "Platform vertical offset from nominal", "units": "m", } def _consistent_sonar_model_attr(ed_obj, sensor): """ Brings consistency to the attribute ``sonar_model`` of the ``Sonar`` group amongst the sensors. 1. Changes ``sonar_model`` to "AZFP" for the AZFP sensor. 2. Sets EK60's attribute ``sonar_software_name`` to the v0.5.x value of ``sonar_model``. 3. Changes ``sonar_model`` to "EK60" for the EK60 sensor. 4. Renames the variable ``Sonar.sonar_model`` to ``Sonar.transducer_name`` for the EK80 sensor. 5. Adds the attribute ``sonar_model`` to the EK80 sensor and sets it to "EK80". Parameters ---------- ed_obj : EchoData EchoData object that was created using echopype version 0.5.x. sensor : str Variable specifying the sensor that created the file. Notes ----- The function directly modifies the input EchoData object. """ if sensor == "AZFP": ed_obj["Sonar"].attrs["sonar_model"] = "AZFP" elif sensor == "EK60": ed_obj["Sonar"].attrs["sonar_software_name"] = ed_obj["Sonar"].attrs["sonar_model"] ed_obj["Sonar"].attrs["sonar_model"] = "EK60" elif sensor == "EK80": ed_obj["Sonar"] = ed_obj["Sonar"].rename({"sonar_model": "transducer_name"}) ed_obj["Sonar"].attrs["sonar_model"] = "EK80" def convert_v05x_to_v06x(echodata_obj): """ This function converts the EchoData structure created in echopype version 0.5.x to the EchoData structure created in echopype version 0.6.x. Specifically, the following items are completed: 1. Rename the coordinate ``range_bin`` to ``range_sample`` 2. Add attributes to `frequency` dimension throughout all sensors. 3. Map ``Beam`` to ``Sonar/Beam_group1`` 4. Map ``Beam_power`` to ``Sonar/Beam_group2`` 5. Adds ``beam`` and ``ping_time`` dimensions to certain variables within the beam groups. 6. Renames ``quadrant`` to ``beam``, sets the values to strings starting at 1, and sets attributes, if necessary. 7. Add comment attribute to all _alongship/_athwartship variables and use two-way beamwidth variables. 8. Adds ``beam_group`` dimension to ``Sonar`` group 9. Adds ``sonar_serial_number``, ``beam_group_name``, and ``beam_group_descr`` to ``Sonar`` group. 10. Renames ``frequency`` to ``channel`` and adds the variable ``frequency_nominal`` to every group that needs it. 11. Move ``transducer_offset_x/y/z`` from beam groups to the ``Platform`` group (for EK60 and EK80 only). 12. Add variables to the `Platform` group and rename ``heave`` to ``vertical_offset`` (if necessary). 13. Add variables and coordinate to the ``Environment`` group for EK80 only. 14. Move AZFP attributes and variables from ``Beam_group1`` to the ``Vendor`` and ``Platform`` groups. Additionally, remove the variable ``cos_tilt_mag``, if it exists. 15. Make the names of the time coordinates in the `Platform` and `Environment` groups consistent and add new the attribute comment to these time coordinates. 16. Make the attribute ``src_filenames`` into the variable ``source_filenames`` in the ``Provenance`` group. 17. Rename the `Vendor` group to `Vendor_specific` for all sonar sensors. 18. Change the attribute ``valid_range`` of variables in the ``Platform`` group into a string, if it is a numpy array. 19. Change the attributes of the variable ``Platform.vertical_offset``. 20. Bring consistency to the attribute ``sonar_model`` of the ``Sonar`` group. Parameters ---------- echodata_obj : EchoData EchoData object that was created using echopype version 0.5.x Notes ----- The function directly modifies the input EchoData object. No actions are taken for AD2CP. """ # TODO: put in an appropriate link to the v5 to v6 conversion outline logger.warning( "Converting echopype version 0.5.x file to 0.6.0." " For specific details on how items have been changed," " please see the echopype documentation. It is recommended " "that one creates the file using echopype.open_raw again, " "rather than relying on this conversion." ) # get the sensor used to create the v0.5.x file. sensor = _get_sensor(echodata_obj["Top-level"].keywords) if sensor == "AD2CP": pass else: _range_bin_to_range_sample(echodata_obj) _add_attrs_to_freq(echodata_obj) _reorganize_beam_groups(echodata_obj) _frequency_to_channel(echodata_obj, sensor) _change_beam_var_names(echodata_obj, sensor) _add_comment_to_beam_vars(echodata_obj, sensor) _modify_sonar_group(echodata_obj, sensor) _move_transducer_offset_vars(echodata_obj, sensor) _add_vars_to_platform(echodata_obj, sensor) _add_vars_coords_to_environment(echodata_obj, sensor) _rearrange_azfp_attrs_vars(echodata_obj, sensor) _make_time_coords_consistent(echodata_obj, sensor) _add_source_filenames_var(echodata_obj) _change_list_attrs_to_str(echodata_obj) _change_vertical_offset_attrs(echodata_obj) _consistent_sonar_model_attr(echodata_obj, sensor) _rename_vendor_group(echodata_obj)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,828
OSOceanAcoustics/echopype
refs/heads/main
/echopype/clean/__init__.py
from .api import estimate_noise, remove_noise __all__ = [ "estimate_noise", "remove_noise", ]
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,829
OSOceanAcoustics/echopype
refs/heads/main
/echopype/visualize/plot.py
import matplotlib.pyplot as plt import matplotlib.cm import xarray as xr import numpy as np from xarray.plot.facetgrid import FacetGrid from matplotlib.collections import QuadMesh from typing import Optional, Union, List from .cm import cmap_d from ..utils.log import _init_logger logger = _init_logger(__name__) def _format_axis_label(axis_variable): return axis_variable.replace('_', " ").title() def _set_label( fg: Union[FacetGrid, QuadMesh, None] = None, filter_var: str = 'channel', filter_val: Union[str, int, float, None] = None, col: Optional[str] = None, ): props = {'boxstyle': 'square', 'facecolor': 'white', 'alpha': 0.7} if isinstance(fg, FacetGrid): text_pos = [0.02, 0.06] fontsize = 14 if col == 'beam': if isinstance(filter_val, list) or filter_val is None: for rl in fg.row_labels: if rl is not None: rl.set_text('') for idx, cl in enumerate(fg.col_labels): if cl is not None: cl.set_text(f'Beam {fg.col_names[idx]}') text_pos = [0.04, 0.06] fontsize = 10 for idx, ax in enumerate(fg.axes.flat): name_dicts = fg.name_dicts.flatten() if filter_var in name_dicts[idx]: chan = name_dicts[idx][filter_var] if col == filter_var: ax.set_title('') else: chan = filter_val ax.set_title(f'Beam {fg.col_names[idx]}') axtext = chan if filter_var == 'frequency': axtext = f"{int(chan / 1000)} kHz" ax.text( *text_pos, axtext, transform=ax.transAxes, fontsize=fontsize, verticalalignment='bottom', bbox=props, ) else: if filter_val is None: raise ValueError( f'{filter_var.title()} value is missing for single echogram plotting.' ) axtext = filter_val if filter_var == 'frequency': axtext = f"{int(axtext / 1000)} kHz" ax = fg.axes ax.text( 0.02, 0.04, axtext, transform=ax.transAxes, fontsize=13, verticalalignment='bottom', bbox=props, ) plt.title('') plt.tight_layout() def _set_plot_defaults(kwargs): plot_defaults = { 'cmap': 'jet', 'figsize': (15, 10), 'robust': False, 'yincrease': False, 'col_wrap': 1, } # Set plot defaults if not passed in kwargs for k, v in plot_defaults.items(): if k not in kwargs: kwargs[k] = v elif k == 'cmap' and k in kwargs: cmap = kwargs[k] try: if cmap in cmap_d: cmap = f'ep.{cmap}' kwargs[k] = cmap matplotlib.cm.get_cmap(cmap) except: import cmocean if cmap.startswith('cmo'): _, cmap = cmap.split('.') if cmap in cmocean.cm.cmap_d: kwargs[k] = f'cmo.{cmap}' else: raise ValueError(f"{cmap} is not a valid colormap.") # Remove extra plotting attributes that should be set # by echopype devs exclude_attrs = ['x', 'y', 'col', 'row'] for attr in exclude_attrs: if attr in kwargs: logger.warning(f"{attr} in kwargs. Removing.") kwargs.pop(attr) return kwargs def _plot_echogram( ds: xr.Dataset, channel: Union[str, List[str], None] = None, frequency: Union[str, List[str], None] = None, variable: str = 'backscatter_r', xaxis: str = 'ping_time', yaxis: str = 'echo_range', **kwargs, ) -> Union[FacetGrid, QuadMesh]: kwargs = _set_plot_defaults(kwargs) row = None col = None filter_var = 'channel' filter_val = None # perform frequency filtering if channel is not None: if 'channel' not in ds.dims: raise ValueError("Channel filtering is not available because channel is not a dimension for your dataset!") ds = ds.sel(channel=channel) filter_val = channel elif frequency is not None: duplicates = False if 'channel' in ds.dims: if len(np.unique(ds.frequency_nominal)) != len(ds.frequency_nominal): duplicates = True ds = ds.where(ds.frequency_nominal.isin(frequency), drop=True) else: if len(np.unique(ds.frequency)) != len(ds.frequency): duplicates = True ds = ds.sel(frequency=frequency) if duplicates: raise ValueError("Duplicate frequency found, please use channel for filtering.") filter_val = frequency filter_var = 'frequency' if 'backscatter_i' in ds.variables: col = 'beam' kwargs.setdefault('figsize', (15, 5)) kwargs.update( { 'col_wrap': None, } ) filtered_ds = np.abs(ds.backscatter_r + 1j * ds.backscatter_i) else: filtered_ds = ds[variable] if 'beam' in filtered_ds.dims: filtered_ds = filtered_ds.isel(beam=0).drop('beam') if 'channel' in filtered_ds.dims and frequency is not None: filtered_ds = filtered_ds.assign_coords({'frequency': ds.frequency_nominal}) filtered_ds = filtered_ds.swap_dims({'channel': 'frequency'}) if filtered_ds.frequency.size == 1: filtered_ds = filtered_ds.isel(frequency=0) # figure out channel/frequency size # to determine plotting method if filtered_ds[filter_var].size > 1: if col is None: col = filter_var else: row = filter_var filtered_ds[xaxis].attrs = { 'long_name': filtered_ds[xaxis].attrs.get( 'long_name', _format_axis_label(xaxis) ), 'units': filtered_ds[xaxis].attrs.get('units', ''), } filtered_ds[yaxis].attrs = { 'long_name': filtered_ds[yaxis].attrs.get( 'long_name', _format_axis_label(yaxis) ), 'units': filtered_ds[yaxis].attrs.get('units', ''), } plots = [] if not filtered_ds[filter_var].shape: if ( np.any(filtered_ds.isnull()).values == np.array(True) and 'echo_range' in filtered_ds.coords and 'range_sample' in filtered_ds.dims and variable in ['backscatter_r', 'Sv'] ): # Handle the nans for echodata and Sv filtered_ds = filtered_ds.sel( ping_time=filtered_ds.echo_range.dropna(dim='ping_time', how='all').ping_time ) filtered_ds = filtered_ds.sel( range_sample=filtered_ds.echo_range.dropna(dim='range_sample').range_sample ) plot = filtered_ds.plot.pcolormesh( x=xaxis, y=yaxis, col=col, row=row, **kwargs, ) _set_label(plot, filter_var=filter_var, filter_val=filter_val, col=col) plots.append(plot) else: # Scale plots num_chan = len(filtered_ds[filter_var]) chan_scaling = (-0.06, -0.16) figsize_scale = tuple( [1 + (scale * num_chan) for scale in chan_scaling] ) new_size = tuple( [ size * figsize_scale[idx] for idx, size in enumerate(kwargs.get('figsize')) ] ) kwargs.update({'figsize': new_size}) for f in filtered_ds[filter_var]: d = filtered_ds[filtered_ds[filter_var] == f.values] if ( np.any(d.isnull()).values == np.array(True) and 'echo_range' in d.coords and 'range_sample' in d.dims and variable in ['backscatter_r', 'Sv'] ): # Handle the nans for echodata and Sv d = d.sel( ping_time=d.echo_range.dropna(dim='ping_time', how='all').ping_time ) d = d.sel( range_sample=d.echo_range.dropna(dim='range_sample').range_sample ) plot = d.plot.pcolormesh( x=xaxis, y=yaxis, col=col, row=row, **kwargs, ) _set_label(plot, filter_var=filter_var, filter_val=filter_val, col=col) plots.append(plot) return plots
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,830
OSOceanAcoustics/echopype
refs/heads/main
/echopype/commongrid/__init__.py
from .api import compute_MVBS, compute_MVBS_index_binning __all__ = [ "compute_MVBS", "compute_MVBS_index_binning", ]
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,831
OSOceanAcoustics/echopype
refs/heads/main
/echopype/convert/parsed_to_zarr.py
import secrets import sys from pathlib import Path from typing import List, Tuple, Union import more_itertools as miter import numpy as np import pandas as pd import zarr from ..utils.io import ECHOPYPE_DIR, check_file_permissions class Parsed2Zarr: """ This class contains functions that facilitate the writing of a parsed file to a zarr file. Additionally, it contains useful information, such as names of array groups and their paths. """ def __init__(self, parser_obj): self.temp_zarr_dir = None self.zarr_file_name = None self.store = None self.zarr_root = None self.parser_obj = parser_obj # parser object ParseEK60/ParseEK80/etc. def _create_zarr_info(self): """ Creates the temporary directory for zarr storage, zarr file name, zarr store, and the root group of the zarr store. """ # get current working directory current_dir = Path.cwd() # Check permission of cwd, raise exception if no permission check_file_permissions(current_dir) # construct temporary directory that will hold the zarr file out_dir = current_dir / ECHOPYPE_DIR / "temp_output" / "parsed2zarr_temp_files" if not out_dir.exists(): out_dir.mkdir(parents=True) # establish temporary directory we will write zarr files to self.temp_zarr_dir = str(out_dir) # create zarr store name zarr_file_name = str(out_dir / secrets.token_hex(16)) + ".zarr" # attempt to find different zarr_file_name, if it already exists count = 0 while Path(zarr_file_name).exists() and count < 10: # generate new zarr_file_name zarr_file_name = str(out_dir / secrets.token_hex(16)) + ".zarr" count += 1 # error out if we are unable to get a unique name, else assign name to class variable if (count == 10) and Path(zarr_file_name).exists(): raise RuntimeError("Unable to construct an unused zarr file name for Parsed2Zarr!") else: self.zarr_file_name = zarr_file_name # create zarr store and zarr group we want to write to self.store = zarr.DirectoryStore(self.zarr_file_name) self.zarr_root = zarr.group(store=self.store, overwrite=True) def _close_store(self): """properly closes zarr store""" # consolidate metadata and close zarr store zarr.consolidate_metadata(self.store) self.store.close() @staticmethod def set_multi_index( pd_obj: Union[pd.Series, pd.DataFrame], unique_dims: List[pd.Index] ) -> Union[pd.Series, pd.DataFrame]: """ Sets a multi-index from the product of the unique dimension values on a series and then returns it. Parameters ---------- pd_obj : Union[pd.Series, pd.DataFrame] Series or DataFrame that needs its multi-index modified. unique_dims : List[pd.Index] List where the elements are the unique values of the index. Returns ------- Union[pd.Series, pd.DataFrame] ``pd_obj`` with product multi-index Notes ----- By setting the multiindex, this method fills (or pads) missing dimension values. """ multi_index = pd.MultiIndex.from_product(unique_dims) # set product multi-index i.e. a preliminary padding of the df return pd_obj.reindex(multi_index, fill_value=np.nan) @staticmethod def get_max_elem_shape(pd_series: pd.Series) -> np.ndarray: """ Returns the maximum element shape for a Series that has array elements Parameters ---------- pd_series: pd.Series Series with array elements Returns ------- np.ndarray The maximum element shape """ all_shapes = pd_series.apply( lambda x: np.array(x.shape) if isinstance(x, np.ndarray) else None ).dropna() all_dims = np.vstack(all_shapes.to_list()) return all_dims.max(axis=0) def get_col_info( self, pd_series: pd.Series, time_name: str, is_array: bool, max_mb: int ) -> Tuple[int, list]: """ Provides the maximum number of times needed to fill at most `max_mb` MB of memory and the shape of each chunk. Parameters ---------- pd_series : pd.Series Series representing a column of the datagram df time_name : str The name of the index corresponding to time is_array : bool Specifies if we are working with a column that has arrays max_mb : int Maximum MB allowed for each chunk Returns ------- max_num_times : int The number of times needed to fill at most `max_mb` MB of memory. chunk_shape : list The shape of the chunk. Notes ----- This function assumes that our df has 2 indices and ``time_name`` is one of them. For ``chunk_shape`` the first element corresponds to time and this element will be filled later, thus, it is set to None here. The shape of chunk is of the form: ``[None, num_index_2, max_element_shape]`` if we have an array column and ``[None, num_index_2]`` if we have a column that does not contain an array. """ multi_ind_names = list(pd_series.index.names) if len(multi_ind_names) > 2: raise NotImplementedError("series contains more than 2 indices!") multi_ind_names.remove(time_name) # allows us to infer the other index name # get maximum dimension of column element if is_array: max_element_shape = self.get_max_elem_shape(pd_series) else: max_element_shape = 1 # bytes required to hold one element of the column # TODO: this assumes we are holding floats (the 8 value), generalize it elem_bytes = max_element_shape.prod(axis=0) * 8 # the number of unique elements in the second index index_2_name = multi_ind_names[0] num_index_2 = len(pd_series.index.unique(index_2_name)) bytes_per_time = num_index_2 * elem_bytes mb_per_time = bytes_per_time / 1e6 # The maximum number of times needed to fill at most `max_mb` MB of memory max_num_times = max_mb // mb_per_time # create form of chunk shape if isinstance(max_element_shape, np.ndarray): chunk_shape = [None, num_index_2, max_element_shape] else: chunk_shape = [None, num_index_2] return max_num_times, chunk_shape @staticmethod def get_np_chunk( series_chunk: pd.Series, chunk_shape: list, nan_array: np.ndarray ) -> np.ndarray: """ Manipulates the ``series_chunk`` values into the correct shape that can then be written to a zarr array. Parameters ---------- series_chunk : pd.Series A chunk of the dataframe column chunk_shape : list Specifies what shape the numpy chunk should be reshaped to nan_array : np.ndarray An array filled with NaNs that has the maximum length of a column's element. This value is used to pad empty elements. Returns ------- np_chunk : np.ndarray Final form of series_chunk that can be written to a zarr array """ if isinstance(nan_array, np.ndarray): # appropriately pad elements of series_chunk, if needed padded_elements = [] for elm in series_chunk.to_list(): if isinstance(elm, np.ndarray): # TODO: ideally this would take place in the parser, do this elm = elm.astype(np.float64) # amount of padding to add to each axis padding_amount = chunk_shape[2] - elm.shape # create np.pad pad_width pad_width = [(0, i) for i in padding_amount] padded_array = np.pad(elm, pad_width, "constant", constant_values=np.nan) padded_elements.append(padded_array) else: padded_elements.append(nan_array) np_chunk = np.concatenate(padded_elements, axis=0, dtype=np.float64) # reshape chunk to the appropriate size full_shape = chunk_shape[:2] + list(chunk_shape[2]) np_chunk = np_chunk.reshape(full_shape) else: np_chunk = series_chunk.to_numpy().reshape(chunk_shape) return np_chunk def write_chunks( self, pd_series: pd.Series, zarr_grp: zarr.group, is_array: bool, chunks: list, chunk_shape: list, ) -> None: """ Writes ``pd_series`` to ``zarr_grp`` as a zarr array with name ``pd_series.name``, using the specified chunks. Parameters ---------- pd_series : pd:Series Series representing a column of the datagram df zarr_grp: zarr.group Zarr group that we should write the zarr array to is_array : bool True if ``pd_series`` has elements that are arrays, False otherwise chunks: list A list where each element corresponds to a list of index values that should be chosen for the chunk. For example, if we are chunking along time, ``chunks`` would have the form: ``[['2004-09-09 16:19:06.059000', ..., '2004-09-09 16:19:06.746000'], ['2004-09-09 16:19:07.434000', ..., '2004-09-09 16:19:08.121000']]``. chunk_shape: list A list where each element specifies the shape of the zarr chunk for a given element of ``chunks`` """ if is_array: # nan array used in padding of elements nan_array = np.empty(chunk_shape[2], dtype=np.float64) nan_array[:] = np.nan else: nan_array = np.empty(1, dtype=np.float64) # obtain the number of times for each chunk chunk_len = [len(i) for i in chunks] max_chunk_len = max(chunk_len) zarr_chunk_shape = chunk_shape[:2] + list(chunk_shape[2]) zarr_chunk_shape[0] = max_chunk_len # obtain initial chunk in the proper form series_chunk = pd_series.loc[chunks[0]] chunk_shape[0] = chunk_len[0] np_chunk = self.get_np_chunk(series_chunk, chunk_shape, nan_array) # create array in zarr_grp using initial chunk full_array = zarr_grp.array( name=pd_series.name, data=np_chunk, chunks=zarr_chunk_shape, dtype="f8", fill_value="NaN", ) # append each chunk to full_array for i, chunk in enumerate(chunks[1:], start=1): series_chunk = pd_series.loc[chunk] chunk_shape[0] = chunk_len[i] np_chunk = self.get_np_chunk(series_chunk, chunk_shape, nan_array) full_array.append(np_chunk) def write_df_column( self, pd_series: pd.Series, zarr_grp: zarr.group, is_array: bool, unique_time_ind: pd.Index, max_mb: int = 100, ) -> None: """ Obtains the appropriate information needed to determine the chunks of a column and then calls the function that writes a column to a zarr array. Parameters ---------- pd_series: pd.Series Series with product multi-index and elements that are either an array or none of the elements are arrays. zarr_grp: zarr.group Zarr group that we should write the zarr array to is_array : bool True if ``pd_series`` is such that the elements of every column are arrays, False otherwise unique_time_ind : pd.Index The unique time index values of ``pd_series`` max_mb : int Maximum MB allowed for each chunk Notes ----- This assumes that our pd_series has at most 2 indices. """ if len(pd_series.index.names) > 2: raise NotImplementedError("series contains more than 2 indices!") # For a column, obtain the maximum amount of times needed for # each chunk and the associated form for the shape of the chunks max_num_times, chunk_shape = self.get_col_info( pd_series, unique_time_ind.name, is_array=is_array, max_mb=max_mb ) # evenly chunk unique times so that the smallest and largest # chunk differ by at most 1 element chunks = list(miter.chunked_even(unique_time_ind, max_num_times)) self.write_chunks(pd_series, zarr_grp, is_array, chunks, chunk_shape) def _get_zarr_dgrams_size(self) -> int: """ Returns the size in bytes of the list of zarr datagrams. """ size = 0 for i in self.parser_obj.zarr_datagrams: size += sum([sys.getsizeof(val) for key, val in i.items()]) return size def array_series_bytes(self, pd_series: pd.Series, n_rows: int) -> int: """ Determines the amount of bytes required for a series with array elements, for ``n_rows``. Parameters ---------- pd_series: pd.Series Series with array elements n_rows: int The number of rows with array elements Returns ------- The amount of bytes required to hold data """ # the number of bytes required to hold 1 element of series # Note: this assumes that we are holding floats pow_bytes = self.get_max_elem_shape(pd_series).prod(axis=0) * 8 # total memory required for series data return n_rows * pow_bytes def whether_write_to_zarr(self, **kwargs) -> None: """ Determines if the zarr data provided will expand into a form that is larger than a percentage of the total physical RAM. """ pass def datagram_to_zarr(self, **kwargs) -> None: """ Facilitates the conversion of a list of datagrams to a form that can be written to a zarr store. """ pass
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,832
OSOceanAcoustics/echopype
refs/heads/main
/echopype/calibrate/__init__.py
from .api import compute_Sv, compute_TS __all__ = ["compute_Sv", "compute_TS"]
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,833
OSOceanAcoustics/echopype
refs/heads/main
/echopype/echodata/convention/utils.py
from ..convention import sonarnetcdf_1 def _get_sonar_groups(): """Utility to reorder convention file by the paths""" group_mapping = sonarnetcdf_1.yaml_dict["groups"] sonar_groups = {} for k, v in group_mapping.items(): group_path = v.get("ep_group") if any(group_path == p for p in [None, "/"]): group_path = "Top-level" sonar_groups.setdefault( group_path, {"description": v.get("description"), "name": v.get("name")}, ) return sonar_groups
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,834
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/echodata/test_echodata.py
from textwrap import dedent import os import fsspec from pathlib import Path import shutil from datatree import DataTree from zarr.errors import GroupNotFoundError import echopype from echopype.calibrate.env_params_old import EnvParams from echopype.echodata import EchoData from echopype import open_converted from echopype.calibrate.calibrate_ek import CalibrateEK60, CalibrateEK80 import pytest import xarray as xr import numpy as np from utils import get_mock_echodata, check_consolidated @pytest.fixture(scope="module") def single_ek60_zarr(test_path): return ( test_path['EK60'] / "ncei-wcsd" / "Summer2017-D20170615-T190214__NEW.zarr" ) @pytest.fixture( params=[ single_ek60_zarr, (str, "ncei-wcsd", "Summer2017-D20170615-T190214.zarr"), (None, "ncei-wcsd", "Summer2017-D20170615-T190214__NEW.nc"), "s3://data/ek60/ncei-wcsd/Summer2017-D20170615-T190214.nc", "http://localhost:8080/data/ek60/ncei-wcsd/Summer2017-D20170615-T190214.zarr", "s3://data/ek60/ncei-wcsd/Summer2017-D20170615-T190214.zarr", fsspec.get_mapper( "s3://data/ek60/ncei-wcsd/Summer2017-D20170615-T190214.zarr", **dict( client_kwargs=dict(endpoint_url="http://localhost:9000/"), key="minioadmin", secret="minioadmin", ), ), ], ids=[ "ek60_zarr_path", "ek60_zarr_path_string", "ek60_netcdf_path", "ek60_netcdf_s3_string", "ek60_zarr_http_string", "ek60_zarr_s3_string", "ek60_zarr_s3_FSMap", ], ) def ek60_converted_zarr(request, test_path): if isinstance(request.param, tuple): desired_type, *paths = request.param if desired_type is not None: return desired_type(test_path['EK60'].joinpath(*paths)) else: return test_path['EK60'].joinpath(*paths) else: return request.param @pytest.fixture( params=[ ( ("EK60", "ncei-wcsd", "Summer2017-D20170615-T190214.raw"), "EK60", None, None, "CW", "power", ), ( ("EK80_NEW", "D20211004-T233354.raw"), "EK80", None, None, "CW", "power", ), ( ("EK80_NEW", "echopype-test-D20211004-T235930.raw"), "EK80", None, None, "BB", "complex", ), ( ("EK80_NEW", "D20211004-T233115.raw"), "EK80", None, None, "CW", "complex", ), ( ("ES70", "D20151202-T020259.raw"), "ES70", None, None, None, None, ), ( ("AZFP", "ooi", "17032923.01A"), "AZFP", ("AZFP", "ooi", "17032922.XML"), "Sv", None, None, ), ( ("AZFP", "ooi", "17032923.01A"), "AZFP", ("AZFP", "ooi", "17032922.XML"), "TS", None, None, ), ( ("AD2CP", "raw", "090", "rawtest.090.00001.ad2cp"), "AD2CP", None, None, None, None, ), ], ids=[ "ek60_cw_power", "ek80_cw_power", "ek80_bb_complex", "ek80_cw_complex", "es70", "azfp_sv", "azfp_sp", "ad2cp", ], ) def compute_range_samples(request, test_path): ( filepath, sonar_model, azfp_xml_path, azfp_cal_type, ek_waveform_mode, ek_encode_mode, ) = request.param if sonar_model.lower() == 'es70': pytest.xfail( reason="Not supported at the moment", ) path_model, *paths = filepath filepath = test_path[path_model].joinpath(*paths) if azfp_xml_path is not None: path_model, *paths = azfp_xml_path azfp_xml_path = test_path[path_model].joinpath(*paths) return ( filepath, sonar_model, azfp_xml_path, azfp_cal_type, ek_waveform_mode, ek_encode_mode, ) @pytest.fixture( params=[ { "path_model": "EK60", "raw_path": "Winter2017-D20170115-T150122.raw", }, { "path_model": "EK80", "raw_path": "D20170912-T234910.raw", }, ], ids=[ "ek60_winter2017", "ek80_summer2017", ], ) def range_check_files(request, test_path): return ( request.param["path_model"], test_path[request.param["path_model"]].joinpath(request.param['raw_path']) ) class TestEchoData: expected_groups = ( 'Top-level', 'Environment', 'Platform', 'Platform/NMEA', 'Provenance', 'Sonar', 'Sonar/Beam_group1', 'Vendor_specific', ) @pytest.fixture(scope="class") def mock_echodata(self): return get_mock_echodata() @pytest.fixture(scope="class") def converted_zarr(self, single_ek60_zarr): return single_ek60_zarr def create_ed(self, converted_raw_path): return EchoData.from_file(converted_raw_path=converted_raw_path) def test_constructor(self, converted_zarr): ed = self.create_ed(converted_zarr) assert ed.sonar_model == 'EK60' assert ed.converted_raw_path == converted_zarr assert ed.storage_options == {} for group in self.expected_groups: assert isinstance(ed[group], xr.Dataset) def test_group_paths(self, converted_zarr): ed = self.create_ed(converted_zarr) assert ed.group_paths == self.expected_groups def test_nbytes(self, converted_zarr): ed = self.create_ed(converted_zarr) assert isinstance(ed.nbytes, float) assert ed.nbytes == 4688692.0 def test_repr(self, converted_zarr): zarr_path_string = str(converted_zarr.absolute()) expected_repr = dedent( f"""\ <EchoData: standardized raw data from {zarr_path_string}> Top-level: contains metadata about the SONAR-netCDF4 file format. ├── Environment: contains information relevant to acoustic propagation through water. ├── Platform: contains information about the platform on which the sonar is installed. │ └── NMEA: contains information specific to the NMEA protocol. ├── Provenance: contains metadata about how the SONAR-netCDF4 version of the data were obtained. ├── Sonar: contains sonar system metadata and sonar beam groups. │ └── Beam_group1: contains backscatter power (uncalibrated) and other beam or channel-specific data, including split-beam angle data when they exist. └── Vendor_specific: contains vendor-specific information about the sonar and the data.""" ) ed = self.create_ed(converted_raw_path=converted_zarr) actual = "\n".join(x.rstrip() for x in repr(ed).split("\n")) assert expected_repr == actual def test_repr_html(self, converted_zarr): zarr_path_string = str(converted_zarr.absolute()) ed = self.create_ed(converted_raw_path=converted_zarr) assert hasattr(ed, "_repr_html_") html_repr = ed._repr_html_().strip() assert ( f"""<div class="xr-obj-type">EchoData: standardized raw data from {zarr_path_string}</div>""" in html_repr ) with xr.set_options(display_style="text"): html_fallback = ed._repr_html_().strip() assert html_fallback.startswith( "<pre>&lt;EchoData" ) and html_fallback.endswith("</pre>") def test_setattr(self, converted_zarr): sample_data = xr.Dataset({"x": [0, 0, 0]}) sample_data2 = xr.Dataset({"y": [0, 0, 0]}) ed = self.create_ed(converted_raw_path=converted_zarr) current_ed_beam = ed["Sonar/Beam_group1"] current_ed_top = ed['Top-level'] ed["Sonar/Beam_group1"] = sample_data ed['Top-level'] = sample_data2 assert ed["Sonar/Beam_group1"].equals(sample_data) is True assert ed["Sonar/Beam_group1"].equals(current_ed_beam) is False assert ed['Top-level'].equals(sample_data2) is True assert ed['Top-level'].equals(current_ed_top) is False def test_getitem(self, converted_zarr): ed = self.create_ed(converted_raw_path=converted_zarr) beam = ed['Sonar/Beam_group1'] assert isinstance(beam, xr.Dataset) assert ed['MyGroup'] is None ed._tree = None try: ed['Sonar'] except Exception as e: assert isinstance(e, ValueError) def test_setitem(self, converted_zarr): ed = self.create_ed(converted_raw_path=converted_zarr) ed['Sonar/Beam_group1'] = ed['Sonar/Beam_group1'].rename({'beam': 'beam_newname'}) assert sorted(ed['Sonar/Beam_group1'].dims.keys()) == ['beam_newname', 'channel', 'ping_time', 'range_sample'] try: ed['SomeRandomGroup'] = 'Testing value' except Exception as e: assert isinstance(e, GroupNotFoundError) def test_get_dataset(self, converted_zarr): ed = self.create_ed(converted_raw_path=converted_zarr) node = DataTree() result = ed._EchoData__get_dataset(node) ed_node = ed._tree['Sonar'] ed_result = ed._EchoData__get_dataset(ed_node) assert result is None assert isinstance(ed_result, xr.Dataset) @pytest.mark.parametrize("consolidated", [True, False]) def test_to_zarr_consolidated(self, mock_echodata, consolidated): """ Tests to_zarr consolidation. Currently, this test uses a mock EchoData object that only has attributes. The consolidated flag provided will be used in every to_zarr call (which is used to write each EchoData group to zarr_path). """ zarr_path = Path('test.zarr') mock_echodata.to_zarr(str(zarr_path), consolidated=consolidated, overwrite=True) check = True if consolidated else False zmeta_path = zarr_path / ".zmetadata" assert zmeta_path.exists() is check if check is True: check_consolidated(mock_echodata, zmeta_path) # clean up the zarr file shutil.rmtree(zarr_path) def test_open_converted(ek60_converted_zarr, minio_bucket): # noqa def _check_path(zarr_path): storage_options = {} if zarr_path.startswith("s3://"): storage_options = dict( client_kwargs=dict(endpoint_url="http://localhost:9000/"), key="minioadmin", secret="minioadmin", ) return storage_options storage_options = {} if not isinstance(ek60_converted_zarr, fsspec.FSMap): storage_options = _check_path(str(ek60_converted_zarr)) try: ed = open_converted( ek60_converted_zarr, storage_options=storage_options ) assert isinstance(ed, EchoData) is True except Exception as e: if ( isinstance(ek60_converted_zarr, str) and ek60_converted_zarr.startswith("s3://") and ek60_converted_zarr.endswith(".nc") ): assert isinstance(e, ValueError) is True # def test_compute_range(compute_range_samples): # ( # filepath, # sonar_model, # azfp_xml_path, # azfp_cal_type, # ek_waveform_mode, # ek_encode_mode, # ) = compute_range_samples # ed = echopype.open_raw(filepath, sonar_model, azfp_xml_path) # rng = np.random.default_rng(0) # stationary_env_params = EnvParams( # xr.Dataset( # data_vars={ # "pressure": ("time3", np.arange(50)), # "salinity": ("time3", np.arange(50)), # "temperature": ("time3", np.arange(50)), # }, # coords={ # "time3": np.arange("2017-06-20T01:00", "2017-06-20T01:25", np.timedelta64(30, "s"), dtype="datetime64[ns]") # } # ), # data_kind="stationary" # ) # if "time3" in ed["Platform"] and sonar_model != "AD2CP": # ed.compute_range(stationary_env_params, azfp_cal_type, ek_waveform_mode) # else: # try: # ed.compute_range(stationary_env_params, ek_waveform_mode="CW", azfp_cal_type="Sv") # except ValueError: # pass # else: # raise AssertionError # mobile_env_params = EnvParams( # xr.Dataset( # data_vars={ # "pressure": ("time", np.arange(100)), # "salinity": ("time", np.arange(100)), # "temperature": ("time", np.arange(100)), # }, # coords={ # "latitude": ("time", rng.random(size=100) + 44), # "longitude": ("time", rng.random(size=100) - 125), # } # ), # data_kind="mobile" # ) # if "latitude" in ed["Platform"] and "longitude" in ed["Platform"] and sonar_model != "AD2CP" and not np.isnan(ed["Platform"]["time1"]).all(): # ed.compute_range(mobile_env_params, azfp_cal_type, ek_waveform_mode) # else: # try: # ed.compute_range(mobile_env_params, ek_waveform_mode="CW", azfp_cal_type="Sv") # except ValueError: # pass # else: # raise AssertionError # env_params = {"sound_speed": 343} # if sonar_model == "AD2CP": # try: # ed.compute_range( # env_params, ek_waveform_mode="CW", azfp_cal_type="Sv" # ) # except ValueError: # pass # AD2CP is not currently supported in ed.compute_range # else: # raise AssertionError # else: # echo_range = ed.compute_range( # env_params, # azfp_cal_type, # ek_waveform_mode, # ) # assert isinstance(echo_range, xr.DataArray) def test_nan_range_entries(range_check_files): sonar_model, ek_file = range_check_files echodata = echopype.open_raw(ek_file, sonar_model=sonar_model) if sonar_model == "EK80": ds_Sv = echopype.calibrate.compute_Sv(echodata, waveform_mode='BB', encode_mode='complex') cal_obj = CalibrateEK80( echodata, env_params=None, cal_params=None, ecs_file=None, waveform_mode="BB", encode_mode="complex", ) range_output = cal_obj.range_meter # broadband complex data EK80 file: always need to drop "beam" dimension nan_locs_backscatter_r = ~echodata["Sonar/Beam_group1"].backscatter_r.isel(beam=0).drop("beam").isnull() else: # EK60 file does not need dropping "beam" dimension ds_Sv = echopype.calibrate.compute_Sv(echodata) cal_obj = CalibrateEK60(echodata, env_params={}, cal_params=None, ecs_file=None) range_output = cal_obj.range_meter nan_locs_backscatter_r = ~echodata["Sonar/Beam_group1"].backscatter_r.isnull() nan_locs_Sv_range = ~ds_Sv.echo_range.isnull() nan_locs_range = ~range_output.isnull() assert xr.Dataset.equals(nan_locs_backscatter_r, nan_locs_range) assert xr.Dataset.equals(nan_locs_backscatter_r, nan_locs_Sv_range) @pytest.mark.parametrize( ["ext_type", "sonar_model", "variable_mappings", "path_model", "raw_path", "platform_data"], [ ( "external-trajectory", "EK80", # variable_mappings dictionary as {Platform_var_name: external-data-var-name} {"pitch": "PITCH", "roll": "ROLL", "longitude": "longitude", "latitude": "latitude"}, "EK80", ( "saildrone", "SD2019_WCS_v05-Phase0-D20190617-T125959-0.raw", ), ( "saildrone", "saildrone-gen_5-fisheries-acoustics-code-sprint-sd1039-20190617T130000-20190618T125959-1_hz-v1.1595357449818.nc", #noqa ), ), ( "fixed-location", "EK60", # variable_mappings dictionary as {Platform_var_name: external-data-var-name} {"longitude": "longitude", "latitude": "latitude"}, "EK60", ( "ooi", "CE02SHBP-MJ01C-07-ZPLSCB101_OOI-D20191201-T000000.raw" ), (-100.0, -50.0), ), ], ) def test_update_platform( ext_type, sonar_model, variable_mappings, path_model, raw_path, platform_data, test_path ): raw_file = test_path[path_model] / raw_path[0] / raw_path[1] ed = echopype.open_raw(raw_file, sonar_model=sonar_model) # Test that the variables in Platform are all empty (nan) for variable in variable_mappings.keys(): assert np.isnan(ed["Platform"][variable].values).all() # Prepare the external data if ext_type == "external-trajectory": extra_platform_data_file_name = platform_data[1] extra_platform_data = xr.open_dataset( test_path[path_model] / platform_data[0] / extra_platform_data_file_name ) elif ext_type == "fixed-location": extra_platform_data_file_name = None extra_platform_data = xr.Dataset( { "longitude": (["time"], np.array([float(platform_data[0])])), "latitude": (["time"], np.array([float(platform_data[1])])), }, coords={ "time": (["time"], np.array([ed['Sonar/Beam_group1'].ping_time.values.min()])) }, ) # Run update_platform ed.update_platform( extra_platform_data, variable_mappings=variable_mappings, extra_platform_data_file_name=extra_platform_data_file_name, ) for variable in variable_mappings.keys(): assert not np.isnan(ed["Platform"][variable].values).all() # times have max interval of 2s # check times are > min(ed["Sonar/Beam_group1"]["ping_time"]) - 2s assert ( ed["Platform"]["time3"] > ed["Sonar/Beam_group1"]["ping_time"].min() - np.timedelta64(2, "s") ).all() # check there is only 1 time < min(ed["Sonar/Beam_group1"]["ping_time"]) assert ( np.count_nonzero( ed["Platform"]["time3"] < ed["Sonar/Beam_group1"]["ping_time"].min() ) <= 1 ) # check times are < max(ed["Sonar/Beam_group1"]["ping_time"]) + 2s assert ( ed["Platform"]["time3"] < ed["Sonar/Beam_group1"]["ping_time"].max() + np.timedelta64(2, "s") ).all() # check there is only 1 time > max(ed["Sonar/Beam_group1"]["ping_time"]) assert ( np.count_nonzero( ed["Platform"]["time3"] > ed["Sonar/Beam_group1"]["ping_time"].max() ) <= 1 ) def test_update_platform_multidim(test_path): raw_file = test_path["EK60"] / "ooi" / "CE02SHBP-MJ01C-07-ZPLSCB101_OOI-D20191201-T000000.raw" ed = echopype.open_raw(raw_file, sonar_model="EK60") extra_platform_data = xr.Dataset( { "lon": (["time"], np.array([-100.0])), "lat": (["time"], np.array([-50.0])), "pitch": (["time_pitch"], np.array([0.1])), "waterlevel": ([], float(10)), }, coords={ "time": (["time"], np.array([ed['Sonar/Beam_group1'].ping_time.values.min()])), "time_pitch": ( ["time_pitch"], # Adding a time delta is not necessary, but it may be handy if we later # want to expand the scope of this test np.array([ed['Sonar/Beam_group1'].ping_time.values.min()]) + np.timedelta64(5, "s") ) }, ) platform_preexisting_dims = ed["Platform"].dims variable_mappings = { "longitude": "lon", "latitude": "lat", "pitch": "pitch", "water_level": "waterlevel" } ed.update_platform(extra_platform_data, variable_mappings=variable_mappings) # Updated variables are not all nan for variable in variable_mappings.keys(): assert not np.isnan(ed["Platform"][variable].values).all() # Number of dimensions in Platform group and addition of time3 and time4 assert len(ed["Platform"].dims) == len(platform_preexisting_dims) + 2 assert "time3" in ed["Platform"].dims assert "time4" in ed["Platform"].dims # Dimension assignment assert ed["Platform"]["longitude"].dims[0] == ed["Platform"]["latitude"].dims[0] assert ed["Platform"]["pitch"].dims[0] != ed["Platform"]["longitude"].dims[0] assert ed["Platform"]["longitude"].dims[0] not in platform_preexisting_dims assert ed["Platform"]["pitch"].dims[0] not in platform_preexisting_dims # scalar variable assert len(ed["Platform"]["water_level"].dims) == 0 @pytest.mark.parametrize( ["variable_mappings"], [ pytest.param( # lat and lon both exist, but aligned on different time dimension: should fail {"longitude": "lon", "latitude": "lat"}, marks=pytest.mark.xfail(strict=True, reason="Fail since lat and lon not on the same time dimension") ), pytest.param( # only lon exists: should fail {"longitude": "lon"}, marks=pytest.mark.xfail(strict=True, reason="Fail since only lon exists without lat") ), ], ids=[ "lat_lon_diff_time", "lon_only" ] ) def test_update_platform_latlon(test_path, variable_mappings): raw_file = test_path["EK60"] / "ooi" / "CE02SHBP-MJ01C-07-ZPLSCB101_OOI-D20191201-T000000.raw" ed = echopype.open_raw(raw_file, sonar_model="EK60") if "latitude" in variable_mappings: extra_platform_data = xr.Dataset( { "lon": (["time1"], np.array([-100.0])), "lat": (["time2"], np.array([-50.0])), }, coords={ "time1": (["time1"], np.array([ed['Sonar/Beam_group1'].ping_time.values.min()])), "time2": (["time2"], np.array([ed['Sonar/Beam_group1'].ping_time.values.min()]) + np.timedelta64(5, "s")), }, ) else: extra_platform_data = xr.Dataset( { "lon": (["time"], np.array([-100.0])), }, coords={ "time": (["time"], np.array([ed['Sonar/Beam_group1'].ping_time.values.min()])), }, ) ed.update_platform(extra_platform_data, variable_mappings=variable_mappings) @pytest.mark.filterwarnings("ignore:No variables will be updated") def test_update_platform_no_update(test_path): raw_file = test_path["EK60"] / "ooi" / "CE02SHBP-MJ01C-07-ZPLSCB101_OOI-D20191201-T000000.raw" ed = echopype.open_raw(raw_file, sonar_model="EK60") extra_platform_data = xr.Dataset( { "lon": (["time"], np.array([-100.0])), "lat": (["time"], np.array([-50.0])), }, coords={ "time": (["time"], np.array([ed['Sonar/Beam_group1'].ping_time.values.min()])), }, ) # variable names in mappings different from actual external dataset variable_mappings = {"longitude": "longitude", "latitude": "latitude"} ed.update_platform(extra_platform_data, variable_mappings=variable_mappings)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,835
OSOceanAcoustics/echopype
refs/heads/main
/echopype/qc/api.py
from typing import List, Optional import numpy as np import xarray as xr from ..echodata import EchoData from ..utils.log import _init_logger logger = _init_logger(__name__) def _clean_reversed(time_old: np.ndarray, win_len: int): time_old_diff = np.diff(time_old) # get indices of arr_diff with negative values neg_idx = np.argwhere(time_old_diff < np.timedelta64(0, "ns")).flatten() # substitute out the reversed timestamp using the previous one new_diff = [] for ni in neg_idx: local_win_idx = ni + np.arange(-win_len, 0) if local_win_idx[0] < 0: first_valid_idx = np.argwhere(local_win_idx == 0).flatten()[0] local_win_idx = local_win_idx[first_valid_idx:] new_diff.append(np.median(time_old_diff[local_win_idx])) time_old_diff[neg_idx] = new_diff # perform cumulative sum of differences after 1st neg index c_diff = np.cumsum(time_old_diff[neg_idx[0] :], axis=0) # create new array that preserves differences, but enforces increasing vals new_time = time_old.copy() new_time[neg_idx[0] + 1 :] = new_time[neg_idx[0]] + c_diff return new_time def coerce_increasing_time( ds: xr.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 ---------- ds : xr.Dataset a dataset for which the time coordinate needs to be corrected time_name : str name of the time coordinate to be corrected win_len : int 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. """ ds[time_name].data[:] = _clean_reversed(ds[time_name].data, win_len) def exist_reversed_time(ds, time_name): """Test for occurrence of time reversal in specified datetime coordinate variable. Parameters ---------- ds : xr.Dataset a dataset for which the time coordinate will be tested time_name : str name of the time coordinate to be tested Returns ------- `True` if at least one time reversal is found, `False` otherwise. """ return (np.diff(ds[time_name]) < np.timedelta64(0, "ns")).any() def check_and_correct_reversed_time( combined_group: xr.Dataset, time_str: str, ed_group: str ) -> Optional[xr.DataArray]: """ Makes sure that the time coordinate ``time_str`` in ``combined_group`` is in the correct order and corrects it, if it is not. If coercion is necessary, the input `combined_group` will be directly modified. Parameters ---------- combined_group : xr.Dataset Dataset representing a combined EchoData group time_str : str Name of time coordinate to be checked and corrected ed_group : str Name of ``EchoData`` group name Returns ------- old_time : xr.DataArray or None If correction is necessary, returns the time before reversal correction, otherwise returns None Warns ----- UserWarning If a time reversal is detected """ if time_str in combined_group and exist_reversed_time(combined_group, time_str): logger.warning( f"{ed_group} {time_str} reversal detected; {time_str} will be corrected" # noqa " (see https://github.com/OSOceanAcoustics/echopype/pull/297)" ) old_time = combined_group[time_str].copy() coerce_increasing_time(combined_group, time_name=time_str) else: old_time = None return old_time def create_old_time_array(group: str, old_time_in: xr.DataArray) -> xr.DataArray: """ Creates an old time array with the appropriate values, name, attributes, and encoding. Parameters ---------- group: str The name of the ``EchoData`` group that contained the old time old_time_in: xr.DataArray The uncorrected old time Returns ------- old_time_array: xr.DataArray The newly created old time array """ # make a copy, so we don't change the source array old_time = old_time_in.copy() # get name of old time and dim for Provenance group ed_name = group.replace("-", "_").replace("/", "_").lower() old_time_name = ed_name + "_old_" + old_time.name old_time_name_dim = old_time_name + "_dim" # construct old time attributes attributes = old_time.attrs attributes["comment"] = f"Uncorrected {old_time.name} from the combined group {group}." # create old time array old_time_array = xr.DataArray( data=old_time.values, dims=[old_time_name_dim], attrs=attributes, name=old_time_name ) # set encodings old_time_array.encoding = old_time.encoding return old_time_array def orchestrate_reverse_time_check( ed_comb: EchoData, zarr_store: str, possible_time_dims: List[str], storage_options: dict, consolidated: bool = True, ) -> None: """ Performs a reverse time check of all groups and each time dimension within the group. If a reversed time is found it will be corrected in ``ed_comb``, updated in the zarr store, the old time will be added to the ``Provenance`` group in ``ed_comb``, the old time will be written to the zarr store, and the attribute ``reversed_ping_times`` in the ``Provenance`` group will be set to ``1``. Parameters ---------- ed_comb: EchoData ``EchoData`` object that has been constructed from combined ``EchoData`` objects zarr_store: str The zarr store containing the ``ed_comb`` data possible_time_dims: list of str All possible time dimensions that can occur within ``ed_comb``, which should be checked storage_options: dict Additional keywords to pass to the filesystem class. consolidated : bool Flag to consolidate zarr metadata. Defaults to ``True`` Notes ----- If correction is necessary, ``ed_comb`` will be directly modified. """ # set Provenance attribute to zero in ed_comb ed_comb["Provenance"].attrs["reversed_ping_times"] = 0 # set Provenance attribute to zero in zarr (Dataset needed for metadata creation) only_attrs_ds = xr.Dataset(attrs=ed_comb["Provenance"].attrs) only_attrs_ds.to_zarr( zarr_store, group="Provenance", mode="a", storage_options=storage_options, consolidated=consolidated, ) for group in ed_comb.group_paths: if group != "Platform/NMEA": # Platform/NMEA is skipped because we found that the times which correspond to # other non-GPS messages are often out of order and correcting them is not # possible with the current implementation of _clean_ping_time in qc.api due # to excessive recursion. There is also no obvious advantage in correcting # the order of these timestamps. # get all time dimensions of the group ed_comb_time_dims = set(ed_comb[group].dims).intersection(possible_time_dims) for time in ed_comb_time_dims: old_time = check_and_correct_reversed_time( combined_group=ed_comb[group], time_str=time, ed_group=group ) if old_time is not None: old_time_array = create_old_time_array(group, old_time) # put old times in Provenance and modify attribute ed_comb["Provenance"][old_time_array.name] = old_time_array ed_comb["Provenance"].attrs["reversed_ping_times"] = 1 # save old time to zarr store old_time_ds = old_time_array.to_dataset() old_time_ds.attrs = ed_comb["Provenance"].attrs old_time_ds.to_zarr( zarr_store, group="Provenance", mode="a", storage_options=storage_options, consolidated=consolidated, ) # save corrected time to zarr store ed_comb[group][[time]].to_zarr( zarr_store, group=group, mode="r+", storage_options=storage_options, consolidated=consolidated, )
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,836
OSOceanAcoustics/echopype
refs/heads/main
/echopype/visualize/__init__.py
""" Visualization module to quickly plot raw, Sv, and MVBS dataset. **NOTE: To use this subpackage. `Matplotlib` and `cmocean` package must be installed.** """ from .api import create_echogram from . import cm __all__ = ["create_echogram", "cm"]
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,837
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/qc/test_qc.py
import numpy as np import xarray as xr from echopype.qc import coerce_increasing_time, exist_reversed_time from echopype.qc.api import _clean_reversed import pytest @pytest.fixture def ds_time(): return xr.Dataset( data_vars={"a": ("time", np.arange(36))}, coords={ "time": np.array([ '2021-07-15T22:59:54.328000000', '2021-07-15T22:59:54.598000128', '2021-07-15T22:59:54.824999936', '2021-07-15T22:59:55.170999808', '2021-07-15T22:59:56.172999680', '2021-07-15T22:59:55.467999744', '2021-07-15T22:59:55.737999872', '2021-07-15T22:59:55.966000128', '2021-07-15T22:59:56.467999744', '2021-07-15T22:59:56.813000192', '2021-07-15T22:59:57.040999936', '2021-07-15T22:59:57.178999808', '2021-07-15T22:59:58.178999808', '2021-07-15T22:59:57.821000192', '2021-07-15T22:59:58.092000256', '2021-07-15T22:59:58.318999552', '2021-07-15T22:59:58.730999808', '2021-07-15T22:59:59.092000256', '2021-07-15T22:59:59.170999808', '2021-07-15T23:00:00.170999808', '2021-07-15T23:00:01.170999808', '2021-07-15T22:59:59.719000064', '2021-07-15T22:59:59.989999616', '2021-07-15T23:00:00.573000192', '2021-07-15T23:00:00.843999744', '2021-07-15T23:00:01.071000064', '2021-07-15T23:00:02.170999808', '2021-07-15T23:00:03.181000192', '2021-07-15T23:00:01.692999680', '2021-07-15T23:00:02.054000128', '2021-07-15T23:00:02.592999936', '2021-07-15T23:00:02.864000000', '2021-07-15T23:00:03.480999936', '2021-07-15T23:00:04.171999744', '2021-07-15T23:00:05.179999744', '2021-07-15T23:00:03.771999744'], dtype='datetime64[ns]') }, ) @pytest.mark.parametrize( ["win_len", "input_arr", "expected_arr"], [ ( 2, np.array([0,1,2,3,4,2,3,4,6,8,10,11,12,13,15,17,19,13,15,17,21], dtype="datetime64[ns]"), np.array([0,1,2,3,4,5,6,7,9,11,13,14,15,16,18,20,22,24,26,28,32], dtype="datetime64[ns]") ), ( 6, (np.array([0,1,2,3,4,2,3,4,6,8,10,11,12,13,15,17,19,13,15,17,21])*2).astype("datetime64[ns]"), np.array([0,2,4,6,8,10,12,14,18,22,26,28,30,32,36,40,44,47,51,55,63]).astype("datetime64[ns]"), ), ], ids=[ "win_len2", "win_len6" ] ) def test__clean_reversed(win_len, input_arr, expected_arr): arr_fixed = _clean_reversed(input_arr, win_len) # fixed array follows monotonically increasing order arr_fixed_diff = np.diff(arr_fixed) assert np.argwhere(arr_fixed_diff < np.timedelta64(0, "ns")).flatten().size == 0 # new filled value should have diff being the median of local_win_len before reversal assert np.all(arr_fixed == expected_arr) def test_coerce_increasing_time(ds_time): # fixed timestamp follows monotonically increasing order coerce_increasing_time(ds_time, "time") assert np.argwhere(ds_time["time"].diff(dim="time").data < np.timedelta64(0, "ns")).flatten().size == 0 def test_exist_reversed_time(ds_time): # data has reversed timestamps to begin with assert exist_reversed_time(ds_time, "time") == True # after correction there are no reversed timestamps coerce_increasing_time(ds_time, "time") assert exist_reversed_time(ds_time, "time") == False
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,838
OSOceanAcoustics/echopype
refs/heads/main
/echopype/core.py
import os import re from typing import TYPE_CHECKING, Any, Callable, Dict, Union from fsspec.mapping import FSMap from typing_extensions import Literal from .convert.parse_ad2cp import ParseAd2cp from .convert.parse_azfp import ParseAZFP from .convert.parse_ek60 import ParseEK60 from .convert.parse_ek80 import ParseEK80 from .convert.parsed_to_zarr_ek60 import Parsed2ZarrEK60 from .convert.parsed_to_zarr_ek80 import Parsed2ZarrEK80 from .convert.set_groups_ad2cp import SetGroupsAd2cp from .convert.set_groups_azfp import SetGroupsAZFP from .convert.set_groups_ek60 import SetGroupsEK60 from .convert.set_groups_ek80 import SetGroupsEK80 if TYPE_CHECKING: # Please keep SonarModelsHint updated with the keys of the SONAR_MODELS dict SonarModelsHint = Literal["AZFP", "EK60", "ES70", "EK80", "ES80", "EA640", "AD2CP"] PathHint = Union[str, os.PathLike, FSMap] FileFormatHint = Literal[".nc", ".zarr"] EngineHint = Literal["netcdf4", "zarr"] def validate_azfp_ext(test_ext: str): if not re.fullmatch(r"\.\d{2}[a-zA-Z]", test_ext): raise ValueError( 'Expecting a file in the form ".XXY" ' f"where XX is a number and Y is a letter but got {test_ext}" ) def validate_ext(ext: str) -> Callable[[str], None]: def inner(test_ext: str): if ext.casefold() != test_ext.casefold(): raise ValueError(f"Expecting a {ext} file but got {test_ext}") return inner SONAR_MODELS: Dict["SonarModelsHint", Dict[str, Any]] = { "AZFP": { "validate_ext": validate_azfp_ext, "xml": True, "parser": ParseAZFP, "parsed2zarr": None, "set_groups": SetGroupsAZFP, "dgram_zarr_vars": {}, }, "EK60": { "validate_ext": validate_ext(".raw"), "xml": False, "parser": ParseEK60, "parsed2zarr": Parsed2ZarrEK60, "set_groups": SetGroupsEK60, "dgram_zarr_vars": {"power": ["timestamp", "channel"], "angle": ["timestamp", "channel"]}, }, "ES70": { "validate_ext": validate_ext(".raw"), "xml": False, "parser": ParseEK60, "parsed2zarr": Parsed2ZarrEK60, "set_groups": SetGroupsEK60, "dgram_zarr_vars": {"power": ["timestamp", "channel"], "angle": ["timestamp", "channel"]}, }, "EK80": { "validate_ext": validate_ext(".raw"), "xml": False, "parser": ParseEK80, "parsed2zarr": Parsed2ZarrEK80, "set_groups": SetGroupsEK80, "dgram_zarr_vars": { "power": ["timestamp", "channel_id"], "complex": ["timestamp", "channel_id"], "angle": ["timestamp", "channel_id"], }, }, "ES80": { "validate_ext": validate_ext(".raw"), "xml": False, "parser": ParseEK80, "parsed2zarr": Parsed2ZarrEK80, "set_groups": SetGroupsEK80, "dgram_zarr_vars": { "power": ["timestamp", "channel_id"], "complex": ["timestamp", "channel_id"], "angle": ["timestamp", "channel_id"], }, }, "EA640": { "validate_ext": validate_ext(".raw"), "xml": False, "parser": ParseEK80, "parsed2zarr": Parsed2ZarrEK80, "set_groups": SetGroupsEK80, "dgram_zarr_vars": { "power": ["timestamp", "channel_id"], "complex": ["timestamp", "channel_id"], "angle": ["timestamp", "channel_id"], }, }, "AD2CP": { "validate_ext": validate_ext(".ad2cp"), "xml": False, "parser": ParseAd2cp, "parsed2zarr": None, "set_groups": SetGroupsAd2cp, "dgram_zarr_vars": {}, }, }
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,839
OSOceanAcoustics/echopype
refs/heads/main
/echopype/convert/parse_ek60.py
from .parse_base import ParseEK class ParseEK60(ParseEK): """Class for converting data from Simrad EK60 echosounders.""" def __init__(self, file, params, storage_options={}, dgram_zarr_vars={}): super().__init__(file, params, storage_options, dgram_zarr_vars) def _select_datagrams(self, params): # Translates user input into specific datagrams or ALL if params == "ALL": return ["ALL"] elif params == "GPS": return ["NME"] else: raise ValueError("Unknown data type", params)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,840
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/calibrate/test_cal_params.py
import pytest import numpy as np import xarray as xr from echopype.calibrate.cal_params import ( CAL_PARAMS, param2da, sanitize_user_cal_dict, _get_interp_da, get_cal_params_AZFP, get_cal_params_EK, get_vend_cal_params_power ) @pytest.fixture def freq_center(): return xr.DataArray( [[25, 55]], dims=["ping_time", "channel"], coords={"channel": ["chA", "chB"], "ping_time": [1]} ) @pytest.fixture def vend_AZFP(): """ A mock AZFP Vendor_specific group for cal testing. """ da = xr.DataArray([10, 20], dims=["channel"], coords={"channel": ["chA", "chB"]}) vend = xr.Dataset() for p_name in CAL_PARAMS["AZFP"]: if p_name != "equivalent_beam_angle": da.name = p_name vend[p_name] = da return vend @pytest.fixture def beam_AZFP(): """ A mock AZFP Sonar/Beam_group1 group for cal testing. """ beam = xr.Dataset() beam["equivalent_beam_angle"] = xr.DataArray( [[10, 20]], dims=["ping_time", "channel"], coords={"channel": ["chA", "chB"], "ping_time": [1]}, ) return beam.transpose("channel", "ping_time") @pytest.fixture def vend_EK(): """ A mock EK Sonar/Beam_groupX group for cal testing. """ vend = xr.Dataset() for p_name in ["sa_correction", "gain_correction"]: vend[p_name] = xr.DataArray( np.array([[10, 20, 30, 40], [110, 120, 130, 140]]), dims=["channel", "pulse_length_bin"], coords={"channel": ["chA", "chB"], "pulse_length_bin": [0, 1, 2, 3]}, ) vend["pulse_length"] = xr.DataArray( np.array([[64, 128, 256, 512], [128, 256, 512, 1024]]), coords={"channel": vend["channel"], "pulse_length_bin": vend["pulse_length_bin"]} ) vend["impedance_transceiver"] = xr.DataArray( [1000, 2000], coords={"channel": vend["channel"]} ) vend["transceiver_type"] = xr.DataArray( ["WBT", "WBT"], coords={"channel": vend["channel"]} ) return vend @pytest.fixture def beam_EK(): """ A mock EK Sonar/Beam_groupX group for cal testing. """ beam = xr.Dataset() for p_name in [ "equivalent_beam_angle", "angle_offset_alongship", "angle_offset_athwartship", "angle_sensitivity_alongship", "angle_sensitivity_athwartship", "beamwidth_twoway_alongship", "beamwidth_twoway_athwartship" ]: beam[p_name] = xr.DataArray( np.array([[123], [456]]), dims=["channel", "ping_time"], coords={"channel": ["chA", "chB"], "ping_time": [1]}, ) beam["frequency_nominal"] = xr.DataArray([25, 55], dims=["channel"], coords={"channel": ["chA", "chB"]}) return beam.transpose("channel", "ping_time") @pytest.mark.parametrize( ("p_val", "channel", "da_output"), [ # input p_val a scalar, input channel a list (1, ["chA", "chB"], xr.DataArray([1, 1], dims=["channel"], coords={"channel": ["chA", "chB"]})), # input p_val a list, input channel an xr.DataArray ( [1, 2], xr.DataArray(["chA", "chB"], dims=["channel"], coords={"channel": ["chA", "chB"]}), xr.DataArray([1, 2], dims=["channel"], coords={"channel": ["chA", "chB"]}) ), # input p_val a list with the wrong length: this should fail pytest.param( [1, 2, 3], ["chA", "chB"], None, marks=pytest.mark.xfail(strict=True, reason="Fail since lengths of p_val and channel are not identical") ), ], ids=[ "in_p_val_scalar_channel_list", "in_p_val_list_channel_xrda", "in_p_val_list_wrong_length", ] ) def test_param2da(p_val, channel, da_output): da_assembled = param2da(p_val, channel) assert da_assembled.identical(da_output) @pytest.mark.parametrize( ("sonar_type", "user_dict", "channel", "out_dict"), [ # sonar_type only allows EK or AZFP pytest.param( "XYZ", None, None, None, marks=pytest.mark.xfail(strict=True, reason="Fail since sonar_type is not 'EK' nor 'AZFP'") ), # input channel # - is not a list nor an xr.DataArray: fail with value error pytest.param( "EK80", 1, None, None, marks=pytest.mark.xfail(strict=True, reason="Fail since channel has to be either a list or an xr.DataArray"), ), # TODO: input channel has different order than those in the inarg channel # input param dict # - contains extra param: should come out with only those defined in CAL_PARAMS # - contains missing param: missing ones (wrt CAL_PARAMS) should be empty pytest.param("EK80", {"extra_param": 1}, ["chA", "chB"], dict.fromkeys(CAL_PARAMS["EK80"])), # input param: # - is xr.DataArray without channel coorindate: fail with value error pytest.param( "EK80", {"sa_correction": xr.DataArray([1, 1], dims=["some_coords"], coords={"some_coords": ["A", "B"]})}, ["chA", "chB"], None, marks=pytest.mark.xfail(strict=True, reason="input sa_correction does not contain a 'channel' coordinate"), ), # input individual param: # - with channel cooridinate but not identical to argin channel: fail with value error pytest.param( "EK80", {"sa_correction": xr.DataArray([1, 1], dims=["channel"], coords={"channel": ["chA", "B"]})}, ["chA", "chB"], None, marks=pytest.mark.xfail(strict=True, reason="input sa_correction contains a 'channel' coordinate but it is not identical with input channel"), ), # input individual param: # - with channel cooridinate identical to argin channel: should pass pytest.param( "EK80", {"sa_correction": xr.DataArray([1, 1], dims=["channel"], coords={"channel": ["chA", "chB"]})}, ["chA", "chB"], dict(dict.fromkeys(CAL_PARAMS["EK80"]), **{"sa_correction": xr.DataArray([1, 1], dims=["channel"], coords={"channel": ["chA", "chB"]})}), ), # input individual param: # - a scalar needing to be organized to xr.DataArray at output via param2da: should pass pytest.param( "EK80", {"sa_correction": 1}, ["chA", "chB"], dict(dict.fromkeys(CAL_PARAMS["EK80"]), **{"sa_correction": xr.DataArray([1, 1], dims=["channel"], coords={"channel": ["chA", "chB"]})}), ), # input individual param: # - a list needing to be organized to xr.DataArray at output via param2da: should pass pytest.param( "EK80", {"sa_correction": [1, 2]}, ["chA", "chB"], dict(dict.fromkeys(CAL_PARAMS["EK80"]), **{"sa_correction": xr.DataArray([1, 2], dims=["channel"], coords={"channel": ["chA", "chB"]})}), ), # input individual param: # - a list with wrong length (ie not identical to channel): fail with value error pytest.param( "EK80", {"sa_correction": [1, 2, 3]}, ["chA", "chB"], None, marks=pytest.mark.xfail(strict=True, reason="input sa_correction contains a list of wrong length that does not match that of channel"), ), ], ids=[ "sonar_type_invalid", "channel_invalid", "in_extra_param", "in_da_no_channel_coord", "in_da_channel_not_identical", "in_da_channel_identical", "in_scalar", "in_list", "in_list_wrong_length", ], ) def test_sanitize_user_cal_dict(sonar_type, user_dict, channel, out_dict): sanitized_dict = sanitize_user_cal_dict(sonar_type, user_dict, channel) assert isinstance(sanitized_dict, dict) assert len(sanitized_dict) == len(out_dict) for p_name, p_val in sanitized_dict.items(): if isinstance(p_val, xr.DataArray): assert p_val.identical(out_dict[p_name]) else: assert p_val == out_dict[p_name] @pytest.mark.parametrize( ("da_param", "alternative", "da_output"), [ # da_param: alternative is const: output is xr.DataArray with all const ( None, 1, xr.DataArray([[1], [1]], dims=["channel", "ping_time"], coords={"channel": ["chA", "chB"], "ping_time": [1]}) ), # da_param: alternative is xr.DataArray: output selected with the right channel ( None, xr.DataArray([1, 1, 2], dims=["channel"], coords={"channel": ["chA", "chB", "chC"]}), xr.DataArray([[1], [1]], dims=["channel", "ping_time"], coords={"channel": ["chA", "chB"], "ping_time": [1]}) ), # da_param: xr.DataArray with freq-dependent values/coordinates # - output should be interpolated with the right values ( xr.DataArray( np.array([[1, 2, 3, np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan, 4, 5, 6], [np.nan, 2, 3, 4, np.nan, np.nan]]), dims=["cal_channel_id", "cal_frequency"], coords={"cal_channel_id": ["chA", "chB", "chC"], "cal_frequency": [10, 20, 30, 40, 50, 60]}, ), None, xr.DataArray([[2.5], [5.5]], dims=["channel", "ping_time"], coords={"ping_time": [1], "channel": ["chA", "chB"]}), ), # da_param: xr.DataArray with only one channel having freq-dependent values/coordinates # - that single channel should be interpolated with the right value # - other channels will use alternative # - alternative could be of the following form: # - scalar ( xr.DataArray( np.array([[np.nan, np.nan, np.nan, 4, 5, 6]]), dims=["cal_channel_id", "cal_frequency"], coords={"cal_channel_id": ["chB"], "cal_frequency": [10, 20, 30, 40, 50, 60]}, ), 75, xr.DataArray( [[75], [5.5]], dims=["channel", "ping_time"], coords={"ping_time": [1], "channel": ["chA", "chB"]} ), ), # - xr.DataArray with coordinates channel, ping_time ( xr.DataArray( np.array([[np.nan, np.nan, np.nan, 4, 5, 6]]), dims=["cal_channel_id", "cal_frequency"], coords={"cal_channel_id": ["chB"], "cal_frequency": [10, 20, 30, 40, 50, 60]}, ), xr.DataArray( np.array([[100], [200]]), dims=["channel", "ping_time"], coords={"ping_time": [1], "channel": ["chA", "chB"]}, ), xr.DataArray( [[100], [5.5]], dims=["channel", "ping_time"], coords={"ping_time": [1], "channel": ["chA", "chB"]} ), # TODO: cases where freq_center does not have the ping_time dimension # this is the case for CW data since freq_center = beam["frequency_nominal"] # this was caught by the file in test_compute_Sv_ek80_CW_complex() # TODO: cases where freq_center contains only a single frequency # in this case had to use freq_center.sel(channel=ch_id).size because # len(freq_center.sel(channel=ch_id)) is an invalid statement # this was caught by the file in test_compute_Sv_ek80_CW_power_BB_complex() ), ], ids=[ "in_None_alt_const", "in_None_alt_da", "in_da_all_channel_out_interp", "in_da_some_channel_alt_scalar", "in_da_some_channel_alt_da2coords", # channel, ping_time ] ) def test_get_interp_da(freq_center, da_param, alternative, da_output): da_interp = _get_interp_da(da_param, freq_center, alternative) assert da_interp.identical(da_output) @pytest.mark.parametrize( ("user_dict", "out_dict"), [ # input param is a scalar ( {"EL": 1, "equivalent_beam_angle": 2}, dict( {p_name: xr.DataArray([10, 20], dims=["channel"], coords={"channel": ["chA", "chB"]}) for p_name in CAL_PARAMS["AZFP"]}, **{ "EL": xr.DataArray([1, 1], dims=["channel"], coords={"channel": ["chA", "chB"]}), "equivalent_beam_angle": xr.DataArray([2, 2], dims=["channel"], coords={"channel": ["chA", "chB"]}), } ), ), # input param is a list ( {"EL": [1, 2], "equivalent_beam_angle": [3, 4]}, dict( {p_name: xr.DataArray([10, 20], dims=["channel"], coords={"channel": ["chA", "chB"]}) for p_name in CAL_PARAMS["AZFP"]}, **{ "EL": xr.DataArray([1, 2], dims=["channel"], coords={"channel": ["chA", "chB"]}), "equivalent_beam_angle": xr.DataArray([3, 4], dims=["channel"], coords={"channel": ["chA", "chB"]}), } ), ), # input param is a list of wrong length: this should fail pytest.param( {"EL": [1, 2, 3], "equivalent_beam_angle": [3, 4]}, None, marks=pytest.mark.xfail(strict=True, reason="Fail since lengths of input list and channel are not identical"), ), # input param is an xr.DataArray with coordinate 'channel' ( { "EL": xr.DataArray([1, 2], dims=["channel"], coords={"channel": ["chA", "chB"]}), "equivalent_beam_angle": xr.DataArray([3, 4], dims=["channel"], coords={"channel": ["chA", "chB"]}), }, dict( {p_name: xr.DataArray([10, 20], dims=["channel"], coords={"channel": ["chA", "chB"]}) for p_name in CAL_PARAMS["AZFP"]}, **{ "EL": xr.DataArray([1, 2], dims=["channel"], coords={"channel": ["chA", "chB"]}), "equivalent_beam_angle": xr.DataArray([3, 4], dims=["channel"], coords={"channel": ["chA", "chB"]}), } ), ), # input param is an xr.DataArray with coordinate 'channel' but wrong length: this should fail pytest.param( { "EL": xr.DataArray([1, 2, 3], dims=["channel"], coords={"channel": ["chA", "chB", "chC"]}), "equivalent_beam_angle": xr.DataArray([3, 4, 5], dims=["channel"], coords={"channel": ["chA", "chB", "chC"]}), }, None, marks=pytest.mark.xfail(strict=True, reason="Fail since lengths of input data array channel and data channel are not identical"), ), ], ids=[ "in_scalar", "in_list", "in_list_wrong_length", "in_da", "in_da_wrong_length", ] ) def test_get_cal_params_AZFP(beam_AZFP, vend_AZFP, user_dict, out_dict): cal_dict = get_cal_params_AZFP(beam=beam_AZFP, vend=vend_AZFP, user_dict=user_dict) for p_name, p_val in cal_dict.items(): # remove name for all da p_val.name = None out_val = out_dict[p_name] out_val.name = None assert p_val.identical(out_val) # The test above 'test_get_cal_params_AZFP' covers the cases where user input param # is one of the following: a scalar, list, and xr.DataArray of coords/dims ('channel') # Here we only test for the following new cases: # - where all params are input by user # - input xr.DataArray has coords/dims (cal_channel_id, cal_frequency) @pytest.mark.parametrize( ("user_dict", "out_dict", "freq_center_scaling"), [ # input xr.DataArray has coords/dims (cal_channel_id, cal_frequency) # no freq-related scaling: freq_center = beam_EK["frequency_nominal"] ( { "gain_correction": xr.DataArray( np.array([[1, 2, 3, np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan, 4, 5, 6]]), dims=["cal_channel_id", "cal_frequency"], coords={"cal_channel_id": ["chA", "chB"], "cal_frequency": [10, 20, 30, 40, 50, 60]}, ), # add sa_correction here to bypass things going into get_vend_cal_params_power "sa_correction": xr.DataArray( np.array([111, 222]), dims=["channel"], coords={"channel": ["chA", "chB"]}, ), }, dict( { p_name: xr.DataArray( [[123], [456]], dims=["channel", "ping_time"], coords={"channel": ["chA", "chB"], "ping_time": [1]}, ) for p_name in CAL_PARAMS["EK80"] }, **{ "gain_correction": xr.DataArray( [[2.5], [5.5]], dims=["channel", "ping_time"], coords={"ping_time": [1], "channel": ["chA", "chB"]}, ), "sa_correction": xr.DataArray( np.array([111, 222]), dims=["channel"], coords={"channel": ["chA", "chB"]} ), "impedance_transducer": xr.DataArray( np.array([[75], [75]]), dims=["channel", "ping_time"], coords={"channel": ["chA", "chB"], "ping_time": [1]} ), "impedance_transceiver": xr.DataArray( np.array([1000, 2000]), dims=["channel"], coords={"channel": ["chA", "chB"]} ), "receiver_sampling_frequency": xr.DataArray( np.array([1500000, 1500000]), dims=["channel"], coords={"channel": ["chA", "chB"]} ), }, ), 1, # no scaling of freq_center ), # input xr.DataArray has coords/dims (cal_channel_id, cal_frequency) # with freq-related scaling: freq_center != beam_EK["frequency_nominal"] ( { "gain_correction": xr.DataArray( np.array([[1, 2, 3, np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan, 4, 5, 6]]), dims=["cal_channel_id", "cal_frequency"], coords={"cal_channel_id": ["chA", "chB"], "cal_frequency": [10, 20, 30, 40, 50, 60]}, ), # add sa_correction here to bypass things going into get_vend_cal_params_power "sa_correction": xr.DataArray( np.array([111, 222]), dims=["channel"], coords={"channel": ["chA", "chB"]}, ), }, dict( { p_name: xr.DataArray( [[123], [456]], dims=["channel", "ping_time"], coords={"channel": ["chA", "chB"], "ping_time": [1]}, ) for p_name in CAL_PARAMS["EK80"] }, **{ "gain_correction": xr.DataArray( np.array([[2.5], [5.5]]) * 0.79, # scaled by the factor as freq_center in function body dims=["channel", "ping_time"], coords={"ping_time": [1], "channel": ["chA", "chB"]}, ), "sa_correction": xr.DataArray( np.array([111, 222]), dims=["channel"], coords={"channel": ["chA", "chB"]} ), "impedance_transducer": xr.DataArray( np.array([[75], [75]]), dims=["channel", "ping_time"], coords={"channel": ["chA", "chB"], "ping_time": [1]} ), "impedance_transceiver": xr.DataArray( np.array([1000, 2000]), dims=["channel"], coords={"channel": ["chA", "chB"]} ), "receiver_sampling_frequency": xr.DataArray( np.array([1500000, 1500000]), dims=["channel"], coords={"channel": ["chA", "chB"]} ), }, ), 0.79, # with scaling of freq_center ), pytest.param( { "gain_correction": xr.DataArray( np.array([[1, 2, 3, np.nan], [np.nan, 4, 5, 6], [np.nan, 2, 3, np.nan]]), dims=["cal_channel_id", "cal_frequency"], coords={"cal_channel_id": ["chA", "chB", "chC"], "cal_frequency": [10, 20, 30, 40]}, ), }, None, 1, marks=pytest.mark.xfail(strict=True, reason="Fail since cal_channel_id in input param does not match channel of data"), ), ], ids=[ "in_da_freq_dep_no_scaling", "in_da_freq_dep_with_scaling", "in_da_freq_dep_channel_mismatch", ] ) def test_get_cal_params_EK80_BB(beam_EK, vend_EK, freq_center, user_dict, out_dict, freq_center_scaling): # If freq_center != beam_EK["frequency_nominal"], the following params will be scaled: # - angle_sensitivity_alongship/athwartship (by fc/fn) # - beamwidth_alongship/athwartship (by fn/fc) # - equivalent_beam_angle (by (fn/fc)^2) freq_center = freq_center * freq_center_scaling # scale by an arbitrary number for p in ["angle_sensitivity_alongship", "angle_sensitivity_athwartship"]: out_dict[p] = out_dict[p] * freq_center / beam_EK["frequency_nominal"] for p in ["beamwidth_alongship", "beamwidth_athwartship"]: out_dict[p] = out_dict[p] * beam_EK["frequency_nominal"] / freq_center out_dict["equivalent_beam_angle"] = ( out_dict["equivalent_beam_angle"] + 20 * np.log10(beam_EK["frequency_nominal"] / freq_center) ) cal_dict = get_cal_params_EK( waveform_mode="BB", freq_center=freq_center, beam=beam_EK, vend=vend_EK, user_dict=user_dict ) for p_name, p_val in cal_dict.items(): print(p_name) # remove name for all da p_val.name = None out_val = out_dict[p_name] out_val.name = None assert p_val.identical(out_dict[p_name]) @pytest.mark.parametrize( ("user_dict", "out_dict"), [ # cal_params should not contain: # impedance_transducer, impedance_transceiver, receiver_sampling_frequency ( { # add sa_correction here to bypass things going into get_vend_cal_params_power "gain_correction": xr.DataArray( [555, 777], dims=["channel"], coords={"channel": ["chA", "chB"]}, ), # add sa_correction here to bypass things going into get_vend_cal_params_power "sa_correction": xr.DataArray( [111, 222], dims=["channel"], coords={"channel": ["chA", "chB"]}, ) }, dict( { p_name: xr.DataArray( [[123], [456]], dims=["channel", "ping_time"], coords={"channel": ["chA", "chB"], "ping_time": [1]}, ) for p_name in [ "sa_correction", "gain_correction", "equivalent_beam_angle", "angle_offset_alongship", "angle_offset_athwartship", "angle_sensitivity_alongship", "angle_sensitivity_athwartship", "beamwidth_alongship", "beamwidth_athwartship", ] }, **{ "gain_correction": xr.DataArray( [555, 777], dims=["channel"], coords={"channel": ["chA", "chB"]}, ), "sa_correction": xr.DataArray( [111, 222], dims=["channel"], coords={"channel": ["chA", "chB"]} ), }, ), ), ], ids=[ "in_da", ] ) def test_get_cal_params_EK60(beam_EK, vend_EK, freq_center, user_dict, out_dict): # Remove some variables from Vendor group to mimic EK60 data vend_EK = vend_EK.drop("impedance_transceiver").drop("transceiver_type") cal_dict = get_cal_params_EK( waveform_mode="CW", freq_center=freq_center, beam=beam_EK, vend=vend_EK, user_dict=user_dict, sonar_type="EK60" ) for p_name, p_val in cal_dict.items(): # remove name for all da p_val.name = None out_val = out_dict[p_name] out_val.name = None assert p_val.identical(out_dict[p_name]) @pytest.mark.parametrize( ("param", "beam", "da_output"), [ # no NaN entry in transmit_duration_nominal ( "sa_correction", xr.DataArray( np.array([[64, 256, 128, 512], [512, 1024, 256, 128]]).T, dims=["ping_time", "channel"], coords={"ping_time": [1, 2, 3, 4], "channel": ["chA", "chB"]}, name="transmit_duration_nominal", ).to_dataset(), xr.DataArray( np.array([[10, 30, 20, 40], [130, 140, 120, 110]]).T, dims=["ping_time", "channel"], coords={"ping_time": [1, 2, 3, 4], "channel": ["chA", "chB"]}, name="sa_correction", ).astype(np.float64), ), # with NaN entry in transmit_duration_nominal ( "sa_correction", xr.DataArray( np.array([[64, np.nan, 128, 512], [512, 1024, 256, np.nan]]).T, dims=["ping_time", "channel"], coords={"ping_time": [1, 2, 3, 4], "channel": ["chA", "chB"]}, name="transmit_duration_nominal", ).to_dataset(), xr.DataArray( np.array([[10, np.nan, 20, 40], [130, 140, 120, np.nan]]).T, dims=["ping_time", "channel"], coords={"ping_time": [1, 2, 3, 4], "channel": ["chA", "chB"]}, name="sa_correction", ), ), ], ids=[ "in_no_nan", "in_with_nan", ] ) def test_get_vend_cal_params_power(vend_EK, beam, param, da_output): da_param = get_vend_cal_params_power(beam, vend_EK, param) assert da_param.identical(da_output)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,841
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/calibrate/test_ecs.py
import pytest from datetime import datetime import numpy as np import xarray as xr from echopype.calibrate.ecs import ECSParser, ecs_ev2ep, conform_channel_order @pytest.fixture def ecs_path(test_path): return test_path['ECS'] CORRECT_PARSED_PARAMS = { "fileset": { "SoundSpeed": 1496.0, "TvgRangeCorrection": "BySamples", "TvgRangeCorrectionOffset": 2.0, }, "sourcecal": { "T1": { "AbsorptionCoefficient": 0.002822, "EK60SaCorrection": -0.7, "Ek60TransducerGain": 22.95, "Frequency": 18.00, "MajorAxis3dbBeamAngle": 10.82, "MajorAxisAngleOffset": 0.25, "MajorAxisAngleSensitivity": 13.89, "MinorAxis3dbBeamAngle": 10.9, "MinorAxisAngleOffset": -0.18, "MinorAxisAngleSensitivity": 13.89, "SoundSpeed": 1480.6, "TwoWayBeamAngle": -17.37, }, "T2": { "AbsorptionCoefficient": 0.009855, "EK60SaCorrection": -0.52, "Ek60TransducerGain": 26.07, "Frequency": 38.00, "MajorAxis3dbBeamAngle": 6.85, "MajorAxisAngleOffset": 0.0, "MajorAxisAngleSensitivity": 21.970001, "MinorAxis3dbBeamAngle": 6.81, "MinorAxisAngleOffset": -0.08, "MinorAxisAngleSensitivity": 21.970001, "SoundSpeed": 1480.6, "TwoWayBeamAngle": -21.01, }, "T3": { "AbsorptionCoefficient": 0.032594, "EK60SaCorrection": -0.3, "Ek60TransducerGain": 26.55, "Frequency": 120.00, "MajorAxis3dbBeamAngle": 6.52, "MajorAxisAngleOffset": 0.37, "MajorAxisAngleSensitivity": 23.12, "MinorAxis3dbBeamAngle": 6.58, "MinorAxisAngleOffset": -0.05, "MinorAxisAngleSensitivity": 23.12, "SoundSpeed": 1480.6, "TwoWayBeamAngle": -20.47, }, }, "localcal": {"MyCal": {"TwoWayBeamAngle": -17.37}}, } env_params_dict = { "sound_speed": [1480.6, 1480.6, 1480.6], "sound_absorption": [0.002822, 0.009855, 0.032594], "frequency_nominal": [1.8e+04, 3.8e+04, 1.2e+05], } CORRECT_ENV_DATASET = xr.Dataset( {k: (["channel"], v) for k, v in env_params_dict.items()}, coords={"channel": np.arange(3)} ) cal_params_dict = { "sa_correction": [-0.7, -0.52, -0.3], "gain_correction": [22.95, 26.07, 26.55], "frequency_nominal": [1.8e+04, 3.8e+04, 1.2e+05], "beamwidth_athwartship": [10.82, 6.85, 6.52], "angle_offset_athwartship": [0.25, 0.0, 0.37], "angle_sensitivity_athwartship": [13.89, 21.970001, 23.12], "beamwidth_alongship": [10.9, 6.81, 6.58], "angle_offset_alongship": [-0.18, -0.08, -0.05], "angle_sensitivity_alongship": [13.89, 21.970001, 23.12], "equivalent_beam_angle": [-17.37, -17.37, -17.37], } CORRECT_CAL_DATASET = xr.Dataset( {k: (["channel"], v) for k, v in cal_params_dict.items()}, coords={"channel": np.arange(3)} ) def test_convert_ecs_ek60_hake(ecs_path): # Test converting ECS from hake survey (not all variables are used, ie some has '#' in front) ecs_path = ecs_path / "Summer2017_JuneCal_3freq_mod.ecs" ecs = ECSParser(ecs_path) ecs.parse() # Spot test parsed outcome assert ecs.data_type == "SimradEK60Raw" assert ecs.version == "1.00" assert ecs.file_creation_time == datetime( year=2015, month=6, day=19, hour=23, minute=26, second=4 ) assert ecs.parsed_params == CORRECT_PARSED_PARAMS # Test ECS hierarchy dict_ev_params = ecs.get_cal_params() # SourceCal overwrite FileSet settings assert dict_ev_params["T1"]["SoundSpeed"] == 1480.60 # LocalCal overwrites SourceCal assert dict_ev_params["T2"]["TwoWayBeamAngle"] == -17.37 # Test assembled datasets ds_env, ds_cal, _ = ecs_ev2ep(dict_ev_params, "EK60") assert ds_cal.identical(CORRECT_CAL_DATASET) assert ds_env.identical(CORRECT_ENV_DATASET) def test_convert_ecs_ek80_template(ecs_path): # Test converting template ECS generated by Echoview, with all '#' removed (ie use all params) ecs_path = ecs_path / "Simrad_EK80_ES80_WBAT_EKAuto_Kongsberg_EA640_nohash.ecs" ecs = ECSParser(ecs_path) ecs.parse() dict_ev_params = ecs.get_cal_params() # applies ECS hierarchy env_params, cal_params, cal_params_BB = ecs_ev2ep(dict_ev_params, "EK80") assert dict_ev_params["T1"]["SoundSpeed"] == 1480.60 def test_check_source_channel_order(): ds_in = xr.Dataset( { "var1": (["channel"], [1, 2, 3]), "frequency_nominal": (["channel"], [18000, 38000, 120000]), }, coords={"channel": np.arange(3)} ) freq_ref = xr.DataArray( [38000, 18000, 120000], coords={"channel": ["chB", "chA", "chC"]}, dims=["channel"], ) ds_out = conform_channel_order(ds_in, freq_ref) assert np.all(ds_out["channel"].values == ["chB", "chA", "chC"]) # channel follow those of freq_ref assert not "frequency_nominal" in ds_out # frequency_nominal has been dropped def test_convert_ecs_template_ek60(ecs_path): # Test converting an EV calibration file (ECS) ecs_path = ecs_path / "Ex60_Ex70_EK15_nohash.ecs" ecs = ECSParser(ecs_path) ecs.parse() # Spot test parsed outcome assert ecs.data_type == "Ex60_Ex70_EK15" assert ecs.version == "1.00" assert ecs.file_creation_time == datetime( year=2023, month=3, day=16, hour=21, minute=38, second=58 ) # Apply ECS hierarchy dict_ev_params = ecs.get_cal_params() # Convert dict to xr.DataArray ds_env, ds_cal, _ = ecs_ev2ep(dict_ev_params, "EK60") # Conform to specific channel/frequency order freq_ref = xr.DataArray( [38000, 18000, 120000, 70000, 200000], coords={"channel": ["chB", "chA", "chD", "chC", "chE"]}, dims=["channel"], ) ds_cal_reorder = conform_channel_order(ds_cal, freq_ref) ds_env_reorder = conform_channel_order(ds_env, freq_ref) # Check reordered values for p_name in ds_cal_reorder.data_vars: assert np.all(ds_cal[p_name].values[[1, 0, 3, 2, 4]] == ds_cal_reorder[p_name].values) for p_name in ds_env_reorder.data_vars: assert np.all(ds_env[p_name].values[[1, 0, 3, 2, 4]] == ds_env_reorder[p_name].values)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,842
OSOceanAcoustics/echopype
refs/heads/main
/echopype/echodata/__init__.py
""" EchoData is an object that handles interfacing raw converted data. It is used for calibration and other processing. """ from . import convention from .echodata import EchoData __all__ = ["EchoData", "convention"]
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,843
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/convert/test_convert_ek80.py
import pytest import numpy as np import pandas as pd from scipy.io import loadmat from echopype import open_raw from echopype.testing import TEST_DATA_FOLDER from echopype.convert.set_groups_ek80 import WIDE_BAND_TRANS, PULSE_COMPRESS, FILTER_IMAG, FILTER_REAL, DECIMATION @pytest.fixture def ek80_path(test_path): return test_path["EK80"] def pytest_generate_tests(metafunc): ek80_new_path = TEST_DATA_FOLDER / "ek80_new" ek80_new_files = ek80_new_path.glob("**/*.raw") if "ek80_new_file" in metafunc.fixturenames: metafunc.parametrize( "ek80_new_file", ek80_new_files, ids=lambda f: str(f.name) ) @pytest.fixture def ek80_new_file(request): return request.param # raw_path_simrad = ['./echopype/test_data/ek80/simrad/EK80_SimradEcho_WC381_Sequential-D20150513-T090935.raw', # './echopype/test_data/ek80/simrad/EK80_SimradEcho_WC381_Sequential-D20150513-T091004.raw', # './echopype/test_data/ek80/simrad/EK80_SimradEcho_WC381_Sequential-D20150513-T091034.raw', # './echopype/test_data/ek80/simrad/EK80_SimradEcho_WC381_Sequential-D20150513-T091105.raw'] # raw_paths = ['./echopype/test_data/ek80/Summer2018--D20180905-T033113.raw', # './echopype/test_data/ek80/Summer2018--D20180905-T033258.raw'] # Multiple files (CW and BB) def check_env_xml(echodata): # check environment xml datagram # check env vars env_vars = { "sound_velocity_source": ["Manual", "Calculated"], "transducer_name": ["Unknown"], } for env_var, expected_env_var_values in env_vars.items(): assert env_var in echodata["Environment"] assert echodata["Environment"][env_var].dims == ("time1",) assert all([env_var_value in expected_env_var_values for env_var_value in echodata["Environment"][env_var]]) assert "transducer_sound_speed" in echodata["Environment"] assert echodata["Environment"]["transducer_sound_speed"].dims == ("time1",) assert (1480 <= echodata["Environment"]["transducer_sound_speed"]).all() and (echodata["Environment"]["transducer_sound_speed"] <= 1500).all() assert "sound_velocity_profile" in echodata["Environment"] assert echodata["Environment"]["sound_velocity_profile"].dims == ("time1", "sound_velocity_profile_depth") assert (1470 <= echodata["Environment"]["sound_velocity_profile"]).all() and (echodata["Environment"]["sound_velocity_profile"] <= 1500).all() # check env dims assert "time1" in echodata["Environment"] assert "sound_velocity_profile_depth" assert np.array_equal(echodata["Environment"]["sound_velocity_profile_depth"], [1, 1000]) # check a subset of platform variables. plat_vars specifies a list of possible, expected scalar values # for each variable. The variables from the EchoData object are tested against this dictionary # to verify their presence and their scalar values plat_vars = { "drop_keel_offset": [np.nan, 0, 7.5], "drop_keel_offset_is_manual": [0, 1], "water_level": [0], "water_level_draft_is_manual": [0, 1] } for plat_var, expected_plat_var_values in plat_vars.items(): assert plat_var in echodata["Platform"] if np.isnan(expected_plat_var_values).all(): assert np.isnan(echodata["Platform"][plat_var]).all() else: assert echodata["Platform"][plat_var] in expected_plat_var_values # check plat dims assert "time1" in echodata["Platform"] assert "time2" in echodata["Platform"] def test_convert(ek80_new_file, dump_output_dir): print("converting", ek80_new_file) echodata = open_raw(raw_file=str(ek80_new_file), sonar_model="EK80") echodata.to_netcdf(save_path=dump_output_dir, overwrite=True) nc_file = (dump_output_dir / ek80_new_file.name).with_suffix('.nc') assert nc_file.is_file() is True nc_file.unlink() check_env_xml(echodata) def test_convert_ek80_complex_matlab(ek80_path): """Compare parsed EK80 CW power/angle data with Matlab parsed data.""" ek80_raw_path_bb = str(ek80_path.joinpath('D20170912-T234910.raw')) ek80_matlab_path_bb = str( ek80_path.joinpath('from_matlab', 'D20170912-T234910_data.mat') ) # Convert file echodata = open_raw(raw_file=ek80_raw_path_bb, sonar_model='EK80') # check water_level assert (echodata["Platform"]["water_level"] == 0).all() # Test complex parsed data ds_matlab = loadmat(ek80_matlab_path_bb) assert np.array_equal( ( echodata["Sonar/Beam_group1"].backscatter_r .sel(channel='WBT 549762-15 ES70-7C') .isel(ping_time=0) .dropna('range_sample').squeeze().values[1:, :] # squeeze remove ping_time dimension ), np.real( ds_matlab['data']['echodata'][0][0][0, 0]['complexsamples'] ), # real part ) assert np.array_equal( ( echodata["Sonar/Beam_group1"].backscatter_i .sel(channel='WBT 549762-15 ES70-7C') .isel(ping_time=0) .dropna('range_sample').squeeze().values[1:, :] # squeeze remove ping_time dimension ), np.imag( ds_matlab['data']['echodata'][0][0][0, 0]['complexsamples'] ), # imag part ) check_env_xml(echodata) # check platform nan_plat_vars = [ "MRU_offset_x", "MRU_offset_y", "MRU_offset_z", "MRU_rotation_x", "MRU_rotation_y", "MRU_rotation_z", "position_offset_x", "position_offset_y", "position_offset_z" ] for plat_var in nan_plat_vars: assert plat_var in echodata["Platform"] assert np.isnan(echodata["Platform"][plat_var]).all() zero_plat_vars = [ "transducer_offset_x", "transducer_offset_y", "transducer_offset_z", ] for plat_var in zero_plat_vars: assert plat_var in echodata["Platform"] assert (echodata["Platform"][plat_var] == 0).all() def test_convert_ek80_cw_power_angle_echoview(ek80_path): """Compare parsed EK80 CW power/angle data with csv exported by EchoView.""" ek80_raw_path_cw = str( ek80_path.joinpath('D20190822-T161221.raw') ) # Small file (CW) freq_list = [18, 38, 70, 120, 200] ek80_echoview_power_csv = [ ek80_path.joinpath( 'from_echoview', 'D20190822-T161221', '%dkHz.power.csv' % freq ) for freq in freq_list ] ek80_echoview_angle_csv = [ ek80_path.joinpath( 'from_echoview', 'D20190822-T161221', '%dkHz.angles.points.csv' % freq ) for freq in freq_list ] # Convert file echodata = open_raw(ek80_raw_path_cw, sonar_model='EK80') # get indices of sorted frequency_nominal values. This is necessary # because the frequency_nominal values are not always in ascending order. sorted_freq_ind = np.argsort(echodata["Sonar/Beam_group1"].frequency_nominal) # get sorted channel list based on frequency_nominal values channel_list = echodata["Sonar/Beam_group1"].channel[sorted_freq_ind.values] # check water_level assert (echodata["Platform"]["water_level"] == 0).all() # Test power # single point error in original raw data. Read as -2000 by echopype and -999 by EchoView echodata["Sonar/Beam_group1"].backscatter_r[sorted_freq_ind.values[3], 4, 13174] = -999 for file, chan in zip(ek80_echoview_power_csv, channel_list): test_power = pd.read_csv(file, delimiter=';').iloc[:, 13:].values assert np.allclose( test_power, echodata["Sonar/Beam_group1"].backscatter_r.sel(channel=chan).dropna('range_sample'), rtol=0, atol=1.1e-5, ) # Convert from electrical angles to physical angle [deg] major = ( echodata["Sonar/Beam_group1"]['angle_athwartship'] * 1.40625 / echodata["Sonar/Beam_group1"]['angle_sensitivity_athwartship'] - echodata["Sonar/Beam_group1"]['angle_offset_athwartship'] ) minor = ( echodata["Sonar/Beam_group1"]['angle_alongship'] * 1.40625 / echodata["Sonar/Beam_group1"]['angle_sensitivity_alongship'] - echodata["Sonar/Beam_group1"]['angle_offset_alongship'] ) for chan, file in zip(channel_list, ek80_echoview_angle_csv): df_angle = pd.read_csv(file) # NB: EchoView exported data only has 6 pings, but raw data actually has 7 pings. # The first raw ping (ping 0) was removed in EchoView for some reason. # Therefore the comparison will use ping 1-6. for ping_idx in df_angle['Ping_index'].value_counts().index: assert np.allclose( df_angle.loc[df_angle['Ping_index'] == ping_idx, ' Major'], major.sel(channel=chan) .isel(ping_time=ping_idx) .dropna('range_sample'), rtol=0, atol=5e-5, ) assert np.allclose( df_angle.loc[df_angle['Ping_index'] == ping_idx, ' Minor'], minor.sel(channel=chan) .isel(ping_time=ping_idx) .dropna('range_sample'), rtol=0, atol=5e-5, ) check_env_xml(echodata) # check platform nan_plat_vars = [ "MRU_offset_x", "MRU_offset_y", "MRU_offset_z", "MRU_rotation_x", "MRU_rotation_y", "MRU_rotation_z", "position_offset_x", "position_offset_y", "position_offset_z" ] for plat_var in nan_plat_vars: assert plat_var in echodata["Platform"] assert np.isnan(echodata["Platform"][plat_var]).all() zero_plat_vars = [ "transducer_offset_x", "transducer_offset_y", ] for plat_var in zero_plat_vars: assert plat_var in echodata["Platform"] assert (echodata["Platform"][plat_var] == 0).all() assert "transducer_offset_z" in echodata["Platform"] assert (echodata["Platform"]["transducer_offset_z"] == 9.15).all() def test_convert_ek80_complex_echoview(ek80_path): """Compare parsed EK80 BB data with csv exported by EchoView.""" ek80_raw_path_bb = ek80_path.joinpath('D20170912-T234910.raw') ek80_echoview_bb_power_csv = ek80_path.joinpath( 'from_echoview', 'D20170912-T234910', '70 kHz raw power.complex.csv' ) # Convert file echodata = open_raw(raw_file=ek80_raw_path_bb, sonar_model='EK80') # check water_level assert (echodata["Platform"]["water_level"] == 0).all() # Test complex parsed data df_bb = pd.read_csv( ek80_echoview_bb_power_csv, header=None, skiprows=[0] ) # averaged across beams assert np.allclose( echodata["Sonar/Beam_group1"].backscatter_r.sel(channel='WBT 549762-15 ES70-7C') .dropna('range_sample') .mean(dim='beam'), df_bb.iloc[::2, 14:], # real rows rtol=0, atol=8e-6, ) assert np.allclose( echodata["Sonar/Beam_group1"].backscatter_i.sel(channel='WBT 549762-15 ES70-7C') .dropna('range_sample') .mean(dim='beam'), df_bb.iloc[1::2, 14:], # imag rows rtol=0, atol=4e-6, ) check_env_xml(echodata) # check platform nan_plat_vars = [ "MRU_offset_x", "MRU_offset_y", "MRU_offset_z", "MRU_rotation_x", "MRU_rotation_y", "MRU_rotation_z", "position_offset_x", "position_offset_y", "position_offset_z" ] for plat_var in nan_plat_vars: assert plat_var in echodata["Platform"] assert np.isnan(echodata["Platform"][plat_var]).all() zero_plat_vars = [ "transducer_offset_x", "transducer_offset_y", "transducer_offset_z", ] for plat_var in zero_plat_vars: assert plat_var in echodata["Platform"] assert (echodata["Platform"][plat_var] == 0).all() def test_convert_ek80_cw_bb_in_single_file(ek80_path): """Make sure can convert a single EK80 file containing both CW and BB mode data.""" ek80_raw_path_bb_cw = str( ek80_path.joinpath('Summer2018--D20180905-T033113.raw') ) echodata = open_raw(raw_file=ek80_raw_path_bb_cw, sonar_model='EK80') # Check there are both Sonar/Beam_group1 and /Sonar/Beam_power groups in the converted file assert echodata["Sonar/Beam_group2"] assert echodata["Sonar/Beam_group1"] # check platform nan_plat_vars = [ "MRU_offset_x", "MRU_offset_y", "MRU_offset_z", "MRU_rotation_x", "MRU_rotation_y", "MRU_rotation_z", "position_offset_x", "position_offset_y", "position_offset_z" ] for plat_var in nan_plat_vars: assert plat_var in echodata["Platform"] assert np.isnan(echodata["Platform"][plat_var]).all() zero_plat_vars = [ "transducer_offset_x", "transducer_offset_y", "transducer_offset_z", ] for plat_var in zero_plat_vars: assert plat_var in echodata["Platform"] assert (echodata["Platform"][plat_var] == 0).all() # check water_level assert (echodata["Platform"]["water_level"] == 0).all() check_env_xml(echodata) def test_convert_ek80_freq_subset(ek80_path): """Make sure we can convert EK80 file with multiple frequency channels off.""" ek80_raw_path_freq_subset = str( ek80_path.joinpath('2019118 group2survey-D20191214-T081342.raw') ) echodata = open_raw(raw_file=ek80_raw_path_freq_subset, sonar_model='EK80') # Check if converted output has only 2 frequency channels assert echodata["Sonar/Beam_group1"].channel.size == 2 # check platform nan_plat_vars = [ "MRU_offset_x", "MRU_offset_y", "MRU_offset_z", "MRU_rotation_x", "MRU_rotation_y", "MRU_rotation_z", "position_offset_x", "position_offset_y", "position_offset_z" ] for plat_var in nan_plat_vars: assert plat_var in echodata["Platform"] assert np.isnan(echodata["Platform"][plat_var]).all() zero_plat_vars = [ "transducer_offset_x", "transducer_offset_y", "transducer_offset_z", ] for plat_var in zero_plat_vars: assert plat_var in echodata["Platform"] assert (echodata["Platform"][plat_var] == 0).all() # check water_level assert (echodata["Platform"]["water_level"] == 0).all() check_env_xml(echodata) def test_convert_ek80_raw4(ek80_path): """Make sure we can convert EK80 file with RAW4 datagram..""" ek80_raw_path_freq_subset = str( ek80_path.joinpath('raw4-D20220514-T172704.raw') ) echodata = open_raw(raw_file=ek80_raw_path_freq_subset, sonar_model='EK80') # Check if correct data variables exist in Beam_group1 assert "transmit_sample" in echodata["Sonar/Beam_group1"] for var in ["transmit_pulse_r", "transmit_pulse_i"]: assert var in echodata["Sonar/Beam_group1"] assert echodata["Sonar/Beam_group1"][var].dims == ( 'channel', 'ping_time', 'transmit_sample' ) def test_convert_ek80_no_fil_coeff(ek80_path): """Make sure we can convert EK80 file with empty filter coefficients.""" echodata = open_raw(raw_file=ek80_path.joinpath('D20210330-T123857.raw'), sonar_model='EK80') vendor_spec_ds = echodata["Vendor_specific"] for t in [WIDE_BAND_TRANS, PULSE_COMPRESS]: for p in [FILTER_REAL, FILTER_IMAG, DECIMATION]: assert f"{t}_{p}" not in vendor_spec_ds
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,844
OSOceanAcoustics/echopype
refs/heads/main
/echopype/convert/set_groups_ek80.py
from collections import defaultdict from typing import Dict, List, Union import numpy as np import xarray as xr from numpy.typing import NDArray from ..utils.coding import set_time_encodings from ..utils.log import _init_logger from .set_groups_base import SetGroupsBase logger = _init_logger(__name__) WIDE_BAND_TRANS = "WBT" PULSE_COMPRESS = "PC" FILTER_IMAG = "filter_i" FILTER_REAL = "filter_r" DECIMATION = "decimation" class SetGroupsEK80(SetGroupsBase): """Class for saving groups to netcdf or zarr from EK80 data files.""" # The sets beam_only_names, ping_time_only_names, and # beam_ping_time_names are used in set_groups_base and # in converting from v0.5.x to v0.6.0. The values within # these sets are applied to all Sonar/Beam_groupX groups. # 2023-07-24: # PRs: # - https://github.com/OSOceanAcoustics/echopype/pull/1056 # - https://github.com/OSOceanAcoustics/echopype/pull/1083 # The artificially added beam and ping_time dimensions at v0.6.0 # were reverted at v0.8.0, due to concerns with efficiency and code clarity # (see https://github.com/OSOceanAcoustics/echopype/issues/684 and # https://github.com/OSOceanAcoustics/echopype/issues/978). # However, the mechanisms to expand these dimensions were preserved for # flexibility and potential later use. # Note such expansion is still applied on AZFP data for 2 variables # (see set_groups_azfp.py). # Variables that need only the beam dimension added to them. beam_only_names = set() # Variables that need only the ping_time dimension added to them. ping_time_only_names = set() # Variables that need beam and ping_time dimensions added to them. beam_ping_time_names = set() beamgroups_possible = [ { "name": "Beam_group1", "descr": { "power": "contains backscatter power (uncalibrated) and " "other beam or channel-specific data," " including split-beam angle data when they exist.", "complex": "contains complex backscatter data and other " "beam or channel-specific data.", }, }, { "name": "Beam_group2", "descr": ( "contains backscatter power (uncalibrated) and other beam or channel-specific data," # noqa " including split-beam angle data when they exist." ), }, ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # if we have zarr files, create parser_obj.ch_ids if self.parsed2zarr_obj.temp_zarr_dir: for k, v in self.parsed2zarr_obj.p2z_ch_ids.items(): self.parser_obj.ch_ids[k] = self._get_channel_ids(v) # obtain sorted channel dict in ascending order for each usage scenario self.sorted_channel = { "all": self._sort_list(list(self.parser_obj.config_datagram["configuration"].keys())), "power": self._sort_list(self.parser_obj.ch_ids["power"]), "complex": self._sort_list(self.parser_obj.ch_ids["complex"]), "power_complex": self._sort_list( self.parser_obj.ch_ids["power"] + self.parser_obj.ch_ids["complex"] ), "angle": self._sort_list(self.parser_obj.ch_ids["angle"]), } @staticmethod def _sort_list(list_in: List[str]) -> List[str]: """ Sorts a list in ascending order and then returns the sorted list. Parameters ---------- list_in: List[str] List to be sorted Returns ------- List[str] A copy of the input list in ascending order """ # make copy so we don't directly modify input list list_in_copy = list_in.copy() # sort list in ascending order list_in_copy.sort(reverse=False) return list_in_copy def set_env(self) -> xr.Dataset: """Set the Environment group.""" # set time1 if it exists if "timestamp" in self.parser_obj.environment: time1 = np.array([self.parser_obj.environment["timestamp"]]) else: time1 = np.array([np.datetime64("NaT")]) # Collect variables dict_env = dict() for k, v in self.parser_obj.environment.items(): if k in ["temperature", "depth", "acidity", "salinity", "sound_speed"]: dict_env[k] = (["time1"], [v]) # Rename to conform with those defined in convention if "sound_speed" in dict_env: dict_env["sound_speed_indicative"] = dict_env.pop("sound_speed") for k in [ "sound_absorption", "absorption", ]: # add possible variation until having example if k in dict_env: dict_env["absorption_indicative"] = dict_env.pop(k) if "sound_velocity_profile" in self.parser_obj.environment: dict_env["sound_velocity_profile"] = ( ["time1", "sound_velocity_profile_depth"], [self.parser_obj.environment["sound_velocity_profile"][1::2]], { "long_name": "sound velocity profile", "standard_name": "speed_of_sound_in_sea_water", "units": "m/s", "valid_min": 0.0, "comment": "parsed from raw data files as (depth, sound_speed) value pairs", }, ) varnames = ["sound_velocity_source", "transducer_name", "transducer_sound_speed"] for vn in varnames: if vn in self.parser_obj.environment: dict_env[vn] = ( ["time1"], [self.parser_obj.environment[vn]], ) ds = xr.Dataset( dict_env, coords={ "time1": ( ["time1"], time1, { "axis": "T", "long_name": "Timestamps for NMEA position datagrams", "standard_name": "time", "comment": "Time coordinate corresponding to environmental " "variables. Note that Platform.time3 is the same " "as Environment.time1.", }, ), "sound_velocity_profile_depth": ( ["sound_velocity_profile_depth"], self.parser_obj.environment["sound_velocity_profile"][::2] if "sound_velocity_profile" in self.parser_obj.environment else [], { "standard_name": "depth", "units": "m", "axis": "Z", "positive": "down", "valid_min": 0.0, }, ), }, ) return set_time_encodings(ds) def set_sonar(self, beam_group_type: list = ["power", None]) -> xr.Dataset: # Collect unique variables params = [ "transducer_frequency", "serial_number", "transducer_name", "transducer_serial_number", "application_name", "application_version", "channel_id_short", ] var = defaultdict(list) # collect all variables in params for ch_id in self.sorted_channel["all"]: data = self.parser_obj.config_datagram["configuration"][ch_id] for param in params: var[param].append(data[param]) # obtain the correct beam_group and corresponding description from beamgroups_possible for idx, beam in enumerate(beam_group_type): if beam is None: # obtain values from an element where the key 'descr' does not have keys self._beamgroups.append(self.beamgroups_possible[idx]) else: # obtain values from an element where the key 'descr' DOES have keys self._beamgroups.append( { "name": self.beamgroups_possible[idx]["name"], "descr": self.beamgroups_possible[idx]["descr"][beam], } ) # Add beam_group and beam_group_descr variables sharing a common dimension # (beam_group), using the information from self._beamgroups beam_groups_vars, beam_groups_coord = self._beam_groups_vars() # Create dataset sonar_vars = { "frequency_nominal": ( ["channel"], var["transducer_frequency"], { "units": "Hz", "long_name": "Transducer frequency", "valid_min": 0.0, "standard_name": "sound_frequency", }, ), "transceiver_serial_number": ( ["channel"], var["serial_number"], { "long_name": "Transceiver serial number", }, ), "transducer_name": ( ["channel"], var["transducer_name"], { "long_name": "Transducer name", }, ), "transducer_serial_number": ( ["channel"], var["transducer_serial_number"], { "long_name": "Transducer serial number", }, ), } ds = xr.Dataset( {**sonar_vars, **beam_groups_vars}, coords={ "channel": ( ["channel"], self.sorted_channel["all"], self._varattrs["beam_coord_default"]["channel"], ), **beam_groups_coord, }, ) # Assemble sonar group global attribute dictionary sonar_attr_dict = { "sonar_manufacturer": "Simrad", "sonar_model": self.sonar_model, # transducer (sonar) serial number is not reliably stored in the EK80 raw # data file and would be channel-dependent. For consistency with EK60, # will not try to populate sonar_serial_number from the raw datagrams "sonar_serial_number": "", "sonar_software_name": var["application_name"][0], "sonar_software_version": var["application_version"][0], "sonar_type": "echosounder", } ds = ds.assign_attrs(sonar_attr_dict) return ds def set_platform(self) -> xr.Dataset: """Set the Platform group.""" freq = np.array( [ self.parser_obj.config_datagram["configuration"][ch]["transducer_frequency"] for ch in self.sorted_channel["power_complex"] ] ) # Collect variables if "water_level_draft" in self.parser_obj.environment: water_level = self.parser_obj.environment["water_level_draft"] else: water_level = np.nan logger.info("WARNING: The water_level_draft was not in the file. Value set to NaN.") time1, msg_type, lat, lon = self._extract_NMEA_latlon() time2 = self.parser_obj.mru.get("timestamp", None) time2 = np.array(time2) if time2 is not None else [np.nan] # Assemble variables into a dataset: variables filled with nan if do not exist platform_dict = {"platform_name": "", "platform_type": "", "platform_code_ICES": ""} ds = xr.Dataset( { "latitude": (["time1"], lat, self._varattrs["platform_var_default"]["latitude"]), "longitude": (["time1"], lon, self._varattrs["platform_var_default"]["longitude"]), "sentence_type": ( ["time1"], msg_type, self._varattrs["platform_var_default"]["sentence_type"], ), "pitch": ( ["time2"], np.array(self.parser_obj.mru.get("pitch", [np.nan])), self._varattrs["platform_var_default"]["pitch"], ), "roll": ( ["time2"], np.array(self.parser_obj.mru.get("roll", [np.nan])), self._varattrs["platform_var_default"]["roll"], ), "vertical_offset": ( ["time2"], np.array(self.parser_obj.mru.get("heave", [np.nan])), self._varattrs["platform_var_default"]["vertical_offset"], ), "water_level": ( [], water_level, self._varattrs["platform_var_default"]["water_level"], ), "drop_keel_offset": ( [], self.parser_obj.environment.get("drop_keel_offset", np.nan), ), "drop_keel_offset_is_manual": ( [], self.parser_obj.environment.get("drop_keel_offset_is_manual", np.nan), ), "water_level_draft_is_manual": ( [], self.parser_obj.environment.get("water_level_draft_is_manual", np.nan), ), "transducer_offset_x": ( ["channel"], [ self.parser_obj.config_datagram["configuration"][ch].get( "transducer_offset_x", np.nan ) for ch in self.sorted_channel["power_complex"] ], self._varattrs["platform_var_default"]["transducer_offset_x"], ), "transducer_offset_y": ( ["channel"], [ self.parser_obj.config_datagram["configuration"][ch].get( "transducer_offset_y", np.nan ) for ch in self.sorted_channel["power_complex"] ], self._varattrs["platform_var_default"]["transducer_offset_y"], ), "transducer_offset_z": ( ["channel"], [ self.parser_obj.config_datagram["configuration"][ch].get( "transducer_offset_z", np.nan ) for ch in self.sorted_channel["power_complex"] ], self._varattrs["platform_var_default"]["transducer_offset_z"], ), **{ var: ([], np.nan, self._varattrs["platform_var_default"][var]) for var in [ "MRU_offset_x", "MRU_offset_y", "MRU_offset_z", "MRU_rotation_x", "MRU_rotation_y", "MRU_rotation_z", "position_offset_x", "position_offset_y", "position_offset_z", ] }, "frequency_nominal": ( ["channel"], freq, { "units": "Hz", "long_name": "Transducer frequency", "valid_min": 0.0, "standard_name": "sound_frequency", }, ), }, coords={ "channel": ( ["channel"], self.sorted_channel["power_complex"], self._varattrs["beam_coord_default"]["channel"], ), "time1": ( ["time1"], time1, { **self._varattrs["platform_coord_default"]["time1"], "comment": "Time coordinate corresponding to NMEA position data.", }, ), "time2": ( ["time2"], time2, { "axis": "T", "long_name": "Timestamps for platform motion and orientation data", "standard_name": "time", "comment": "Time coordinate corresponding to platform motion and " "orientation data.", }, ), }, ) ds = ds.assign_attrs(platform_dict) return set_time_encodings(ds) def _assemble_ds_ping_invariant(self, params, data_type): """Assemble dataset for ping-invariant params in the /Sonar/Beam_group1 group. Parameters ---------- data_type : str 'complex' or 'power' params : dict beam parameters that do not change across ping """ freq = np.array( [ self.parser_obj.config_datagram["configuration"][ch]["transducer_frequency"] for ch in self.sorted_channel[data_type] ] ) beam_params = defaultdict() for param in params: beam_params[param] = [ self.parser_obj.config_datagram["configuration"][ch].get(param, np.nan) for ch in self.sorted_channel[data_type] ] for i, ch in enumerate(self.sorted_channel[data_type]): if ( np.isclose(beam_params["transducer_alpha_x"][i], 0.00) and np.isclose(beam_params["transducer_alpha_y"][i], 0.00) and np.isclose(beam_params["transducer_alpha_z"][i], 0.00) ): beam_params["transducer_alpha_x"][i] = np.nan beam_params["transducer_alpha_y"][i] = np.nan beam_params["transducer_alpha_z"][i] = np.nan ds = xr.Dataset( { "frequency_nominal": ( ["channel"], freq, { "units": "Hz", "long_name": "Transducer frequency", "valid_min": 0.0, "standard_name": "sound_frequency", }, ), "beam_type": ( ["channel"], beam_params["transducer_beam_type"], {"long_name": "type of transducer (0-single, 1-split)"}, ), "beamwidth_twoway_alongship": ( ["channel"], beam_params["beam_width_alongship"], { "long_name": "Half power two-way beam width along alongship axis of beam", # noqa "units": "arc_degree", "valid_range": (0.0, 360.0), "comment": ( "Introduced in echopype for Simrad echosounders to avoid potential confusion with convention definitions. " # noqa "The alongship angle corresponds to the minor angle in SONAR-netCDF4 vers 2. " # noqa "The convention defines one-way transmit or receive beamwidth (beamwidth_receive_minor and beamwidth_transmit_minor), but Simrad echosounders record two-way beamwidth in the data." # noqa ), }, ), "beamwidth_twoway_athwartship": ( ["channel"], beam_params["beam_width_athwartship"], { "long_name": "Half power two-way beam width along athwartship axis of beam", # noqa "units": "arc_degree", "valid_range": (0.0, 360.0), "comment": ( "Introduced in echopype for Simrad echosounders to avoid potential confusion with convention definitions. " # noqa "The athwartship angle corresponds to the major angle in SONAR-netCDF4 vers 2. " # noqa "The convention defines one-way transmit or receive beamwidth (beamwidth_receive_major and beamwidth_transmit_major), but Simrad echosounders record two-way beamwidth in the data." # noqa ), }, ), "beam_direction_x": ( ["channel"], beam_params["transducer_alpha_x"], { "long_name": "x-component of the vector that gives the pointing " "direction of the beam, in sonar beam coordinate " "system", "units": "1", "valid_range": (-1.0, 1.0), }, ), "beam_direction_y": ( ["channel"], beam_params["transducer_alpha_y"], { "long_name": "y-component of the vector that gives the pointing " "direction of the beam, in sonar beam coordinate " "system", "units": "1", "valid_range": (-1.0, 1.0), }, ), "beam_direction_z": ( ["channel"], beam_params["transducer_alpha_z"], { "long_name": "z-component of the vector that gives the pointing " "direction of the beam, in sonar beam coordinate " "system", "units": "1", "valid_range": (-1.0, 1.0), }, ), "angle_offset_alongship": ( ["channel"], beam_params["angle_offset_alongship"], { "long_name": "electrical alongship angle offset of the transducer", "comment": ( "Introduced in echopype for Simrad echosounders. " # noqa "The alongship angle corresponds to the minor angle in SONAR-netCDF4 vers 2. " # noqa ), }, ), "angle_offset_athwartship": ( ["channel"], beam_params["angle_offset_athwartship"], { "long_name": "electrical athwartship angle offset of the transducer", "comment": ( "Introduced in echopype for Simrad echosounders. " # noqa "The athwartship angle corresponds to the major angle in SONAR-netCDF4 vers 2. " # noqa ), }, ), "angle_sensitivity_alongship": ( ["channel"], beam_params["angle_sensitivity_alongship"], { "long_name": "alongship angle sensitivity of the transducer", "comment": ( "Introduced in echopype for Simrad echosounders. " # noqa "The alongship angle corresponds to the minor angle in SONAR-netCDF4 vers 2. " # noqa ), }, ), "angle_sensitivity_athwartship": ( ["channel"], beam_params["angle_sensitivity_athwartship"], { "long_name": "athwartship angle sensitivity of the transducer", "comment": ( "Introduced in echopype for Simrad echosounders. " # noqa "The athwartship angle corresponds to the major angle in SONAR-netCDF4 vers 2. " # noqa ), }, ), "equivalent_beam_angle": ( ["channel"], beam_params["equivalent_beam_angle"], { "long_name": "Equivalent beam angle", "units": "sr", "valid_range": (0.0, 4 * np.pi), }, ), "transceiver_software_version": ( ["channel"], beam_params["transceiver_software_version"], ), "beam_stabilisation": ( [], np.array(0, np.byte), { "long_name": "Beam stabilisation applied (or not)", "flag_values": [0, 1], "flag_meanings": ["not stabilised", "stabilised"], }, ), "non_quantitative_processing": ( [], np.array(0, np.int16), { "long_name": "Presence or not of non-quantitative processing applied" " to the backscattering data (sonar specific)", "flag_values": [0], "flag_meanings": ["None"], }, ), }, coords={ "channel": ( ["channel"], self.sorted_channel[data_type], self._varattrs["beam_coord_default"]["channel"], ), }, attrs={"beam_mode": "vertical", "conversion_equation_t": "type_3"}, ) if data_type == "power": ds = ds.assign( { "transmit_frequency_start": ( ["channel"], freq, self._varattrs["beam_var_default"]["transmit_frequency_start"], ), "transmit_frequency_stop": ( ["channel"], freq, self._varattrs["beam_var_default"]["transmit_frequency_stop"], ), } ) return ds def _add_freq_start_end_ds(self, ds_tmp: xr.Dataset, ch: str) -> xr.Dataset: """ Returns a Dataset with variables ``transmit_frequency_start`` and ``transmit_frequency_stop`` added to ``ds_tmp`` for a specific channel. Parameters ---------- ds_tmp: xr.Dataset Dataset containing the complex data ch: str Channel id """ # Process if it's a BB channel (not all pings are CW, where pulse_form encodes CW as 0) # CW data encoded as complex samples do NOT have frequency_start and frequency_end if not np.all(np.array(self.parser_obj.ping_data_dict["pulse_form"][ch]) == 0): freq_start = np.array(self.parser_obj.ping_data_dict["frequency_start"][ch]) freq_stop = np.array(self.parser_obj.ping_data_dict["frequency_end"][ch]) elif not self.sorted_channel["power"]: freq = self.parser_obj.config_datagram["configuration"][ch]["transducer_frequency"] freq_start = np.full(len(self.parser_obj.ping_time[ch]), freq) freq_stop = freq_start else: return ds_tmp ds_f_start_end = xr.Dataset( { "transmit_frequency_start": ( ["ping_time"], freq_start.astype(float), self._varattrs["beam_var_default"]["transmit_frequency_start"], ), "transmit_frequency_stop": ( ["ping_time"], freq_stop.astype(float), self._varattrs["beam_var_default"]["transmit_frequency_stop"], ), }, coords={ "ping_time": ( ["ping_time"], self.parser_obj.ping_time[ch], self._varattrs["beam_coord_default"]["ping_time"], ), }, ) ds_tmp = xr.merge( [ds_tmp, ds_f_start_end], combine_attrs="override" ) # override keeps the Dataset attributes return ds_tmp def _assemble_ds_complex(self, ch): num_transducer_sectors = np.unique( np.array(self.parser_obj.ping_data_dict["n_complex"][ch]) ) if num_transducer_sectors.size > 1: # this is not supposed to happen raise ValueError("Transducer sector number changes in the middle of the file!") else: num_transducer_sectors = num_transducer_sectors[0] data_shape = self.parser_obj.ping_data_dict["complex"][ch].shape data_shape = ( data_shape[0], int(data_shape[1] / num_transducer_sectors), num_transducer_sectors, ) data = self.parser_obj.ping_data_dict["complex"][ch].reshape(data_shape) ds_tmp = xr.Dataset( { "backscatter_r": ( ["ping_time", "range_sample", "beam"], np.real(data), { "long_name": self._varattrs["beam_var_default"]["backscatter_r"][ "long_name" ], "units": "dB", }, ), "backscatter_i": ( ["ping_time", "range_sample", "beam"], np.imag(data), { "long_name": self._varattrs["beam_var_default"]["backscatter_i"][ "long_name" ], "units": "dB", }, ), }, coords={ "ping_time": ( ["ping_time"], self.parser_obj.ping_time[ch], self._varattrs["beam_coord_default"]["ping_time"], ), "range_sample": ( ["range_sample"], np.arange(data_shape[1]), self._varattrs["beam_coord_default"]["range_sample"], ), "beam": ( ["beam"], np.arange(start=1, stop=num_transducer_sectors + 1).astype(str), self._varattrs["beam_coord_default"]["beam"], ), }, ) ds_tmp = self._add_freq_start_end_ds(ds_tmp, ch) return set_time_encodings(ds_tmp) def _add_trasmit_pulse_complex(self, ds_tmp: xr.Dataset, ch: str) -> xr.Dataset: """ Adds RAW4 datagram values (transmit pulse recorded in complex samples), if it exists, to the power and angle data. Parameters ---------- ds_tmp : xr.Dataset Dataset to add the transmit data to ch : str Name of channel key to grab the data from Returns ------- ds_tmp : xr.Dataset The input Dataset with transmit data added to it. """ # If RAW4 datagram (transmit pulse recorded in complex samples) exists if (len(self.parser_obj.ping_data_dict_tx["complex"]) != 0) and ( ch in self.parser_obj.ping_data_dict_tx["complex"].keys() ): # Add coordinate transmit_sample ds_tmp = ds_tmp.assign_coords( { "transmit_sample": ( ["transmit_sample"], np.arange(self.parser_obj.ping_data_dict_tx["complex"][ch].shape[1]), { "long_name": "Transmit pulse sample number, base 0", "comment": "Only exist for Simrad EK80 file with RAW4 datagrams", }, ), }, ) # Add data variables transmit_pulse_r/i ds_tmp = ds_tmp.assign( { "transmit_pulse_r": ( ["ping_time", "transmit_sample"], np.real(self.parser_obj.ping_data_dict_tx["complex"][ch]), { "long_name": "Real part of the transmit pulse", "units": "V", "comment": "Only exist for Simrad EK80 file with RAW4 datagrams", }, ), "transmit_pulse_i": ( ["ping_time", "transmit_sample"], np.imag(self.parser_obj.ping_data_dict_tx["complex"][ch]), { "long_name": "Imaginary part of the transmit pulse", "units": "V", "comment": "Only exist for Simrad EK80 file with RAW4 datagrams", }, ), }, ) return ds_tmp def _assemble_ds_power(self, ch): ds_tmp = xr.Dataset( { "backscatter_r": ( ["ping_time", "range_sample"], self.parser_obj.ping_data_dict["power"][ch], { "long_name": self._varattrs["beam_var_default"]["backscatter_r"][ "long_name" ], "units": "dB", }, ), }, coords={ "ping_time": ( ["ping_time"], self.parser_obj.ping_time[ch], self._varattrs["beam_coord_default"]["ping_time"], ), "range_sample": ( ["range_sample"], np.arange(self.parser_obj.ping_data_dict["power"][ch].shape[1]), self._varattrs["beam_coord_default"]["range_sample"], ), }, ) ds_tmp = self._add_trasmit_pulse_complex(ds_tmp, ch) # If angle data exist if ch in self.sorted_channel["angle"]: ds_tmp = ds_tmp.assign( { "angle_athwartship": ( ["ping_time", "range_sample"], self.parser_obj.ping_data_dict["angle"][ch][:, :, 0], { "long_name": "electrical athwartship angle", "comment": ( "Introduced in echopype for Simrad echosounders. " # noqa + "The athwartship angle corresponds to the major angle in SONAR-netCDF4 vers 2. " # noqa ), }, ), "angle_alongship": ( ["ping_time", "range_sample"], self.parser_obj.ping_data_dict["angle"][ch][:, :, 1], { "long_name": "electrical alongship angle", "comment": ( "Introduced in echopype for Simrad echosounders. " # noqa + "The alongship angle corresponds to the minor angle in SONAR-netCDF4 vers 2. " # noqa ), }, ), } ) ds_tmp = self._add_freq_start_end_ds(ds_tmp, ch) return set_time_encodings(ds_tmp) def _assemble_ds_common(self, ch, range_sample_size): """Variables common to complex and power/angle data.""" # pulse duration may have different names if "pulse_length" in self.parser_obj.ping_data_dict: pulse_length = np.array( self.parser_obj.ping_data_dict["pulse_length"][ch], dtype="float32" ) else: pulse_length = np.array( self.parser_obj.ping_data_dict["pulse_duration"][ch], dtype="float32" ) def pulse_form_map(pulse_form): str_map = np.array(["CW", "LFM", "", "", "", "FMD"]) return str_map[pulse_form] ds_common = xr.Dataset( { "sample_interval": ( ["ping_time"], self.parser_obj.ping_data_dict["sample_interval"][ch], { "long_name": "Interval between recorded raw data samples", "units": "s", "valid_min": 0.0, }, ), "transmit_power": ( ["ping_time"], self.parser_obj.ping_data_dict["transmit_power"][ch], { "long_name": "Nominal transmit power", "units": "W", "valid_min": 0.0, }, ), "transmit_duration_nominal": ( ["ping_time"], pulse_length, { "long_name": "Nominal bandwidth of transmitted pulse", "units": "s", "valid_min": 0.0, }, ), "slope": ( ["ping_time"], self.parser_obj.ping_data_dict["slope"][ch], {"long_name": "Hann window slope parameter for transmit signal"}, ), "channel_mode": ( ["ping_time"], np.array(self.parser_obj.ping_data_dict["channel_mode"][ch], dtype=np.byte), { "long_name": "Transceiver mode", "flag_values": [0, 1], "flag_meanings": ["Active", "Unknown"], }, ), "transmit_type": ( ["ping_time"], pulse_form_map(np.array(self.parser_obj.ping_data_dict["pulse_form"][ch])), { "long_name": "Type of transmitted pulse", "flag_values": ["CW", "LFM", "FMD"], "flag_meanings": [ "Continuous Wave – a pulse nominally of one frequency", "Linear Frequency Modulation – a pulse which varies from " "transmit_frequency_start to transmit_frequency_stop in a linear " "manner over the nominal pulse duration (transmit_duration_nominal)", "Frequency Modulated 'D' - An EK80-specific FM type that is not " "clearly described", ], }, ), "sample_time_offset": ( ["ping_time"], ( np.array(self.parser_obj.ping_data_dict["offset"][ch]) * np.array(self.parser_obj.ping_data_dict["sample_interval"][ch]) ), { "long_name": "Time offset that is subtracted from the timestamp" " of each sample", "units": "s", }, ), }, coords={ "ping_time": ( ["ping_time"], self.parser_obj.ping_time[ch], self._varattrs["beam_coord_default"]["ping_time"], ), "range_sample": ( ["range_sample"], np.arange(range_sample_size), self._varattrs["beam_coord_default"]["range_sample"], ), }, ) return set_time_encodings(ds_common) @staticmethod def merge_save(ds_combine: List[xr.Dataset], ds_invariant: xr.Dataset) -> xr.Dataset: """Merge data from all complex or all power/angle channels""" ds_combine = xr.merge(ds_combine) ds_combine = xr.merge( [ds_invariant, ds_combine], combine_attrs="override" ) # override keeps the Dataset attributes return set_time_encodings(ds_combine) def _attach_vars_to_ds_data(self, ds_data: xr.Dataset, ch: str, rs_size: int) -> xr.Dataset: """ Attaches common variables and the channel dimension. Parameters ---------- ds_data : xr.Dataset Data set to add variables to ch: str Channel string associated with variables rs_size: int The size of the range sample dimension i.e. ``range_sample.size`` Returns ------- ``ds_data`` with the variables added to it. """ ds_common = self._assemble_ds_common(ch, rs_size) ds_data = xr.merge([ds_data, ds_common], combine_attrs="override") # Attach channel dimension/coordinate ds_data = ds_data.expand_dims( {"channel": [self.parser_obj.config_datagram["configuration"][ch]["channel_id"]]} ) ds_data["channel"] = ds_data["channel"].assign_attrs( **self._varattrs["beam_coord_default"]["channel"] ) return ds_data def _get_ds_beam_power_zarr(self, ds_invariant_power: xr.Dataset) -> xr.Dataset: """ Constructs the data set `ds_beam_power` when there are zarr variables present. Parameters ---------- ds_invariant_power : xr.Dataset Dataset for ping-invariant params associated with power Returns ------- A Dataset representing `ds_beam_power`. """ # TODO: In the future it would be nice to have a dictionary of # attributes stored in one place for all of the variables. # This would reduce unnecessary code duplication in the # functions below. # obtain DataArrays using zarr variables zarr_path = self.parsed2zarr_obj.zarr_file_name backscatter_r = self._get_power_dataarray(zarr_path) angle_athwartship, angle_alongship = self._get_angle_dataarrays(zarr_path) # create power related ds using DataArrays created from zarr file ds_power = xr.merge([backscatter_r, angle_athwartship, angle_alongship]) ds_power = set_time_encodings(ds_power) # obtain additional variables that need to be added to ds_power ds_tmp = [] for ch in self.sorted_channel["power"]: ds_data = self._add_trasmit_pulse_complex(ds_tmp=xr.Dataset(), ch=ch) ds_data = set_time_encodings(ds_data) ds_data = self._attach_vars_to_ds_data(ds_data, ch, rs_size=ds_power.range_sample.size) ds_tmp.append(ds_data) ds_tmp = self.merge_save(ds_tmp, ds_invariant_power) return xr.merge([ds_tmp, ds_power], combine_attrs="override") def _get_ds_complex_zarr(self, ds_invariant_complex: xr.Dataset) -> xr.Dataset: """ Constructs the data set `ds_complex` when there are zarr variables present. Parameters ---------- ds_invariant_complex : xr.Dataset Dataset for ping-invariant params associated with complex data Returns ------- A Dataset representing `ds_complex`. """ # TODO: In the future it would be nice to have a dictionary of # attributes stored in one place for all of the variables. # This would reduce unnecessary code duplication in the # functions below. # obtain DataArrays using zarr variables zarr_path = self.parsed2zarr_obj.zarr_file_name backscatter_r, backscatter_i = self._get_complex_dataarrays(zarr_path) # create power related ds using DataArrays created from zarr file ds_complex = xr.merge([backscatter_r, backscatter_i]) ds_complex = set_time_encodings(ds_complex) # obtain additional variables that need to be added to ds_complex ds_tmp = [] for ch in self.sorted_channel["complex"]: ds_data = self._add_trasmit_pulse_complex(ds_tmp=xr.Dataset(), ch=ch) ds_data = self._add_freq_start_end_ds(ds_data, ch) ds_data = set_time_encodings(ds_data) ds_data = self._attach_vars_to_ds_data( ds_data, ch, rs_size=ds_complex.range_sample.size ) ds_tmp.append(ds_data) ds_tmp = self.merge_save(ds_tmp, ds_invariant_complex) return xr.merge([ds_tmp, ds_complex], combine_attrs="override") def set_beam(self) -> List[xr.Dataset]: """Set the /Sonar/Beam_group1 group.""" # Assemble ping-invariant beam data variables params = [ "transducer_beam_type", "beam_width_alongship", "beam_width_athwartship", "transducer_alpha_x", "transducer_alpha_y", "transducer_alpha_z", "angle_offset_alongship", "angle_offset_athwartship", "angle_sensitivity_alongship", "angle_sensitivity_athwartship", "transducer_offset_x", "transducer_offset_y", "transducer_offset_z", "equivalent_beam_angle", "transceiver_software_version", ] # Assemble dataset for ping-invariant params if self.sorted_channel["complex"]: ds_invariant_complex = self._assemble_ds_ping_invariant(params, "complex") if self.sorted_channel["power"]: ds_invariant_power = self._assemble_ds_ping_invariant(params, "power") if not self.parsed2zarr_obj.temp_zarr_dir: # Assemble dataset for backscatter data and other ping-by-ping data ds_complex = [] ds_power = [] for ch in self.sorted_channel["all"]: if ch in self.sorted_channel["complex"]: ds_data = self._assemble_ds_complex(ch) elif ch in self.sorted_channel["power"]: ds_data = self._assemble_ds_power(ch) else: # skip for channels containing no data continue ds_data = self._attach_vars_to_ds_data( ds_data, ch, rs_size=ds_data.range_sample.size ) if ch in self.sorted_channel["complex"]: ds_complex.append(ds_data) else: ds_power.append(ds_data) # Merge and save group: # if both complex and power data exist: complex data in /Sonar/Beam_group1 group # and power data in /Sonar/Beam_group2 # if only one type of data exist: data in /Sonar/Beam_group1 group ds_beam_power = None if len(ds_complex) > 0: ds_beam = self.merge_save(ds_complex, ds_invariant_complex) if len(ds_power) > 0: ds_beam_power = self.merge_save(ds_power, ds_invariant_power) else: ds_beam = self.merge_save(ds_power, ds_invariant_power) else: if self.sorted_channel["power"]: ds_power = self._get_ds_beam_power_zarr(ds_invariant_power) else: ds_power = None if self.sorted_channel["complex"]: ds_complex = self._get_ds_complex_zarr(ds_invariant_complex) else: ds_complex = None # correctly assign the beam groups ds_beam_power = None if ds_complex: ds_beam = ds_complex if ds_power: ds_beam_power = ds_power else: ds_beam = ds_power # Manipulate some Dataset dimensions to adhere to convention if isinstance(ds_beam_power, xr.Dataset): self.beam_groups_to_convention( ds_beam_power, self.beam_only_names, self.beam_ping_time_names, self.ping_time_only_names, ) self.beam_groups_to_convention( ds_beam, self.beam_only_names, self.beam_ping_time_names, self.ping_time_only_names ) return [ds_beam, ds_beam_power] def set_vendor(self) -> xr.Dataset: """Set the Vendor_specific group.""" config = self.parser_obj.config_datagram["configuration"] # Channel-specific parameters # exist for all channels: # - sa_correction # - gain (indexed by pulse_length) # may not exist for data from earlier EK80 software: # - impedance # - receiver sampling frequency # - transceiver type table_params = [ "transducer_frequency", "impedance", # transceiver impedance (z_er), different from transducer impedance (z_et) "rx_sample_frequency", # receiver sampling frequency "transceiver_type", "pulse_duration", "sa_correction", "gain", ] # grab all variables in table_params param_dict = defaultdict(list) for ch in self.sorted_channel["all"]: v = self.parser_obj.config_datagram["configuration"][ch] for p in table_params: if p in v: # only for parameter that exist in configuration dict param_dict[p].append(v[p]) # make values into numpy arrays for p in param_dict.keys(): param_dict[p] = np.array(param_dict[p]) # Param size check if ( not param_dict["pulse_duration"].shape == param_dict["sa_correction"].shape == param_dict["gain"].shape ): raise ValueError("Narrowband calibration parameters dimension mismatch!") ds_table = xr.Dataset( { "frequency_nominal": ( ["channel"], param_dict["transducer_frequency"], { "units": "Hz", "long_name": "Transducer frequency", "valid_min": 0.0, "standard_name": "sound_frequency", }, ), "sa_correction": ( ["channel", "pulse_length_bin"], np.array(param_dict["sa_correction"]), ), "gain_correction": ( ["channel", "pulse_length_bin"], np.array(param_dict["gain"]), ), "pulse_length": ( ["channel", "pulse_length_bin"], np.array(param_dict["pulse_duration"]), ), }, coords={ "channel": ( ["channel"], self.sorted_channel["all"], self._varattrs["beam_coord_default"]["channel"], ), "pulse_length_bin": ( ["pulse_length_bin"], np.arange(param_dict["pulse_duration"].shape[1]), ), }, ) # Parameters that may or may not exist (due to EK80 software version) if "impedance" in param_dict: ds_table["impedance_transceiver"] = xr.DataArray( param_dict["impedance"], dims=["channel"], coords={"channel": ds_table["channel"]}, attrs={ "units": "ohm", "long_name": "Transceiver impedance", }, ) if "rx_sample_frequency" in param_dict: ds_table["receiver_sampling_frequency"] = xr.DataArray( param_dict["rx_sample_frequency"].astype(float), dims=["channel"], coords={"channel": ds_table["channel"]}, attrs={ "units": "Hz", "long_name": "Receiver sampling frequency", }, ) if "transceiver_type" in param_dict: ds_table["transceiver_type"] = xr.DataArray( param_dict["transceiver_type"], dims=["channel"], coords={"channel": ds_table["channel"]}, attrs={ "long_name": "Transceiver type", }, ) # Broadband calibration parameters: use the zero padding approach cal_ch_ids = [ ch for ch in self.sorted_channel["all"] if "calibration" in config[ch] ] # channels with cal params ds_cal = [] for ch_id in cal_ch_ids: # TODO: consider using the full_ch_name below in place of channel id (ch_id) # full_ch_name = (f"{config[ch]['transceiver_type']} " + # f"{config[ch]['serial_number']}-" + # f"{config[ch]['hw_channel_configuration']} " + # f"{config[ch]['channel_id_short']}") cal_params = [ "gain", "impedance", # transducer impedance (z_et), different from transceiver impedance (z_er) # noqa "phase", "beamwidth_alongship", "beamwidth_athwartship", "angle_offset_alongship", "angle_offset_athwartship", ] param_dict = {} for p in cal_params: if p in config[ch_id]["calibration"]: # only for parameters that exist in dict param_dict[p] = (["cal_frequency"], config[ch_id]["calibration"][p]) ds_ch = xr.Dataset( data_vars=param_dict, coords={ "cal_frequency": ( ["cal_frequency"], config[ch_id]["calibration"]["frequency"], { "long_name": "Frequency of calibration parameter", "units": "Hz", }, ) }, ) ds_ch = ds_ch.expand_dims({"cal_channel_id": [ch_id]}) ds_ch["cal_channel_id"].attrs[ "long_name" ] = "ID of channels containing broadband calibration information" ds_cal.append(ds_ch) ds_cal = xr.merge(ds_cal) if "impedance" in ds_cal: ds_cal = ds_cal.rename_vars({"impedance": "impedance_transducer"}) # Save decimation factors and filter coefficients # Param map values # 1: wide band transceiver (WBT) # 2: pulse compression (PC) param_map = {1: WIDE_BAND_TRANS, 2: PULSE_COMPRESS} coeffs_and_decimation = { t: {FILTER_IMAG: [], FILTER_REAL: [], DECIMATION: []} for t in list(param_map.values()) } for ch in self.sorted_channel["all"]: fil_coeffs = self.parser_obj.fil_coeffs.get(ch, None) fil_df = self.parser_obj.fil_df.get(ch, None) if fil_coeffs and fil_df: # get filter coefficient values for type_num, values in fil_coeffs.items(): param = param_map[type_num] coeffs_and_decimation[param][FILTER_IMAG].append(np.imag(values)) coeffs_and_decimation[param][FILTER_REAL].append(np.real(values)) # get decimation factor values for type_num, value in fil_df.items(): param = param_map[type_num] coeffs_and_decimation[param][DECIMATION].append(value) # Assemble everything into a Dataset ds = xr.merge([ds_table, ds_cal]) # Add the coeffs and decimation ds = ds.pipe(self._add_filter_params, coeffs_and_decimation) # Save the entire config XML in vendor group in case of info loss ds["config_xml"] = self.parser_obj.config_datagram["xml"] return ds @staticmethod def _add_filter_params( dataset: xr.Dataset, coeffs_and_decimation: Dict[str, Dict[str, List[Union[int, NDArray]]]] ) -> xr.Dataset: """ Assembles filter coefficient and decimation factors and add to the dataset Parameters ---------- dataset : xr.Dataset xarray dataset where the filter coefficient and decimation factors will be added coeffs_and_decimation : dict dictionary holding the filter coefficient and decimation factors Returns ------- xr.Dataset The modified dataset with filter coefficient and decimation factors included """ attribute_values = { FILTER_IMAG: "filter coefficients (imaginary part)", FILTER_REAL: "filter coefficients (real part)", DECIMATION: "decimation factor", WIDE_BAND_TRANS: "Wideband transceiver", PULSE_COMPRESS: "Pulse compression", } coeffs_xr_data = {} for cd_type, values in coeffs_and_decimation.items(): for key, data in values.items(): if data: if "filter" in key: attrs = { "long_name": f"{attribute_values[cd_type]} {attribute_values[key]}" } # filter_i and filter_r max_len = np.max([len(a) for a in data]) # Pad arrays data = np.asarray( [ np.pad(a, (0, max_len - len(a)), "constant", constant_values=np.nan) for a in data ] ) dims = ["channel", f"{cd_type}_filter_n"] else: attrs = { "long_name": f"{attribute_values[cd_type]} {attribute_values[DECIMATION]}" # noqa } dims = ["channel"] # Set the xarray data dictionary coeffs_xr_data[f"{cd_type}_{key}"] = (dims, data, attrs) return dataset.assign(coeffs_xr_data)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,845
OSOceanAcoustics/echopype
refs/heads/main
/echopype/consolidate/api.py
import datetime import pathlib from typing import Optional, Union import numpy as np import xarray as xr from ..calibrate.ek80_complex import get_filter_coeff from ..echodata import EchoData from ..echodata.simrad import retrieve_correct_beam_group from ..utils.io import validate_source_ds_da from ..utils.prov import add_processing_level from .split_beam_angle import add_angle_to_ds, get_angle_complex_samples, get_angle_power_samples def swap_dims_channel_frequency(ds: xr.Dataset) -> xr.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 ---------- ds : xr.Dataset 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. """ # Only possible if no duplicated frequencies if np.unique(ds["frequency_nominal"]).size == ds["frequency_nominal"].size: return ( ds.set_coords("frequency_nominal") .swap_dims({"channel": "frequency_nominal"}) .reset_coords("channel") ) else: raise ValueError( "Duplicated transducer nominal frequencies exist in the file. " "Operation is not valid." ) def add_depth( ds: xr.Dataset, depth_offset: float = 0, tilt: float = 0, downward: bool = True, ) -> xr.Dataset: """ Create a depth data variable based on data in Sv dataset. The depth is generated based on whether the transducers are mounted vertically or with a polar angle to vertical, and whether the transducers were pointed up or down. Parameters ---------- ds : xr.Dataset Source Sv dataset to which a depth variable will be added. Must contain `echo_range`. depth_offset : float Offset along the vertical (depth) dimension to account for actual transducer position in water, since `echo_range` is counted from transducer surface. Default is 0. tilt : float Transducer tilt angle [degree]. Default is 0 (transducer mounted vertically). downward : bool Whether or not the transducers point downward. Default to True. Returns ------- The input dataset with a `depth` variable (in meters) added Notes ----- Currently this function only scalar inputs of depth_offset and tilt angle. In future expansion we plan to add the following options: * Allow inputs as xr.DataArray for time-varying variations of these variables * Use data stored in the EchoData object or raw-converted file from which the Sv is derived, specifically `water_level`, `vertical_offtset` and `tilt` in the `Platform` group. """ # TODO: add options to use water_depth, vertical_offset, tilt stored in EchoData # # Water level has to come from somewhere # if depth_offset is None: # if "water_level" in ds: # depth_offset = ds["water_level"] # else: # raise ValueError( # "water_level not found in dataset and needs to be supplied by the user" # ) # # If not vertical needs to have tilt # if not vertical: # if tilt is None: # if "tilt" in ds: # tilt = ds["tilt"] # else: # raise ValueError( # "tilt not found in dataset and needs to be supplied by the user. " # "Required when vertical=False" # ) # else: # tilt = 0 # Multiplication factor depending on if transducers are pointing downward mult = 1 if downward else -1 # Compute depth ds["depth"] = mult * ds["echo_range"] * np.cos(tilt / 180 * np.pi) + depth_offset ds["depth"].attrs = {"long_name": "Depth", "standard_name": "depth", "units": "m"} # Add history attribute history_attr = ( f"{datetime.datetime.utcnow()} +00:00. " "Added based on echo_range or other data in Sv dataset." # noqa ) ds["depth"] = ds["depth"].assign_attrs({"history": history_attr}) return ds @add_processing_level("L2A") def add_location(ds: xr.Dataset, echodata: EchoData = None, nmea_sentence: Optional[str] = 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 ---------- ds : xr.Dataset An Sv or MVBS dataset for which the geographical locations will be added to echodata An `EchoData` object holding the raw data nmea_sentence NMEA sentence to select a subset of location data (optional) Returns ------- The input dataset with the location data added """ def sel_interp(var, time_dim_name): # NMEA sentence selection if nmea_sentence: position_var = echodata["Platform"][var][ echodata["Platform"]["sentence_type"] == nmea_sentence ] else: position_var = echodata["Platform"][var] if len(position_var) == 1: # Propagate single, fixed-location coordinate return xr.DataArray( data=position_var.values[0] * np.ones(len(ds["ping_time"]), dtype=np.float64), dims=["ping_time"], attrs=position_var.attrs, ) else: # Values may be nan if there are ping_time values outside the time_dim_name range return position_var.interp(**{time_dim_name: ds["ping_time"]}) if "longitude" not in echodata["Platform"] or echodata["Platform"]["longitude"].isnull().all(): raise ValueError("Coordinate variables not present or all nan") interp_ds = ds.copy() time_dim_name = list(echodata["Platform"]["longitude"].dims)[0] interp_ds["latitude"] = sel_interp("latitude", time_dim_name) interp_ds["longitude"] = sel_interp("longitude", time_dim_name) # Most attributes are attached automatically via interpolation # here we add the history history_attr = ( f"{datetime.datetime.utcnow()} +00:00. " "Interpolated or propagated from Platform latitude/longitude." # noqa ) for da_name in ["latitude", "longitude"]: interp_ds[da_name] = interp_ds[da_name].assign_attrs({"history": history_attr}) if time_dim_name in interp_ds: interp_ds = interp_ds.drop_vars(time_dim_name) return interp_ds def add_splitbeam_angle( source_Sv: Union[xr.Dataset, str, pathlib.Path], echodata: EchoData, waveform_mode: str, encode_mode: str, pulse_compression: bool = False, storage_options: dict = {}, return_dataset: bool = True, ) -> xr.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 An ``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`` return_dataset: bool, default=True If ``True``, ``source_Sv`` with split-beam angles added will be returned. ``return_dataset=False`` is useful when ``source_Sv`` is a path and users only want to write the split-beam angle data to this path. Returns ------- xr.Dataset or None If ``return_dataset=False``, nothing will be returned. If ``return_dataset=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. """ # ensure that echodata was produced by EK60 or EK80-like sensors if echodata.sonar_model not in ["EK60", "ES70", "EK80", "ES80", "EA640"]: raise ValueError( "The sonar model that produced echodata does not have split-beam " "transducers, split-beam angles cannot be added to source_Sv!" ) # validate the source_Sv type or path (if it is provided) source_Sv, file_type = validate_source_ds_da(source_Sv, storage_options) # initialize source_Sv_path source_Sv_path = None if isinstance(source_Sv, str): # store source_Sv path so we can use it to write to later source_Sv_path = source_Sv # TODO: In the future we can improve this by obtaining the variable names, channels, # and dimension lengths directly from source_Sv using zarr or netcdf4. This would # prevent the unnecessary loading in of the coordinates, which the below statement does. # open up Dataset using source_Sv path source_Sv = xr.open_dataset(source_Sv, engine=file_type, chunks={}, **storage_options) # raise not implemented error if source_Sv corresponds to MVBS if source_Sv.attrs["processing_function"] == "commongrid.compute_MVBS": raise NotImplementedError("Adding split-beam data to MVBS has not been implemented!") # check that the appropriate waveform and encode mode have been given # and obtain the echodata group path corresponding to encode_mode ed_beam_group = retrieve_correct_beam_group(echodata, waveform_mode, encode_mode) # check that source_Sv at least has a channel dimension if "channel" not in source_Sv.variables: raise ValueError("The input source_Sv Dataset must have a channel dimension!") # Select ds_beam channels from source_Sv ds_beam = echodata[ed_beam_group].sel(channel=source_Sv["channel"].values) # Assemble angle param dict angle_param_list = [ "angle_sensitivity_alongship", "angle_sensitivity_athwartship", "angle_offset_alongship", "angle_offset_athwartship", ] angle_params = {} for p_name in angle_param_list: if p_name in source_Sv: angle_params[p_name] = source_Sv[p_name] else: raise ValueError(f"source_Sv does not contain the necessary parameter {p_name}!") # fail if source_Sv and ds_beam do not have the same lengths # for ping_time, range_sample, and channel same_dim_lens = [ ds_beam.dims[dim] == source_Sv.dims[dim] for dim in ["channel", "ping_time", "range_sample"] ] if not same_dim_lens: raise ValueError( "The 'source_Sv' dataset does not have the same dimensions as data in 'echodata'!" ) # obtain split-beam angles from # CW mode data if waveform_mode == "CW": if encode_mode == "power": # power data theta, phi = get_angle_power_samples(ds_beam, angle_params) else: # complex data # operation is identical with BB complex data theta, phi = get_angle_complex_samples(ds_beam, angle_params) # BB mode data else: if pulse_compression: # with pulse compression # put receiver fs into the same dict for simplicity pc_params = get_filter_coeff( echodata["Vendor_specific"].sel(channel=source_Sv["channel"].values) ) pc_params["receiver_sampling_frequency"] = source_Sv["receiver_sampling_frequency"] theta, phi = get_angle_complex_samples(ds_beam, angle_params, pc_params) else: # without pulse compression # operation is identical with CW complex data theta, phi = get_angle_complex_samples(ds_beam, angle_params) # add theta and phi to source_Sv input source_Sv = add_angle_to_ds( theta, phi, source_Sv, return_dataset, source_Sv_path, file_type, storage_options ) # Add history attribute history_attr = ( f"{datetime.datetime.utcnow()} +00:00. " "Calculated using data stored in the Beam groups of the echodata object." # noqa ) for da_name in ["angle_alongship", "angle_athwartship"]: source_Sv[da_name] = source_Sv[da_name].assign_attrs({"history": history_attr}) return source_Sv
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,846
OSOceanAcoustics/echopype
refs/heads/main
/echopype/convert/__init__.py
""" Unpack manufacturer-specific data files into an interoperable netCDF or Zarr format. The current version supports: - Simrad EK60 echosounder ``.raw`` data - Simrad EK80 echosounder ``.raw`` data - ASL Environmental Sciences AZFP echosounder ``.01A`` data """ # flake8: noqa from .parse_ad2cp import ParseAd2cp from .parse_azfp import ParseAZFP from .parse_base import ParseBase from .parse_ek60 import ParseEK60 from .parse_ek80 import ParseEK80 from .set_groups_ad2cp import SetGroupsAd2cp from .set_groups_azfp import SetGroupsAZFP from .set_groups_ek60 import SetGroupsEK60 from .set_groups_ek80 import SetGroupsEK80
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,847
OSOceanAcoustics/echopype
refs/heads/main
/echopype/utils/prov.py
import functools import re from datetime import datetime as dt from pathlib import Path from typing import Any, Dict, List, Tuple, Union import numpy as np import xarray as xr from _echopype_version import version as ECHOPYPE_VERSION from numpy.typing import NDArray from typing_extensions import Literal from .log import _init_logger ProcessType = Literal["conversion", "combination", "processing", "mask"] # Note that this PathHint is defined differently from the one in ..core PathHint = Union[str, Path] PathSequenceHint = Union[List[PathHint], Tuple[PathHint], NDArray[PathHint]] logger = _init_logger(__name__) def echopype_prov_attrs(process_type: ProcessType) -> Dict[str, str]: """ Standard echopype software attributes for provenance Parameters ---------- process_type : ProcessType Echopype process function type """ prov_dict = { f"{process_type}_software_name": "echopype", f"{process_type}_software_version": ECHOPYPE_VERSION, f"{process_type}_time": dt.utcnow().isoformat(timespec="seconds") + "Z", # use UTC time } return prov_dict def _sanitize_source_files(paths: Union[PathHint, PathSequenceHint]): """ Create sanitized list of string paths from heterogeneous path inputs. Parameters ---------- paths : Union[PathHint, PathSequenceHint] File paths as either a single path string or pathlib Path, a sequence (tuple, list or np.ndarray) of strings or pathlib Paths, or a mixed sequence that may contain another sequence as an element. Returns ------- paths_list : List[str] List of file paths. Empty list if no source path element was parsed successfully. """ sequence_types = (list, tuple, np.ndarray) if isinstance(paths, (str, Path)): return [str(paths)] elif isinstance(paths, sequence_types): paths_list = [] for p in paths: if isinstance(p, (str, Path)): paths_list.append(str(p)) elif isinstance(p, sequence_types): paths_list += [str(pp) for pp in p if isinstance(pp, (str, Path))] else: logger.warning( "Unrecognized file path element type, path element will not be" f" written to (meta)source_file provenance attribute. {p}" ) return paths_list else: logger.warning( "Unrecognized file path element type, path element will not be" f" written to (meta)source_file provenance attribute. {paths}" ) return [] def source_files_vars( source_paths: Union[PathHint, PathSequenceHint], meta_source_paths: Union[PathHint, PathSequenceHint] = None, ) -> Dict[str, Dict[str, Tuple]]: """ Create source_filenames and meta_source_filenames provenance variables dicts to be used for creating xarray DataArray. Parameters ---------- source_paths : Union[PathHint, PathSequenceHint] Source file paths as either a single path string or pathlib Path, a sequence (tuple, list or np.ndarray) of strings or pathlib Paths, or a mixed sequence that may contain another sequence as an element. meta_source_paths : Union[PathHint, PathSequenceHint] Source file paths for metadata files (often as XML files), as either a single path string or pathlib Path, a sequence (tuple, list or np.ndarray) of strings or pathlib Paths, or a mixed sequence that may contain another sequence as an element. Returns ------- files_vars : Dict[str, Dict[str, Tuple]] Contains 3 items: source_files_var : Dict[str, Tuple] Single-element dict containing a tuple for creating the source_filenames xarray DataArray with filenames dimension meta_source_files_var : Dict[str, Tuple] Single-element dict containing a tuple for creating the meta_source_filenames xarray DataArray with filenames dimension source_files_coord : Dict[str, Tuple] Single-element dict containing a tuple for creating the filenames coordinate variable xarray DataArray """ source_files = _sanitize_source_files(source_paths) files_vars = dict() files_vars["source_files_var"] = { "source_filenames": ( "filenames", source_files, {"long_name": "Source filenames"}, ), } if meta_source_paths is None or meta_source_paths == "": files_vars["meta_source_files_var"] = None else: meta_source_files = _sanitize_source_files(meta_source_paths) files_vars["meta_source_files_var"] = { "meta_source_filenames": ( "filenames", meta_source_files, {"long_name": "Metadata source filenames"}, ), } files_vars["source_files_coord"] = { "filenames": ( "filenames", list(range(len(source_files))), {"long_name": "Index for data and metadata source filenames"}, ), } return files_vars def _check_valid_latlon(ds): """Verify that the dataset contains valid latitude and longitude variables""" if ( "longitude" in ds and not ds["longitude"].isnull().all() and "latitude" in ds and not ds["latitude"].isnull().all() ): return True else: return False # L0 is not actually used by echopype but is included for completeness PROCESSING_LEVELS = dict( L0="Level 0", L1A="Level 1A", L1B="Level 1B", L2A="Level 2A", L2B="Level 2B", L3A="Level 3A", L3B="Level 3B", L4="Level 4", ) def add_processing_level(processing_level_code: str, is_echodata: bool = False) -> Any: """ Wraps functions or methods that return either an xr.Dataset or an echodata object Parameters ---------- processing_level_code : str Data processing level code. Can be either the exact code (eg, L1A, L2B, L4) or using * as a wildcard for either level or sublevel (eg, L*A, L2*) where the wildcard value of the input is propagated to the output. is_echodata : bool Flag specifying if the decorated function returns an EchoData object (optional) Returns ------- An xr.Dataset or EchoData object with processing level attributes inserted if appropriate, or unchanged otherwise. """ def wrapper(func): # TODO: Add conventions attr, with "ACDD-1.3" entry, if not already present? def _attrs_dict(processing_level): return { "processing_level": processing_level, "processing_level_url": "https://echopype.readthedocs.io/en/stable/processing-levels.html", # noqa } if not ( processing_level_code in PROCESSING_LEVELS or re.fullmatch(r"L\*[A|B]|L[1-4]\*", processing_level_code) ): raise ValueError( f"Decorator processing_level_code {processing_level_code} " f"used in {func.__qualname__} is invalid." ) # Found the class method vs module function solution in # https://stackoverflow.com/a/49100736 if len(func.__qualname__.split(".")) > 1: # Handle class methods @functools.wraps(func) def inner(self, *args, **kwargs): func(self, *args, **kwargs) if _check_valid_latlon(self["Platform"]): processing_level = PROCESSING_LEVELS[processing_level_code] self["Top-level"] = self["Top-level"].assign_attrs( _attrs_dict(processing_level) ) else: logger.info( "EchoData object (converted raw file) does not contain " "valid Platform location data. Processing level attributes " "will not be added." ) return inner else: # Handle stand-alone module functions @functools.wraps(func) def inner(*args, **kwargs): dataobj = func(*args, **kwargs) if is_echodata: ed = dataobj if _check_valid_latlon(ed["Platform"]): # The decorator is passed the exact, final level code, with sublevel processing_level = PROCESSING_LEVELS[processing_level_code] ed["Top-level"] = ed["Top-level"].assign_attrs( _attrs_dict(processing_level) ) else: logger.info( "EchoData object (converted raw file) does not contain " "valid Platform location data. Processing level attributes " "will not be added." ) return ed elif isinstance(dataobj, xr.Dataset): ds = dataobj if _check_valid_latlon(ds): if processing_level_code in PROCESSING_LEVELS: # The decorator is passed the exact, final level code, with sublevel processing_level = PROCESSING_LEVELS[processing_level_code] elif ( "*" in processing_level_code and "input_processing_level" in ds.attrs.keys() ): if processing_level_code[-1] == "*": # The decorator is passed a level code without sublevel (eg, L3*). # The decorated function's "input" dataset's sublevel (A or B) will # be propagated to the function's output dataset. For L2 and L3 sublevel = ds.attrs["input_processing_level"][-1] level = processing_level_code[1] elif processing_level_code[1] == "*": # The decorator is passed a sublevel code without level (eg, L*A). # The decorated function's "input" dataset's level (2 or 3) will # be propagated to the function's output dataset. For L2 and L3 sublevel = processing_level_code[-1] level = ds.attrs["input_processing_level"][-2] processing_level = PROCESSING_LEVELS[f"L{level}{sublevel}"] del ds.attrs["input_processing_level"] else: raise RuntimeError( "Processing level attributes (processing_level_code {processing_level_code}) " # noqa f"cannot be added. Please ensure that {func.__qualname__} " "uses the function insert_input_processing_level." ) ds = ds.assign_attrs(_attrs_dict(processing_level)) else: logger.info( "xarray Dataset does not contain valid location data. " "Processing level attributes will not be added." ) if "input_processing_level" in ds.attrs: del ds.attrs["input_processing_level"] return ds else: raise RuntimeError( f"{func.__qualname__}: Processing level decorator function cannot be used " "with a function that does not return an xarray Dataset or EchoData object" ) return inner return wrapper def insert_input_processing_level(ds, input_ds): """ Copy processing_level attribute from input xr.Dataset, if it exists, and write it out as input_processing_level Parameters ---------- ds : xr.Dataset The xr.Dataset returned by the decorated function input_ds : xr.Dataset The xr.Dataset that is the "input" to the decorated function Returns ------- ds with input_processing_level attribute inserted if appropriate, a renamed copy of the processing_level attribute from input_ds if present. """ if "processing_level" in input_ds.attrs.keys(): return ds.assign_attrs({"input_processing_level": input_ds.attrs["processing_level"]}) else: return ds
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,848
OSOceanAcoustics/echopype
refs/heads/main
/echopype/convert/parse_ek80.py
from .parse_base import ParseEK class ParseEK80(ParseEK): """Class for converting data from Simrad EK80 echosounders.""" def __init__(self, file, params, storage_options={}, dgram_zarr_vars={}): super().__init__(file, params, storage_options, dgram_zarr_vars) self.environment = {} # dictionary to store environment data def _select_datagrams(self, params): """Translates user input into specific datagrams or ALL""" def translate_to_dgram(s): if s == "ALL": return ["ALL"] # The GPS flag indicates that only the NME and MRU datagrams are parsed. # It is kept in the list because it is used in SetGroups # to flag that only the platform group is saved. elif s == "GPS": return ["NME", "MRU"] # CONFIG flag indicates that only the configuration XML is parsed. # The XML flag is not needed because the configuration is always # the first datagram parsed. elif s == "CONFIG": return ["CONFIG"] # XML flag indicates that XML0 datagrams should be read. # ENV flag indicates that of the XML datagrams, # only keep the environment datagrams elif s == "ENV": return ["XML", "ENV"] # EXPORT_XML flag passed in only by the to_xml function # Used to print the export message when writing to an xml file elif s == "EXPORT_XML": return ["print_export_msg"] else: raise ValueError("Unknown data type", params) # Params is a string when user sets data_type in to_netcdf/to_zarr if isinstance(params, str): dgrams = translate_to_dgram(params) # Params is a list when the parse classes are called by to_xml else: dgrams = [] for p in params: dgrams += translate_to_dgram(p) return dgrams
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,849
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/echodata/test_echodata_simrad.py
""" Tests functions contained within echodata/simrad.py """ import pytest from echopype.echodata.simrad import retrieve_correct_beam_group, check_input_args_combination @pytest.mark.parametrize( ("waveform_mode", "encode_mode", "pulse_compression"), [ pytest.param("CW", "comp_power", None, marks=pytest.mark.xfail(strict=True, reason='This test should fail since comp_power ' 'is not an acceptable choice for encode_mode.')), pytest.param("CB", None, None, marks=pytest.mark.xfail(strict=True, reason='This test should fail since CB is not an ' 'acceptable choice for waveform_mode.')), pytest.param("BB", "power", None, marks=pytest.mark.xfail(strict=True, reason='This test should fail since BB and power is ' 'not an acceptable combination.')), pytest.param("BB", "power", True, marks=pytest.mark.xfail(strict=True, reason='This test should fail since BB and complex ' 'must be used if pulse_compression is True.')), pytest.param("CW", "complex", True, marks=pytest.mark.xfail(strict=True, reason='This test should fail since BB and complex ' 'must be used if pulse_compression is True.')), pytest.param("CW", "power", True, marks=pytest.mark.xfail(strict=True, reason='This test should fail since BB and complex ' 'must be used if pulse_compression is True.')), ("CW", "complex", False), ("CW", "power", False), ("BB", "complex", False), ("BB", "complex", True), ], ids=["incorrect_encode_mode", "incorrect_waveform_mode", "BB_power_combo", "BB_power_pc_True", "CW_complex_pc_True", "CW_power_pc_True", "CW_complex_pc_False", "CW_power_pc_False", "BB_complex_pc_False", "BB_complex_pc_True"] ) def test_check_input_args_combination(waveform_mode: str, encode_mode: str, pulse_compression: bool): """ Ensures that ``check_input_args_combination`` functions correctly when provided various combinations of the input parameters. Parameters ---------- waveform_mode: str Type of transmit waveform encode_mode: str Type of encoded return echo data pulse_compression: bool States whether pulse compression should be used """ check_input_args_combination(waveform_mode, encode_mode, pulse_compression) def test_retrieve_correct_beam_group(): # TODO: create this test once we are happy with the form of retrieve_correct_beam_group pytest.skip("We need to add tests for retrieve_correct_beam_group!")
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,850
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/utils/test_coding.py
import pytest import numpy as np import xarray as xr import math import dask from echopype.utils.coding import _get_auto_chunk, set_netcdf_encodings @pytest.mark.parametrize( "chunk", ["auto", "5MB", "10MB", "30MB", "70MB", "100MB", "default"], ) def test__get_auto_chunk(chunk): random_data = 15 + 8 * np.random.randn(10, 1000, 1000) da = xr.DataArray( data=random_data, dims=["x", "y", "z"] ) if chunk == "auto": dask_data = da.chunk('auto').data elif chunk == "default": dask_data = da.chunk(_get_auto_chunk(da)).data else: dask_data = da.chunk(_get_auto_chunk(da, chunk)).data chunk_byte_size = math.prod(dask_data.chunksize + (dask_data.itemsize,)) if chunk in ["auto", "100MB", "default"]: assert chunk_byte_size == dask_data.nbytes, "Default chunk is not equal to data array size!" else: assert chunk_byte_size <= dask.utils.parse_bytes(chunk), "Calculated chunk exceeded max chunk!" def test_set_netcdf_encodings(): # create a test dataset ds = xr.Dataset( { "var1": xr.DataArray(np.random.rand(10), dims="dim1"), "var2": xr.DataArray(np.random.rand(10), dims="dim1", attrs={"attr1": "value1"}), "var3": xr.DataArray(["a", "b", "c"], dims="dim2"), }, attrs={"global_attr": "global_value"}, ) # test with default compression settings encoding = set_netcdf_encodings(ds, {}) assert isinstance(encoding, dict) assert len(encoding) == 3 assert "var1" in encoding assert "var2" in encoding assert "var3" in encoding assert encoding["var1"]["zlib"] is True assert encoding["var1"]["complevel"] == 4 assert encoding["var2"]["zlib"] is True assert encoding["var2"]["complevel"] == 4 assert encoding["var3"]["zlib"] is False # test with custom compression settings compression_settings = {"zlib": True, "complevel": 5} encoding = set_netcdf_encodings(ds, compression_settings) assert isinstance(encoding, dict) assert len(encoding) == 3 assert "var1" in encoding assert "var2" in encoding assert "var3" in encoding assert encoding["var1"]["zlib"] is True assert encoding["var1"]["complevel"] == 5 assert encoding["var2"]["zlib"] is True assert encoding["var2"]["complevel"] == 5 assert encoding["var3"]["zlib"] is False
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,851
OSOceanAcoustics/echopype
refs/heads/main
/echopype/echodata/convention/conv.py
from importlib import resources from typing import Optional import yaml from .. import convention class _Convention: def __init__(self, version: Optional[str]): """Prepare to read the convention yaml file""" self._yaml_dict = {} # Hardwired to 1.0, for now self.version = "1.0" if version: self.version = version @property def yaml_dict(self): """Read data from disk""" if self._yaml_dict: # Data has already been read, return it directly return self._yaml_dict with resources.open_text(package=convention, resource=f"{self.version}.yml") as fid: convention_yaml = yaml.load(fid, Loader=yaml.SafeLoader) self._yaml_dict = convention_yaml return self._yaml_dict
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,852
OSOceanAcoustics/echopype
refs/heads/main
/.ci_helpers/run-test.py
"""run-test.py Script to run tests in Github and locally. """ import argparse import glob import os import re import shutil import sys from pathlib import Path import pytest from pytest import ExitCode EXIT_CODES = { ExitCode.OK: 0, ExitCode.TESTS_FAILED: 1, ExitCode.INTERRUPTED: 2, ExitCode.INTERNAL_ERROR: 3, ExitCode.USAGE_ERROR: 4, ExitCode.NO_TESTS_COLLECTED: 5, } MODULES_TO_TEST = { "root": {}, # This is to test the root folder. "calibrate": {}, "clean": {}, "commongrid": {}, "consolidate": {}, "convert": {}, "echodata": {}, "mask": {}, "metrics": {}, "qc": {}, "utils": {}, "visualize": {}, } if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run tests listed.") parser.add_argument( "touchedfiles", metavar="TOUCHED_FILES", type=str, nargs="?", default="", help="Comma separated list of changed files.", ) parser.add_argument("--pytest-args", type=str, help="Optional pytest args", default="") parser.add_argument( "--local", action="store_true", help="Optional flag for running tests locally, not in continuous integration.", ) parser.add_argument( "--include-cov", action="store_true", help="Optional flag for including coverage. Exports to coverage.xml by default.", ) args = parser.parse_args() if args.local: temp_path = Path("~/.echopype/temp_output") dump_path = Path("echopype/test_data/dump") if temp_path.exists(): shutil.rmtree(temp_path) if dump_path.exists(): shutil.rmtree(dump_path) if args.touchedfiles == "": echopype_folder = Path("echopype") file_list = glob.glob(str(echopype_folder / "**" / "*.py"), recursive=True) else: file_list = args.touchedfiles.split(",") else: file_list = args.touchedfiles.split(",") pytest_args = [] if args.pytest_args: pytest_args = args.pytest_args.split(",") if args.include_cov: # Checks for cov in pytest_args for arg in pytest_args: if re.match("--cov", arg) is not None: raise ValueError( "pytest args may not have any cov arguments if --include-cov is set." ) pytest_args = pytest_args + [ "--cov-report=xml", "--cov-append", ] test_to_run = {} for module, mod_extras in MODULES_TO_TEST.items(): if module == "root": file_globs = [ "echopype/*", "echopype/tests/*", ] else: file_globs = [ f"echopype/{module}/*", f"echopype/tests/{module}/*", ] if "extra_globs" in mod_extras: file_globs = file_globs + mod_extras["extra_globs"] for f in file_list: file_path = Path(f) file_name, file_ext = os.path.splitext(os.path.basename(f)) if file_ext == ".py": if any(((file_path.match(fg)) for fg in file_globs)): if module not in test_to_run: test_to_run[module] = [] test_to_run[module].append(file_path) original_pytest_args = pytest_args.copy() total_exit_codes = [] for k, v in test_to_run.items(): print(f"=== RUNNING {k.upper()} TESTS===") print(f"Touched files: {','.join([os.path.basename(p) for p in v])}") if k == "root": file_glob_str = "echopype/tests/test_*.py" cov_mod_arg = ["--cov=echopype"] else: file_glob_str = f"echopype/tests/{k}/*.py" cov_mod_arg = [f"--cov=echopype/{k}"] if args.include_cov: pytest_args = original_pytest_args + cov_mod_arg test_files = glob.glob(file_glob_str) final_args = pytest_args + test_files print(f"Pytest args: {final_args}") exit_code = pytest.main(final_args) total_exit_codes.append(EXIT_CODES[exit_code]) if len(total_exit_codes) == 0: print("No test(s) were run.") sys.exit(0) if all(True if e == 0 else False for e in total_exit_codes): print("All tests have been run successfully!") sys.exit(0) else: print("Some runs have failed. Please see the log.") sys.exit(1)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,853
OSOceanAcoustics/echopype
refs/heads/main
/echopype/metrics/__init__.py
""" Functions to compute summary statistics from echo data. """ from .summary_statistics import abundance, aggregation, center_of_mass, dispersion, evenness __all__ = [ "abundance", "aggregation", "center_of_mass", "dispersion", "evenness", ]
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,854
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/calibrate/test_calibrate_ek80.py
import pytest import numpy as np import pandas as pd import xarray as xr import echopype as ep @pytest.fixture def ek80_path(test_path): return test_path['EK80'] @pytest.fixture def ek80_cal_path(test_path): return test_path['EK80_CAL'] @pytest.fixture def ek80_ext_path(test_path): return test_path['EK80_EXT'] def test_ek80_transmit_chirp(ek80_cal_path, ek80_ext_path): """ Test transmit chirp reconstruction against Andersen et al. 2021/pyEcholab implementation """ ek80_raw_path = ek80_cal_path / "2018115-D20181213-T094600.raw" # rx impedance / rx fs / tcvr type ed = ep.open_raw(ek80_raw_path, sonar_model="EK80") # Calibration object detail waveform_mode = "BB" encode_mode = "complex" cal_obj = ep.calibrate.calibrate_ek.CalibrateEK80( echodata=ed, waveform_mode=waveform_mode, encode_mode=encode_mode, env_params=None, cal_params=None ) fs = cal_obj.cal_params["receiver_sampling_frequency"] filter_coeff = ep.calibrate.ek80_complex.get_filter_coeff(ed["Vendor_specific"].sel(channel=cal_obj.chan_sel)) tx, tx_time = ep.calibrate.ek80_complex.get_transmit_signal( ed["Sonar/Beam_group1"].sel(channel=cal_obj.chan_sel), filter_coeff, waveform_mode, fs ) tau_effective = ep.calibrate.ek80_complex.get_tau_effective( ytx_dict=tx, fs_deci_dict={k: 1 / np.diff(v[:2]) for (k, v) in tx_time.items()}, # decimated fs waveform_mode=cal_obj.waveform_mode, channel=cal_obj.chan_sel, ping_time=cal_obj.echodata["Sonar/Beam_group1"]["ping_time"], ) # Load pyEcholab object: channel WBT 714590-15 ES70-7C import pickle with open(ek80_ext_path / "pyecholab/pyel_BB_calibration.pickle", 'rb') as handle: pyecholab_BB = pickle.load(handle) # Compare first ping since all params identical ch_sel = "WBT 714590-15 ES70-7C" # receive sampling frequency assert pyecholab_BB["rx_sample_frequency"][0] == fs.sel(channel=ch_sel) # WBT filter assert np.all(pyecholab_BB["filters"][1]["coefficients"] == filter_coeff[ch_sel]["wbt_fil"]) assert np.all(pyecholab_BB["filters"][1]["decimation_factor"] == filter_coeff[ch_sel]["wbt_decifac"]) # PC filter assert np.all(pyecholab_BB["filters"][2]["coefficients"] == filter_coeff[ch_sel]["pc_fil"]) assert np.all(pyecholab_BB["filters"][2]["decimation_factor"] == filter_coeff[ch_sel]["pc_decifac"]) # transmit signal assert np.allclose(pyecholab_BB["_tx_signal"][0], tx[ch_sel]) # tau effective # use np.isclose for now since difference is 2.997176e-5 (pyecholab) and 2.99717595e-05 (echopype) # will see if it causes downstream major differences assert np.isclose(tau_effective.sel(channel=ch_sel).data, pyecholab_BB["_tau_eff"][0]) def test_ek80_BB_params(ek80_cal_path, ek80_ext_path): """ Test power from pulse compressed BB data """ ek80_raw_path = ek80_cal_path / "2018115-D20181213-T094600.raw" # rx impedance / rx fs / tcvr type ed = ep.open_raw(ek80_raw_path, sonar_model="EK80") # Calibration object detail waveform_mode = "BB" encode_mode = "complex" cal_obj = ep.calibrate.calibrate_ek.CalibrateEK80( echodata=ed, waveform_mode=waveform_mode, encode_mode=encode_mode, env_params={"formula_absorption": "FG"}, cal_params=None ) z_er = cal_obj.cal_params["impedance_transceiver"] z_et = cal_obj.cal_params["impedance_transducer"] # B_theta_phi_m = cal_obj._get_B_theta_phi_m() params_BB_map = { # param name mapping: echopype (ep) : pyecholab (pyel) "angle_offset_alongship": "angle_offset_alongship", "angle_offset_athwartship": "angle_offset_athwartship", "beamwidth_alongship": "beam_width_alongship", "beamwidth_athwartship": "beam_width_athwartship", "gain_correction": "gain", # this is *before* B_theta_phi_m BB correction } # Load pyEcholab object: channel WBT 714590-15 ES70-7C import pickle with open(ek80_ext_path / "pyecholab/pyel_BB_calibration.pickle", 'rb') as handle: pyel_BB_cal = pickle.load(handle) with open(ek80_ext_path / "pyecholab/pyel_BB_raw_data.pickle", 'rb') as handle: pyel_BB_raw = pickle.load(handle) ch_sel = "WBT 714590-15 ES70-7C" # pyecholab calibration object # TODO: need to check B_theta_phi_m values assert pyel_BB_cal["impedance"] == z_er.sel(channel=ch_sel) for p_ep, p_pyel in params_BB_map.items(): # all interpolated BB params assert np.isclose(pyel_BB_cal[p_pyel][0], cal_obj.cal_params[p_ep].sel(channel=ch_sel).isel(ping_time=0)) assert pyel_BB_cal["sa_correction"][0] == cal_obj.cal_params["sa_correction"].sel(channel=ch_sel).isel(ping_time=0) assert pyel_BB_cal["sound_speed"] == cal_obj.env_params["sound_speed"] assert np.isclose( pyel_BB_cal["absorption_coefficient"][0], cal_obj.env_params["sound_absorption"].sel(channel=ch_sel).isel(ping_time=0) ) # pyecholab raw_data object assert pyel_BB_raw["ZTRANSDUCER"] == z_et.sel(channel=ch_sel).isel(ping_time=0) assert pyel_BB_raw["transmit_power"][0] == ed["Sonar/Beam_group1"]["transmit_power"].sel(channel=ch_sel).isel(ping_time=0) assert pyel_BB_raw["transceiver_type"] == ed["Vendor_specific"]["transceiver_type"].sel(channel=ch_sel) def test_ek80_BB_range(ek80_cal_path, ek80_ext_path): ek80_raw_path = ek80_cal_path / "2018115-D20181213-T094600.raw" # rx impedance / rx fs / tcvr type ed = ep.open_raw(ek80_raw_path, sonar_model="EK80") # Calibration object waveform_mode = "BB" encode_mode = "complex" cal_obj = ep.calibrate.calibrate_ek.CalibrateEK80( echodata=ed, waveform_mode=waveform_mode, encode_mode=encode_mode, env_params={"formula_absorption": "FG"}, cal_params=None ) ch_sel = "WBT 714590-15 ES70-7C" # Load pyecholab pickle import pickle with open(ek80_ext_path / "pyecholab/pyel_BB_p_data.pickle", 'rb') as handle: pyel_BB_p_data = pickle.load(handle) # Assert ep_vals = cal_obj.range_meter.sel(channel=ch_sel).isel(ping_time=0).data pyel_vals = pyel_BB_p_data["range"] assert np.allclose(pyel_vals, ep_vals) def test_ek80_BB_power_Sv(ek80_cal_path, ek80_ext_path): ek80_raw_path = ek80_cal_path / "2018115-D20181213-T094600.raw" # rx impedance / rx fs / tcvr type ed = ep.open_raw(ek80_raw_path, sonar_model="EK80") # Calibration object waveform_mode = "BB" encode_mode = "complex" cal_obj = ep.calibrate.calibrate_ek.CalibrateEK80( echodata=ed, waveform_mode=waveform_mode, encode_mode=encode_mode, env_params={"formula_absorption": "FG"}, cal_params=None ) # Params needed beam = cal_obj.echodata[cal_obj.ed_beam_group].sel(channel=cal_obj.chan_sel) z_er = cal_obj.cal_params["impedance_transceiver"] z_et = cal_obj.cal_params["impedance_transducer"] fs = cal_obj.cal_params["receiver_sampling_frequency"] filter_coeff = ep.calibrate.ek80_complex.get_filter_coeff(ed["Vendor_specific"].sel(channel=cal_obj.chan_sel)) tx, tx_time = ep.calibrate.ek80_complex.get_transmit_signal(beam, filter_coeff, waveform_mode, fs) # Get power from complex samples prx = cal_obj._get_power_from_complex(beam=beam, chirp=tx, z_et=z_et, z_er=z_er) ch_sel = "WBT 714590-15 ES70-7C" # Load pyecholab pickle import pickle with open(ek80_ext_path / "pyecholab/pyel_BB_p_data.pickle", 'rb') as handle: pyel_BB_p_data = pickle.load(handle) # Power: only compare non-Nan, non-Inf values pyel_vals = pyel_BB_p_data["power"] ep_vals = 10 * np.log10(prx.sel(channel=ch_sel).data) assert pyel_vals.shape == ep_vals.shape idx_to_cmp = ~( np.isinf(pyel_vals) | np.isnan(pyel_vals) | np.isinf(ep_vals) | np.isnan(ep_vals) ) assert np.allclose(pyel_vals[idx_to_cmp], ep_vals[idx_to_cmp]) # Sv: only compare non-Nan, non-Inf values # comparing for only the last values now until fixing the range computation ds_Sv = ep.calibrate.compute_Sv( ed, waveform_mode="BB", encode_mode="complex" ) pyel_vals = pyel_BB_p_data["sv_data"] ep_vals = ds_Sv["Sv"].sel(channel=ch_sel).squeeze().data assert pyel_vals.shape == ep_vals.shape idx_to_cmp = ~( np.isinf(pyel_vals) | np.isnan(pyel_vals) | np.isinf(ep_vals) | np.isnan(ep_vals) ) assert np.allclose(pyel_vals[idx_to_cmp], ep_vals[idx_to_cmp]) def test_ek80_BB_power_echoview(ek80_path): """Compare pulse compressed outputs from echopype and csv exported from EchoView. Unresolved: the difference is large and it is not clear why. """ ek80_raw_path = str(ek80_path.joinpath('D20170912-T234910.raw')) ek80_bb_pc_test_path = str( ek80_path.joinpath( 'from_echoview', '70 kHz pulse-compressed power.complex.csv' ) ) echodata = ep.open_raw(ek80_raw_path, sonar_model='EK80') # Create a CalibrateEK80 object to perform pulse compression cal_obj = ep.calibrate.calibrate_ek.CalibrateEK80( echodata, env_params=None, cal_params=None, waveform_mode="BB", encode_mode="complex" ) beam = echodata["Sonar/Beam_group1"].sel(channel=cal_obj.chan_sel) coeff = ep.calibrate.ek80_complex.get_filter_coeff(echodata["Vendor_specific"].sel(channel=cal_obj.chan_sel)) chirp, _ = ep.calibrate.ek80_complex.get_transmit_signal(beam, coeff, "BB", cal_obj.cal_params["receiver_sampling_frequency"]) pc = ep.calibrate.ek80_complex.compress_pulse( backscatter=beam["backscatter_r"] + 1j * beam["backscatter_i"], chirp=chirp) pc = pc / ep.calibrate.ek80_complex.get_norm_fac(chirp) # normalization for each channel pc_mean = pc.sel(channel="WBT 549762-15 ES70-7C").mean(dim="beam").dropna("range_sample") # Read EchoView pc raw power output df = pd.read_csv(ek80_bb_pc_test_path, header=None, skiprows=[0]) df_header = pd.read_csv( ek80_bb_pc_test_path, header=0, usecols=range(14), nrows=0 ) df = df.rename( columns={ cc: vv for cc, vv in zip(df.columns, df_header.columns.values) } ) df.columns = df.columns.str.strip() df_real = df.loc[df["Component"] == " Real", :].iloc[:, 14:] # values start at column 15 # Skip an initial chunk of samples due to unknown larger difference # this difference is also documented in pyecholab tests # Below only compare the first ping ev_vals = df_real.values[:, :] ep_vals = pc_mean.values.real[:, :] assert np.allclose(ev_vals[:, 69:8284], ep_vals[:, 69:], atol=1e-4) assert np.allclose(ev_vals[:, 90:8284], ep_vals[:, 90:], atol=1e-5)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,855
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/commongrid/test_nasc.py
import pytest import numpy as np from echopype import open_raw from echopype.calibrate import compute_Sv from echopype.commongrid import compute_NASC from echopype.commongrid.nasc import ( get_distance_from_latlon, get_depth_bin_info, get_dist_bin_info, get_distance_from_latlon, ) from echopype.consolidate import add_location, add_depth @pytest.fixture def ek60_path(test_path): return test_path['EK60'] # def test_compute_NASC(ek60_path): # raw_path = ek60_path / "ncei-wcsd/Summer2017-D20170620-T011027.raw" # ed = open_raw(raw_path, sonar_model="EK60") # ds_Sv = add_depth(add_location(compute_Sv(ed), ed, nmea_sentence="GGA")) # cell_dist = 0.1 # cell_depth = 20 # ds_NASC = compute_NASC(ds_Sv, cell_dist, cell_depth) # dist_nmi = get_distance_from_latlon(ds_Sv) # # Check dimensions # da_NASC = ds_NASC["NASC"] # assert da_NASC.dims == ("channel", "distance", "depth") # assert np.all(ds_NASC["channel"].values == ds_Sv["channel"].values) # assert da_NASC["depth"].size == np.ceil(ds_Sv["depth"].max() / cell_depth) # assert da_NASC["distance"].size == np.ceil(dist_nmi.max() / cell_dist)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,856
OSOceanAcoustics/echopype
refs/heads/main
/echopype/convert/api.py
from pathlib import Path from typing import TYPE_CHECKING, Dict, Optional, Tuple import fsspec from datatree import DataTree # fmt: off # black and isort have conflicting ideas about how this should be formatted from ..core import SONAR_MODELS from .parsed_to_zarr import Parsed2Zarr if TYPE_CHECKING: from ..core import EngineHint, PathHint, SonarModelsHint # fmt: on from ..echodata.echodata import XARRAY_ENGINE_MAP, EchoData from ..utils import io from ..utils.coding import COMPRESSION_SETTINGS from ..utils.log import _init_logger from ..utils.prov import add_processing_level BEAM_SUBGROUP_DEFAULT = "Beam_group1" # Logging setup logger = _init_logger(__name__) def to_file( echodata: EchoData, engine: "EngineHint", save_path: Optional["PathHint"] = None, compress: bool = True, overwrite: bool = False, parallel: bool = False, output_storage_options: Dict[str, str] = {}, **kwargs, ): """Save content of EchoData to netCDF or zarr. Parameters ---------- engine : str {'netcdf4', 'zarr'} type of converted file save_path : str path that converted .nc file will be saved compress : bool whether or not to perform compression on data variables Defaults to ``True`` overwrite : bool whether or not to overwrite existing files Defaults to ``False`` parallel : bool whether or not to use parallel processing. (Not yet implemented) output_storage_options : dict Additional keywords to pass to the filesystem class. **kwargs : dict, optional Extra arguments to either `xr.Dataset.to_netcdf` or `xr.Dataset.to_zarr`: refer to each method documentation for a list of all possible arguments. """ if parallel: raise NotImplementedError("Parallel conversion is not yet implemented.") if engine not in XARRAY_ENGINE_MAP.values(): raise ValueError("Unknown type to convert file to!") # Assemble output file names and path output_file = io.validate_output_path( source_file=echodata.source_file, engine=engine, save_path=save_path, output_storage_options=output_storage_options, ) # Get all existing files fs = fsspec.get_mapper(output_file, **output_storage_options).fs # get file system exists = True if fs.exists(output_file) else False # Sequential or parallel conversion if exists and not overwrite: logger.info( f"{echodata.source_file} has already been converted to {engine}. " # noqa f"File saving not executed." ) else: if exists: logger.info(f"overwriting {output_file}") else: logger.info(f"saving {output_file}") _save_groups_to_file( echodata, output_path=io.sanitize_file_path( file_path=output_file, storage_options=output_storage_options ), engine=engine, compress=compress, **kwargs, ) # Link path to saved file with attribute as if from open_converted echodata.converted_raw_path = output_file def _save_groups_to_file(echodata, output_path, engine, compress=True, **kwargs): """Serialize all groups to file.""" # TODO: in terms of chunking, would using rechunker at the end be faster and more convenient? # TODO: investigate chunking before we save Dataset to a file # Top-level group io.save_file( echodata["Top-level"], path=output_path, mode="w", engine=engine, compression_settings=COMPRESSION_SETTINGS[engine] if compress else None, **kwargs, ) # Environment group io.save_file( echodata["Environment"], # TODO: chunking necessary? path=output_path, mode="a", engine=engine, group="Environment", compression_settings=COMPRESSION_SETTINGS[engine] if compress else None, **kwargs, ) # Platform group io.save_file( echodata["Platform"], # TODO: chunking necessary? time1 and time2 (EK80) only path=output_path, mode="a", engine=engine, group="Platform", compression_settings=COMPRESSION_SETTINGS[engine] if compress else None, **kwargs, ) # Platform/NMEA group: some sonar model does not produce NMEA data if echodata["Platform/NMEA"] is not None: io.save_file( echodata["Platform/NMEA"], # TODO: chunking necessary? path=output_path, mode="a", engine=engine, group="Platform/NMEA", compression_settings=COMPRESSION_SETTINGS[engine] if compress else None, **kwargs, ) # Provenance group io.save_file( echodata["Provenance"], path=output_path, group="Provenance", mode="a", engine=engine, compression_settings=COMPRESSION_SETTINGS[engine] if compress else None, **kwargs, ) # Sonar group io.save_file( echodata["Sonar"], path=output_path, group="Sonar", mode="a", engine=engine, compression_settings=COMPRESSION_SETTINGS[engine] if compress else None, **kwargs, ) # /Sonar/Beam_groupX group if echodata.sonar_model == "AD2CP": for i in range(1, len(echodata["Sonar"]["beam_group"]) + 1): io.save_file( echodata[f"Sonar/Beam_group{i}"], path=output_path, mode="a", engine=engine, group=f"Sonar/Beam_group{i}", compression_settings=COMPRESSION_SETTINGS[engine] if compress else None, **kwargs, ) else: io.save_file( echodata[f"Sonar/{BEAM_SUBGROUP_DEFAULT}"], path=output_path, mode="a", engine=engine, group=f"Sonar/{BEAM_SUBGROUP_DEFAULT}", compression_settings=COMPRESSION_SETTINGS[engine] if compress else None, **kwargs, ) if echodata["Sonar/Beam_group2"] is not None: # some sonar model does not produce Sonar/Beam_group2 io.save_file( echodata["Sonar/Beam_group2"], path=output_path, mode="a", engine=engine, group="Sonar/Beam_group2", compression_settings=COMPRESSION_SETTINGS[engine] if compress else None, **kwargs, ) # Vendor_specific group io.save_file( echodata["Vendor_specific"], # TODO: chunking necessary? path=output_path, mode="a", engine=engine, group="Vendor_specific", compression_settings=COMPRESSION_SETTINGS[engine] if compress else None, **kwargs, ) def _set_convert_params(param_dict: Dict[str, str]) -> Dict[str, str]: """Set parameters (metadata) that may not exist in the raw files. The default set of parameters include: - Platform group: ``platform_name``, ``platform_type``, ``platform_code_ICES``, ``water_level`` - Top-level group: ``survey_name`` Other parameters will be saved to the top level. # TODO: revise docstring, give examples. Examples -------- # set parameters that may not already be in source files echodata.set_param({ 'platform_name': 'OOI', 'platform_type': 'mooring' }) """ out_params = dict() # Parameters for the Platform group out_params["platform_name"] = param_dict.get("platform_name", "") out_params["platform_code_ICES"] = param_dict.get("platform_code_ICES", "") out_params["platform_type"] = param_dict.get("platform_type", "") out_params["water_level"] = param_dict.get("water_level", None) # Parameters for the Top-level group out_params["survey_name"] = param_dict.get("survey_name", "") for k, v in param_dict.items(): if k not in out_params: out_params[k] = v return out_params def _check_file( raw_file, sonar_model: "SonarModelsHint", xml_path: Optional["PathHint"] = None, storage_options: Dict[str, str] = {}, ) -> Tuple[str, str]: """Checks whether the file and/or xml file exists and whether they have the correct extensions. Parameters ---------- raw_file : str path to raw data file sonar_model : str model of the sonar instrument xml_path : str path to XML config file used by AZFP storage_options : dict options for cloud storage Returns ------- file : str path to existing raw data file xml : str path to existing xml file empty string if no xml file is required for the specified model """ if SONAR_MODELS[sonar_model]["xml"]: # if this sonar model expects an XML file if not xml_path: raise ValueError(f"XML file is required for {sonar_model} raw data") else: if ".XML" not in Path(xml_path).suffix.upper(): raise ValueError(f"{Path(xml_path).name} is not an XML file") xmlmap = fsspec.get_mapper(str(xml_path), **storage_options) if not xmlmap.fs.exists(xmlmap.root): raise FileNotFoundError(f"There is no file named {Path(xml_path).name}") xml = xml_path else: xml = "" # TODO: https://github.com/OSOceanAcoustics/echopype/issues/229 # to add compatibility for pathlib.Path objects for local paths fsmap = fsspec.get_mapper(raw_file, **storage_options) validate_ext = SONAR_MODELS[sonar_model]["validate_ext"] if not fsmap.fs.exists(fsmap.root): raise FileNotFoundError(f"There is no file named {Path(raw_file).name}") validate_ext(Path(raw_file).suffix.upper()) return str(raw_file), str(xml) @add_processing_level("L1A", is_echodata=True) def open_raw( raw_file: "PathHint", sonar_model: "SonarModelsHint", xml_path: Optional["PathHint"] = None, convert_params: Optional[Dict[str, str]] = None, storage_options: Optional[Dict[str, str]] = None, use_swap: bool = False, max_mb: int = 100, ) -> Optional[EchoData]: """Create an EchoData object containing parsed data from a single raw data file. The EchoData object can be used for adding metadata and ancillary data as well as to serialize the parsed data to zarr or netcdf. Parameters ---------- raw_file : str path to raw data file sonar_model : str 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 - ``AD2CP``: Nortek Signature series ADCP (tested with Signature 500 and Signature 1000) xml_path : str path to XML config file used by AZFP convert_params : dict parameters (metadata) that may not exist in the raw file and need to be added to the converted file storage_options : dict options for cloud storage use_swap: bool If True, variables with a large memory footprint will be written to a temporary zarr store at ``~/.echopype/temp_output/parsed2zarr_temp_files`` max_mb : int The maximum data chunk size in Megabytes (MB), when offloading variables with a large memory footprint to a temporary zarr store Returns ------- EchoData object 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 ----- ``use_swap=True`` is only available for the following echosounders: EK60, ES70, EK80, ES80, EA640. Additionally, this feature is currently in beta. """ if raw_file is None: raise FileNotFoundError("The path to the raw data file must be specified.") # Check for path type if isinstance(raw_file, Path): raw_file = str(raw_file) if not isinstance(raw_file, str): raise TypeError("File path must be a string or Path") if sonar_model is None: raise ValueError("Sonar model must be specified.") # Check inputs if convert_params is None: convert_params = {} storage_options = storage_options if storage_options is not None else {} # Uppercased model in case people use lowercase sonar_model = sonar_model.upper() # type: ignore # Check models if sonar_model not in SONAR_MODELS: raise ValueError( f"Unsupported echosounder model: {sonar_model}\nMust be one of: {list(SONAR_MODELS)}" # noqa ) # Check file extension and existence file_chk, xml_chk = _check_file(raw_file, sonar_model, xml_path, storage_options) # TODO: remove once 'auto' option is added if not isinstance(use_swap, bool): raise ValueError("use_swap must be of type bool.") # Ensure use_swap is 'auto', if it is a string # TODO: use the following when we allow for 'auto' option # if isinstance(use_swap, str) and use_swap != "auto": # raise ValueError("use_swap must be a bool or equal to 'auto'.") # TODO: the if-else below only works for the AZFP vs EK contrast, # but is brittle since it is abusing params by using it implicitly if SONAR_MODELS[sonar_model]["xml"]: params = xml_chk else: params = "ALL" # reserved to control if only wants to parse a certain type of datagram # obtain dict associated with directly writing to zarr dgram_zarr_vars = SONAR_MODELS[sonar_model]["dgram_zarr_vars"] # Parse raw file and organize data into groups parser = SONAR_MODELS[sonar_model]["parser"]( file_chk, params=params, storage_options=storage_options, dgram_zarr_vars=dgram_zarr_vars ) parser.parse_raw() # Direct offload to zarr and rectangularization only available for some sonar models if sonar_model in ["EK60", "ES70", "EK80", "ES80", "EA640"]: # Create sonar_model-specific p2z object p2z = SONAR_MODELS[sonar_model]["parsed2zarr"](parser) # Determines if writing to zarr is necessary and writes to zarr p2z_flag = use_swap is True or ( use_swap == "auto" and p2z.whether_write_to_zarr(mem_mult=0.4) ) if p2z_flag: p2z.datagram_to_zarr(max_mb=max_mb) # Rectangularize the transmit data parser.rectangularize_transmit_ping_data(data_type="complex") else: del p2z # Create general p2z object p2z = Parsed2Zarr(parser) parser.rectangularize_data() else: # No rectangularization for other sonar models p2z = Parsed2Zarr(parser) # Create general p2z object setgrouper = SONAR_MODELS[sonar_model]["set_groups"]( parser, input_file=file_chk, xml_path=xml_chk, output_path=None, sonar_model=sonar_model, params=_set_convert_params(convert_params), parsed2zarr_obj=p2z, ) # Setup tree dictionary tree_dict = {} # Top-level date_created varies depending on sonar model # Top-level is called "root" within tree if sonar_model in ["EK60", "ES70", "EK80", "ES80", "EA640"]: tree_dict["/"] = setgrouper.set_toplevel( sonar_model=sonar_model, date_created=parser.config_datagram["timestamp"], ) else: tree_dict["/"] = setgrouper.set_toplevel( sonar_model=sonar_model, date_created=parser.ping_time[0] ) tree_dict["Environment"] = setgrouper.set_env() tree_dict["Platform"] = setgrouper.set_platform() if sonar_model in ["EK60", "ES70", "EK80", "ES80", "EA640"]: tree_dict["Platform/NMEA"] = setgrouper.set_nmea() tree_dict["Provenance"] = setgrouper.set_provenance() # Allocate a tree_dict entry for Sonar? Otherwise, a DataTree error occurs tree_dict["Sonar"] = None # Set multi beam groups beam_groups = setgrouper.set_beam() beam_group_type = [] for idx, beam_group in enumerate(beam_groups, start=1): if beam_group is not None: # fill in beam_group_type (only necessary for EK80, ES80, EA640) if idx == 1: # choose the appropriate description key for Beam_group1 beam_group_type.append("complex" if "backscatter_i" in beam_group else "power") else: # provide None for all other beam groups (since the description does not have a key) beam_group_type.append(None) tree_dict[f"Sonar/Beam_group{idx}"] = beam_group if sonar_model in ["EK80", "ES80", "EA640"]: tree_dict["Sonar"] = setgrouper.set_sonar(beam_group_type=beam_group_type) else: tree_dict["Sonar"] = setgrouper.set_sonar() tree_dict["Vendor_specific"] = setgrouper.set_vendor() # Create tree and echodata # TODO: make the creation of tree dynamically generated from yaml tree = DataTree.from_dict(tree_dict, name="root") echodata = EchoData( source_file=file_chk, xml_path=xml_chk, sonar_model=sonar_model, parsed2zarr_obj=p2z ) echodata._set_tree(tree) echodata._load_tree() return echodata
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,857
OSOceanAcoustics/echopype
refs/heads/main
/echopype/convert/set_groups_azfp.py
""" Class to save unpacked echosounder data to appropriate groups in netcdf or zarr. """ from typing import List import numpy as np import xarray as xr from ..utils.coding import set_time_encodings from .set_groups_base import SetGroupsBase class SetGroupsAZFP(SetGroupsBase): """Class for saving groups to netcdf or zarr from AZFP data files.""" # The sets beam_only_names, ping_time_only_names, and # beam_ping_time_names are used in set_groups_base and # in converting from v0.5.x to v0.6.0. The values within # these sets are applied to all Sonar/Beam_groupX groups. # 2023-07-24: # PRs: # - https://github.com/OSOceanAcoustics/echopype/pull/1056 # - https://github.com/OSOceanAcoustics/echopype/pull/1083 # Most of the artificially added beam and ping_time dimensions at v0.6.0 # were reverted at v0.8.0, due to concerns with efficiency and code clarity # (see https://github.com/OSOceanAcoustics/echopype/issues/684 and # https://github.com/OSOceanAcoustics/echopype/issues/978). # However, the mechanisms to expand these dimensions were preserved for # flexibility and potential later use. # Note such expansion is still applied on AZFP data for 2 variables (see below). # Variables that need only the beam dimension added to them. beam_only_names = set() # Variables that need only the ping_time dimension added to them. # These variables do not change with ping_time in typical AZFP use cases, # but we keep them here for consistency with EK60/EK80 EchoData formats ping_time_only_names = { "sample_interval", "transmit_duration_nominal", } # Variables that need beam and ping_time dimensions added to them. beam_ping_time_names = set() beamgroups_possible = [ { "name": "Beam_group1", "descr": "contains backscatter power (uncalibrated) and other beam or channel-specific data.", # noqa } ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # get frequency values freq_old = list(self.parser_obj.unpacked_data["frequency"]) # sort the frequencies in ascending order freq_new = freq_old[:] freq_new.sort(reverse=False) # obtain sorted frequency indices self.freq_ind_sorted = [freq_new.index(ch) for ch in freq_old] # obtain sorted frequencies self.freq_sorted = self.parser_obj.unpacked_data["frequency"][self.freq_ind_sorted] # obtain channel_ids self.channel_ids_sorted = self._create_unique_channel_name() # Put Frequency in Hz (this should be done after create_unique_channel_name) self.freq_sorted = self.freq_sorted * 1000 # Frequency in Hz def _create_unique_channel_name(self): """ Creates a unique channel name for AZFP sensor using the variable unpacked_data created by the AZFP parser """ serial_number = self.parser_obj.unpacked_data["serial_number"] if serial_number.size == 1: freq_as_str = self.freq_sorted.astype(int).astype(str) # TODO: replace str(i+1) with Frequency Number from XML channel_id = [ str(serial_number) + "-" + freq + "-" + str(i + 1) for i, freq in enumerate(freq_as_str) ] return channel_id else: raise NotImplementedError( "Creating a channel name for more than" + " one serial number has not been implemented." ) def set_env(self) -> xr.Dataset: """Set the Environment group.""" # TODO Look at why this cannot be encoded without the modifications # @ngkavin: what modification? ping_time = self.parser_obj.ping_time ds = xr.Dataset( { "temperature": ( ["time1"], self.parser_obj.unpacked_data["temperature"], { "long_name": "Water temperature", "standard_name": "sea_water_temperature", "units": "deg_C", }, ) }, coords={ "time1": ( ["time1"], ping_time, { "axis": "T", "long_name": "Timestamp of each ping", "standard_name": "time", "comment": "Time coordinate corresponding to environmental variables.", }, ) }, ) return set_time_encodings(ds) def set_sonar(self) -> xr.Dataset: """Set the Sonar group.""" # Add beam_group and beam_group_descr variables sharing a common dimension # (beam_group), using the information from self._beamgroups self._beamgroups = self.beamgroups_possible beam_groups_vars, beam_groups_coord = self._beam_groups_vars() ds = xr.Dataset(beam_groups_vars, coords=beam_groups_coord) # Assemble sonar group global attribute dictionary sonar_attr_dict = { "sonar_manufacturer": "ASL Environmental Sciences", "sonar_model": self.sonar_model, "sonar_serial_number": int(self.parser_obj.unpacked_data["serial_number"]), "sonar_software_name": "AZFP", # TODO: software version is hardwired. Read it from the XML file's AZFP_Version node "sonar_software_version": "1.4", "sonar_type": "echosounder", } ds = ds.assign_attrs(sonar_attr_dict) return ds def set_platform(self) -> xr.Dataset: """Set the Platform group.""" platform_dict = {"platform_name": "", "platform_type": "", "platform_code_ICES": ""} unpacked_data = self.parser_obj.unpacked_data time2 = self.parser_obj.ping_time time1 = [time2[0]] # If tilt_x and/or tilt_y are all nan, create single-value time2 dimension # and single-value (np.nan) tilt_x and tilt_y tilt_x = [np.nan] if np.isnan(unpacked_data["tilt_x"]).all() else unpacked_data["tilt_x"] tilt_y = [np.nan] if np.isnan(unpacked_data["tilt_y"]).all() else unpacked_data["tilt_y"] if (len(tilt_x) == 1 and np.isnan(tilt_x)) and (len(tilt_y) == 1 and np.isnan(tilt_y)): time2 = [time2[0]] ds = xr.Dataset( { "latitude": ( ["time1"], [np.nan], self._varattrs["platform_var_default"]["latitude"], ), "longitude": ( ["time1"], [np.nan], self._varattrs["platform_var_default"]["longitude"], ), "pitch": ( ["time2"], [np.nan] * len(time2), self._varattrs["platform_var_default"]["pitch"], ), "roll": ( ["time2"], [np.nan] * len(time2), self._varattrs["platform_var_default"]["roll"], ), "vertical_offset": ( ["time2"], [np.nan] * len(time2), self._varattrs["platform_var_default"]["vertical_offset"], ), "water_level": ( [], np.nan, self._varattrs["platform_var_default"]["water_level"], ), "tilt_x": ( ["time2"], tilt_x, { "long_name": "Tilt X", "units": "arc_degree", }, ), "tilt_y": ( ["time2"], tilt_y, { "long_name": "Tilt Y", "units": "arc_degree", }, ), **{ var: ( ["channel"], [np.nan] * len(self.channel_ids_sorted), self._varattrs["platform_var_default"][var], ) for var in [ "transducer_offset_x", "transducer_offset_y", "transducer_offset_z", ] }, **{ var: ([], np.nan, self._varattrs["platform_var_default"][var]) for var in [ "MRU_offset_x", "MRU_offset_y", "MRU_offset_z", "MRU_rotation_x", "MRU_rotation_y", "MRU_rotation_z", "position_offset_x", "position_offset_y", "position_offset_z", ] }, "frequency_nominal": ( ["channel"], self.freq_sorted, { "units": "Hz", "long_name": "Transducer frequency", "valid_min": 0.0, "standard_name": "sound_frequency", }, ), }, coords={ "channel": ( ["channel"], self.channel_ids_sorted, self._varattrs["beam_coord_default"]["channel"], ), "time1": ( ["time1"], # xarray and probably CF don't accept time coordinate variable with Nan values time1, { **self._varattrs["platform_coord_default"]["time1"], "comment": "Time coordinate corresponding to NMEA position data.", }, ), "time2": ( ["time2"], time2, { "axis": "T", "long_name": "Timestamps for platform motion and orientation data", "standard_name": "time", "comment": "Time coordinate corresponding to platform motion and " "orientation data.", }, ), }, ) ds = ds.assign_attrs(platform_dict) return set_time_encodings(ds) def set_beam(self) -> List[xr.Dataset]: """Set the Beam group.""" unpacked_data = self.parser_obj.unpacked_data parameters = self.parser_obj.parameters dig_rate = unpacked_data["dig_rate"][self.freq_ind_sorted] # dim: freq ping_time = self.parser_obj.ping_time # Build variables in the output xarray Dataset N = [] # for storing backscatter_r values for each frequency for ich in self.freq_ind_sorted: N.append( np.array( [unpacked_data["counts"][p][ich] for p in range(len(unpacked_data["year"]))] ) ) # Largest number of counts along the range dimension among the different channels longest_range_sample = np.max(unpacked_data["num_bins"]) range_sample = np.arange(longest_range_sample) # Pad power data if any(unpacked_data["num_bins"] != longest_range_sample): N_tmp = np.full((len(N), len(ping_time), longest_range_sample), np.nan) for i, n in enumerate(N): N_tmp[i, :, : n.shape[1]] = n N = N_tmp del N_tmp tdn = ( unpacked_data["pulse_length"][self.freq_ind_sorted] / 1e6 ) # Convert microseconds to seconds range_samples_per_bin = unpacked_data["range_samples_per_bin"][ self.freq_ind_sorted ] # from data header # Calculate sample interval in seconds if len(dig_rate) == len(range_samples_per_bin): # TODO: below only correct if range_samples_per_bin=1, # need to implement p.86 for the case when averaging is used sample_int = range_samples_per_bin / dig_rate else: # TODO: not sure what this error means raise ValueError("dig_rate and range_samples not unique across frequencies") ds = xr.Dataset( { "frequency_nominal": ( ["channel"], self.freq_sorted, { "units": "Hz", "long_name": "Transducer frequency", "valid_min": 0.0, "standard_name": "sound_frequency", }, ), "beam_type": ( ["channel"], [0] * len(self.channel_ids_sorted), { "long_name": "Beam type", "flag_values": [0, 1], "flag_meanings": [ "Single beam", "Split aperture beam", ], }, ), **{ f"beam_direction_{var}": ( ["channel"], [np.nan] * len(self.channel_ids_sorted), { "long_name": f"{var}-component of the vector that gives the pointing " "direction of the beam, in sonar beam coordinate " "system", "units": "1", "valid_range": (-1.0, 1.0), }, ) for var in ["x", "y", "z"] }, "backscatter_r": ( ["channel", "ping_time", "range_sample"], np.array(N, dtype=np.float32), { "long_name": self._varattrs["beam_var_default"]["backscatter_r"][ "long_name" ], "units": "count", }, ), "equivalent_beam_angle": ( ["channel"], parameters["BP"][self.freq_ind_sorted], { "long_name": "Equivalent beam angle", "units": "sr", "valid_range": (0.0, 4 * np.pi), }, ), "gain_correction": ( ["channel"], np.array(unpacked_data["gain"][self.freq_ind_sorted], dtype=np.float64), {"long_name": "Gain correction", "units": "dB"}, ), "sample_interval": ( ["channel"], sample_int, { "long_name": "Interval between recorded raw data samples", "units": "s", "valid_min": 0.0, }, ), "transmit_duration_nominal": ( ["channel"], tdn, { "long_name": "Nominal bandwidth of transmitted pulse", "units": "s", "valid_min": 0.0, }, ), "transmit_frequency_start": ( ["channel"], self.freq_sorted, self._varattrs["beam_var_default"]["transmit_frequency_start"], ), "transmit_frequency_stop": ( ["channel"], self.freq_sorted, self._varattrs["beam_var_default"]["transmit_frequency_stop"], ), "transmit_type": ( [], "CW", { "long_name": "Type of transmitted pulse", "flag_values": ["CW"], "flag_meanings": [ "Continuous Wave – a pulse nominally of one frequency", ], }, ), "beam_stabilisation": ( [], np.array(0, np.byte), { "long_name": "Beam stabilisation applied (or not)", "flag_values": [0, 1], "flag_meanings": ["not stabilised", "stabilised"], }, ), "non_quantitative_processing": ( [], np.array(0, np.int16), { "long_name": "Presence or not of non-quantitative processing applied" " to the backscattering data (sonar specific)", "flag_values": [0], "flag_meanings": ["None"], }, ), "sample_time_offset": ( [], 0.0, { "long_name": "Time offset that is subtracted from the timestamp" " of each sample", "units": "s", }, ), }, coords={ "channel": ( ["channel"], self.channel_ids_sorted, self._varattrs["beam_coord_default"]["channel"], ), "ping_time": ( ["ping_time"], ping_time, self._varattrs["beam_coord_default"]["ping_time"], ), "range_sample": ( ["range_sample"], range_sample, self._varattrs["beam_coord_default"]["range_sample"], ), }, attrs={ "beam_mode": "", "conversion_equation_t": "type_4", }, ) # Manipulate some Dataset dimensions to adhere to convention self.beam_groups_to_convention( ds, self.beam_only_names, self.beam_ping_time_names, self.ping_time_only_names ) return [set_time_encodings(ds)] def set_vendor(self) -> xr.Dataset: """Set the Vendor_specific group.""" unpacked_data = self.parser_obj.unpacked_data parameters = self.parser_obj.parameters ping_time = self.parser_obj.ping_time tdn = parameters["pulse_length"][self.freq_ind_sorted] / 1e6 anc = np.array(unpacked_data["ancillary"]) # convert to np array for easy slicing # Build variables in the output xarray Dataset Sv_offset = np.zeros_like(self.freq_sorted) for ind, ich in enumerate(self.freq_ind_sorted): # TODO: should not access the private function, better to compute Sv_offset in parser Sv_offset[ind] = self.parser_obj._calc_Sv_offset( self.freq_sorted[ind], unpacked_data["pulse_length"][ich] ) ds = xr.Dataset( { "frequency_nominal": ( ["channel"], self.freq_sorted, { "units": "Hz", "long_name": "Transducer frequency", "valid_min": 0.0, "standard_name": "sound_frequency", }, ), # unpacked ping by ping data from 01A file "digitization_rate": ( ["channel"], unpacked_data["dig_rate"][self.freq_ind_sorted], { "long_name": "Number of samples per second in kHz that is processed by the " "A/D converter when digitizing the returned acoustic signal" }, ), "lockout_index": ( ["channel"], unpacked_data["lockout_index"][self.freq_ind_sorted], { "long_name": "The distance, rounded to the nearest Bin Size after the " "pulse is transmitted that over which AZFP will ignore echoes" }, ), "number_of_bins_per_channel": ( ["channel"], unpacked_data["num_bins"][self.freq_ind_sorted], {"long_name": "Number of bins per channel"}, ), "number_of_samples_per_average_bin": ( ["channel"], unpacked_data["range_samples_per_bin"][self.freq_ind_sorted], {"long_name": "Range samples per bin for each channel"}, ), "board_number": ( ["channel"], unpacked_data["board_num"][self.freq_ind_sorted], {"long_name": "The board the data came from channel 1-4"}, ), "data_type": ( ["channel"], unpacked_data["data_type"][self.freq_ind_sorted], { "long_name": "Datatype for each channel 1=Avg unpacked_data (5bytes), " "0=raw (2bytes)" }, ), "ping_status": (["ping_time"], unpacked_data["ping_status"]), "number_of_acquired_pings": ( ["ping_time"], unpacked_data["num_acq_pings"], {"long_name": "Pings acquired in the burst"}, ), "first_ping": (["ping_time"], unpacked_data["first_ping"]), "last_ping": (["ping_time"], unpacked_data["last_ping"]), "data_error": ( ["ping_time"], unpacked_data["data_error"], {"long_name": "Error number if an error occurred"}, ), "sensors_flag": (["ping_time"], unpacked_data["sensor_flag"]), "ancillary": ( ["ping_time", "ancillary_len"], unpacked_data["ancillary"], {"long_name": "Tilt-X, Y, Battery, Pressure, Temperature"}, ), "ad_channels": ( ["ping_time", "ad_len"], unpacked_data["ad"], {"long_name": "AD channel 6 and 7"}, ), "battery_main": (["ping_time"], unpacked_data["battery_main"]), "battery_tx": (["ping_time"], unpacked_data["battery_tx"]), "profile_number": (["ping_time"], unpacked_data["profile_number"]), # unpacked ping by ping ancillary data from 01A file "temperature_counts": ( ["ping_time"], anc[:, 4], {"long_name": "Raw counts for temperature"}, ), "tilt_x_count": (["ping_time"], anc[:, 0], {"long_name": "Raw counts for Tilt-X"}), "tilt_y_count": (["ping_time"], anc[:, 1], {"long_name": "Raw counts for Tilt-Y"}), # unpacked data with dim len=0 from 01A file "profile_flag": unpacked_data["profile_flag"], "burst_interval": ( [], unpacked_data["burst_int"], { "long_name": "Time in seconds between bursts or between pings if the burst" " interval has been set equal to the ping period" }, ), "ping_per_profile": ( [], unpacked_data["ping_per_profile"], { "long_name": "Number of pings in a profile if ping averaging has been " "selected" }, # noqa ), "average_pings_flag": ( [], unpacked_data["avg_pings"], {"long_name": "Flag indicating whether the pings average in time"}, ), "spare_channel": ([], unpacked_data["spare_chan"], {"long_name": "Spare channel"}), "ping_period": ( [], unpacked_data["ping_period"], {"long_name": "Time between pings in a profile set"}, ), "phase": ( [], unpacked_data["phase"], {"long_name": "Phase number used to acquire the profile"}, ), "number_of_channels": ( [], unpacked_data["num_chan"], {"long_name": "Number of channels (1, 2, 3, or 4)"}, ), # parameters with channel dimension from XML file "XML_transmit_duration_nominal": ( ["channel"], tdn, {"long_name": "(From XML file) Nominal bandwidth of transmitted pulse"}, ), # tdn comes from parameters "XML_gain_correction": ( ["channel"], parameters["gain"][self.freq_ind_sorted], {"long_name": "(From XML file) Gain correction"}, ), "XML_digitization_rate": ( ["channel"], parameters["dig_rate"][self.freq_ind_sorted], { "long_name": "(From XML file) Number of samples per second in kHz that is " "processed by the A/D converter when digitizing the returned acoustic " "signal" }, ), "XML_lockout_index": ( ["channel"], parameters["lockout_index"][self.freq_ind_sorted], { "long_name": "(From XML file) The distance, rounded to the nearest " "Bin Size after the pulse is transmitted that over which AZFP will " "ignore echoes" }, ), "DS": (["channel"], parameters["DS"][self.freq_ind_sorted]), "EL": ( ["channel"], parameters["EL"][self.freq_ind_sorted], {"long_name": "Sound pressure at the transducer", "units": "dB"}, ), "TVR": ( ["channel"], parameters["TVR"][self.freq_ind_sorted], { "long_name": "Transmit voltage response of the transducer", "units": "dB re 1uPa/V at 1m", }, ), "VTX": ( ["channel"], parameters["VTX"][self.freq_ind_sorted], {"long_name": "Amplified voltage sent to the transducer"}, ), "Sv_offset": (["channel"], Sv_offset), "number_of_samples_digitized_per_pings": ( ["channel"], parameters["range_samples"][self.freq_ind_sorted], ), "number_of_digitized_samples_averaged_per_pings": ( ["channel"], parameters["range_averaging_samples"][self.freq_ind_sorted], ), # parameters with dim len=0 from XML file "XML_sensors_flag": parameters["sensors_flag"], "XML_burst_interval": ( [], parameters["burst_interval"], { "long_name": "Time in seconds between bursts or between pings if the burst " "interval has been set equal to the ping period" }, ), "XML_sonar_serial_number": parameters["serial_number"], "number_of_frequency": parameters["num_freq"], "number_of_pings_per_burst": parameters["pings_per_burst"], "average_burst_pings_flag": parameters["average_burst_pings"], # temperature coefficients from XML file **{ f"temperature_k{var}": ( [], parameters[f"k{var}"], {"long_name": f"Thermistor bridge coefficient {var}"}, ) for var in ["a", "b", "c"] }, **{ f"temperature_{var}": ( [], parameters[var], {"long_name": f"Thermistor calibration coefficient {var}"}, ) for var in ["A", "B", "C"] }, # tilt coefficients from XML file **{ f"tilt_X_{var}": ( [], parameters[f"X_{var}"], {"long_name": f"Calibration coefficient {var} for Tilt-X"}, ) for var in ["a", "b", "c", "d"] }, **{ f"tilt_Y_{var}": ( [], parameters[f"Y_{var}"], {"long_name": f"Calibration coefficient {var} for Tilt-Y"}, ) for var in ["a", "b", "c", "d"] }, }, coords={ "channel": ( ["channel"], self.channel_ids_sorted, self._varattrs["beam_coord_default"]["channel"], ), "ping_time": ( ["ping_time"], ping_time, { "axis": "T", "long_name": "Timestamp of each ping", "standard_name": "time", }, ), "ancillary_len": ( ["ancillary_len"], list(range(len(unpacked_data["ancillary"][0]))), ), "ad_len": (["ad_len"], list(range(len(unpacked_data["ad"][0])))), }, ) return set_time_encodings(ds)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,858
OSOceanAcoustics/echopype
refs/heads/main
/echopype/commongrid/mvbs.py
""" Contains core functions needed to compute the MVBS of an input dataset. """ import warnings from typing import Tuple, Union import dask.array import numpy as np import xarray as xr def get_bin_indices( echo_range: np.ndarray, bins_er: np.ndarray, times: np.ndarray, bins_time: np.ndarray ) -> Tuple[np.ndarray, np.ndarray]: """ Obtains the bin index of ``echo_range`` and ``times`` based on the binning ``bins_er`` and ``bins_time``, respectively. Parameters ---------- echo_range: np.ndarray 2D array of echo range values bins_er: np.ndarray 1D array (used by np.digitize) representing the binning required for ``echo_range`` times: np.ndarray 1D array corresponding to the time values that should be binned bins_time: np.ndarray 1D array (used by np.digitize) representing the binning required for ``times`` Returns ------- digitized_echo_range: np.ndarray 2D array of bin indices for ``echo_range`` bin_time_ind: np.ndarray 1D array of bin indices for ``times`` """ # get bin index for each echo range value digitized_echo_range = np.digitize(echo_range, bins_er, right=False) # turn datetime into integers, so we can use np.digitize if isinstance(times, dask.array.Array): times_i8 = times.compute().data.view("i8") else: times_i8 = times.view("i8") # turn datetime into integers, so we can use np.digitize bins_time_i8 = bins_time.view("i8") # get bin index for each time bin_time_ind = np.digitize(times_i8, bins_time_i8, right=False) return digitized_echo_range, bin_time_ind def bin_and_mean_echo_range( arr: Union[np.ndarray, dask.array.Array], digitized_echo_range: np.ndarray, n_bin_er: int ) -> Union[np.ndarray, dask.array.Array]: """ Bins and means ``arr`` with respect to the ``echo_range`` bins. Parameters ---------- arr: np.ndarray or dask.array.Array 2D array (dimension: [``echo_range`` x ``ping_time``]) to bin along ``echo_range`` and compute mean of each bin digitized_echo_range: np.ndarray 2D array of bin indices for ``echo_range`` n_bin_er: int The number of echo range bins Returns ------- er_means: np.ndarray or dask.array.Array 2D array representing the bin and mean of ``arr`` along ``echo_range`` """ binned_means = [] for bin_er in range(1, n_bin_er): # Catch a known warning that can occur, which does not impact the results with warnings.catch_warnings(): # ignore warnings caused by taking a mean of an array filled with NaNs warnings.filterwarnings(action="ignore", message="Mean of empty slice") # bin and mean echo_range dimension er_selected_data = np.nanmean(arr[:, digitized_echo_range == bin_er], axis=1) # collect all echo_range bins binned_means.append(er_selected_data) # create full echo_range binned array er_means = np.vstack(binned_means) return er_means def get_unequal_rows(mat: np.ndarray, row: np.ndarray) -> np.ndarray: """ Obtains those row indices of ``mat`` that are not equal to ``row``. Parameters ---------- mat: np.ndarray 2D array with the same column dimension as the number of elements in ``row`` row: np.ndarray 1D array with the same number of element elements as the column dimension of ``mat`` Returns ------- row_ind_not_equal: np.ndarray The row indices of ``mat`` that are not equal to ``row`` Notes ----- Elements with NaNs are considered equal if they are in the same position. """ # compare row against all rows in mat (allowing for NaNs to be equal) element_nan_equal = (mat == row) | (np.isnan(mat) & np.isnan(row)) # determine if mat row is equal to row row_not_equal = np.logical_not(np.all(element_nan_equal, axis=1)) if isinstance(row_not_equal, dask.array.Array): row_not_equal = row_not_equal.compute() # get those row indices that are not equal to row row_ind_not_equal = np.argwhere(row_not_equal).flatten() return row_ind_not_equal def if_all_er_steps_identical(er_chan: Union[xr.DataArray, np.ndarray]) -> bool: """ A comprehensive check that determines if all ``echo_range`` values along ``ping_time`` have the same step size. If they do not have the same step sizes, then grouping of the ``echo_range`` values will be necessary. Parameters ---------- er_chan: xr.DataArray or np.ndarray 2D array containing the ``echo_range`` values for each ``ping_time`` Returns ------- bool True, if grouping of ``echo_range`` along ``ping_time`` is necessary, otherwise False Notes ----- ``er_chan`` should have rows corresponding to ``ping_time`` and columns corresponding to ``range_sample`` """ # grab the in-memory numpy echo_range values, if necessary if isinstance(er_chan, xr.DataArray): er_chan = er_chan.values # grab the first ping_time that is not filled with NaNs ping_index = 0 while np.all(np.isnan(er_chan[ping_index, :])): ping_index += 1 # determine those rows of er_chan that are not equal to the row ping_index unequal_ping_ind = get_unequal_rows(er_chan, er_chan[ping_index, :]) if len(unequal_ping_ind) > 0: # see if all unequal_ping_ind are filled with NaNs all_nans = np.all(np.all(np.isnan(er_chan[unequal_ping_ind, :]), axis=1)) if all_nans: # All echo_range values have the same step size return False else: # Some echo_range values have different step sizes return True else: # All echo_range values have the same step size return False def if_last_er_steps_identical(er_chan: Union[xr.DataArray, np.ndarray]) -> bool: """ An alternative (less comprehensive) check that determines if all ``echo_range`` values along ``ping_time`` have the same step size. If they do not have the same step sizes, then grouping of the ``echo_range`` values will be necessary. Parameters ---------- er_chan: xr.DataArray or np.ndarray 2D array containing the ``echo_range`` values for each ``ping_time`` Returns ------- bool True, if grouping of ``echo_range`` along ``ping_time`` is necessary, otherwise False Notes ----- It is possible that this method will incorrectly determine if grouping is necessary. ``er_chan`` should have rows corresponding to ``ping_time`` and columns corresponding to ``range_sample`` """ # determine the number of NaNs in each ping and find the unique number of NaNs unique_num_nans = np.unique(np.isnan(er_chan.data).sum(axis=1)) # compute the results, if necessary, to allow for downstream checks if isinstance(unique_num_nans, dask.array.Array): unique_num_nans = unique_num_nans.compute() # determine if any value is not 0 or er_chan.shape[1] unexpected_num_nans = False in np.logical_or( unique_num_nans == 0, unique_num_nans == er_chan.shape[1] ) if unexpected_num_nans: # echo_range varies with ping_time return True else: # make sure that the final echo_range value for each ping_time is the same (account for NaN) num_non_nans = np.logical_not(np.isnan(np.unique(er_chan.data[:, -1]))).sum() # compute the results, if necessary, to allow for downstream checks if isinstance(num_non_nans, dask.array.Array): num_non_nans = num_non_nans.compute() if num_non_nans > 1: # echo_range varies with ping_time return True else: # echo_range does not vary with ping_time return False def is_er_grouping_needed( echo_range: Union[xr.DataArray, np.ndarray], comprehensive_er_check: bool ) -> bool: """ Determines if ``echo_range`` values along ``ping_time`` can change and thus need to be grouped. Parameters ---------- echo_range: xr.DataArray or np.ndarray 2D array containing the ``echo_range`` values for each ``ping_time`` comprehensive_er_check: bool If True, a more comprehensive check will be completed to determine if ``echo_range`` grouping along ``ping_time`` is needed, otherwise a less comprehensive check will be done Returns ------- bool If True grouping of ``echo_range`` will be required, else it will not be necessary """ if comprehensive_er_check: return if_all_er_steps_identical(echo_range) else: return if_last_er_steps_identical(echo_range) def group_dig_er_bin_mean_echo_range( arr: Union[np.ndarray, dask.array.Array], digitized_echo_range: Union[np.ndarray, dask.array.Array], n_bin_er: int, ) -> Union[np.ndarray, dask.array.Array]: """ Groups the rows of ``arr`` such that they have the same corresponding row values in ``digitized_echo_range``, then applies ``bin_and_mean_echo_range`` on each group, and lastly assembles the correctly ordered ``er_means`` array representing the bin and mean of ``arr`` with respect to ``echo_range``. Parameters ---------- arr: dask.array.Array or np.ndarray The 2D array whose values should be binned digitized_echo_range: dask.array.Array or np.ndarray 2D array of bin indices for ``echo_range`` n_bin_er: int The number of echo range bins Returns ------- er_means: dask.array.Array or np.ndarray The bin and mean of ``arr`` with respect to ``echo_range`` """ # compute bin indices to allow for downstream processes (mainly axis argument in unique) if isinstance(digitized_echo_range, dask.array.Array): digitized_echo_range = digitized_echo_range.compute() # determine the unique rows of digitized_echo_range and the inverse unique_er_bin_ind, unique_inverse = np.unique(digitized_echo_range, axis=0, return_inverse=True) # create groups of row indices using the unique inverse grps_same_ind = [ np.argwhere(unique_inverse == grp).flatten() for grp in np.unique(unique_inverse) ] # for each group bin and mean arr along echo_range # note: the values appended may not be in the correct final order binned_er = [] for count, grp in enumerate(grps_same_ind): binned_er.append( bin_and_mean_echo_range(arr[grp, :], unique_er_bin_ind[count, :], n_bin_er) ) # construct er_means and put the columns in the correct order binned_er_array = np.hstack(binned_er) correct_column_ind = np.argsort(np.concatenate(grps_same_ind)) er_means = binned_er_array[:, correct_column_ind] return er_means def bin_and_mean_2d( arr: Union[dask.array.Array, np.ndarray], bins_time: np.ndarray, bins_er: np.ndarray, times: np.ndarray, echo_range: np.ndarray, comprehensive_er_check: bool = True, ) -> np.ndarray: """ Bins and means ``arr`` based on ``times`` and ``echo_range``, and their corresponding bins. If ``arr`` is ``Sv`` then this will compute the MVBS. Parameters ---------- arr: dask.array.Array or np.ndarray The 2D array whose values should be binned bins_time: np.ndarray 1D array (used by np.digitize) representing the binning required for ``times`` bins_er: np.ndarray 1D array (used by np.digitize) representing the binning required for ``echo_range`` times: np.ndarray 1D array corresponding to the time values that should be binned echo_range: np.ndarray 2D array of echo range values comprehensive_er_check: bool If True, a more comprehensive check will be completed to determine if ``echo_range`` grouping along ``ping_time`` is needed, otherwise a less comprehensive check will be done Returns ------- final_reduced: np.ndarray The final binned and mean ``arr``, if ``arr`` is ``Sv`` then this is the MVBS Notes ----- This function assumes that ``arr`` has rows corresponding to ``ping_time`` and columns corresponding to ``echo_range``. This function should not be run if the number of ``echo_range`` values vary amongst ``ping_times``. This should not occur for our current use of echopype-generated Sv data. """ # get the number of echo range and time bins n_bin_er = len(bins_er) n_bin_time = len(bins_time) # obtain the bin indices for echo_range and times digitized_echo_range, bin_time_ind = get_bin_indices(echo_range, bins_er, times, bins_time) # determine if grouping of echo_range values with the same step size is necessary er_grouping_needed = is_er_grouping_needed(echo_range, comprehensive_er_check) if er_grouping_needed: # groups, bins, and means arr with respect to echo_range er_means = group_dig_er_bin_mean_echo_range(arr, digitized_echo_range, n_bin_er) else: # bin and mean arr with respect to echo_range er_means = bin_and_mean_echo_range(arr, digitized_echo_range[0, :], n_bin_er) # if er_means is a dask array we compute it so the graph does not get too large if isinstance(er_means, dask.array.Array): er_means = er_means.compute() # create final reduced array i.e. MVBS final = np.empty((n_bin_time, n_bin_er - 1)) for bin_time in range(1, n_bin_time + 1): # obtain er_mean indices corresponding to the time bin indices = np.argwhere(bin_time_ind == bin_time).flatten() if len(indices) == 0: # fill values with NaN, if there are no values in the bin final[bin_time - 1, :] = np.nan else: # bin and mean the er_mean time bin final[bin_time - 1, :] = np.nanmean(er_means[:, indices], axis=1) return final def get_MVBS_along_channels( ds_Sv: xr.Dataset, echo_range_interval: np.ndarray, ping_interval: np.ndarray ) -> np.ndarray: """ Computes the MVBS of ``ds_Sv`` along each channel for the given intervals. Parameters ---------- ds_Sv: xr.Dataset A Dataset containing ``Sv`` and ``echo_range`` data with coordinates ``channel``, ``ping_time``, and ``range_sample`` echo_range_interval: np.ndarray 1D array (used by np.digitize) representing the binning required for ``echo_range`` ping_interval: np.ndarray 1D array (used by np.digitize) representing the binning required for ``ping_time`` Returns ------- np.ndarray The MVBS value of the input ``ds_Sv`` for all channels Notes ----- If the values in ``ds_Sv`` are delayed then the binning and mean of ``Sv`` with respect to ``echo_range`` will take place, then the delayed result will be computed, and lastly the binning and mean with respect to ``ping_time`` will be completed. It is necessary to apply a compute midway through this method because Dask graph layers get too large and this makes downstream operations very inefficient. """ all_MVBS = [] for chan in ds_Sv.channel: # squeeze to remove "channel" dim if present # TODO: not sure why not already removed for the AZFP case. Investigate. ds = ds_Sv.sel(channel=chan).squeeze() # average should be done in linear domain sv = 10 ** (ds["Sv"] / 10) # get MVBS for channel in linear domain chan_MVBS = bin_and_mean_2d( sv.data, bins_time=ping_interval, bins_er=echo_range_interval, times=sv.ping_time.data, echo_range=ds["echo_range"], comprehensive_er_check=True, ) # apply inverse mapping to get back to the original domain and store values all_MVBS.append(10 * np.log10(chan_MVBS)) # collect the MVBS values for each channel return np.stack(all_MVBS, axis=0)
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,859
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/clean/test_noise.py
import numpy as np import xarray as xr import echopype as ep import pytest from numpy.random import default_rng def test_remove_noise(): """Test remove_noise on toy data""" # Parameters for fake data nchan, npings, nrange_samples = 1, 10, 100 chan = np.arange(nchan).astype(str) ping_index = np.arange(npings) range_sample = np.arange(nrange_samples) data = np.ones(nrange_samples) # Insert noise points np.put(data, 30, -30) np.put(data, 60, -30) # Add more pings data = np.array([data] * npings) # Make DataArray Sv = xr.DataArray( [data], coords=[ ('channel', chan), ('ping_time', ping_index), ('range_sample', range_sample), ], ) Sv.name = "Sv" ds_Sv = Sv.to_dataset() ds_Sv = ds_Sv.assign( echo_range=xr.DataArray( np.array([[np.linspace(0, 10, nrange_samples)] * npings]), coords=Sv.coords, ) ) ds_Sv = ds_Sv.assign(sound_absorption=0.001) # Run noise removal ds_Sv = ep.clean.remove_noise( ds_Sv, ping_num=2, range_sample_num=5, SNR_threshold=0 ) # Test if noise points are nan assert np.isnan( ds_Sv.Sv_corrected.isel(channel=0, ping_time=0, range_sample=30) ) assert np.isnan( ds_Sv.Sv_corrected.isel(channel=0, ping_time=0, range_sample=60) ) # Test remove noise on a normal distribution np.random.seed(1) data = np.random.normal( loc=-100, scale=2, size=(nchan, npings, nrange_samples) ) # Make Dataset to pass into remove_noise Sv = xr.DataArray( data, coords=[ ('channel', chan), ('ping_time', ping_index), ('range_sample', range_sample), ], ) Sv.name = "Sv" ds_Sv = Sv.to_dataset() # Attach required echo_range and sound_absorption values ds_Sv = ds_Sv.assign( echo_range=xr.DataArray( np.array([[np.linspace(0, 3, nrange_samples)] * npings]), coords=Sv.coords, ) ) ds_Sv = ds_Sv.assign(sound_absorption=0.001) # Run noise removal ds_Sv = ep.clean.remove_noise( ds_Sv, ping_num=2, range_sample_num=5, SNR_threshold=0 ) null = ds_Sv.Sv_corrected.isnull() # Test to see if the right number of points are removed before the range gets too large assert ( np.count_nonzero(null.isel(channel=0, range_sample=slice(None, 50))) == 6 ) def test_remove_noise_no_sound_absorption(): """ Tests remove_noise on toy data that does not have sound absorption as a variable. """ pytest.xfail(f"Tests for remove_noise have not been implemented" + " when no sound absorption is provided!")
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,860
OSOceanAcoustics/echopype
refs/heads/main
/echopype/convert/parse_base.py
import os from collections import defaultdict from datetime import datetime as dt import numpy as np from ..utils.log import _init_logger from .utils.ek_raw_io import RawSimradFile, SimradEOF FILENAME_DATETIME_EK60 = ( "(?P<survey>.+)?-?D(?P<date>\\w{1,8})-T(?P<time>\\w{1,6})-?(?P<postfix>\\w+)?.raw" ) logger = _init_logger(__name__) class ParseBase: """Parent class for all convert classes.""" def __init__(self, file, storage_options): self.source_file = file self.timestamp_pattern = None # regex pattern used to grab datetime embedded in filename self.ping_time = [] # list to store ping time self.storage_options = storage_options self.zarr_datagrams = [] # holds all parsed datagrams def _print_status(self): """Prints message to console giving information about the raw file being parsed.""" class ParseEK(ParseBase): """Class for converting data from Simrad echosounders.""" def __init__(self, file, params, storage_options, dgram_zarr_vars): super().__init__(file, storage_options) # Parent class attributes # regex pattern used to grab datetime embedded in filename self.timestamp_pattern = FILENAME_DATETIME_EK60 # Class attributes self.config_datagram = None self.ping_data_dict = defaultdict(lambda: defaultdict(list)) # ping data self.ping_data_dict_tx = defaultdict(lambda: defaultdict(list)) # transmit ping data self.ping_time = defaultdict(list) # store ping time according to channel self.num_range_sample_groups = None # number of range_sample groups self.ch_ids = defaultdict( list ) # Stores the channel ids for each data type (power, angle, complex) self.data_type = self._select_datagrams(params) self.nmea = defaultdict(list) # Dictionary to store NMEA data(timestamp and string) self.mru = defaultdict(list) # Dictionary to store MRU data (heading, pitch, roll, heave) self.fil_coeffs = defaultdict(dict) # Dictionary to store PC and WBT coefficients self.fil_df = defaultdict(dict) # Dictionary to store filter decimation factors self.CON1_datagram = None # Holds the ME70 CON1 datagram # dgram vars and their associated dims that should be written directly to zarr self.dgram_zarr_vars = dgram_zarr_vars def _print_status(self): time = dt.utcfromtimestamp(self.config_datagram["timestamp"].tolist() / 1e9).strftime( "%Y-%b-%d %H:%M:%S" ) logger.info( f"parsing file {os.path.basename(self.source_file)}, " f"time of first ping: {time}" ) def rectangularize_data(self): """ Rectangularize the power, angle, and complex data. Additionally, convert the data to a numpy array indexed by channel. """ # append zarr datagrams to channel ping data for dgram in self.zarr_datagrams: self._append_channel_ping_data(dgram, zarr_vars=False) # Rectangularize all data and convert to numpy array indexed by channel for data_type in ["power", "angle", "complex"]: # Receive data for k, v in self.ping_data_dict[data_type].items(): if all( (x is None) or (x.size == 0) for x in v ): # if no data in a particular channel self.ping_data_dict[data_type][k] = None else: # Sort complex and power/angle channels and pad NaN self.ch_ids[data_type].append(k) self.ping_data_dict[data_type][k] = self.pad_shorter_ping(v) # Transmit data self.rectangularize_transmit_ping_data(data_type) def rectangularize_transmit_ping_data(self, data_type: str) -> None: """ Rectangularize the ``data_type`` data within transmit ping data. Additionally, convert the data to a numpy array indexed by channel. Parameters ---------- data_type: str The key of ``self.ping_data_dict_tx`` to rectangularize """ # Transmit data for k, v in self.ping_data_dict_tx[data_type].items(): if all((x is None) or (x.size == 0) for x in v): # if no data in a particular channel self.ping_data_dict_tx[data_type][k] = None else: self.ping_data_dict_tx[data_type][k] = self.pad_shorter_ping(v) def parse_raw(self): """Parse raw data file from Simrad EK60, EK80, and EA640 echosounders.""" with RawSimradFile(self.source_file, "r", storage_options=self.storage_options) as fid: self.config_datagram = fid.read(1) self.config_datagram["timestamp"] = np.datetime64( self.config_datagram["timestamp"].replace(tzinfo=None), "[ns]" ) if "configuration" in self.config_datagram: for v in self.config_datagram["configuration"].values(): if "pulse_duration" not in v and "pulse_length" in v: # it seems like sometimes this field can appear with the name "pulse_length" # and in the form of floats separated by semicolons v["pulse_duration"] = [float(x) for x in v["pulse_length"].split(";")] # If exporting to XML file (EK80/EA640 only), print a message if "print_export_msg" in self.data_type: if "ENV" in self.data_type: xml_type = "environment" elif "CONFIG" in self.data_type: xml_type = "configuration" logger.info(f"exporting {xml_type} XML file") # Don't parse anything else if only the config xml is required. if "CONFIG" in self.data_type: return # If not exporting to XML, print the usual converting message else: self._print_status() # Check if reading an ME70 file with a CON1 datagram. next_datagram = fid.peek() if next_datagram == "CON1": self.CON1_datagram = fid.read(1) else: self.CON1_datagram = None # IDs of the channels found in the dataset # self.ch_ids = list(self.config_datagram['configuration'].keys()) # Read the rest of datagrams self._read_datagrams(fid) if "ALL" in self.data_type: # Convert ping time to 1D numpy array, stored in dict indexed by channel, # this will help merge data from all channels into a cube for ch, val in self.ping_time.items(): self.ping_time[ch] = np.array(val, dtype="datetime64[ns]") def _read_datagrams(self, fid): """Read all datagrams. A sample EK60 RAW0 datagram: {'type': 'RAW0', 'low_date': 71406392, 'high_date': 30647127, 'channel': 1, 'mode': 3, 'transducer_depth': 9.149999618530273, 'frequency': 18000.0, 'transmit_power': 2000.0, 'pulse_length': 0.0010239999974146485, 'bandwidth': 1573.66552734375, 'sample_interval': 0.00025599999935366213, 'sound_velocity': 1466.0, 'absorption_coefficient': 0.0030043544247746468, 'heave': 0.0, 'roll': 0.0, 'pitch': 0.0, 'temperature': 4.0, 'heading': 0.0, 'transmit_mode': 1, 'spare0': '\x00\x00\x00\x00\x00\x00', 'offset': 0, 'count': 1386, 'timestamp': numpy.datetime64('2018-02-11T16:40:25.276'), 'bytes_read': 5648, 'power': array([ -6876, -8726, -11086, ..., -11913, -12522, -11799], dtype=int16), 'angle': array([[ 110, 13], [ 3, -4], [ -54, -65], ..., [ -92, -107], [-104, -122], [ 82, 74]], dtype=int8)} A sample EK80 XML-parameter datagram: {'channel_id': 'WBT 545612-15 ES200-7C', 'channel_mode': 0, 'pulse_form': 1, 'frequency_start': '160000', 'frequency_end': '260000', 'pulse_duration': 0.001024, 'sample_interval': 5.33333333333333e-06, 'transmit_power': 15.0, 'slope': 0.01220703125} A sample EK80 XML-environment datagram: {'type': 'XML0', 'low_date': 3137819385, 'high_date': 30616609, 'timestamp': numpy.datetime64('2017-09-12T23:49:10.723'), 'bytes_read': 448, 'subtype': 'environment', 'environment': {'depth': 240.0, 'acidity': 8.0, 'salinity': 33.7, 'sound_speed': 1486.4, 'temperature': 6.9, 'latitude': 45.0, 'sound_velocity_profile': [1.0, 1486.4, 1000.0, 1486.4], 'sound_velocity_source': 'Manual', 'drop_keel_offset': 0.0, 'drop_keel_offset_is_manual': 0, 'water_level_draft': 0.0, 'water_level_draft_is_manual': 0, 'transducer_name': 'Unknown', 'transducer_sound_speed': 1490.0}, 'xml': '<?xml version="1.0" encoding="utf-8"?>\r\n<Environment Depth="240" ... />\r\n</Environment>'} """ # noqa num_datagrams_parsed = 0 while True: try: # TODO: @ngkvain: what I need in the code to not PARSE the raw0/3 datagram # when users only want CONFIG or ENV, but the way this is implemented # the raw0/3 datagrams are still parsed, you are just not saving them new_datagram = fid.read(1) except SimradEOF: break # Convert the timestamp to a datetime64 object. new_datagram["timestamp"] = np.datetime64( new_datagram["timestamp"].replace(tzinfo=None), "[ns]" ) num_datagrams_parsed += 1 # Skip any datagram that the user does not want to save if ( not any(new_datagram["type"].startswith(dgram) for dgram in self.data_type) and "ALL" not in self.data_type ): continue # XML datagrams store environment or instrument parameters for EK80 if new_datagram["type"].startswith("XML"): if new_datagram["subtype"] == "environment" and ( "ENV" in self.data_type or "ALL" in self.data_type ): self.environment = new_datagram["environment"] self.environment["xml"] = new_datagram["xml"] self.environment["timestamp"] = new_datagram["timestamp"] # Don't parse anything else if only the environment xml is required. if "ENV" in self.data_type: break elif new_datagram["subtype"] == "parameter" and ("ALL" in self.data_type): current_parameters = new_datagram["parameter"] # RAW0 datagrams store raw acoustic data for a channel for EK60 elif new_datagram["type"].startswith("RAW0"): # Save channel-specific ping time. The channels are stored as 1-based indices self.ping_time[new_datagram["channel"]].append(new_datagram["timestamp"]) # Append ping by ping data self._append_channel_ping_data(new_datagram) # EK80 datagram sequence: # - XML0 pingsequence # - XML0 parameter # - RAW4 # - RAW3 # RAW3 datagrams store raw acoustic data for a channel for EK80 elif new_datagram["type"].startswith("RAW3"): curr_ch_id = new_datagram["channel_id"] # Check if the proceeding Parameter XML does not # match with data in this RAW3 datagram if current_parameters["channel_id"] != curr_ch_id: raise ValueError("Parameter ID does not match RAW") # Save channel-specific ping time self.ping_time[curr_ch_id].append(new_datagram["timestamp"]) # Append ping by ping data new_datagram.update(current_parameters) self._append_channel_ping_data(new_datagram) # RAW4 datagrams store raw transmit pulse for a channel for EK80 elif new_datagram["type"].startswith("RAW4"): curr_ch_id = new_datagram["channel_id"] # Check if the proceeding Parameter XML does not # match with data in this RAW4 datagram if current_parameters["channel_id"] != curr_ch_id: raise ValueError("Parameter ID does not match RAW") # Ping time is identical to the immediately following RAW3 datagram # so does not need to be stored separately # Append ping by ping data new_datagram.update(current_parameters) self._append_channel_ping_data(new_datagram, rx=False) # NME datagrams store ancillary data as NMEA-0817 style ASCII data. elif new_datagram["type"].startswith("NME"): self.nmea["timestamp"].append(new_datagram["timestamp"]) self.nmea["nmea_string"].append(new_datagram["nmea_string"]) # MRU datagrams contain motion data for each ping for EK80 elif new_datagram["type"].startswith("MRU"): self.mru["heading"].append(new_datagram["heading"]) self.mru["pitch"].append(new_datagram["pitch"]) self.mru["roll"].append(new_datagram["roll"]) self.mru["heave"].append(new_datagram["heave"]) self.mru["timestamp"].append(new_datagram["timestamp"]) # FIL datagrams contain filters for processing bascatter data for EK80 elif new_datagram["type"].startswith("FIL"): self.fil_coeffs[new_datagram["channel_id"]][new_datagram["stage"]] = new_datagram[ "coefficients" ] self.fil_df[new_datagram["channel_id"]][new_datagram["stage"]] = new_datagram[ "decimation_factor" ] # TAG datagrams contain time-stamped annotations inserted via the recording software elif new_datagram["type"].startswith("TAG"): logger.info("TAG datagram encountered.") # BOT datagrams contain sounder detected bottom depths from .bot files elif new_datagram["type"].startswith("BOT"): logger.info("BOT datagram encountered.") # DEP datagrams contain sounder detected bottom depths from .out files # as well as reflectivity data elif new_datagram["type"].startswith("DEP"): logger.info("DEP datagram encountered.") else: logger.info("Unknown datagram type: " + str(new_datagram["type"])) def _append_zarr_dgram(self, full_dgram: dict): """ Selects a subset of the datagram values that need to be sent directly to a zarr file and appends them to the class variable ``zarr_datagrams``. Additionally, if any power data exists, the conversion factor will be applied to it. Parameters ---------- full_dgram : dict Successfully parsed datagram containing at least one variable that should be written to a zarr file Returns ------- reduced_datagram : dict A reduced datagram containing only those variables that should be written to a zarr file and their associated dimensions. """ wanted_vars = set() for key in self.dgram_zarr_vars.keys(): wanted_vars = wanted_vars.union({key, *self.dgram_zarr_vars[key]}) # construct reduced datagram reduced_datagram = {key: full_dgram[key] for key in wanted_vars if key in full_dgram.keys()} # apply conversion factor to power data, if it exists if ("power" in reduced_datagram.keys()) and ( isinstance(reduced_datagram["power"], np.ndarray) ): # Manufacturer-specific power conversion factor INDEX2POWER = 10.0 * np.log10(2.0) / 256.0 reduced_datagram["power"] = reduced_datagram["power"].astype("float32") * INDEX2POWER if reduced_datagram: self.zarr_datagrams.append(reduced_datagram) def _append_channel_ping_data(self, datagram, rx=True, zarr_vars=True): """ Append ping by ping data. Parameters ---------- datagram : dict the newly read sample datagram rx : bool whether this is receive ping data zarr_vars : bool whether one should account for zarr vars """ # TODO: do a thorough check with the convention and processing # unsaved = ['channel', 'channel_id', 'low_date', 'high_date', # 'offset', 'frequency' , # 'transmit_mode', 'spare0', 'bytes_read', 'type'] #, 'n_complex'] ch_id = datagram["channel_id"] if "channel_id" in datagram else datagram["channel"] # append zarr variables, if they exist if zarr_vars and rx: common_vars = set(self.dgram_zarr_vars.keys()).intersection(set(datagram.keys())) if common_vars: self._append_zarr_dgram(datagram) for var in common_vars: del datagram[var] for k, v in datagram.items(): if rx: self.ping_data_dict[k][ch_id].append(v) else: self.ping_data_dict_tx[k][ch_id].append(v) @staticmethod def pad_shorter_ping(data_list) -> np.ndarray: """ Pad shorter ping with NaN: power, angle, complex samples. Parameters ---------- data_list : list Power, angle, or complex samples for each channel from RAW3 datagram. Each ping is one entry in the list. Returns ------- out_array : np.ndarray Numpy array containing samplings from all pings. The array is NaN-padded if some pings are of different lengths. """ lens = np.array([len(item) for item in data_list]) if np.unique(lens).size != 1: # if some pings have different lengths along range if data_list[0].ndim == 2: # Angle data have an extra dimension for alongship and athwartship samples mask = lens[:, None, None] > np.array([np.arange(lens.max())] * 2).T else: mask = lens[:, None] > np.arange(lens.max()) # Take care of problem of np.nan being implicitly "real" if data_list[0].dtype in {np.dtype("complex64"), np.dtype("complex128")}: out_array = np.full(mask.shape, np.nan + 0j) else: out_array = np.full(mask.shape, np.nan) # Fill in values out_array[mask] = np.concatenate(data_list).reshape(-1) # reshape in case data > 1D else: out_array = np.array(data_list) return out_array def _select_datagrams(self, params): """Translates user input into specific datagrams or ALL Valid use cases: # get GPS info only (EK60, EK80) # ec.to_netcdf(data_type='GPS') # get configuration XML only (EK80) # ec.to_netcdf(data_type='CONFIG') # get environment XML only (EK80) # ec.to_netcdf(data_type='ENV') """
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,861
OSOceanAcoustics/echopype
refs/heads/main
/echopype/tests/convert/test_parsed_to_zarr.py
import pytest import xarray as xr from typing import List, Tuple from echopype import open_raw from pathlib import Path import os.path @pytest.fixture def ek60_path(test_path): return test_path['EK60'] def compare_zarr_vars(ed_zarr: xr.Dataset, ed_no_zarr: xr.Dataset, var_to_comp: List[str], ed_path) -> Tuple[xr.Dataset, xr.Dataset]: """ Compares the dask variables in ``ed_zarr`` against their counterparts in ``ed_no_zarr`` by computing the dask results and using xarray to make sure the variables are identical. Additionally, this function will drop all of these compared variables. Parameters ---------- ed_zarr : xr.Dataset EchoData object with variables that were written directly to a zarr and then loaded with dask ed_no_zarr : xr.Dataset An in-memory EchoData object var_to_comp : List[str] List representing those variables that were written directly to a zarr and then loaded with dask ed_path : str EchoData group (e.g. "Sonar/Beam_group1") Returns ------- Tuple[xr.Dataset, xr.Dataset] Datasets ``ed_zarr`` and ``ed_no_zarr``, respectively with ``var_to_comp`` removed. """ for var in var_to_comp: for chan in ed_zarr[ed_path][var].channel: # here we compute to make sure values are being compared, rather than just shapes var_zarr = ed_zarr[ed_path][var].sel(channel=chan).compute() var_no_zarr = ed_no_zarr[ed_path][var].sel(channel=chan) assert var_zarr.identical(var_no_zarr) ed_zarr[ed_path] = ed_zarr[ed_path].drop_vars(var_to_comp) ed_no_zarr[ed_path] = ed_no_zarr[ed_path].drop_vars(var_to_comp) return ed_zarr, ed_no_zarr @pytest.mark.parametrize( ["raw_file", "sonar_model", "use_swap"], [ ("L0003-D20040909-T161906-EK60.raw", "EK60", True), pytest.param( "L0003-D20040909-T161906-EK60.raw", "EK60", False, marks=pytest.mark.xfail( run=False, reason="Expected out of memory error. See https://github.com/OSOceanAcoustics/echopype/issues/489", ), ), ], ids=["noaa_offloaded", "noaa_not_offloaded"], ) def test_raw2zarr(raw_file, sonar_model, use_swap, ek60_path): """Tests for memory expansion relief""" import os from tempfile import TemporaryDirectory from echopype.echodata.echodata import EchoData name = os.path.basename(raw_file).replace('.raw', '') fname = f"{name}__{use_swap}.zarr" file_path = ek60_path / raw_file echodata = open_raw( raw_file=file_path, sonar_model=sonar_model, use_swap=use_swap ) # Most likely succeed if it doesn't crash assert isinstance(echodata, EchoData) with TemporaryDirectory() as tmpdir: output_save_path = os.path.join(tmpdir, fname) echodata.to_zarr(output_save_path) # If it goes all the way to here it is most likely successful assert os.path.exists(output_save_path) if use_swap: # create a copy of zarr_file_name. The join is necessary so that we are not referencing zarr_file_name temp_zarr_path = ''.join(echodata.parsed2zarr_obj.zarr_file_name) del echodata # make sure that the temporary zarr was deleted assert Path(temp_zarr_path).exists() is False @pytest.mark.parametrize( ["path_model", "raw_file", "sonar_model"], [ ("EK60", os.path.join("ncei-wcsd", "Summer2017-D20170615-T190214.raw"), "EK60"), ("EK60", "DY1002_EK60-D20100318-T023008_rep_freq.raw", "EK60"), ("EK80", "Summer2018--D20180905-T033113.raw", "EK80"), ("EK80_CAL", "2018115-D20181213-T094600.raw", "EK80"), ("EK80", "Green2.Survey2.FM.short.slow.-D20191004-T211557.raw", "EK80"), ("EK80", "2019118 group2survey-D20191214-T081342.raw", "EK80"), ], ids=["ek60_summer_2017", "ek60_rep_freq", "ek80_summer_2018", "ek80_bb_w_cal", "ek80_short_slow", "ek80_grp_2_survey"], ) def test_direct_to_zarr_integration(path_model: str, raw_file: str, sonar_model: str, test_path: dict) -> None: """ Integration Test that ensure writing variables directly to a temporary zarr store and then assigning them to the EchoData object create an EchoData object that is identical to the method of not writing directly to a zarr. Parameters ---------- path_model: str The key in ``test_path`` pointing to the appropriate directory containing ``raw_file`` raw_file: str The raw file to test sonar_model: str The sonar model corresponding to ``raw_file`` test_path: dict A dictionary of all the model paths. Notes ----- This test should only be conducted with small raw files as DataSets must be loaded into RAM! """ raw_file_path = test_path[path_model] / raw_file ed_zarr = open_raw(raw_file_path, sonar_model=sonar_model, use_swap=True, max_mb=100) ed_no_zarr = open_raw(raw_file_path, sonar_model=sonar_model, use_swap=False) for grp in ed_zarr.group_paths: # remove conversion time so we can do a direct comparison if "conversion_time" in ed_zarr[grp].attrs: del ed_zarr[grp].attrs["conversion_time"] del ed_no_zarr[grp].attrs["conversion_time"] # Compare angle, power, complex, if zarr drop the zarr variables and compare datasets if grp == "Sonar/Beam_group2": var_to_comp = ['angle_athwartship', 'angle_alongship', 'backscatter_r'] ed_zarr, ed_no_zarr = compare_zarr_vars(ed_zarr, ed_no_zarr, var_to_comp, grp) if grp == "Sonar/Beam_group1": if 'backscatter_i' in ed_zarr[grp]: var_to_comp = ['backscatter_r', 'backscatter_i'] else: var_to_comp = ['angle_athwartship', 'angle_alongship', 'backscatter_r'] ed_zarr, ed_no_zarr = compare_zarr_vars(ed_zarr, ed_no_zarr, var_to_comp, grp) assert ed_zarr[grp].identical(ed_no_zarr[grp]) # create a copy of zarr_file_name. The join is necessary so that we are not referencing zarr_file_name temp_zarr_path = ''.join(ed_zarr.parsed2zarr_obj.zarr_file_name) del ed_zarr # make sure that the temporary zarr was deleted assert Path(temp_zarr_path).exists() is False
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}
73,862
OSOceanAcoustics/echopype
refs/heads/main
/echopype/echodata/widgets/widgets.py
import datetime import html from functools import lru_cache from pathlib import Path import pkg_resources from jinja2 import Environment, FileSystemLoader, Template from jinja2.exceptions import TemplateNotFound from .utils import _single_node_repr, hash_value, html_repr, make_key FILTERS = { "datetime_from_timestamp": datetime.datetime.fromtimestamp, "html_escape": html.escape, "type": type, "repr": repr, "html_repr": html_repr, "hash_value": hash_value, "make_key": make_key, "node_repr": _single_node_repr, } HERE = Path(__file__).parent STATIC_DIR = HERE / "static" TEMPLATE_PATHS = [HERE / "templates"] STATIC_FILES = ( "static/html/icons-svg-inline.html", "static/css/style.css", ) @lru_cache(None) def _load_static_files(): """Lazily load the resource files into memory the first time they are needed. Clone from xarray.core.formatted_html_template. """ return [pkg_resources.resource_string(__name__, fname).decode("utf8") for fname in STATIC_FILES] def get_environment() -> Environment: loader = FileSystemLoader(TEMPLATE_PATHS) environment = Environment(loader=loader) environment.filters.update(FILTERS) return environment def get_template(name: str) -> Template: try: return get_environment().get_template(name) except TemplateNotFound as e: raise TemplateNotFound( f"Unable to find {name} in echopype.echodata.widgets. TEMPLATE_PATHS {TEMPLATE_PATHS}" ) from e
{"/echopype/convert/set_groups_ad2cp.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/convert/parse_ad2cp.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/utils/test_source_filenames.py": ["/echopype/utils/prov.py"], "/echopype/echodata/convention/__init__.py": ["/echopype/echodata/convention/conv.py"], "/echopype/consolidate/split_beam_angle.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/calibrate/ecs.py": ["/echopype/utils/log.py"], "/echopype/tests/calibrate/test_ecs_integration.py": ["/echopype/__init__.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/cal_params.py"], "/echopype/calibrate/api.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/convert/parse_ad2cp.py": ["/echopype/convert/parse_base.py"], "/echopype/echodata/combine.py": ["/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/echodata.py"], "/echopype/tests/consolidate/test_consolidate_integration.py": ["/echopype/__init__.py"], "/echopype/echodata/api.py": ["/echopype/echodata/echodata.py", "/echopype/core.py"], "/echopype/tests/utils/test_utils_io.py": ["/echopype/utils/io.py"], "/echopype/echodata/sensor_ep_version_mapping/ep_version_mapper.py": ["/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py"], "/echopype/tests/mask/test_mask.py": ["/echopype/__init__.py", "/echopype/mask/__init__.py", "/echopype/mask/api.py"], "/echopype/tests/conftest.py": ["/echopype/testing.py"], "/echopype/tests/echodata/utils.py": ["/echopype/convert/set_groups_base.py", "/echopype/echodata/echodata.py"], "/echopype/tests/commongrid/test_mvbs.py": ["/echopype/__init__.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/calibrate/test_cal_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/test_core.py": ["/echopype/core.py"], "/echopype/calibrate/calibrate_azfp.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/echodata/widgets/utils.py": ["/echopype/echodata/convention/utils.py"], "/echopype/echodata/simrad.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek60.py": ["/echopype/__init__.py"], "/echopype/convert/parsed_to_zarr_ek60.py": ["/echopype/convert/parsed_to_zarr.py"], "/echopype/mask/api.py": ["/echopype/utils/io.py", "/echopype/utils/prov.py"], "/echopype/qc/__init__.py": ["/echopype/qc/api.py"], "/echopype/tests/utils/test_processinglevels_integration.py": ["/echopype/__init__.py"], "/echopype/tests/metrics/test_metrics_summary_statistics.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/__init__.py": ["/echopype/convert/api.py", "/echopype/echodata/api.py", "/echopype/echodata/combine.py", "/echopype/utils/io.py", "/echopype/utils/log.py"], "/.ci_helpers/check-version.py": ["/echopype/__init__.py"], "/echopype/calibrate/ek80_complex.py": ["/echopype/convert/set_groups_ek80.py"], "/echopype/consolidate/__init__.py": ["/echopype/consolidate/api.py"], "/echopype/commongrid/api.py": ["/echopype/utils/prov.py", "/echopype/commongrid/mvbs.py"], "/echopype/tests/echodata/test_echodata_combine.py": ["/echopype/__init__.py", "/echopype/utils/coding.py", "/echopype/echodata/__init__.py", "/echopype/echodata/combine.py"], "/echopype/tests/utils/test_utils_log.py": ["/echopype/__init__.py"], "/echopype/mask/__init__.py": ["/echopype/mask/api.py"], "/echopype/tests/convert/test_convert_ad2cp.py": ["/echopype/__init__.py", "/echopype/testing.py"], "/echopype/convert/parsed_to_zarr_ek80.py": ["/echopype/convert/parsed_to_zarr_ek60.py"], "/echopype/tests/visualize/test_plot.py": ["/echopype/__init__.py", "/echopype/visualize/__init__.py", "/echopype/testing.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/echodata/__init__.py", "/echopype/visualize/api.py"], "/echopype/calibrate/env_params.py": ["/echopype/echodata/__init__.py", "/echopype/calibrate/cal_params.py"], "/echopype/convert/utils/ek_raw_parsers.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_date_conversion.py"], "/echopype/tests/convert/test_convert_azfp.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_calibrate.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py"], "/echopype/calibrate/range.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/calibrate/env_params.py"], "/echopype/tests/calibrate/test_env_params.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params.py"], "/echopype/convert/set_groups_base.py": ["/echopype/echodata/convention/__init__.py", "/echopype/utils/coding.py", "/echopype/utils/prov.py"], "/echopype/clean/api.py": ["/echopype/utils/prov.py", "/echopype/clean/noise_est.py"], "/echopype/calibrate/calibrate_ek.py": ["/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/log.py", "/echopype/calibrate/cal_params.py", "/echopype/calibrate/calibrate_base.py", "/echopype/calibrate/ecs.py", "/echopype/calibrate/ek80_complex.py", "/echopype/calibrate/env_params.py", "/echopype/calibrate/range.py"], "/echopype/calibrate/calibrate_base.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py", "/echopype/calibrate/ecs.py"], "/echopype/echodata/echodata.py": ["/echopype/utils/coding.py", "/echopype/utils/io.py", "/echopype/utils/log.py", "/echopype/utils/prov.py", "/echopype/echodata/convention/__init__.py", "/echopype/echodata/widgets/utils.py", "/echopype/echodata/widgets/widgets.py", "/echopype/core.py", "/echopype/convert/api.py"], "/echopype/visualize/api.py": ["/echopype/visualize/plot.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py", "/echopype/calibrate/calibrate_azfp.py", "/echopype/utils/log.py"], "/echopype/echodata/sensor_ep_version_mapping/v05x_to_v06x.py": ["/echopype/core.py", "/echopype/utils/log.py", "/echopype/echodata/convention/__init__.py"], "/echopype/clean/__init__.py": ["/echopype/clean/api.py"], "/echopype/visualize/plot.py": ["/echopype/visualize/cm.py", "/echopype/utils/log.py"], "/echopype/commongrid/__init__.py": ["/echopype/commongrid/api.py"], "/echopype/convert/parsed_to_zarr.py": ["/echopype/utils/io.py"], "/echopype/calibrate/__init__.py": ["/echopype/calibrate/api.py"], "/echopype/echodata/convention/utils.py": ["/echopype/echodata/convention/__init__.py"], "/echopype/tests/echodata/test_echodata.py": ["/echopype/__init__.py", "/echopype/calibrate/env_params_old.py", "/echopype/echodata/__init__.py", "/echopype/calibrate/calibrate_ek.py"], "/echopype/qc/api.py": ["/echopype/echodata/__init__.py", "/echopype/utils/log.py"], "/echopype/visualize/__init__.py": ["/echopype/visualize/api.py"], "/echopype/tests/qc/test_qc.py": ["/echopype/qc/__init__.py", "/echopype/qc/api.py"], "/echopype/core.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/parsed_to_zarr_ek60.py", "/echopype/convert/parsed_to_zarr_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/parse_ek60.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/calibrate/test_cal_params.py": ["/echopype/calibrate/cal_params.py"], "/echopype/tests/calibrate/test_ecs.py": ["/echopype/calibrate/ecs.py"], "/echopype/echodata/__init__.py": ["/echopype/echodata/echodata.py"], "/echopype/tests/convert/test_convert_ek80.py": ["/echopype/__init__.py", "/echopype/testing.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/convert/set_groups_ek80.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/consolidate/api.py": ["/echopype/calibrate/ek80_complex.py", "/echopype/echodata/__init__.py", "/echopype/echodata/simrad.py", "/echopype/utils/io.py", "/echopype/utils/prov.py", "/echopype/consolidate/split_beam_angle.py"], "/echopype/convert/__init__.py": ["/echopype/convert/parse_ad2cp.py", "/echopype/convert/parse_azfp.py", "/echopype/convert/parse_base.py", "/echopype/convert/parse_ek60.py", "/echopype/convert/parse_ek80.py", "/echopype/convert/set_groups_ad2cp.py", "/echopype/convert/set_groups_azfp.py", "/echopype/convert/set_groups_ek60.py", "/echopype/convert/set_groups_ek80.py"], "/echopype/utils/prov.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_ek80.py": ["/echopype/convert/parse_base.py"], "/echopype/tests/echodata/test_echodata_simrad.py": ["/echopype/echodata/simrad.py"], "/echopype/tests/utils/test_coding.py": ["/echopype/utils/coding.py"], "/echopype/echodata/convention/conv.py": ["/echopype/echodata/__init__.py"], "/echopype/metrics/__init__.py": ["/echopype/metrics/summary_statistics.py"], "/echopype/tests/calibrate/test_calibrate_ek80.py": ["/echopype/__init__.py"], "/echopype/tests/commongrid/test_nasc.py": ["/echopype/__init__.py", "/echopype/calibrate/__init__.py", "/echopype/commongrid/__init__.py", "/echopype/commongrid/nasc.py", "/echopype/consolidate/__init__.py"], "/echopype/convert/api.py": ["/echopype/core.py", "/echopype/convert/parsed_to_zarr.py", "/echopype/echodata/echodata.py", "/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/utils/prov.py"], "/echopype/convert/set_groups_azfp.py": ["/echopype/utils/coding.py", "/echopype/convert/set_groups_base.py"], "/echopype/tests/clean/test_noise.py": ["/echopype/__init__.py"], "/echopype/convert/parse_base.py": ["/echopype/utils/log.py", "/echopype/convert/utils/ek_raw_io.py"], "/echopype/tests/convert/test_parsed_to_zarr.py": ["/echopype/__init__.py", "/echopype/echodata/echodata.py"], "/echopype/echodata/widgets/widgets.py": ["/echopype/echodata/widgets/utils.py"], "/echopype/tests/echodata/test_echodata_structure.py": ["/echopype/echodata/echodata.py", "/echopype/echodata/api.py"], "/echopype/tests/calibrate/test_range_integration.py": ["/echopype/__init__.py"], "/echopype/tests/calibrate/test_env_params_integration.py": ["/echopype/__init__.py"], "/echopype/tests/convert/test_convert_source_target_locs.py": ["/echopype/__init__.py", "/echopype/utils/coding.py"], "/echopype/tests/utils/test_utils_uwa.py": ["/echopype/utils/uwa.py"], "/echopype/utils/io.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/core.py"], "/echopype/tests/calibrate/test_ek80_complex.py": ["/echopype/calibrate/ek80_complex.py"], "/echopype/convert/set_groups_ek60.py": ["/echopype/utils/coding.py", "/echopype/utils/log.py", "/echopype/convert/set_groups_base.py"], "/echopype/convert/utils/ek_raw_io.py": ["/echopype/utils/log.py"], "/echopype/convert/parse_azfp.py": ["/echopype/utils/log.py", "/echopype/convert/parse_base.py"]}