diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index df68a07..513c254 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -8,16 +8,16 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - name: Set up Python - uses: actions/setup-python@v5 + uses: actions/setup-python@v7 with: python-version: 3.14 - name: Set up Pixi ${{ matrix.python-version }} - uses: prefix-dev/setup-pixi@v0.9.4 + uses: prefix-dev/setup-pixi@v0.10.0 with: - pixi-version: v0.62.2 + pixi-version: v0.76.2 # Project environment caching uses pixi.lock as the cache key input. # If you don't commit a lockfile, disable caching to avoid ENOENT. # cache: ${{ hashFiles('pixi.lock') != '' }} @@ -33,7 +33,7 @@ jobs: --config pyproject.toml - name: Push API documentation to Github Pages - uses: peaceiris/actions-gh-pages@v3 + uses: peaceiris/actions-gh-pages@v4 with: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: ./docs diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index 4a02a37..0f5e04f 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -16,11 +16,11 @@ jobs: timeout-minutes: 2 steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Set up python - uses: actions/setup-python@v5 + uses: actions/setup-python@v7 with: - python-version: 3.13 + python-version: 3.14 - name: Runs pre-commit run: | pip install pre-commit diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index a7e4e6c..5fac034 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -20,12 +20,12 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - name: Set up Pixi - uses: prefix-dev/setup-pixi@v0.9.4 + uses: prefix-dev/setup-pixi@v0.10.0 with: - pixi-version: v0.62.2 + pixi-version: v0.76.2 environments: buildenv - name: Build release distributions @@ -34,7 +34,7 @@ jobs: pixi run -e buildenv python -m build - name: Upload distributions - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: release-dists path: dist/ @@ -60,7 +60,7 @@ jobs: steps: - name: Retrieve release distributions - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v8 with: name: release-dists path: dist/ diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml index 0e062a2..5558eb3 100644 --- a/.github/workflows/python-package.yml +++ b/.github/workflows/python-package.yml @@ -27,7 +27,7 @@ jobs: pixi-env: py314dev steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - name: Set up Pixi ${{ matrix.python-version }} uses: prefix-dev/setup-pixi@v0.9.4 with: diff --git a/config/zppy_template_r05.jinja b/config/zppy_template_r05.jinja index f6a5da1..7f8d3a5 100644 --- a/config/zppy_template_r05.jinja +++ b/config/zppy_template_r05.jinja @@ -5,6 +5,9 @@ common: &common Case ID: [{{ case_id }}] Climatology years: [1980-2020] Model: [E3SM-ELM] +{% endraw %} + Model years: [{{ year1 }} - {{ year2 }}] +{% raw %} climo: {{ dir_native }}/{{ case_id }}_{clim}_{sea_s}_{sea_e}_climo.nc latlon: &climo_ann_file {{ dir_native }}/{{ case_id }}_ANN_{sea_s}_{sea_e}_climo.nc @@ -18,11 +21,11 @@ common: &common topov: topo landfracv: landfrac img_height: 300 - {% endraw %} +{% endraw %} # These come from zppy year_s: {{ year1 }} year_e: {{ year2 }} - {% raw %} +{% raw %} common_smb: &common_smb smbv: QICE @@ -36,6 +39,13 @@ common_smb: &common_smb - {{ livvproj_dir }}/smb/smb_icecores.bib - {{ livvproj_dir }}/livvkit.bib +common_snow: &common_snow + cmap: YlGnBu + cmap_diff: BrBG + units: mm + References: + - {{ livvproj_dir }}/livvkit.bib + common_energy: &common_energy desc: Surface energy balance component {component}{comment} from {data_var_names} references: @@ -46,6 +56,15 @@ common_energy: &common_energy cmap: plasma cmap_diff: RdBu_r +common_elm: &common_elm + dataset_names: { model: ELM } + timeseries_dirs: + model: "{{ dir_ts_native }}" + 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 + common_racmo: &common_racmo clim_years: dset_a: { year_s: 1980, year_e: 2020 } @@ -57,8 +76,8 @@ common_racmo: &common_racmo model: "{{ dir_ts_native }}" dset_a: "{{ racmo_root_dir }}/ts" ts_file_patterns: - model: "{_var}_{year_s}01_{year_e}12.nc" - dset_a: "{_var}_{icesheet}_{year_s}01_{year_e}12.nc" + model: "{_var}_{year_s:04d}01_{year_e:04d}12.nc" + dset_a: "{_var}_{icesheet}_{year_s:04d}01_{year_e:04d}12.nc" masks: dset_a: {{ livvproj_dir }}/grids/msk_{icesheet}_r025_rcm.nc model: {{ livvproj_dir }}/grids/msk_{icesheet}_r025_rcm.nc @@ -73,6 +92,12 @@ common_era5: &common_era5 dset_a: { year_s: 1979, year_e: 2019} in_dirs: {dset_a: {{ e3sm_diags_data_dir }}/observations/Atm/climatology/ERA5} file_patterns: {dset_a: 'ERA5_{season}_{sea_s}_{sea_e}_climo.nc'} + timeseries_dirs: + model: "{{ dir_ts_native }}" + dset_a: "{{ e3sm_diags_data_dir }}/observations/Atm/time-series/ERA5" + ts_file_patterns: + model: "{_var}_{year_s:04d}01_{year_e:04d}12.nc" + dset_a: "{_var}_{year_s:04d}01_{year_e:04d}12.nc" masks: dset_a: {{ livvproj_dir }}/grids/msk_{icesheet}_r025_remap_era5.traave.nc model_remap: {{ livvproj_dir }}/grids/msk_{icesheet}_r025_remap_era5.traave.nc @@ -82,6 +107,12 @@ common_merra: &common_merra climo_remap: {{ dir_merra2 }}/{{ case_id }}_{clim}_{sea_s}_{sea_e}_climo.nc in_dirs: {dset_a: {{ e3sm_diags_data_dir }}/observations/Atm/climatology/MERRA2} file_patterns: {dset_a: 'MERRA2_{season}_{sea_s}_{sea_e}_climo.nc'} + timeseries_dirs: + model: "{{ dir_ts_native }}" + dset_a: "{{ e3sm_diags_data_dir }}/observations/Atm/time-series/MERRA2" + ts_file_patterns: + model: "{_var}_{year_s:04d}01_{year_e:04d}12.nc" + dset_a: "{_var}_{year_s:04d}01_{year_e:04d}12.nc" masks: dset_a: {{ livvproj_dir }}/grids/msk_{icesheet}_r025_remap_merra2.traave.nc model_remap: {{ livvproj_dir }}/grids/msk_{icesheet}_r025_remap_merra2.traave.nc @@ -100,6 +131,12 @@ common_ceres: &common_ceres scales: { model: 1, dset_a: 1 } clim_years: dset_a: { year_s: 2001, year_e: 2018 } + timeseries_dirs: + model: "{{ dir_ts_native }}" + dset_a: "{{ e3sm_diags_data_dir }}/observations/Atm/time-series/ceres_ebaf_surface_v4.1" + ts_file_patterns: + model: "{_var}_{year_s:04d}01_{year_e:04d}12.nc" + dset_a: "{_var}_{year_s:04d}01_{year_e:04d}12.nc" in_dirs: dset_a: {{ e3sm_diags_data_dir }}/observations/Atm/climatology/ceres_ebaf_surface_v4.1 file_patterns: @@ -109,6 +146,18 @@ common_ceres: &common_ceres model_remap: {{ livvproj_dir }}/grids/msk_{icesheet}_r025_remap_cmip6.traave.nc model_native: {{ livvproj_dir }}/grids/msk_{icesheet}_rcm_r05.nc +common_modis: &common_modis + climo_remap: {{ dir_native }}/{{ case_id }}_{clim}_{sea_s}_{sea_e}_climo.nc + dataset_names: {model: 'ELM', dset_a: MODIS/Terra} + scales: {model: 100, dset_a: 1} + clim_years: + dset_a: { year_s: 2001, year_e: 2025} + 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 + common_racmo_gis: &common_racmo_gis climo_remap: {{ dir_racmo_gis }}/{{ case_id }}_{clim}_{sea_s}_{sea_e}_climo.nc icesheet: gis @@ -303,6 +352,61 @@ common_racmo_cmb_vars: &common_racmo_cmb_vars mask_weight: true units: mm w. e. yr^-1 +common_snow_storage_vars: &common_snow_storage_vars + - title: Snow Depth (liquid water) + model: H2OSNO + sign: 1 + scales: {model: 1} + units: "mm" + ac_axis: 0 + cmin: 0.0 + cmax: 25000 + cmap: YlGnBu + cmin_d: -8000 + cmax_d: 8000 + - title: Snow ice + model: SNOWICE + sign: 1 + scales: {model: 1} + units: "mm" + ac_axis: 0 + cmin: 0.0 + cmax: 25000 + cmap: YlGnBu + cmin_d: -8000 + cmax_d: 8000 + - title: Snow liquid water + model: SNOWLIQ + sign: 1 + scales: {model: 1} + ac_axis: 1 + units: "mm" + cmin: 0.0 + # cmax: 80 + cmap: YlGnBu + cmin_d: -10 + cmax_d: 10 + - title: Surface water runoff + model: QH2OSFC + sign: 1 + scales: {model: 365 * 24 * 3600} + units: "mm w. e. yr^-1" + cmin: 0.0 + cmap: YlGnBu + ac_axis: 0 + +common_snow_cover_vars: &common_snow_cover_vars + - title: Snow cover + model: FSNO + dset_a: Snow_Cover_Monthly_CMG + sign: 1 + ac_contrib_sign: { model: 1, dset_a: 1 } + scales: {model: 100, dset_a: 1} + units: "%" + cmin: 0 + cmax: 100 + cmap: YlGnBu + common_racmo_energy_vars: &common_racmo_energy_vars - title: Surface temperature dset_a: tas @@ -646,6 +750,30 @@ Surface_Mass_Balance_GIS: desc: "{component} component of SMB from {data_var_names}" {% endif %} +{% if snow %} +Snow_Storage_GIS: + module: /global/homes/m/mek/livvext/livvext/snow/snow.py + data_vars: *common_snow_storage_vars + icesheet: gis + <<: [*common, *common_snow, *common_elm] + scales: + { model: 1, } + primary_var: H2OSNO + desc: "{component} component of snow storage from {data_var_names}" + +Snow_Cover_GIS: + module: /global/homes/m/mek/livvext/livvext/snow/snow.py + data_vars: *common_snow_cover_vars + icesheet: gis + <<: [*common, *common_snow, *common_modis] + scales: + { model: 100, dset_a: 1} + primary_var: FSNO + desc: "{component} snow cover from {data_var_names}" + references: + - /global/cfs/cdirs/e3sm/diagnostics/livvkit_data/livvkit.bib +{% endif %} + {% if energy_racmo %} Energy_Balance_RACMO_GIS: module: {{ livvext_root }}/energy/energy.py @@ -706,6 +834,31 @@ Surface_Mass_Balance_AIS: desc: "{component} component of SMB from {data_var_names}" {% endif %} +{% if snow %} +Snow_Storage_AIS: + module: /global/homes/m/mek/livvext/livvext/snow/snow.py + data_vars: *common_snow_storage_vars + icesheet: ais + <<: [*common, *common_snow, *common_elm] + scales: + { model: 1, } + primary_var: H2OSNO + desc: "{component} component of snow storage from {data_var_names}" + +Snow_Cover_AIS: + module: /global/homes/m/mek/livvext/livvext/snow/snow.py + data_vars: *common_snow_cover_vars + icesheet: gis + <<: [*common, *common_snow, *common_modis] + scales: + { model: 100, dset_a: 1} + primary_var: FSNO + desc: "{component} snow storage from {data_var_names}" + icesheet: ais + references: + - /global/cfs/cdirs/e3sm/diagnostics/livvkit_data/livvkit.bib +{% endif %} + {% if energy_racmo %} Energy_Balance_RACMO_AIS: module: {{ livvext_root }}/energy/energy.py diff --git a/livvext/__init__.py b/livvext/__init__.py index a45ab5f..1de0aa2 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, 1, 2) +__version_info__ = (1, 2, 0) __version__ = ".".join(str(vi) for vi in __version_info__) diff --git a/livvext/annual_cycle.py b/livvext/annual_cycle.py index 20f6eab..a89d590 100644 --- a/livvext/annual_cycle.py +++ b/livvext/annual_cycle.py @@ -20,9 +20,22 @@ """ +def one_axis(data_vars): + """ + Given a list of LIVVkit data_vars, check if all annual cycles should be plotted on + the same axis. + """ + axis_test = [_var.get("ac_axis", 0) for _var in data_vars] + return len(set(axis_test)) == 1 + + def main(args, config): """Load climatology for model and "observational" data sets, create plots.""" - _files = [lxc.proc_climo_file(config, "climo_remap", mon) for mon in range(1, 13)] + if "climo_remap" in config: + _clim_key = "climo_remap" + else: + _clim_key = "climo" + _files = [lxc.proc_climo_file(config, _clim_key, mon) for mon in range(1, 13)] model_data = xr.open_mfdataset( _files, combine="nested", @@ -30,23 +43,55 @@ def main(args, config): ) mons = [f"{mon:02d}" for mon in np.arange(0, 12) + 1] - obs_data = lxc.load_obs( - config, sea=mons, mode="_monthlyPSR_", single_ds="dset_a", expect_one_time=False - ) + + if "dset_a" in config.get("dataset_names"): + obs_data = lxc.load_obs( + config, + sea=mons, + mode="_monthlyPSR_", + single_ds="dset_a", + expect_one_time=False, + ) + else: + obs_data = {} + obs_aavg = {} model_aavg = {} diffs_aavg = {} mask_r = {} area_r = {} - fig, axes = plt.subplots(1, 2, figsize=(12, 5), sharey=True) + # Going to be Model + number of obs datasets + nplts = len(obs_data) + 1 + if nplts == 2: + fig, axes0 = plt.subplots( + 1, 2, figsize=(12, 5), sharey=True, dpi=config.get("img_dpi", 90) + ) + else: + fig, axes0 = plt.subplots(1, 1, figsize=(8, 5), dpi=config.get("img_dpi", 90)) + axes0 = [axes0] + mons = np.arange(1, 12 + 1) obs_data_out = {} model_data_out = {} + plotted_lines = [None, None] + + # Check that all data_vars are on the same ac_axis (default to 0) + if not one_axis(config["data_vars"]): + axes1 = [_axis.twinx() for _axis in axes0] for idx, data_var in enumerate(config["data_vars"]): logger.info(f"WORKING ON {data_var['title']}") _obs_in = {} + # Left or right axis (0 for left 1 for right, default to 0) + _axis = data_var.get("ac_axis", 0) + + if _axis == 0: + axes = axes0 + logger.info(f"USING AXIS 0 FOR {data_var['title']}") + else: + axes = axes1 + logger.info(f"USING AXIS 1 FOR {data_var['title']}") aavg_config = data_var.get("aavg", None) @@ -78,7 +123,7 @@ def main(args, config): mask_r[data_var["title"]] = {} area_r[data_var["title"]] = {} - for _vers in ["dset_a"]: + for _vers in _obs_in: obs_aavg[data_var["title"]][_vers], mask_r[_vers], area_r[_vers], _ = ( lxc.area_avg( _obs_in[_vers], @@ -91,6 +136,7 @@ def main(args, config): sum_out=_do_sum, ) ) + model_aavg[data_var["title"]], _, _, _ = lxc.area_avg( _model_plt, {}, @@ -106,48 +152,58 @@ def main(args, config): color = f"C{idx}" lw = 1.1 - _obs_plt = ( - obs_aavg[data_var["title"]]["dset_a"] - * data_var["ac_contrib_sign"]["dset_a"] - * _aavg_scale - ) + _obs_plt = None + if obs_aavg[data_var["title"]].get("dset_a", None) is not None: + _obs_plt = ( + obs_aavg[data_var["title"]]["dset_a"] + * data_var["ac_contrib_sign"]["dset_a"] + * _aavg_scale + ) + obs_data_out[data_var["title"]] = _obs_plt # if isinstance(_obs_plt, np.ma.masked_array): # _obs_plt = _obs_plt.compressed().squeeze() _model_plt = ( model_aavg[data_var["title"]] - * data_var["ac_contrib_sign"]["model"] + * data_var.get("ac_contrib_sign", {}).get("model", 1) * 365 * _aavg_scale ) - obs_data_out[data_var["title"]] = _obs_plt + model_data_out[data_var["title"]] = _model_plt var_label = f" {data_var['title']}" - axes[0].plot(mons, _model_plt, label=var_label, color=color, marker=".", lw=lw) - axes[1].plot( - mons, - _obs_plt.squeeze(), - label=var_label, - color=color, - marker=".", - lw=lw, + if not one_axis(config["data_vars"]): + if data_var.get("ac_axis", 0) == 0: + var_label += " (L)" + else: + var_label += " (R)" + + _lin0 = axes[0].plot( + mons, _model_plt, label=var_label, color=color, marker=".", lw=lw ) - logger.info(f"DONE - WORKING ON {data_var['title']}") + if plotted_lines[0] is None: + plotted_lines[0] = _lin0 + else: + plotted_lines[0] += _lin0 - obs_data_out["month"] = np.arange(1, 12 + 1) - model_data_out["month"] = np.arange(1, 12 + 1) + if _obs_plt is not None: + _lin1 = axes[1].plot( + mons, + _obs_plt.squeeze(), + label=var_label, + color=color, + marker=".", + lw=lw, + ) + if plotted_lines[1] is None: + plotted_lines[1] = _lin1 + else: + plotted_lines[1] += _lin1 - obs_data_out = pd.DataFrame(obs_data_out) - obs_data_out.index = obs_data_out["month"] + logger.info(f"DONE - WORKING ON {data_var['title']}") - obs_data_out.to_csv( - Path( - args.out, - f"annual_cycle_{lxc.img_file_prefix(config)}" - f"{config['dataset_names']['dset_a'].replace(' ', '_').replace('.', '_')}.csv", - ) - ) + model_data_out["month"] = np.arange(1, 12 + 1) model_data_out = pd.DataFrame(model_data_out) model_data_out.index = model_data_out["month"] model_data_out.to_csv( @@ -157,33 +213,58 @@ def main(args, config): f"{config['dataset_names']['model']}.csv", ) ) + if "dset_a" in config: + obs_data_out["month"] = np.arange(1, 12 + 1) + obs_data_out = pd.DataFrame(obs_data_out) + obs_data_out.index = obs_data_out["month"] - if _aavg_units == "": - axes[0].set_ylabel(f"[{config['units']}]") + obs_data_out.to_csv( + Path( + args.out, + f"annual_cycle_{lxc.img_file_prefix(config)}" + f"{config['dataset_names']['dset_a'].replace(' ', '_').replace('.', '_')}.csv", + ) + ) + if not one_axis(config["data_vars"]): + _ax0 = [axes0[0], axes1[0]] else: - axes[0].set_ylabel(f"[{_aavg_units}]") - for axis in axes: + _ax0 = [axes0[0]] + + for _ax in _ax0: + if _aavg_units == "": + _units = config.get("units", data_var.get("units", None)) + _ax.set_ylabel(f"[{_units}]") + else: + _ax.set_ylabel(f"[{_aavg_units}]") + + for _ix, axis in enumerate(axes): axis.grid(visible=True, ls="--", lw=0.5) axis.set_xlabel("Month") axis.set_xticks(mons, lxc.MON_NAMES) - axis.legend(fontsize=8) + _labels = [_line.get_label() for _line in plotted_lines[_ix]] + axis.legend(plotted_lines[_ix], _labels, fontsize=8) _ = axes[0].set_title(config["dataset_names"]["model"]) - _ = axes[1].set_title(config["dataset_names"]["dset_a"]) + if len(axes) > 1: + _ = axes[1].set_title(config["dataset_names"]["dset_a"]) plt.tight_layout() - + ext = config.get("img_extn", "png") img_file = os.path.join( - args.out, f"{lxc.img_file_prefix(config)}_components_annual_cycle.png" + args.out, f"{lxc.img_file_prefix(config)}_components_annual_cycle.{ext}" ) fig.savefig(img_file) img_link = os.path.join( "imgs", os.path.basename(args.out), os.path.basename(img_file) ) + _names = {**config["dataset_names"]} + if "dset_a" not in _names: + _names["dset_a"] = "" + img_elem = el.Image( "SMB component annual cycles", - " ".join(DESCRIBE_COMPONENTS.split()).format(**config["dataset_names"]), + " ".join(DESCRIBE_COMPONENTS.split()).format(**_names), img_link, height=args.img_height, group=f"{IMG_GROUP}_ANN", diff --git a/livvext/common.py b/livvext/common.py index 13264e4..b2b7e53 100644 --- a/livvext/common.py +++ b/livvext/common.py @@ -24,6 +24,8 @@ import livvext.utils as lxu TFORM = ccrs.PlateCarree() +"""Transform for data on a regular lat / lon grid.""" + SEASON_NAME = { "ANN": "annual", "DJF": "winter", @@ -31,8 +33,14 @@ "MAM": "spring", "SON": "autumn", } +"""Map seasonal (MMM) abbreviations to human-readable names for seasons.""" + MON_NAMES = [dt.datetime(2000, mon, 1).strftime("%b") for mon in range(1, 12 + 1)] +"""List of short month names (Jan, Feb, ...).""" + DAYS_PER_MONTH = np.array([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]) +"""`np.ndarray` of number of days per month.""" + DAYS_PER_SEASON = { "DJF": (31 + 31 + 28), "MAM": (31 + 30 + 31), @@ -43,9 +51,10 @@ "JAS": (31 + 31 + 30), "OND": (31 + 30 + 31), } +"""Map seasonal (MMM) abbreviations to number of days per season.""" -def img_file_prefix(config): +def img_file_prefix(config: dict) -> str: """Convert the module name into a file prefix for the image output.""" # Just use the filename for the top-level module # maybe in the future this is fancier...but not now @@ -53,7 +62,7 @@ def img_file_prefix(config): return mod_name -def check_longitude(data, lon_coord="lon"): +def check_longitude(data: xr.Dataset | xr.DataArray, lon_coord: str = "lon"): """Check that longitudes are -180 - +180.""" lon = data[lon_coord] _data = data @@ -80,46 +89,110 @@ def check_longitude(data, lon_coord="lon"): return _data -def get_season_bounds(season, year_s, year_e): +def get_season_bounds( + season: str | int | float, + year_s: int, + year_e: int, + mon_s: int = None, + mon_e: int = None, +) -> tuple[str]: """Determine season bounds for climatology files.""" _seasons = { - "DJF": (1, 12), + "DJF": (12, 2), "MAM": (3, 5), "JJA": (6, 8), "SON": (9, 11), + "JFM": (1, 3), + "AMJ": (4, 6), + "JAS": (7, 9), + "OND": (10, 12), "ANN": (1, 12), } + if mon_s is not None and mon_e is None: + mon_e = (mon_s + 10) % 12 + 1 + if mon_e is not None and mon_s is None: + mon_s = (mon_e % 12) + 1 + + if mon_s is None and mon_e is None: + mon_s = 1 + mon_e = 12 + + # Borrowing from Charlie Zender's ncclimo + yyyymm_first = -1 + yyyymm_last = -1 + + mth_idx = mon_s + yr_idx = year_s if season in _seasons: - _lb, _ub = _seasons[season] - _lb = f"{_lb:02d}" - _ub = f"{_ub:02d}" + sea_s, sea_e = _seasons[season] + while True: + yyyymm_crr = yr_idx * 100 + mth_idx + month_in_season = False + if sea_s <= sea_e: + # season doesn't span years e.g. MAM, OND + if (mth_idx >= sea_s) and (mth_idx <= sea_e): + month_in_season = True + else: + # Season spans years (e.g. DJF) + if (mth_idx >= sea_s) or (mth_idx <= sea_e): + month_in_season = True + if month_in_season: + if yyyymm_first < 0: + yyyymm_first = yyyymm_crr + yyyymm_last = yyyymm_crr + + if (mth_idx == mon_e) and (yr_idx == year_e): + # This is the last month available, break out of the loop and end + break + + mth_idx += 1 + if mth_idx > 12: + # start at Jan of the next year + mth_idx = 1 + yr_idx += 1 + + year_first = yyyymm_first // 100 + year_last = yyyymm_last // 100 + + month_first = yyyymm_first % 100 + month_last = yyyymm_last % 100 + else: - # Assume "season" is a month + # Assume this "season" is a month if isinstance(season, str): - if len(season) == 1: - try: - _lb = f"{int(season):02d}" - _ub = f"{int(season):02d}" - except (ValueError, TypeError) as _err: - logger.error(f"UNKNOWN SEASON TYPE: {season}") - raise (_err) - else: - _lb = season - _ub = season - elif isinstance(season, int): - _lb = f"{int(season):02d}" - _ub = f"{int(season):02d}" + try: + _mon = int(season) + except (ValueError, TypeError) as _err: + logger.error(f"UNKNOWN SEASON TYPE: {season}") + raise (_err) + + elif isinstance(season, int) or isinstance(season, float): + _mon = int(season) else: logger.error(f"UNKNOWN SEASON TYPE: {season}") - bound_l = f"{year_s:04d}{_lb}" - bound_u = f"{year_e:04d}{_ub}" + if mon_s != 1 and mon_e != 12: + if _mon >= mon_s: + year_first = year_s + year_last = year_e - 1 + else: + year_first = year_s + 1 + year_last = year_e + else: + year_first = year_s + year_last = year_e + + month_first = _mon + month_last = _mon + + bound_l = f"{year_first:04d}{month_first:02d}" + bound_u = f"{year_last:04d}{month_last:02d}" return bound_l, bound_u -def proc_climo_file(config, file_tag, sea): +def proc_climo_file(config: dict, file_tag: str, sea: str) -> str: """ Process the climatology file to maintain backward compatibility with standalone LEX. @@ -140,9 +213,16 @@ def proc_climo_file(config, file_tag, sea): """ _filename = config[file_tag] + mon_s = config.get("mon_s", None) + mon_e = config.get("mon_e", None) + if "{sea_s}" in _filename: sea_s, sea_e = get_season_bounds( - sea, config.get("year_s", None), config.get("year_e", None) + sea, + config.get("year_s", None), + config.get("year_e", None), + mon_s, + mon_e, ) if isinstance(sea, int): sea = f"{sea:02d}" @@ -166,95 +246,33 @@ def get_cycle(sea): return cycle -def gen_file_list_old( - config: dict, - var_name: list | tuple | str, - overs: str, - sea: list | tuple | str, - cycle: str, - mode: str, -): - var_files = [] - - def _fcn_filt(_var): - _fcn_names = ["formula", "+", "-", "/", "*", "^", "sum", "diff"] - return _var not in _fcn_names - - def var_file(_var, _mode, _sea): - return config["file_patterns"][overs].format( - _var=_var, - season=_sea, - mode=_mode, - ) - - if isinstance(var_name, str) and isinstance(sea, str): - var_files = [ - Path( - config["in_dirs"][overs].format(cycle=cycle), - var_file(var_name, mode, sea), - ) - ] - - elif isinstance(var_name, str) and isinstance(sea, (list, tuple)): - var_files = [ - Path( - config["in_dirs"][overs].format(cycle=cycle), - var_file(var_name, mode, _sea), - ) - for _sea in sea - ] - - elif isinstance(var_name, (list, tuple)) and isinstance(sea, str): - _file_vars = lxu.extract_vars(var_name) - - var_files = [ - Path( - config["in_dirs"][overs].format(cycle=cycle), - config["file_patterns"][overs].format( - _var=ivar, - season=sea, - mode=mode, - ), - ) - for ivar in _file_vars - ] - - elif isinstance(var_name, (list, tuple)) and isinstance(sea, (list, tuple)): - var_files = [] - _file_vars = lxu.extract_vars(var_name) - - for _sea in sea: - var_files.extend( - [ - Path( - config["in_dirs"][overs].format(cycle=cycle), - var_file(ivar, mode, _sea), - ) - for ivar in _file_vars - ] - ) - - for idx, _file in enumerate(var_files): - if not _file.exists(): - # First swap climoS_ANN for ANN_climoS: - new_name = _file.name.replace("climoS_ANN", "ANN_climoS") - _test_file = Path(*var_files[-1].parts[:-1], new_name) - if not _test_file.exists(): - # Now swap climoA for climoS (avg for sum) - new_name = new_name.replace("climoS", "climoA") - _test_file = Path(*var_files[-1].parts[:-1], new_name) - if not _test_file.exists(): - new_name = new_name.replace("ANN_climoA", "climoA_ann") - _test_file = Path(*var_files[-1].parts[:-1], new_name) - if not _test_file.exists(): - new_name = _file.name.replace("PSR_", "A_") - - var_files[idx] = Path(*var_files[-1].parts[:-1], new_name) +def var_filename_format(file_pattern, _var, isheet, _sea, year_s, year_e, sep="_"): + """ + Fill in a LIVVext defined string template for a particular variable, season, and run. - return var_files + Parameters + ---------- + file_pattern : `str` + Filename template with spots for variable, icesheet, and season start / end + _var : `str` + Model or observational field name + isheet : `str` + Icesheet name (gis or ais) + _sea : `str` + Season name or month number (e.g. ANN, DJF,..., '01' or 1) + year_s : `int` + Start year of climatology + year_e : `int` + End year of climatology + sep : `str`, optional + Separator within the template, if defined. By default "_" + Returns + ------- + `str` + Formatted filename -def var_filename_format(file_pattern, _var, isheet, _sea, year_s, year_e, sep="_"): + """ sea_s, sea_e = get_season_bounds(_sea, year_s, year_e) if isinstance(_sea, int): season = f"{_sea:02d}" @@ -275,7 +293,33 @@ def gen_file_list( overs: str, sea: list | tuple | str, cycle: str, -): +) -> list[Path]: + """ + Generate a list of files to be loaded for a particular dataset climatology. + + Parameters + ---------- + config : dict + LIVVext configuratrion dictionary. Must have keys: + - ``file_patterns``: the file match pattern for each dataset + - ``in_dirs``: Absolute path to directory for each dataset + - ``clim_years``: Start and end year for climatology + - ``icesheet``: Icesheet identifier (optional, defaults to gis) + var_name : list | tuple | str + Name or list/tuple of names of fields to be loaded, each in a separate file + overs : str + Observation version (dset_a, dset_b, ..., or model) + sea : list | tuple | str + Season or list/tuple of seasons to be loaded + cycle : str + Climatology averaging period (e.g. ann, sea, mon) + + Returns + ------- + list[Path] + List of full file paths to be loaded + + """ var_files = [] def _fcn_filt(_var): @@ -340,7 +384,34 @@ def _fcn_filt(_var): def load_obs(config, sea="ANN", mode="climoS", single_ds=None, expect_one_time=True): - """ """ + """ + Load observational (or reanalysis) data. + + Parameters + ---------- + config : dict + LIVVext configuratrion dictionary. Must have keys: + - ``in_dirs``: the input directories each dataset + - ``data_vars``: the variables to be analyzed + - ``file_patterns``: the file match pattern for each dataset + - ``in_dirs``: Absolute path to directory for each dataset + - ``clim_years``: Start and end year for climatology + - ``icesheet``: Icesheet identifier (optional, defaults to gis) + sea : str, optional + Season or month (e.g. ANN, DJF, '01', 1), by default "ANN" + mode : str, optional + Climatology mode, for sum (climoS), average (climoA), by default "climoS" + single_ds : str, optional + Load only one dataset, by default None, load all datasets in ``config["in_dirs"]`` + expect_one_time : bool, optional + Assume dataset has a single time per file, by default True + + Returns + ------- + dict[`xr.Dataset`] + Dictionary of `xr.Dataset` s, one for each dataset in ``config["in_dirs"]``. + + """ files = {} obs_data = {} @@ -390,6 +461,24 @@ def gen_file_list_timeseries( var_name: list | tuple | str, overs: str, ): + """ + Similar to `gen_file_list` but for timeseries data. Generate list of files to load. + + Parameters + ---------- + config : dict + LIVVext configuratrion dictionary. + var_name : list | tuple | str + Field name or list/tuple of field names to be loaded + overs : str + "Observational" dataset version (e.g. dset_a, dset_b, ..., or model) + + Returns + ------- + list[Path] + List of absolute paths to input dataset files + + """ var_files = [] def _fcn_filt(_var): @@ -439,8 +528,25 @@ def _fcn_filt(_var): @logger.catch -def load_timeseries_data(config): - """Load data for timeseries.""" +def load_timeseries_data(config: dict): + """ + Load data for timeseries. + + Parameters + ---------- + config : `dict` + LIVVext configuration dictionary. Should have keys: + - ``timeseries_dirs`` + - ``data_vars`` + - ``dataset_names`` + - Other keys as required by ``get_file_list_timeseries`` + + Returns + ------- + dict[`xr.Dataset`] + Dictionary of datasets for each dataset in ``config["timeseries_dirs"]`` + + """ files = {} obs_data = {} @@ -479,7 +585,31 @@ def load_timeseries_data(config): return obs_data -def parse_var(data_var, dataset, scale): +def parse_var( + data_var: list | tuple | str, dataset: xr.Dataset, scale: float | int | str +) -> xr.DataArray: + """ + Parse a data_var formula or name. + + Parameters + ---------- + data_var : `list` | `tuple` | `str` + data_var definition, if a list or tuple, this is a formula for + computing a derived field, if a string, this is a native output + field from the dataset. See `livvext.utils.extract_ds` for more details. + dataset : `xr.Dataset` + Input `xr.Dataset` + scale : `float` | `int` | `str` + Scale the ``data_var`` field after computation by ``scale``. Can be + numeric or a string representation (e.g. 1e-6, 32.5, or "365 * 24"). + See `livvext.utils.eval_expr` for more details. + + Returns + ------- + `xr.DataArray` + Xarray DataArray of the field of intrest + + """ if isinstance(scale, (int, float)): _scale = scale else: @@ -492,7 +622,21 @@ def parse_var(data_var, dataset, scale): return _vardata.squeeze() * _scale -def parse_var_name(data_var): +def parse_var_name(data_var: list | tuple | str) -> str: + """ + Parse a LIVVext ``data_var`` formula or native netCDF field name string. + + Parameters + ---------- + data_var : `list` | `tuple` | `str` + LIVVext ``data_var`` formula if list or tuple, native output field name if string + + Returns + ------- + `str` + String representation of the output field or formula + + """ if isinstance(data_var, str): _out = data_var elif isinstance(data_var, (list, tuple)): @@ -501,14 +645,14 @@ def parse_var_name(data_var): def area_avg( - data, - config, - area_file, - area_var, - mask_file=None, - mask_var=None, - sum_out=False, - land_only=False, + data: xr.DataArray | np.ndarray, + config: dict, + area_file: Path, + area_var: str, + mask_file: Path = None, + mask_var: str = None, + sum_out: bool = False, + land_only: bool = False, ): """ Compute a masked and weighted area average of some field. @@ -528,6 +672,11 @@ def area_avg( mask_var : str, optional Name of the netCDF variable which contains the ice sheet mask data, if not set, then use ``maskv`` from ``config`` + sum_out: bool, optional + Return the weighted sum rather than average. Defualt is False + land_only: bool, optional + Return the average or sum over grid cells which are 100% land so no + ocean cells are included. Default is False Returns ------- @@ -597,8 +746,29 @@ def area_avg( return _avg, isheet_mask, area_maskice, _data -def closest_points(model_x, model_y, obs_x, obs_y): - """Determine closest model points to set of observation x/y points.""" +def closest_points( + model_x: np.ndarray, model_y: np.ndarray, obs_x: np.ndarray, obs_y: np.ndarray +) -> tuple[np.ndarray]: + """Determine closest model points to set of observation x/y points. + + Parameters + ---------- + model_x : `np.ndarray` + Model x coordinate array (lon) + model_y : `np.ndarray` + Model y coordinate array (lat) + obs_x : `np.ndarray` + Observation x locations (lon) + obs_y : `np.ndarray` + Observation y locations (lat) + + Returns + ------- + tuple[np.ndarray] + Array of closest points, Array of indicies for observations on the model mesh + (nobs, ny, nx) + + """ # All points in model domain; convert to radians for kd tree query below if model_x.ndim == 2: lon2d = model_x @@ -652,6 +822,10 @@ def summarize_result(result): status = "Success" if isinstance(result, livvkit.elements.Error): status = "Failure" + elif isinstance(result, livvkit.elements.CompositeElement): + _errs = [isinstance(_ele, livvkit.elements.Error) for _ele in result.elements] + if any(_errs): + status = "Failure" summary = LIVVDict() try: @@ -668,6 +842,8 @@ def summarize_result(result): return summary +# STUFF BELOW HERE IS PROBABLY UN-USED------------------------------------------------- +# Should probably check and remove stuff that isn't needed anymore def annotate_plot(axis, color_field=None, label=None): """Add land / ocean, gridlines, colourbar.""" axis.coastlines(linewidth=0.5) diff --git a/livvext/compare_gridded.py b/livvext/compare_gridded.py index 2169704..f77235a 100644 --- a/livvext/compare_gridded.py +++ b/livvext/compare_gridded.py @@ -3,12 +3,14 @@ """Compare up to three gridded datasets. Typically one "Model" and 1 or 2 "Observations" """ import os +import argparse import matplotlib.path as mpath import matplotlib.pyplot as plt import numpy as np import pandas as pd import xarray as xr +from loguru import logger from cartopy import crs as ccrs from cartopy import feature as cfeature from livvkit import elements as el @@ -81,6 +83,7 @@ def annotate_plot( cnrtxt=None, gridline_args=None, icesheet="gis", + stats=None, ): """Add land / ocean, gridlines, colourbar.""" axis.coastlines(linewidth=0.1) @@ -120,19 +123,30 @@ def annotate_plot( if ylabel is not None: axis.set_ylabel(ylabel) - if cnrtxt is not None: - plt.figtext( - 0.98, - 0.02, - s=f"Avg.\n{cnrtxt}", - horizontalalignment="right", - verticalalignment="bottom", - transform=axis.transAxes, - bbox={"facecolor": "grey", "alpha": 0.1}, - ) + if cnrtxt is not None and stats is None: + _text = f"Avg.\n{cnrtxt}" + elif stats is not None: + _text = "" + for _stat in ["min", "max", "avg"]: + _text += f"{_stat.capitalize()}: {stats[_stat]:.3g}\n" + + if "units" in stats: + _text += stats["units"] + else: + _text = _text[:-1] + + plt.figtext( + 0.98, + 0.02, + s=_text, + horizontalalignment="right", + verticalalignment="bottom", + transform=axis.transAxes, + bbox={"facecolor": "grey", "alpha": 0.1}, + ) -def get_figure(n_dsets, proj=None, icesheet="gis"): +def get_figure(n_dsets, proj=None, icesheet="gis", config={}): """Set up figure based on number of datasets to be plotted.""" fig_size = { "gis": {3: (10, 10), 2: (10, 8), 1: (7, 10)}, @@ -148,7 +162,9 @@ def get_figure(n_dsets, proj=None, icesheet="gis"): elif icesheet == "ais": proj = ccrs.SouthPolarStereo(central_longitude=0) - fig = plt.figure(figsize=fig_size[icesheet][n_dsets], dpi=90) + _dpi = config.get("img_dpi", 90) + logger.info(f"CREATING FIGURE WITH SIZE {fig_size[icesheet][n_dsets]} DPI={_dpi}") + fig = plt.figure(figsize=fig_size[icesheet][n_dsets], dpi=_dpi) if n_dsets == 3: axes = [fig.add_subplot(2, 3, i + 1, projection=proj) for i in range(6)] @@ -163,7 +179,7 @@ def get_figure(n_dsets, proj=None, icesheet="gis"): return fig, axes, proj -def main(args, config, sea="ANN"): +def main(args: argparse.Namespace, config: dict, sea: str | int = "ANN"): """ Generate comparison plots for a particular season. @@ -185,7 +201,8 @@ def main(args, config, sea="ANN"): Raises ------ NotImplementedError - _description_ + When an icesheet is asked for that is not defined (Antarctica or Greenland) + """ units = config.get("units", "UNITS UNKNOWN") icesheet = config.get("icesheet", "gis").lower() @@ -217,10 +234,23 @@ def main(args, config, sea="ANN"): **lxc.load_obs(config, sea, mode=mode), } else: - all_data = { - "model": xr.open_dataset(lxc.proc_climo_file(config, "climo_remap", sea)), - **lxc.load_obs(config, sea, mode=mode), - } + try: + all_data = { + **lxc.load_obs(config, sea, mode=mode), + } + except KeyError: + # Means there's no obs data, so just move on to model data + all_data = {} + + if "climo_remap" in config: + all_data["model"] = xr.open_dataset( + lxc.proc_climo_file(config, "climo_remap", 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]) @@ -243,6 +273,7 @@ def main(args, config, sea="ANN"): diff_names = [] dsets = list(config["dataset_names"]) + logger.info(f"DSETS TO PLOT {dsets}") dsets_to_plot = [_dset for _dset in dsets if "remap" not in _dset] n_dsets_to_plot = len(dsets_to_plot) @@ -290,7 +321,9 @@ def main(args, config, sea="ANN"): diffs[_diffnm[2]] = _plt_data[_diffnm[0]].values * np.nan all_aavg = {} + all_stats = {} diffs_aavg = {} + diffs_stats = {} mask_r = {} area_r = {} @@ -299,6 +332,8 @@ def main(args, config, sea="ANN"): _aavg_scale = aavg_config["scale"] _do_sum = aavg_config["sum"] _aavg_units = aavg_config["units"] + all_stats["aavg_units"] = aavg_config["units"] + diffs_stats["aavg_units"] = aavg_config["units"] else: _aavg_scale = 1.0 _do_sum = False @@ -317,7 +352,18 @@ def main(args, config, sea="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 all_stats.get("aavg_units"): + all_stats[_vers]["units"] = all_stats.get("aavg_units") aavg_out[data_var["title"]] = { config["dataset_names"][_vers]: all_aavg[_vers] for _vers in all_aavg @@ -333,7 +379,18 @@ def main(args, config, sea="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], + } diffs_aavg[_diffname] *= _aavg_scale + 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") + _longname = ( f"{config['dataset_names'][_ds1]} - {config['dataset_names'][_ds2]}" ) @@ -356,7 +413,9 @@ def main(args, config, sea="ANN"): else: raise NotImplementedError(f"ICESHEET {icesheet} NOT FOUND USE ais / gis") - fig, axes, _ = get_figure(n_dsets_to_plot, proj, icesheet=icesheet) + fig, axes, _ = get_figure( + n_dsets_to_plot, proj, icesheet=icesheet, config=config + ) for _vers in _plt_data: try: @@ -380,6 +439,7 @@ def main(args, config, sea="ANN"): _cmin = data_var.get("cmin", None) _cmax = data_var.get("cmax", None) + if _cmin is None or _cmax is None: cmin, cmax = lxc.compute_clevs( data=_plt_data, @@ -387,6 +447,17 @@ def main(args, config, sea="ANN"): bnds=(5, 95), keys=dsets_to_plot, ) + # Repeat this if the cmin and cmax are both 0, until + # cmin is min of the data, cmax is max of the data + _bnd = 5 + while cmin == cmax == 0 and _bnd > 0: + _bnd -= 1 + cmin, cmax = lxc.compute_clevs( + data=_plt_data, + even=config.get("clim_even", False), + bnds=(_bnd, 100 - _bnd), + keys=dsets_to_plot, + ) # Allows for cmin/cmax to be set indivdually in the config file per field if _cmin is not None: @@ -396,7 +467,7 @@ def main(args, config, sea="ANN"): _cmin_d = data_var.get("cmin_d", None) _cmax_d = data_var.get("cmax_d", None) - if _cmin_d is None or _cmax_d is None: + if (_cmin_d is None or _cmax_d is None) and diffs: cmin_d, cmax_d = lxc.compute_clevs( data=diffs, even=True, @@ -440,6 +511,7 @@ def main(args, config, sea="ANN"): label=config["dataset_names"][_vers], cnrtxt=cnrtxt, icesheet=icesheet, + stats=all_stats[_vers], ) if n_dsets_to_plot == 3: @@ -478,18 +550,21 @@ def main(args, config, sea="ANN"): ), cnrtxt=cnrtxt, icesheet=icesheet, + stats=diffs_stats[_diffnm], ) - if n_dsets_to_plot == 3: - add_colorbar(_cfd, fig, axes[2 + n_dsets_to_plot], _units, ndsets) - else: - add_colorbar( - _cfd, fig, axes[-1], _units, ndsets=n_dsets_to_plot, cbar_span=False - ) - plt.tight_layout() - + if diff_names: + # Only add the difference colourbar when there's a diff field + if n_dsets_to_plot == 3: + add_colorbar(_cfd, fig, axes[2 + n_dsets_to_plot], _units, ndsets) + else: + add_colorbar( + _cfd, fig, axes[-1], _units, ndsets=n_dsets_to_plot, cbar_span=False + ) + plt.tight_layout() + ext = config.get("img_extn", "png") img_file = os.path.join( args.out, - f"{lxc.img_file_prefix(config)}_{data_var['title'].replace(' ', '_')}_{sea}.png", + f"{lxc.img_file_prefix(config)}_{data_var['title'].replace(' ', '_')}_{sea}.{ext}", ) fig.savefig(img_file) img_link = os.path.join( diff --git a/livvext/convert_cfg.py b/livvext/convert_cfg.py index 755f0e7..7e6e359 100644 --- a/livvext/convert_cfg.py +++ b/livvext/convert_cfg.py @@ -75,8 +75,8 @@ def json_to_yaml(in_file: Path, out_file: Path = None): yml.dump(cfg, _fout) -def main(args): - """ """ +def main(args: argparse.Namespace): + """Parse command line arguments, run conversion from JSON(s) -> YAML(s).""" print(args) assert not (args.cfg_in and args.indir), "Supply only directory OR input file" diff --git a/livvext/generate_cfg.py b/livvext/generate_cfg.py index fdc2b81..408a984 100644 --- a/livvext/generate_cfg.py +++ b/livvext/generate_cfg.py @@ -9,7 +9,7 @@ import livvext ALL_SHEETS = "gis,ais" -ALL_SETS = "cmb,smb,energy_racmo,energy_era5,energy_merra2,energy_ceres" +ALL_SETS = "cmb,smb,snow,energy_racmo,energy_era5,energy_merra2,energy_ceres" def args(): @@ -63,7 +63,7 @@ def args(): type=str, default="all", help=( - "Analysis sets to run: cmb, smb, energy_racmo, energy_era5, " + "Analysis sets to run: cmb, smb, snow, energy_racmo, energy_era5, " "energy_merra2, energy_ceres, or all to run all available" ), ) @@ -97,7 +97,7 @@ def args(): return parser.parse_args() -def gen_cfg(cfg_template, params, cfg_out): +def gen_cfg(cfg_template: Path, params: dict, cfg_out: Path) -> Path: """ Generate and write LIVVext configuration file from template and parameters. @@ -131,7 +131,7 @@ def gen_cfg(cfg_template, params, cfg_out): return cfg_out -def parse_sets(sheets, sets): +def parse_sets(sheets: str, sets: str) -> dict: """Parse comma separated strings of sets / icesheets to analyse.""" params = {} diff --git a/livvext/smb/smb/plot_IB_hist.py b/livvext/smb/smb/plot_IB_hist.py index 1e2cf2f..051a6eb 100644 --- a/livvext/smb/smb/plot_IB_hist.py +++ b/livvext/smb/smb/plot_IB_hist.py @@ -73,7 +73,9 @@ def main(args, config): zwally_regions = [2, 3, 4, 1, 5, 6, 7, 8] pltcrds = [(0, 1), (1, 0), (1, 1), (0, 0), (2, 0), (2, 1), (3, 0), (3, 1)] - fig, axes = plt.subplots(nrows=4, ncols=2, figsize=(10, 20)) + fig, axes = plt.subplots( + nrows=4, ncols=2, figsize=(10, 20), dpi=config.get("img_dpi", 90) + ) for i in range(0, len(list_regions)): regname = list_regions[i] inde = pltcrds[i] @@ -88,7 +90,8 @@ def main(args, config): subs.set_ylim(0, 1000) plt.tight_layout() - img_file = os.path.join(args.out, "IB_diffhist_basins.png") + ext = config.get("img_extn", "png") + img_file = os.path.join(args.out, f"IB_diffhist_basins.{ext}") plt.savefig(img_file) plt.close() @@ -110,7 +113,7 @@ def main(args, config): index=ice_bridge.index, columns=["difference"], ) - _ = plt.figure(figsize=(8, 8)) + _ = plt.figure(figsize=(8, 8), dpi=config.get("img_dpi", 90)) hist1 = difftest["difference"].hist(bins=20) hist1.set_xlabel("Model - observed SMB difference\n(kg m$^{-2}$ a$^{-1}$)") hist1.set_ylabel("Cell frequency") @@ -118,7 +121,7 @@ def main(args, config): hist1.axvline(x=0.0, c="lightskyblue", linewidth=2) plt.tight_layout() - img_file = os.path.join(args.out, "IB_diffhist_all.png") + img_file = os.path.join(args.out, f"IB_diffhist_all.{ext}") plt.savefig(img_file) plt.close() diff --git a/livvext/smb/smb/plot_IB_scatter.py b/livvext/smb/smb/plot_IB_scatter.py index b844348..5de0325 100644 --- a/livvext/smb/smb/plot_IB_scatter.py +++ b/livvext/smb/smb/plot_IB_scatter.py @@ -46,6 +46,7 @@ def main(args, config): "8.0": "firebrick", } if accplot.shape[0] > 0: + fig, axis = plt.subplots(1, 1, figsize=(8, 8), dpi=config.get("img_dpi", 90)) testplot = accplot.plot( kind="scatter", x="b", @@ -54,7 +55,7 @@ def main(args, config): c=majorbasins.apply(lambda x: colors[x]), legend=True, alpha=0.1, - figsize=(8, 8), + ax=axis, ) else: return [] @@ -67,7 +68,8 @@ def main(args, config): testplot.set_title("Accumulation") plt.tight_layout() - img_file = os.path.join(args.out, "IB_AccCompare.png") + ext = config.get("img_extn", "png") + img_file = os.path.join(args.out, f"IB_AccCompare.{ext}") plt.savefig(img_file) plt.close() diff --git a/livvext/smb/smb/plot_core_hists.py b/livvext/smb/smb/plot_core_hists.py index 215dd87..20280f1 100644 --- a/livvext/smb/smb/plot_core_hists.py +++ b/livvext/smb/smb/plot_core_hists.py @@ -66,7 +66,9 @@ def main(args, config): zwally_regions = [2, 3, 4, 1, 5, 6, 7, 8] pltcrds = [(0, 1), (1, 0), (1, 1), (0, 0), (2, 0), (2, 1), (3, 0), (3, 1)] - fig, axes = plt.subplots(nrows=4, ncols=2, figsize=(10, 20)) + fig, axes = plt.subplots( + nrows=4, ncols=2, figsize=(10, 20), dpi=config.get("img_dpi", 90) + ) for i in range(0, len(list_regions)): regname = list_regions[i] inde = pltcrds[i] @@ -81,7 +83,8 @@ def main(args, config): subs.set_ylim(0, 65) plt.tight_layout() - img_file = os.path.join(args.out, "core_diffhist_basins.png") + ext = config.get("img_extn", "png") + img_file = os.path.join(args.out, f"core_diffhist_basins.{ext}") plt.savefig(img_file) plt.close() img_link = os.path.join( @@ -99,7 +102,7 @@ def main(args, config): difftest = pd.DataFrame( data=smb_avg.mod_b - smb_avg.b, index=smb_avg.index, columns=["difference"] ) - _ = plt.figure(figsize=(8, 8)) + _ = plt.figure(figsize=(8, 8), dpi=config.get("img_dpi", 90)) hist1 = difftest["difference"].hist(bins=30, edgecolor="k") hist1.set_xlabel("Model - observed SMB difference\n(kg m$^{-2}$ a$^{-1}$)") hist1.set_ylabel("Cell frequency") @@ -107,7 +110,7 @@ def main(args, config): hist1.axvline(x=0.0, c="lightskyblue", linewidth=2) plt.tight_layout() - img_file = os.path.join(args.out, "core_diffhist_all.png") + img_file = os.path.join(args.out, f"core_diffhist_all.{ext}") plt.savefig(img_file) plt.close() diff --git a/livvext/smb/smb/plot_core_transects.py b/livvext/smb/smb/plot_core_transects.py index 5e01483..19c4689 100644 --- a/livvext/smb/smb/plot_core_transects.py +++ b/livvext/smb/smb/plot_core_transects.py @@ -93,7 +93,8 @@ def main(args, config): testplot.set_ylim(-5500, 1500) plt.tight_layout() - img_file = os.path.join(args.out, "core_smbelev_obs.png") + ext = config.get("img_extn", "png") + img_file = os.path.join(args.out, f"core_smbelev_obs.{ext}") plt.savefig(img_file) plt.close() @@ -125,7 +126,7 @@ def main(args, config): testplot2.set_ylim(-5500, 1500) plt.tight_layout() - img_file = os.path.join(args.out, "core_smbelev_mod.png") + img_file = os.path.join(args.out, f"core_smbelev_mod.{ext}") plt.savefig(img_file) plt.close() @@ -152,7 +153,7 @@ def main(args, config): "K-transect", ] - fig = plt.figure(figsize=(12, 12)) + fig = plt.figure(figsize=(12, 12), dpi=config.get("img_dpi", 90)) for i in range(0, len(glacier_list)): glacplot = fig.add_subplot(i + 221) glac_name = glacier_list[i] @@ -180,7 +181,7 @@ def main(args, config): glacplot.set_title(glac_longnames[i], size=12) plt.tight_layout() - img_file = os.path.join(args.out, "core_transects.png") + img_file = os.path.join(args.out, f"core_transects.{ext}") plt.savefig(img_file) plt.close() @@ -203,6 +204,7 @@ def main(args, config): accplot = working[working.source != "promice"] majorbasins = np.floor(accplot.zwallyBasin).astype("str") + fig, axis = plt.subplots(1, 1, figsize=(8, 8), dpi=config.get("img_dpi", 90)) testplot = accplot.plot( kind="scatter", x="b", @@ -211,7 +213,7 @@ def main(args, config): c=majorbasins.apply(lambda x: colors[x]), legend=True, alpha=0.6, - figsize=(8, 8), + ax=axis, ) testplot.set_xlabel("Field SMB estimate (kg m$^{-2}$ a$^{-1}$)") testplot.set_ylabel("Modeled SMB (kg m$^{-2}$ a$^{-1}$)") @@ -221,7 +223,7 @@ def main(args, config): testplot.set_title("Accumulation") plt.tight_layout() - img_file = os.path.join(args.out, "core_AccCompare.png") + img_file = os.path.join(args.out, f"core_AccCompare.{ext}") plt.savefig(img_file) plt.close() @@ -240,6 +242,7 @@ def main(args, config): ablplot = working[working.source == "promice"] majorbasins = np.floor(ablplot.zwallyBasin).astype("str") + fig, axis = plt.subplots(1, 1, figsize=(8, 8), dpi=config.get("img_dpi", 90)) testplot = ablplot.plot( kind="scatter", x="b", @@ -248,7 +251,7 @@ def main(args, config): c=majorbasins.apply(lambda x: colors[x]), legend=True, alpha=0.6, - figsize=(8, 8), + ax=axis, ) testplot.set_xlabel("Field SMB estimate (kg m$^{-2}$ a$^{-1}$)") testplot.set_ylabel("Modeled SMB (kg m$^{-2}$ a$^{-1}$)") @@ -258,7 +261,7 @@ def main(args, config): testplot.set_title("Ablation") plt.tight_layout() - img_file = os.path.join(args.out, "core_AblCompare.png") + img_file = os.path.join(args.out, f"core_AblCompare.{ext}") plt.savefig(img_file) plt.close() diff --git a/livvext/smb/smb/plot_spatial.py b/livvext/smb/smb/plot_spatial.py index 3bc8ce9..9d305f9 100644 --- a/livvext/smb/smb/plot_spatial.py +++ b/livvext/smb/smb/plot_spatial.py @@ -139,7 +139,7 @@ def plot_core(args, config): tform = ccrs.PlateCarree() lons_model, lats_model, msmb = load_model_data(config) - fig, axes, proj = lxcg.get_figure(1, icesheet="gis") + fig, axes, proj = lxcg.get_figure(1, icesheet="gis", config=config) vabsmax = 2000 cf_smb_model = axes[0].pcolormesh( @@ -186,7 +186,8 @@ def plot_core(args, config): ) plt.tight_layout() - img_file = os.path.join(args.out, "core_spatial.png") + ext = config.get("img_extn", "png") + img_file = os.path.join(args.out, f"core_spatial.{ext}") plt.savefig(img_file) plt.close() @@ -216,7 +217,7 @@ def plot_ib_spatial(args, config): tform = ccrs.PlateCarree() _, _, ib_file = preproc.ib_outfile(config) ice_bridge = pd.read_csv(ib_file) - fig, axes, proj = lxcg.get_figure(1, icesheet="gis") + fig, axes, proj = lxcg.get_figure(1, icesheet="gis", config=config) lat_obs = ice_bridge["Y"].values lon_obs = ice_bridge["X"].values @@ -242,7 +243,9 @@ def plot_ib_spatial(args, config): ndsets=1, ) plt.tight_layout() - img_file = os.path.join(args.out, "IB_spatial.png") + + ext = config.get("img_extn", "png") + img_file = os.path.join(args.out, f"IB_spatial.{ext}") plt.savefig(img_file) plt.close() @@ -260,7 +263,7 @@ def plot_ib_spatial(args, config): img_list.append(img_elem) # Plot IB - Model difference - fig, axes, proj = lxcg.get_figure(1, icesheet="gis") + fig, axes, proj = lxcg.get_figure(1, icesheet="gis", config=config) smbobs_diff = ice_bridge["mod_b"].values - ice_bridge["b"].values cf_diff = axes[0].scatter( lon_obs, @@ -289,7 +292,9 @@ def plot_ib_spatial(args, config): ) plt.tight_layout() - img_file = os.path.join(args.out, "IB_spatial_difference.png") + + ext = config.get("img_extn", "png") + img_file = os.path.join(args.out, f"IB_spatial_difference.{ext}") plt.savefig(img_file) plt.close() @@ -342,7 +347,7 @@ def plot_metadata(args, config): ] ) - fig, axes, proj = lxcg.get_figure(1, icesheet="gis") + fig, axes, proj = lxcg.get_figure(1, icesheet="gis", config=config) # Read in the zwally basins and mask out model cells that are missing a basin designation basins = np.floor(zwally_data.zwally_basin.values) @@ -443,7 +448,8 @@ def plot_metadata(args, config): ) plt.tight_layout() - img_file = os.path.join(args.out, "plot_meta_old.png") + ext = config.get("img_extn", "png") + img_file = os.path.join(args.out, f"plot_meta_old.{ext}") plt.savefig(img_file) plt.close() diff --git a/livvext/smb/smb_icecores.py b/livvext/smb/smb_icecores.py index d00b571..167e2b2 100644 --- a/livvext/smb/smb_icecores.py +++ b/livvext/smb/smb_icecores.py @@ -82,6 +82,10 @@ comparison to gridded RACMO reanalysis. [CMB = (Precip - (Runoff + Sublimation)] """, }, + "H2OSNO": { + "gis": "Analysis of the model snow storage terms for Greenland ice sheet", + "ais": "Analysis of the model snow storage terms for Antarctic ice sheet", + }, } base_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") @@ -207,9 +211,15 @@ def _format_table(x): tabs["References"] = [refs] logger.info(f"FINISHED SMB_ICECORES WITH OUTPUT TO {img_dir}") + try: + _docs = PAGE_DOCS[config.get("primary_var", "smbgl")][ + config.get("icesheet", "gis") + ] + except KeyError: + _docs = f"Plots for {config.get('primary_var', 'UNKNOWN')}" return el.Page( name, - PAGE_DOCS[config.get("primary_var", "smbgl")][config.get("icesheet", "gis")], + _docs, elements=[run_summary, el.Tabs(tabs)], ) diff --git a/livvext/snow/__init__.py b/livvext/snow/__init__.py new file mode 100644 index 0000000..878725f --- /dev/null +++ b/livvext/snow/__init__.py @@ -0,0 +1 @@ +"""Module for analyzing snow properties over an ice sheet""" diff --git a/livvext/snow/snow.py b/livvext/snow/snow.py new file mode 100644 index 0000000..e073891 --- /dev/null +++ b/livvext/snow/snow.py @@ -0,0 +1,237 @@ +# 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 snow properties 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 snow properties over Greenland.", + "ais": "An analysis of the Models's snow properties 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 SNOW COVER 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: + run_summary = el.Table( + title="Case Summary", data=config["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 snow property 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"Snow property components {SEASON_NAME[season]} ({season})", + images[season], + ), + ] + + 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 SNOW PROPERTY 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/time_series_plot.py b/livvext/time_series_plot.py index 1bcf324..6b3dd05 100644 --- a/livvext/time_series_plot.py +++ b/livvext/time_series_plot.py @@ -100,6 +100,7 @@ def main(args, config): _obs_in[rvers] = lxc.parse_var( data_var[rvers], obs_data[rvers], _scale[rvers] ) + try: _model_plt = lxc.parse_var(data_var["model"], model_data, _scale["model"]) except KeyError: @@ -111,7 +112,8 @@ def main(args, config): mask_r[data_var["title"]] = {} area_r[data_var["title"]] = {} - for _vers in ["dset_a"]: + # for _vers in ["dset_a"]: + for _vers in obs_data: obs_aavg[data_var["title"]][_vers], mask_r[_vers], area_r[_vers], _ = ( lxc.area_avg( _obs_in[_vers], @@ -124,13 +126,13 @@ def main(args, config): sum_out=_do_sum, ) ) - + _model_area_file = config["masks"].get( + "model_native", config["masks"].get("model") + ) model_aavg[data_var["title"]], _, _, _ = lxc.area_avg( _model_plt, {}, - area_file=config["masks"]["model_native"].format( - icesheet=config["icesheet"] - ), + area_file=_model_area_file.format(icesheet=config["icesheet"]), area_var="area", mask_var="Icemask", sum_out=_do_sum, @@ -140,29 +142,62 @@ def main(args, config): lw = 1.1 _contrib_signs = data_var.get("ac_contrib_sign", None) if _contrib_signs is not None: - obs_contrib_sign = _contrib_signs.get("dset_a", 1) model_contrib_sign = _contrib_signs.get("model", 1) else: - obs_contrib_sign = 1 model_contrib_sign = 1 - _obs_plt = ( - obs_aavg[data_var["title"]]["dset_a"] * obs_contrib_sign * _aavg_scale - ).squeeze() - try: - _model_plt = ( - model_aavg[data_var["title"]] - * model_contrib_sign - * _aavg_scale - * lxu.eval_expr(_scale["model"]) + # _obs_plt = ( + # obs_aavg[data_var["title"]]["dset_a"] * obs_contrib_sign * _aavg_scale + # ).squeeze() + _obs_plt = {} + for _dset in obs_aavg[data_var["title"]]: + if _contrib_signs is not None: + obs_contrib_sign = _contrib_signs.get(_dset, 1) + else: + obs_contrib_sign = 1 + _obs_plt[_dset] = ( + obs_aavg[data_var["title"]][_dset] * obs_contrib_sign * _aavg_scale ) - except TypeError: - raise + + _model_plt = ( + model_aavg[data_var["title"]] + * model_contrib_sign + * _aavg_scale + * lxu.eval_expr(_scale["model"]) + ) model_m, model_b, model_t = compute_trend(ts_data["model"].time, _model_plt) - obs_m, obs_b, obs_t = compute_trend(ts_data["dset_a"].time, _obs_plt) + obs_trends = {} + for _dset in ts_data: + if "model" not in _dset: + obs_trends[_dset] = compute_trend(ts_data[_dset].time, _obs_plt[_dset]) + + nplts = len(_obs_plt) + 1 + _ncols = np.ceil(np.sqrt(nplts)) + _nrows = np.ceil(nplts / _ncols) + if _ncols == _nrows > 1: + figsize = (12, 12) + fontsize_legend = 8 + elif _ncols == _nrows == 1: + figsize = (12, 6) + fontsize_legend = 12 + else: + figsize = (12, 5) + fontsize_legend = 8 + + fig, axes = plt.subplots( + nrows=int(_nrows), + ncols=int(_ncols), + figsize=figsize, + sharey=True, + dpi=config.get("img_dpi", 90), + ) + + if nplts > 1: + axes = axes.flatten() + else: + axes = [axes] - fig, axes = plt.subplots(1, 2, figsize=(12, 5), sharey=True) var_label = f" {data_var['title']}" # Plot model time series @@ -183,53 +218,63 @@ def main(args, config): ls="--", ) - axes[0].set_xlabel("Model Time") + axes[0].set_xlabel("Model Time [year]", fontsize=fontsize_legend) - # Plot obs time series - axes[1].plot( - ts_data["dset_a"].time, - _obs_plt.squeeze(), - label=var_label, - color=color, - lw=lw, - ) - # Plot obs trend line - axes[1].plot( - ts_data["dset_a"].time, - obs_m * obs_t + obs_b, - label=f"{obs_m:.3e} * t + {obs_b:.3e}", - color="k", - lw=lw * 0.9, - ls="--", - ) + for obix, _dset in enumerate(_obs_plt): + # Plot obs time series + axes[obix + 1].plot( + ts_data[_dset].time, + _obs_plt[_dset].squeeze(), + label=var_label, + color=color, + lw=lw, + ) + # Plot obs trend line + obs_m, obs_b, obs_t = obs_trends[_dset] + axes[obix + 1].plot( + ts_data[_dset].time, + obs_m * obs_t + obs_b, + label=f"{obs_m:.3e} * t + {obs_b:.3e}", + color="k", + lw=lw * 0.9, + ls="--", + ) + + axes[obix + 1].set_xlabel( + f"Time ({config['dataset_names'][_dset]})", fontsize=fontsize_legend + ) + _ = axes[obix + 1].set_title(config["dataset_names"][_dset]) - axes[1].set_xlabel(f"Time ({config['dataset_names']['dset_a']})") for _axis in axes: _axis.grid(visible=True, ls="--") if _aavg_units == "": - axes[0].set_ylabel(f"[{_units}]") + axes[0].set_ylabel(f"[{_units}]", fontsize=fontsize_legend) _trend_units = f"{_units}/yr" else: - axes[0].set_ylabel(f"[{_aavg_units}]") + axes[0].set_ylabel(f"[{_aavg_units}]", fontsize=fontsize_legend) _trend_units = f"{_aavg_units}/yr" + # If units are already a flux per year, make it read per year^2 + if _trend_units[-8:] == "yr^-1/yr": + _trend_units = _trend_units.replace(_trend_units[-8:], "yr^-2") + for axis in axes: axis.grid(visible=True, ls="--", lw=0.5) - axis.legend(fontsize=8) + axis.legend(fontsize=fontsize_legend) _modelname = config["dataset_names"].get( "model", config["dataset_names"].get("model_native") ) _ = axes[0].set_title(_modelname) - _ = axes[1].set_title(config["dataset_names"]["dset_a"]) plt.tight_layout() if not Path(args.out).exists(): Path(args.out).mkdir(parents=True) + ext = config.get("img_extn", "png") img_file = os.path.join( args.out, f"{lxc.img_file_prefix(config)}_" - f"{data_var['title'].lower().replace(' ', '_')}_timeseries.png", + f"{data_var['title'].lower().replace(' ', '_')}_timeseries.{ext}", ) fig.savefig(img_file) img_link = os.path.join( diff --git a/livvext/utils.py b/livvext/utils.py index ae5cbad..53260a2 100644 --- a/livvext/utils.py +++ b/livvext/utils.py @@ -54,7 +54,7 @@ def bib2html(bib, style=None, backend=None): style : `pybtex.style.formatting.BaseStyle`, optional Bibliography style to output, by default None, which uses ``pybtex.style.formatting.plain.Style`` - backend : `pybtex.backends.BaseBackend`, optional + backend : ``pybtex.backends.BaseBackend``, optional HTML backend to format HTML output, by default None, which uses ``pybtex.backends.html.Backend`` diff --git a/pyproject.toml b/pyproject.toml index 7c24f72..fda0df3 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.3.1", + "livvkit>=3.4.0", ] classifiers = [ @@ -155,8 +155,18 @@ intersphinx = [ "https://xarray.pydata.org/en/latest/objects.inv", "https://docs.pybtex.org/objects.inv", "https://livvkit.github.io/Docs/objects.inv", + "http://docs.scipy.org/doc/numpy/objects.inv", ] theme = "readthedocs" -privacy = ["PRIVATE:**.__*__", "PUBLIC:**.__init__", "PRIVATE:**.ipynb_checkpoints"] -add-package = ["./livvext", "./livvext/smb", "./livvext/energy"] +privacy = [ + "PRIVATE:**.__*__", + "PUBLIC:**.__init__", + "PRIVATE:**.ipynb_checkpoints", +] +add-package = [ + "./livvext", + "./livvext/smb", + "./livvext/energy", + "./livvext/snow", +] diff --git a/tests/conftest.py b/tests/conftest.py index 69b2da0..8590582 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -9,3 +9,10 @@ def generate_livv_output(): outdir = "simple_extn_output" __main__.main(["-V", "tests/simple_test.yml", "-o", outdir]) return Path(outdir, "index.json") + + +@pytest.fixture(scope="session") +def generate_livv_output_from_output(): + outdir = "simple_extn_output_from_output" + __main__.main(["-V", "simple_extn_output/livvkit.yml", "-o", outdir]) + return Path(outdir, "index.json") diff --git a/tests/extension_simple.py b/tests/extension_simple.py index f184358..36d068a 100644 --- a/tests/extension_simple.py +++ b/tests/extension_simple.py @@ -51,13 +51,15 @@ def run(name, config): """ # TODO: Put your analysis here element_list = [ - el.Error("Unimplemented test", "This test contains no analysis code!"), + el.RawHTML("Unimplemented test
This test contains no analysis code!"), el.Table( title="Sample Table", data={"row1": [1, 2, 3], "row2": [4, 5, 6]}, transpose=True, ), ] + if config.get("throw_exception", False): + raise ValueError("Testing failure mode...this is what an error looks like!") return el.Page( name, diff --git a/tests/simple_test.yml b/tests/simple_test.yml index 94336fe..874ff6b 100644 --- a/tests/simple_test.yml +++ b/tests/simple_test.yml @@ -5,5 +5,11 @@ common: Clim Years: 1890-1906 ExtensionTest: module: tests/extension_simple.py - description: A minimal LIVVkit extensions test. + desc: A minimal LIVVkit extensions test. + meta: *meta + +BadExtensionTest: + module: tests/extension_simple.py + desc: A minimal LIVVkit extensions test. + throw_exception: True meta: *meta diff --git a/tests/test_common.py b/tests/test_common.py index f85a63f..c658991 100644 --- a/tests/test_common.py +++ b/tests/test_common.py @@ -76,6 +76,42 @@ def test_get_season_bounds(): lxc.get_season_bounds(_testseason, test_year_s, test_year_e) == truth_out[idx] ) + mon_s = 3 + mon_e = 2 + truth_out_mon = [ + ("191503", "202002"), + ("191512", "202002"), + ("191503", "201905"), + ("191506", "201908"), + ("191509", "201911"), + ("191601", "202001"), + ("191601", "202001"), + ("191512", "201912"), + ] + + for idx, _testseason in enumerate(test_seasons): + assert ( + lxc.get_season_bounds( + _testseason, test_year_s, test_year_e, mon_s=mon_s, mon_e=mon_e + ) + == truth_out_mon[idx] + ) + + # Test calling only mon_s + assert lxc.get_season_bounds("ANN", test_year_s, test_year_e, mon_s=5) == ( + "191505", + "202004", + ) + # Test calling only mon_e + assert lxc.get_season_bounds("ANN", test_year_s, test_year_e, mon_e=4) == ( + "191505", + "202004", + ) + # Test with start month in middle of season + assert lxc.get_season_bounds("MAM", test_year_s, test_year_e, mon_s=4) == ( + "191504", + "202003", + ) def test_proc_climo_file(): @@ -105,6 +141,21 @@ def test_proc_climo_file(): assert lxc.proc_climo_file(config, "test_1", _season) == truth_1[idx] assert lxc.proc_climo_file(config, "test_2", _season) == truth_2[idx] + config_non_jan = dict(config) + config_non_jan["mon_s"] = 3 + config_non_jan["mon_e"] = 12 + + truth_non_jan = [ + "E3SMCASE.F2010.ne4pg2_oQU480_ANN_190003_202012_climo.nc", + "E3SMCASE.F2010.ne4pg2_oQU480_DJF_190012_202012_climo.nc", + "E3SMCASE.F2010.ne4pg2_oQU480_01_190001_202001_climo.nc", + "E3SMCASE.F2010.ne4pg2_oQU480_10_190010_202010_climo.nc", + ] + for idx, _season in enumerate(test_seasons): + assert ( + lxc.proc_climo_file(config_non_jan, "test_1", _season) == truth_non_jan[idx] + ) + def test_get_cycle(): """""" diff --git a/tests/test_simple.py b/tests/test_simple.py index 0464c9d..cbc499b 100644 --- a/tests/test_simple.py +++ b/tests/test_simple.py @@ -25,3 +25,29 @@ def test_simple_extn(generate_livv_output): assert test_data["Page"]["elements"][0]["Table"]["title"] == "Validation", ( "TABLE TITLE INCORRECT" ) + + +def test_simple_extn_output(generate_livv_output_from_output): + with open(generate_livv_output_from_output, "r") as _fin: + test_data = json.loads(_fin.read()) + + assert "Page" in test_data, "LIVVkit Page not found in extn output" + test_fields = [ + "elements", + "title", + "description", + "_ref_list", + "Data", + "__module__", + "_html_template", + "_latex_template", + ] + for _field in test_fields: + assert _field in test_data["Page"], f"{_field} not found in Page data" + + assert len(test_data["Page"]["elements"][0]["Table"]["data"]) > 0, ( + "NOT ENOUGH ELEMENTS FOR NAV TO BE GENERATED" + ) + assert test_data["Page"]["elements"][0]["Table"]["title"] == "Validation", ( + "TABLE TITLE INCORRECT" + )