Skip to content

Commit 55c7318

Browse files
committed
Linting
1 parent da40bd6 commit 55c7318

7 files changed

Lines changed: 105 additions & 53 deletions

File tree

oceanarray/mooring.py

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,34 +4,34 @@
44
import pandas as pd
55
from scipy.interpolate import interp1d
66

7+
78
def filter_all_time_vars(ds):
89
"""
910
Return a copy of ds with all data variables of length TIME lowpass filtered.
1011
"""
1112
# Get sampling rate from TIME (assume TIME is in seconds or has a uniform spacing)
12-
time = ds['TIME']
13-
dt = (time[1] - time[0]) / np.timedelta64(1, 's') # seconds
13+
time = ds["TIME"]
14+
dt = (time[1] - time[0]) / np.timedelta64(1, "s") # seconds
1415
sr = 1.0 / dt # Hz
1516

1617
# 2 day cutoff frequency in Hz
1718
co = 1.0 / (2 * 24 * 3600) # 2 days in seconds
1819

1920
ds_filt = ds.copy(deep=True)
2021
for var in ds.data_vars:
21-
if 'TIME' in ds[var].dims and ds[var].sizes['TIME'] == ds['TIME'].size:
22+
if "TIME" in ds[var].dims and ds[var].sizes["TIME"] == ds["TIME"].size:
2223
y = ds[var].values
23-
filtered = tools.auto_filt(y, sr, co, typ='low', fo=6)
24+
filtered = tools.auto_filt(y, sr, co, typ="low", fo=6)
2425
ds_filt[var].values = filtered
2526
return ds_filt
2627

2728

28-
2929
def get_12hourly_time_grid(
3030
time_or_ds,
31-
freq='12h',
31+
freq="12h",
3232
start_offset=pd.Timedelta(days=1),
3333
end_offset=pd.Timedelta(0),
34-
time_var='TIME'
34+
time_var="TIME",
3535
):
3636
"""
3737
Given a pandas.DatetimeIndex, array of datetimes, or xarray.Dataset,
@@ -63,40 +63,52 @@ def get_12hourly_time_grid(
6363
time = pd.to_datetime(time_or_ds)
6464
start = time[0]
6565
stop = time[-1]
66-
start_day = (start + start_offset).normalize() if start.time() != pd.Timestamp('00:00').time() else start.normalize()
66+
start_day = (
67+
(start + start_offset).normalize()
68+
if start.time() != pd.Timestamp("00:00").time()
69+
else start.normalize()
70+
)
6771
stop_day = (stop - end_offset).normalize()
6872
jd_grid = pd.date_range(start=start_day, end=stop_day, freq=freq)
6973
return jd_grid
7074

75+
7176
def interp_to_12hour_grid(ds1):
7277
jd_grid = get_12hourly_time_grid(ds1)
73-
time1 = ds1['TIME'].values
78+
time1 = ds1["TIME"].values
7479

75-
vars_to_interp = [v for v in ds1.data_vars if ds1[v].shape == ds1['TIME'].shape]
76-
for v in ['YY', 'MM', 'DD', 'HH']:
80+
vars_to_interp = [v for v in ds1.data_vars if ds1[v].shape == ds1["TIME"].shape]
81+
for v in ["YY", "MM", "DD", "HH"]:
7782
if v in vars_to_interp:
7883
vars_to_interp.remove(v)
7984

8085
interp_vars = {}
8186
for var in vars_to_interp:
82-
interp_func = interp1d(time1.astype('datetime64[s]').astype(float), ds1[var].values, bounds_error=False, fill_value='extrapolate')
83-
interp_vars[var] = interp_func(jd_grid.values.astype('datetime64[s]').astype(float))
87+
interp_func = interp1d(
88+
time1.astype("datetime64[s]").astype(float),
89+
ds1[var].values,
90+
bounds_error=False,
91+
fill_value="extrapolate",
92+
)
93+
interp_vars[var] = interp_func(
94+
jd_grid.values.astype("datetime64[s]").astype(float)
95+
)
8496

8597
ds_interp = xr.Dataset(
86-
{var: (['TIME'], interp_vars[var]) for var in interp_vars},
87-
coords={'TIME': jd_grid}
98+
{var: (["TIME"], interp_vars[var]) for var in interp_vars},
99+
coords={"TIME": jd_grid},
88100
)
89101
# Copy attributes from ds1
90102
ds_interp.attrs = ds1.attrs.copy()
91103

92104
# Add singleton variables (variables with no TIME dimension)
93105
for var in ds1.data_vars:
94-
if 'TIME' not in ds1[var].dims:
106+
if "TIME" not in ds1[var].dims:
95107
ds_interp[var] = ds1[var]
96108

97109
# Also copy over coordinates that are not 'TIME'
98110
for coord in ds1.coords:
99-
if coord != 'TIME' and coord not in ds_interp.coords:
111+
if coord != "TIME" and coord not in ds_interp.coords:
100112
ds_interp = ds_interp.assign_coords({coord: ds1[coord]})
101113

102114
return ds_interp

oceanarray/rodb.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,6 @@ def rodbload(filepath, variables: list[str] = None) -> xr.Dataset:
219219
}
220220

221221

222-
223222
def format_latlon(value, is_lat=True):
224223
deg = int(abs(value))
225224
minutes = (abs(value) - deg) * 60

oceanarray/tools.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import logging
22
import numpy as np
33
import xarray as xr
4-
import numpy as np
54
from scipy.signal import butter, filtfilt
65

76
# Initialize logging
@@ -42,7 +41,7 @@
4241
}
4342

4443

45-
def auto_filt(y, sr, co, typ='low', fo=6):
44+
def auto_filt(y, sr, co, typ="low", fo=6):
4645
"""
4746
Apply a Butterworth digital filter to a data array.
4847

tests/test_instrument.py

Lines changed: 36 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,24 @@
44
from datetime import datetime
55
from pathlib import Path
66

7-
from oceanarray.instrument import apply_microcat_calibration_from_txt, stage2_trim, trim_suggestion
8-
from oceanarray.instrument import apply_microcat_calibration_from_txt
7+
from oceanarray.instrument import (
8+
apply_microcat_calibration_from_txt,
9+
stage2_trim,
10+
trim_suggestion,
11+
)
912
from oceanarray.rodb import rodbload
1013

14+
1115
def test_trim_suggestion_basic():
1216
time = pd.date_range("2020-01-01", periods=10, freq="h")
13-
ds = xr.Dataset({
14-
"T": ("TIME", [0]*3 + [10]*4 + [0]*3),
15-
"C": ("TIME", [0]*3 + [12]*4 + [0]*3),
16-
"P": ("TIME", [0]*3 + [8]*4 + [0]*3),
17-
}, coords={"TIME": time})
17+
ds = xr.Dataset(
18+
{
19+
"T": ("TIME", [0] * 3 + [10] * 4 + [0] * 3),
20+
"C": ("TIME", [0] * 3 + [12] * 4 + [0] * 3),
21+
"P": ("TIME", [0] * 3 + [8] * 4 + [0] * 3),
22+
},
23+
coords={"TIME": time},
24+
)
1825

1926
start, end = trim_suggestion(ds, percent=80, threshold=5)
2027

@@ -36,31 +43,44 @@ def test_stage2_trim_single_sample():
3643

3744
def test_apply_microcat_with_flags(tmp_path):
3845
txt = tmp_path / "mock.microcat.txt"
39-
txt.write_text("""Conductivity: 1.0 2.0
46+
txt.write_text(
47+
"""Conductivity: 1.0 2.0
4048
Temperature: -0.5 0.5
4149
Pressure: 0.0 1.0
4250
Average conductivity applied? y
4351
Average temperature applied? y
4452
Average pressure applied? n
45-
""")
53+
"""
54+
)
4655

4756
# Create dummy .use file
4857
time = pd.date_range("2022-01-01", periods=3, freq="h")
49-
ds = xr.Dataset({"T": ("TIME", [10.0, 11.0, 12.0]),
50-
"C": ("TIME", [35.0, 35.1, 35.2]),
51-
"P": ("TIME", [1000.0, 1001.0, 1002.0])},
52-
coords={"TIME": time})
58+
ds = xr.Dataset(
59+
{
60+
"T": ("TIME", [10.0, 11.0, 12.0]),
61+
"C": ("TIME", [35.0, 35.1, 35.2]),
62+
"P": ("TIME", [1000.0, 1001.0, 1002.0]),
63+
},
64+
coords={"TIME": time},
65+
)
5366
use_path = tmp_path / "mock.use"
5467
ds.to_netcdf(use_path) # write as .nc, simulate reading in `rodbload`
5568

5669
# Patch rodbload to return this dataset
5770
from oceanarray import instrument
71+
5872
instrument.rodb.rodbload = lambda _: ds
5973

6074
ds_cal = apply_microcat_calibration_from_txt(txt, use_path)
61-
assert "T" in ds_cal and np.allclose(ds_cal["T"].values, [10.0 + 0.0, 11.0 + 0.0, 12.0 + 0.0], atol=1e-6)
62-
assert "C" in ds_cal and np.allclose(ds_cal["C"].values, [36.5, 36.6, 36.7], atol=1e-6)
63-
assert "P" in ds_cal and np.allclose(ds_cal["P"].values, [1000.0, 1001.0, 1002.0], atol=1e-6) # unchanged
75+
assert "T" in ds_cal and np.allclose(
76+
ds_cal["T"].values, [10.0 + 0.0, 11.0 + 0.0, 12.0 + 0.0], atol=1e-6
77+
)
78+
assert "C" in ds_cal and np.allclose(
79+
ds_cal["C"].values, [36.5, 36.6, 36.7], atol=1e-6
80+
)
81+
assert "P" in ds_cal and np.allclose(
82+
ds_cal["P"].values, [1000.0, 1001.0, 1002.0], atol=1e-6
83+
) # unchanged
6484

6585

6686
def test_apply_microcat_calibration_from_txt(tmp_path):

tests/test_mooring.py

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,28 @@
11
import numpy as np
22
import pandas as pd
33
import xarray as xr
4-
import pytest
5-
from oceanarray.mooring import get_12hourly_time_grid, filter_all_time_vars # Adjust import as needed
6-
from oceanarray import tools # Assuming auto_filt is defined here
4+
from oceanarray.mooring import (
5+
get_12hourly_time_grid,
6+
filter_all_time_vars,
7+
) # Adjust import as needed
8+
9+
from oceanarray.mooring import interp_to_12hour_grid
710

8-
from oceanarray.mooring import interp_to_12hour_grid, get_12hourly_time_grid
911

1012
def test_interp_to_12hour_grid():
1113
# Create a synthetic dataset
1214
time = pd.date_range("2020-01-01", periods=48, freq="h") # hourly for 2 days
1315
data = np.sin(np.linspace(0, 2 * np.pi, len(time))) # sinusoidal signal
14-
attrs = {'platform': 'testmoor'}
16+
attrs = {"platform": "testmoor"}
1517

1618
ds = xr.Dataset(
1719
{
1820
"T": ("TIME", data),
1921
"sal": ("TIME", data * 2),
20-
"const": ("DEPTH", [1.0, 2.0])
22+
"const": ("DEPTH", [1.0, 2.0]),
2123
},
2224
coords={"TIME": time, "DEPTH": [10, 20]},
23-
attrs=attrs
25+
attrs=attrs,
2426
)
2527

2628
# Run interpolation
@@ -46,13 +48,16 @@ def test_interp_to_12hour_grid():
4648
assert "DEPTH" in ds_interp.coords
4749
np.testing.assert_array_equal(ds_interp["DEPTH"], ds["DEPTH"])
4850

51+
4952
def test_filter_all_time_vars_lowpass_behavior():
5053
# Create a synthetic signal: high-frequency + low-frequency component
5154
time = pd.date_range("2020-01-01", periods=240, freq="h") # 10-day hourly record
5255
t_seconds = (time - time[0]).total_seconds().values
5356

5457
low_freq_signal = np.sin(2 * np.pi * t_seconds / (4 * 24 * 3600)) # 4-day period
55-
high_freq_noise = 0.5 * np.sin(2 * np.pi * t_seconds / (12 * 3600)) # 12-hour period
58+
high_freq_noise = 0.5 * np.sin(
59+
2 * np.pi * t_seconds / (12 * 3600)
60+
) # 12-hour period
5661
signal = low_freq_signal + high_freq_noise
5762

5863
ds = xr.Dataset(
@@ -88,7 +93,7 @@ def test_filter_all_time_vars_ignores_non_time_vars():
8893
"var1": ("TIME", np.sin(np.linspace(0, 10, 48))),
8994
"scalar": ((), 5.0),
9095
},
91-
coords={"TIME": time}
96+
coords={"TIME": time},
9297
)
9398

9499
ds_filtered = filter_all_time_vars(ds)
@@ -104,7 +109,9 @@ def test_get_12hourly_time_grid_with_array():
104109
expected_end = pd.Timestamp("2020-01-05T00:00")
105110
assert grid[0] == expected_start
106111
assert grid[-1] == expected_end
107-
assert (grid.freq == pd.tseries.frequencies.to_offset("12h")) or (grid.freqstr == "12h")
112+
assert (grid.freq == pd.tseries.frequencies.to_offset("12h")) or (
113+
grid.freqstr == "12h"
114+
)
108115

109116

110117
def test_get_12hourly_time_grid_with_dataset():
@@ -117,7 +124,9 @@ def test_get_12hourly_time_grid_with_dataset():
117124

118125
def test_get_12hourly_time_grid_custom_offset():
119126
times = pd.date_range("2023-07-01T00:00", "2023-07-03T23:59", freq="1h")
120-
grid = get_12hourly_time_grid(times, start_offset=pd.Timedelta(hours=0), end_offset=pd.Timedelta(days=1))
127+
grid = get_12hourly_time_grid(
128+
times, start_offset=pd.Timedelta(hours=0), end_offset=pd.Timedelta(days=1)
129+
)
121130
assert grid[0] == pd.Timestamp("2023-07-01T00:00")
122131
assert grid[-1] == pd.Timestamp("2023-07-02T00:00")
123132

tests/test_plotters.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,13 +61,16 @@ def test_plot_microcat_handles_time_format():
6161
assert isinstance(formatter, mdates.DateFormatter)
6262
assert formatter.fmt == "%Y.%b"
6363

64+
6465
def test_plot_trim_windows_creates_figaxes():
6566
import numpy as np
6667
import xarray as xr
6768
from oceanarray import plotters
6869
from datetime import datetime, timedelta
6970

70-
time = np.array([np.datetime64(datetime(2023, 1, 1) + timedelta(hours=i)) for i in range(48)])
71+
time = np.array(
72+
[np.datetime64(datetime(2023, 1, 1) + timedelta(hours=i)) for i in range(48)]
73+
)
7174
data = np.random.random(48)
7275
ds = xr.Dataset(
7376
{
@@ -84,6 +87,7 @@ def test_plot_trim_windows_creates_figaxes():
8487
assert fig is not None
8588
assert axes.shape == (3, 2)
8689

90+
8791
def test_plot_microcat_generates_expected_plot():
8892
import numpy as np
8993
import xarray as xr
@@ -105,6 +109,7 @@ def test_plot_microcat_generates_expected_plot():
105109
fig = plotters.plot_microcat(ds)
106110
assert fig is not None
107111

112+
108113
def test_show_variables_on_xarray_dataset():
109114
import numpy as np
110115
import xarray as xr
@@ -125,6 +130,7 @@ def test_show_variables_on_xarray_dataset():
125130
html = styled.to_html()
126131
assert "<table" in html # crude but effective confirmation
127132

133+
128134
def test_show_attributes_from_dataset():
129135
import xarray as xr
130136
from oceanarray import plotters

0 commit comments

Comments
 (0)