Skip to content

Commit fb8550e

Browse files
authored
Merge pull request #3408 from samsrabin/gddgen-log-changes
Logging improvements for GDD-generation workflow
2 parents b779f98 + ac5899b commit fb8550e

File tree

9 files changed

+234
-52
lines changed

9 files changed

+234
-52
lines changed

.git-blame-ignore-revs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,5 @@ cdf40d265cc82775607a1bf25f5f527bacc97405
7070
4ad46f46de7dde753b4653c15f05326f55116b73
7171
75db098206b064b8b7b2a0604d3f0bf8fdb950cc
7272
84609494b54ea9732f64add43b2f1dd035632b4c
73+
ac03492012837799b7111607188acff9f739044a
74+
d858665d799690d73b56bcb961684382551193f4

python/ctsm/crop_calendars/cropcal_module.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from ctsm.crop_calendars.cropcal_constants import DEFAULT_GDD_MIN
1414
from ctsm.crop_calendars.import_ds import import_ds
1515
from ctsm.utils import is_instantaneous
16+
from ctsm.ctsm_logging import log
1617

1718
MISSING_RX_GDD_VAL = -1
1819

@@ -49,11 +50,12 @@ def check_and_trim_years(year_1, year_n, ds_in):
4950
return ds_in
5051

5152

52-
def open_lu_ds(filename, year_1, year_n, existing_ds, ungrid=True):
53+
def open_lu_ds(filename, year_1, year_n, existing_ds, *, logger, ungrid=True):
5354
"""
5455
Open land-use dataset
5556
"""
5657
# Open and trim to years of interest
58+
log(logger, f"Opening this_ds_gridded: {filename}")
5759
this_ds_gridded = xr.open_dataset(filename).sel(time=slice(year_1, year_n))
5860

5961
# Assign actual lon/lat coordinates
@@ -347,14 +349,15 @@ def import_output(
347349
gdds_rx_ds=None,
348350
verbose=False,
349351
throw_errors=True,
352+
logger=None,
350353
):
351354
"""
352355
Import CLM output
353356
"""
354357
any_bad = False
355358

356359
# Import
357-
this_ds = import_ds(filename, my_vars=my_vars, my_vegtypes=my_vegtypes)
360+
this_ds = import_ds(filename, my_vars=my_vars, my_vegtypes=my_vegtypes, logger=logger)
358361

359362
# Trim to years of interest (do not include extra year needed for finishing last growing season)
360363
if year_1 and year_n:

python/ctsm/crop_calendars/generate_gdds.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir, os.pardir, "python"
1919
)
2020
sys.path.insert(1, _CTSM_PYTHON)
21+
from ctsm.ctsm_logging import log, error # pylint: disable=wrong-import-position
2122
import ctsm.crop_calendars.cropcal_module as cc # pylint: disable=wrong-import-position
2223
import ctsm.crop_calendars.generate_gdds_functions as gddfn # pylint: disable=wrong-import-position
2324

@@ -85,11 +86,11 @@ def main(
8586
raise RuntimeError(
8687
"only_make_figs True but not all plotting modules are available"
8788
) from exc
88-
gddfn.log(logger, "Not all plotting modules are available; disabling save_figs")
89+
log(logger, "Not all plotting modules are available; disabling save_figs")
8990
save_figs = False
9091

9192
# Print some info
92-
gddfn.log(logger, f"Saving to {output_dir}")
93+
log(logger, f"Saving to {output_dir}")
9394

9495
# Parse list of crops to skip
9596
if "," in skip_crops:
@@ -107,7 +108,7 @@ def main(
107108
yr_1_import_str = f"{first_season+1}-01-01"
108109
yr_n_import_str = f"{last_season+2}-01-01"
109110

110-
gddfn.log(
111+
log(
111112
logger,
112113
f"Importing netCDF time steps {yr_1_import_str} through {yr_n_import_str} "
113114
+ "(years are +1 because of CTSM output naming)",
@@ -191,7 +192,7 @@ def main(
191192
h1_instantaneous,
192193
)
193194

194-
gddfn.log(logger, f" Saving pickle file ({pickle_file})...")
195+
log(logger, f" Saving pickle file ({pickle_file})...")
195196
with open(pickle_file, "wb") as file:
196197
pickle.dump(
197198
[
@@ -219,9 +220,10 @@ def main(
219220
[i for i, c in enumerate(gddaccum_yp_list) if not isinstance(c, type(None))]
220221
]
221222

222-
gddfn.log(logger, "Done")
223+
log(logger, "Done")
223224

224225
if not h2_ds:
226+
log(logger, f"Opening h2_ds: {h2_ds_file}")
225227
h2_ds = xr.open_dataset(h2_ds_file)
226228

227229
######################################################
@@ -236,7 +238,7 @@ def main(
236238
"s", sdates_rx, incl_patches1d_itype_veg, mxsowings, logger
237239
)
238240

239-
gddfn.log(logger, "Getting and gridding mean GDDs...")
241+
log(logger, "Getting and gridding mean GDDs...")
240242
gdd_maps_ds = gddfn.yp_list_to_ds(
241243
gddaccum_yp_list, h2_ds, incl_vegtypes_str, sdates_rx, longname_prefix, logger
242244
)
@@ -247,10 +249,10 @@ def main(
247249
# Fill NAs with dummy values
248250
dummy_fill = -1
249251
gdd_maps_ds = gdd_maps_ds.fillna(dummy_fill)
250-
gddfn.log(logger, "Done getting and gridding means.")
252+
log(logger, "Done getting and gridding means.")
251253

252254
# Add dummy variables for crops not actually simulated
253-
gddfn.log(logger, "Adding dummy variables...")
255+
log(logger, "Adding dummy variables...")
254256
# Unnecessary?
255257
template_ds = xr.open_dataset(sdates_file, decode_times=True)
256258
all_vars = [v.replace("sdate", "gdd") for v in template_ds if "sdate" in v]
@@ -278,9 +280,7 @@ def make_dummy(this_crop_gridded, addend):
278280

279281
for var_index, this_var in enumerate(dummy_vars):
280282
if this_var in gdd_maps_ds:
281-
gddfn.error(
282-
logger, f"{this_var} is already in gdd_maps_ds. Why overwrite it with dummy?"
283-
)
283+
error(logger, f"{this_var} is already in gdd_maps_ds. Why overwrite it with dummy?")
284284
dummy_gridded.name = this_var
285285
dummy_gridded.attrs["long_name"] = dummy_longnames[var_index]
286286
gdd_maps_ds[this_var] = dummy_gridded
@@ -294,14 +294,14 @@ def add_lonlat_attrs(this_ds):
294294
gdd_maps_ds = add_lonlat_attrs(gdd_maps_ds)
295295
gddharv_maps_ds = add_lonlat_attrs(gddharv_maps_ds)
296296

297-
gddfn.log(logger, "Done.")
297+
log(logger, "Done.")
298298

299299
######################
300300
### Save to netCDF ###
301301
######################
302302

303303
if not only_make_figs:
304-
gddfn.log(logger, "Saving...")
304+
log(logger, "Saving...")
305305

306306
# Get output file path
307307
datestr = dt.datetime.now().strftime("%Y%m%d_%H%M%S")
@@ -336,7 +336,7 @@ def save_gdds(sdates_file, hdates_file, outfile, gdd_maps_ds, sdates_rx):
336336

337337
save_gdds(sdates_file, hdates_file, outfile, gdd_maps_ds, sdates_rx)
338338

339-
gddfn.log(logger, "Done saving.")
339+
log(logger, "Done saving.")
340340

341341
########################################
342342
### Save things needed for mapmaking ###

python/ctsm/crop_calendars/generate_gdds_functions.py

Lines changed: 8 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@
66
import warnings
77
import os
88
import glob
9-
import datetime as dt
109
from importlib import util as importlib_util
1110
import numpy as np
1211
import xarray as xr
1312

1413
from ctsm.utils import is_instantaneous
14+
from ctsm.ctsm_logging import log, error
1515
import ctsm.crop_calendars.cropcal_utils as utils
1616
import ctsm.crop_calendars.cropcal_module as cc
1717
from ctsm.crop_calendars.xr_flexsel import xr_flexsel
@@ -54,23 +54,6 @@
5454
CAN_PLOT = False
5555

5656

57-
def log(logger, string):
58-
"""
59-
Simultaneously print INFO messages to console and to log file
60-
"""
61-
print(string)
62-
logger.info(string)
63-
64-
65-
def error(logger, string):
66-
"""
67-
Simultaneously print ERROR messages to console and to log file
68-
"""
69-
print(string)
70-
logger.error(string)
71-
raise RuntimeError(string)
72-
73-
7457
def check_sdates(dates_ds, sdates_rx, outdir_figs, logger, verbose=False):
7558
"""
7659
Checking that input and output sdates match
@@ -271,7 +254,6 @@ def import_and_process_1yr(
271254
"""
272255
save_figs = True
273256
log(logger, f"netCDF year {this_year}...")
274-
log(logger, dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
275257

276258
# Without dask, this can take a LONG time at resolutions finer than 2-deg
277259
if importlib_util.find_spec("dask"):
@@ -308,6 +290,7 @@ def import_and_process_1yr(
308290
my_vegtypes=crops_to_read,
309291
time_slice=slice(f"{slice_year}-01-01", f"{slice_year}-12-31"),
310292
chunks=chunks,
293+
logger=logger,
311294
)
312295
for timestep in dates_ds["time"].values:
313296
print(timestep)
@@ -579,6 +562,7 @@ def import_and_process_1yr(
579562
my_vars=my_vars,
580563
my_vegtypes=crops_to_read,
581564
chunks=chunks,
565+
logger=logger,
582566
)
583567

584568
# Restrict to patches we're including
@@ -604,7 +588,7 @@ def import_and_process_1yr(
604588
incl_vegtype_indices = []
605589
for var, vegtype_str in enumerate(incl_vegtypes_str):
606590
if vegtype_str in skip_crops:
607-
log(logger, f" SKIPPING {vegtype_str}")
591+
log(logger, f"SKIPPING {vegtype_str}")
608592
continue
609593

610594
vegtype_int = utils.vegtype_str2int(vegtype_str)[0]
@@ -619,7 +603,7 @@ def import_and_process_1yr(
619603
check_gddharv = True
620604
if not this_crop_gddaccum_da.size:
621605
continue
622-
log(logger, f" {vegtype_str}...")
606+
log(logger, f"{vegtype_str}...")
623607
incl_vegtype_indices = incl_vegtype_indices + [var]
624608

625609
# Get prescribed harvest dates for these patches
@@ -1116,7 +1100,9 @@ def make_figures(
11161100
if land_use_file:
11171101
year_1_lu = year_1 if first_land_use_year is None else first_land_use_year
11181102
year_n_lu = year_n if last_land_use_year is None else last_land_use_year
1119-
lu_ds = cc.open_lu_ds(land_use_file, year_1_lu, year_n_lu, gdd_maps_ds, ungrid=False)
1103+
lu_ds = cc.open_lu_ds(
1104+
land_use_file, year_1_lu, year_n_lu, gdd_maps_ds, logger=logger, ungrid=False
1105+
)
11201106
lu_years_text = f" (masked by {year_1_lu}-{year_n_lu} area)"
11211107
lu_years_file = f"_mask{year_1_lu}-{year_n_lu}"
11221108
else:

0 commit comments

Comments
 (0)