gliderflightOG1 API
readers
- gliderflightOG1.readers.load_dataset(array_name: str, source: str = None, file_list: str | list[str] = None, transport_only: bool = True, data_dir: str | Path | None = None, redownload: bool = False) list[Dataset][source]
Load raw datasets from a selected AMOC observing array.
- Parameters:
array_name (str) – The name of the observing array to load. Options are: - ‘rapid’ : RAPID 26N array
source (str, optional) – URL or local path to the data source. If None, the reader-specific default source will be used.
file_list (str or list of str, optional) – Filename or list of filenames to process. If None, the reader-specific default files will be used.
transport_only (bool, optional) – If True, restrict to transport files only.
data_dir (str, optional) – Local directory for downloaded files.
redownload (bool, optional) – If True, force redownload of the data.
- Returns:
List of datasets loaded from the specified array.
- Return type:
list of xarray.Dataset
- Raises:
ValueError – If an unknown array name is provided.
- gliderflightOG1.readers.load_sample_dataset(array_name: str = 'rapid') Dataset[source]
Load a sample dataset for quick testing.
Currently supports: - ‘rapid’ : loads the ‘RAPID_26N_TRANSPORT.nc’ file
- Parameters:
array_name (str, optional) – The name of the observing array to load. Default is ‘rapid’.
- Returns:
A single xarray Dataset from the sample file.
- Return type:
xr.Dataset
- Raises:
ValueError – If the array_name is not recognised.
flight
plotters
- gliderflightOG1.plotters.plot_model_comparisons(glider: Dataset, models: dict, x_axis: str = 'TIME', select_dives: list = None, select_timerange: tuple = None, variable: str = 'VERTICAL_SPEED', label_variable: str = 'Measured Vertical Speed', model_labels: list = None, title: str = '')[source]
Plot measured vs modeled glider speeds for multiple models.
- Parameters:
glider (xarray.Dataset) – Dataset containing glider measurements.
models (dict) – Dictionary of model outputs, e.g., {‘steady’: speed_array, ‘unsteady’: speed_array}.
x_axis (str, optional) – Which x-axis to use (‘TIME’ or ‘DIVENUM’).
select_dives (list of int, optional) – List of dive numbers to plot.
select_timerange (tuple of floats, optional) – (start_time, end_time) in same units as glider[‘TIME’].
variable (str, optional) – Measured variable name (default ‘VERTICAL_SPEED’).
label_variable (str, optional) – Label for measured variable.
model_labels (list of str, optional) – Labels for model results; if None, keys of models dict are used.
title (str, optional) – Plot title.
- gliderflightOG1.plotters.show_attributes(data)[source]
Processes an xarray Dataset or a netCDF file, extracts attribute information, and returns a DataFrame with details about the attributes.
- Parameters:
xr.Dataset) (data (str or)
- Returns:
pandas.DataFrame –
Attribute: The name of the attribute.
Value: The value of the attribute.
- Return type:
A DataFrame containing the following columns:
- gliderflightOG1.plotters.show_variables(data)[source]
Processes an xarray Dataset or a netCDF file, extracts variable information, and returns a styled DataFrame with details about the variables.
- Parameters:
xr.Dataset) (data (str or)
- Returns:
pandas.io.formats.style.Styler –
dims: The dimension of the variable (or “string” if it is a string type).
name: The name of the variable.
units: The units of the variable (if available).
comment: Any additional comments about the variable (if available).
- Return type:
A styled DataFrame containing the following columns:
writers
- gliderflightOG1.writers.save_dataset(ds, output_file='../data/test.nc', delete_existing=False, prompt_user=True)[source]
Attempts to save the dataset to a NetCDF file. If a TypeError occurs due to invalid attribute values, it converts the invalid attributes to strings and retries the save operation.
- Parameters:
(xarray.Dataset) (ds)
(str) (output_file)
(bool) (prompt_user)
(bool)
- Returns:
bool (True if the dataset was saved successfully, False otherwise.)
Based on (https://github.com/pydata/xarray/issues/3743)
tools
- gliderflightOG1.tools.bl_coord(wg, wspdg, pgrid, mld)[source]
Compute means for below-mixed-layer segments of profiles.
- Parameters:
wg (ndarray) – Measured vertical speeds gridded (profiles x pressure levels).
wspdg (ndarray) – Modeled vertical speeds gridded (profiles x pressure levels).
pgrid (ndarray) – Pressure grid [dbar].
mld (ndarray) – Mixed layer depth estimates [dbar] (one per profile).
- Returns:
wmean – Mean difference (wspdg - wg) below mixed layer, per profile.
- Return type:
ndarray
- gliderflightOG1.tools.calc_w_meas(ds, depth_var='DEPTH')[source]
Calculates the vertical velocity of a glider using changes in pressure with time.
- Parameters:
ds (xarray.Dataset) – Dataset containing DEPTH and TIME.
- Returns:
ds – Containing the new variable GLIDER_VERT_VELO_DZDT (array-like), with vertical velocities calculated from dz/dt
- Return type:
xarray.Dataset
Notes
Original Author: Eleanor Frajka-Williams
Seaglider/basestation3.Utils.ctr_1st_diff() code dydx = np.array(np.zeros(len(y)), float) end = len(x) - 1 dydx[1:end] = (y[2:] - y[0 : end - 1]) / (x[2:] - x[0 : end - 1]) dydx[0] = (y[1] - y[0]) / (x[1] - x[0]) dydx[end] = (y[end] - y[end - 1]) / (x[end] - x[end - 1])
- gliderflightOG1.tools.choose_min_long(w_measured, w_model, time, divenum, updn, press, whichone)[source]
Compute different minimization metrics for long time-series.
- Parameters:
w_measured (array-like) – Measured vertical speeds [cm/s].
w_model (array-like) – Modeled vertical speeds [cm/s].
time (array-like) – Time array [seconds or days].
divenum (array-like) – Dive number array.
updn (array-like) – Up or down flag.
press (array-like) – Pressure measurements [dbar].
whichone (int) – Choice of metric.
- Returns:
allmin – Dictionary of metrics.
- Return type:
dict
- gliderflightOG1.tools.choose_min_prof(wg, wspdg, timeg, mld, divenumg, updng, pgrid, whichone, plotflag=0)[source]
Choose minimization metric based on gridded profiles.
- Parameters:
wg (ndarray) – Measured vertical speeds binned on grid.
wspdg (ndarray) – Modeled vertical speeds binned on grid.
timeg (ndarray) – Gridded time.
mld (ndarray) – Mixed layer depth estimates.
divenumg (ndarray) – Dive number array corresponding to grid.
updng (ndarray) – Up/down indicator corresponding to grid.
pgrid (ndarray) – Pressure bin grid [dbar].
whichone (int) – Metric selector (5–8).
plotflag (int, optional) – If >0, makes a plot.
- Returns:
allmin (dict) – Dictionary of minimization metric(s).
tmp (array) – Profile-wise differences (typically dive-climb).
- gliderflightOG1.tools.compute_insitu_density(salinity, temperature, pressure, longitude=None, latitude=None)[source]
Compute in-situ density from salinity, temperature, and pressure using GSW.
- Parameters:
salinity (array-like) – Practical salinity (PSU).
temperature (array-like) – In-situ temperature (°C).
pressure (array-like) – Pressure (dbar).
longitude (array-like, optional) – Longitude (degrees East). If not provided, defaults to -40°.
latitude (array-like, optional) – Latitude (degrees North). If not provided, defaults to 30°.
- Returns:
density – In-situ density (kg/m³).
- Return type:
array-like
- gliderflightOG1.tools.convert_units_var(var_values, current_unit, new_unit, unit_conversion={'Celsius': {'factor': 1, 'units_name': 'degrees_Celsius'}, 'Pa': {'factor': 0.0001, 'units_name': 'dbar'}, 'S m-1': {'factor': 0.1, 'units_name': 'mS cm-1'}, 'S/m': {'factor': 0.1, 'units_name': 'mS/cm'}, 'cm': {'factor': 0.01, 'units_name': 'm'}, 'cm s-1': {'factor': 0.01, 'units_name': 'm s-1'}, 'cm/s': {'factor': 0.01, 'units_name': 'm/s'}, 'dbar': {'factor': 10000, 'units_name': 'Pa'}, 'degrees_Celsius': {'factor': 1, 'units_name': 'Celsius'}, 'g m-3': {'factor': 0.001, 'units_name': 'kg m-3'}, 'kg m-3': {'factor': 1000, 'units_name': 'g m-3'}, 'km': {'factor': 1000, 'units_name': 'm'}, 'm': {'factor': 100, 'units_name': 'cm'}, 'm s-1': {'factor': 100, 'units_name': 'cm s-1'}, 'm/s': {'factor': 100, 'units_name': 'cm/s'}, 'mS cm-1': {'factor': 10, 'units_name': 'S m-1'}, 'mS/cm': {'factor': 10, 'units_name': 'S/m'}})[source]
Convert the units of variables in an xarray Dataset to preferred units. This is useful, for instance, to convert cm/s to m/s.
- Parameters:
(xarray.Dataset) (ds)
(list) (preferred_units)
(dict) (unit_conversion)
string (Each key is a unit) –
‘factor’: The factor to multiply the variable by to convert it.
’units_name’: The new unit name after conversion.
with (and each value is a dictionary) –
‘factor’: The factor to multiply the variable by to convert it.
’units_name’: The new unit name after conversion.
- Returns:
xarray.Dataset
- Return type:
The dataset with converted units.
- gliderflightOG1.tools.cum_ttest(ndof, p)[source]
Approximate cumulative Student’s t-test value.
- Parameters:
ndof (int) – Degrees of freedom.
p (float) – Confidence level (e.g., 95).
- Returns:
tval – t-distribution value corresponding to p and ndof.
- Return type:
float
- gliderflightOG1.tools.gridthem(w_measured, w_model, time, divenum, updn, press, pgrid)[source]
Bin average vertical speeds into pressure bins.
- Parameters:
w_measured (array)
w_model (array)
time (array)
divenum (array)
updn (array)
press (array)
pgrid (array) – Pressure grid.
- Returns:
wg (array) – Binned measured w.
wspdg (array) – Binned modeled w.
timeg (array) – Binned times.
divenumg (array) – Binned dive numbers.
updng (array) – Binned up/down flags.
- gliderflightOG1.tools.ml_coord(wg, wspdg, pgrid, mld, minmld=40)[source]
Compute means and variances for mixed-layer segments of profiles.
- Parameters:
wg (ndarray) – Measured vertical speeds gridded (profiles x pressure levels).
wspdg (ndarray) – Modeled vertical speeds gridded (profiles x pressure levels).
pgrid (ndarray) – Pressure grid [dbar].
mld (ndarray) – Mixed layer depth estimates [dbar] (one per profile).
minmld (float, optional) – Minimum mixed layer depth to use [dbar] (default 40 dbar).
- Returns:
wmean (ndarray) – Mean vertical speed difference within ML for each profile.
wsqr (ndarray) – RMS vertical speed difference within ML for each profile.
h (ndarray) – Mixed layer depth used per profile [dbar].
hgrid (ndarray) – Scaled pressure bin array (zgrid) [0-1].
Perform bin-averaging of vertical speed offsets over pressure bins.
- Parameters:
pressure (array-like) – Pressure measurements [dbar].
ww (array-like) – Vertical speed difference (measured - modeled) [cm/s].
zgrid (array-like) – Grid of pressure bin edges [dbar].
dall (array-like, optional) – Dive number array to account for degrees of freedom (default None).
- Returns:
meanw (np.ndarray) – Mean vertical speed in each bin [cm/s].
zbin (np.ndarray) – Midpoint pressure for each bin [dbar].
NNz (np.ndarray) – Number of points in each bin.
CIpm (np.ndarray, optional) – Confidence interval around mean (NaN if dall not provided).
- gliderflightOG1.tools.ramsey_offset(w_measured, w_model, updn, pressure, zgrid)[source]
Calculate Ramsey offset misfit between measured and modeled vertical speeds.
- Parameters:
w_measured (array-like) – Measured vertical speeds [cm/s].
w_model (array-like) – Modeled vertical speeds [cm/s].
updn (array-like) – Up/down flag (positive = climb, negative = dive).
pressure (array-like) – Pressure [dbar] corresponding to each measurement.
zgrid (array-like) – Pressure bin edges for averaging [dbar].
- Returns:
allmin (dict) – Dictionary containing ‘ramsey’ WRMS value.
tmp (array-like) – Difference between mean dive and mean climb profiles [cm/s].
- gliderflightOG1.tools.reformat_units_var(ds, var_name, unit_format={'S/m': 'S m-1', 'cm/s': 'cm s-1', 'degrees_Celsius': 'Celsius', 'g/m^3': 'g m-3', 'm/s': 'm s-1', 'm^3/s': 'Sv', 'meters': 'm'})[source]
Renames units in the dataset based on the provided dictionary for OG1.
- Parameters:
(xarray.Dataset) (ds)
(dict) (unit_format)
- Returns:
xarray.Dataset
- Return type:
The dataset with renamed units.
- gliderflightOG1.tools.time_derivative(time: ndarray, values: ndarray, n: int = 1, max_dt: float | None = 500) ndarray[source]
Compute the time derivative using a central difference over ±n samples.
- Parameters:
time (np.ndarray) – Array of times (datetime64).
values (np.ndarray) – Array of values to differentiate.
n (int, default=1) – Number of samples on each side for the central difference.
max_dt (float or None, default=500) – Maximum allowed time interval (s). Larger intervals are set to NaN. Set to None to disable.
- Returns:
derivative – Time derivative with NaN padding at the ends.
- Return type:
np.ndarray
utilities
- gliderflightOG1.utilities.add_heights(ds, bathymetry=None)[source]
Add height above apogee, and height above bottom.
Height above apogee is calculated independently for each profile:
height_above_apogee = max(depth in profile) - depth
Height above bottom is:
height_above_bottom = -(depth + bathymetry)
- Parameters:
ds (xarray.Dataset) – Dataset containing DEPTH, PROFILE_NUMBER, LONGITUDE and LATITUDE.
bathymetry (xarray.Dataset) – GEBCO bathymetry dataset containing ‘elevation’, ‘lon’, and ‘lat’.
- Returns:
Dataset with BATHYMETRY, HEIGHT_ABOVE_APOGEE and HEIGHT_ABOVE_BOTTOM added.
- Return type:
xarray.Dataset
- gliderflightOG1.utilities.apply_defaults(default_source: str, default_files: List[str]) Callable[source]
Decorator to apply default values for ‘source’ and ‘file_list’ parameters if they are None.
- Parameters:
default_source (str) – Default source URL or path.
default_files (list of str) – Default list of filenames.
- Returns:
A wrapped function with defaults applied.
- Return type:
Callable
- gliderflightOG1.utilities.check_og1_flight_variables(ds: Dataset, function_name: str)[source]
Check that a dataset contains required OG1 variables for flight model functions.
- Parameters:
ds (xr.Dataset) – OG1 format glider dataset to validate
function_name (str) – Name of the flight model function (key in OG1_FLIGHT_MODEL_VARS)
- Raises:
KeyError – If required variables are missing
ValueError – If function_name is not recognized
- Returns:
missing_optional – List of optional variables that are missing (for informational purposes)
- Return type:
list
- gliderflightOG1.utilities.construct_2dgrid(x, y, v, xi=1, yi=1, x_bin_center: bool = True, y_bin_center: bool = True, agg: str = 'median')[source]
Constructs a 2D gridded representation of input data based on specified resolutions. The function takes in x, y, and v data, and generates a grid where each cell contains the aggregated value (e.g., mean, median) of v corresponding to the x and y coordinates. If the input data is already binned and you want the grid coordinates to align with the original bin edges, set x_bin_center and y_bin_center to False and the resolution (i.e. xi and yi) to the bin size.
- Parameters:
x (array-like) – Input data representing the x-dimension.
y (array-like) – Input data representing the y-dimension.
v (array-like) – Input data representing the z-dimension (values to be gridded).
xi (int or float, optional, default=1) – Resolution for the x-dimension grid spacing.
yi (int or float, optional, default=1) – Resolution for the y-dimension grid spacing.
x_bin_center (bool, optional, default=True) – If True, the x-coordinate grid (XI) corresponds to the center of each x-bin. If False, it corresponds to the left edge of each bin. This is especially useful if the input x data is already binned with the same resolution as xi, and you want the grid coordinates to align with the original bin edges. (e.g. profile numbers).
y_bin_center (bool, optional, default=True) – Same as x_bin_center, but for the y-coordinate grid (YI). Set to False if your y data is already pre-binned with the same resolution as yi.
agg (str, optional, default='median') – Aggregation method to be used for gridding. Options include ‘mean’, ‘median’, etc.
- Returns:
grid (numpy.ndarray) – Gridded representation of the z-values over the x and y space.
XI (numpy.ndarray) – Gridded x-coordinates corresponding to the specified resolution.
YI (numpy.ndarray) – Gridded y-coordinates corresponding to the specified resolution.
Notes
Original Author: Bastien Queste [Source Code](https://github.com/bastienqueste/gliderad2cp/blob/de0652f70f4768c228f83480fa7d1d71c00f9449/gliderad2cp/process_adcp.py#L140)
Modified by Till Moritz: added the aggregation parameter and the option to chose either bin center or bin edge as the grid coordinates.
- gliderflightOG1.utilities.download_file(url: str, dest_folder: str, redownload: bool = False) str[source]
Download a file from HTTP(S) or FTP to the specified destination folder.
- Parameters:
url (str) – The URL of the file to download.
dest_folder (str) – Local folder to save the downloaded file.
redownload (bool, optional) – If True, force re-download of the file even if it exists.
- Returns:
The full path to the downloaded file.
- Return type:
str
- Raises:
ValueError – If the URL scheme is unsupported.
- gliderflightOG1.utilities.interpolate_over_nans(ds, var_name, method='linear')[source]
Interpolates over NaN values in a specified variable of an xarray Dataset along the ‘N_MEASUREMENTS’ dimension.
- Parameters:
ds (xarray.Dataset) – The input dataset containing the variable to interpolate.
var_name (str) – The name of the variable in the dataset to interpolate.
method (str, optional) – The interpolation method to use (default is ‘linear’). Other methods supported by xarray can be used.
- Returns:
A new dataset with the specified variable interpolated over NaN values.
- Return type:
xarray.Dataset
- gliderflightOG1.utilities.print_profile_diffs(ds, vars_to_print=('PITCH', 'TEMP'), n=20, position='beginning', profiles=None)[source]
Print timestamps, time differences, and selected variables for each profile.
- Parameters:
ds (xarray.Dataset)
vars_to_print (list/tuple of str) – Variables to print (e.g., [“PITCH”, “TEMP”])
n (int) – Number of samples per profile
position (str) – “beginning”, “end”, or “middle” — where to select the n points
- gliderflightOG1.utilities.regular_grid(data, res)[source]
Create bin edges for a regular grid such that multiples of res fall on bin centers. For example, with res=5 the edges are [-2.5, 2.5, 7.5, …]
- Parameters:
data (array-like) – Input data used to determine the grid range.
res (float) – Grid resolution (bin width).
- Returns:
Bin edges for the regular grid.
- Return type:
numpy.ndarray
- gliderflightOG1.utilities.resolve_file_path(file_name: str, source: str | Path | None, download_url: str | None, local_data_dir: Path, redownload: bool = False) Path[source]
Resolve the path to a data file, using local source, cache, or downloading if necessary.
- Parameters:
file_name (str) – The name of the file to resolve.
source (str or Path or None) – Optional local source directory.
download_url (str or None) – URL to download the file if needed.
local_data_dir (Path) – Directory where downloaded files are stored.
redownload (bool, optional) – If True, force redownload even if cached file exists.
- Returns:
Path to the resolved file.
- Return type:
Path
- gliderflightOG1.utilities.restore_masked_array(values, mask, fill_value=nan)[source]
Restore an array to its original length using a boolean mask.
- Parameters:
values (np.ndarray) – Values corresponding to mask == True.
mask (np.ndarray) – Boolean mask of the original array.
fill_value (float, default=np.nan) – Value to insert where mask == False.
- Returns:
full_array – Array of the same length as mask.
- Return type:
np.ndarray
- gliderflightOG1.utilities.safe_update_attrs(ds: Dataset, new_attrs: Dict[str, str], overwrite: bool = False, verbose: bool = True) Dataset[source]
Safely update attributes of an xarray Dataset without overwriting existing keys, unless explicitly allowed.
- Parameters:
ds (xr.Dataset) – The xarray Dataset whose attributes will be updated.
new_attrs (dict of str) – Dictionary of new attributes to add.
overwrite (bool, optional) – If True, allow overwriting existing attributes. Defaults to False.
verbose (bool, optional) – If True, emit a warning when skipping existing attributes. Defaults to True.
- Returns:
The dataset with updated attributes.
- Return type:
xr.Dataset