Skip to content

Commit 43b1663

Browse files
authored
Merge pull request #143 from MBARIMike/main
Add planktivore variables from the Backseat (_) Group
2 parents b570dd8 + 2873082 commit 43b1663

6 files changed

Lines changed: 213 additions & 21 deletions

File tree

‎.vscode/launch.json‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -458,7 +458,9 @@
458458
// Processing truncated at 2025-01-12T15:15:43 instead of 2025-01-13T17:43:58 - seems to happen with several other log_files too
459459
//"args": ["-v", "1", "--log_file", "pontus/missionlogs/2025/20250107_20250123/20250111T233141/202501112331_202501131744.nc4", "--no_cleanup"]
460460
// Test sipper_odv() with a log_file that has an ESP Sample
461-
"args": ["-v", "1", "--log_file", "daphne/missionlogs/2026/20260316_20260318/20260317T191958/202603171919_202603181628.nc4", "--no_cleanup"]
461+
//"args": ["-v", "1", "--log_file", "daphne/missionlogs/2026/20260316_20260318/20260317T191958/202603171919_202603181628.nc4", "--no_cleanup"]
462+
// Test sipper_odv() with a log_file that has an ESP Sample
463+
"args": ["-v", "1", "--log_file", "ahi/missionlogs/2025/20250414_20250418/20250415T040019/202504150400_202504152346.nc4", "--no_cleanup"]
462464
},
463465

464466
]

‎src/data/create_products.py‎

Lines changed: 160 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,10 @@ def __init__( # noqa: PLR0913
190190
"proxy_adinos": "algae",
191191
"proxy_diatoms": "Purples",
192192
"proxy_hdinos": "Blues",
193+
"avgrois": "YlOrRd",
194+
"casetemp": "thermal",
195+
"casehumidity": "PuBu",
196+
"casepress": "deep",
193197
}
194198

195199
def _open_ds(self):
@@ -407,6 +411,20 @@ def _get_biolume_plot_variables(self) -> list:
407411
return self._get_lrauv_biolume_variables()
408412
return self._get_dorado_biolume_variables()
409413

414+
def _get_planktivore_plot_variables(self) -> list:
415+
"""Get planktivore + context variables for plot_planktivore_2column()."""
416+
return [
417+
("backseat_planktivore_hm_avgrois", "linear"),
418+
("backseat_planktivore_lm_avgrois", "linear"),
419+
("backseat_planktivore_casetemp", "linear"),
420+
("backseat_planktivore_casehumidity", "linear"),
421+
("density", "linear"),
422+
("wetlabsbb2fl_particulatebackscatteringcoeff470nm", "linear"),
423+
("wetlabsbb2fl_particulatebackscatteringcoeff650nm", "linear"),
424+
("wetlabsbb2fl_mass_concentration_of_chlorophyll_in_sea_water", "linear"),
425+
("backseat_planktivore_casepress", "linear"),
426+
]
427+
410428
def _plot_nighttime_indicator(
411429
self,
412430
fig: matplotlib.figure.Figure,
@@ -1750,12 +1768,11 @@ def plot_biolume_2column(self) -> str: # noqa: C901, PLR0912, PLR0915
17501768

17511769
self._open_ds()
17521770

1753-
# Early return if no biolume variables present
1754-
biolume_prefix = "wetlabsubat_" if self._is_lrauv() else "biolume_"
1755-
if not any(v.startswith(biolume_prefix) for v in self.ds.variables):
1771+
# Early return if no biolume plot variables present in dataset
1772+
plot_variables = self._get_biolume_plot_variables()
1773+
if not any(var in self.ds for var, _ in plot_variables):
17561774
self.logger.warning(
1757-
"No %s* variables found in dataset, skipping plot_biolume_2column",
1758-
biolume_prefix,
1775+
"No biolume plot variables found in dataset, skipping plot_biolume_2column",
17591776
)
17601777
return None
17611778

@@ -1868,6 +1885,143 @@ def plot_biolume_2column(self) -> str: # noqa: C901, PLR0912, PLR0915
18681885
self.logger.info("Saved biolume 2column plot to %s", output_file)
18691886
return str(output_file)
18701887

1888+
def plot_planktivore_2column(self) -> str: # noqa: C901, PLR0912, PLR0915
1889+
"""Create 2-column planktivore plot with map, ROIs, engineering, and context.
1890+
1891+
Layout (5 rows x 2 columns, column-major order):
1892+
(0,0) track map (0,1) density
1893+
(1,0) hm_avgrois (1,1) backscatter470
1894+
(2,0) lm_avgrois (2,1) backscatter650
1895+
(3,0) casetemp (3,1) chlorophyll
1896+
(4,0) casehumidity (4,1) casepress
1897+
"""
1898+
# Skip plotting in pytest environment - too many prerequisites for CI
1899+
if "pytest" in sys.modules:
1900+
self.logger.info("Skipping plot_planktivore_2column in pytest environment")
1901+
return None
1902+
1903+
self._open_ds()
1904+
1905+
# Early return if no planktivore plot variables present in dataset
1906+
planktivore_vars = [
1907+
v
1908+
for v, _ in self._get_planktivore_plot_variables()
1909+
if v.startswith("backseat_planktivore_")
1910+
]
1911+
if not any(var in self.ds for var in planktivore_vars):
1912+
self.logger.warning(
1913+
"No backseat_planktivore plot variables found in dataset, "
1914+
"skipping plot_planktivore_2column",
1915+
)
1916+
return None
1917+
1918+
idist, iz, distnav = self._grid_dims()
1919+
if idist.size == 0 or iz.size == 0 or distnav.size == 0:
1920+
self.logger.warning(
1921+
"Skipping plot_planktivore_2column due to missing gridding dimensions"
1922+
)
1923+
return None
1924+
1925+
fig, ax = plt.subplots(nrows=5, ncols=2, figsize=(18, 10))
1926+
plt.subplots_adjust(hspace=0.15, wspace=0.04, left=0.05, right=0.97, top=0.96, bottom=0.06)
1927+
1928+
best_ctd = None
1929+
if self._is_lrauv():
1930+
self.logger.info("LRAUV mission detected for planktivore 2column plot")
1931+
self._compute_density_lrauv()
1932+
else:
1933+
self.logger.info("Dorado mission detected for planktivore 2column plot")
1934+
best_ctd = self._get_best_ctd()
1935+
self._compute_density(best_ctd)
1936+
1937+
self._plot_track_map(ax[0, 0], ax[1, 0])
1938+
1939+
if self.auv_name and self.mission:
1940+
try:
1941+
gulper_locations = self._get_gulper_locations(distnav)
1942+
except FileNotFoundError as e:
1943+
self.logger.warning("Error retrieving gulper locations: %s", e) # noqa: TRY400
1944+
gulper_locations = {}
1945+
else:
1946+
try:
1947+
gulper_locations = self._get_sipper_locations(distnav)
1948+
except FileNotFoundError as e:
1949+
self.logger.warning("Error retrieving sipper locations: %s", e) # noqa: TRY400
1950+
gulper_locations = {}
1951+
1952+
try:
1953+
profile_bottoms = self._profile_bottoms(distnav)
1954+
except (TypeError, ValueError) as e:
1955+
self.logger.warning("Error computing profile bottoms: %s", e) # noqa: TRY400
1956+
profile_bottoms = None
1957+
1958+
try:
1959+
bottom_depths = self._get_bathymetry(
1960+
self.ds.cf["longitude"].to_numpy(),
1961+
self.ds.cf["latitude"].to_numpy(),
1962+
)
1963+
except ValueError as e: # noqa: BLE001
1964+
self.logger.warning("Error retrieving bathymetry: %s", e) # noqa: TRY400
1965+
bottom_depths = None
1966+
1967+
row = 1
1968+
col = 0
1969+
1970+
plot_variables = self._get_planktivore_plot_variables()
1971+
1972+
for var, scale in plot_variables:
1973+
self.logger.info("Plotting %s...", var)
1974+
if var not in self.ds:
1975+
self.logger.warning("%s not in dataset, plotting with no data", var)
1976+
1977+
self._plot_var(
1978+
var,
1979+
idist,
1980+
iz,
1981+
distnav,
1982+
fig,
1983+
ax,
1984+
row,
1985+
col,
1986+
profile_bottoms,
1987+
scale=scale,
1988+
gulper_locations=gulper_locations,
1989+
bottom_depths=bottom_depths,
1990+
best_ctd=best_ctd,
1991+
)
1992+
if row != 4: # noqa: PLR2004
1993+
ax[row, col].get_xaxis().set_visible(False)
1994+
else:
1995+
ax[row, col].set_xlabel("Distance along track (km)")
1996+
1997+
if row == 4 and col == 0: # noqa: PLR2004
1998+
row = 0
1999+
col = 1
2000+
else:
2001+
row += 1
2002+
2003+
self._plot_nighttime_indicator(fig, ax[0, 1], distnav)
2004+
2005+
if self._is_lrauv():
2006+
netcdfs_dir = Path(BASE_LRAUV_PATH, f"{Path(self.log_file).parent}")
2007+
output_file = Path(
2008+
netcdfs_dir,
2009+
f"{Path(self.log_file).stem}_{self.freq}_2column_planktivore.png",
2010+
)
2011+
else:
2012+
images_dir = Path(BASE_PATH, self.auv_name, MISSIONIMAGES, self.mission)
2013+
Path(images_dir).mkdir(parents=True, exist_ok=True)
2014+
output_file = Path(
2015+
images_dir,
2016+
f"{self.auv_name}_{self.mission}_{self.freq}_2column_planktivore.png",
2017+
)
2018+
plt.savefig(output_file, dpi=100, bbox_inches="tight")
2019+
plt.show()
2020+
plt.close(fig)
2021+
2022+
self.logger.info("Saved planktivore 2column plot to %s", output_file)
2023+
return str(output_file)
2024+
18712025
def _get_best_ctd(self) -> str:
18722026
"""Determine best CTD to use for ODV lookup table based on metadata"""
18732027
# LRAUV doesn't use multiple CTDs, return None
@@ -2333,6 +2487,7 @@ def process_command_line(self):
23332487
p_start = time.time()
23342488
cp.plot_2column()
23352489
cp.plot_biolume_2column()
2490+
cp.plot_planktivore_2column()
23362491
if cp.mission and cp.auv_name:
23372492
cp.gulper_odv()
23382493
if cp.log_file:

‎src/data/nc42netcdfs.py‎

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,15 @@
7777
{"name": "VolumeScatCoeff117deg700nm"},
7878
{"name": "mass_concentration_of_petroleum_hydrocarbons_in_sea_water"},
7979
],
80+
"_": [
81+
{"name": "planktivore_diatoms"},
82+
{"name": "planktivore_dinoflagellates"},
83+
{"name": "planktivore_caseTemp"},
84+
{"name": "planktivore_caseHumidity"},
85+
{"name": "planktivore_casePress"},
86+
{"name": "planktivore_HM_AvgRois"},
87+
{"name": "planktivore_LM_AvgRois"},
88+
],
8089
"WetLabsUBAT": [
8190
{"name": "average_bioluminescence"},
8291
{"name": "flow_rate"},
@@ -205,9 +214,12 @@ def extract_groups_to_files_netcdf4(self, log_file: str) -> Path:
205214

206215
# Extract all other groups
207216
all_groups = list(src_dataset.groups.keys())
217+
if "_" in all_groups:
218+
self._extract_backseat_group(log_file, src_dataset, netcdfs_dir)
219+
208220
for group_name in sorted(SCIENG_PARMS):
209-
if group_name == "/" or group_name not in all_groups:
210-
if group_name != "/" and group_name not in all_groups:
221+
if group_name in {"/", "_"} or group_name not in all_groups:
222+
if group_name not in {"/", "_"} and group_name not in all_groups:
211223
self.logger.warning("Group %s not found in %s", group_name, input_file)
212224
continue
213225
self._extract_single_group(log_file, group_name, src_dataset, netcdfs_dir)
@@ -243,6 +255,32 @@ def _extract_root_group(
243255
else:
244256
self.logger.warning("No requested variables found in root group '/'")
245257

258+
def _extract_backseat_group(
259+
self, log_file: str, src_dataset: netCDF4.Dataset, output_dir: Path
260+
):
261+
"""Extract variables from the '_' group to <stem>_{GROUP}_Backseat.nc."""
262+
backseat_parms = SCIENG_PARMS.get("_", [])
263+
if not backseat_parms:
264+
return
265+
266+
try:
267+
src_group = src_dataset.groups["_"]
268+
except KeyError:
269+
self.logger.warning("Backseat group '_' not found in %s", Path(log_file).name)
270+
return
271+
272+
self.logger.info("Extracting backseat group '_' as Backseat")
273+
vars_to_extract, requested_vars = self._get_available_variables(src_group, backseat_parms)
274+
275+
if vars_to_extract:
276+
output_file = output_dir / f"{Path(log_file).stem}_{GROUP}_Backseat.nc"
277+
self._create_netcdf_file(log_file, "Backseat", src_group, vars_to_extract, output_file)
278+
self.logger.info("Extracted backseat group '_' to %s", output_file)
279+
else:
280+
self.logger.warning(
281+
"No requested variables (%s) found in backseat group '_'", requested_vars
282+
)
283+
246284
def _extract_single_group(
247285
self,
248286
log_file: str,

‎src/data/process.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -700,6 +700,7 @@ def create_products(self, mission: str = None, log_file: str = None) -> None:
700700
cp.logger.addHandler(self.log_handler)
701701

702702
cp.plot_biolume_2column()
703+
cp.plot_planktivore_2column()
703704
cp.plot_2column()
704705
if mission and "dorado" in cp.auv_name.lower():
705706
cp.gulper_odv()

‎src/data/resample.py‎

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1987,10 +1987,14 @@ def resample_variable( # noqa: PLR0913
19871987
surface_exclusion_depth_m,
19881988
)
19891989
else:
1990-
self.df_o[variable] = self.ds[variable].to_pandas()
1991-
self.df_o[f"{variable}_mf"] = (
1990+
orig_series = self.ds[variable].to_pandas()
1991+
mf_series = (
19921992
self.ds[variable].rolling(**{timevar: mf_width}, center=True).median().to_pandas()
19931993
)
1994+
# Reset df_o per variable to avoid index alignment issues when
1995+
# variables within the same instrument have different time axes
1996+
# (e.g., Backseat group has diatoms at ~10s and case* at ~1s)
1997+
self.df_o = pd.DataFrame({variable: orig_series, f"{variable}_mf": mf_series})
19941998
# Resample to center of freq https://stackoverflow.com/a/69945592/1281657
19951999
self.logger.info(
19962000
"Resampling %s with frequency %s following %d point median filter",
@@ -2006,19 +2010,11 @@ def resample_variable( # noqa: PLR0913
20062010
)
20072011
dt_index = pd.date_range(mission_start, mission_end, freq=freq.lower())
20082012
self.df_r[variable] = pd.Series(np.nan, index=dt_index)
2009-
instr_data = (
2010-
self.df_o[f"{variable}_mf"]
2011-
.shift(0.5, freq=freq.lower())
2012-
.resample(freq.lower())
2013-
.mean()
2014-
)
2013+
instr_data = mf_series.shift(0.5, freq=freq.lower()).resample(freq.lower()).mean()
20152014
self.df_r.loc[instr_data.index, variable] = instr_data
20162015
else:
20172016
self.df_r[variable] = (
2018-
self.df_o[f"{variable}_mf"]
2019-
.shift(0.5, freq=freq.lower())
2020-
.resample(freq.lower())
2021-
.mean()
2017+
mf_series.shift(0.5, freq=freq.lower()).resample(freq.lower()).mean()
20222018
)
20232019
return ".mean() aggregator"
20242020

‎src/data/test_process_i2map.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def test_process_i2map(complete_i2map_processing):
3232
# update the expected size here.
3333
EXPECTED_SIZE_GITHUB = 63137
3434
EXPECTED_SIZE_ACT = 63106
35-
EXPECTED_SIZE_LOCAL = 64642
35+
EXPECTED_SIZE_LOCAL = 64650
3636
if str(proc.args.base_path).startswith("/home/runner"):
3737
# The size is different in GitHub Actions, maybe due to different metadata
3838
assert nc_file.stat().st_size == EXPECTED_SIZE_GITHUB # noqa: S101

0 commit comments

Comments
 (0)