Skip to content

Commit 4736b20

Browse files
committed
add summarize option
1 parent 4cb43e4 commit 4736b20

3 files changed

Lines changed: 104 additions & 93 deletions

File tree

oceanval/data/variable_summary_template.ipynb

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@
117117
},
118118
"outputs": [],
119119
"source": [
120-
"data_dir = \"/data/proteus1/scratch/rwi/oceanval_testing/oceanval_summaries/data\"\n"
120+
"data_dir = \"../../../oceanval_summaries/data\""
121121
]
122122
},
123123
{
@@ -132,7 +132,12 @@
132132
"outputs": [],
133133
"source": [
134134
"data_paths = nc.glob(f\"{data_dir}/{variable}/\")\n",
135-
"i_fig = 1"
135+
"i_fig = 1\n",
136+
"ff = f\"{data_dir}/{variable}/summaries_config.pkl\"\n",
137+
"with open(ff, \"rb\") as f:\n",
138+
" summaries = pickle.load(f)\n",
139+
"clim_period = f\"{summaries[variable].climatology_years[0]}-{summaries[variable].climatology_years[1]}\"\n",
140+
"robust = summaries[variable].robust"
136141
]
137142
},
138143
{
@@ -150,7 +155,7 @@
150155
"if len(surface_clim) > 0:\n",
151156
" md(f\"## Sea surface climatology of {variable}\") \n",
152157
" ds = nc.open_data(surface_clim[0], checks = False) \n",
153-
" ds.pub_plot(robust = True)\n"
158+
" ds.pub_plot(robust = robust)\n"
154159
]
155160
},
156161
{
@@ -165,7 +170,7 @@
165170
"outputs": [],
166171
"source": [
167172
"if len(surface_clim) > 0:\n",
168-
" md(f\"**Figure {i_fig}**: Sea surface climatology of {variable}.\")\n",
173+
" md(f\"**Figure {i_fig}**: Sea surface climatology of {variable} ({clim_period}).\")\n",
169174
" i_fig += 1"
170175
]
171176
},
@@ -184,7 +189,7 @@
184189
"if len(verticalmean_clim) > 0:\n",
185190
" md(f\"## Vertical mean climatology of {variable}\") \n",
186191
" ds = nc.open_data(verticalmean_clim[0], checks = False) \n",
187-
" ds.pub_plot(robust = True)"
192+
" ds.pub_plot(robust = robust)"
188193
]
189194
},
190195
{
@@ -198,8 +203,9 @@
198203
},
199204
"outputs": [],
200205
"source": [
201-
"md(f\"**Figure {i_fig}**: Climatoloy of vertical average {variable}.\")\n",
202-
"i_fig += 1"
206+
"if len(verticalmean_clim) > 0:\n",
207+
" md(f\"**Figure {i_fig}**: Climatology of vertical average {variable} ({clim_period}).\")\n",
208+
" i_fig += 1"
203209
]
204210
},
205211
{
@@ -215,9 +221,9 @@
215221
"source": [
216222
"verticalintegrated_clim = [x for x in data_paths if \"verticalintegrated_climatology\" in x]\n",
217223
"if len(verticalintegrated_clim) > 0:\n",
218-
" md(f\"## Vertical integrated climatology of {variable}\") \n",
224+
" md(f\"## Vertical integrated climatology of {variable}\")\n",
219225
" ds = nc.open_data(verticalintegrated_clim[0], checks = False) \n",
220-
" ds.pub_plot(robust = True)\n",
226+
" ds.pub_plot(robust = robust)\n",
221227
" "
222228
]
223229
},
@@ -233,7 +239,7 @@
233239
"outputs": [],
234240
"source": [
235241
"if len(verticalintegrated_clim) > 0:\n",
236-
" md(f\"**Figure {i_fig}**: Climatology of vertical integrated {variable}.\")\n",
242+
" md(f\"**Figure {i_fig}**: Climatology of vertical integrated {variable} ({clim_period}).\")\n",
237243
" i_fig += 1"
238244
]
239245
},

oceanval/parsers.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -922,10 +922,11 @@ def add_summary(
922922
model_variable=None,
923923
long_name=None,
924924
short_name=None,
925-
trends = {"period":[-1E9, 1E9], "window":1},
925+
trends = None,
926926
vertical_integration=False,
927927
vertical_mean =False,
928-
climatology_years = None
928+
climatology_years = None,
929+
robust = False
929930
):
930931
"""
931932
Add a variable to be summarized from model output.
@@ -948,6 +949,8 @@ def add_summary(
948949
Whether to vertically integrate the variable.
949950
vertical_mean : bool, default False
950951
Whether to vertically average the variable.
952+
robust : bool, default False
953+
Whether to use a robust plot for climatologies
951954
952955
Returns
953956
-------
@@ -990,6 +993,9 @@ def add_summary(
990993
except (TypeError, ValueError) as e:
991994
raise ValueError("climatology_years values must be integers")
992995

996+
# check robust is boolean
997+
if not isinstance(robust, bool):
998+
raise ValueError("robust must be a boolean value")
993999

9941000
# Validate required parameters
9951001
if name is None:
@@ -1003,10 +1009,11 @@ def add_summary(
10031009
raise ValueError("Model variable must be provided")
10041010

10051011
# check trends is a dict with period and window
1006-
if not isinstance(trends, dict):
1007-
raise ValueError("trends must be a dictionary with keys 'period' and 'window'")
1008-
if "period" not in trends or "window" not in trends:
1009-
raise ValueError("trends dictionary must contain 'period' and 'window' keys")
1012+
if trends is not None:
1013+
if not isinstance(trends, dict):
1014+
raise ValueError("trends must be a dictionary with keys 'period' and 'window'")
1015+
if "period" not in trends or "window" not in trends:
1016+
raise ValueError("trends dictionary must contain 'period' and 'window' keys")
10101017

10111018
# Create variable if it doesn't exist, or get existing one
10121019
if getattr(self, name, None) is None:
@@ -1016,6 +1023,7 @@ def add_summary(
10161023
var = self[name]
10171024

10181025
var.trends = trends
1026+
var.robust = robust
10191027
# Set attributes
10201028
var.name = name
10211029
var.start = start

oceanval/summarize.py

Lines changed: 74 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -619,93 +619,94 @@ def summarize(
619619
continue
620620

621621
# Open and process the data
622-
try:
623-
ds = nc.open_data(all_files, checks=False)
622+
ds = nc.open_data(all_files, checks=False)
624623

625-
# Check if variable exists
626-
if model_var not in ds.variables:
627-
print(f" Warning: Variable {model_var} not found in files")
628-
continue
624+
# Check if variable exists
625+
if model_var not in ds.variables:
626+
print(f" Warning: Variable {model_var} not found in files")
627+
continue
629628

630-
# Subset to variable of interest
631-
ds.subset(variables=model_var)
629+
# Subset to variable of interest
630+
ds.subset(variables=model_var)
632631

633-
# Apply time range
632+
# Apply time range
634633

635-
# Apply spatial subsetting
636-
if lon_lim is not None and lat_lim is not None:
637-
ds.subset(lon=lon_lim, lat=lat_lim)
634+
# Apply spatial subsetting
635+
if lon_lim is not None and lat_lim is not None:
636+
ds.subset(lon=lon_lim, lat=lat_lim)
638637

639-
# Handle missing values
640-
if as_missing is not None:
641-
ds.as_missing(as_missing)
638+
# Handle missing values
639+
if as_missing is not None:
640+
ds.as_missing(as_missing)
642641

643-
# Apply depth range if specified
644-
ds.merge("time")
645-
ds.tmean("year")
646-
ds.run()
647-
648-
# now do the climatology
649-
clim_years = summaries[var_name].climatology_years
650-
ds_clim = ds.copy()
651-
ds_clim.subset(years=range(clim_years[0], clim_years[1] + 1))
652-
ds_clim.top()
653-
ds_clim.tmean()
642+
# Apply depth range if specified
643+
ds.merge("time")
644+
ds.tmean("year")
645+
ds.run()
646+
647+
# now do the climatology
648+
clim_years = summaries[var_name].climatology_years
649+
ds_clim = ds.copy()
650+
ds_clim.subset(years=range(clim_years[0], clim_years[1] + 1))
651+
ds_clim.top()
652+
ds_clim.tmean()
654653

655-
# Prepare output filename
656-
out_file = f"{summary_dir}/data/{var_name}/{var_name}_surface_climatology.nc"
657-
os.makedirs(os.path.dirname(out_file), exist_ok=True)
654+
# Prepare output filename
655+
out_file = f"{summary_dir}/data/{var_name}/{var_name}_surface_climatology.nc"
656+
os.makedirs(os.path.dirname(out_file), exist_ok=True)
658657

659-
# Check if we should overwrite
660-
if os.path.exists(out_file) and not overwrite:
661-
print(f" File exists and overwrite=False, skipping: {out_file}")
662-
continue
658+
# Check if we should overwrite
659+
if os.path.exists(out_file) and not overwrite:
660+
print(f" File exists and overwrite=False, skipping: {out_file}")
661+
continue
663662

664-
# Save the result
665-
# delete if it iexists
663+
# Save the result
664+
# delete if it iexists
665+
if os.path.exists(out_file):
666+
os.remove(out_file)
667+
ds_clim.to_nc(out_file, overwrite=True, zip=True)
668+
print(f" Saved: {out_file}")
669+
trend_info = summaries[var_name].trends
670+
trends = trend_info is not None
671+
# now figure out if vertical mean is neeed
672+
if summaries[var_name].vertical_mean:
673+
ds_vertmean = ds.copy()
674+
ds_vertmean.subset(years=clim_years)
675+
ds_vertmean.tmean()
676+
thickness = session_info["ds_thickness"]
677+
if thickness is None:
678+
ds_vertmean.vertical_mean(fixed = True)
679+
else:
680+
ds_vertmean.vertical_mean(thickness = ds_cell_thickness)
681+
# climatological years
682+
out_file = f"{summary_dir}/data/{var_name}/{var_name}_verticalmean_climatology.nc"
683+
os.makedirs(os.path.dirname(out_file), exist_ok=True)
666684
if os.path.exists(out_file):
667685
os.remove(out_file)
668-
ds_clim.to_nc(out_file, overwrite=True, zip=True)
686+
ds_vertmean.to_nc(out_file, overwrite=True, zip=True)
669687
print(f" Saved: {out_file}")
670-
# now figure out if vertical mean is neeed
671-
if summaries[var_name].vertical_mean:
672-
ds_vertmean = ds.copy()
673-
ds_vertmean.subset(years=clim_years)
674-
ds_vertmean.tmean()
675-
thickness = session_info["ds_thickness"]
676-
if thickness is None:
677-
ds_vertmean.vertical_mean(fixed = True)
678-
else:
679-
ds_vertmean.vertical_mean(thickness = ds_cell_thickness)
680-
# climatological years
681-
out_file = f"{summary_dir}/data/{var_name}/{var_name}_verticalmean_climatology.nc"
682-
os.makedirs(os.path.dirname(out_file), exist_ok=True)
683-
if os.path.exists(out_file):
684-
os.remove(out_file)
685-
ds_vertmean.to_nc(out_file, overwrite=True, zip=True)
686-
print(f" Saved: {out_file}")
687688

688-
# now do vertical integration if needed
689-
if summaries[var_name].vertical_integration:
690-
ds_vertint = ds.copy()
691-
ds_vertint.subset(years=clim_years)
692-
ds_vertint.tmean()
693-
thickness = session_info["ds_thickness"]
694-
if thickness is None:
695-
ds_vertint.vertical_integration(fixed = True)
696-
else:
697-
ds_vertint.vertical_integration(thickness = ds_cell_thickness)
698-
# climatological years
699-
out_file = f"{summary_dir}/data/{var_name}/{var_name}_verticalintegrated_climatology.nc"
700-
os.makedirs(os.path.dirname(out_file), exist_ok=True)
701-
if os.path.exists(out_file):
702-
os.remove(out_file)
703-
ds_vertint.to_nc(out_file, overwrite=True, zip=True)
704-
print(f" Saved: {out_file}")
689+
# now do vertical integration if needed
690+
if summaries[var_name].vertical_integration:
691+
ds_vertint = ds.copy()
692+
ds_vertint.subset(years=clim_years)
693+
ds_vertint.tmean()
694+
thickness = session_info["ds_thickness"]
695+
if thickness is None:
696+
ds_vertint.vertical_integration(fixed = True)
697+
else:
698+
ds_vertint.vertical_integration(thickness = ds_cell_thickness)
699+
# climatological years
700+
out_file = f"{summary_dir}/data/{var_name}/{var_name}_verticalintegrated_climatology.nc"
701+
os.makedirs(os.path.dirname(out_file), exist_ok=True)
702+
if os.path.exists(out_file):
703+
os.remove(out_file)
704+
ds_vertint.to_nc(out_file, overwrite=True, zip=True)
705+
print(f" Saved: {out_file}")
705706

706-
# now do the spatial mean timeseries
707+
# now do the spatial mean timeseries
708+
if trends:
707709
ds_trends = ds.copy()
708-
trend_info = summaries[var_name].trends
709710
period = trend_info["period"]
710711
ds_trends.subset(years = range(period[0], period[1] + 1))
711712
window = trend_info["window"]
@@ -715,7 +716,6 @@ def summarize(
715716
ds_trends.vertical_integration(fixed = True)
716717
else:
717718
ds_trends.vertical_integration(thickness = ds_cell_thickness)
718-
ds_trends.fix_amm7_grid()
719719
ds_trends.spatial_sum(by_area = True)
720720
out_file = f"{summary_dir}/data/{var_name}/{var_name}_verticalintegrated_spatialsumtimeseries.nc"
721721
os.makedirs(os.path.dirname(out_file), exist_ok = True)
@@ -724,6 +724,7 @@ def summarize(
724724

725725
ds_trends.to_nc(out_file, overwrite=True, zip=True)
726726

727+
if trends:
727728
ds_trends = ds.copy()
728729
ds_trends.top()
729730
ds_trends.spatial_mean()
@@ -743,10 +744,6 @@ def summarize(
743744
ds_trends.to_nc(out_file, overwrite=True, zip=True)
744745

745746

746-
except Exception as e:
747-
print(f" Error processing {var_name}: {str(e)}")
748-
warnings.warn(f"Failed to process {var_name}: {str(e)}")
749-
continue
750747

751748
# Save summaries configuration
752749
config_file = os.path.join(f"{summary_dir}/data/{var_name}", "summaries_config.pkl")

0 commit comments

Comments
 (0)