{ "cells": [ { "cell_type": "markdown", "id": "c6a29764-f39c-431c-8e77-fbc6bfe20f01", "metadata": {}, "source": [ "# Demo\n", "\n", "The purpose of this notebook is to demonstrate the functionality of `gliderflightOG1`.\n", "\n", "The demo is organised to show\n", "\n", "- Step 1: Regressing the Seaglider steady flight model for chosen parameters\n", "\n", "- Step 2: Recalculating the glider flight using the flight model and chosen parameters\n", "\n" ] }, { "cell_type": "code", "execution_count": 1, "id": "6a1920f3", "metadata": { "execution": { "iopub.execute_input": "2026-10-13T13:31:56.684768Z", "iopub.status.busy": "2026-10-13T13:31:56.684629Z", "iopub.status.idle": "2026-10-13T13:31:57.590748Z", "shell.execute_reply": "2026-10-13T13:31:57.590092Z" } }, "outputs": [], "source": [ "\n", "import xarray as xr\n", "from gliderflightOG1 import plotters, tools\n", "import numpy as np\n", "from gliderflightOG1 import seaglider # Assuming correct project style\n" ] }, { "cell_type": "code", "execution_count": 2, "id": "bb7592d5", "metadata": { "execution": { "iopub.execute_input": "2026-10-13T13:31:57.592645Z", "iopub.status.busy": "2026-10-13T13:31:57.592408Z", "iopub.status.idle": "2026-10-13T13:31:57.678563Z", "shell.execute_reply": "2026-10-13T13:31:57.677946Z" } }, "outputs": [ { "ename": "ValueError", "evalue": "cannot rename 'divenum' because it is not a variable or dimension in this dataset", "output_type": "error", "traceback": [ "\u001b[31m---------------------------------------------------------------------------\u001b[39m", "\u001b[31mValueError\u001b[39m Traceback (most recent call last)", "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[2]\u001b[39m\u001b[32m, line 6\u001b[39m\n\u001b[32m 2\u001b[39m glider = xr.open_dataset(\u001b[33m'../data/sg014_20080214T220104_delayed.nc'\u001b[39m)\n\u001b[32m 3\u001b[39m glider = tools.calc_w_meas(glider)\n\u001b[32m 4\u001b[39m \n\u001b[32m 5\u001b[39m \u001b[38;5;66;03m# 2. Rename and clean up fields as needed\u001b[39;00m\n\u001b[32m----> \u001b[39m\u001b[32m6\u001b[39m glider = glider.rename({\n\u001b[32m 7\u001b[39m \u001b[33m'VBD_CC'\u001b[39m: \u001b[33m'VBD'\u001b[39m,\n\u001b[32m 8\u001b[39m \u001b[33m'divenum'\u001b[39m: \u001b[33m'DIVENUM'\u001b[39m,\n\u001b[32m 9\u001b[39m })\n", "\u001b[36mFile \u001b[39m\u001b[32m~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:4342\u001b[39m, in \u001b[36mDataset.rename\u001b[39m\u001b[34m(self, name_dict, **names)\u001b[39m\n\u001b[32m 4338\u001b[39m Dataset.rename_vars\n\u001b[32m 4339\u001b[39m Dataset.rename_dims\n\u001b[32m 4340\u001b[39m DataArray.rename\n\u001b[32m 4341\u001b[39m \"\"\"\n\u001b[32m-> \u001b[39m\u001b[32m4342\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m self._rename(name_dict=name_dict, **names)\n", "\u001b[36mFile \u001b[39m\u001b[32m~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:4280\u001b[39m, in \u001b[36mDataset._rename\u001b[39m\u001b[34m(self, name_dict, **names)\u001b[39m\n\u001b[32m 4276\u001b[39m \"\"\"\n\u001b[32m 4277\u001b[39m name_dict = either_dict_or_kwargs(name_dict, names, \u001b[33m\"rename\"\u001b[39m)\n\u001b[32m 4278\u001b[39m \u001b[38;5;28;01mfor\u001b[39;00m k \u001b[38;5;28;01min\u001b[39;00m name_dict.keys():\n\u001b[32m 4279\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m k \u001b[38;5;28;01mnot\u001b[39;00m \u001b[38;5;28;01min\u001b[39;00m self \u001b[38;5;28;01mand\u001b[39;00m k \u001b[38;5;28;01mnot\u001b[39;00m \u001b[38;5;28;01min\u001b[39;00m self.dims:\n\u001b[32m-> \u001b[39m\u001b[32m4280\u001b[39m raise ValueError(\n\u001b[32m 4281\u001b[39m f\"cannot rename {k!r} because it is not a \"\n\u001b[32m 4282\u001b[39m \u001b[33m\"variable or dimension in this dataset\"\u001b[39m\n\u001b[32m 4283\u001b[39m )\n", "\u001b[31mValueError\u001b[39m: cannot rename 'divenum' because it is not a variable or dimension in this dataset" ] } ], "source": [ "\n", "# 1. Load your dataset\n", "glider = xr.open_dataset('../data/sg014_20080214T220104_delayed.nc')\n", "glider = tools.calc_w_meas(glider)\n", "\n", "# 2. Rename and clean up fields as needed\n", "glider = glider.rename({\n", " 'VBD_CC': 'VBD',\n", " 'divenum': 'DIVENUM',\n", "})\n" ] }, { "cell_type": "code", "execution_count": 3, "id": "384b3ab6", "metadata": { "execution": { "iopub.execute_input": "2026-10-13T13:31:57.680140Z", "iopub.status.busy": "2026-10-13T13:31:57.679990Z", "iopub.status.idle": "2026-10-13T13:31:57.727643Z", "shell.execute_reply": "2026-10-13T13:31:57.727016Z" } }, "outputs": [ { "ename": "KeyError", "evalue": "\"No variable named 'VBD'. Did you mean one of ('C_VBD', 'VBD_CC')?\"", "output_type": "error", "traceback": [ "\u001b[31m---------------------------------------------------------------------------\u001b[39m", "\u001b[31mKeyError\u001b[39m Traceback (most recent call last)", "\u001b[36mFile \u001b[39m\u001b[32m~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:1330\u001b[39m, in \u001b[36mDataset._construct_dataarray\u001b[39m\u001b[34m(self, name)\u001b[39m\n\u001b[32m 1328\u001b[39m variable = self._variables[name]\n\u001b[32m 1329\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m KeyError:\n\u001b[32m-> \u001b[39m\u001b[32m1330\u001b[39m _, name, variable = _get_virtual_variable(self._variables, name, self.sizes)\n\u001b[32m 1331\u001b[39m \n", "\u001b[31mKeyError\u001b[39m: 'VBD'", "\nDuring handling of the above exception, another exception occurred:\n", "\u001b[31mKeyError\u001b[39m Traceback (most recent call last)", "\u001b[36mFile \u001b[39m\u001b[32m~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:1448\u001b[39m, in \u001b[36mDataset.__getitem__\u001b[39m\u001b[34m(self, key)\u001b[39m\n\u001b[32m 1446\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m isinstance(key, tuple):\n\u001b[32m 1447\u001b[39m message += f\"\\nHint: use a list to select multiple variables, for example `ds[{list(key)}]`\"\n\u001b[32m-> \u001b[39m\u001b[32m1448\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m KeyError(message) \u001b[38;5;28;01mfrom\u001b[39;00m e\n\u001b[32m 1449\u001b[39m \n", "\u001b[36mFile \u001b[39m\u001b[32m~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:1330\u001b[39m, in \u001b[36mDataset._construct_dataarray\u001b[39m\u001b[34m(self, name)\u001b[39m\n\u001b[32m 1328\u001b[39m variable = self._variables[name]\n\u001b[32m 1329\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m KeyError:\n\u001b[32m-> \u001b[39m\u001b[32m1330\u001b[39m _, name, variable = _get_virtual_variable(self._variables, name, self.sizes)\n\u001b[32m 1331\u001b[39m \n", "\u001b[36mFile \u001b[39m\u001b[32m~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset_utils.py:79\u001b[39m, in \u001b[36m_get_virtual_variable\u001b[39m\u001b[34m(variables, key, dim_sizes)\u001b[39m\n\u001b[32m 78\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mlen\u001b[39m(split_key) != \u001b[32m2\u001b[39m:\n\u001b[32m---> \u001b[39m\u001b[32m79\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mKeyError\u001b[39;00m(key)\n\u001b[32m 81\u001b[39m ref_name, var_name = split_key\n", "\u001b[31mKeyError\u001b[39m: 'VBD'", "\nThe above exception was the direct cause of the following exception:\n", "\u001b[31mKeyError\u001b[39m Traceback (most recent call last)", "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[3]\u001b[39m\u001b[32m, line 11\u001b[39m\n\u001b[32m 7\u001b[39m \u001b[38;5;66;03m# Assume TIME is in seconds or known units\u001b[39;00m\n\u001b[32m 8\u001b[39m \n\u001b[32m 9\u001b[39m \n\u001b[32m 10\u001b[39m \u001b[38;5;66;03m# c) Create fake C_VBD\u001b[39;00m\n\u001b[32m---> \u001b[39m\u001b[32m11\u001b[39m glider[\u001b[33m'C_VBD'\u001b[39m] = xr.zeros_like(glider[\u001b[33m'VBD'\u001b[39m])\n", "\u001b[36mFile \u001b[39m\u001b[32m~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:1448\u001b[39m, in \u001b[36mDataset.__getitem__\u001b[39m\u001b[34m(self, key)\u001b[39m\n\u001b[32m 1444\u001b[39m \n\u001b[32m 1445\u001b[39m \u001b[38;5;66;03m# If someone attempts `ds['foo' , 'bar']` instead of `ds[['foo', 'bar']]`\u001b[39;00m\n\u001b[32m 1446\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m isinstance(key, tuple):\n\u001b[32m 1447\u001b[39m message += f\"\\nHint: use a list to select multiple variables, for example `ds[{list(key)}]`\"\n\u001b[32m-> \u001b[39m\u001b[32m1448\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m KeyError(message) \u001b[38;5;28;01mfrom\u001b[39;00m e\n\u001b[32m 1449\u001b[39m \n\u001b[32m 1450\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m utils.iterable_of_hashable(key):\n\u001b[32m 1451\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m self._copy_listed(key)\n", "\u001b[31mKeyError\u001b[39m: \"No variable named 'VBD'. Did you mean one of ('C_VBD', 'VBD_CC')?\"" ] } ], "source": [ "\n", "# 3. Add missing variables\n", "# a) Create UPDN from PITCH\n", "glider = glider.assign_coords(TIME=glider['TIME']) # Make sure TIME is coordinate\n", "glider['UPDN'] = xr.where(glider['PITCH'] > 0, 1, -1)\n", "\n", "# b) Create VERTICAL_SPEED from dP/dt\n", "# Assume TIME is in seconds or known units\n", "\n", "\n", "# c) Create fake C_VBD\n", "glider['C_VBD'] = xr.zeros_like(glider['VBD'])\n" ] }, { "cell_type": "code", "execution_count": 4, "id": "92fb8d8b", "metadata": { "execution": { "iopub.execute_input": "2026-10-13T13:31:57.729302Z", "iopub.status.busy": "2026-10-13T13:31:57.729148Z", "iopub.status.idle": "2026-10-13T13:31:57.752629Z", "shell.execute_reply": "2026-10-13T13:31:57.752102Z" } }, "outputs": [ { "ename": "KeyError", "evalue": "\"No variable named 'DIVENUM'. Did you mean one of ('DIVE_NUMBER',)?\"", "output_type": "error", "traceback": [ "\u001b[31m---------------------------------------------------------------------------\u001b[39m", "\u001b[31mKeyError\u001b[39m Traceback (most recent call last)", "\u001b[36mFile \u001b[39m\u001b[32m~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:1330\u001b[39m, in \u001b[36mDataset._construct_dataarray\u001b[39m\u001b[34m(self, name)\u001b[39m\n\u001b[32m 1328\u001b[39m variable = self._variables[name]\n\u001b[32m 1329\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m KeyError:\n\u001b[32m-> \u001b[39m\u001b[32m1330\u001b[39m _, name, variable = _get_virtual_variable(self._variables, name, self.sizes)\n\u001b[32m 1331\u001b[39m \n", "\u001b[31mKeyError\u001b[39m: 'DIVENUM'", "\nDuring handling of the above exception, another exception occurred:\n", "\u001b[31mKeyError\u001b[39m Traceback (most recent call last)", "\u001b[36mFile \u001b[39m\u001b[32m~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:1448\u001b[39m, in \u001b[36mDataset.__getitem__\u001b[39m\u001b[34m(self, key)\u001b[39m\n\u001b[32m 1446\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m isinstance(key, tuple):\n\u001b[32m 1447\u001b[39m message += f\"\\nHint: use a list to select multiple variables, for example `ds[{list(key)}]`\"\n\u001b[32m-> \u001b[39m\u001b[32m1448\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m KeyError(message) \u001b[38;5;28;01mfrom\u001b[39;00m e\n\u001b[32m 1449\u001b[39m \n", "\u001b[36mFile \u001b[39m\u001b[32m~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:1330\u001b[39m, in \u001b[36mDataset._construct_dataarray\u001b[39m\u001b[34m(self, name)\u001b[39m\n\u001b[32m 1328\u001b[39m variable = self._variables[name]\n\u001b[32m 1329\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m KeyError:\n\u001b[32m-> \u001b[39m\u001b[32m1330\u001b[39m _, name, variable = _get_virtual_variable(self._variables, name, self.sizes)\n\u001b[32m 1331\u001b[39m \n", "\u001b[36mFile \u001b[39m\u001b[32m~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset_utils.py:79\u001b[39m, in \u001b[36m_get_virtual_variable\u001b[39m\u001b[34m(variables, key, dim_sizes)\u001b[39m\n\u001b[32m 78\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mlen\u001b[39m(split_key) != \u001b[32m2\u001b[39m:\n\u001b[32m---> \u001b[39m\u001b[32m79\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mKeyError\u001b[39;00m(key)\n\u001b[32m 81\u001b[39m ref_name, var_name = split_key\n", "\u001b[31mKeyError\u001b[39m: 'DIVENUM'", "\nThe above exception was the direct cause of the following exception:\n", "\u001b[31mKeyError\u001b[39m Traceback (most recent call last)", "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[4]\u001b[39m\u001b[32m, line 18\u001b[39m\n\u001b[32m 14\u001b[39m \u001b[33m'mass'\u001b[39m: \u001b[32m52.0\u001b[39m, \u001b[38;5;66;03m# Approx mass of glider [kg]\u001b[39;00m\n\u001b[32m 15\u001b[39m })\n\u001b[32m 16\u001b[39m \n\u001b[32m 17\u001b[39m \u001b[38;5;66;03m# 4. Subselect a few dives to test\u001b[39;00m\n\u001b[32m---> \u001b[39m\u001b[32m18\u001b[39m dives_to_use = glider[\u001b[33m'DIVENUM'\u001b[39m].values\n\u001b[32m 19\u001b[39m ensmat = dives_to_use[:\u001b[32m20\u001b[39m] \u001b[38;5;66;03m# first 20 dives for testing\u001b[39;00m\n", "\u001b[36mFile \u001b[39m\u001b[32m~/micromamba/envs/gliderflightOG1/lib/python3.14/site-packages/xarray/core/dataset.py:1448\u001b[39m, in \u001b[36mDataset.__getitem__\u001b[39m\u001b[34m(self, key)\u001b[39m\n\u001b[32m 1444\u001b[39m \n\u001b[32m 1445\u001b[39m \u001b[38;5;66;03m# If someone attempts `ds['foo' , 'bar']` instead of `ds[['foo', 'bar']]`\u001b[39;00m\n\u001b[32m 1446\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m isinstance(key, tuple):\n\u001b[32m 1447\u001b[39m message += f\"\\nHint: use a list to select multiple variables, for example `ds[{list(key)}]`\"\n\u001b[32m-> \u001b[39m\u001b[32m1448\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m KeyError(message) \u001b[38;5;28;01mfrom\u001b[39;00m e\n\u001b[32m 1449\u001b[39m \n\u001b[32m 1450\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m utils.iterable_of_hashable(key):\n\u001b[32m 1451\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m self._copy_listed(key)\n", "\u001b[31mKeyError\u001b[39m: \"No variable named 'DIVENUM'. Did you mean one of ('DIVE_NUMBER',)?\"" ] } ], "source": [ "\n", "# d) Add starter attributes\n", "glider.attrs.update({\n", " 'hd_a': 0.0036, # starting guess\n", " 'hd_b': 0.0098, # starting guess\n", " 'hd_c': 0.0010, # starting guess\n", " 'vbdbias': 0.0, # start assuming no bias\n", " 'abs_compress': 4e-6, # reasonable guess\n", " 'therm_expan': 2e-5, # reasonable guess\n", " 'rho0': 1025.0, # typical seawater density\n", " 'vbd_min_cnts': 0.0,\n", " 'vbd_cnts_per_cc': 1.0,\n", " 'temp_ref': 10.0,\n", " 'volmax': 0.0,\n", " 'mass': 52.0, # Approx mass of glider [kg]\n", "})\n", "\n", "# 4. Subselect a few dives to test\n", "dives_to_use = glider['DIVENUM'].values\n", "ensmat = dives_to_use[:20] # first 20 dives for testing\n" ] }, { "cell_type": "code", "execution_count": 5, "id": "254dc998", "metadata": { "execution": { "iopub.execute_input": "2026-10-13T13:31:57.754228Z", "iopub.status.busy": "2026-10-13T13:31:57.754067Z", "iopub.status.idle": "2026-10-13T13:31:57.771922Z", "shell.execute_reply": "2026-10-13T13:31:57.771248Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
<xarray.Dataset> Size: 16MB\n",
       "Dimensions:                 (N_MEASUREMENTS: 54046)\n",
       "Coordinates:\n",
       "    TIME                    (N_MEASUREMENTS) datetime64[ns] 432kB 2008-02-14T...\n",
       "    DEPTH                   (N_MEASUREMENTS) float64 432kB 0.0 0.0 ... 1.254 0.0\n",
       "    LONGITUDE               (N_MEASUREMENTS) float64 432kB ...\n",
       "    LATITUDE                (N_MEASUREMENTS) float64 432kB ...\n",
       "Dimensions without coordinates: N_MEASUREMENTS\n",
       "Data variables: (12/72)\n",
       "    TEMP_RAW_QC             (N_MEASUREMENTS) float32 216kB ...\n",
       "    TEMP_QC                 (N_MEASUREMENTS) float32 216kB ...\n",
       "    GLIDE_SPEED_QC          (N_MEASUREMENTS) float32 216kB ...\n",
       "    TIME_DOXY               (N_MEASUREMENTS) datetime64[ns] 432kB ...\n",
       "    DOXY_QC                 (N_MEASUREMENTS) float32 216kB ...\n",
       "    PSAL_RAW_QC             (N_MEASUREMENTS) float32 216kB ...\n",
       "    ...                      ...\n",
       "    TRAJECTORY              <U21 84B ...\n",
       "    DEPLOYMENT_LATITUDE     float64 8B ...\n",
       "    DEPLOYMENT_LONGITUDE    float64 8B ...\n",
       "    DEPLOYMENT_TIME         datetime64[ns] 8B ...\n",
       "    GLIDER_VERT_VELO_DZDT   (N_MEASUREMENTS) float64 432kB 0.0001975 ... -0.0...\n",
       "    UPDN                    (N_MEASUREMENTS) int64 432kB -1 -1 -1 -1 ... 1 1 -1\n",
       "Attributes: (12/52)\n",
       "    title:                                      OceanGliders trajectory file\n",
       "    id:                                         sg014_20080214T220104_delayed\n",
       "    platform:                                   sub-surface gliders\n",
       "    platform_vocabulary:                        https://vocab.nerc.ac.uk/coll...\n",
       "    naming_authority:                           edu.washington.apl\n",
       "    institution:                                School of Oceanography\\nUnive...\n",
       "    ...                                         ...\n",
       "    rho0:                                       1025.0\n",
       "    vbd_min_cnts:                               0.0\n",
       "    vbd_cnts_per_cc:                            1.0\n",
       "    temp_ref:                                   10.0\n",
       "    volmax:                                     0.0\n",
       "    mass:                                       52.0
" ], "text/plain": [ " Size: 16MB\n", "Dimensions: (N_MEASUREMENTS: 54046)\n", "Coordinates:\n", " TIME (N_MEASUREMENTS) datetime64[ns] 432kB 2008-02-14T...\n", " DEPTH (N_MEASUREMENTS) float64 432kB 0.0 0.0 ... 1.254 0.0\n", " LONGITUDE (N_MEASUREMENTS) float64 432kB ...\n", " LATITUDE (N_MEASUREMENTS) float64 432kB ...\n", "Dimensions without coordinates: N_MEASUREMENTS\n", "Data variables: (12/72)\n", " TEMP_RAW_QC (N_MEASUREMENTS) float32 216kB ...\n", " TEMP_QC (N_MEASUREMENTS) float32 216kB ...\n", " GLIDE_SPEED_QC (N_MEASUREMENTS) float32 216kB ...\n", " TIME_DOXY (N_MEASUREMENTS) datetime64[ns] 432kB ...\n", " DOXY_QC (N_MEASUREMENTS) float32 216kB ...\n", " PSAL_RAW_QC (N_MEASUREMENTS) float32 216kB ...\n", " ... ...\n", " TRAJECTORY \u001b[39m\u001b[32m9\u001b[39m ensmat=ensmat,\n\u001b[32m 10\u001b[39m plotflag=\u001b[38;5;28;01mFalse\u001b[39;00m,\n\u001b[32m 11\u001b[39m unstdyflag=\u001b[32m0\u001b[39m,\n\u001b[32m 12\u001b[39m )\n", "\u001b[31mNameError\u001b[39m: name 'ensmat' is not defined" ] } ], "source": [ "\n", "# 5. Which parameters to optimize\n", "whichpar = [1, 1, 1, 0, 0, 0] # solve for hd_a, hd_b, vbdbias\n", "\n", "# 6. Run the regression\n", "regressout, allwrms = seaglider.regress_all_vec(\n", " whichpar=whichpar,\n", " glider=glider,\n", " whichone=10, # Ramsey's method\n", " ensmat=ensmat,\n", " plotflag=False,\n", " unstdyflag=0,\n", ")\n", "\n", "def renormalize_params(params, factors, direction='normalize'):\n", " \"\"\"Renormalize parameters with given factors.\n", "\n", " Parameters\n", " ----------\n", " params : np.ndarray\n", " The parameters to transform. Expected order is\n", " [hd_a, hd_b, vbdbias, abs_compress, therm_expan, hd_c].\n", " factors : list or np.ndarray\n", " The factors for renormalization.\n", " direction : str, optional\n", " 'normalize' to divide by factors, 'denormalize' to multiply by factors.\n", " Default is 'normalize'.\n", "\n", " Returns\n", " -------\n", " np.ndarray\n", " Transformed parameters.\n", "\n", " Raises\n", " ------\n", " ValueError\n", " If the direction is not 'normalize' or 'denormalize'.\n", "\n", " \"\"\"\n", " if direction == 'normalize':\n", " return params * factors\n", " elif direction == 'denormalize':\n", " return params / factors\n", " else:\n", " raise ValueError(\"Direction must be 'normalize' or 'denormalize'.\")\n", "\n", "# Define renormalization factors\n", "factors = np.array([1e3, 1e3, 1, 1e6, 1e5, 1e5])\n", "\n", "# Create a vector of params from regressout with the same size as factors\n", "params = np.zeros_like(factors)\n", "params[np.array(whichpar, dtype=bool)] = regressout\n", "# Renormalize regressout\n", "#regressout_normalized = renormalize_params(regressout, factors, direction='normalize')\n", "regressout_norm = renormalize_params(params, factors, direction='denormalize')\n", "\n", "print(\"Optimized parameters:\", regressout_norm)\n", "print(\"Final WRMS:\", allwrms)\n", "\n" ] }, { "cell_type": "code", "execution_count": 7, "id": "d29c335e", "metadata": { "execution": { "iopub.execute_input": "2026-10-13T13:31:57.784170Z", "iopub.status.busy": "2026-10-13T13:31:57.784041Z", "iopub.status.idle": "2026-10-13T13:31:57.791775Z", "shell.execute_reply": "2026-10-13T13:31:57.791103Z" } }, "outputs": [ { "ename": "NameError", "evalue": "name 'regressout_norm' is not defined", "output_type": "error", "traceback": [ "\u001b[31m---------------------------------------------------------------------------\u001b[39m", "\u001b[31mNameError\u001b[39m Traceback (most recent call last)", "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[7]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m regressout_norm\n", "\u001b[31mNameError\u001b[39m: name 'regressout_norm' is not defined" ] } ], "source": [ "regressout_norm" ] }, { "cell_type": "code", "execution_count": 8, "id": "e2d99f12", "metadata": { "execution": { "iopub.execute_input": "2026-10-13T13:31:57.793082Z", "iopub.status.busy": "2026-10-13T13:31:57.792955Z", "iopub.status.idle": "2026-10-13T13:31:57.802733Z", "shell.execute_reply": "2026-10-13T13:31:57.802067Z" } }, "outputs": [ { "ename": "NameError", "evalue": "name 'regressout_norm' is not defined", "output_type": "error", "traceback": [ "\u001b[31m---------------------------------------------------------------------------\u001b[39m", "\u001b[31mNameError\u001b[39m Traceback (most recent call last)", "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[8]\u001b[39m\u001b[32m, line 6\u001b[39m\n\u001b[32m 2\u001b[39m \u001b[38;5;66;03m# Update glider attributes with optimized parameters\u001b[39;00m\n\u001b[32m 3\u001b[39m glider.attrs.update({\n\u001b[32m 4\u001b[39m \u001b[38;5;66;03m# 'hd_a': regressout_norm[0],\u001b[39;00m\n\u001b[32m 5\u001b[39m \u001b[38;5;66;03m# 'hd_b': regressout_norm[1],\u001b[39;00m\n\u001b[32m----> \u001b[39m\u001b[32m6\u001b[39m \u001b[33m'vbdbias'\u001b[39m: regressout_norm[\u001b[32m2\u001b[39m],\n\u001b[32m 7\u001b[39m \u001b[38;5;66;03m# Keep other parameters as they were\u001b[39;00m\n\u001b[32m 8\u001b[39m })\n\u001b[32m 9\u001b[39m \n", "\u001b[31mNameError\u001b[39m: name 'regressout_norm' is not defined" ] } ], "source": [ "# 7. Apply optimized parameters and run flight model\n", "# Update glider attributes with optimized parameters\n", "glider.attrs.update({\n", "# 'hd_a': regressout_norm[0],\n", "# 'hd_b': regressout_norm[1], \n", " 'vbdbias': regressout_norm[2],\n", " # Keep other parameters as they were\n", "})\n", "\n", "# Run flight model with optimized parameters\n", "try:\n", " # Calculate flight velocities using the optimized parameters\n", " glider_with_model = seaglider.flightvec_ds(\n", " glider, \n", " xl=1.0, # typical glider length in meters\n", " hd_a=glider.attrs['hd_a'],\n", " hd_b=glider.attrs['hd_b'], \n", " hd_c=glider.attrs['hd_c']\n", " )\n", " \n", " print(\"Flight model calculation completed successfully!\")\n", " print(f\"Added variables: {list(set(glider_with_model.data_vars) - set(glider.data_vars))}\")\n", " \n", " # Simple plot showing model results\n", " import matplotlib.pyplot as plt\n", " \n", " # Plot a subset of the data for visualization\n", " time_subset = slice(0, 500) # First 500 data points\n", " \n", " fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))\n", " \n", " # Plot vertical velocities\n", " if 'VERTICAL_SPEED' in glider_with_model:\n", " ax1.plot(glider_with_model['TIME'][time_subset], \n", " glider_with_model['VERTICAL_SPEED'][time_subset], \n", " 'b-', label='Observed', alpha=0.7)\n", " \n", " if 'umag' in glider_with_model:\n", " ax1.plot(glider_with_model['TIME'][time_subset], \n", " glider_with_model['umag'][time_subset], \n", " 'r-', label='Model (umag)', alpha=0.7)\n", " \n", " ax1.set_ylabel('Velocity (m/s)')\n", " ax1.set_title('Glider Flight Model Results')\n", " ax1.legend()\n", " ax1.grid(True, alpha=0.3)\n", " \n", " # Plot glide angle if available\n", " if 'thdeg' in glider_with_model:\n", " ax2.plot(glider_with_model['TIME'][time_subset], \n", " glider_with_model['thdeg'][time_subset], \n", " 'g-', label='Glide Angle (degrees)', alpha=0.7)\n", " ax2.set_ylabel('Angle (degrees)')\n", " ax2.legend()\n", " ax2.grid(True, alpha=0.3)\n", " \n", " ax2.set_xlabel('Time')\n", " \n", " plt.tight_layout()\n", " plt.show()\n", " \n", "except Exception as e:\n", " print(f\"Error running flight model: {e}\")\n", " print(\"This may be due to missing variables or incompatible data format.\")\n", " print(\"Check that all required variables are present in the dataset.\")" ] } ], "metadata": { "kernelspec": { "display_name": "venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.14.8" } }, "nbformat": 4, "nbformat_minor": 5 }