diff --git a/.github/parm/use_case_groups.json b/.github/parm/use_case_groups.json index b765aef421..c5c83157a9 100644 --- a/.github/parm/use_case_groups.json +++ b/.github/parm/use_case_groups.json @@ -51,7 +51,7 @@ }, { "category": "marine_and_coastal", - "index_list": "0", + "index_list": "0-1", "new": false }, { diff --git a/docs/_static/marine_and_coastal-GridStat_fcstRTOFS_obsOSTIA_iceCover.png b/docs/_static/marine_and_coastal-GridStat_fcstRTOFS_obsOSTIA_iceCover.png new file mode 100644 index 0000000000..df1989bb32 Binary files /dev/null and b/docs/_static/marine_and_coastal-GridStat_fcstRTOFS_obsOSTIA_iceCover.png differ diff --git a/docs/use_cases/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover.py b/docs/use_cases/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover.py new file mode 100644 index 0000000000..d727ae9dea --- /dev/null +++ b/docs/use_cases/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover.py @@ -0,0 +1,164 @@ +""" +GridStat: Python Embedding to read and process ice cover +======================================================== + +model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover.conf + +""" +############################################################################## +# Scientific Objective +# -------------------- +# +# This use case utilizes Python embedding to extract several statistics from the ice cover data over both pole regions, +# which was already being done in a closed system. By producing the same output via METplus, this use case +# provides standardization and reproducible results. + +############################################################################## +# Datasets +# -------- +# +# | **Forecast:** RTOFS ice cover file via Python Embedding script/file +# +# | **Observation:** OSTIA ice cover file via Python Embedding script/file +# +# | **Location:** All of the input data required for this use case can be found in the met_test sample data tarball. Click here to the METplus releases page and download sample data for the appropriate release: https://github.com/dtcenter/METplus/releases +# | This tarball should be unpacked into the directory that you will set the value of INPUT_BASE. See `Running METplus`_ section for more information. +# +# | **Data Source:** JPL's PODAAC and NCEP's FTPPRD data servers +# | + +############################################################################## +# External Dependencies +# --------------------- +# +# You will need to use a version of Python 3.6+ that has the following packages installed: +# +# * scikit-learn +# * pyproj +# * pyresample +# +# If the version of Python used to compile MET did not have these libraries at the time of compilation, you will need to add these packages or create a new Python environment with these packages. +# +# If this is the case, you will need to set the MET_PYTHON_EXE environment variable to the path of the version of Python you want to use. If you want this version of Python to only apply to this use case, set it in the [user_env_vars] section of a METplus configuration file.: +# +# [user_env_vars] +# MET_PYTHON_EXE = /path/to/python/with/required/packages/bin/python + +############################################################################## +# METplus Components +# ------------------ +# +# This use case utilizes the METplus GridStat wrapper to generate a +# command to run the MET tool GridStat with Python Embedding for the specified user hemispheres + +############################################################################## +# METplus Workflow +# ---------------- +# +# GridStat is the only tool called in this example. This use case will pass in the two +# hemispheres via a custom loop list, with both the observation and forecast gridded data +# being pulled from the files via Python Embedding. All of the desired statistics reside in the CNT line type, +# so that is the only output requested. +# It processes the following run time: +# +# | **Valid:** 2021-03-05 0Z +# | + +############################################################################## +# METplus Configuration +# --------------------- +# +# METplus first loads all of the configuration files found in parm/metplus_config, +# then it loads any configuration files passed to METplus via the command line +# with the -c option, i.e. -c parm/use_cases/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover.conf +# +# .. highlight:: bash +# .. literalinclude:: ../../../../parm/use_cases/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover.conf + +############################################################################## +# MET Configuration +# --------------------- +# +# METplus sets environment variables based on user settings in the METplus configuration file. +# See :ref:`How METplus controls MET config file settings` for more details. +# +# **YOU SHOULD NOT SET ANY OF THESE ENVIRONMENT VARIABLES YOURSELF! THEY WILL BE OVERWRITTEN BY METPLUS WHEN IT CALLS THE MET TOOLS!** +# +# If there is a setting in the MET configuration file that is currently not supported by METplus you'd like to control, please refer to: +# :ref:`Overriding Unsupported MET config file settings` +# +# .. note:: See the :ref:`GridStat MET Configuration` section of the User's Guide for more information on the environment variables used in the file below: +# +# .. highlight:: bash +# .. literalinclude:: ../../../../parm/met_config/GridStatConfig_wrapped + +############################################################################## +# Python Embedding +# ---------------- +# +# This use case uses one Python script to read forecast and observation data +# +# parm/use_cases/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover/read_ice_data.py +# +# .. highlight:: python +# .. literalinclude:: ../../../../parm/use_cases/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover/read_ice_data.py +# + +############################################################################## +# Running METplus +# --------------- +# +# This use case can be run two ways: +# +# 1) Passing in GridStat_fcstRTOFS_obsOSTIA_iceCover.conf then a user-specific system configuration file:: +# +# run_metplus.py -c /path/to/METplus/parm/use_cases/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover.conf -c /path/to/user_system.conf +# +# 2) Modifying the configurations in parm/metplus_config, then passing in GridStat_fcstRTOFS_obsOSTIA_iceCover.conf:: +# +# run_metplus.py -c /path/to/METplus/parm/use_cases/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover.conf +# +# The former method is recommended. Whether you add them to a user-specific configuration file or modify the metplus_config files, the following variables must be set correctly: +# +# * **INPUT_BASE** - Path to directory where sample data tarballs are unpacked (See Datasets section to obtain tarballs). This is not required to run METplus, but it is required to run the examples in parm/use_cases +# * **OUTPUT_BASE** - Path where METplus output will be written. This must be in a location where you have write permissions +# * **MET_INSTALL_DIR** - Path to location where MET is installed locally +# +# Example User Configuration File:: +# +# [dir] +# INPUT_BASE = /path/to/sample/input/data +# OUTPUT_BASE = /path/to/output/dir +# MET_INSTALL_DIR = /path/to/met-X.Y +# +# **NOTE:** All of these items must be found under the [dir] section. +# + +############################################################################## +# Expected Output +# --------------- +# +# A successful run will output the following both to the screen and to the logfile:: +# +# INFO: METplus has successfully finished running. +# +# Refer to the value set for **OUTPUT_BASE** to find where the output data was generated. +# Output for thisIce use case will be found in 20210305 (relative to **OUTPUT_BASE**) +# and will contain the following files: +# +# * grid_stat_north_000000L_20210305_120000V_cnt.txt +# * grid_stat_south_000000L_20210305_120000V_cnt.txt +# * grid_stat_north_000000L_20210305_120000V.stat +# * grid_stat_south_000000L_20210305_120000V.stat + +############################################################################## +# Keywords +# -------- +# +# .. note:: +# `GridStatToolUseCase `_ +# `PythonEmbeddingFileUseCase `_ +# `MarineAndCoastalAppUseCase `_ +# +# sphinx_gallery_thumbnail_path = '_static/marine_and_coastal-GridStat_fcstRTOFS_obsOSTIA_iceCover.png' +# diff --git a/internal_tests/use_cases/all_use_cases.txt b/internal_tests/use_cases/all_use_cases.txt index da4924dbd9..6a8935fb29 100644 --- a/internal_tests/use_cases/all_use_cases.txt +++ b/internal_tests/use_cases/all_use_cases.txt @@ -88,6 +88,7 @@ Category: data_assimilation Category: marine_and_coastal 0::PlotDataPlane_obsHYCOM_coordTripolar::model_applications/marine_and_coastal/PlotDataPlane_obsHYCOM_coordTripolar.conf:: xesmf_env, py_embed +1::GridStat_fcstRTOFS_obsOSTIA_iceCover::model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover.conf:: icecover_env, py_embed Category: medium_range diff --git a/parm/use_cases/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover.conf b/parm/use_cases/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover.conf new file mode 100644 index 0000000000..2af2870a2d --- /dev/null +++ b/parm/use_cases/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover.conf @@ -0,0 +1,263 @@ +# GridStat METplus Configuration + +# section heading for [config] variables - all items below this line and +# before the next section heading correspond to the [config] section +[config] + +# List of applications to run - only GridStat for this case +PROCESS_LIST = GridStat + +# time looping - options are INIT, VALID, RETRO, and REALTIME +# If set to INIT or RETRO: +# INIT_TIME_FMT, INIT_BEG, INIT_END, and INIT_INCREMENT must also be set +# If set to VALID or REALTIME: +# VALID_TIME_FMT, VALID_BEG, VALID_END, and VALID_INCREMENT must also be set +LOOP_BY = VALID + +# Format of INIT_BEG and INT_END using % items +# %Y = 4 digit year, %m = 2 digit month, %d = 2 digit day, etc. +# see www.strftime.org for more information +# %Y%m%d%H expands to YYYYMMDDHH +VALID_TIME_FMT = %Y%m%d + +# Start time for METplus run - must match INIT_TIME_FMT +VALID_BEG=20210305 + +# End time for METplus run - must match INIT_TIME_FMT +VALID_END=20210305 + +# Increment between METplus runs (in seconds if no units are specified) +# Must be >= 60 seconds +VALID_INCREMENT = 1M + +# List of forecast leads to process for each run time (init or valid) +# In hours if units are not specified +# If unset, defaults to 0 (don't loop through forecast leads) +LEAD_SEQ = 0 + +GRID_STAT_CUSTOM_LOOP_LIST = north, south + +# Order of loops to process data - Options are times, processes +# Not relevant if only one item is in the PROCESS_LIST +# times = run all wrappers in the PROCESS_LIST for a single run time, then +# increment the run time and run all wrappers again until all times have +# been evaluated. +# processes = run the first wrapper in the PROCESS_LIST for all times +# specified, then repeat for the next item in the PROCESS_LIST until all +# wrappers have been run +LOOP_ORDER = times + +# Verbosity of MET output - overrides LOG_VERBOSITY for GridStat only +#LOG_GRID_STAT_VERBOSITY = 2 + +# Location of MET config file to pass to GridStat +GRID_STAT_CONFIG_FILE = {PARM_BASE}/met_config/GridStatConfig_wrapped + +# grid to remap data. Value is set as the 'to_grid' variable in the 'regrid' dictionary +# See MET User's Guide for more information +GRID_STAT_REGRID_TO_GRID = NONE + +#GRID_STAT_INTERP_FIELD = +#GRID_STAT_INTERP_VLD_THRESH = +#GRID_STAT_INTERP_SHAPE = +#GRID_STAT_INTERP_TYPE_METHOD = +#GRID_STAT_INTERP_TYPE_WIDTH = + +#GRID_STAT_NC_PAIRS_VAR_NAME = + +#GRID_STAT_CLIMO_MEAN_TIME_INTERP_METHOD = +#GRID_STAT_CLIMO_STDEV_TIME_INTERP_METHOD = + +GRID_STAT_GRID_WEIGHT_FLAG = AREA + +# Name to identify model (forecast) data in output +MODEL = RTOFS + +# Name to identify observation data in output +OBTYPE = UKMO + +# set the desc value in the GridStat MET config file +GRID_STAT_DESC = NA + +# List of variables to compare in GridStat - FCST_VAR1 variables correspond +# to OBS_VAR1 variables +# Note [FCST/OBS/BOTH]_GRID_STAT_VAR_NAME can be used instead if different evaluations +# are needed for different tools + +# Name of forecast variable 1 +FCST_VAR1_NAME = {CONFIG_DIR}/read_ice_data.py {INPUT_BASE}/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover/{valid?fmt=%Y%m%d}_rtofs_glo_2ds_n024_ice.nc {INPUT_BASE}/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover/{valid?fmt=%Y%m%d}12_UKMO_L4.nc {custom} fcst + +# List of levels to evaluate for forecast variable 1 +# A03 = 3 hour accumulation in GRIB file +FCST_VAR1_LEVELS = + +# List of thresholds to evaluate for each name/level combination for +# forecast variable 1 +FCST_VAR1_THRESH = + +#FCST_GRID_STAT_FILE_TYPE = + +# Name of observation variable 1 +OBS_VAR1_NAME = {CONFIG_DIR}/read_ice_data.py {INPUT_BASE}/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover/{valid?fmt=%Y%m%d}_rtofs_glo_2ds_n024_ice.nc {INPUT_BASE}/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover/{valid?fmt=%Y%m%d}12_UKMO_L4.nc {custom} obs + + +# List of levels to evaluate for observation variable 1 +# (*,*) is NetCDF notation - must include quotes around these values! +# must be the same length as FCST_VAR1_LEVELS +OBS_VAR1_LEVELS = + +# List of thresholds to evaluate for each name/level combination for +# observation variable 1 +OBS_VAR1_THRESH = + +#GRID_STAT_MET_CONFIG_OVERRIDES = cat_thresh = [>=0.15]; +#BOTH_VAR1_THRESH = >=0.15 + +#OBS_GRID_STAT_FILE_TYPE = + +# Time relative to valid time (in seconds) to allow files to be considered +# valid. Set both BEGIN and END to 0 to require the exact time in the filename +# Not used in this example. +FCST_GRID_STAT_FILE_WINDOW_BEGIN = 0 +FCST_GRID_STAT_FILE_WINDOW_END = 0 +OBS_GRID_STAT_FILE_WINDOW_BEGIN = 0 +OBS_GRID_STAT_FILE_WINDOW_END = 0 + +# MET GridStat neighborhood values +# See the MET User's Guide GridStat section for more information + +# width value passed to nbrhd dictionary in the MET config file +GRID_STAT_NEIGHBORHOOD_WIDTH = 1 + +# shape value passed to nbrhd dictionary in the MET config file +GRID_STAT_NEIGHBORHOOD_SHAPE = SQUARE + +# cov thresh list passed to nbrhd dictionary in the MET config file +GRID_STAT_NEIGHBORHOOD_COV_THRESH = >=0.5 + +# Set to true to run GridStat separately for each field specified +# Set to false to create one run of GridStat per run time that +# includes all fields specified. +GRID_STAT_ONCE_PER_FIELD = False + +# Set to true if forecast data is probabilistic +FCST_IS_PROB = false + +# Only used if FCST_IS_PROB is true - sets probabilistic threshold +FCST_GRID_STAT_PROB_THRESH = ==0.1 + +# Set to true if observation data is probabilistic +# Only used if configuring forecast data as the 'OBS' input +OBS_IS_PROB = false + +# Only used if OBS_IS_PROB is true - sets probabilistic threshold +OBS_GRID_STAT_PROB_THRESH = ==0.1 + +GRID_STAT_OUTPUT_PREFIX = {custom} + +#GRID_STAT_CLIMO_MEAN_FILE_NAME = +#GRID_STAT_CLIMO_MEAN_FIELD = +#GRID_STAT_CLIMO_MEAN_REGRID_METHOD = +#GRID_STAT_CLIMO_MEAN_REGRID_WIDTH = +#GRID_STAT_CLIMO_MEAN_REGRID_VLD_THRESH = +#GRID_STAT_CLIMO_MEAN_REGRID_SHAPE = +#GRID_STAT_CLIMO_MEAN_TIME_INTERP_METHOD = +#GRID_STAT_CLIMO_MEAN_MATCH_MONTH = +#GRID_STAT_CLIMO_MEAN_DAY_INTERVAL = +#GRID_STAT_CLIMO_MEAN_HOUR_INTERVAL = + +#GRID_STAT_CLIMO_STDEV_FILE_NAME = +#GRID_STAT_CLIMO_STDEV_FIELD = +#GRID_STAT_CLIMO_STDEV_REGRID_METHOD = +#GRID_STAT_CLIMO_STDEV_REGRID_WIDTH = +#GRID_STAT_CLIMO_STDEV_REGRID_VLD_THRESH = +#GRID_STAT_CLIMO_STDEV_REGRID_SHAPE = +#GRID_STAT_CLIMO_STDEV_TIME_INTERP_METHOD = +#GRID_STAT_CLIMO_STDEV_MATCH_MONTH = +#GRID_STAT_CLIMO_STDEV_DAY_INTERVAL = +#GRID_STAT_CLIMO_STDEV_HOUR_INTERVAL = + + +#GRID_STAT_CLIMO_CDF_BINS = 1 +#GRID_STAT_CLIMO_CDF_CENTER_BINS = False +#GRID_STAT_CLIMO_CDF_WRITE_BINS = True + +#GRID_STAT_OUTPUT_FLAG_FHO = NONE +#GRID_STAT_OUTPUT_FLAG_CTC = NONE +#GRID_STAT_OUTPUT_FLAG_CTS = NONE +#GRID_STAT_OUTPUT_FLAG_MCTC = NONE +#GRID_STAT_OUTPUT_FLAG_MCTS = NONE +GRID_STAT_OUTPUT_FLAG_CNT = BOTH +#GRID_STAT_OUTPUT_FLAG_SL1L2 = NONE +#GRID_STAT_OUTPUT_FLAG_SAL1L2 = NONE +#GRID_STAT_OUTPUT_FLAG_VL1L2 = NONE +#GRID_STAT_OUTPUT_FLAG_VAL1L2 = NONE +#GRID_STAT_OUTPUT_FLAG_VCNT = NONE +#GRID_STAT_OUTPUT_FLAG_PCT = NONE +#GRID_STAT_OUTPUT_FLAG_PSTD = NONE +#GRID_STAT_OUTPUT_FLAG_PJC = NONE +#GRID_STAT_OUTPUT_FLAG_PRC = NONE +#GRID_STAT_OUTPUT_FLAG_ECLV = BOTH +#GRID_STAT_OUTPUT_FLAG_NBRCTC = NONE +#GRID_STAT_OUTPUT_FLAG_NBRCTS = NONE +#GRID_STAT_OUTPUT_FLAG_NBRCNT = NONE +#GRID_STAT_OUTPUT_FLAG_GRAD = BOTH +#GRID_STAT_OUTPUT_FLAG_DMAP = NONE + +#GRID_STAT_NC_PAIRS_FLAG_LATLON = FALSE +#GRID_STAT_NC_PAIRS_FLAG_RAW = FALSE +#GRID_STAT_NC_PAIRS_FLAG_DIFF = FALSE +#GRID_STAT_NC_PAIRS_FLAG_CLIMO = FALSE +#GRID_STAT_NC_PAIRS_FLAG_CLIMO_CDP = FALSE +#GRID_STAT_NC_PAIRS_FLAG_WEIGHT = FALSE +#GRID_STAT_NC_PAIRS_FLAG_NBRHD = FALSE +#GRID_STAT_NC_PAIRS_FLAG_FOURIER = FALSE +#GRID_STAT_NC_PAIRS_FLAG_GRADIENT = FALSE +#GRID_STAT_NC_PAIRS_FLAG_DISTANCE_MAP = FALSE +#GRID_STAT_NC_PAIRS_FLAG_APPLY_MASK = FALSE + + +# End of [config] section and start of [dir] section +[dir] +#use case configuration file directory +CONFIG_DIR = {PARM_BASE}/use_cases/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover +# directory containing forecast input to GridStat +FCST_GRID_STAT_INPUT_DIR = + +# directory containing observation input to GridStat +OBS_GRID_STAT_INPUT_DIR = + +# directory containing climatology mean input to GridStat +# Not used in this example +GRID_STAT_CLIMO_MEAN_INPUT_DIR = + +# directory containing climatology mean input to GridStat +# Not used in this example +GRID_STAT_CLIMO_STDEV_INPUT_DIR = + +# directory to write output from GridStat +GRID_STAT_OUTPUT_DIR = {OUTPUT_BASE} + +# End of [dir] section and start of [filename_templates] section +[filename_templates] + +# Template to look for forecast input to GridStat relative to FCST_GRID_STAT_INPUT_DIR +FCST_GRID_STAT_INPUT_TEMPLATE = PYTHON_NUMPY + +# Template to look for observation input to GridStat relative to OBS_GRID_STAT_INPUT_DIR +OBS_GRID_STAT_INPUT_TEMPLATE = PYTHON_NUMPY + +# Optional subdirectories relative to GRID_STAT_OUTPUT_DIR to write output from GridStat +GRID_STAT_OUTPUT_TEMPLATE = {valid?fmt=%Y%m%d} + +# Template to look for climatology input to GridStat relative to GRID_STAT_CLIMO_MEAN_INPUT_DIR +# Not used in this example +GRID_STAT_CLIMO_MEAN_INPUT_TEMPLATE = + +# Template to look for climatology input to GridStat relative to GRID_STAT_CLIMO_STDEV_INPUT_DIR +# Not used in this example +GRID_STAT_CLIMO_STDEV_INPUT_TEMPLATE = + +# Used to specify one or more verification mask files for GridStat +# Not used for this example +GRID_STAT_VERIFICATION_MASK_TEMPLATE = diff --git a/parm/use_cases/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover/read_ice_data.py b/parm/use_cases/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover/read_ice_data.py new file mode 100644 index 0000000000..0e1343e51e --- /dev/null +++ b/parm/use_cases/model_applications/marine_and_coastal/GridStat_fcstRTOFS_obsOSTIA_iceCover/read_ice_data.py @@ -0,0 +1,221 @@ +#!/bin/env python +""" +Code adapted from +Todd Spindler +NOAA/NWS/NCEP/EMC + +Designed to read in RTOFS and OSTIA data +and based on user input, process Arctic or Antarctic regions +for ice cover, and pass back in memory the forecast or observation +data field +""" + +import numpy as np +from sklearn.metrics import mean_squared_error +import xarray as xr +import pandas as pd +from pyproj import Geod +import pyresample as pyr +from datetime import datetime, date +import os, sys + +#------------------------------------- +def iceArea(lon1,lat1,ice1): + """ + Compute the cell side dimensions (Vincenty) and the cell surface areas. + This assumes the ice has already been masked and subsampled as needed + returns ice_extent, ice_area, surface_area = iceArea(lon,lat,ice) + surface_area is the computed grid areas in km**2) + """ + lon=lon1.copy() + lat=lat1.copy() + ice=ice1.copy() + g=Geod(ellps='WGS84') + _,_,xdist=g.inv(lon,lat,np.roll(lon,-1,axis=1),np.roll(lat,-1,axis=1)) + _,_,ydist=g.inv(lon,lat,np.roll(lon,-1,axis=0),np.roll(lat,-1,axis=0)) + xdist=np.ma.array(xdist,mask=ice.mask)/1000. + ydist=np.ma.array(ydist,mask=ice.mask)/1000. + xdist=xdist[:-1,:-1] + ydist=ydist[:-1,:-1] + ice=ice[:-1,:-1] # just to match the roll + extent=xdist*ydist # extent is surface area only + area=xdist*ydist*ice # ice area is actual ice cover (area * concentration) + return extent.flatten().sum(), area.flatten().sum(), extent + +#-------------------------------------------------------- + +try: + rtofsfile, icefile, hemisphere, file_flag = sys.argv[1:] +except ValueError: + print("Must specify the following elements: fcst_file obs_file hemisphere file_flag") + sys.exit(1) + +HEMISPHERES = ['north', 'south'] +FILE_FLAGS = ['fcst', 'obs'] + +if hemisphere not in HEMISPHERES or file_flag not in FILE_FLAGS: + print(f"ERROR: Invalid hemisphere value ({hemisphere}) or file_flag value ({file_flag}) " + f"Valid options are {HEMISPHERES} {FILE_FLAGS}") + sys.exit(1) + +print('processing',hemisphere+'ern hemisphere') +if hemisphere == 'north': + bounding_lat=30.98 +else: + bounding_lat=-39.23 + + +# load rtofs data and subset to hemisphere of interest and ice cover min value +print('reading rtofs ice') +if not os.path.exists(rtofsfile): + print('missing rtofs file',rtofsfile) + sys.exit(1) +rtofs=xr.open_dataset(rtofsfile,decode_times=True) +rtofs=rtofs.ice_coverage[0,:-1,] + +# load OSTIA data +print('reading OSTIA ice') +if not os.path.exists(icefile): + print('missing OSTIA ice file',icefile) + sys.exit(1) +ncep=xr.open_dataset(icefile,decode_times=True) +ncep=ncep.rename({'lon':'Longitude','lat':'Latitude'}) +ncep=ncep.sea_ice_fraction.squeeze() + +# trim to polar regions +if hemisphere == 'north': + rtofs=rtofs.where((rtofs.Latitude>=bounding_lat),drop=True) + ncep=ncep.where((ncep.Latitude>=bounding_lat),drop=True) +else: + rtofs=rtofs.where((rtofs.Latitude<=bounding_lat),drop=True) + ncep=ncep.where((ncep.Latitude<=bounding_lat),drop=True) + +# now it's back to masked arrays for the RTOFS data +rlon=rtofs.Longitude.values +rlat=rtofs.Latitude.values +rice=rtofs.to_masked_array() + +nlon=ncep.Longitude.values%360. # shift from -180 - 180 to 0-360 +nlat=ncep.Latitude.values +nlon,nlat=np.meshgrid(nlon,nlat) # shift from 1-d to 2-d arrays +nice=ncep.to_masked_array() + +# mask out values below 15% +rice.mask=np.ma.mask_or(rice.mask,rice<0.15) +nice.mask=np.ma.mask_or(nice.mask,nice<0.15) + +# compute ice area on original grids +print('computing ice area') +ncep_extent,ncep_area,ncep_surface_area=iceArea(nlon,nlat,nice) +rtofs_extent,rtofs_area,rtofs_surface_area=iceArea(rlon,rlat,rice) + +# interpolate rtofs to ncep grid +print('interpolating rtofs to OSTIA grid') + +# pyresample gausssian-weighted kd-tree interp +rlon1=pyr.utils.wrap_longitudes(rlon) +rlat1=rlat.copy() +nlon1=pyr.utils.wrap_longitudes(nlon) +nlat1=nlat.copy() +# define the grids +orig_def = pyr.geometry.GridDefinition(lons=rlon1,lats=rlat1) +targ_def = pyr.geometry.GridDefinition(lons=nlon1,lats=nlat1) +radius=50000 +sigmas=25000 +rice2=pyr.kd_tree.resample_gauss(orig_def,rice,targ_def, + radius_of_influence=radius, + sigmas=sigmas, + nprocs=8, + neighbours=8, + fill_value=None) + +print('creating combined mask') +combined_mask=np.logical_and(nice.mask,rice2.mask) +nice2=nice.filled(fill_value=0.0) +rice2=rice2.filled(fill_value=0.0) +nice2=np.ma.array(nice2,mask=combined_mask) +rice2=np.ma.array(rice2,mask=combined_mask) + +#Create the MET grids based on the file_flag +if file_flag == 'fcst': + met_data = rice2[:-1,:-1] + met_data = met_data[::-1,] + #trim the lat/lon grids so they match the data fields + #note that nice1 lat/lon fields are valid, since rice2 is interpolated to nice2 + lat_met = nlat1[:-1,:-1] + lon_met = nlon1[:-1,:-1] + print("Data shape: "+repr(met_data.shape)) + v_str = rtofsfile.split('_')[-6].split('/')[-1] + v_str = v_str + '_120000' + lat_ll = float(lat_met.min()) + lon_ll = float(lon_met.min()) + n_lat = lat_met.shape[0] + n_lon = lon_met.shape[1] + delta_lat = (float(lat_met.max()) - float(lat_met.min()))/float(n_lat) + delta_lon = (float(lon_met.max()) - float(lon_met.min()))/float(n_lon) + print(f"variables:" + f"lat_ll: {lat_ll} lon_ll: {lon_ll} n_lat: {n_lat} n_lon: {n_lon} delta_lat: {delta_lat} delta_lon: {delta_lon}") + met_data.attrs = { + 'valid': v_str, + 'init': v_str, + 'lead': "00", + 'accum': "00", + 'name': 'ice_coverage', + 'standard_name': rtofs.standard_name, + 'long_name': rtofs.long_name.strip(), + 'level': "SURFACE", + 'units': "UNKNOWN", + + 'grid': { + 'type': "LatLon", + 'name': "RTOFS Grid", + 'lat_ll': lat_ll, + 'lon_ll': lon_ll, + 'delta_lat': delta_lat, + 'delta_lon': delta_lon, + 'Nlat': n_lat, + 'Nlon': n_lon, + } + } + attrs = met_data.attrs +if file_flag == 'obs': + met_data = nice2[:-1,:-1] + met_data = met_data[::-1,] + #modify the lat and lon grids since they need to match the data dimensions, and code cuts the last row/column of data + lat_met = nlat1[:-1,:-1] + lon_met = nlon1[:-1,:-1] + print("Data shape: " +repr(met_data.shape)) + v_str = icefile.split('_')[-3].split('/')[-1] + v_str = v_str[:-2]+'_120000' + lat_ll = float(lat_met.min()) + lon_ll = float(lon_met.min()) + n_lat = lat_met.shape[0] + n_lon = lon_met.shape[1] + delta_lat = (float(lat_met.max()) - float(lat_met.min()))/float(n_lat) + delta_lon = (float(lon_met.max()) - float(lon_met.min()))/float(n_lon) + print(f"variables:" + f"lat_ll: {lat_ll} lon_ll: {lon_ll} n_lat: {n_lat} n_lon: {n_lon} delta_lat: {delta_lat} delta_lon: {delta_lon}") + met_data.attrs = { + 'valid': v_str, + 'init': v_str, + 'lead': "00", + 'accum': "00", + 'name': 'ice_coverage', + 'standard_name': ncep.standard_name, + 'long_name': ncep.long_name.strip(), + 'level': "SURFACE", + 'units': "UNKNOWN", + + 'grid': { + 'type': "LatLon", + 'name': "RTOFS Grid", + 'lat_ll': lat_ll, + 'lon_ll': lon_ll, + 'delta_lat': delta_lat, + 'delta_lon': delta_lon, + 'Nlat': n_lat, + 'Nlon': n_lon, + } + } + attrs = met_data.attrs +