diff --git a/.github/workflows/python_linter.yaml b/.github/workflows/python_linter.yaml index b53fc50855..b63a2a513c 100644 --- a/.github/workflows/python_linter.yaml +++ b/.github/workflows/python_linter.yaml @@ -33,5 +33,8 @@ jobs: # Run python unittests - name: Lint the test directory run: | - export PYTHONPATH=${PWD}/ush - pylint --min-similarity-lines=15 --ignore-imports=yes tests/test_python/ + ./manage_externals/checkout_externals workflow-tools + export PYTHONPATH=$(pwd)/ush:$(pwd)/ush/python_utils/workflow-tools:$(pwd)/ush/python_utils/workflow-tools/src + pylint --ignore-imports=yes tests/test_python/ + pylint ush/create_*.py + pylint ush/generate_FV3LAM_wflow.py diff --git a/.github/workflows/python_unittests.yaml b/.github/workflows/python_unittests.yaml index 0f213ff6bb..5e491dea6e 100644 --- a/.github/workflows/python_unittests.yaml +++ b/.github/workflows/python_unittests.yaml @@ -37,8 +37,8 @@ jobs: # Run python unittests - name: Run python unittests run: | - ./manage_externals/checkout_externals ufs-weather-model + ./manage_externals/checkout_externals ufs-weather-model workflow-tools # exclude test_retrieve_data that is tested in functional test - export PYTHONPATH=${PWD}/ush + export PYTHONPATH=$(pwd)/ush:$(pwd)/ush/python_utils/workflow-tools:$(pwd)/ush/python_utils/workflow-tools/src python3 -m unittest -b tests/test_python/*.py diff --git a/.gitignore b/.gitignore index bc3eee8545..a727b940c0 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ tests/WE2E/log.* ush/__pycache__/ ush/config.yaml ush/python_utils/__pycache__/ +ush/python_utils/workflow-tools/ ush/*.swp *.swp diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000000..0cb488e3d5 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,624 @@ +[MAIN] + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Clear in-memory caches upon conclusion of linting. Useful if running pylint +# in a server-like mode. +clear-cache-post-run=no + +# Load and enable all available extensions. Use --list-extensions to see a list +# all available extensions. +#enable-all-extensions= + +# In error mode, messages with a category besides ERROR or FATAL are +# suppressed, and no reports are done by default. Error mode is compatible with +# disabling specific errors. +#errors-only= + +# Always return a 0 (non-error) status code, even if lint errors are found. +# This is primarily useful in continuous integration scripts. +#exit-zero= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-allow-list= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. (This is an alternative name to extension-pkg-allow-list +# for backward compatibility.) +extension-pkg-whitelist= + +# Return non-zero exit code if any of these messages/categories are detected, +# even if score is above --fail-under value. Syntax same as enable. Messages +# specified are enabled, while categories only check already-enabled messages. +fail-on= + +# Specify a score threshold under which the program will exit with error. +fail-under=10 + +# Interpret the stdin as a python script, whose filename needs to be passed as +# the module_or_package argument. +#from-stdin= + +# Files or directories to be skipped. They should be base names, not paths. +ignore=CVS + +# Add files or directories matching the regular expressions patterns to the +# ignore-list. The regex matches against paths and can be in Posix or Windows +# format. Because '\\' represents the directory delimiter on Windows systems, +# it can't be used as an escape character. +ignore-paths= + +# Files or directories matching the regular expression patterns are skipped. +# The regex matches against base names, not paths. The default value ignores +# Emacs file locks +ignore-patterns=^\.# + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis). It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use, and will cap the count on Windows to +# avoid hangs. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python module names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Minimum Python version to use for version dependent checks. Will default to +# the version used to run pylint. +py-version=3.9 + +# Discover python modules and packages in the file system subtree. +recursive=no + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + +# In verbose mode, extra non-checker-related info will be displayed. +#verbose= + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. If left empty, argument names will be checked with the set +# naming style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. If left empty, attribute names will be checked with the set naming +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Bad variable names regexes, separated by a comma. If names match any regex, +# they will always be refused +bad-names-rgxs= + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. If left empty, class attribute names will be checked +# with the set naming style. +#class-attribute-rgx= + +# Naming style matching correct class constant names. +class-const-naming-style=UPPER_CASE + +# Regular expression matching correct class constant names. Overrides class- +# const-naming-style. If left empty, class constant names will be checked with +# the set naming style. +#class-const-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. If left empty, class names will be checked with the set naming style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. If left empty, constant names will be checked with the set naming +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. If left empty, function names will be checked with the set +# naming style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Good variable names regexes, separated by a comma. If names match any regex, +# they will always be accepted +good-names-rgxs= + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. If left empty, inline iteration names will be checked +# with the set naming style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. If left empty, method names will be checked with the set naming style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. If left empty, module names will be checked with the set naming style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Regular expression matching correct type variable names. If left empty, type +# variable names will be checked with the set naming style. +#typevar-rgx= + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. If left empty, variable names will be checked with the set +# naming style. +#variable-rgx= + + +[CLASSES] + +# Warn about protected attribute access inside special methods +check-protected-access-in-special-methods=no + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=mcs + + +[DESIGN] + +# List of regular expressions of class ancestor names to ignore when counting +# public methods (see R0903) +exclude-too-few-public-methods= + +# List of qualified class names to ignore when counting class parents (see +# R0901) +ignored-parents= + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when caught. +overgeneral-exceptions=builtins.BaseException,builtins.Exception + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow explicit reexports by alias from a package __init__. +allow-reexport-from-package=no + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules= + +# Output a graph (.gv or any supported image format) of external dependencies +# to the given file (report RP0402 must not be disabled). +ext-import-graph= + +# Output a graph (.gv or any supported image format) of all (i.e. internal and +# external) dependencies to the given file (report RP0402 must not be +# disabled). +import-graph= + +# Output a graph (.gv or any supported image format) of internal dependencies +# to the given file (report RP0402 must not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[LOGGING] + +# The type of string formatting that logging methods do. `old` means using % +# formatting, `new` is for `{}` formatting. +logging-format-style=new + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, +# UNDEFINED. +confidence=HIGH, + CONTROL_FLOW, + INFERENCE, + INFERENCE_FAILURE, + UNDEFINED + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then re-enable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead, + logging-fstring-interpolation + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=c-extension-no-member + + +[METHOD_ARGS] + +# List of qualified names (i.e., library.method) which require a timeout +# parameter e.g. 'requests.api.get,requests.api.post' +timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + +# Regular expression of note tags to take in consideration. +notes-rgx= + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit,argparse.parse_error + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'fatal', 'error', 'warning', 'refactor', +# 'convention', and 'info' which contain the number of messages in each +# category, as well as 'statement' which is the total number of statements +# analyzed. This score is used by the global evaluation report (RP0004). +evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +#output-format= + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[SIMILARITIES] + +# Comments are removed from the similarity computation +ignore-comments=yes + +# Docstrings are removed from the similarity computation +ignore-docstrings=yes + +# Imports are removed from the similarity computation +ignore-imports=yes + +# Signatures are removed from the similarity computation +ignore-signatures=yes + +# Minimum lines number of a similarity. +min-similarity-lines=15 + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it work, +# install the 'python-enchant' package. +spelling-dict= + +# List of comma separated words that should be considered directives if they +# appear at the beginning of a comment and should not be checked. +spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[STRING] + +# This flag controls whether inconsistent-quotes generates a warning when the +# character used as a quote delimiter is used inconsistently within a module. +check-quote-consistency=no + +# This flag controls whether the implicit-str-concat should generate a warning +# on implicit string concatenation in sequences defined over several lines. +check-str-concat-over-line-jumps=no + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of symbolic message names to ignore for Mixin members. +ignored-checks-for-mixins=no-member, + not-async-context-manager, + not-context-manager, + attribute-defined-outside-init + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + +# Regex pattern to define which classes are considered mixins. +mixin-class-rgx=.*[Mm]ixin + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of names allowed to shadow builtins +allowed-redefined-builtins= + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io diff --git a/Externals.cfg b/Externals.cfg index b1d865e398..50e38794c7 100644 --- a/Externals.cfg +++ b/Externals.cfg @@ -62,5 +62,14 @@ hash = 0a86f73 local_path = sorc/AQM-utils required = True +[workflow-tools] +protocol = git +repo_url = https://github.com/ufs-community/workflow-tools +# Specify either a branch name or a hash but not both. +# branch = develop +hash = e1b3b6f +local_path = ush/python_utils/workflow-tools +required = True + [externals_description] schema_version = 1.0.0 diff --git a/docs/UsersGuide/source/RocotoInfo.rst b/docs/UsersGuide/source/RocotoInfo.rst index 7557addc7d..ad0ec024c9 100644 --- a/docs/UsersGuide/source/RocotoInfo.rst +++ b/docs/UsersGuide/source/RocotoInfo.rst @@ -11,7 +11,7 @@ system as the task dependencies allow and runs one instance of the workflow for The SRW App workflow is defined in a Jinja-enabled Rocoto XML template called ``FV3LAM_wflow.xml``, which resides in the ``parm`` directory. When the ``generate_FV3LAM_wflow.py`` -script is run, the ``fill_jinja_template.py`` script is called, and the parameters in the template file +script is run, the ``set_template`` uwtool is called, and the parameters in the template file are filled in. The completed file contains the workflow task names, parameters needed by the job scheduler, and task interdependencies. The generated XML file is then copied to the experiment directory: ``$EXPTDIR/FV3LAM_wflow.xml``. diff --git a/docs/UsersGuide/source/RunSRW.rst b/docs/UsersGuide/source/RunSRW.rst index 7dc69c5149..5bea592809 100644 --- a/docs/UsersGuide/source/RunSRW.rst +++ b/docs/UsersGuide/source/RunSRW.rst @@ -755,7 +755,7 @@ The generated workflow will appear in ``$EXPTDIR``, where ``EXPTDIR=${EXPT_BASED .. _WorkflowGeneration: .. figure:: _static/SRW_regional_workflow_gen.png - :alt: Flowchart of the workflow generation process. Scripts are called in the following order: source_util_funcs.sh (which calls bash_utils), then set_FV3nml_sfc_climo_filenames.py, set_FV3nml_ens_stoch_seeds.py, create_diag_table_file.py, and setup.py. setup.py calls several scripts: set_cycle_dates.py, set_grid_params_GFDLgrid.py, set_grid_params_ESGgrid.py, link_fix.py, set_ozone_param.py, set_thompson_mp_fix_files.py, config_defaults.yaml, config.yaml, and valid_param_vals.yaml. Then, it sets a number of variables, including FIXgsm, TOPO_DIR, and SFC_CLIMO_INPUT_DIR variables. Next, set_predef_grid_params.py is called, and the FIXam and FIXLAM directories are set, along with the forecast input files. The setup script also calls set_extrn_mdl_params.py, sets the GRID_GEN_METHOD with HALO, checks various parameters, and generates shell scripts. Then, the workflow generation script sets up YAML-compliant strings and generates the actual Rocoto workflow XML file from the template file (fill_jinja_template.py). The workflow generation script checks the crontab file and, if applicable, copies certain fix files to the experiment directory. Then, it copies templates of various input files to the experiment directory and sets parameters for the input.nml file. Finally, it generates the workflow. Additional information on each step appears in comments within each script. + :alt: Flowchart of the workflow generation process. Scripts are called in the following order: source_util_funcs.sh (which calls bash_utils), then set_FV3nml_sfc_climo_filenames.py, set_FV3nml_ens_stoch_seeds.py, create_diag_table_file.py, and setup.py. setup.py calls several scripts: set_cycle_dates.py, set_grid_params_GFDLgrid.py, set_grid_params_ESGgrid.py, link_fix.py, set_ozone_param.py, set_thompson_mp_fix_files.py, config_defaults.yaml, config.yaml, and valid_param_vals.yaml. Then, it sets a number of variables, including FIXgsm, TOPO_DIR, and SFC_CLIMO_INPUT_DIR variables. Next, set_predef_grid_params.py is called, and the FIXam and FIXLAM directories are set, along with the forecast input files. The setup script also calls set_extrn_mdl_params.py, sets the GRID_GEN_METHOD with HALO, checks various parameters, and generates shell scripts. Then, the workflow generation script produces a YAML configuration file and generates the actual Rocoto workflow XML file from the template file (by calling uwtools set_template). The workflow generation script checks the crontab file and, if applicable, copies certain fix files to the experiment directory. Then, it copies templates of various input files to the experiment directory and sets parameters for the input.nml file. Finally, it generates the workflow. Additional information on each step appears in comments within each script. *Experiment Generation Description* diff --git a/modulefiles/set_pythonpath.lua b/modulefiles/set_pythonpath.lua new file mode 100644 index 0000000000..e816ed6cfc --- /dev/null +++ b/modulefiles/set_pythonpath.lua @@ -0,0 +1,13 @@ +help([[ +This module sets the PYTHONPATH in the user environment to allow the +workflow tools to be imported +]]) + +whatis([===[Sets paths for using workflow-tools with SRW]===]) + +local mod_path, mod_file = splitFileName(myFileName()) +local uwtools_scripts_path = pathJoin(mod_path, "/../ush/python_utils/workflow-tools") +local uwtools_package_path = pathJoin(mod_path, "/../ush/python_utils/workflow-tools/src/") + +prepend_path("PYTHONPATH", uwtools_scripts_path) +prepend_path("PYTHONPATH", uwtools_package_path) diff --git a/modulefiles/tasks/cheyenne/plot_allvars.local.lua b/modulefiles/tasks/cheyenne/plot_allvars.local.lua new file mode 100644 index 0000000000..2263141a0a --- /dev/null +++ b/modulefiles/tasks/cheyenne/plot_allvars.local.lua @@ -0,0 +1,5 @@ +unload("python") +prepend_path("MODULEPATH","/glade/work/epicufsrt/contrib/miniconda3/modulefiles") +load(pathJoin("miniconda3", os.getenv("miniconda3_ver") or "4.12.0")) + +setenv("SRW_ENV", "regional_workflow") diff --git a/modulefiles/tasks/cheyenne/python_srw.lua b/modulefiles/tasks/cheyenne/python_srw.lua index 2263141a0a..57e2c2eed0 100644 --- a/modulefiles/tasks/cheyenne/python_srw.lua +++ b/modulefiles/tasks/cheyenne/python_srw.lua @@ -2,4 +2,4 @@ unload("python") prepend_path("MODULEPATH","/glade/work/epicufsrt/contrib/miniconda3/modulefiles") load(pathJoin("miniconda3", os.getenv("miniconda3_ver") or "4.12.0")) -setenv("SRW_ENV", "regional_workflow") +setenv("SRW_ENV", "workflow_tools") diff --git a/modulefiles/tasks/gaea/plot_allvars.local.lua b/modulefiles/tasks/gaea/plot_allvars.local.lua new file mode 100644 index 0000000000..74336ca1cf --- /dev/null +++ b/modulefiles/tasks/gaea/plot_allvars.local.lua @@ -0,0 +1,4 @@ +prepend_path("MODULEPATH","/lustre/f2/dev/role.epic/contrib/modulefiles") +load(pathJoin("miniconda3", os.getenv("miniconda3_ver") or "4.12.0")) + +setenv("SRW_ENV", "regional_workflow") diff --git a/modulefiles/tasks/gaea/python_srw.lua b/modulefiles/tasks/gaea/python_srw.lua index 74336ca1cf..c0f454fa71 100644 --- a/modulefiles/tasks/gaea/python_srw.lua +++ b/modulefiles/tasks/gaea/python_srw.lua @@ -1,4 +1,4 @@ prepend_path("MODULEPATH","/lustre/f2/dev/role.epic/contrib/modulefiles") load(pathJoin("miniconda3", os.getenv("miniconda3_ver") or "4.12.0")) -setenv("SRW_ENV", "regional_workflow") +setenv("SRW_ENV", "workflow_tools") diff --git a/modulefiles/tasks/hera/plot_allvars.local.lua b/modulefiles/tasks/hera/plot_allvars.local.lua new file mode 100644 index 0000000000..7934169824 --- /dev/null +++ b/modulefiles/tasks/hera/plot_allvars.local.lua @@ -0,0 +1,4 @@ +prepend_path("MODULEPATH","/scratch1/NCEPDEV/nems/role.epic/miniconda3/modulefiles") +load(pathJoin("miniconda3", os.getenv("miniconda3_ver") or "4.12.0")) + +setenv("SRW_ENV", "regional_workflow") diff --git a/modulefiles/tasks/hera/python_srw.lua b/modulefiles/tasks/hera/python_srw.lua index 7934169824..62ddf7d9e8 100644 --- a/modulefiles/tasks/hera/python_srw.lua +++ b/modulefiles/tasks/hera/python_srw.lua @@ -1,4 +1,4 @@ prepend_path("MODULEPATH","/scratch1/NCEPDEV/nems/role.epic/miniconda3/modulefiles") load(pathJoin("miniconda3", os.getenv("miniconda3_ver") or "4.12.0")) -setenv("SRW_ENV", "regional_workflow") +setenv("SRW_ENV", "workflow_tools") diff --git a/modulefiles/tasks/jet/plot_allvars.local.lua b/modulefiles/tasks/jet/plot_allvars.local.lua new file mode 100644 index 0000000000..ef4f248966 --- /dev/null +++ b/modulefiles/tasks/jet/plot_allvars.local.lua @@ -0,0 +1,4 @@ +prepend_path("MODULEPATH","/mnt/lfs4/HFIP/hfv3gfs/role.epic/miniconda3/modulefiles") +load(pathJoin("miniconda3", os.getenv("miniconda3_ver") or "4.12.0")) + +setenv("SRW_ENV", "regional_workflow") diff --git a/modulefiles/tasks/jet/python_srw.lua b/modulefiles/tasks/jet/python_srw.lua index ef4f248966..3c7987be18 100644 --- a/modulefiles/tasks/jet/python_srw.lua +++ b/modulefiles/tasks/jet/python_srw.lua @@ -1,4 +1,4 @@ prepend_path("MODULEPATH","/mnt/lfs4/HFIP/hfv3gfs/role.epic/miniconda3/modulefiles") load(pathJoin("miniconda3", os.getenv("miniconda3_ver") or "4.12.0")) -setenv("SRW_ENV", "regional_workflow") +setenv("SRW_ENV", "workflow_tools") diff --git a/modulefiles/tasks/jet/run_vx.local.lua b/modulefiles/tasks/jet/run_vx.local.lua index 13b6b4b954..750fd7603e 100644 --- a/modulefiles/tasks/jet/run_vx.local.lua +++ b/modulefiles/tasks/jet/run_vx.local.lua @@ -1,3 +1 @@ -append_path("MODULEPATH", "/contrib/anaconda/modulefiles") -load(pathJoin("intel", os.getenv("intel_ver") or "18.0.5.274")) -load(pathJoin("anaconda", os.getenv("anaconda_ver") or "5.3.1")) +load("python_srw") diff --git a/modulefiles/tasks/noaacloud/plot_allvars.local.lua b/modulefiles/tasks/noaacloud/plot_allvars.local.lua new file mode 100644 index 0000000000..602d60842f --- /dev/null +++ b/modulefiles/tasks/noaacloud/plot_allvars.local.lua @@ -0,0 +1 @@ +prepend_path("PATH", "/contrib/EPIC/miniconda3/4.12.0/envs/regional_workflow/bin") diff --git a/modulefiles/tasks/orion/plot_allvars.local.lua b/modulefiles/tasks/orion/plot_allvars.local.lua new file mode 100644 index 0000000000..5b7b0afc57 --- /dev/null +++ b/modulefiles/tasks/orion/plot_allvars.local.lua @@ -0,0 +1,5 @@ +unload("python") +append_path("MODULEPATH","/work/noaa/epic-ps/role-epic-ps/miniconda3/modulefiles") +load(pathJoin("miniconda3", os.getenv("miniconda3_ver") or "4.12.0")) + +setenv("SRW_ENV", "regional_workflow") diff --git a/modulefiles/tasks/orion/python_srw.lua b/modulefiles/tasks/orion/python_srw.lua index 5b7b0afc57..c7e25d3ad4 100644 --- a/modulefiles/tasks/orion/python_srw.lua +++ b/modulefiles/tasks/orion/python_srw.lua @@ -2,4 +2,4 @@ unload("python") append_path("MODULEPATH","/work/noaa/epic-ps/role-epic-ps/miniconda3/modulefiles") load(pathJoin("miniconda3", os.getenv("miniconda3_ver") or "4.12.0")) -setenv("SRW_ENV", "regional_workflow") +setenv("SRW_ENV", "workflow_tools") diff --git a/modulefiles/wflow_cheyenne.lua b/modulefiles/wflow_cheyenne.lua index 35b7365d43..9a7a37c0b5 100644 --- a/modulefiles/wflow_cheyenne.lua +++ b/modulefiles/wflow_cheyenne.lua @@ -11,12 +11,14 @@ append_path("MODULEPATH","/glade/p/ral/jntp/UFS_SRW_app/modules") load("rocoto") unload("python") + +load("set_pythonpath") prepend_path("MODULEPATH","/glade/work/epicufsrt/contrib/miniconda3/modulefiles") load(pathJoin("miniconda3", os.getenv("miniconda3_ver") or "4.12.0")) if mode() == "load" then LmodMsgRaw([===[Please do the following to activate conda: - > conda activate regional_workflow + > conda activate workflow_tools ]===]) end diff --git a/modulefiles/wflow_gaea.lua b/modulefiles/wflow_gaea.lua index e4b726aac1..f623acd15b 100644 --- a/modulefiles/wflow_gaea.lua +++ b/modulefiles/wflow_gaea.lua @@ -5,6 +5,7 @@ the NOAA RDHPC machine Gaea whatis([===[Loads libraries needed for running the UFS SRW App on gaea ]===]) +load("set_pythonpath") prepend_path("MODULEPATH","/lustre/f2/dev/role.epic/contrib/modulefiles") load(pathJoin("miniconda3", os.getenv("miniconda3_ver") or "4.12.0")) load("rocoto") @@ -14,6 +15,6 @@ setenv("PROJ_LIB", "/lustre/f2/dev/role.epic/contrib/miniconda3/4.12.0/envs/regi if mode() == "load" then LmodMsgRaw([===[Please do the following to activate conda: - > conda activate regional_workflow + > conda activate workflow_tools ]===]) end diff --git a/modulefiles/wflow_hera.lua b/modulefiles/wflow_hera.lua index efca665dd2..5d6ebeed1d 100644 --- a/modulefiles/wflow_hera.lua +++ b/modulefiles/wflow_hera.lua @@ -6,12 +6,13 @@ the NOAA RDHPC machine Hera whatis([===[Loads libraries needed for running the UFS SRW App on Hera ]===]) load("rocoto") +load("set_pythonpath") prepend_path("MODULEPATH","/scratch1/NCEPDEV/nems/role.epic/miniconda3/modulefiles") load(pathJoin("miniconda3", os.getenv("miniconda3_ver") or "4.12.0")) if mode() == "load" then LmodMsgRaw([===[Please do the following to activate conda: - > conda activate regional_workflow + > conda activate workflow_tools ]===]) end diff --git a/modulefiles/wflow_jet.lua b/modulefiles/wflow_jet.lua index be11c223bc..5f109429dc 100644 --- a/modulefiles/wflow_jet.lua +++ b/modulefiles/wflow_jet.lua @@ -6,12 +6,13 @@ the NOAA RDHPC machine Jet whatis([===[Loads libraries needed for running the UFS SRW App on Jet ]===]) load("rocoto") +load("set_pythonpath") prepend_path("MODULEPATH","/mnt/lfs4/HFIP/hfv3gfs/role.epic/miniconda3/modulefiles") load(pathJoin("miniconda3", os.getenv("miniconda3_ver") or "4.12.0")) if mode() == "load" then LmodMsgRaw([===[Please do the following to activate conda: - > conda activate regional_workflow + > conda activate workflow_tools ]===]) end diff --git a/modulefiles/wflow_linux.lua b/modulefiles/wflow_linux.lua index 6c4cc6949d..3fb5d1123a 100644 --- a/modulefiles/wflow_linux.lua +++ b/modulefiles/wflow_linux.lua @@ -31,9 +31,12 @@ prepend_path("PATH", pathJoin(rocoto_path,"bin")) local srw_path="/home/username/ufs-srweather-app" prepend_path("PATH", pathJoin(srw_path, "ush/rocoto_fake_slurm")) +-- set python path +load("set_pythonpath") + -- display conda activation message if mode() == "load" then LmodMsgRaw([===[Please do the following to activate conda: - > conda activate regional_workflow + > conda activate workflow_tools ]===]) end diff --git a/modulefiles/wflow_macos.lua b/modulefiles/wflow_macos.lua index d7cf30e0a3..6ee6022b20 100644 --- a/modulefiles/wflow_macos.lua +++ b/modulefiles/wflow_macos.lua @@ -31,10 +31,13 @@ prepend_path("PATH", pathJoin(rocoto_path,"bin")) local srw_path="/Users/username/ufs-srweather-app" prepend_path("PATH", pathJoin(srw_path, "ush/rocoto_fake_slurm")) +-- set python path +load("set_pythonpath") + -- display conda activation message if mode() == "load" then LmodMsgRaw([===[Please do the following to activate conda virtual environment: - > conda activate regional_workflow" + > conda activate workflow_tools" ]===]) end diff --git a/modulefiles/wflow_noaacloud.lua b/modulefiles/wflow_noaacloud.lua index 80501f5075..6c8925444d 100644 --- a/modulefiles/wflow_noaacloud.lua +++ b/modulefiles/wflow_noaacloud.lua @@ -7,6 +7,8 @@ whatis([===[Loads libraries needed for running the UFS SRW App on NOAA cloud ]== prepend_path("MODULEPATH","/apps/modules/modulefiles") load("rocoto") +load("set_pythonpath") + prepend_path("MODULEPATH","/contrib/EPIC/miniconda3/modulefiles") load(pathJoin("miniconda3", os.getenv("miniconda3_ver") or "4.12.0")) diff --git a/modulefiles/wflow_odin.lua b/modulefiles/wflow_odin.lua index 7b1b5d8203..f042b00894 100644 --- a/modulefiles/wflow_odin.lua +++ b/modulefiles/wflow_odin.lua @@ -5,6 +5,8 @@ the NSSL machine Odin whatis([===[Loads libraries needed for running the UFS SRW App on Odin ]===]) +load("set_pythonpath") + if mode() == "load" then -- >>> conda initialize >>> -- !! Contents within this block are managed by 'conda init' !! @@ -28,6 +30,6 @@ if mode() == "load" then LmodMsgRaw([===[Please do the following to activate conda: > conda config --set changeps1 False - > conda activate regional_workflow + > conda activate workflow_tools ]===]) end diff --git a/modulefiles/wflow_orion.lua b/modulefiles/wflow_orion.lua index 78997de1bb..46da63f5d4 100644 --- a/modulefiles/wflow_orion.lua +++ b/modulefiles/wflow_orion.lua @@ -8,6 +8,7 @@ whatis([===[Loads libraries needed for running SRW on Orion ]===]) load("contrib") load("rocoto") load("wget") +load("set_pythonpath") unload("python") append_path("MODULEPATH","/work/noaa/epic-ps/role-epic-ps/miniconda3/modulefiles") @@ -15,7 +16,7 @@ load(pathJoin("miniconda3", os.getenv("miniconda3_ver") or "4.12.0")) if mode() == "load" then LmodMsgRaw([===[Please do the following to activate conda: - > conda activate regional_workflow + > conda activate workflow_tools ]===]) end diff --git a/modulefiles/wflow_singularity.lua b/modulefiles/wflow_singularity.lua index 3c16a93570..309c5eac23 100644 --- a/modulefiles/wflow_singularity.lua +++ b/modulefiles/wflow_singularity.lua @@ -4,10 +4,11 @@ a singularity container ]]) whatis([===[Loads libraries needed for running the UFS SRW App in a singularity container]===]) +load("set_pythonpath") append_path("MODULEPATH","/opt/hpc-modules/modulefiles/core") load("miniconda3") if mode() == "load" then - execute{cmd="conda activate regional_workflow", modeA={"load"}} + execute{cmd="conda activate workflow_tools", modeA={"load"}} end diff --git a/modulefiles/wflow_wcoss2.lua b/modulefiles/wflow_wcoss2.lua index a061b93323..4212f17493 100644 --- a/modulefiles/wflow_wcoss2.lua +++ b/modulefiles/wflow_wcoss2.lua @@ -7,6 +7,7 @@ whatis([===[Loads libraries needed for running the UFS SRW App on WCOSS2 ]===]) load(pathJoin("intel", os.getenv("intel_ver"))) load(pathJoin("python", os.getenv("python_ver"))) +load("set_pythonpath") prepend_path("MODULEPATH","/apps/ops/test/nco/modulefiles") load(pathJoin("core/rocoto", os.getenv("rocoto_ver"))) diff --git a/scripts/exregional_run_met_genensprod_or_ensemblestat.sh b/scripts/exregional_run_met_genensprod_or_ensemblestat.sh index 49e2dfdd91..9631efdb6d 100755 --- a/scripts/exregional_run_met_genensprod_or_ensemblestat.sh +++ b/scripts/exregional_run_met_genensprod_or_ensemblestat.sh @@ -381,25 +381,32 @@ settings="\ 'accum_no_pad': '${ACCUM_NO_PAD:-}' 'field_thresholds': '${FIELD_THRESHOLDS:-}' " + +# Store the settings in a temporary file +tmpfile=$( $READLINK -f "$(mktemp ./met_plus_settings.XXXXXX.yaml)") +cat > $tmpfile << EOF +$settings +EOF # # Call the python script to generate the METplus configuration file from # the jinja template. # -$USHdir/fill_jinja_template.py -q \ - -u "${settings}" \ - -t ${metplus_config_tmpl_fp} \ - -o ${metplus_config_fp} || \ +python3 $USHdir/python_utils/workflow-tools/scripts/templater.py \ + -c "${tmpfile}" \ + -i ${metplus_config_tmpl_fp} \ + -o ${metplus_config_fp} || \ print_err_msg_exit "\ -Call to python script fill_jinja_template.py to generate a METplus +Call to workflow-tools templater to generate a METplus configuration file from a jinja template failed. Parameters passed to this script are: Full path to template METplus configuration file: metplus_config_tmpl_fp = \"${metplus_config_tmpl_fp}\" Full path to output METplus configuration file: metplus_config_fp = \"${metplus_config_fp}\" - Jinja settings specified on command line: - settings = -$settings" + Full path to configuration file: + ${tmpfile} +" +rm $tmpfile # #----------------------------------------------------------------------- # diff --git a/scripts/exregional_run_met_gridstat_or_pointstat_vx.sh b/scripts/exregional_run_met_gridstat_or_pointstat_vx.sh index a6a30671b6..5027b54fcc 100755 --- a/scripts/exregional_run_met_gridstat_or_pointstat_vx.sh +++ b/scripts/exregional_run_met_gridstat_or_pointstat_vx.sh @@ -379,25 +379,32 @@ settings="\ 'accum_no_pad': '${ACCUM_NO_PAD:-}' 'field_thresholds': '${FIELD_THRESHOLDS:-}' " + +# Store the settings in a temporary file +tmpfile=$( $READLINK -f "$(mktemp ./met_plus_settings.XXXXXX.yaml)") +cat > $tmpfile << EOF +$settings +EOF # # Call the python script to generate the METplus configuration file from # the jinja template. # -$USHdir/fill_jinja_template.py -q \ - -u "${settings}" \ - -t ${metplus_config_tmpl_fp} \ - -o ${metplus_config_fp} || \ +python3 $USHdir/python_utils/workflow-tools/scripts/templater.py \ + -c "${tmpfile}" \ + -i ${metplus_config_tmpl_fp} \ + -o ${metplus_config_fp} || \ print_err_msg_exit "\ -Call to python script fill_jinja_template.py to generate a METplus +Call to workflow-tools templater to generate a METplus configuration file from a jinja template failed. Parameters passed to this script are: Full path to template METplus configuration file: metplus_config_tmpl_fp = \"${metplus_config_tmpl_fp}\" Full path to output METplus configuration file: metplus_config_fp = \"${metplus_config_fp}\" - Jinja settings specified on command line: - settings = -$settings" + Full path to configuration file: + ${tmpfile} +" +rm $tmpfile # #----------------------------------------------------------------------- # diff --git a/scripts/exregional_run_met_gridstat_or_pointstat_vx_ensmean.sh b/scripts/exregional_run_met_gridstat_or_pointstat_vx_ensmean.sh index c8cb4d9cac..45929fbcb6 100755 --- a/scripts/exregional_run_met_gridstat_or_pointstat_vx_ensmean.sh +++ b/scripts/exregional_run_met_gridstat_or_pointstat_vx_ensmean.sh @@ -343,25 +343,33 @@ settings="\ 'accum_no_pad': '${ACCUM_NO_PAD:-}' 'field_thresholds': '${FIELD_THRESHOLDS:-}' " + +# Store the settings in a temporary file +tmpfile=$( $READLINK -f "$(mktemp ./met_plus_settings.XXXXXX.yaml)") +cat > $tmpfile << EOF +$settings +EOF # # Call the python script to generate the METplus configuration file from # the jinja template. # -$USHdir/fill_jinja_template.py -q \ - -u "${settings}" \ - -t ${metplus_config_tmpl_fp} \ - -o ${metplus_config_fp} || \ + +python3 $USHdir/python_utils/workflow-tools/scripts/templater.py \ + -c "${tmpfile}" \ + -i ${metplus_config_tmpl_fp} \ + -o ${metplus_config_fp} || \ print_err_msg_exit "\ -Call to python script fill_jinja_template.py to generate a METplus +Call to workflow-tools templater to generate a METplus configuration file from a jinja template failed. Parameters passed to this script are: Full path to template METplus configuration file: metplus_config_tmpl_fp = \"${metplus_config_tmpl_fp}\" Full path to output METplus configuration file: metplus_config_fp = \"${metplus_config_fp}\" - Jinja settings specified on command line: - settings = -$settings" + Full path to configuration file: + ${tmpfile} +" +rm $tmpfile # #----------------------------------------------------------------------- # diff --git a/scripts/exregional_run_met_gridstat_or_pointstat_vx_ensprob.sh b/scripts/exregional_run_met_gridstat_or_pointstat_vx_ensprob.sh index 473a17dcf5..7478f35562 100755 --- a/scripts/exregional_run_met_gridstat_or_pointstat_vx_ensprob.sh +++ b/scripts/exregional_run_met_gridstat_or_pointstat_vx_ensprob.sh @@ -305,25 +305,31 @@ settings="\ 'accum_no_pad': '${ACCUM_NO_PAD:-}' 'field_thresholds': '${FIELD_THRESHOLDS:-}' " +# Store the settings in a temporary file +tmpfile=$( $READLINK -f "$(mktemp ./met_plus_settings.XXXXXX.yaml)") +cat > $tmpfile << EOF +$settings +EOF # # Call the python script to generate the METplus configuration file from # the jinja template. # -$USHdir/fill_jinja_template.py -q \ - -u "${settings}" \ - -t ${metplus_config_tmpl_fp} \ - -o ${metplus_config_fp} || \ +python3 $USHdir/python_utils/workflow-tools/scripts/templater.py \ + -c "${tmpfile}" \ + -i ${metplus_config_tmpl_fp} \ + -o ${metplus_config_fp} || \ print_err_msg_exit "\ -Call to python script fill_jinja_template.py to generate a METplus +Call to workflow-tools templater to generate a METplus configuration file from a jinja template failed. Parameters passed to this script are: Full path to template METplus configuration file: metplus_config_tmpl_fp = \"${metplus_config_tmpl_fp}\" Full path to output METplus configuration file: metplus_config_fp = \"${metplus_config_fp}\" - Jinja settings specified on command line: - settings = -$settings" + Full path to configuration file: + ${tmpfile} +" +rm $tmpfile # #----------------------------------------------------------------------- # diff --git a/scripts/exregional_run_met_pb2nc_obs.sh b/scripts/exregional_run_met_pb2nc_obs.sh index 95feb701f4..3365e7f8c6 100755 --- a/scripts/exregional_run_met_pb2nc_obs.sh +++ b/scripts/exregional_run_met_pb2nc_obs.sh @@ -270,25 +270,31 @@ settings="\ 'accum_no_pad': '${ACCUM_NO_PAD:-}' 'field_thresholds': '${FIELD_THRESHOLDS:-}' " +# Store the settings in a temporary file +tmpfile=$( $READLINK -f "$(mktemp ./met_plus_settings.XXXXXX.yaml)") +cat > $tmpfile << EOF +$settings +EOF # # Call the python script to generate the METplus configuration file from # the jinja template. # -$USHdir/fill_jinja_template.py -q \ - -u "${settings}" \ - -t ${metplus_config_tmpl_fp} \ - -o ${metplus_config_fp} || \ +python3 $USHdir/python_utils/workflow-tools/scripts/templater.py \ + -c ${tmpfile} \ + -i ${metplus_config_tmpl_fp} \ + -o ${metplus_config_fp} || \ print_err_msg_exit "\ -Call to python script fill_jinja_template.py to generate a METplus +Call to workflow-tools templater.py to generate a METplus configuration file from a jinja template failed. Parameters passed to this script are: Full path to template METplus configuration file: metplus_config_tmpl_fp = \"${metplus_config_tmpl_fp}\" Full path to output METplus configuration file: metplus_config_fp = \"${metplus_config_fp}\" - Jinja settings specified on command line: - settings = -$settings" + Full path to configuration file: + ${tmpfile} +" +rm $tmpfile # #----------------------------------------------------------------------- # diff --git a/scripts/exregional_run_met_pcpcombine.sh b/scripts/exregional_run_met_pcpcombine.sh index a40bece103..6951158041 100755 --- a/scripts/exregional_run_met_pcpcombine.sh +++ b/scripts/exregional_run_met_pcpcombine.sh @@ -346,25 +346,32 @@ settings="\ 'accum_no_pad': '${ACCUM_NO_PAD:-}' 'field_thresholds': '${FIELD_THRESHOLDS:-}' " +# Store the settings in a temporary file +tmpfile=$( $READLINK -f "$(mktemp ./met_plus_settings.XXXXXX.yaml)") +cat > $tmpfile << EOF +$settings +EOF + # # Call the python script to generate the METplus configuration file from # the jinja template. # -$USHdir/fill_jinja_template.py -q \ - -u "${settings}" \ - -t ${metplus_config_tmpl_fp} \ - -o ${metplus_config_fp} || \ +python3 $USHdir/python_utils/workflow-tools/scripts/templater.py \ + -c ${tmpfile} \ + -i ${metplus_config_tmpl_fp} \ + -o ${metplus_config_fp} || \ print_err_msg_exit "\ -Call to python script fill_jinja_template.py to generate a METplus +Call to workflow-tools templater.py to generate a METplus configuration file from a jinja template failed. Parameters passed to this script are: Full path to template METplus configuration file: metplus_config_tmpl_fp = \"${metplus_config_tmpl_fp}\" Full path to output METplus configuration file: metplus_config_fp = \"${metplus_config_fp}\" - Jinja settings specified on command line: - settings = -$settings" + Full path to configuration file: + ${tmpfile} +" +rm $tmpfile # #----------------------------------------------------------------------- # diff --git a/tests/test_python/test_python_utils.py b/tests/test_python/test_python_utils.py index ea7c903b16..4104d7db93 100644 --- a/tests/test_python/test_python_utils.py +++ b/tests/test_python/test_python_utils.py @@ -168,8 +168,7 @@ def test_import_vars(self): # python util.import_vars(env_vars=env_vars) - # assuming all environments arlready have $PWD set - #pylint: disable= + # assuming all environments already have $PWD set self.assertEqual( os.path.realpath(PWD), #pylint: disable=undefined-variable os.path.realpath(os.getcwd()) diff --git a/tests/test_python/test_set_FV3nml_ens_stoch_seeds.py b/tests/test_python/test_set_FV3nml_ens_stoch_seeds.py index 15c7d79223..9a452bc1c2 100644 --- a/tests/test_python/test_set_FV3nml_ens_stoch_seeds.py +++ b/tests/test_python/test_set_FV3nml_ens_stoch_seeds.py @@ -21,6 +21,7 @@ class Testing(unittest.TestCase): """ Define the tests """ def test_set_FV3nml_ens_stoch_seeds(self): """ Call the function and make sure it doesn't fail""" + os.chdir(self.mem_dir) set_FV3nml_ens_stoch_seeds(cdate=self.cdate) def setUp(self): @@ -40,18 +41,20 @@ def setUp(self): ) EXPTDIR = self.tmp_dir.name - cp_vrfy( - os.path.join(PARMdir, "input.nml.FV3"), - os.path.join(EXPTDIR, "input.nml_base"), - ) - # Put this in the tmp_dir structure so it gets cleaned up - mem_dir = os.path.join( + self.mem_dir = os.path.join( EXPTDIR, f"{date_to_str(self.cdate,format='%Y%m%d%H')}", "mem2", ) - mkdir_vrfy("-p", mem_dir) + + mkdir_vrfy("-p", self.mem_dir) + cp_vrfy( + os.path.join(PARMdir, "input.nml.FV3"), + os.path.join(EXPTDIR, "input.nml_base"), + ) + + set_env_var("USHdir", USHdir) set_env_var("ENSMEM_INDX", 2) set_env_var("FV3_NML_FN", "input.nml") diff --git a/ush/create_aqm_rc_file.py b/ush/create_aqm_rc_file.py index fa8960f7db..02d8d827e5 100644 --- a/ush/create_aqm_rc_file.py +++ b/ush/create_aqm_rc_file.py @@ -1,25 +1,26 @@ #!/usr/bin/env python3 +""" +Function that creates the config file for running AQM. +""" import os import sys import argparse -from datetime import datetime from textwrap import dedent +import tempfile from python_utils import ( - import_vars, - set_env_var, - print_input_args, + import_vars, + print_input_args, str_to_type, - print_info_msg, - print_err_msg_exit, - lowercase, + print_info_msg, cfg_to_yaml_str, load_shell_config, flatten_dict ) -from fill_jinja_template import fill_jinja_template +# These come from ush/python_utils/workflow-tools +from scripts.templater import set_template def create_aqm_rc_file(cdate, run_dir, init_concentrations): """ Creates an aqm.rc file in the specified run directory @@ -36,7 +37,8 @@ def create_aqm_rc_file(cdate, run_dir, init_concentrations): #import all environment variables import_vars() - + #pylint: disable=undefined-variable + # #----------------------------------------------------------------------- # @@ -56,23 +58,37 @@ def create_aqm_rc_file(cdate, run_dir, init_concentrations): # Extract from cdate the starting year, month, and day of the forecast. # yyyymmdd=cdate.strftime('%Y%m%d') - mm=f"{cdate.month:02d}" - hh=f"{cdate.hour:02d}" + mm=f"{cdate.month:02d}" # pylint: disable=invalid-name + hh=f"{cdate.hour:02d}" # pylint: disable=invalid-name # # Set parameters in the aqm.rc file. # aqm_rc_bio_file_fp=os.path.join(AQM_BIO_DIR, AQM_BIO_FILE) - aqm_fire_file_fn=AQM_FIRE_FILE_PREFIX+"_"+yyyymmdd+"_t"+hh+"z"+AQM_FIRE_FILE_SUFFIX - aqm_rc_fire_file_fp=os.path.join(COMINext, "FIRE_EMISSION", aqm_fire_file_fn) - aqm_dust_file_fn=AQM_DUST_FILE_PREFIX+"_"+PREDEF_GRID_NAME+AQM_DUST_FILE_SUFFIX - aqm_rc_dust_file_fp=os.path.join(AQM_DUST_DIR, aqm_dust_file_fn) - aqm_canopy_file_fn=AQM_CANOPY_FILE_PREFIX+"."+mm+AQM_CANOPY_FILE_SUFFIX - aqm_rc_canopy_file_fp=os.path.join(AQM_CANOPY_DIR, PREDEF_GRID_NAME, aqm_canopy_file_fn) + + # Fire config + aqm_rc_fire_file_fp=os.path.join( + COMINext, + "FIRE_EMISSION", + f"{AQM_FIRE_FILE_PREFIX}_{yyyymmdd}_t{hh}z{AQM_FIRE_FILE_SUFFIX}" + ) + + # Dust config + aqm_rc_dust_file_fp=os.path.join( + AQM_DUST_DIR, + f"{AQM_DUST_FILE_PREFIX}_{PREDEF_GRID_NAME}{AQM_DUST_FILE_SUFFIX}", + ) + + # Canopy config + aqm_rc_canopy_file_fp=os.path.join( + AQM_CANOPY_DIR, + PREDEF_GRID_NAME, + f"{AQM_CANOPY_FILE_PREFIX}.{mm}{AQM_CANOPY_FILE_SUFFIX}", + ) # #----------------------------------------------------------------------- # # Create a multiline variable that consists of a yaml-compliant string - # specifying the values that the jinja variables in the template + # specifying the values that the jinja variables in the template # AQM_RC_TMPL_FN file should be set to. # #----------------------------------------------------------------------- @@ -94,14 +110,14 @@ def create_aqm_rc_file(cdate, run_dir, init_concentrations): "aqm_rc_product_frequency": AQM_RC_PRODUCT_FREQUENCY } settings_str = cfg_to_yaml_str(settings) - + print_info_msg( dedent( f""" The variable \"settings\" specifying values to be used in the \"{AQM_RC_FN}\" file has been set as follows:\n settings =\n\n""" - ) + ) + settings_str, verbose=VERBOSE, ) @@ -113,35 +129,24 @@ def create_aqm_rc_file(cdate, run_dir, init_concentrations): # #----------------------------------------------------------------------- # - try: - fill_jinja_template( + with tempfile.NamedTemporaryFile( + dir="./", + mode="w+t", + prefix="aqm_rc_settings", + suffix=".yaml") as tmpfile: + tmpfile.write(settings_str) + tmpfile.seek(0) + set_template( [ - "-q", - "-u", - settings_str, - "-t", - AQM_RC_TMPL_FP, - "-o", + "-q", + "-c", + tmpfile.name, + "-i", + AQM_RC_TMPL_FP, + "-o", aqm_rc_fp, ] ) - except: - print_err_msg_exit( - dedent( - f""" - Call to python script fill_jinja_template.py to create a \"{AQM_RC_FN}\" - file from a jinja2 template failed. Parameters passed to this script are: - Full path to template aqm.rc file: - AQM_RC_TMPL_FP = \"{AQM_RC_TMPL_FP}\" - Full path to output aqm.rc file: - aqm_rc_fp = \"{aqm_rc_fp}\" - Namelist settings specified on command line:\n - settings =\n\n""" - ) - + settings_str - ) - return False - return True def parse_args(argv): @@ -178,6 +183,5 @@ def parse_args(argv): create_aqm_rc_file( run_dir=args.run_dir, cdate=str_to_type(args.cdate), - init_concentrations=str_to_type(args.init_concentrations), + init_concentrations=str_to_type(args.init_concentrations), ) - diff --git a/ush/create_diag_table_file.py b/ush/create_diag_table_file.py index 845ce2dc77..3ef9ec3901 100644 --- a/ush/create_diag_table_file.py +++ b/ush/create_diag_table_file.py @@ -1,22 +1,27 @@ #!/usr/bin/env python3 +""" +Function to create a diag_table file for the FV3 model using a +template. +""" import os import sys import argparse from textwrap import dedent +import tempfile + from python_utils import ( import_vars, - set_env_var, print_input_args, print_info_msg, - print_err_msg_exit, cfg_to_yaml_str, load_shell_config, flatten_dict, ) -from fill_jinja_template import fill_jinja_template +# These come from ush/python_utils/workflow-tools +from scripts.templater import set_template def create_diag_table_file(run_dir): @@ -33,6 +38,7 @@ def create_diag_table_file(run_dir): # import all environment variables import_vars() + #pylint: disable=undefined-variable # create a diagnostic table file within the specified run directory print_info_msg( f""" @@ -71,27 +77,16 @@ def create_diag_table_file(run_dir): verbose=VERBOSE, ) - # call fill jinja - try: - fill_jinja_template( - ["-q", "-u", settings_str, "-t", DIAG_TABLE_TMPL_FP, "-o", diag_table_fp] - ) - except: - print_err_msg_exit( - dedent( - f""" - Call to python script fill_jinja_template.py to create a '{DIAG_TABLE_FN}' - file from a jinja2 template failed. Parameters passed to this script are: - Full path to template diag table file: - DIAG_TABLE_TMPL_FP = '{DIAG_TABLE_TMPL_FP}' - Full path to output diag table file: - diag_table_fp = '{diag_table_fp}' - Namelist settings specified on command line:\n - settings =\n\n""" - ) - + settings_str + with tempfile.NamedTemporaryFile(dir="./", + mode="w+t", + prefix="aqm_rc_settings", + suffix=".yaml") as tmpfile: + tmpfile.write(settings_str) + tmpfile.seek(0) + # set_template does its own error handling + set_template( + ["-c", tmpfile.name, "-i", DIAG_TABLE_TMPL_FP, "-o", diag_table_fp] ) - return False return True diff --git a/ush/create_model_configure_file.py b/ush/create_model_configure_file.py index f835212e7d..e39fff695e 100644 --- a/ush/create_model_configure_file.py +++ b/ush/create_model_configure_file.py @@ -1,30 +1,32 @@ #!/usr/bin/env python3 - +""" +Create a model_configure file for the FV3 forecast model from a +template. +""" import os import sys import argparse -from datetime import datetime from textwrap import dedent +import tempfile from python_utils import ( import_vars, - set_env_var, print_input_args, str_to_type, print_info_msg, - print_err_msg_exit, lowercase, cfg_to_yaml_str, load_shell_config, flatten_dict, ) -from fill_jinja_template import fill_jinja_template +# These come from ush/python_utils/workflow-tools +from scripts.templater import set_template def create_model_configure_file( cdate, fcst_len_hrs, fhrot, run_dir, sub_hourly_post, dt_subhourly_post_mnts, dt_atmos -): + ): #pylint: disable=too-many-arguments """Creates a model configuration file in the specified run directory @@ -45,6 +47,8 @@ def create_model_configure_file( # import all environment variables import_vars() + # pylint: disable=undefined-variable + # # ----------------------------------------------------------------------- # @@ -60,18 +64,6 @@ def create_model_configure_file( verbose=VERBOSE, ) # - # Extract from cdate the starting year, month, day, and hour of the forecast. - # - yyyy = cdate.year - mm = cdate.month - dd = cdate.day - hh = cdate.hour - # - # Set parameters in the model configure file. - # - dot_quilting_dot=f".{lowercase(str(QUILTING))}." - dot_write_dopost=f".{lowercase(str(WRITE_DOPOST))}." - # # ----------------------------------------------------------------------- # # Create a multiline variable that consists of a yaml-compliant string @@ -81,16 +73,16 @@ def create_model_configure_file( # ----------------------------------------------------------------------- # settings = { - "start_year": yyyy, - "start_month": mm, - "start_day": dd, - "start_hour": hh, + "start_year": cdate.year, + "start_month": cdate.month, + "start_day": cdate.day, + "start_hour": cdate.hour, "nhours_fcst": fcst_len_hrs, "fhrot": fhrot, "dt_atmos": DT_ATMOS, "restart_interval": RESTART_INTERVAL, - "write_dopost": dot_write_dopost, - "quilting": dot_quilting_dot, + "write_dopost": f".{lowercase(str(WRITE_DOPOST))}.", + "quilting": f".{lowercase(str(QUILTING))}.", "output_grid": WRTCMP_output_grid, } # @@ -126,8 +118,7 @@ def create_model_configure_file( } ) elif ( - WRTCMP_output_grid == "regional_latlon" - or WRTCMP_output_grid == "rotated_latlon" + WRTCMP_output_grid in ("regional_latlon", "rotated_latlon") ): settings.update( { @@ -203,34 +194,23 @@ def create_model_configure_file( # model_config_fp = os.path.join(run_dir, MODEL_CONFIG_FN) - try: - fill_jinja_template( + with tempfile.NamedTemporaryFile(dir="./", + mode="w+t", + suffix=".yaml", + prefix="model_config_settings.") as tmpfile: + tmpfile.write(settings_str) + tmpfile.seek(0) + # set_template does its own error handling + set_template( [ - "-q", - "-u", - settings_str, - "-t", + "-c", + tmpfile.name, + "-i", MODEL_CONFIG_TMPL_FP, "-o", model_config_fp, ] ) - except: - print_err_msg_exit( - dedent( - f""" - Call to python script fill_jinja_template.py to create a '{MODEL_CONFIG_FN}' - file from a jinja2 template failed. Parameters passed to this script are: - Full path to template model config file: - MODEL_CONFIG_TMPL_FP = '{MODEL_CONFIG_TMPL_FP}' - Full path to output model config file: - model_config_fp = '{model_config_fp}' - Namelist settings specified on command line:\n - settings =\n\n""" - ) - + settings_str - ) - return False return True diff --git a/ush/create_nems_configure_file.py b/ush/create_nems_configure_file.py index 9d4b9cd2de..7a2ef0723f 100644 --- a/ush/create_nems_configure_file.py +++ b/ush/create_nems_configure_file.py @@ -1,25 +1,27 @@ #!/usr/bin/env python3 +""" +Function to create a NEMS configuration file for the FV3 forecast +model(s) from a template. +""" + import os import sys import argparse -from datetime import datetime +import tempfile from textwrap import dedent from python_utils import ( - import_vars, - set_env_var, - print_input_args, - str_to_type, - print_info_msg, - print_err_msg_exit, - lowercase, + import_vars, + print_input_args, + print_info_msg, cfg_to_yaml_str, load_shell_config, flatten_dict, ) -from fill_jinja_template import fill_jinja_template +# These come from ush/python_utils/workflow-tools +from scripts.templater import set_template def create_nems_configure_file(run_dir): """ Creates a nems configuration file in the specified @@ -35,7 +37,9 @@ def create_nems_configure_file(run_dir): #import all environment variables import_vars() - + + # pylint: disable=undefined-variable + # #----------------------------------------------------------------------- # @@ -56,7 +60,7 @@ def create_nems_configure_file(run_dir): #----------------------------------------------------------------------- # # Create a multiline variable that consists of a yaml-compliant string - # specifying the values that the jinja variables in the template + # specifying the values that the jinja variables in the template # model_configure file should be set to. # #----------------------------------------------------------------------- @@ -69,15 +73,15 @@ def create_nems_configure_file(run_dir): "atm_omp_num_threads": OMP_NUM_THREADS_RUN_FCST, } settings_str = cfg_to_yaml_str(settings) - + print_info_msg( dedent( f""" The variable \"settings\" specifying values to be used in the \"{NEMS_CONFIG_FN}\" file has been set as follows:\n settings =\n\n""" - ) - + settings_str, + ) + + settings_str, verbose=VERBOSE, ) # @@ -88,25 +92,15 @@ def create_nems_configure_file(run_dir): # #----------------------------------------------------------------------- # - try: - fill_jinja_template(["-q", "-u", settings_str, "-t", NEMS_CONFIG_TMPL_FP, "-o", nems_config_fp]) - except: - print_err_msg_exit( - dedent( - f""" - Call to python script fill_jinja_template.py to create the nems.configure - file from a jinja2 template failed. Parameters passed to this script are: - Full path to template nems.configure file: - NEMS_CONFIG_TMPL_FP = \"{NEMS_CONFIG_TMPL_FP}\" - Full path to output nems.configure file: - nems_config_fp = \"{nems_config_fp}\" - Namelist settings specified on command line:\n - settings =\n\n""" - ) - + settings_str - ) - return False + # Store the settings in a temporary file + with tempfile.NamedTemporaryFile(dir="./", + mode="w+t", + prefix="nems_config_settings", + suffix=".yaml") as tmpfile: + tmpfile.write(settings_str) + tmpfile.seek(0) + set_template(["-c", tmpfile.name, "-i", NEMS_CONFIG_TMPL_FP, "-o", nems_config_fp]) return True def parse_args(argv): @@ -133,7 +127,5 @@ def parse_args(argv): cfg = flatten_dict(cfg) import_vars(dictionary=cfg) create_nems_configure_file( - run_dir=args.run_dir, + run_dir=args.run_dir, ) - - diff --git a/ush/fill_jinja_template.py b/ush/fill_jinja_template.py deleted file mode 100755 index f810136753..0000000000 --- a/ush/fill_jinja_template.py +++ /dev/null @@ -1,302 +0,0 @@ -#!/usr/bin/env python3 - -""" -This utility fills in a user-supplied Jinja template from either a YAML file, or -command line arguments. - -The user configuration file and commandline arguments should be YAML-formatted. -This script will support a single- or two-level YAML config file. For example: - - 1. expt1: - date_first_cycl: !datetime 2019043000 - date_last_cycl: !datetime 2019050100 - cycl_freq: !!str 12:00:00 - - expt2: - date_first_cycl: !datetime 2019061012 - date_last_cycl: !datetime 2019061212 - cycl_freq: !!str 12:00:00 - - 2. date_first_cycl: !datetime 2019043000 - date_last_cycl: !datetime 2019050100 - cycl_freq: !!str 12:00:00 - - In Case 1, provide the name of the file and the section title, e.g. expt2, - to the -c command line argument. Only provide the name of the file in -c - option if it's configured as in Case 2 above. - - -Supported YAML Tags: - - The script supports additional YAML configuration tags. - - !datetime Converts an input string formatted as YYYYMMDDHH[mm[ss]] to a - Python datetime object - !join Uses os.path.join to join a list as a path. - -Expected behavior: - - - The template file is required. Script fails if not provided. - - Command line arguments in the -u setting override the -c settings. - -""" - -import datetime as dt -import os -import sys - -import argparse -import jinja2 as j2 -from jinja2 import meta -import yaml - - -def join(loader, node): - - """Uses os to join a list as a path.""" - - return os.path.join(*loader.construct_sequence(node)) - - -def to_datetime(loader, node): - - """Converts a date string with format YYYYMMDDHH[MM[SS]] to a datetime - object.""" - - value = loader.construct_scalar(node) - val_len = len(value) - - # Check that the input string contains only numbers and is expected length. - if val_len not in [10, 12, 14] or not value.isnumeric(): - msg = f"{value} does not conform to input format YYYYMMDDHH[MM[SS]]" - raise ValueError(msg) - - # Use a subset of the string corresponding to the input length of the string - # 2 chosen here since Y is a 4 char year. - date_format = "%Y%m%d%H%M%S"[0 : val_len - 2] - - return dt.datetime.strptime(value, date_format) - - -yaml.add_constructor("!datetime", to_datetime, Loader=yaml.SafeLoader) -yaml.add_constructor("!join", join, Loader=yaml.SafeLoader) - - -def file_exists(arg): - - """Checks whether a file exists, and returns the path if it does.""" - - if not os.path.exists(arg): - msg = f"{arg} does not exist!" - raise argparse.ArgumentTypeError(msg) - - return arg - - -def config_exists(arg): - - """ - Checks whether the config file exists and if it contains the input - section. Returns the config as a Python dict. - """ - - if len(arg) > 2: - msg = f"{len(arg)} arguments were provided for config. Only 2 allowed!" - raise argparse.ArgumentTypeError(msg) - - file_name = file_exists(arg[0]) - section_name = arg[1] if len(arg) == 2 else None - - # Load the YAML file into a dictionary - with open(file_name, "r") as fn: - cfg = yaml.load(fn, Loader=yaml.SafeLoader) - - if section_name: - try: - cfg = cfg[section_name] - except KeyError: - msg = f"Section {section_name} does not exist in top level of {file_name}" - raise argparse.ArgumentTypeError(msg) - - return cfg - - -def load_config(arg): - - """ - Check to ensure that the provided config file exists. If it does, load it - with YAML's safe loader and return the resulting dict. - """ - - # Check for existence of file - if not os.path.exists(arg): - msg = f"{arg} does not exist!" - raise argparse.ArgumentTypeError(msg) - - return yaml.safe_load(arg) - - -def load_str(arg): - - """Load a dict string safely using YAML. Return the resulting dict.""" - - return yaml.load(arg, Loader=yaml.SafeLoader) - - -def path_ok(arg): - - """ - Check whether the path to the file exists, and is writeable. Return the path - if it passes all checks, otherwise raise an error. - """ - - # Get the absolute path provided by arg - dir_name = os.path.abspath(os.path.dirname(arg)) - - # Ensure the arg path exists, and is writable. Raise error if not. - if os.path.lexists(dir_name) and os.access(dir_name, os.W_OK): - return arg - - msg = f"{arg} is not a writable path!" - raise argparse.ArgumentTypeError(msg) - - -def parse_args(argv): - - """ - Function maintains the arguments accepted by this script. Please see - Python's argparse documenation for more information about settings of each - argument. - """ - - parser = argparse.ArgumentParser(description="Fill in a Rocoto XML template.") - - # Optional - parser.add_argument( - "-c", - "--config", - help="Full path to a YAML user config file, and a \ - top-level section to use (optional).", - nargs="*", - type=load_config, - ) - parser.add_argument( - "-q", - "--quiet", - action="store_true", - help="Suppress all output", - ) - parser.add_argument( - "-u", - "--user_config", - help="Command-line user config options in YAML-formatted string", - type=load_str, - ) - # Required - parser.add_argument( - "-t", - "--xml_template", - dest="template", - help="Full path to the jinja template", - required=True, - type=file_exists, - ) - parser.add_argument( - "-o", - "--outxml", - dest="outxml", - help="Full path to the output Rocoto XML file.", - required=True, - type=path_ok, - ) - return parser.parse_args(argv) - - -def update_dict(dest, newdict, quiet=False): - - """ - Overwrites all values in dest dictionary section with key/value pairs from - newdict. Does not support multi-layer update. - - Turn off print statements with quiet=True. - - Input: - dest A dict that is to be updated. - newdict A dict containing sections and keys corresponding to - those in dest and potentially additional ones, that will be used to - update the dest dict. - quiet An optional boolean flag to turn off output. - Output: - None - Result: - The dest dict is updated in place. - """ - - if not quiet: - print("*" * 50) - - for key, value in newdict.items(): - if not quiet: - print(f"Overriding {key:>20} = {value}") - - # Set key in dict - dest[key] = value - - if not quiet: - print("*" * 50) - - -def fill_jinja_template(argv, config_dict=None): - - """ - Loads a Jinja template, determines its necessary undefined variables, - retrives them from user supplied settings, and renders the final result. - """ - - # parse args - cla = parse_args(argv) - if cla.config: - cla.config = config_exists(cla.config) - - # Create a Jinja Environment to load the template. - env = j2.Environment(loader=j2.FileSystemLoader(cla.template, - encoding='utf-8')) - template_source = env.loader.get_source(env, "") - template = env.get_template("") - parsed_content = env.parse(template_source) - - # Gather all of the undefined variables in the template. - template_vars = meta.find_undeclared_variables(parsed_content) - - # Read in the config options from the provided (optional) YAML file - cfg = cla.config if cla.config is not None else {} - - if config_dict is not None: - update_dict(cfg, config_dict, quiet=cla.quiet) - - # Update cfg with (optional) command-line entries, overriding those in YAML file - if cla.user_config: - update_dict(cfg, cla.user_config, quiet=cla.quiet) - - # Loop through all the undefined Jinja template variables, and grab the - # required values from the config file. - tvars = {} - for var in template_vars: - - if cfg.get(var, "NULL") == "NULL": - raise KeyError(f"{var} does not exist in user-supplied settings!") - - if not cla.quiet: - print(f"{var:>25}: {cfg.get(var)}") - - tvars[var] = cfg.get(var) - - # Fill in XML template - xml_contents = template.render(**tvars) - with open(cla.outxml, "w") as fn: - fn.write(xml_contents) - - -if __name__ == "__main__": - - fill_jinja_template(sys.argv[1:]) diff --git a/ush/generate_FV3LAM_wflow.py b/ush/generate_FV3LAM_wflow.py index d91d21db58..5022bfed4c 100755 --- a/ush/generate_FV3LAM_wflow.py +++ b/ush/generate_FV3LAM_wflow.py @@ -1,45 +1,46 @@ #!/usr/bin/env python3 +""" +User interface to create an experiment directory consistent with the +user-defined config.yaml file. +""" + +# pylint: disable=invalid-name + import os -import sys -import subprocess import logging -from multiprocessing import Process from textwrap import dedent -from datetime import datetime, timedelta +import sys from python_utils import ( log_info, import_vars, export_vars, - load_config_file, - update_dict, cp_vrfy, ln_vrfy, mkdir_vrfy, mv_vrfy, - run_command, - date_to_str, - define_macos_utilities, create_symlink_to_file, check_for_preexist_dir_file, cfg_to_yaml_str, find_pattern_in_str, - set_env_var, - get_env_var, - lowercase, flatten_dict, ) from setup import setup from set_FV3nml_sfc_climo_filenames import set_FV3nml_sfc_climo_filenames from get_crontab_contents import add_crontab_line -from fill_jinja_template import fill_jinja_template from set_namelist import set_namelist from check_python_version import check_python_version +# These come from ush/python_utils/workflow-tools +from scripts.templater import set_template -def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", debug: bool = False) -> str: +# pylint: disable=too-many-locals,too-many-branches, too-many-statements +def generate_FV3LAM_wflow( + ushdir, + logfile: str = "log.generate_FV3LAM_wflow", + debug: bool = False) -> str: """Function to setup a forecast experiment and create a workflow (according to the parameters specified in the config file) @@ -101,7 +102,6 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de expt_config["user"]["PARMdir"], wflow_xml_fn, ) - global_var_defns_fp = expt_config["workflow"]["GLOBAL_VAR_DEFNS_FP"] log_info( f""" @@ -114,21 +114,10 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de # rocoto_yaml_fp = expt_config["workflow"]["ROCOTO_YAML_FP"] args = ["-o", wflow_xml_fp, - "-t", template_xml_fp, - "-c", rocoto_yaml_fp ] - if not debug: - args.append("-q") - - try: - fill_jinja_template(args) - except: - raise Exception( - dedent( - f""" - Call to fill_jinja_template failed. - """ - ) - ) + "-i", template_xml_fp, + "-c", rocoto_yaml_fp, + ] + set_template(args) # # ----------------------------------------------------------------------- # @@ -168,6 +157,7 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de import_vars(dictionary=flatten_dict(expt_config)) export_vars(source_dict=flatten_dict(expt_config)) + # pylint: disable=undefined-variable if USE_CRON_TO_RELAUNCH: add_crontab_line() @@ -237,20 +227,20 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de # ----------------------------------------------------------------------- # log_info( - f""" + """ Copying templates of various input files to the experiment directory...""", verbose=verbose, ) log_info( - f""" + """ Copying the template data table file to the experiment directory...""", verbose=verbose, ) cp_vrfy(DATA_TABLE_TMPL_FP, DATA_TABLE_FP) log_info( - f""" + """ Copying the template field table file to the experiment directory...""", verbose=verbose, ) @@ -262,7 +252,7 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de # DIR). # log_info( - f""" + """ Copying the CCPP physics suite definition XML file from its location in the forecast model directory structure to the experiment directory...""", verbose=verbose, @@ -274,9 +264,10 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de # DIR). # log_info( - f""" - Copying the field dictionary file from its location in the forecast - model directory structure to the experiment directory...""", + """ + Copying the field dictionary file from its location in the + forecast model directory structure to the experiment + directory...""", verbose=verbose, ) cp_vrfy(FIELD_DICT_IN_UWM_FP, FIELD_DICT_FP) @@ -294,7 +285,7 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de ) # # Set npx and npy, which are just NX plus 1 and NY plus 1, respectively. - # These need to be set in the FV3-LAM Fortran namelist file. They represent + # These need to be set in the FV3-LAM Fortran namelist file. They represent # the number of cell vertices in the x and y directions on the regional # grid. # @@ -323,9 +314,7 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de # Also, may want to set lsm here as well depending on SDF_USES_RUC_LSM. # lsoil = 4 - if (EXTRN_MDL_NAME_ICS == "HRRR" or EXTRN_MDL_NAME_ICS == "RAP") and ( - SDF_USES_RUC_LSM - ): + if EXTRN_MDL_NAME_ICS in ("HRRR", "RAP") and SDF_USES_RUC_LSM: lsoil = 9 if CCPP_PHYS_SUITE == "FV3_GFS_v15_thompson_mynn_lam3km": lsoil = "" @@ -374,9 +363,10 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de "layout": [LAYOUT_X, LAYOUT_Y], "bc_update_interval": LBC_SPEC_INTVL_HRS, }) - if ( CCPP_PHYS_SUITE == "FV3_GFS_2017_gfdl_mp" or - CCPP_PHYS_SUITE == "FV3_GFS_2017_gfdlmp_regional" or - CCPP_PHYS_SUITE == "FV3_GFS_v15p2" ): + if CCPP_PHYS_SUITE in ("FV3_GFS_2017_gfdl_mp", + "FV3_GFS_2017_gfdlmp_regional", + "FV3_GFS_v15p2", + ): if CPL_AQM: fv_core_nml_dict.update({ "dnats": 5 @@ -385,7 +375,7 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de fv_core_nml_dict.update({ "dnats": 1 }) - elif CCPP_PHYS_SUITE == "FV3_GFS_v16": + elif CCPP_PHYS_SUITE == "FV3_GFS_v16": if CPL_AQM: fv_core_nml_dict.update({ "hord_tr": 8, @@ -417,25 +407,26 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de if CPL_AQM: gfs_physics_nml_dict.update({ - "cplaqm": True, + "cplaqm": True, "cplocn2atm": False, - "fscav_aero": ["aacd:0.0", "acet:0.0", "acrolein:0.0", "acro_primary:0.0", "ald2:0.0", - "ald2_primary:0.0", "aldx:0.0", "benzene:0.0", "butadiene13:0.0", "cat1:0.0", - "cl2:0.0", "clno2:0.0", "co:0.0", "cres:0.0", "cron:0.0", - "ech4:0.0", "epox:0.0", "eth:0.0", "etha:0.0", "ethy:0.0", - "etoh:0.0", "facd:0.0", "fmcl:0.0", "form:0.0", "form_primary:0.0", - "gly:0.0", "glyd:0.0", "h2o2:0.0", "hcl:0.0", "hg:0.0", - "hgiigas:0.0", "hno3:0.0", "hocl:0.0", "hono:0.0", "hpld:0.0", - "intr:0.0", "iole:0.0", "isop:0.0", "ispd:0.0", "ispx:0.0", - "ket:0.0", "meoh:0.0", "mepx:0.0", "mgly:0.0", "n2o5:0.0", - "naph:0.0", "no:0.0", "no2:0.0", "no3:0.0", "ntr1:0.0", - "ntr2:0.0", "o3:0.0", "ole:0.0", "opan:0.0", "open:0.0", - "opo3:0.0", "pacd:0.0", "pan:0.0", "panx:0.0", "par:0.0", - "pcvoc:0.0", "pna:0.0", "prpa:0.0", "rooh:0.0", "sesq:0.0", - "so2:0.0", "soaalk:0.0", "sulf:0.0", "terp:0.0", "tol:0.0", - "tolu:0.0", "vivpo1:0.0", "vlvoo1:0.0", "vlvoo2:0.0", "vlvpo1:0.0", - "vsvoo1:0.0", "vsvoo2:0.0", "vsvoo3:0.0", "vsvpo1:0.0", "vsvpo2:0.0", - "vsvpo3:0.0", "xopn:0.0", "xylmn:0.0", "*:0.2" ] + "fscav_aero": [ + "aacd:0.0", "acet:0.0", "acrolein:0.0", "acro_primary:0.0", "ald2:0.0", + "ald2_primary:0.0", "aldx:0.0", "benzene:0.0", "butadiene13:0.0", "cat1:0.0", + "cl2:0.0", "clno2:0.0", "co:0.0", "cres:0.0", "cron:0.0", + "ech4:0.0", "epox:0.0", "eth:0.0", "etha:0.0", "ethy:0.0", + "etoh:0.0", "facd:0.0", "fmcl:0.0", "form:0.0", "form_primary:0.0", + "gly:0.0", "glyd:0.0", "h2o2:0.0", "hcl:0.0", "hg:0.0", + "hgiigas:0.0", "hno3:0.0", "hocl:0.0", "hono:0.0", "hpld:0.0", + "intr:0.0", "iole:0.0", "isop:0.0", "ispd:0.0", "ispx:0.0", + "ket:0.0", "meoh:0.0", "mepx:0.0", "mgly:0.0", "n2o5:0.0", + "naph:0.0", "no:0.0", "no2:0.0", "no3:0.0", "ntr1:0.0", + "ntr2:0.0", "o3:0.0", "ole:0.0", "opan:0.0", "open:0.0", + "opo3:0.0", "pacd:0.0", "pan:0.0", "panx:0.0", "par:0.0", + "pcvoc:0.0", "pna:0.0", "prpa:0.0", "rooh:0.0", "sesq:0.0", + "so2:0.0", "soaalk:0.0", "sulf:0.0", "terp:0.0", "tol:0.0", + "tolu:0.0", "vivpo1:0.0", "vlvoo1:0.0", "vlvoo2:0.0", "vlvpo1:0.0", + "vsvoo1:0.0", "vsvoo2:0.0", "vsvoo3:0.0", "vsvpo1:0.0", "vsvpo2:0.0", + "vsvpo3:0.0", "xopn:0.0", "xylmn:0.0", "*:0.2" ] }) settings["gfs_physics_nml"] = gfs_physics_nml_dict @@ -492,7 +483,7 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de settings_str = cfg_to_yaml_str(settings) log_info( - f""" + """ The variable 'settings' specifying values of the weather model's namelist variables has been set as follows:\n""", verbose=verbose, @@ -511,40 +502,19 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de # # ----------------------------------------------------------------------- # - try: - set_namelist( - [ - "-q", - "-n", - FV3_NML_BASE_SUITE_FP, - "-c", - FV3_NML_YAML_CONFIG_FP, - CCPP_PHYS_SUITE, - "-u", - settings_str, - "-o", - FV3_NML_FP, - ] - ) - except: - logging.exception( - dedent( - f""" - Call to python script set_namelist.py to generate an FV3 namelist file - failed. Parameters passed to this script are: - Full path to base namelist file: - FV3_NML_BASE_SUITE_FP = '{FV3_NML_BASE_SUITE_FP}' - Full path to yaml configuration file for various physics suites: - FV3_NML_YAML_CONFIG_FP = '{FV3_NML_YAML_CONFIG_FP}' - Physics suite to extract from yaml configuration file: - CCPP_PHYS_SUITE = '{CCPP_PHYS_SUITE}' - Full path to output namelist file: - FV3_NML_FP = '{FV3_NML_FP}' - Namelist settings specified on command line:\n - settings =\n\n""" - ) - + settings_str - ) + set_namelist( + [ + "-n", + FV3_NML_BASE_SUITE_FP, + "-c", + FV3_NML_YAML_CONFIG_FP, + CCPP_PHYS_SUITE, + "-u", + settings_str, + "-o", + FV3_NML_FP, + ] + ) # # If not running the TN_MAKE_GRID task (which implies the workflow will # use pregenerated grid files), set the namelist variables specifying @@ -581,34 +551,16 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de # # populate the namelist file # - try: - set_namelist( - [ - "-q", - "-n", - FV3_NML_FP, - "-u", - settings_str, - "-o", - FV3_NML_CYCSFC_FP, - ] - ) - except: - logging.exception( - dedent( - f""" - Call to python script set_namelist.py to generate an FV3 namelist file - failed. Parameters passed to this script are: - Full path to output namelist file: - FV3_NML_FP = '{FV3_NML_FP}' - Full path to output namelist file for DA: - FV3_NML_RESTART_FP = '{FV3_NML_CYCSFC_FP}' - Namelist settings specified on command line:\n - settings =\n\n""" - ) - + settings_str - ) - + set_namelist( + [ + "-n", + FV3_NML_FP, + "-u", + settings_str, + "-o", + FV3_NML_CYCSFC_FP, + ] + ) # # ----------------------------------------------------------------------- # @@ -624,7 +576,7 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de lupdatebc = False if DO_UPDATE_BC: lupdatebc = False # not ready for setting this to true yet - + settings = {} settings["fv_core_nml"] = { "external_ic": False, @@ -644,33 +596,17 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de # # populate the namelist file # - try: - set_namelist( - [ - "-q", - "-n", - FV3_NML_FP, - "-u", - settings_str, - "-o", - FV3_NML_RESTART_FP, - ] - ) - except: - logging.exception( - dedent( - f""" - Call to python script set_namelist.py to generate an FV3 namelist file - failed. Parameters passed to this script are: - Full path to output namelist file: - FV3_NML_FP = '{FV3_NML_FP}' - Full path to output namelist file for DA: - FV3_NML_RESTART_FP = '{FV3_NML_RESTART_FP}' - Namelist settings specified on command line:\n - settings =\n\n""" - ) - + settings_str - ) + set_namelist( + [ + "-q", + "-n", + FV3_NML_FP, + "-u", + settings_str, + "-o", + FV3_NML_RESTART_FP, + ] + ) # # ----------------------------------------------------------------------- # @@ -782,65 +718,31 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de # #----------------------------------------------------------------------- # - if DO_ENSEMBLE and ( DO_SPP or DO_SPPT or DO_SHUM or DO_SKEB or DO_LSM_SPP): - - try: + if DO_ENSEMBLE and any((DO_SPP, DO_SPPT, DO_SHUM, DO_SKEB, DO_LSM_SPP)): + + set_namelist( + [ + "-n", + FV3_NML_FP, + "-u", + settings_str, + "-o", + FV3_NML_STOCH_FP, + ] + ) + + if DO_DACYCLE or DO_ENKFUPDATE: set_namelist( [ "-q", "-n", - FV3_NML_FP, + FV3_NML_RESTART_FP, "-u", settings_str, "-o", - FV3_NML_STOCH_FP, + FV3_NML_RESTART_STOCH_FP, ] ) - except: - logging.exception( - dedent( - f""" - Call to python script set_namelist.py to generate an FV3 namelist file - failed. Parameters passed to this script are: - Full path to output namelist file: - FV3_NML_FP = '{FV3_NML_FP}' - Full path to output namelist file for stochastics: - FV3_NML_STOCH_FP = '{FV3_NML_STOCH_FP}' - Namelist settings specified on command line:\n - settings =\n\n""" - ) - + settings_str - ) - - if DO_DACYCLE or DO_ENKFUPDATE: - try: - set_namelist( - [ - "-q", - "-n", - FV3_NML_RESTART_FP, - "-u", - settings_str, - "-o", - FV3_NML_RESTART_STOCH_FP, - ] - ) - except: - logging.exception( - dedent( - f""" - Call to python script set_namelist.py to generate an FV3 namelist file - failed. Parameters passed to this script are: - Full path to output namelist file: - FV3_NML_FP = '{FV3_NML_FP}' - Full path to output namelist file for stochastics: - FV3_NML_RESTART_STOCH_FP = '{FV3_NML_RESTART_STOCH_FP}' - Namelist settings specified on command line:\n - settings =\n\n""" - ) - + settings_str - ) - # # ----------------------------------------------------------------------- # @@ -867,6 +769,7 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de rocotorun_cmd = f"rocotorun -w {WFLOW_XML_FN} -d {wflow_db_fn} -v 10" rocotostat_cmd = f"rocotostat -w {WFLOW_XML_FN} -d {wflow_db_fn} -v 10" + # pylint: disable=line-too-long log_info( f""" To launch the workflow, change location to the experiment directory @@ -897,8 +800,10 @@ def generate_FV3LAM_wflow(ushdir, logfile: str = "log.generate_FV3LAM_wflow", de */{CRON_RELAUNCH_INTVL_MNTS} * * * * cd {EXPTDIR} && ./launch_FV3LAM_wflow.sh called_from_cron="TRUE" """ ) + # pylint: enable=line-too-long - # If we got to this point everything was successful: move the log file to the experiment directory. + # If we got to this point everything was successful: move the log + # file to the experiment directory. mv_vrfy(logfile, EXPTDIR) return EXPTDIR @@ -908,7 +813,7 @@ def setup_logging(logfile: str = "log.generate_FV3LAM_wflow", debug: bool = Fals """ Sets up logging, printing high-priority (INFO and higher) messages to screen, and printing all messages with detailed timing and routine info in the specified text file. - + If debug = True, print all messages to both screen and log file. """ logging.getLogger().setLevel(logging.DEBUG) @@ -921,7 +826,8 @@ def setup_logging(logfile: str = "log.generate_FV3LAM_wflow", debug: bool = Fals logging.getLogger().addHandler(fh) logging.debug(f"Finished setting up debug file logging in {logfile}") - # If there are already multiple handlers, that means generate_FV3LAM_workflow was called from another function. + # If there are already multiple handlers, that means + # generate_FV3LAM_workflow was called from another function. # In that case, do not change the console (print-to-screen) logging. if len(logging.getLogger().handlers) > 1: return @@ -944,7 +850,7 @@ def setup_logging(logfile: str = "log.generate_FV3LAM_wflow", debug: bool = Fals # experiment/workflow. try: expt_dir = generate_FV3LAM_wflow(USHdir, wflow_logfile) - except: + except: # pylint: disable=bare-except logging.exception( dedent( f""" @@ -957,18 +863,18 @@ def setup_logging(logfile: str = "log.generate_FV3LAM_wflow", debug: bool = Fals """ ) ) - else: - # If no exception, note workflow generation completion - log_info( - f""" - ======================================================================== + sys.exit(1) + + # pylint: disable=undefined-variable + # Note workflow generation completion + log_info( + f""" + ======================================================================== Experiment generation completed. The experiment directory is: EXPTDIR='{EXPTDIR}' - ======================================================================== - """ - ) - - + ======================================================================== + """ + ) diff --git a/ush/load_modules_run_task.sh b/ush/load_modules_run_task.sh index 8d00a8fe65..a3b8aaca5a 100755 --- a/ush/load_modules_run_task.sh +++ b/ush/load_modules_run_task.sh @@ -98,16 +98,21 @@ set -u # #----------------------------------------------------------------------- # +default_modules_dir="$HOMEdir/modulefiles" machine=$(echo_lowercase $MACHINE) source "${HOMEdir}/etc/lmod-setup.sh" ${machine} +module use "${default_modules_dir}" + if [ "${machine}" != "wcoss2" ]; then - module use "${HOMEdir}/modulefiles" module load "${BUILD_MOD_FN}" || print_err_msg_exit "\ Loading of platform- and compiler-specific module file (BUILD_MOD_FN) for the workflow task specified by task_name failed: task_name = \"${task_name}\" BUILD_MOD_FN = \"${BUILD_MOD_FN}\"" fi + +module load set_pythonpath || print_err_msg_exit "\ + Loading the module to set PYTHONPATH for workflow-tools failed." # #----------------------------------------------------------------------- # @@ -134,9 +139,8 @@ fi # #----------------------------------------------------------------------- # -modules_dir="$HOMEdir/modulefiles/tasks/$machine" +modules_dir="$default_modules_dir/tasks/$machine" modulefile_name="${task_name}" -default_modules_dir="$HOMEdir/modulefiles" # #----------------------------------------------------------------------- # @@ -173,6 +177,8 @@ elif [ -f ${modules_dir}/python_srw.lua ] ; then modules_dir = \"${modules_dir}\"" fi + + module list # Modules that use conda and need an environment activated will set the diff --git a/ush/load_modules_wflow.sh b/ush/load_modules_wflow.sh index 5e7e30e3a7..7631295d76 100755 --- a/ush/load_modules_wflow.sh +++ b/ush/load_modules_wflow.sh @@ -62,7 +62,7 @@ task failed: $has_mu && set +u if [ ! -z $(command -v conda) ]; then - conda activate regional_workflow + conda activate workflow_tools fi $has_mu && set -u diff --git a/ush/set_FV3nml_sfc_climo_filenames.py b/ush/set_FV3nml_sfc_climo_filenames.py index cdc4ed1628..bc579151c5 100644 --- a/ush/set_FV3nml_sfc_climo_filenames.py +++ b/ush/set_FV3nml_sfc_climo_filenames.py @@ -60,7 +60,7 @@ def set_FV3nml_sfc_climo_filenames(): # Set the suffix of the surface climatology files. suffix = "tileX.nc" - # create yaml-complaint string + # create yaml-compliant string settings = {} dummy_run_dir = os.path.join(EXPTDIR, "any_cyc")