Skip to content

Commit 9465ceb

Browse files
committed
Make a separate _cbit.png page for the cbit_amphoursused plot.
1 parent 55fbf83 commit 9465ceb

3 files changed

Lines changed: 154 additions & 53 deletions

File tree

‎.vscode/launch.json‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -501,12 +501,12 @@
501501
//"args": ["--auv_name", "ahi", "--start", "20260303", "--end", "20260331", "-v", "2", "--clobber"]
502502
// Test a month with fewer plots to make
503503
//"args": ["--auv_name", "daphne", "--start", "20260101", "--end", "20260131", "-v", "2", "--clobber"]
504-
// Test pyxis
505-
//"args": ["--auv_name", "pyxis", "--start", "20260501", "--end", "20260531", "-v", "1", "--clobber"]
504+
// Test pyxis and cbit_amphoursused plot
505+
"args": ["--auv_name", "pyxis", "--start", "20260501", "--end", "20260531", "-v", "1", "--clobber"]
506506
// Test --current_month
507507
//"args": ["--current_month", "-v", "1"]
508508
// Test reading downwelling_photosynthetic_photon_flux_in_sea_water from the root group of the netCDF file instead of the instrument group, which was the case for some early daphne log files
509-
"args": ["--auv_name", "daphne", "--start", "20260501", "--end", "20260531", "-v", "1", "--clobber"]
509+
//"args": ["--auv_name", "daphne", "--start", "20260501", "--end", "20260531", "-v", "1", "--clobber"]
510510
},
511511
{
512512
"name": "lrauv_deployment_plots",

‎src/data/create_products.py‎

Lines changed: 149 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -613,7 +613,6 @@ def _get_planktivore_plot_variables(self) -> list:
613613

614614
def _get_lrauv_engineering_plot_variables(self) -> list:
615615
"""Get LRAUV engineering/platform variables for plot_engineering_2column()."""
616-
is_pyxis_realtime = self.auv_name == "pyxis" and self.mission and "realtime" in self.mission
617616
return [
618617
("bpc1_platform_battery_charge", "linear"),
619618
("bpc1_platform_battery_voltage", "linear"),
@@ -622,12 +621,7 @@ def _get_lrauv_engineering_plot_variables(self) -> list:
622621
("universals_platform_yaw_angle", "linear"),
623622
("universals_platform_roll_angle", "linear"),
624623
("buoyancyservo_platform_buoyancy_position", "linear"),
625-
(
626-
"cbit_amphoursused"
627-
if is_pyxis_realtime
628-
else "elevatorservo_platform_elevator_angle",
629-
"linear",
630-
),
624+
("elevatorservo_platform_elevator_angle", "linear"),
631625
("massservo_platform_mass_position", "linear"),
632626
]
633627

@@ -853,7 +847,12 @@ def sbd_png_paths(self) -> list[Path]:
853847
"""
854848
if not self.output_dir or not self.plot_name_stem:
855849
return []
856-
suffixes = ("_2column_cmocean", "_2column_planktivore", "_2column_engineering")
850+
suffixes = (
851+
"_2column_cmocean",
852+
"_2column_planktivore",
853+
"_2column_engineering",
854+
"_2column_cbit",
855+
)
857856
return [
858857
p
859858
for suffix in suffixes
@@ -1447,11 +1446,41 @@ def _overlay_sipper_on_map(self, map_ax: matplotlib.axes.Axes, transformer) -> N
14471446
)
14481447
first = False
14491448

1450-
def _plot_track_map( # noqa: PLR0915
1449+
def _section_overlays(self, distnav: xr.DataArray) -> tuple:
1450+
"""Return (profile_bottoms, bottom_depths) for section plots, None on error."""
1451+
try:
1452+
profile_bottoms = self._profile_bottoms(distnav)
1453+
except (TypeError, ValueError) as e:
1454+
self.logger.warning("Error computing profile bottoms: %s", e) # noqa: TRY400
1455+
profile_bottoms = None
1456+
try:
1457+
bottom_depths = self._get_bathymetry(
1458+
self.ds.cf["longitude"].to_numpy(),
1459+
self.ds.cf["latitude"].to_numpy(),
1460+
)
1461+
except ValueError as e: # noqa: BLE001
1462+
self.logger.warning("Error retrieving bathymetry: %s", e) # noqa: TRY400
1463+
bottom_depths = None
1464+
return profile_bottoms, bottom_depths
1465+
1466+
def _cumulative_profile_numbers(self) -> np.ndarray:
1467+
"""Return profile_number array that increments monotonically across log files."""
1468+
profile_numbers = self.ds["profile_number"].to_numpy()
1469+
result = profile_numbers.copy().astype(float)
1470+
offset = 0
1471+
for i in range(1, len(profile_numbers)):
1472+
if profile_numbers[i] < profile_numbers[i - 1]:
1473+
offset += profile_numbers[i - 1]
1474+
result[i] = profile_numbers[i] + offset
1475+
return result
1476+
1477+
def _plot_track_map( # noqa: PLR0915, PLR0913
14511478
self,
14521479
map_ax: matplotlib.axes.Axes,
14531480
reference_ax: matplotlib.axes.Axes,
14541481
night_ref_ax: matplotlib.axes.Axes | None = None,
1482+
color_data: np.ndarray | None = None,
1483+
color_label: str | None = None,
14551484
) -> None:
14561485
"""Plot AUV track map on left side with title and times on right.
14571486
@@ -1534,21 +1563,17 @@ def _plot_track_map( # noqa: PLR0915
15341563
# Make the plot square by using equal aspect with explicit box adjustment
15351564
map_ax.set_aspect("equal", adjustable="box")
15361565

1537-
# Plot the track colored by a cumulative profile number that keeps
1538-
# incrementing across concatenated log files (profile_number resets to
1539-
# zero at the start of each log file).
1540-
profile_numbers = self.ds["profile_number"].to_numpy()
1541-
cumulative_profile = profile_numbers.copy().astype(float)
1542-
offset = 0
1543-
for i in range(1, len(profile_numbers)):
1544-
if profile_numbers[i] < profile_numbers[i - 1]:
1545-
offset += profile_numbers[i - 1]
1546-
cumulative_profile[i] = profile_numbers[i] + offset
1566+
# Color the track by caller-supplied data when provided, otherwise by
1567+
# cumulative profile number (keeps incrementing across concatenated files).
1568+
if color_data is not None:
1569+
c_values, cmap_name = color_data, "hot_r"
1570+
else:
1571+
c_values, cmap_name = self._cumulative_profile_numbers(), "jet"
15471572
scatter = map_ax.scatter(
15481573
x_merc,
15491574
y_merc,
1550-
c=cumulative_profile,
1551-
cmap="jet",
1575+
c=c_values,
1576+
cmap=cmap_name,
15521577
s=1,
15531578
alpha=0.6,
15541579
)
@@ -1607,7 +1632,7 @@ def _plot_track_map( # noqa: PLR0915
16071632
cax=cbar_ax,
16081633
orientation="vertical",
16091634
)
1610-
cbar.set_label("Profile Number", fontsize=9)
1635+
cbar.set_label(color_label if color_label is not None else "Profile Number", fontsize=9)
16111636
cbar.ax.tick_params(labelsize=8)
16121637

16131638
# Remove axes, labels, and ticks but keep the border
@@ -2981,20 +3006,7 @@ def plot_planktivore_2column(self) -> str: # noqa: C901, PLR0912, PLR0915
29813006
self.logger.warning("Error retrieving sipper locations: %s", e) # noqa: TRY400
29823007
gulper_locations = {}
29833008

2984-
try:
2985-
profile_bottoms = self._profile_bottoms(distnav)
2986-
except (TypeError, ValueError) as e:
2987-
self.logger.warning("Error computing profile bottoms: %s", e) # noqa: TRY400
2988-
profile_bottoms = None
2989-
2990-
try:
2991-
bottom_depths = self._get_bathymetry(
2992-
self.ds.cf["longitude"].to_numpy(),
2993-
self.ds.cf["latitude"].to_numpy(),
2994-
)
2995-
except ValueError as e: # noqa: BLE001
2996-
self.logger.warning("Error retrieving bathymetry: %s", e) # noqa: TRY400
2997-
bottom_depths = None
3009+
profile_bottoms, bottom_depths = self._section_overlays(distnav)
29983010

29993011
row = 1
30003012
col = 0
@@ -3105,20 +3117,7 @@ def plot_engineering_2column(self) -> str: # noqa: C901, PLR0912, PLR0915
31053117

31063118
self._plot_track_map(ax[0, 0], ax[1, 0], ax[0, 1])
31073119

3108-
try:
3109-
profile_bottoms = self._profile_bottoms(distnav)
3110-
except (TypeError, ValueError) as e:
3111-
self.logger.warning("Error computing profile bottoms: %s", e) # noqa: TRY400
3112-
profile_bottoms = None
3113-
3114-
try:
3115-
bottom_depths = self._get_bathymetry(
3116-
self.ds.cf["longitude"].to_numpy(),
3117-
self.ds.cf["latitude"].to_numpy(),
3118-
)
3119-
except ValueError as e: # noqa: BLE001
3120-
self.logger.warning("Error retrieving bathymetry: %s", e) # noqa: TRY400
3121-
bottom_depths = None
3120+
profile_bottoms, bottom_depths = self._section_overlays(distnav)
31223121

31233122
row = 1
31243123
col = 0
@@ -3182,6 +3181,106 @@ def plot_engineering_2column(self) -> str: # noqa: C901, PLR0912, PLR0915
31823181
self.logger.info("Saved engineering 2column plot to %s", output_file)
31833182
return str(output_file)
31843183

3184+
def plot_cbit_2column(self) -> str:
3185+
"""Create a 3-panel plot for cbit_amphoursused: track map, distance scatter, time series."""
3186+
_CBIT_VAR = "cbit_amphoursused"
3187+
3188+
if "pytest" in sys.modules:
3189+
return None
3190+
if not self._is_lrauv():
3191+
return None
3192+
3193+
self._open_ds()
3194+
3195+
if _CBIT_VAR not in self.ds:
3196+
self.logger.debug("%s not in dataset, skipping plot_cbit_2column", _CBIT_VAR)
3197+
return None
3198+
3199+
cbit = self.ds[_CBIT_VAR].dropna("time")
3200+
if cbit.size == 0:
3201+
self.logger.debug("No valid %s data, skipping plot_cbit_2column", _CBIT_VAR)
3202+
return None
3203+
3204+
idist, iz, distnav = self._grid_dims([_CBIT_VAR])
3205+
if distnav.size == 0:
3206+
self.logger.warning("Skipping plot_cbit_2column due to missing distnav")
3207+
return None
3208+
3209+
units = self.ds[_CBIT_VAR].attrs.get("units", "Ah")
3210+
ylabel = f"Amp-hours Used ({units})"
3211+
3212+
cbit_at_nav = cbit.interp(time=distnav.coords["time"], method="linear").to_numpy()
3213+
times = pd.to_datetime(cbit.coords["time"].to_numpy())
3214+
cbit_vals = cbit.to_numpy()
3215+
3216+
fig = plt.figure(figsize=(18, 8))
3217+
gs = matplotlib.gridspec.GridSpec(2, 2, figure=fig, hspace=0.35, wspace=0.15)
3218+
ax_map = fig.add_subplot(gs[0, 0])
3219+
ax_section = fig.add_subplot(gs[0, 1])
3220+
ax_time = fig.add_subplot(gs[1, :])
3221+
3222+
# Track map colored by Ah Used
3223+
self._plot_track_map(
3224+
ax_map,
3225+
ax_time,
3226+
ax_section,
3227+
color_data=cbit_at_nav,
3228+
color_label=ylabel,
3229+
)
3230+
3231+
# Depth-vs-distance section colored by Ah Used (same style as other plot pages)
3232+
profile_bottoms, bottom_depths = self._section_overlays(distnav)
3233+
3234+
ax_array = np.array([[ax_map, ax_section]])
3235+
self._plot_var(
3236+
_CBIT_VAR,
3237+
idist,
3238+
iz,
3239+
distnav,
3240+
fig,
3241+
ax_array,
3242+
0,
3243+
1,
3244+
profile_bottoms,
3245+
scale="linear",
3246+
gulper_locations={},
3247+
bottom_depths=bottom_depths,
3248+
best_ctd=None,
3249+
)
3250+
ax_section.set_xlabel("Distance along track (km)")
3251+
3252+
# Time series
3253+
ax_time.plot(times, cbit_vals, color="tab:red", linewidth=1)
3254+
ax_time.set_xlabel("Time (UTC)")
3255+
ax_time.set_ylabel(ylabel)
3256+
ax_time.set_title("Ah Used vs. Time")
3257+
ax_time.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y-%m-%d\n%H:%M"))
3258+
plt.setp(ax_time.get_xticklabels(), rotation=0, ha="center", fontsize=8)
3259+
3260+
out_dir = (
3261+
self.output_dir
3262+
if self.output_dir is not None
3263+
else Path(BASE_LRAUV_PATH, f"{Path(self.log_file).parent}")
3264+
)
3265+
out_dir.mkdir(parents=True, exist_ok=True)
3266+
stem = self.plot_name_stem if self.plot_name_stem is not None else Path(self.log_file).stem
3267+
output_file = Path(out_dir, f"{stem}_{self.freq}_2column_cbit.png")
3268+
created = datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S %Z")
3269+
fig.text(
3270+
0,
3271+
0,
3272+
f"Created by auv-python's create_products.py on {created}.",
3273+
fontsize=6,
3274+
fontstyle="italic",
3275+
ha="left",
3276+
va="bottom",
3277+
)
3278+
plt.savefig(output_file, dpi=100, bbox_inches="tight")
3279+
plt.close(fig)
3280+
3281+
self.logger.info("Saved cbit 2column plot to %s", output_file)
3282+
return str(output_file)
3283+
31853284
def _get_best_ctd(self) -> str:
31863285
"""Determine best CTD to use for ODV lookup table based on metadata"""
31873286
# LRAUV doesn't use multiple CTDs, return None

‎src/data/process_lrauv_sbd.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,7 @@ def _make_per_log_plots(
215215
cp.plot_2column()
216216
cp.plot_planktivore_2column()
217217
cp.plot_engineering_2column()
218+
cp.plot_cbit_2column()
218219
except Exception as e: # noqa: BLE001
219220
logger.warning("Per-log plot failed for %s: %s", p.name, e)
220221

@@ -266,6 +267,7 @@ def _make_products(
266267
cp.plot_2column()
267268
cp.plot_planktivore_2column()
268269
cp.plot_engineering_2column()
270+
cp.plot_cbit_2column()
269271

270272
png_paths = cp.sbd_png_paths()
271273
if png_paths:

0 commit comments

Comments
 (0)