Demo

The purpose of this notebook is to demonstrate the functionality of gliderflightOG1.

The demo is organised to show

  • Step 1: Regressing the Seaglider steady flight model for chosen parameters

  • Step 2: Recalculating the glider flight using the flight model and chosen parameters

[1]:

import xarray as xr from gliderflightOG1 import plotters, tools import numpy as np from gliderflightOG1 import seaglider # Assuming correct project style
[2]:

# 1. Load your dataset glider = xr.open_dataset('../data/sg014_20080214T220104_delayed.nc') glider = tools.calc_w_meas(glider) # 2. Rename and clean up fields as needed glider = glider.rename({ 'VBD_CC': 'VBD', 'divenum': 'DIVENUM', })
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[2], line 6
      2 glider = xr.open_dataset('../data/sg014_20080214T220104_delayed.nc')
      3 glider = tools.calc_w_meas(glider)
      4
      5 # 2. Rename and clean up fields as needed
----> 6 glider = glider.rename({
      7     'VBD_CC': 'VBD',
      8     'divenum': 'DIVENUM',
      9 })

File ~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:4342, in Dataset.rename(self, name_dict, **names)
   4338         Dataset.rename_vars
   4339         Dataset.rename_dims
   4340         DataArray.rename
   4341         """
-> 4342         return self._rename(name_dict=name_dict, **names)

File ~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:4280, in Dataset._rename(self, name_dict, **names)
   4276         """
   4277         name_dict = either_dict_or_kwargs(name_dict, names, "rename")
   4278         for k in name_dict.keys():
   4279             if k not in self and k not in self.dims:
-> 4280                 raise ValueError(
   4281                     f"cannot rename {k!r} because it is not a "
   4282                     "variable or dimension in this dataset"
   4283                 )

ValueError: cannot rename 'divenum' because it is not a variable or dimension in this dataset
[3]:

# 3. Add missing variables # a) Create UPDN from PITCH glider = glider.assign_coords(TIME=glider['TIME']) # Make sure TIME is coordinate glider['UPDN'] = xr.where(glider['PITCH'] > 0, 1, -1) # b) Create VERTICAL_SPEED from dP/dt # Assume TIME is in seconds or known units # c) Create fake C_VBD glider['C_VBD'] = xr.zeros_like(glider['VBD'])
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File ~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:1330, in Dataset._construct_dataarray(self, name)
   1328             variable = self._variables[name]
   1329         except KeyError:
-> 1330             _, name, variable = _get_virtual_variable(self._variables, name, self.sizes)
   1331

KeyError: 'VBD'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
File ~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:1448, in Dataset.__getitem__(self, key)
   1446                 if isinstance(key, tuple):
   1447                     message += f"\nHint: use a list to select multiple variables, for example `ds[{list(key)}]`"
-> 1448                 raise KeyError(message) from e
   1449

File ~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:1330, in Dataset._construct_dataarray(self, name)
   1328             variable = self._variables[name]
   1329         except KeyError:
-> 1330             _, name, variable = _get_virtual_variable(self._variables, name, self.sizes)
   1331

File ~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset_utils.py:79, in _get_virtual_variable(variables, key, dim_sizes)
     78 if len(split_key) != 2:
---> 79     raise KeyError(key)
     81 ref_name, var_name = split_key

KeyError: 'VBD'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
Cell In[3], line 11
      7 # Assume TIME is in seconds or known units
      8
      9
     10 # c) Create fake C_VBD
---> 11 glider['C_VBD'] = xr.zeros_like(glider['VBD'])

File ~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:1448, in Dataset.__getitem__(self, key)
   1444
   1445                 # If someone attempts `ds['foo' , 'bar']` instead of `ds[['foo', 'bar']]`
   1446                 if isinstance(key, tuple):
   1447                     message += f"\nHint: use a list to select multiple variables, for example `ds[{list(key)}]`"
-> 1448                 raise KeyError(message) from e
   1449
   1450         if utils.iterable_of_hashable(key):
   1451             return self._copy_listed(key)

KeyError: "No variable named 'VBD'. Did you mean one of ('C_VBD', 'VBD_CC')?"
[4]:

# d) Add starter attributes glider.attrs.update({ 'hd_a': 0.0036, # starting guess 'hd_b': 0.0098, # starting guess 'hd_c': 0.0010, # starting guess 'vbdbias': 0.0, # start assuming no bias 'abs_compress': 4e-6, # reasonable guess 'therm_expan': 2e-5, # reasonable guess 'rho0': 1025.0, # typical seawater density 'vbd_min_cnts': 0.0, 'vbd_cnts_per_cc': 1.0, 'temp_ref': 10.0, 'volmax': 0.0, 'mass': 52.0, # Approx mass of glider [kg] }) # 4. Subselect a few dives to test dives_to_use = glider['DIVENUM'].values ensmat = dives_to_use[:20] # first 20 dives for testing
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File ~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:1330, in Dataset._construct_dataarray(self, name)
   1328             variable = self._variables[name]
   1329         except KeyError:
-> 1330             _, name, variable = _get_virtual_variable(self._variables, name, self.sizes)
   1331

KeyError: 'DIVENUM'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
File ~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:1448, in Dataset.__getitem__(self, key)
   1446                 if isinstance(key, tuple):
   1447                     message += f"\nHint: use a list to select multiple variables, for example `ds[{list(key)}]`"
-> 1448                 raise KeyError(message) from e
   1449

File ~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:1330, in Dataset._construct_dataarray(self, name)
   1328             variable = self._variables[name]
   1329         except KeyError:
-> 1330             _, name, variable = _get_virtual_variable(self._variables, name, self.sizes)
   1331

File ~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset_utils.py:79, in _get_virtual_variable(variables, key, dim_sizes)
     78 if len(split_key) != 2:
---> 79     raise KeyError(key)
     81 ref_name, var_name = split_key

KeyError: 'DIVENUM'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
Cell In[4], line 18
     14     'mass': 52.0,  # Approx mass of glider [kg]
     15 })
     16
     17 # 4. Subselect a few dives to test
---> 18 dives_to_use = glider['DIVENUM'].values
     19 ensmat = dives_to_use[:20]  # first 20 dives for testing

File ~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:1448, in Dataset.__getitem__(self, key)
   1444
   1445                 # If someone attempts `ds['foo' , 'bar']` instead of `ds[['foo', 'bar']]`
   1446                 if isinstance(key, tuple):
   1447                     message += f"\nHint: use a list to select multiple variables, for example `ds[{list(key)}]`"
-> 1448                 raise KeyError(message) from e
   1449
   1450         if utils.iterable_of_hashable(key):
   1451             return self._copy_listed(key)

KeyError: "No variable named 'DIVENUM'. Did you mean one of ('DIVE_NUMBER',)?"
[5]:
glider
[5]:
<xarray.Dataset> Size: 16MB
Dimensions:                 (N_MEASUREMENTS: 54046)
Coordinates:
    TIME                    (N_MEASUREMENTS) datetime64[ns] 432kB 2008-02-14T...
    DEPTH                   (N_MEASUREMENTS) float64 432kB 0.0 0.0 ... 1.254 0.0
    LONGITUDE               (N_MEASUREMENTS) float64 432kB ...
    LATITUDE                (N_MEASUREMENTS) float64 432kB ...
Dimensions without coordinates: N_MEASUREMENTS
Data variables: (12/72)
    TEMP_RAW_QC             (N_MEASUREMENTS) float32 216kB ...
    TEMP_QC                 (N_MEASUREMENTS) float32 216kB ...
    GLIDE_SPEED_QC          (N_MEASUREMENTS) float32 216kB ...
    TIME_DOXY               (N_MEASUREMENTS) datetime64[ns] 432kB ...
    DOXY_QC                 (N_MEASUREMENTS) float32 216kB ...
    PSAL_RAW_QC             (N_MEASUREMENTS) float32 216kB ...
    ...                      ...
    TRAJECTORY              <U21 84B ...
    DEPLOYMENT_LATITUDE     float64 8B ...
    DEPLOYMENT_LONGITUDE    float64 8B ...
    DEPLOYMENT_TIME         datetime64[ns] 8B ...
    GLIDER_VERT_VELO_DZDT   (N_MEASUREMENTS) float64 432kB 0.0001975 ... -0.0...
    UPDN                    (N_MEASUREMENTS) int64 432kB -1 -1 -1 -1 ... 1 1 -1
Attributes: (12/52)
    title:                                      OceanGliders trajectory file
    id:                                         sg014_20080214T220104_delayed
    platform:                                   sub-surface gliders
    platform_vocabulary:                        https://vocab.nerc.ac.uk/coll...
    naming_authority:                           edu.washington.apl
    institution:                                School of Oceanography\nUnive...
    ...                                         ...
    rho0:                                       1025.0
    vbd_min_cnts:                               0.0
    vbd_cnts_per_cc:                            1.0
    temp_ref:                                   10.0
    volmax:                                     0.0
    mass:                                       52.0
[6]:

# 5. Which parameters to optimize whichpar = [1, 1, 1, 0, 0, 0] # solve for hd_a, hd_b, vbdbias # 6. Run the regression regressout, allwrms = seaglider.regress_all_vec( whichpar=whichpar, glider=glider, whichone=10, # Ramsey's method ensmat=ensmat, plotflag=False, unstdyflag=0, ) def renormalize_params(params, factors, direction='normalize'): """Renormalize parameters with given factors. Parameters ---------- params : np.ndarray The parameters to transform. Expected order is [hd_a, hd_b, vbdbias, abs_compress, therm_expan, hd_c]. factors : list or np.ndarray The factors for renormalization. direction : str, optional 'normalize' to divide by factors, 'denormalize' to multiply by factors. Default is 'normalize'. Returns ------- np.ndarray Transformed parameters. Raises ------ ValueError If the direction is not 'normalize' or 'denormalize'. """ if direction == 'normalize': return params * factors elif direction == 'denormalize': return params / factors else: raise ValueError("Direction must be 'normalize' or 'denormalize'.") # Define renormalization factors factors = np.array([1e3, 1e3, 1, 1e6, 1e5, 1e5]) # Create a vector of params from regressout with the same size as factors params = np.zeros_like(factors) params[np.array(whichpar, dtype=bool)] = regressout # Renormalize regressout #regressout_normalized = renormalize_params(regressout, factors, direction='normalize') regressout_norm = renormalize_params(params, factors, direction='denormalize') print("Optimized parameters:", regressout_norm) print("Final WRMS:", allwrms)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[6], line 9
      5 regressout, allwrms = seaglider.regress_all_vec(
      6     whichpar=whichpar,
      7     glider=glider,
      8     whichone=10,  # Ramsey's method
----> 9     ensmat=ensmat,
     10     plotflag=False,
     11     unstdyflag=0,
     12 )

NameError: name 'ensmat' is not defined
[7]:
regressout_norm
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[7], line 1
----> 1 regressout_norm

NameError: name 'regressout_norm' is not defined
[8]:
# 7. Apply optimized parameters and run flight model
# Update glider attributes with optimized parameters
glider.attrs.update({
#    'hd_a': regressout_norm[0],
#    'hd_b': regressout_norm[1],
    'vbdbias': regressout_norm[2],
    # Keep other parameters as they were
})

# Run flight model with optimized parameters
try:
    # Calculate flight velocities using the optimized parameters
    glider_with_model = seaglider.flightvec_ds(
        glider,
        xl=1.0,  # typical glider length in meters
        hd_a=glider.attrs['hd_a'],
        hd_b=glider.attrs['hd_b'],
        hd_c=glider.attrs['hd_c']
    )

    print("Flight model calculation completed successfully!")
    print(f"Added variables: {list(set(glider_with_model.data_vars) - set(glider.data_vars))}")

    # Simple plot showing model results
    import matplotlib.pyplot as plt

    # Plot a subset of the data for visualization
    time_subset = slice(0, 500)  # First 500 data points

    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))

    # Plot vertical velocities
    if 'VERTICAL_SPEED' in glider_with_model:
        ax1.plot(glider_with_model['TIME'][time_subset],
                glider_with_model['VERTICAL_SPEED'][time_subset],
                'b-', label='Observed', alpha=0.7)

    if 'umag' in glider_with_model:
        ax1.plot(glider_with_model['TIME'][time_subset],
                glider_with_model['umag'][time_subset],
                'r-', label='Model (umag)', alpha=0.7)

    ax1.set_ylabel('Velocity (m/s)')
    ax1.set_title('Glider Flight Model Results')
    ax1.legend()
    ax1.grid(True, alpha=0.3)

    # Plot glide angle if available
    if 'thdeg' in glider_with_model:
        ax2.plot(glider_with_model['TIME'][time_subset],
                glider_with_model['thdeg'][time_subset],
                'g-', label='Glide Angle (degrees)', alpha=0.7)
        ax2.set_ylabel('Angle (degrees)')
        ax2.legend()
        ax2.grid(True, alpha=0.3)

    ax2.set_xlabel('Time')

    plt.tight_layout()
    plt.show()

except Exception as e:
    print(f"Error running flight model: {e}")
    print("This may be due to missing variables or incompatible data format.")
    print("Check that all required variables are present in the dataset.")
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[8], line 6
      2 # Update glider attributes with optimized parameters
      3 glider.attrs.update({
      4 #    'hd_a': regressout_norm[0],
      5 #    'hd_b': regressout_norm[1],
----> 6     'vbdbias': regressout_norm[2],
      7     # Keep other parameters as they were
      8 })
      9

NameError: name 'regressout_norm' is not defined