diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml index 5558eb3..cf6bfb8 100644 --- a/.github/workflows/python-package.yml +++ b/.github/workflows/python-package.yml @@ -25,6 +25,8 @@ jobs: pixi-env: py313dev - python-version: "3.14" pixi-env: py314dev + - python-version: "3.15" + pixi-env: py315dev steps: - uses: actions/checkout@v7 diff --git a/config/zppy_template_r05.jinja b/config/zppy_template_r05.jinja index 7f8d3a5..1d30ffd 100644 --- a/config/zppy_template_r05.jinja +++ b/config/zppy_template_r05.jinja @@ -46,6 +46,13 @@ common_snow: &common_snow References: - {{ livvproj_dir }}/livvkit.bib +common_river: &common_river + cmap: YlGnBu + cmap_diff: BrBG + units: m^3 s^-1 + References: + - {{ livvproj_dir }}/livvkit.bib + common_energy: &common_energy desc: Surface energy balance component {component}{comment} from {data_var_names} references: @@ -63,7 +70,17 @@ common_elm: &common_elm ts_file_patterns: model: "{_var}_{year_s:04d}01_{year_e:04d}12.nc" masks: - model: /global/cfs/cdirs/e3sm/diagnostics/livvkit_data/grids/msk_{icesheet}_rcm_r05.nc + model: {{ livvproj_dir }}/grids/msk_{icesheet}_rcm_r05.nc + +common_mosart: &common_mosart + climo_river: {{ dir_river }}/{{ case_id }}_{clim}_{sea_s}_{sea_e}_climo.nc + dataset_names: { model: MOSART } + timeseries_dirs: + model: "{{ dir_ts_river }}" + ts_file_patterns: + model: "{_var}_{year_s:04d}01_{year_e:04d}12.nc" + masks: + model: {{ livvproj_dir }}/grids/msk_{icesheet}_rcm_r05.nc common_racmo: &common_racmo clim_years: @@ -155,8 +172,8 @@ common_modis: &common_modis in_dirs: {dset_a: /global/cfs/cdirs/e3sm/zender/mod10cm/rgr/} file_patterns: {dset_a: 'mod10cm_{season}_{sea_s}_{sea_e}_climo.nc'} masks: - dset_a: /global/cfs/cdirs/e3sm/diagnostics/livvkit_data/grids/msk_{icesheet}_rcm_r05.nc - model: /global/cfs/cdirs/e3sm/diagnostics/livvkit_data/grids/msk_{icesheet}_rcm_r05.nc + dset_a: {{ livvproj_dir }}/grids/msk_{icesheet}_rcm_r05.nc + model: {{ livvproj_dir }}/grids/msk_{icesheet}_rcm_r05.nc common_racmo_gis: &common_racmo_gis climo_remap: {{ dir_racmo_gis }}/{{ case_id }}_{clim}_{sea_s}_{sea_e}_climo.nc @@ -407,6 +424,30 @@ common_snow_cover_vars: &common_snow_cover_vars cmax: 100 cmap: YlGnBu +common_river_vars: &common_river_vars + - title: "Total discharge to ocean: ice" + model: TOTAL_DISCHARGE_TO_OCEAN_ICE + sign: 1 + scales: {model: 1} + units: "m^3 s^-1" + ac_axis: 0 + cmin: 0.0 + # cmax: 5000 + cmap: YlGnBu + # cmin_d: -8000 + # cmax_d: 8000 + - title: "Total discharge to ocean: liquid" + model: TOTAL_DISCHARGE_TO_OCEAN_LIQ + sign: 1 + scales: {model: 1} + units: "m^3 s^-1" + ac_axis: 0 + cmin: 0.0 + # cmax: 5000 + cmap: YlGnBu + # cmin_d: -8000 + # cmax_d: 8000 + common_racmo_energy_vars: &common_racmo_energy_vars - title: Surface temperature dset_a: tas @@ -771,7 +812,21 @@ Snow_Cover_GIS: primary_var: FSNO desc: "{component} snow cover from {data_var_names}" references: - - /global/cfs/cdirs/e3sm/diagnostics/livvkit_data/livvkit.bib + - {{ livvproj_dir }}/livvkit.bib +{% endif %} + +{% if river %} +River_Discharge_GIS: + module: /global/homes/m/mek/livvext/livvext/river/river.py + data_vars: *common_river_vars + icesheet: gis + <<: [*common, *common_river, *common_mosart] + scales: + { model: 1,} + primary_var: TOTAL_DISCHARGE_TO_OCEAN_LIQ + desc: "{component} river discharge from {data_var_names}" + references: + - {{ livvproj_dir }}/livvkit.bib {% endif %} {% if energy_racmo %} @@ -856,7 +911,21 @@ Snow_Cover_AIS: desc: "{component} snow storage from {data_var_names}" icesheet: ais references: - - /global/cfs/cdirs/e3sm/diagnostics/livvkit_data/livvkit.bib + - {{ livvproj_dir }}/livvkit.bib +{% endif %} + +{% if river %} +River_Discharge_AIS: + module: /global/homes/m/mek/livvext/livvext/river/river.py + data_vars: *common_river_vars + icesheet: ais + <<: [*common, *common_mosart, *common_river,] + scales: + { model: 1,} + primary_var: TOTAL_DISCHARGE_TO_OCEAN_LIQ + desc: "{component} river discharge from {data_var_names}" + references: + - {{ livvproj_dir }}/livvkit.bib {% endif %} {% if energy_racmo %} diff --git a/livvext/__init__.py b/livvext/__init__.py index 1de0aa2..aec13f0 100644 --- a/livvext/__init__.py +++ b/livvext/__init__.py @@ -31,5 +31,5 @@ Storage for global variables. These are set upon startup in the options module """ -__version_info__ = (1, 2, 0) +__version_info__ = (1, 3, 0) __version__ = ".".join(str(vi) for vi in __version_info__) diff --git a/livvext/compare_gridded.py b/livvext/compare_gridded.py index f77235a..039a067 100644 --- a/livvext/compare_gridded.py +++ b/livvext/compare_gridded.py @@ -127,13 +127,20 @@ def annotate_plot( _text = f"Avg.\n{cnrtxt}" elif stats is not None: _text = "" - for _stat in ["min", "max", "avg"]: + if "tot" in stats: + _text += f"Tot: {stats['tot']:.3g}\n{stats.get('aavg_units')}\n" + else: + _text += f"Avg: {stats['avg']:.3g}\n" + + for _stat in ["min", "max"]: _text += f"{_stat.capitalize()}: {stats[_stat]:.3g}\n" if "units" in stats: _text += stats["units"] else: _text = _text[:-1] + else: + _text = "" plt.figtext( 0.98, @@ -246,11 +253,14 @@ def main(args: argparse.Namespace, config: dict, sea: str | int = "ANN"): all_data["model"] = xr.open_dataset( lxc.proc_climo_file(config, "climo_remap", sea) ) + elif "climo_river" in config: + all_data["model"] = xr.open_dataset( + lxc.proc_climo_file(config, "climo_river", sea) + ) else: all_data["model"] = xr.open_dataset( lxc.proc_climo_file(config, "climo", sea) ) - for _vers in all_data: all_data[_vers] = lxc.check_longitude(all_data[_vers]) @@ -352,18 +362,20 @@ def main(args: argparse.Namespace, config: dict, sea: str | int = "ANN"): sum_out=_do_sum, land_only=config.get("mask_ocean", {}).get(_vers, False), ) - all_stats[_vers] = { - "min": np.nanmin(_plt_data[_vers]), - "max": np.nanmax(_plt_data[_vers]), - "avg": all_aavg[_vers], - } - all_aavg[_vers] *= _aavg_scale - for _stat in all_stats[_vers]: - all_stats[_vers][_stat] *= _aavg_scale + if _do_sum: + _avgkey = "tot" + else: + _avgkey = "avg" + # Sometimes area average, sometimes area sum is the "mean" measure + all_stats[_vers] = {_avgkey: all_aavg[_vers]} + + # for _stat in all_stats[_vers]: + # all_stats[_vers][_stat] *= _aavg_scale if all_stats.get("aavg_units"): - all_stats[_vers]["units"] = all_stats.get("aavg_units") + all_stats[_vers]["aavg_units"] = all_stats.get("aavg_units") + all_stats[_vers]["units"] = _units aavg_out[data_var["title"]] = { config["dataset_names"][_vers]: all_aavg[_vers] for _vers in all_aavg @@ -379,17 +391,20 @@ def main(args: argparse.Namespace, config: dict, sea: str | int = "ANN"): sum_out=_do_sum, land_only=config.get("mask_ocean", {}).get(_ds2, False), ) - diffs_stats[_diffname] = { - "min": np.nanmin(diffs[_diffname]), - "max": np.nanmax(diffs[_diffname]), - "avg": diffs_aavg[_diffname], - } + + if _do_sum: + _avgkey = "tot" + else: + _avgkey = "avg" diffs_aavg[_diffname] *= _aavg_scale - for _stat in diffs_stats[_diffname]: - diffs_stats[_diffname][_stat] *= _aavg_scale + diffs_stats[_diffname] = {_avgkey: diffs_aavg[_diffname]} + + # for _stat in diffs_stats[_diffname]: + # diffs_stats[_diffname][_stat] *= _aavg_scale if diffs_stats.get("aavg_units"): - diffs_stats[_diffname]["units"] = diffs_stats.get("aavg_units") + diffs_stats[_diffname]["aavg_units"] = diffs_stats.get("aavg_units") + diffs_stats[_diffname]["units"] = _units _longname = ( f"{config['dataset_names'][_ds1]} - {config['dataset_names'][_ds2]}" @@ -483,6 +498,12 @@ def main(args: argparse.Namespace, config: dict, sea: str | int = "ANN"): ndsets = len(dsets) _comment = "" for idx, _vers in enumerate(dsets_to_plot): + all_stats[_vers].update( + { + "min": np.nanmin(_plt_data[_vers]), + "max": np.nanmax(_plt_data[_vers]), + } + ) _cf = axes[idx].pcolormesh( all_data[_vers]["lon"], all_data[_vers]["lat"], @@ -533,6 +554,12 @@ def main(args: argparse.Namespace, config: dict, sea: str | int = "ANN"): else: cnrtxt = f"{diffs_aavg[_diffnm]:.2f}" + diffs_stats[_diffnm].update( + { + "min": np.nanmin(diffs[_diffnm]), + "max": np.nanmax(diffs[_diffnm]), + } + ) _cfd = axes[n_dsets_to_plot + idx].pcolormesh( all_data[_ds1]["lon"], all_data[_ds1]["lat"], diff --git a/livvext/energy/energy.py b/livvext/energy/energy.py index 0311b2e..ab26820 100644 --- a/livvext/energy/energy.py +++ b/livvext/energy/energy.py @@ -78,9 +78,9 @@ def run(name, config): elements = [] if "meta" in config: - run_summary = el.Table( - title="Case Summary", data=config["meta"], transpose=True - ) + meta = utils.climo_meta_update(config) + + run_summary = el.Table(title="Case Summary", data=meta, transpose=True) else: run_summary = el.RawHTML("

Case Summary

") diff --git a/livvext/generate_cfg.py b/livvext/generate_cfg.py index 408a984..f483b5d 100644 --- a/livvext/generate_cfg.py +++ b/livvext/generate_cfg.py @@ -184,6 +184,12 @@ def main(): _ts_dir = _grid_dir.replace("/clim/", "/ts/monthly/") climo_dirs[f"dir_{_grid}"] = Path(_grid_dir) ts_dirs[f"dir_ts_{_grid}"] = Path(_ts_dir) + climo_dirs["dir_river"] = Path( + str(climo_dirs["dir_native"]).replace("lnd", "rof") + ) + ts_dirs["dir_ts_river"] = Path( + str(ts_dirs["dir_ts_native"]).replace("lnd", "rof") + ) case_dir = Path(cl_args.casedir) diff --git a/livvext/river/__init__.py b/livvext/river/__init__.py new file mode 100644 index 0000000..7f751e4 --- /dev/null +++ b/livvext/river/__init__.py @@ -0,0 +1 @@ +"""Module for analyzing river discharge over an ice sheet""" diff --git a/livvext/river/river.py b/livvext/river/river.py new file mode 100644 index 0000000..c09312a --- /dev/null +++ b/livvext/river/river.py @@ -0,0 +1,260 @@ +# Copyright (c) 2015,2016, UT-BATTELLE, LLC +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# 3. Neither the name of the copyright holder nor the names of its contributors +# may be used to endorse or promote products derived from this software without +# specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""An analysis of the Models's river discharge over GIS / AIS.""" + + +# from __future__ import absolute_import, division, print_function, unicode_literals + +import argparse +import os +from pathlib import Path + +import livvkit +import pandas as pd +from livvkit import elements as el +from loguru import logger + +from livvext import compare_gridded, time_series_plot, utils +from livvext.common import SEASON_NAME +from livvext.common import summarize_result as sum_res + +PAGE_DOCS = { + "gis": "An analysis of the Models's river discharge over Greenland.", + "ais": "An analysis of the Models's river discharge over Antarctica.", +} + +base_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") + + +def run(name, config): + """ + Runs the extension. + + Args: + name: The name of the extension + config: A dictionary representation of the configuration file + + Returns: + A LIVVkit page element containing the LIVVkit elements to display on a webpage + + """ + img_dir = Path(livvkit.output_dir, "validation", "imgs", name) + logger.info(f"Starting RIVER DISCHARGE ANALYSIS WITH OUTPUT TO {img_dir}") + if not img_dir.exists(): + img_dir.mkdir(parents=True) + + img_dir = str(img_dir) + config_arg_list = [] + for key, val in config.items(): + config_arg_list.extend(["--" + key, str(val)]) + config_arg_list.extend(["--out", img_dir]) + args = parse_args(config_arg_list) + + elements = [] + + if "meta" in config: + meta = utils.climo_meta_update(config) + + run_summary = el.Table(title="Case Summary", data=meta, transpose=True) + + else: + run_summary = el.RawHTML("

Case Summary

") + + images = {} + tables = {} + + for season in ["ANN", "DJF", "MAM", "JJA", "SON"]: + logger.info( + f"PLOTTING COMPARE GRIDDED FOR {config.get('icesheet', '')} {season}" + ) + _plots, aavgs = compare_gridded.main(args, config, sea=season) + images[season] = _plots + + aavgs = aavgs.apply( + lambda x: pd.Series([f"{xi:.2f}" for xi in x], index=x.index) + ) + + table_el = el.Table( + title="Area weighted averages of river discharge variables.", + data=aavgs, + transpose=True, + ) + tables[season] = table_el + logger.info( + "FINISHED PLOTTING COMPARE GRIDDED FOR " + f"{config.get('icesheet', '')} {season}" + ) + + timeseries_img = [] + if "timeseries_dirs" in config: + logger.info(f"PLOTTING TIMESERIES FOR {config.get('icesheet', '')}") + timeseries_img.extend(time_series_plot.main(args, config)) + logger.info(f"FINISHED PLOTTING TIMESERIES FOR {config.get('icesheet', '')}") + + tabs = {} + + # for season in images: + # tabs[season] = [ + # tables[season], + # el.Gallery( + # f"River discharge components {SEASON_NAME[season]} ({season})", + # images[season], + # ), + # ] + frames = { + _sea: pd.DataFrame(tables[_sea].data, index=tables[_sea].index).T + for _sea in tables + } + frames = pd.concat(frames) + table_combined = el.Table(tables["ANN"].title, data=frames) + tabs["Spatial"] = [table_combined] + tabs["Spatial"].extend( + [ + el.Section( + season, + [ + el.Gallery( + f"River discharge components {SEASON_NAME[season]} ({season})", + images[season], + ), + ], + ) + for season in images + ] + ) + + if timeseries_img: + tabs["Timeseries"] = [el.Gallery("Figures", timeseries_img)] + + if "references" in config: + ref_bib = utils.bib2html(config.get("references")) + elif "References" in config: + ref_bib = utils.bib2html(config.get("References")) + else: + ref_bib = " " + + ref_ele = el.RawHTML( + " ".join( + [ + '

References

', + "If you use this LIVVkit extension for any part of your", + "modeling or analyses, please cite:" + ref_bib + "
", + ] + ) + ) + tabs["References"] = [ref_ele] + elements = [run_summary, el.Tabs(tabs)] + + logger.info(f"FINISHED RIVER DISCHARGE ANALYSIS WITH OUTPUT TO {img_dir}") + return el.Page(name, PAGE_DOCS[config.get("icesheet", "gis")], elements) + + +def print_summary(summary): + """ + Print out a summary generated by this module's summarize_result method + """ + for ele in summary: + print(f"\tCompleted: {ele}") + + +def summarize_result(result): + """Use the summarize_result from livvext.common to summarize.""" + return sum_res(result) + + +def rel_base_path(_file): + _file = os.path.relpath(os.path.join(base_path, _file)) + return _file + + +def parse_args(args=None): + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter + ) + + parser.add_argument( + "--elevation", + type=rel_base_path, + help="Ice sheet elevation in model.", + ) + + parser.add_argument( + "--latlon", + type=rel_base_path, + help="Ice sheet latlon grid in model.", + ) + + parser.add_argument( + "--climo", + type=rel_base_path, + help="Climotology from model.", + ) + + parser.add_argument( + "--out", + default="outputs", + type=rel_base_path, + help="The output directory for the figures.", + ) + + parser.add_argument( + "--latv", default="lat", type=str, help="Latitude variable name" + ) + + parser.add_argument( + "--lonv", default="lon", type=str, help="Longitude variable name" + ) + + parser.add_argument( + "--smbv", default="QICE", type=str, help="Surface mass balance variable name" + ) + + parser.add_argument( + "--topov", default="topo", type=str, help="Topography variable name" + ) + + parser.add_argument( + "--landfracv", default="landfrac", type=str, help="Land fraction variable name" + ) + + parser.add_argument( + "--maskv", default="gis_mask2", type=str, help="Ice sheet mask variable name" + ) + + args, _ = parser.parse_known_args(args) + args.img_height = 300 + + return args + + +def populate_metadata(): + """ + Generates the metadata needed for the output summary page + """ + return {"Type": "Summary", "Title": "Validation", "Headers": []} diff --git a/livvext/smb/smb_icecores.py b/livvext/smb/smb_icecores.py index 167e2b2..d0c63f6 100644 --- a/livvext/smb/smb_icecores.py +++ b/livvext/smb/smb_icecores.py @@ -176,9 +176,9 @@ def _format_table(x): ) if "meta" in config: - run_summary = el.Table( - title="Case Summary", data=config["meta"], transpose=True - ) + meta = utils.climo_meta_update(config) + + run_summary = el.Table(title="Case Summary", data=meta, transpose=True) else: run_summary = el.RawHTML("

Case Summary

") diff --git a/livvext/snow/snow.py b/livvext/snow/snow.py index e073891..6e5384b 100644 --- a/livvext/snow/snow.py +++ b/livvext/snow/snow.py @@ -78,9 +78,9 @@ def run(name, config): elements = [] if "meta" in config: - run_summary = el.Table( - title="Case Summary", data=config["meta"], transpose=True - ) + meta = utils.climo_meta_update(config) + + run_summary = el.Table(title="Case Summary", data=meta, transpose=True) else: run_summary = el.RawHTML("

Case Summary

") diff --git a/livvext/utils.py b/livvext/utils.py index 53260a2..bd35c08 100644 --- a/livvext/utils.py +++ b/livvext/utils.py @@ -306,3 +306,46 @@ def will_it_float(test_str: str) -> bool: except ValueError: _will = False return _will + + +def climo_meta_update(config, dset_tag="dset_a"): + """ + Extract the start / end years of reanalysis climatology to put in metadata table. + + Parameters + ---------- + config : `dict` + LIVVkit configuration dictionary (should contain ``meta``, ``dataset_names``, + and ``clim_years``) + + dset_tag : `str` + Tag for dataset (default is ``dset_a``, but could be ``dset_(b, c, ...)``) + + Returns + ------- + meta : `dict` + Updated metadata for LIVVkit validation page with climatology years for the + ``dset_tag`` dataset + + """ + meta = config.get("meta") + _clim_years = config.get("clim_years") + if _clim_years is not None: + try: + _dset_name = config.get("dataset_names").get(dset_tag) + # Will except if "dataset_names" isn't there, or + # `dset_tag`` not in dataset_names, so just default (shouldn't happen, but) + # would rather default to a generic name than crash the whole module + except (KeyError, AttributeError): + _dset_name = "Comparison dataset?" + _years = _clim_years.get(dset_tag, {"year_s": -1, "year_e": -1}) + _year_fmt = f"{_years['year_s']} - {_years['year_e']}" + + meta[f"{_dset_name} years"] = [_year_fmt] + + # This is legacy, pop the climatology years tag from the metadata so the wrong + # info doesn't appear in the table + if "Climatology years" in meta: + meta.pop("Climatology years") + + return meta diff --git a/pyproject.toml b/pyproject.toml index fda0df3..0e58100 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -60,7 +60,7 @@ dependencies = [ "pybtex>=0.25.1", "f90nml>=1.5", "loguru>=0.7.3", - "livvkit>=3.4.0", + "livvkit>=3.4.1", ] classifiers = [ @@ -131,6 +131,9 @@ python = "3.13.*" [tool.pixi.feature.py314dev.dependencies] python = "3.14.*" +[tool.pixi.feature.py315dev.dependencies] +python = "3.15.*" + [tool.pixi.environments] default = { solve-group = "default" } dev = ["dev"] @@ -139,6 +142,7 @@ py311dev = ["py311dev", "dev"] py312dev = ["py312dev", "dev"] py313dev = ["py313dev", "dev"] py314dev = ["py314dev", "dev"] +py315dev = ["py315dev", "dev"] buildenv = ["buildenv"] [dependency-groups]