diff --git a/.gitignore b/.gitignore index a335b7107e..96349188fc 100644 --- a/.gitignore +++ b/.gitignore @@ -61,11 +61,6 @@ buildnmlc /bld/unit_testers/user_nl_ctsm_real_parameters* /bld/unit_testers/env_run.xml -# tools testing output -td.*.status -td.*.log -td.*.status.xFail - # mksurfdata output surfdata_*.log *.namelist @@ -76,7 +71,6 @@ ctsm.input_data_list ctsm.input_data_list.previous *.stdout.txt.o* /tools/mksurfdata_esmf/PET* -/tools/mksurfdata_esmf/job_name.o* /tools/mksurfdata_esmf/mksurfdata_in /tools/mksurfdata_esmf/surfdata_*.nc /tools/mksurfdata_esmf/landuse.timeseries_*.nc @@ -116,6 +110,9 @@ core.* *.pyc Depends +# Batch output files (both Derecho and Izumi) +*.o[0-9]+ + # Docs build and testing output _build*/ _publish*/ diff --git a/python/conda_env_ctsm_py.yml b/python/conda_env_ctsm_py.yml index 96656696db..13dec57601 100644 --- a/python/conda_env_ctsm_py.yml +++ b/python/conda_env_ctsm_py.yml @@ -17,6 +17,7 @@ dependencies: - black=25.1.0 - cartopy=0.24.0 - matplotlib=3.10.1 + - compliance-checker=6.1.0 - pip=25.0.1 # For VS code diff --git a/python/ctsm/cplhist/__init__.py b/python/ctsm/cplhist/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/python/ctsm/cplhist/aero_1850_monthly_clim.py b/python/ctsm/cplhist/aero_1850_monthly_clim.py new file mode 100644 index 0000000000..9f2eff8e01 --- /dev/null +++ b/python/ctsm/cplhist/aero_1850_monthly_clim.py @@ -0,0 +1,79 @@ +""" +Create a 12-month climatology of the aerosol deposition fields from daily CMEPS coupler history +(CPLHIST) files, for use by DATM. + +The input files are the daily averaged atmosphere coupler history files: + + ARCHDIR/CASE/cpl/hist/CASE.cpl.hx.atm.24h.avrg.YYYY-MM-DD-00000.nc + +for the years BEGYEAR to ENDYEAR. The steps are: + + 1. Average the daily files of each month of each year (ncra) + 2. Average each calendar month over all the years (ncra), and put the 12 months in one + file (ncrcat) + 3. Set the time axis to the middle of each month of YEAR (noleap calendar) + +The output file is: + + OUTDIR/CASE/proc/CASE.cpl.hx.atm.monclim.BEGYEAR-ENDYEAR_cYYYYMMDD.nc + +This needs the NCO commands ncra, ncrcat and ncatted (on Derecho: module load nco). +With --batch, the input is checked and then this tool is submitted to the PBS batch queue. + +The general code is in cplhist_monthly_clim.py, this sets what's specific to aerosols for 1850. + +A previous version of this for CESM2 is in NCL and here on Derecho by Keith Oleson: + /glade/u/home/oleson/misc_programs/CLM5Dev/CMIP6/CreateAeroDepFile_Task5B.ncl +It did 5 year averages over the historical period and then did a linear interpolation +between the 5-year averages. It also used CPLHIST output from several ensemble members and +averged them together with ncea. This is something that will have to be done in the future +in this tool as well. + +Another example for Nitrogen deposition is here from Simone Tilmes and Mike Mills: + https://svn.code.sf.net/p/codescripts/code/trunk/ncl/cam_forcing/CreateDepositionFile.ncl + +Neither were quite right for what's needed here. And both are in NCL which is well after +end of life now. + +Also there is code in LDF to create monthly climatologies, but it's not setup to bring in ensemble +averages and not specialized to create datafiles for DATM aerosol forcing. +""" + +import os + +from ctsm.cplhist.cplhist_monthly_clim import CplhistMonthlyClim + + +class Aero1850MonthlyClim(CplhistMonthlyClim): + """ + Monthly climatology of the aerosol deposition fields for 1850 + """ + + DEFAULT_VARS = [ + "atmImp_Faxa_bcph1", + "atmImp_Faxa_bcph2", + "atmImp_Faxa_bcph3", + "atmImp_Faxa_ocph1", + "atmImp_Faxa_ocph2", + "atmImp_Faxa_ocph3", + "atmImp_Faxa_dstwet1", + "atmImp_Faxa_dstdry1", + "atmImp_Faxa_dstwet2", + "atmImp_Faxa_dstdry2", + "atmImp_Faxa_dstwet3", + "atmImp_Faxa_dstdry3", + "atmImp_Faxa_dstwet4", + "atmImp_Faxa_dstdry4", + ] + DEFAULT_YEAR = 1850 + PBS_JOBNAME = "aero_1850_monthly_clim" + WRAPPER = os.path.join("tools", "cplhist", "aero_1850_monthly_clim") + TITLE = "Monthly Climatology of Daily Averaged Atmosphere Coupler History Files" + COMMENT = "Monthly climatology created from daily averaged CPLHIST files for DATM" + + +def main(): + """ + Main program for aero_1850_monthly_clim + """ + Aero1850MonthlyClim.main() diff --git a/python/ctsm/cplhist/cplhist_monthly_clim.py b/python/ctsm/cplhist/cplhist_monthly_clim.py new file mode 100644 index 0000000000..4e88bfca54 --- /dev/null +++ b/python/ctsm/cplhist/cplhist_monthly_clim.py @@ -0,0 +1,959 @@ +""" +Generic code to create a 12-month climatology from daily CMEPS coupler history (CPLHIST) files, +for use by DATM. + +A specific product (for example aerosol deposition for 1850, see aero_1850_monthly_clim.py) is a +subclass of CplhistMonthlyClim that sets the class attributes for its variables, metadata and +tool name, and can override the methods for the steps that are different for it. + +The input files are the daily averaged atmosphere coupler history files: + + ARCHDIR/CASE/cpl/hist/CASE.cpl.hx.atm.24h.avrg.YYYY-MM-DD-00000.nc + +for the years BEGYEAR to ENDYEAR. The steps are: + + 1. Average the daily files of each month of each year (ncra) + 2. Average each calendar month over all the years (ncra), and put the 12 months in one + file (ncrcat) + 3. Set the time axis to the middle of each month of YEAR (noleap calendar) + +The output file is: + + OUTDIR/CASE/proc/CASE.cpl.hx.atm.OUTPUT_TAG.BEGYEAR-ENDYEAR_cYYYYMMDD.nc + +This needs the NCO commands ncra, ncrcat and ncatted (on Derecho: module load nco). +""" + +import argparse +import concurrent.futures # Handles parallel multi-processing with ncra jobs on different threads +import datetime +import getpass +import io +import logging +import os +import re +import shlex +import shutil +import socket +import subprocess +import sys + +from netCDF4 import Dataset # pylint: disable=no-name-in-module + +from ctsm.args_utils import comma_separated_list +from ctsm.ctsm_logging import ( + setup_logging_pre_config, + add_logging_args, + process_logging_args, + log, +) +from ctsm.git_utils import get_ctsm_git_short_hash +from ctsm.os_utils import run_cmd_output_on_error +from ctsm.path_utils import path_to_ctsm_root +from ctsm.toolchain.gen_mksurfdata_jobscript_single import write_runscript_part1 +from ctsm.utils import abort + +logger = logging.getLogger(__name__) + +# Grid fields that are always written to the output, whatever variable list is used +ALWAYS_VARS = ["atmImp_lon", "atmImp_lat"] +# Days in each month of the noleap calendar +NOLEAP_DAYS = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) +# File name tag of the daily averaged atmosphere coupler history files +HIST_TAG = "cpl.hx.atm.24h.avrg" +# NCO commands that are needed +NCO_COMMANDS = ("ncra", "ncrcat", "ncatted") +# Number of simultaneous ncra jobs inside a PBS batch job, and otherwise (on a login node) +PBS_NJOBS = 64 +INTERACTIVE_NJOBS = 12 +# PBS batch settings +DEFAULT_ACCOUNT = "P93300606" +DEFAULT_QUEUE = "main" + + +def default_njobs(): + """ + Number of simultaneous ncra jobs when not given: more inside a PBS batch job + """ + if os.environ.get("PBS_JOBID"): + return PBS_NJOBS + return INTERACTIVE_NJOBS + + +def input_dir(archdir, case): + """ + Directory with the daily coupler history files + """ + return os.path.join(archdir, case, "cpl", "hist") + + +def output_dir(archdir, outdir, case): + """ + Directory for the output (OUTDIR/CASE/proc, where OUTDIR defaults to ARCHDIR) + """ + if outdir is None: + outdir = archdir + return os.path.join(outdir, case, "proc") + + +def build_var_list(variables, always_vars): + """ + Combine the variables to average with the ones that are always output + + Keeps the order given, drops duplicates and empty names. Returns None when variables is None, + meaning all variables. + """ + if variables is None: + return None + var_list = [] + for var in list(variables) + list(always_vars): + if var and var not in var_list: + var_list.append(var) + return var_list + + +def averaged_vars(variables): + """ + The variables for ncra to average: the ones given, without duplicates, empty names or the + ALWAYS_VARS (which are copied to the output without the time dimension instead). Returns + None when variables is None, meaning all variables. + """ + if variables is None: + return None + return [var for var in build_var_list(variables, []) if var not in ALWAYS_VARS] + + +def year_months(begyr, endyr): + """ + List of (year, month) to process, from BEGYEAR-01 to ENDYEAR-12 + """ + return [(year, month) for year in range(begyr, endyr + 1) for month in range(1, 13)] + + +def index_daily_files(indir, case): + """ + Find the daily coupler history files for this case, matching them by name (not by the time + coordinate in the files) + + Returns a dictionary of sorted file path lists, with (year, month) keys + """ + pattern = re.compile( + rf"^{re.escape(case)}\.{re.escape(HIST_TAG)}\.(\d{{4}})-(\d{{2}})-(\d{{2}})-00000\.nc$" + ) + files_by_month = {} + for filename in sorted(os.listdir(indir)): + match = pattern.match(filename) + if match: + key = (int(match.group(1)), int(match.group(2))) + files_by_month.setdefault(key, []).append(os.path.join(indir, filename)) + return files_by_month + + +def check_day_counts(files_by_month, yms): + """ + Check that every month has a full set of daily files (noleap calendar) + + Returns a list of error messages, empty if all the months are complete + """ + errors = [] + for year, month in yms: + nfiles = len(files_by_month.get((year, month), [])) + expect = NOLEAP_DAYS[month - 1] + if nfiles != expect: + errors.append(f"{year:04d}-{month:02d} has {nfiles} daily files (expected {expect})") + return errors + + +def file_vars(filename): + """ + Return the set of variable names in the netCDF file + """ + with Dataset(filename) as ncfile: + return set(ncfile.variables) + + +def missing_vars(filename, var_list): + """ + Return the variables in var_list that are not in the netCDF file + """ + in_file = file_vars(filename) + return [var for var in var_list if var not in in_file] + + +def check_nco(): + """ + Abort if any of the needed NCO commands can't be found + """ + missing = [cmd for cmd in NCO_COMMANDS if shutil.which(cmd) is None] + if missing: + abort(f"NCO commands not found: {' '.join(missing)} (on Derecho: module load nco)") + + +def ncra_command(infiles, outfile, var_list=None, *, exclude=None, skip_existing=False): + """ + The ncra command (as a list) to average the input files into outfile + + var_list is the variables to average (None for all). When var_list is None, the variables + in exclude (if given) are left out. + + With skip_existing, if outfile already exists, returns an empty list (no command to run) + and logs a message + """ + if skip_existing and os.path.exists(outfile): + log(logger, f"File already exists: {outfile} so skipping ncra command") + return [] + # Use --hst option so that history attribute isn't appended to as it's too long + # Use -O to overwrite the output file without asking (existing files are skipped above + # if they should be kept) + cmd = ["ncra", "-O", "--hst"] + if var_list is not None: + cmd += ["-v", ",".join(var_list)] + elif exclude: + cmd += ["-x", "-v", ",".join(exclude)] + return cmd + list(infiles) + ["-o", outfile] + + +def run_jobs(commands, njobs, *, progress_every=None, runner=run_cmd_output_on_error): + """ + Run the commands (each a list, with the output file last), with at most njobs at once + + Stops at the first failure: the jobs that have not started are cancelled and the runner's + error (normally an abort) is raised. Logs progress every progress_every completed jobs. + Empty commands (for output files that already exist) are skipped. + + Args: + commands (list): The commands to run, each a list of the command and its arguments, + with the output file last (an empty list is skipped) + njobs (int): Number of jobs to run simultaneously + progress_every (int): Log the progress every time this many jobs have completed + runner (function): Python function to call to run each command + + Returns: + None + + Raises: + SystemExit: From the runner's abort if a command fails + KeyboardInterrupt: If the user hits Ctrl-C + """ + commands = [cmd for cmd in commands if cmd] + if not commands: + return + ndone = 0 # number of jobs that have completed + # concurrent.futures executes up to njobs at the same time, but prepares all of them + with concurrent.futures.ThreadPoolExecutor(max_workers=njobs) as executor: + futures = [executor.submit(runner, cmd, f"Failed creating {cmd[-1]}") for cmd in commands] + try: + # Check which jobs are completed + for future in concurrent.futures.as_completed(futures): + future.result() + ndone += 1 + # Report on the progress + if progress_every and ndone % progress_every == 0: + log(logger, f" completed {ndone} of {len(commands)}") + except BaseException: + # Includes KeyboardInterrupt and the SystemExit from abort + # Will die if the user hits Ctrl-C or if the batch job is killed + + # Cancel all the future jobs + for future in futures: + future.cancel() + raise + + +def mon_file(mondir, year, month): + """ + Intermediate file with the monthly mean for one year and month + """ + return os.path.join(mondir, f"mon_{year:04d}-{month:02d}.nc") + + +def clim_file(mondir, month): + """ + Intermediate file with the climatology for one calendar month + """ + return os.path.join(mondir, f"clim_{month:02d}.nc") + + +def check_reused_mon_file(monfile, daily_files, var_list): + """ + Abort if a monthly file left from an earlier run doesn't have all the variables this run + needs (for example if it was made with a different variable list) + + With all variables (var_list is None), the monthly file must have all the variables in the + first daily file, except the ALWAYS_VARS. + """ + in_monfile = file_vars(monfile) + if var_list is None: + var_list = sorted(file_vars(daily_files[0]) - set(ALWAYS_VARS)) + missing = [var for var in var_list if var not in in_monfile] + if missing: + abort( + f"Existing monthly file {monfile} is missing variables: {' '.join(missing)}" + " (it was probably made with a different variable list, remove it and rerun)" + ) + + +def output_filename( # pylint: disable=too-many-positional-arguments + outdir, case, begyr, endyr, todaysdate, tag="monclim" +): + """ + Name of the output climatology file, with the year range and creation date + """ + return os.path.join( + outdir, f"{case}.cpl.hx.atm.{tag}.{begyr:04d}-{endyr:04d}_c{todaysdate:%Y%m%d}.nc" + ) + + +def month_bounds(): + """ + Start and end of each month, in days since the start of a noleap year + """ + bounds = [] + start = 0 + for ndays in NOLEAP_DAYS: + bounds.append((start, start + ndays)) + start += ndays + return bounds + + +def mid_month_times(): + """ + Middle of each month, in days since the start of a noleap year + """ + return [(start + end) / 2.0 for start, end in month_bounds()] + + +def climatology_bounds_values(begyr, endyr, year): + """ + CF climatology bounds for each calendar month, in days since year-01-01 (noleap calendar) + + Each month's bounds span all the averaged years: from the start of the month in begyr + to the end of the month in endyr (for January: begyr-01-01 to endyr-02-01). The values + are negative for years before year. + """ + days_per_year = sum(NOLEAP_DAYS) + return [ + ((begyr - year) * days_per_year + start, (endyr - year) * days_per_year + end) + for start, end in month_bounds() + ] + + +def set_time_axis(filename, year, begyr, endyr): + """ + Set the time of the 12-month file to the middle of each month of year, and its CF + climatology bounds to span the averaged years begyr to endyr, in the noleap calendar + """ + units = f"days since {year:04d}-01-01 00:00:00" + with Dataset(filename, "a") as ncfile: + time = ncfile.variables["time"] + time[:] = mid_month_times() + time.setncattr("units", units) + time.setncattr( + "long_name", "climatological time at exact middle of each month of climatology_bounds" + ) + time.setncattr("standard_name", "time") + time.setncattr("calendar", "noleap") + # For a climatology, CF uses the climatology attribute instead of bounds, and time + # itself has no cell_methods (ncra adds one) + for attr in ("bounds", "cell_methods"): + if attr in time.ncattrs(): + time.delncattr(attr) + time.setncattr("climatology", "climatology_bounds") + # + # Change time_bnds (from CMEPS) to climatology_bounds or create it if it doesn't exist + # + if "time_bnds" in ncfile.variables: + ncfile.renameVariable("time_bnds", "climatology_bounds") + if "climatology_bounds" not in ncfile.variables: + if "ntb" not in ncfile.dimensions: + ncfile.createDimension("ntb", 2) + ncfile.createVariable("climatology_bounds", "f8", ("time", "ntb")) + climatology_bounds = ncfile.variables["climatology_bounds"] + climatology_bounds[:] = climatology_bounds_values(begyr, endyr, year) + # Remove attributes from the renamed time_bnds that don't apply to bounds + for attr in ("bounds", "cell_methods", "coordinates"): + if attr in climatology_bounds.ncattrs(): + climatology_bounds.delncattr(attr) + climatology_bounds.setncattr("units", units) + climatology_bounds.setncattr("long_name", "climatology time interval endpoints") + climatology_bounds.setncattr("standard_name", "time") + # Bounds take axis and calendar from their coordinate (time), so CF checkers report + # these as non-standard on a bounds variable; remove them (time_bnds from CMEPS has them) + for attr in ("axis", "calendar"): + if attr in climatology_bounds.ncattrs(): + climatology_bounds.delncattr(attr) + + +def copy_grid_vars(src_file, dst_file, names): + """ + Copy the grid variables (names) from src_file (a daily file) to dst_file, without the time + dimension, using the first time slice + + The grid doesn't change in time, so the first time slice is the same as all the others (this + isn't checked). Missing dimensions are created in dst_file, and the attributes are copied + (without cell_methods, which is for data variables). + """ + with Dataset(src_file) as src, Dataset(dst_file, "a") as dst: + for name in names: + src_var = src.variables[name] + dims = tuple(dim for dim in src_var.dimensions if dim != "time") + for dim in dims: + if dim not in dst.dimensions: + dst.createDimension(dim, len(src.dimensions[dim])) + attrs = {attr: src_var.getncattr(attr) for attr in src_var.ncattrs()} + # _FillValue can only be set when the variable is created + fill_value = attrs.pop("_FillValue", None) + attrs.pop("cell_methods", None) + dst_var = dst.createVariable(name, src_var.dtype, dims, fill_value=fill_value) + dst_var.setncatts(attrs) + # Index 0 for time, all of every other dimension + first_time = tuple(0 if dim == "time" else slice(None) for dim in src_var.dimensions) + dst_var[...] = src_var[first_time] + + +def add_var_attributes(filename): + """ + Add the climatology cell_methods and the lon/lat coordinates attributes to the averaged data + variables (the variables on the time dimension, other than time, its bounds and lon/lat) + """ + with Dataset(filename, "a") as ncfile: + coords = " ".join(var for var in ALWAYS_VARS if var in ncfile.variables) + for name, var in ncfile.variables.items(): + if name in ALWAYS_VARS: + # cell_methods is for data variables, not coordinates like lon/lat (copy_grid_vars + # already leaves it out, this is just in case) + if "cell_methods" in var.ncattrs(): + var.delncattr("cell_methods") + continue + if name in ("time", "climatology_bounds"): + continue + if "time" not in var.dimensions: + continue + var.setncattr("cell_methods", "time: mean within years time: mean over years") + # Remove standard_name, as the CMEPS field names aren't CF-Convention standard names + if "standard_name" in var.ncattrs(): + var.delncattr("standard_name") + # Use the variable name as the long_name, unless the file already has one + if "long_name" not in var.ncattrs(): + var.setncattr("long_name", name) + if coords: + var.setncattr("coordinates", coords) + + +def submit_batch(script, queue): + """ + Submit the batch job script to PBS (qsub reads it from stdin), and return the job id + """ + if shutil.which("qsub") is None: + abort("qsub not found, can not submit with --batch") + result = subprocess.run( + ["qsub", "-q", queue], input=script, capture_output=True, text=True, check=False + ) + if result.returncode != 0: + abort(f"qsub failed:\n{result.stdout}{result.stderr}") + return result.stdout.strip() + + +class CplhistMonthlyClim: # pylint: disable=too-many-instance-attributes + """ + Monthly climatology from daily CPLHIST files + + This is the base class, a product subclasses it and sets the class attributes that are None + here. The methods are the steps of the work, which a product can override when it needs to do + something different (for example a different averaging, or files from several cases). + """ + + # Variables averaged by default (required) + DEFAULT_VARS = None + # Year to set the climatology time axis to + DEFAULT_YEAR = 1850 + # Tag in the output file name: CASE.cpl.hx.atm.OUTPUT_TAG.BEGYEAR-ENDYEAR_cYYYYMMDD.nc + OUTPUT_TAG = "monclim" + # PBS batch job name (required) + PBS_JOBNAME = None + # The executable wrapper for the product, run by the batch job, e.g. + # os.path.join("tools", "cplhist", "tool_name") (required) + WRAPPER = None + DEFAULT_WALLTIME = "04:00:00" + # Global title and comment attributes of the output file (required), + # " for cyclical year YEAR" is added to the title + TITLE = None + COMMENT = None + + _REQUIRED = ("DEFAULT_VARS", "PBS_JOBNAME", "WRAPPER", "TITLE", "COMMENT") + + def __init_subclass__(cls, **kwargs): + """ + Make sure a product subclass sets the required class attributes + (so a mistake shows up when the module is imported, not part way through a run) + """ + super().__init_subclass__(**kwargs) + missing = [name for name in cls._REQUIRED if getattr(cls, name) is None] + if missing: + raise TypeError(f"{cls.__name__} must set the class attributes: {', '.join(missing)}") + + @classmethod + def get_parser(cls): + """ + Get the parser object, with the description from the product's module docstring + """ + parser = argparse.ArgumentParser( + description=sys.modules[cls.__module__].__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + parser.add_argument( + "archdir", help="Archive directory with the case directories (ARCHDIR/CASE/cpl/hist)" + ) + parser.add_argument("case", help="Case name") + parser.add_argument( + "begyear", type=int, help="First year of the daily files to average (inclusive)" + ) + parser.add_argument( + "endyear", type=int, help="Last year of the daily files to average (inclusive)" + ) + + vars_group = parser.add_mutually_exclusive_group() + vars_group.add_argument( + "--vars", + help=f"""Comma-separated list of variables to average + ({",".join(ALWAYS_VARS)} are always included, copied from the first daily file + without the time dimension) + (default: {",".join(cls.DEFAULT_VARS)})""", + action="store", + dest="vars", + type=comma_separated_list, + default=cls.DEFAULT_VARS, + ) + vars_group.add_argument( + "-a", + "--all-vars", + help="Average all variables in the files", + action="store_true", + dest="all_vars", + ) + parser.add_argument( + "-o", + "--outdir", + help="""Output directory if different from ARCHDIR. Files go under OUTDIR/CASE/proc + (default: ARCHDIR)""", + action="store", + dest="outdir", + default=None, + ) + parser.add_argument( + "-y", + "--year", + help="Year to set the climatology time axis to (default: %(default)s)", + action="store", + dest="year", + type=int, + default=cls.DEFAULT_YEAR, + ) + parser.add_argument( + "-k", + "--keep", + help="Keep the intermediate files in the OUTDIR/CASE/proc/mon directory", + action="store_true", + dest="keep", + ) + parser.add_argument( + "-j", + "--njobs", + help=f"""Number of ncra jobs to run at the same time + (default: {PBS_NJOBS} in a PBS batch job, {INTERACTIVE_NJOBS} otherwise)""", + action="store", + dest="njobs", + type=int, + default=None, + ) + parser.add_argument( + "-b", + "--batch", + help="Check the input, then submit this tool to the PBS batch queue with the same " + "options", + action="store_true", + dest="batch", + ) + parser.add_argument( + "-A", + "--account", + help=f"""PBS project account to charge with --batch + (default: $ACCOUNT if set, otherwise {DEFAULT_ACCOUNT})""", + action="store", + dest="account", + default=None, + ) + parser.add_argument( + "--queue", + help="PBS queue to use with --batch (default: %(default)s)", + action="store", + dest="queue", + default=DEFAULT_QUEUE, + ) + parser.add_argument( + "--walltime", + help="PBS wall clock time limit to use with --batch (default: %(default)s)", + action="store", + dest="walltime", + default=cls.DEFAULT_WALLTIME, + ) + cls.add_product_args(parser) + add_logging_args(parser) + return parser + + @classmethod + def add_product_args(cls, parser): + """ + Add command line arguments specific to a product (none in the base class) + """ + + def __init__(self, args): + """ + Set up from the parsed command line arguments (check_args checks them) + """ + self.args = args + self.njobs = args.njobs if args.njobs is not None else default_njobs() + # Variables for ncra to average (None for all), and the variables the input must have + self.var_list = None if args.all_vars else averaged_vars(args.vars) + self.check_list = build_var_list(self.var_list or [], ALWAYS_VARS) + self.indir = input_dir(args.archdir, args.case) + self.outdir = output_dir(args.archdir, args.outdir, args.case) + self.mondir = os.path.join(self.outdir, "mon") + self.todaysdate = datetime.date.today() + self.yms = year_months(args.begyear, args.endyear) + # Set by check_input + self.files_by_month = None + + def check_args(self): + """ + Check the command line arguments, aborting if there is a problem + """ + args = self.args + for name, year in ( + ("BEGYEAR", args.begyear), + ("ENDYEAR", args.endyear), + ("YEAR", args.year), + ): + if not 1 <= year <= 9999: + abort(f"{name} must be an integer from 1 to 9999: {year}") + if args.begyear > args.endyear: + abort(f"BEGYEAR ({args.begyear}) must not be after ENDYEAR ({args.endyear})") + if args.njobs is not None and args.njobs < 1: + abort(f"NJOBS must be a positive integer: {args.njobs}") + if args.account is not None and not args.batch: + abort("--account is only used with --batch") + if not args.all_vars and not averaged_vars(args.vars): + abort(f"No variables to average given with --vars (besides {','.join(ALWAYS_VARS)})") + if not os.path.isdir(args.archdir): + abort(f"Input archive directory {args.archdir} does not exist") + if args.outdir is not None and not os.path.isdir(args.outdir): + abort(f"Output archive directory {args.outdir} does not exist") + if not os.path.isdir(self.indir): + abort(f"Input case archive directory {self.indir} does not exist") + # + # Abort if the output file already exists + # + outfile = self.output_file() + if os.path.exists(outfile): + abort( + f"Output file {outfile} already exists, remove it or use a different output " + "directory" + ) + + def output_file(self): + """ + Name of the output file for this run + """ + return output_filename( + self.outdir, + self.args.case, + self.args.begyear, + self.args.endyear, + self.todaysdate, + tag=self.OUTPUT_TAG, + ) + + def input_files_by_month(self): + """ + The daily files to average for each month: a dictionary of sorted file path lists, + with (year, month) keys + """ + return index_daily_files(self.indir, self.args.case) + + def check_input(self): + """ + Check the input files before doing any work: every variable in check_list (the requested + variables and the ALWAYS_VARS) is in the first file, and every month in the range has a + full set of daily files + + Sets files_by_month to the daily files for each month + """ + yms = self.yms + log( + logger, + f"Processing {len(yms)} year-months: {self.args.begyear:04d}-01 .." + f" {self.args.endyear:04d}-12", + ) + files_by_month = self.input_files_by_month() + + first_files = files_by_month.get(yms[0], []) + if not first_files: + abort(f"No files for {yms[0][0]:04d}-{yms[0][1]:02d} in {self.indir}") + log(logger, f"Checking the requested variables are in {first_files[0]}") + missing = missing_vars(first_files[0], self.check_list) + if missing: + abort(f"Variables not found in {first_files[0]}: {' '.join(missing)}") + + log(logger, "Checking that every month has the expected number of daily files") + errors = check_day_counts(files_by_month, yms) + if errors: + abort("\n".join(errors)) + self.files_by_month = files_by_month + + def monthly_means(self): + """ + Step 1: average the daily files of each month of each year + + Monthly files left from an earlier run (for example with --keep) are reused, after checking + that they have the variables needed. The ALWAYS_VARS are never averaged (with all + variables they are excluded), as they are copied to the output at the end without time. + """ + log(logger, f"Computing monthly means for each year ({self.njobs} ncra jobs at a time)") + commands = [] + for year, month in self.yms: + monfile = mon_file(self.mondir, year, month) + daily_files = self.files_by_month[(year, month)] + if os.path.exists(monfile): + check_reused_mon_file(monfile, daily_files, self.var_list) + commands.append( + ncra_command( + daily_files, monfile, self.var_list, exclude=ALWAYS_VARS, skip_existing=True + ) + ) + # Show progress every 10 years + run_jobs(commands, self.njobs, progress_every=120) + + def monthly_climatology(self): + """ + Step 2: average each calendar month over the years + + Only this run's years are used, so leftover files from an earlier --keep run are not + included. The climatology files are always recreated, so ones left from an earlier run + with a different year range are not reused. + """ + begyr, endyr = self.args.begyear, self.args.endyear + log(logger, f"Averaging each calendar month over the years {begyr}-{endyr}") + commands = [ + ncra_command( + [mon_file(self.mondir, year, month) for year in range(begyr, endyr + 1)], + clim_file(self.mondir, month), + ) + for month in range(1, 13) + ] + run_jobs(commands, self.njobs) + + def average(self): + """ + Do the averaging steps, ending with the 12 climatology files in mondir + """ + self.monthly_means() + self.monthly_climatology() + + def set_time_axis(self, outfile): + """ + Set the time axis and its bounds on the output file + """ + set_time_axis(outfile, self.args.year, self.args.begyear, self.args.endyear) + + def provenance_attrs(self): + """ + Global attributes saying what the file is, and when, by whom and with what it was created, + as a list of (name, value) + """ + args = self.args + created_with = f"./{os.path.basename(self.WRAPPER)} -- {get_ctsm_git_short_hash()}" + source = ( + f"Created from daily averaged CESM3.0 CPLHIST files for case {args.case} for " + + f"years {args.begyear:04d}-{args.endyear:04d}" + ) + institution = ( + "National Science Foundation (NSF) - National Center for Atmospheric Research" + + " (NCAR) Community Earth System Model (CESM) project" + ) + return [ + ("title", f"{self.TITLE} for cyclical year {args.year}"), + ("comment", self.COMMENT), + ("source", source), + ("institution", institution), + # Use CF-1.11 as the compliance-checker doesn't support CF-1.12 yet + ("Conventions", "CF-1.11"), + ("Created_on", f"{self.todaysdate}"), + ("Created_by", getpass.getuser()), + ("Created_with", created_with), + ("command_used", shlex.join(sys.argv)), + ("time_period_freq", "month_1"), + ("hostname", socket.gethostname()), + # NOTE: this is the CESM2 DOI, and should be updated when a CESM3 DOI is available + # ("model_doi_url", "https://doi.org/10.5065/D67H1H0V"), + # TODO: Uncomment the above when we have a DOI for CESM3.0 + ("made_from_cesm_case", args.case), + ] + + def write_provenance(self, filename): + """ + Add the provenance_attrs global attributes to the file (like update_metadata in + ctsm/site_and_regional/base_case.py, but using ncatted) + """ + logger.debug( + "Write provenance information out to %s for year=%s case=%s years=%s-%s", + filename, + self.args.year, + self.args.case, + self.args.begyear, + self.args.endyear, + ) + # Use Overwrite option since the file already exists and we want to add attributes to it + # Use --hst option so that history attribute isn't appended as it's not helpful + cmd = ["ncatted", "-O", "--hst"] + for name, value in self.provenance_attrs(): + cmd += ["-a", f"{name},global,o,c,{value}"] + # Delete global attributes that don't apply to the climatology (in the same ncatted call, + # so --hst covers it too) + for name in ("file_version",): + cmd += ["-a", f"{name},global,d,,"] + run_cmd_output_on_error(cmd + [filename], f"Failed adding provenance to {filename}") + + def write_output(self, outfile): + """ + Step 3: put the 12 monthly climatologies in one file, copy the grid variables (ALWAYS_VARS) + from the first daily file without time, reset the time axis, and add provenance + attributes + """ + log(logger, "Putting the climatology into one file and finalizing its metadata") + clim_files = [clim_file(self.mondir, month) for month in range(1, 13)] + # -O so ncrcat never stops to ask about overwriting (check_args already made sure the + # output file didn't exist when the run started) + run_cmd_output_on_error( + ["ncrcat", "-O"] + clim_files + [outfile], f"Failed creating {outfile}" + ) + copy_grid_vars(self.files_by_month[self.yms[0]][0], outfile, ALWAYS_VARS) + self.set_time_axis(outfile) + add_var_attributes(outfile) + self.write_provenance(outfile) + log(logger, f"Wrote {outfile} (time = mid-month of year {self.args.year:04d}, noleap)") + + def job_args(self): + """ + The command line arguments for the batch job: the same as given, without the batch options + """ + args = self.args + argv = [args.archdir, args.case, str(args.begyear), str(args.endyear)] + if args.all_vars: + argv.append("--all-vars") + elif args.vars != self.DEFAULT_VARS: + argv += ["--vars", ",".join(args.vars)] + if args.outdir is not None: + argv += ["--outdir", args.outdir] + if args.year != self.DEFAULT_YEAR: + argv += ["--year", str(args.year)] + if args.keep: + argv.append("--keep") + if args.njobs is not None: + argv += ["--njobs", str(args.njobs)] + for option in ("verbose", "silent", "debug"): + if getattr(args, option): + argv.append(f"--{option}") + return argv + + def batch_script(self, argv, *, account, walltime, workdir, njobs): + """ + Text of the PBS batch job script that runs this tool with the arguments argv + Written out to a variable so it can be submitted to qsub from stdin, + instead of writing a temporary file + + njobs is the number of simultaneous ncra jobs the batch job will run + """ + runfile = io.StringIO() + write_runscript_part1( + number_of_nodes=1, + tasks_per_node=njobs, + machine="derecho", + account=account, + walltime=walltime, + runfile=runfile, + name=self.PBS_JOBNAME, + comment="This is a batch script to create a monthly climatology from daily CPLHIST " + "files", + ) + runfile.write("module load nco\n") + runfile.write(f"cd {shlex.quote(workdir)}\n") + wrapper = os.path.join(path_to_ctsm_root(), self.WRAPPER) + runfile.write(shlex.join([sys.executable, wrapper] + argv) + "\n") + return runfile.getvalue() + + def submit(self): + """ + Submit this tool with the same arguments (except the batch ones) to the PBS batch queue + """ + args = self.args + account = args.account or os.environ.get("ACCOUNT") or DEFAULT_ACCOUNT + argv = self.job_args() + # The batch job runs with the njobs given, or the default inside a PBS job + job_njobs = args.njobs if args.njobs is not None else PBS_NJOBS + script = self.batch_script( + argv, + account=account, + walltime=args.walltime, + workdir=os.getcwd(), + njobs=job_njobs, + ) + logger.debug("Batch job script:\n%s", script) + jobid = submit_batch(script, args.queue) + log( + logger, + f"Successfully submitted job {jobid} with arguments: {' '.join(argv)}" + f" (log file will be {self.PBS_JOBNAME}.o{jobid.split('.')[0]} in {os.getcwd()})", + ) + + def run(self): + """ + Check the arguments and the input, then either submit to the batch queue (--batch) + or create the climatology + """ + self.check_args() + if self.var_list is None: + log(logger, f"Averaging all variables except {','.join(ALWAYS_VARS)}") + else: + log(logger, f"Averaging variables: {','.join(self.var_list)}") + log(logger, f"Copying without time from the first daily file: {','.join(ALWAYS_VARS)}") + log(logger, "Create a monthly climatology from daily averaged CPLHIST files for DATM") + + check_nco() + self.check_input() + + # With --batch: the input has been checked, so submit to PBS and stop here + if self.args.batch: + self.submit() + return + + os.makedirs(self.mondir, exist_ok=True) + self.average() + outfile = self.output_file() + self.write_output(outfile) + + if self.args.keep: + log(logger, f"Kept intermediate files in {self.mondir}") + else: + shutil.rmtree(self.mondir) + + log(logger, f"Successfully created monthly climatology: {outfile}") + + @classmethod + def main(cls): + """ + Main program for a product: cls.main() runs it with the command line arguments + """ + setup_logging_pre_config() + args = cls.get_parser().parse_args() + process_logging_args(args) + cls(args).run() diff --git a/python/ctsm/test/test_sys_aero_1850_monthly_clim.py b/python/ctsm/test/test_sys_aero_1850_monthly_clim.py new file mode 100644 index 0000000000..10cff77f35 --- /dev/null +++ b/python/ctsm/test/test_sys_aero_1850_monthly_clim.py @@ -0,0 +1,233 @@ +#!/usr/bin/env python3 + +"""System tests for aero_1850_monthly_clim (needs the NCO commands, on Derecho: module load nco)""" + +import contextlib +import datetime +import io +import os +import shlex +import shutil +import sys +import tempfile +import unittest +from unittest import mock + +import numpy as np +from netCDF4 import Dataset # pylint: disable=no-name-in-module + +# -- add python/ctsm to path (needed if we want to run test stand-alone) +_CTSM_PYTHON = os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir) +sys.path.insert(1, _CTSM_PYTHON) +# pylint: disable=wrong-import-position +from ctsm import unit_testing +from ctsm.cplhist import aero_1850_monthly_clim as aero +from ctsm.cplhist import cplhist_monthly_clim as mclim +from ctsm.os_utils import run_cmd_output_on_error + +# Allow test names that pylint doesn't like; otherwise hard to make them +# readable +# pylint: disable=invalid-name + +CASE = "TC" +BEGYEAR = 2001 +ENDYEAR = 2002 +# A variable that isn't in the default list +EXTRA_VAR = "atmImp_Sa_extra" +NX = 3 +LON = 10.0 + np.arange(NX, dtype="f4") +LAT = -60.0 + np.arange(NX, dtype="f4") + + +def _value(year, month): + """Value of the default variables in the daily files for a year and month""" + # This is arbitrary, but having it be a function of year and month makes it predictable + # but also different for files of different years and months + return (year - 2000) * 100 + month + + +def _write_daily_file(filename, year, month, day_of_year): + """ + Write a daily file like the CMEPS CPLHIST 24h average coupler history files: + 2 time samples, time_bnds, the default variables and EXTRA_VAR on + (time, atmImp_ny, atmImp_nx), and lon/lat with time too + """ + with Dataset(filename, "w") as ncfile: + ncfile.createDimension("time", None) + ncfile.createDimension("ntb", 2) + ncfile.createDimension("atmImp_ny", 1) + ncfile.createDimension("atmImp_nx", NX) + ncfile.file_version = "cmeps0" + start = (year - 1) * 365 + day_of_year + time = ncfile.createVariable("time", "f8", ("time",)) + time.setncatts({"units": "days since 0001-01-01 00:00:00", "calendar": "noleap"}) + time[:] = [start + 0.25, start + 0.75] + time_bnds = ncfile.createVariable("time_bnds", "f8", ("time", "ntb")) + time_bnds.setncatts({"bounds": "time_bnds", "axis": "T", "calendar": "noleap"}) + time_bnds[:] = [[start, start + 0.5], [start + 0.5, start + 1.0]] + dims = ("time", "atmImp_ny", "atmImp_nx") + value = _value(year, month) + for name in aero.Aero1850MonthlyClim.DEFAULT_VARS + [EXTRA_VAR]: + var = ncfile.createVariable(name, "f4", dims, fill_value=1.0e30) + var.setncatts({"units": "kg m-2 s-1", "standard_name": name}) + var[:] = (2.0 * value if name == EXTRA_VAR else value) * np.ones((2, 1, NX)) + for name, values, coord, units in ( + ("atmImp_lon", LON, "longitude", "degrees_E"), + ("atmImp_lat", LAT, "latitude", "degrees_N"), + ): + var = ncfile.createVariable(name, "f4", dims, fill_value=1.0e30) + # Same attributes as CMEPS, the standard_name is needed for CF compliance + var.setncatts({"long_name": coord, "units": units, "standard_name": coord}) + var[:] = values * np.ones((2, 1, NX)) + + +@unittest.skipUnless(shutil.which("ncra"), "NCO not found (on Derecho: module load nco)") +class TestSysDailyToMonthlyClim(unittest.TestCase): + """System tests for aero_1850_monthly_clim, running the NCO commands""" + + @classmethod + def setUpClass(cls): + """Write BEGYEAR to ENDYEAR of daily files, once for all the tests""" + cls._indir_root = tempfile.mkdtemp() + cls._archdir = os.path.join(cls._indir_root, "archive") + indir = mclim.input_dir(cls._archdir, CASE) + os.makedirs(indir) + cls._first_daily = None + for year in range(BEGYEAR, ENDYEAR + 1): + day_of_year = 0 + for month, ndays in enumerate(mclim.NOLEAP_DAYS, start=1): + for day in range(1, ndays + 1): + filename = os.path.join( + indir, f"{CASE}.{mclim.HIST_TAG}.{year:04d}-{month:02d}-{day:02d}-00000.nc" + ) + _write_daily_file(filename, year, month, day_of_year) + day_of_year += 1 + if cls._first_daily is None: + cls._first_daily = filename + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls._indir_root, ignore_errors=True) + + def setUp(self): + self._previous_dir = os.getcwd() + self._tempdir = tempfile.mkdtemp() + os.chdir(self._tempdir) + + def tearDown(self): + os.chdir(self._previous_dir) + shutil.rmtree(self._tempdir, ignore_errors=True) + + def _run(self, *options, outdir=None): + """ + Run main with the options (and 4 ncra jobs), writing under outdir (a new directory under + the test directory by default). Returns the output file name and what was printed. + """ + if outdir is None: + outdir = tempfile.mkdtemp(dir=self._tempdir) + argv = ["aero_1850_monthly_clim", "-j", "4", "-o", outdir] + list(options) + argv += [self._archdir, CASE, str(BEGYEAR), str(ENDYEAR)] + output = io.StringIO() + with mock.patch.object(sys, "argv", argv), contextlib.redirect_stdout(output): + aero.main() + outfile = mclim.output_filename( + mclim.output_dir(self._archdir, outdir, CASE), + CASE, + BEGYEAR, + ENDYEAR, + datetime.date.today(), + ) + self.assertTrue(os.path.exists(outfile), msg=f"{outfile} not created") + return outfile, output.getvalue(), argv + + def _check_cf_compliance(self, outfile): + """Check the output file for CF compliance with the compliance-checker tool""" + cmd = ["compliance-checker", "--test", "cf", outfile] + run_cmd_output_on_error(cmd, "The output file did not pass the CF compliance checker") + + def _check_output(self, outfile, data_vars, year=aero.Aero1850MonthlyClim.DEFAULT_YEAR): + """Check the variables, values, grid, time axis and metadata of the output file""" + units = f"days since {year:04d}-01-01 00:00:00" + with Dataset(outfile) as ncfile: + expected = set(data_vars) | set(mclim.ALWAYS_VARS) | {"time", "climatology_bounds"} + self.assertEqual(set(ncfile.variables), expected) + # Each month is the average over the years of that month + for name in data_vars: + var = ncfile.variables[name] + self.assertEqual(var.dimensions, ("time", "atmImp_ny", "atmImp_nx")) + for month in range(1, 13): + expect = np.mean([_value(yr, month) for yr in range(BEGYEAR, ENDYEAR + 1)]) + if name == EXTRA_VAR: + expect *= 2.0 + np.testing.assert_allclose(var[month - 1], expect, rtol=1.0e-6) + self.assertEqual(var.cell_methods, "time: mean within years time: mean over years") + self.assertEqual(var.coordinates, "atmImp_lon atmImp_lat") + self.assertNotIn("standard_name", var.ncattrs()) + # The grid without the time dimension + for name, values in (("atmImp_lon", LON), ("atmImp_lat", LAT)): + var = ncfile.variables[name] + self.assertEqual(var.dimensions, ("atmImp_ny", "atmImp_nx")) + np.testing.assert_array_equal(var[0], values) + self.assertNotIn("cell_methods", var.ncattrs()) + # The time axis and the climatology bounds + time = ncfile.variables["time"] + np.testing.assert_array_equal(time[:], mclim.mid_month_times()) + self.assertEqual(time.units, units) + self.assertEqual(time.calendar, "noleap") + self.assertEqual(time.climatology, "climatology_bounds") + np.testing.assert_array_equal( + ncfile.variables["climatology_bounds"][:], + mclim.climatology_bounds_values(BEGYEAR, ENDYEAR, year), + ) + self.assertEqual(ncfile.Conventions, "CF-1.11") + self.assertEqual(ncfile.made_from_cesm_case, CASE) + self.assertNotIn("file_version", ncfile.ncattrs()) + return ncfile.command_used + + def test_defaultVars(self): + """The default variables, with the intermediate files removed at the end""" + outfile, _, argv = self._run() + command_used = self._check_output(outfile, aero.Aero1850MonthlyClim.DEFAULT_VARS) + self._check_cf_compliance(outfile) + self.assertEqual(command_used, shlex.join(argv)) + self.assertFalse(os.path.exists(os.path.join(os.path.dirname(outfile), "mon"))) + + def test_varsAndYear(self): + """A variable list (including a grid variable) and the time axis set to another year""" + outfile, _, argv = self._run("--vars", f"{EXTRA_VAR},atmImp_lat", "--year", "2001") + command_used = self._check_output(outfile, [EXTRA_VAR], year=2001) + self._check_cf_compliance(outfile) + # The comma in the --vars list makes it through ncatted + self.assertEqual(command_used, shlex.join(argv)) + + def test_allVars(self): + """All variables: time_bnds is renamed to climatology_bounds, lon/lat aren't averaged""" + outfile, _, _ = self._run("--all-vars") + self._check_output(outfile, aero.Aero1850MonthlyClim.DEFAULT_VARS + [EXTRA_VAR]) + self._check_cf_compliance(outfile) + + def test_keepAndReuse(self): + """With --keep the monthly files are kept, and reused on a rerun""" + outdir = tempfile.mkdtemp(dir=self._tempdir) + outfile, _, _ = self._run("--keep", outdir=outdir) + mondir = os.path.join(os.path.dirname(outfile), "mon") + nyears = ENDYEAR - BEGYEAR + 1 + self.assertEqual(len(os.listdir(mondir)), 12 * nyears + 12) + os.rename(outfile, os.path.join(self._tempdir, "first.nc")) + outfile, printed, _ = self._run("--keep", outdir=outdir) + self.assertEqual(printed.count("skipping ncra command"), 12 * nyears) + self._check_output(outfile, aero.Aero1850MonthlyClim.DEFAULT_VARS) + self._check_cf_compliance(outfile) + + def test_reuseWithDifferentVars_aborts(self): + """Monthly files kept from a run with fewer variables abort a run with all variables""" + outdir = tempfile.mkdtemp(dir=self._tempdir) + outfile, _, _ = self._run("--keep", outdir=outdir) + os.remove(outfile) + with self.assertRaisesRegex(SystemExit, f"is missing variables: {EXTRA_VAR}"): + self._run("--all-vars", outdir=outdir) + + +if __name__ == "__main__": + unit_testing.setup_for_tests() + unittest.main() diff --git a/python/ctsm/test/test_unit_aero_1850_monthly_clim.py b/python/ctsm/test/test_unit_aero_1850_monthly_clim.py new file mode 100644 index 0000000000..aaa6e9be60 --- /dev/null +++ b/python/ctsm/test/test_unit_aero_1850_monthly_clim.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 + +""" +Unit tests for aero_1850_monthly_clim, and the CplhistMonthlyClim class methods it uses + +The module-level functions of cplhist_monthly_clim are tested in test_unit_cplhist_monthly_clim.py +""" + +import datetime +import io +import os +import shlex +import shutil +import sys +import tempfile +import unittest +from unittest import mock + +from ctsm import unit_testing +from ctsm.cplhist import aero_1850_monthly_clim as aero +from ctsm.cplhist import cplhist_monthly_clim as mclim + +# Allow names that pylint doesn't like, because otherwise I find it hard +# to make readable unit test names +# pylint: disable=invalid-name + +CASE = "TESTCASE" +# The product class tested here +CLIM = aero.Aero1850MonthlyClim + + +def _check_args(args): + """Run check_args for the parsed arguments""" + CLIM(args).check_args() + + +# +# Tests for argument parsing +# +class TestGetParser(unittest.TestCase): + """Tests of get_parser""" + + def test_defaults(self): + """The defaults when only the positional arguments are given""" + args = CLIM.get_parser().parse_args(["arch", CASE, "2001", "2002"]) + self.assertEqual(args.archdir, "arch") + self.assertEqual(args.case, CASE) + self.assertEqual((args.begyear, args.endyear), (2001, 2002)) + self.assertEqual(args.vars, CLIM.DEFAULT_VARS) + self.assertFalse(args.all_vars) + self.assertIsNone(args.outdir) + self.assertEqual(args.year, CLIM.DEFAULT_YEAR) + self.assertFalse(args.keep) + self.assertIsNone(args.njobs) + self.assertFalse(args.batch) + self.assertIsNone(args.account) + self.assertEqual(args.queue, mclim.DEFAULT_QUEUE) + self.assertEqual(args.walltime, CLIM.DEFAULT_WALLTIME) + + def test_varsSplitsCommaList(self): + """--vars is split on commas, with spaces stripped""" + args = CLIM.get_parser().parse_args(["--vars", "a, b,c", "arch", CASE, "1", "2"]) + self.assertEqual(args.vars, ["a", "b", "c"]) + + def test_allVarsWithVars_exits(self): + """--all-vars and --vars can't be used together""" + with mock.patch("sys.stderr", new_callable=io.StringIO): + with self.assertRaises(SystemExit): + CLIM.get_parser().parse_args(["-a", "--vars", "a", "arch", CASE, "1", "2"]) + + +# +# Tests for the argument error checking +# +class TestCheckArgs(unittest.TestCase): + """Tests of check_args""" + + def setUp(self): + self._testdir = tempfile.mkdtemp() + self._archdir = os.path.join(self._testdir, "archive") + os.makedirs(mclim.input_dir(self._archdir, CASE)) + + def tearDown(self): + shutil.rmtree(self._testdir, ignore_errors=True) + + def _args(self, *options, archdir=None, years=("2001", "2002")): + """Parse the options, with the archive directory, case and years""" + if archdir is None: + archdir = self._archdir + return CLIM.get_parser().parse_args(list(options) + [archdir, CASE] + list(years)) + + def test_validArgs(self): + """Valid arguments pass""" + _check_args(self._args()) + + def test_yearOutOfRange(self): + """BEGYEAR, ENDYEAR and YEAR must be from 1 to 9999""" + with self.assertRaisesRegex(SystemExit, "ENDYEAR must be an integer from 1 to 9999"): + _check_args(self._args(years=("2001", "10000"))) + with self.assertRaisesRegex(SystemExit, "BEGYEAR must be an integer from 1 to 9999"): + _check_args(self._args(years=("0", "2001"))) + with self.assertRaisesRegex(SystemExit, "YEAR must be an integer from 1 to 9999"): + _check_args(self._args("--year", "10000")) + with self.assertRaisesRegex(SystemExit, "YEAR must be an integer from 1 to 9999"): + _check_args(self._args("--year", "0")) + + def test_begyearAfterEndyear(self): + """BEGYEAR can't be after ENDYEAR""" + with self.assertRaisesRegex(SystemExit, "must not be after ENDYEAR"): + _check_args(self._args(years=("2002", "2001"))) + + def test_njobsZero(self): + """--njobs must be positive""" + with self.assertRaisesRegex(SystemExit, "NJOBS must be a positive integer"): + _check_args(self._args("--njobs", "0")) + + def test_accountWithoutBatch(self): + """--account is only allowed with --batch""" + with self.assertRaisesRegex(SystemExit, "--account is only used with --batch"): + _check_args(self._args("--account", "P1")) + _check_args(self._args("--batch", "--account", "P1")) + + def test_onlyAlwaysVars(self): + """--vars with only the ALWAYS_VARS leaves nothing to average""" + with self.assertRaisesRegex(SystemExit, "No variables to average"): + _check_args(self._args("--vars", ",".join(mclim.ALWAYS_VARS))) + + def test_missingDirectories(self): + """The archive, output and input directories must exist""" + with self.assertRaisesRegex(SystemExit, "Input archive directory .* does not exist"): + _check_args(self._args(archdir=os.path.join(self._testdir, "dir_that_does_not_exist"))) + with self.assertRaisesRegex(SystemExit, "Output archive directory .* does not exist"): + _check_args( + self._args("--outdir", os.path.join(self._testdir, "dir_that_does_not_exist")) + ) + shutil.rmtree(mclim.input_dir(self._archdir, CASE)) + with self.assertRaisesRegex(SystemExit, "Input case archive directory .* does not exist"): + _check_args(self._args()) + + def test_outputExists(self): + """Abort if today's output file already exists""" + outdir = mclim.output_dir(self._archdir, None, CASE) + os.makedirs(outdir) + outfile = mclim.output_filename(outdir, CASE, 2001, 2002, datetime.date.today()) + with open(outfile, "w", encoding="utf-8"): + pass + with self.assertRaisesRegex(SystemExit, "already exists"): + _check_args(self._args()) + + +# +# Tests of writing provenance information is correct +# +class TestWriteProvenance(unittest.TestCase): + """Tests of write_provenance (with the ncatted command mocked)""" + + def test_oneNcattedCommand(self): + """One ncatted --hst command sets the global attributes and deletes file_version""" + # Replace run_cmd_output_on_error with a mock (run_cmd) that does nothing but record + # the call, get_ctsm_git_short_hash to return a fixed hash, and sys.argv with the + # command line given + clim = CLIM(CLIM.get_parser().parse_args(["arch", CASE, "100", "130"])) + clim.todaysdate = datetime.date(2026, 10, 3) + with mock.patch.object(mclim, "run_cmd_output_on_error") as run_cmd, mock.patch.object( + mclim, "get_ctsm_git_short_hash", return_value="abc1234" + ), mock.patch.object(sys, "argv", ["aero_1850_monthly_clim", "--vars", "a,b", "x"]): + clim.write_provenance("out.nc") + run_cmd.assert_called_once() + cmd = run_cmd.call_args.args[0] + self.assertEqual(cmd[:3], ["ncatted", "-O", "--hst"]) + self.assertEqual(cmd[-1], "out.nc") + attrs = cmd[4:-1:2] + self.assertEqual(cmd[3:-1:2], ["-a"] * len(attrs)) + self.assertIn("Conventions,global,o,c,CF-1.11", attrs) + self.assertIn("Created_on,global,o,c,2026-10-03", attrs) + self.assertIn("Created_with,global,o,c,./aero_1850_monthly_clim -- abc1234", attrs) + self.assertIn("command_used,global,o,c,aero_1850_monthly_clim --vars a,b x", attrs) + self.assertIn(f"made_from_cesm_case,global,o,c,{CASE}", attrs) + self.assertIn("file_version,global,d,,", attrs) + title = [attr for attr in attrs if attr.startswith("title,")] + self.assertTrue(title[0].endswith("for cyclical year 1850")) + + +# +# Test the batch options +# +class TestBatch(unittest.TestCase): + """Tests of job_args and batch_script""" + + def test_jobArgs_default(self): + """Only the positional arguments when the defaults are used""" + args = CLIM.get_parser().parse_args(["arch", CASE, "2001", "2002"]) + self.assertEqual(CLIM(args).job_args(), ["arch", CASE, "2001", "2002"]) + + def test_jobArgs_removes_batch_options(self): + """Set all options, but show that job_args returns only the non-batch options""" + args = CLIM.get_parser().parse_args( + [ + "--batch", + "--account", + "P1", + "--queue", + "develop", + "--walltime", + "01:00:00", + "--vars", + "a,b", + "-o", + "out", + "-y", + "2000", + "-k", + "-j", + "8", + "-v", + "arch", + CASE, + "2001", + "2002", + ] + ) + self.assertEqual( + CLIM(args).job_args(), + ["arch", CASE, "2001", "2002", "--vars", "a,b", "--outdir", "out", "--year", "2000"] + + ["--keep", "--njobs", "8", "--verbose"], + ) + + def test_jobArgs_allVars(self): + """Test that --all-vars is passed on when it's called as '-a'""" + args = CLIM.get_parser().parse_args(["-a", "arch", CASE, "2001", "2002"]) + self.assertEqual(CLIM(args).job_args(), ["arch", CASE, "2001", "2002", "--all-vars"]) + + def test_batchScript(self): + """ + Test that batch_script creates: PBS settings, NCO, the directory and the quoted command + """ + argv = ["arch", CASE, "2001", "2002", "--vars", "a,b", "--outdir", "my dir"] + clim = CLIM(CLIM.get_parser().parse_args(["arch", CASE, "2001", "2002"])) + script = clim.batch_script( + argv, account="P1", walltime="01:00:00", workdir="/work dir", njobs=8 + ) + lines = script.splitlines() + self.assertEqual(lines[0], "#!/bin/bash") + self.assertIn(f"#PBS -N {CLIM.PBS_JOBNAME}", lines) + self.assertIn("#PBS -A P1", lines) + self.assertIn("#PBS -l walltime=01:00:00", lines) + self.assertIn("mpiprocs=8", script) + self.assertIn("module load nco", lines) + self.assertIn("cd '/work dir'", lines) + command = shlex.split(lines[-1]) + self.assertEqual(command[0], sys.executable) + self.assertTrue(command[1].endswith(CLIM.WRAPPER)) + self.assertEqual(command[2:], argv) + + +# +# Test that the class attributes of a product subclass are used (this is what a new product, +# for example ozone, will set) +# +class _TestProductClim(mclim.CplhistMonthlyClim): + """A product with different settings than the aerosol one""" + + DEFAULT_VARS = ["atmImp_Sa_o3"] + DEFAULT_YEAR = 2000 + OUTPUT_TAG = "testclim" + PBS_JOBNAME = "test_product_clim" + WRAPPER = os.path.join("tools", "cplhist", "test_product_clim") + DEFAULT_WALLTIME = "01:00:00" + TITLE = "Test product title" + COMMENT = "Test product comment" + + +class TestProductSubclass(unittest.TestCase): + """Tests that a product subclass's class attributes flow through the base class""" + + def setUp(self): + self._args = _TestProductClim.get_parser().parse_args(["arch", CASE, "2001", "2002"]) + self._clim = _TestProductClim(self._args) + + def test_parserDefaults(self): + """The parser defaults come from the subclass""" + self.assertEqual(self._args.vars, ["atmImp_Sa_o3"]) + self.assertEqual(self._args.year, 2000) + self.assertEqual(self._args.walltime, "01:00:00") + + def test_jobArgs(self): + """The subclass defaults aren't passed on to the batch job, the aerosol ones are""" + self.assertEqual(self._clim.job_args(), ["arch", CASE, "2001", "2002"]) + args = _TestProductClim.get_parser().parse_args( + ["--vars", ",".join(CLIM.DEFAULT_VARS), "-y", "1850", "arch", CASE, "2001", "2002"] + ) + self.assertEqual( + _TestProductClim(args).job_args(), + ["arch", CASE, "2001", "2002", "--vars", ",".join(CLIM.DEFAULT_VARS)] + + ["--year", "1850"], + ) + + def test_outputFile(self): + """The output file name uses OUTPUT_TAG""" + self._clim.todaysdate = datetime.date(2026, 10, 3) + self.assertEqual( + self._clim.output_file(), + os.path.join( + "arch", CASE, "proc", f"{CASE}.cpl.hx.atm.testclim.2001-2002_c20261003.nc" + ), + ) + + def test_batchScript(self): + """The batch script uses the subclass's job name and wrapper""" + script = self._clim.batch_script( + ["arch"], account="P1", walltime="01:00:00", workdir="/work", njobs=8 + ) + self.assertIn("#PBS -N test_product_clim", script.splitlines()) + self.assertTrue(shlex.split(script.splitlines()[-1])[1].endswith(_TestProductClim.WRAPPER)) + + def test_provenanceAttrs(self): + """The title, comment and Created_with come from the subclass""" + with mock.patch.object(mclim, "get_ctsm_git_short_hash", return_value="abc1234"): + attrs = dict(self._clim.provenance_attrs()) + self.assertEqual(attrs["title"], "Test product title for cyclical year 2000") + self.assertEqual(attrs["comment"], "Test product comment") + self.assertEqual(attrs["Created_with"], "./test_product_clim -- abc1234") + + def test_missingRequiredAttribute(self): + """A subclass that doesn't set a required class attribute is rejected when it's defined""" + with self.assertRaisesRegex(TypeError, "must set the class attributes: TITLE, COMMENT"): + + class _IncompleteClim(mclim.CplhistMonthlyClim): # pylint: disable=unused-variable + """A product missing TITLE and COMMENT""" + + DEFAULT_VARS = ["a"] + PBS_JOBNAME = "incomplete" + WRAPPER = "incomplete" + + +if __name__ == "__main__": + unit_testing.setup_for_tests() + unittest.main() diff --git a/python/ctsm/test/test_unit_cplhist_monthly_clim.py b/python/ctsm/test/test_unit_cplhist_monthly_clim.py new file mode 100644 index 0000000000..12a9b7661e --- /dev/null +++ b/python/ctsm/test/test_unit_cplhist_monthly_clim.py @@ -0,0 +1,603 @@ +#!/usr/bin/env python3 + +""" +Unit tests for the module-level functions in cplhist_monthly_clim + +NOTE: SOME OF THESE UNIT TESTS HANDLE NetCDF FILES. + Normally we want tests that do I/O in the system tests, because I/O is slow + and has random glitches. Other unit tests use xarray with in memory objects + that don't create actual files. However, right now these tests only take about 10 seconds. +""" + +import datetime +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +import numpy as np +from netCDF4 import Dataset # pylint: disable=no-name-in-module + +from ctsm import unit_testing +from ctsm.cplhist import cplhist_monthly_clim as mclim + +# Allow names that pylint doesn't like, because otherwise I find it hard +# to make readable unit test names +# pylint: disable=invalid-name + +CASE = "TESTCASE" + + +# A couple utility functions for the tests +def _daily_name(case, year, month, day): + """Name of a daily coupler history file""" + return f"{case}.{mclim.HIST_TAG}.{year:04d}-{month:02d}-{day:02d}-00000.nc" + + +def _write_nc(filename, variables, ntime=1): + """ + Write a small netCDF file with the dimensions time (unlimited, ntime records) and n (2), + and the given variables: a dict of name -> (dimensions, attributes) + """ + with Dataset(filename, "w") as ncfile: + ncfile.createDimension("time", None) + ncfile.createDimension("n", 2) + for name, (dims, attrs) in variables.items(): + var = ncfile.createVariable(name, "f8", dims) + var.setncatts(attrs) + shape = tuple(ntime if dim == "time" else 2 for dim in dims) + var[...] = np.ones(shape) + + +# +# Tests for batch and number of jobs +# +class TestDefaultNjobs(unittest.TestCase): + """Tests of default_njobs""" + + def test_inBatchJob(self): + """Inside a PBS job (PBS_JOBID set) use PBS_NJOBS""" + with mock.patch.dict(os.environ, {"PBS_JOBID": "1234.desched1"}): + self.assertEqual(mclim.default_njobs(), mclim.PBS_NJOBS) + + def test_notInBatchJob(self): + """Outside a PBS job use INTERACTIVE_NJOBS""" + with mock.patch.dict(os.environ): + os.environ.pop("PBS_JOBID", None) + self.assertEqual(mclim.default_njobs(), mclim.INTERACTIVE_NJOBS) + + +# +# Tests for the variable lists +# +class TestVarLists(unittest.TestCase): + """Tests of build_var_list and averaged_vars""" + + def test_buildVarList(self): + """Keeps the order, drops duplicates and empty names, adds the extra variables at the end""" + self.assertEqual(mclim.build_var_list(["b", "a", "", "b"], ["c", "a"]), ["b", "a", "c"]) + + def test_buildVarList_none(self): + """None (all variables) stays None""" + self.assertIsNone(mclim.build_var_list(None, ["c"])) + + def test_averagedVars(self): + """The ALWAYS_VARS are removed from the list to average""" + variables = ["a", mclim.ALWAYS_VARS[0], "", "a", "b"] + self.assertEqual(mclim.averaged_vars(variables), ["a", "b"]) + + def test_averagedVars_none(self): + """None (all variables) stays None""" + self.assertIsNone(mclim.averaged_vars(None)) + + +# +# Tests for the year/month list and the daily file indexing +# +class TestYearMonths(unittest.TestCase): + """Tests of year_months""" + + def test_twoYears(self): + """Two years in order""" + yms = mclim.year_months(2001, 2002) + self.assertEqual(len(yms), 24) + self.assertEqual(yms[0], (2001, 1)) + self.assertEqual(yms[11], (2001, 12)) + self.assertEqual(yms[12], (2002, 1)) + self.assertEqual(yms[-1], (2002, 12)) + + def test_singleYear(self): + """A single year, including year 1 and the default year""" + for year in (1, mclim.CplhistMonthlyClim.DEFAULT_YEAR): + with self.subTest(year=year): + self.assertEqual( + mclim.year_months(year, year), [(year, month) for month in range(1, 13)] + ) + + +# +# Test the list of daily files and the file count +# +class TestDailyFiles(unittest.TestCase): + """Tests of index_daily_files and check_day_counts""" + + def setUp(self): + self._testdir = tempfile.mkdtemp() + # Empty files are enough, the files are found by name + for month, ndays in enumerate(mclim.NOLEAP_DAYS, start=1): + for day in range(1, ndays + 1): + self._create_empty_file(_daily_name(CASE, 2001, month, day)) + + def tearDown(self): + shutil.rmtree(self._testdir, ignore_errors=True) + + def _create_empty_file(self, filename): + """Create an empty file in the test directory""" + with open(os.path.join(self._testdir, filename), "w", encoding="utf-8"): + pass + + def test_indexDailyFiles(self): + """ + Check that index_daily_files properly groups and sorts by year and month + and ignores any other files + """ + # Files that should be ignored: another case, and other kinds of files + self._create_empty_file(_daily_name("DIFFERENT_CASE", 2001, 1, 1)) + self._create_empty_file(f"{CASE}.cpl.hi.2001-01-01-00000.nc") + self._create_empty_file(_daily_name(CASE, 2001, 1, 1) + ".base") + # + files_by_month = mclim.index_daily_files(self._testdir, CASE) + self.assertEqual(sorted(files_by_month), mclim.year_months(2001, 2001)) + for (_, month), files in files_by_month.items(): + self.assertEqual(len(files), mclim.NOLEAP_DAYS[month - 1]) + self.assertEqual(files, sorted(files)) + self.assertEqual( + files_by_month[(2001, 1)][0], os.path.join(self._testdir, _daily_name(CASE, 2001, 1, 1)) + ) + + def test_checkDayCounts_complete(self): + """Test that check_day_counts for a complete year is correct""" + files_by_month = mclim.index_daily_files(self._testdir, CASE) + self.assertEqual(mclim.check_day_counts(files_by_month, mclim.year_months(2001, 2001)), []) + + def test_checkDayCounts_missing(self): + """Test that check_day_counts reports missing days and years correctly""" + # Remove one day from the first year + os.remove(os.path.join(self._testdir, _daily_name(CASE, 2001, 2, 14))) + # NOTE: Setup only created files for the first year, so the second year has no files + files_by_month = mclim.index_daily_files(self._testdir, CASE) + errors = mclim.check_day_counts(files_by_month, mclim.year_months(2001, 2002)) + self.assertEqual(len(errors), 13) + # There will be an error reported for the missing day in the first year + # and each month of the second year + self.assertEqual(errors[0], "2001-02 has 27 daily files (expected 28)") + self.assertEqual(errors[1], "2002-01 has 0 daily files (expected 31)") + + +# +# Test the netCDF variable handling functions for the monthly files that were kept +# previously -- to make sure they have the needed variables +# +class TestNetcdfVars(unittest.TestCase): + """Tests of file_vars, missing_vars and check_reused_mon_file""" + + def setUp(self): + self._testdir = tempfile.mkdtemp() + self._daily = os.path.join(self._testdir, "daily.nc") + _write_nc( + self._daily, + { + "a": (("time", "n"), {}), + "b": (("time", "n"), {}), + mclim.ALWAYS_VARS[0]: (("time", "n"), {}), + }, + ) + + def tearDown(self): + shutil.rmtree(self._testdir, ignore_errors=True) + + def _monfile(self, names): + """Write a monthly file with the given variables (on time and n)""" + monfile = os.path.join(self._testdir, "mon.nc") + _write_nc(monfile, {name: (("time", "n"), {}) for name in names}) + return monfile + + def test_fileVars(self): + """The set of variable names in the file""" + self.assertEqual(mclim.file_vars(self._daily), {"a", "b", mclim.ALWAYS_VARS[0]}) + + def test_missingVars(self): + """Only the variables not in the file are returned, in order""" + self.assertEqual(mclim.missing_vars(self._daily, ["c", "a", "d"]), ["c", "d"]) + + def test_checkReusedMonFile_ok(self): + """A monthly file with the needed variables passes, with a list or all variables""" + monfile = self._monfile(["a", "b"]) + mclim.check_reused_mon_file(monfile, [self._daily], ["a"]) + mclim.check_reused_mon_file(monfile, [self._daily], None) + + def test_checkReusedMonFile_missing(self): + """A monthly file missing a requested variable aborts""" + monfile = self._monfile(["a"]) + with self.assertRaisesRegex(SystemExit, "is missing variables: c"): + mclim.check_reused_mon_file(monfile, [self._daily], ["a", "c"]) + with self.assertRaisesRegex(SystemExit, "is missing variables: b"): + mclim.check_reused_mon_file(monfile, [self._daily], None) + + +# +# Check some of the NCO (NetCDF Climate Operators) functions +# +class TestCheckNco(unittest.TestCase): + """Tests of check_nco""" + + def test_missingCommand(self): + """Abort naming the NCO commands that aren't found""" + # Replace shutil.which so that only ncrcat is "not found" + with mock.patch.object( + mclim.shutil, + "which", + # lambda is used here to have a small inline function to define the side effects + side_effect=lambda cmd: None if cmd == "ncrcat" else "/bin/x", + ): + with self.assertRaisesRegex(SystemExit, "NCO commands not found: ncrcat "): + mclim.check_nco() + + def test_allFound(self): + """No abort when all the commands are found""" + # Replace shutil.which so that all the commands are found + with mock.patch.object(mclim.shutil, "which", return_value="/bin/x"): + mclim.check_nco() + + +# +# Tests of the ncra command for record averaging +# +class TestNcraCommand(unittest.TestCase): + """Tests of ncra_command""" + + def setUp(self): + self._testdir = tempfile.mkdtemp() + self._out = os.path.join(self._testdir, "out.nc") + + def tearDown(self): + shutil.rmtree(self._testdir, ignore_errors=True) + + def test_varList(self): + """A variable list gives -v, and exclude is ignored""" + cmd = mclim.ncra_command(["f1", "f2"], self._out, ["a", "b"], exclude=["c"]) + self.assertEqual(cmd, ["ncra", "-O", "--hst", "-v", "a,b", "f1", "f2", "-o", self._out]) + + def test_allVarsExclude(self): + """All variables with exclude gives -x -v""" + cmd = mclim.ncra_command(["f1"], self._out, None, exclude=["c", "d"]) + self.assertEqual(cmd, ["ncra", "-O", "--hst", "-x", "-v", "c,d", "f1", "-o", self._out]) + + def test_allVars(self): + """All variables without exclude averages everything""" + cmd = mclim.ncra_command(["f1"], self._out) + self.assertEqual(cmd, ["ncra", "-O", "--hst", "f1", "-o", self._out]) + + def test_skipExisting(self): + """With skip_existing, an existing output file gives no command""" + expected = ["ncra", "-O", "--hst", "f1", "-o", self._out] + self.assertEqual(mclim.ncra_command(["f1"], self._out, skip_existing=True), expected) + with open(self._out, "w", encoding="utf-8"): + pass + self.assertEqual(mclim.ncra_command(["f1"], self._out, skip_existing=True), []) + self.assertEqual(mclim.ncra_command(["f1"], self._out), expected) + + +# +# Tests of running jobs +# +class TestRunJobs(unittest.TestCase): + """Tests of run_jobs (with a mock runner instead of running the commands)""" + + def test_allRun(self): + """Every non-empty command is run, with an error message naming its output file""" + # Create runner as a MagicMock so that it does nothing, but records each call + runner = mock.MagicMock() + # Run a job in one call sending it three different commands to run at the same time + commands = [ + ["a", "o1"], # run "a" creating file o1 + [], # empty command (output already exists) is skipped + ["b", "o2"], # run "b" creating file o2 + ] + mclim.run_jobs(commands, 2, runner=runner) + # Check that runner had recorded these two calls, and the appropriate error + runner.assert_has_calls( + [ + mock.call(["a", "o1"], "Failed creating o1"), + mock.call(["b", "o2"], "Failed creating o2"), + ], + any_order=True, # running jobs simultaneously we don't know which one will be first + ) + self.assertEqual(runner.call_count, 2) + + def test_oneJobInOrder(self): + """With one job at a time the commands run in order""" + # Create runner as a MagicMock so that it does nothing, but records each call + runner = mock.MagicMock() + commands = [[f"c{i}", f"o{i}"] for i in range(5)] + mclim.run_jobs(commands, 1, runner=runner) + # Check that the calls ran from runner match what's expected + self.assertEqual([call.args[0] for call in runner.call_args_list], commands) + + def test_noCommands(self): + """Only empty commands runs nothing""" + # Create runner as a MagicMock so that it does nothing, but records each call + runner = mock.MagicMock() + mclim.run_jobs([[], []], 4, runner=runner) + runner.assert_not_called() + + def test_failure(self): + """A failing command (the runner aborts) stops with SystemExit""" + + # Define a runner that aborts if the input command is "bad" + def runner(cmd, errmsg): + if cmd[0] == "bad": + sys.exit(errmsg) + + with self.assertRaisesRegex(SystemExit, "Failed creating o2"): + mclim.run_jobs([["good", "o1"], ["bad", "o2"], ["good", "o3"]], 2, runner=runner) + + +# +# Tests of the different output files +# +class TestFilenames(unittest.TestCase): + """Tests of output_filename, mon_file and clim_file""" + + def test_outputFilename(self): + """Zero-padded years and the creation date""" + self.assertEqual( + mclim.output_filename("/out", CASE, 100, 130, datetime.date(2026, 10, 3)), + os.path.join("/out", f"{CASE}.cpl.hx.atm.monclim.0100-0130_c20261003.nc"), + ) + + def test_intermediateFiles(self): + """Names of the monthly and climatology files""" + self.assertEqual(mclim.mon_file("/m", 100, 2), os.path.join("/m", "mon_0100-02.nc")) + self.assertEqual(mclim.clim_file("/m", 2), os.path.join("/m", "clim_02.nc")) + + +# +# Test file output for time and time and climatology bounds +# +class TestTimeValues(unittest.TestCase): + """Tests of month_bounds, mid_month_times and climatology_bounds_values""" + + def test_monthBounds(self): + """Start and end of each month of a noleap year""" + bounds = mclim.month_bounds() + self.assertEqual(len(bounds), 12) # Check that there is just 12 bounds for each month + self.assertEqual(bounds[0], (0, 31)) # January + self.assertEqual(bounds[1], (31, 59)) # February + self.assertEqual(bounds[-1], (334, 365)) # December (last month) + + def test_midMonthTimes(self): + """Middle of each month""" + times = mclim.mid_month_times() + self.assertEqual(times[0], 15.5) # January + self.assertEqual(times[1], 45.0) # February + self.assertEqual(times[-1], 349.5) # December (last month) + + def test_climatologyBounds_singleYear(self): + """Averaging only YEAR gives the bounds of each month of YEAR""" + self.assertEqual(mclim.climatology_bounds_values(1850, 1850, 1850), mclim.month_bounds()) + + def test_climatologyBounds_span(self): + """The bounds go from the month in BEGYEAR to the month in ENDYEAR, negative before YEAR""" + bounds = mclim.climatology_bounds_values(100, 130, 1850) + self.assertEqual(bounds[0], ((100 - 1850) * 365, (130 - 1850) * 365 + 31)) + # December ends at the start of ENDYEAR+1 + self.assertEqual(bounds[-1][1], (131 - 1850) * 365) + self.assertTrue(all(start < 0 and end < 0 for start, end in bounds)) + + +# +# Test setting of the time axis +# +class TestSetTimeAxis(unittest.TestCase): + """Tests of set_time_axis""" + + def setUp(self): + self._testdir = tempfile.mkdtemp() + self._file = os.path.join(self._testdir, "clim.nc") + + def tearDown(self): + shutil.rmtree(self._testdir, ignore_errors=True) + + def _write_clim(self, with_time_bnds=False): + """ + Write a 12-record file like the one from ncrcat, optionally with time_bnds + This is a utility function called both ways in later tests + """ + with Dataset(self._file, "w") as ncfile: + ncfile.createDimension("time", None) + time = ncfile.createVariable("time", "f8", ("time",)) + time.setncatts({"units": "days since 0001-01-01", "bounds": "time_bnds"}) + time.setncattr("cell_methods", "time: mean") + time[:] = np.arange(12.0) + if with_time_bnds: + ncfile.createDimension("ntb", 2) + time_bnds = ncfile.createVariable("time_bnds", "f8", ("time", "ntb")) + time_bnds.setncatts({"axis": "T", "calendar": "noleap", "bounds": "time_bnds"}) + time_bnds.setncattr("cell_methods", "time: mean") + time_bnds[:] = np.zeros((12, 2)) + + def _check(self): + """Check the time axis and climatology bounds after set_time_axis""" + mclim.set_time_axis(self._file, 1850, 2001, 2002) + units = "days since 1850-01-01 00:00:00" + with Dataset(self._file) as ncfile: + self.assertNotIn("time_bnds", ncfile.variables) + time = ncfile.variables["time"] + np.testing.assert_array_equal(time[:], mclim.mid_month_times()) + self.assertEqual(time.units, units) + self.assertEqual(time.calendar, "noleap") + self.assertEqual(time.climatology, "climatology_bounds") + self.assertNotIn("bounds", time.ncattrs()) + self.assertNotIn("cell_methods", time.ncattrs()) + bounds = ncfile.variables["climatology_bounds"] + self.assertEqual(bounds.dimensions, ("time", "ntb")) + np.testing.assert_array_equal( + bounds[:], mclim.climatology_bounds_values(2001, 2002, 1850) + ) + self.assertEqual(bounds.units, units) + for attr in ("axis", "calendar", "bounds", "cell_methods"): + self.assertNotIn(attr, bounds.ncattrs()) + + def test_withTimeBnds(self): + """time_bnds is renamed to climatology_bounds""" + self._write_clim(with_time_bnds=True) + self._check() + + def test_withoutTimeBnds(self): + """climatology_bounds is created when there is no time_bnds""" + self._write_clim() + self._check() + self._write_clim(with_time_bnds=False) + self._check() + + +# +# Test the copy of the grid variables (the ALWAYS_VARS) +# +class TestCopyGridVars(unittest.TestCase): + """Tests of copy_grid_vars""" + + def setUp(self): + self._testdir = tempfile.mkdtemp() + self._src = os.path.join(self._testdir, "daily.nc") + self._dst = os.path.join(self._testdir, "clim.nc") + # Create a CPLHIST history file like from CMEPS: + # float lon/lat on (time, ny, nx) with a fill value and attributes + with Dataset(self._src, "w") as ncfile: + ncfile.createDimension("time", None) + ncfile.createDimension("atmImp_ny", 1) + ncfile.createDimension("atmImp_nx", 3) + for name, base in (("atmImp_lon", 10.0), ("atmImp_lat", -60.0)): + var = ncfile.createVariable( + name, "f4", ("time", "atmImp_ny", "atmImp_nx"), fill_value=1.0e30 + ) + var.setncatts({"long_name": name, "units": "degrees"}) + var.setncattr("cell_methods", "time: mean") + # Different values for the second time, so the first time slice can be checked + var[0] = base + np.arange(3.0).reshape(1, 3) + var[1] = -999.0 + # The destination has atmImp_ny but not atmImp_nx + with Dataset(self._dst, "w") as ncfile: + ncfile.createDimension("time", None) + ncfile.createDimension("atmImp_ny", 1) + + def tearDown(self): + shutil.rmtree(self._testdir, ignore_errors=True) + + def test_copyGridVars(self): + """Copied without time, with the first time slice, attributes and fill value""" + mclim.copy_grid_vars(self._src, self._dst, ["atmImp_lon", "atmImp_lat"]) + with Dataset(self._dst) as ncfile: + self.assertEqual(len(ncfile.dimensions["atmImp_nx"]), 3) + for name, base in (("atmImp_lon", 10.0), ("atmImp_lat", -60.0)): + var = ncfile.variables[name] + self.assertEqual(var.dimensions, ("atmImp_ny", "atmImp_nx")) + self.assertEqual(var.dtype, np.float32) + self.assertAlmostEqual(float(var.getncattr("_FillValue")), 1.0e30, delta=1.0e24) + self.assertEqual(var.long_name, name) + self.assertEqual(var.units, "degrees") + self.assertNotIn("cell_methods", var.ncattrs()) + np.testing.assert_array_equal(var[:], base + np.arange(3.0).reshape(1, 3)) + + +# +# Test that adding variable attributes works correctly +# +class TestAddVarAttributes(unittest.TestCase): + """Tests of add_var_attributes""" + + def setUp(self): + self._testdir = tempfile.mkdtemp() + self._file = os.path.join(self._testdir, "clim.nc") + lon, lat = mclim.ALWAYS_VARS + _write_nc( + self._file, + { + "time": (("time",), {}), + "climatology_bounds": (("time", "n"), {}), + lon: (("n",), {"cell_methods": "time: mean"}), + lat: (("n",), {}), + "a": (("time", "n"), {"standard_name": "a", "cell_methods": "time: mean"}), + "b": (("time", "n"), {"long_name": "Keep this name"}), + "c": (("n",), {}), + }, + ) + + def tearDown(self): + shutil.rmtree(self._testdir, ignore_errors=True) + + def test_addVarAttributes(self): + """Only the data variables on time get the climatology attributes""" + mclim.add_var_attributes(self._file) + cell_methods = "time: mean within years time: mean over years" + with Dataset(self._file) as ncfile: + for name in ("a", "b"): + var = ncfile.variables[name] + self.assertEqual(var.cell_methods, cell_methods) + self.assertEqual(var.coordinates, " ".join(mclim.ALWAYS_VARS)) + self.assertNotIn("standard_name", var.ncattrs()) + self.assertEqual(ncfile.variables["a"].long_name, "a") + self.assertEqual(ncfile.variables["b"].long_name, "Keep this name") + for name in ["time", "climatology_bounds", "c"] + mclim.ALWAYS_VARS: + self.assertNotIn("cell_methods", ncfile.variables[name].ncattrs()) + self.assertNotIn("coordinates", ncfile.variables[name].ncattrs()) + + +# +# Test the submission to the batch queue +# +class TestSubmitBatch(unittest.TestCase): + """Tests of submit_batch""" + + def test_submitBatch(self): + """ + Test submit_batch that qsub gets the queue and the script on stdin, + and the job id is returned + """ + result = subprocess.CompletedProcess([], 0, stdout="1234.desched1\n", stderr="") + # Replace shutil.which to return the qsub path + # and subprocess.run to return the result without running qsub + with mock.patch.object(mclim.shutil, "which", return_value="/bin/qsub"), mock.patch.object( + mclim.subprocess, "run", return_value=result + ) as run: + self.assertEqual(mclim.submit_batch("the script", "develop"), "1234.desched1") + self.assertEqual(run.call_args.args[0], ["qsub", "-q", "develop"]) + self.assertEqual(run.call_args.kwargs["input"], "the script") + + def test_submitBatch_fails(self): + """Test that submit_batch aborts if qsub fails""" + # Create a result that mimics a qsub error + result = subprocess.CompletedProcess([], 1, stdout="", stderr="qsub: bad account") + # Replace shutil.which to return the qsub path + # and subprocess.run to return the result without running qsub + with mock.patch.object(mclim.shutil, "which", return_value="/bin/qsub"), mock.patch.object( + mclim.subprocess, "run", return_value=result + ): + with self.assertRaisesRegex(SystemExit, "qsub failed:\nqsub: bad account"): + mclim.submit_batch("the script", "main") + + def test_submitBatch_noQsub(self): + """Abort if qsub isn't found""" + # Replace shutil.which to return None, as it does when the command isn't found + with mock.patch.object(mclim.shutil, "which", return_value=None): + with self.assertRaisesRegex(SystemExit, "qsub not found"): + mclim.submit_batch("the script", "main") + + +if __name__ == "__main__": + unit_testing.setup_for_tests() + unittest.main() diff --git a/python/ctsm/toolchain/gen_mksurfdata_jobscript_single.py b/python/ctsm/toolchain/gen_mksurfdata_jobscript_single.py index 1413e49158..7d53607287 100755 --- a/python/ctsm/toolchain/gen_mksurfdata_jobscript_single.py +++ b/python/ctsm/toolchain/gen_mksurfdata_jobscript_single.py @@ -152,9 +152,12 @@ def write_runscript_part1( runfile, descrip="input namelist", name="mksurfdata", + comment=None, ): """ Write run script (part 1) Batch headers + + comment: if given, replaces the default description line written after the batch headers """ runfile.write("#!/bin/bash\n") runfile.write("# Edit the batch directives for your batch system\n") @@ -196,9 +199,11 @@ def write_runscript_part1( runfile.write(f"cd {tool_path}\n") runfile.write("\n") - runfile.write( - f"# This is a batch script to run a set of resolutions for mksurfdata_esmf {descrip}\n" - ) + if comment is None: + comment = ( + f"This is a batch script to run a set of resolutions for mksurfdata_esmf {descrip}" + ) + runfile.write(f"# {comment}\n") runfile.write( "# NOTE: THIS SCRIPT IS AUTOMATICALLY GENERATED " + "SO IN GENERAL YOU SHOULD NOT EDIT it!!\n\n" diff --git a/tools/cplhist/aero_1850_monthly_clim b/tools/cplhist/aero_1850_monthly_clim new file mode 100755 index 0000000000..c7ecab1a97 --- /dev/null +++ b/tools/cplhist/aero_1850_monthly_clim @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +""" +This is a just top-level skeleton script that calls +aero_1850_monthly_clim.py. +The original code (aero_1850_monthly_clim.py, using cplhist_monthly_clim.py) is located under the +python/ctsm/cplhist folder. + +It creates a 12-month climatology of the aerosol deposition fields from +daily averaged CMEPS coupler history (CPLHIST) files, for use by DATM. + +For full instructions on how to run the code and different options, +please check the python/ctsm/cplhist/aero_1850_monthly_clim.py file. + +To run this script the following packages are required: + - netCDF4 + - the NCO commands ncra, ncrcat and ncatted +---------------------------------------------------------------- +To see all available options for aero_1850_monthly_clim + ./aero_1850_monthly_clim --help +---------------------------------------------------------------- +Instructions for running using the conda python environments +and NCO on Derecho: +module load conda nco +../../py_env_create +conda activate ctsm_pylib +""" + +import os +import sys + +# -- add python/ctsm to path +_CTSM_PYTHON = os.path.join( + os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir, "python" +) +sys.path.insert(1, _CTSM_PYTHON) + +from ctsm.cplhist.aero_1850_monthly_clim import main + +if __name__ == "__main__": + main()