Skip to content
Snippets Groups Projects
Commit 0e0bb9b5 authored by Bianca Wentzel's avatar Bianca Wentzel
Browse files

Merge branch 'plugin_template' into 'master'

Plugin template

Closes #1

See merge request !2
parents 45b268fe 585418dd
No related branches found
No related tags found
1 merge request!2Plugin template
Pipeline #92833 failed
{
"template": "https://gitlab.dkrz.de/ch1187/plugins4freva/freva-plugin-template.git",
"commit": "24977a4ad70419ee781f97bab68acfc0cbc19b20",
"checkout": null,
"context": {
"cookiecutter": {
"plugin_authors": "Christian Beier",
"plugin_author_emails": "christian.beier@b-tu.de",
"plugin_maintainers": "Christian Beier, Mostafa Hadizadeh, Bianca Wentzel",
"plugin_maintainer_emails": "christian.beier@b-tu.de,hadizadeh@dkrz.de,wentzel@dkrz.de",
"project_name": "RegiKlim",
"gitlab_host": "gitlab.dkrz.de",
"gitlab_username": "ch1187/plugins4freva",
"git_remote_protocoll": "https",
"institution": "Brandenburgische Technische Universität Cottbus-Senftenberg",
"institution_url": "https://www.b-tu.de/",
"conda_channels": "conda-forge",
"conda_dependencies": "r-base, pip",
"add_assets": "yes",
"pip_dependencies": "numpy",
"plugin_title": "PET",
"plugin_slug": "pet",
"plugin_folder": "pet",
"plugin_short_description": "PET",
"keywords": "",
"_extensions": [
"local_extensions.UnderlinedExtension"
],
"copyright_holder": "Brandenburgische Technische Universität Cottbus-Senftenberg",
"copyright_year": "2024",
"code_license": "BSD-3-Clause",
"use_reuse": "yes",
"documentation_license": "CC-BY-4.0",
"documentation_url": "https://pet.readthedocs.io/en/latest/",
"use_markdown_for_documentation": "yes",
"deploy_pages_in_ci": "yes",
"supplementary_files_license": "CC0-1.0",
"use_dkrz_runner": "yes",
"ci_build_stage": "no",
"use_cibuildwheel": "no",
"ci_matrix": "no",
"use_pytest_xdist": "no",
"deploy_plugin_in_ci": "yes",
"__ci_build_stage": "no",
"use_submodules": "no",
"_template": "https://gitlab.dkrz.de/ch1187/plugins4freva/freva-plugin-template.git"
}
},
"directory": "/tmp/tmphp745fb8/template",
"skip": [
".git",
".mypy_cache"
]
}
SPDX-FileCopyrightText: 2024 2024 Brandenburgische Technische Universität Cottbus-Senftenberg
SPDX-License-Identifier: BSD-3-Clause
# SPDX-FileCopyrightText: 2024 Brandenburgische Technische Universität Cottbus-Senftenberg
#
# SPDX-License-Identifier: CC0-1.0
pet/_version.py export-subst
# SPDX-FileCopyrightText: 2024 Brandenburgische Technische Universität Cottbus-Senftenberg
#
# SPDX-License-Identifier: CC0-1.0
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
static/
docs/api
pet/migrations/00*.py
docs/_static/orcid.*
plugin_env/
# SPDX-FileCopyrightText: 2024 Brandenburgische Technische Universität Cottbus-Senftenberg
#
# SPDX-License-Identifier: CC0-1.0
stages:
- test
- pages
variables:
PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"
cache:
paths:
- .cache/pip
.config_freva: &config_freva
image: ghcr.io/freva-clint/freva-dev:latest
tags:
- docker-any-image
before_script:
- conda create --override-channels --channel conda-forge --prefix ./plugin_env python==3.10
# ⚠️ Due to complex bashrc setup in `freva-dev` image, we need to reinit conda manually
- source /opt/evaluation_system/etc/profile.d/conda.sh
- export PATH="$CI_PROJECT_DIR/plugin_env/bin:$PATH"
- conda activate $CI_PROJECT_DIR/plugin_env
- conda clean -a -y
- pip install pytest
- conda config --set channel_priority strict
- conda install --override-channels --channel conda-forge -y pandoc graphviz wget zip git git-lfs cdo nco jq freva
- git lfs install
# ensure cdo and nco are up
- cdo --version
- freva --version
# configure the freva plugin
- export EVALUATION_SYSTEM_CONFIG_FILE=$CI_PROJECT_DIR/plugin_env/freva/evaluation_system.conf
- export EVALUATION_SYSTEM_CONFIG_DIR=$CI_PROJECT_DIR/plugin_env/freva/
- wget https://freva.gitlab-pages.dkrz.de/metadata-crawler-source/binaries/data-crawler -O data-crawler
- chmod +x data-crawler
func-test:
<<: *config_freva
stage: test
script:
# ⚠️ To make the following jobs work, please have a look at the `climate-change-profile` plugin at the link below:
# https://gitlab.dkrz.de/ch1187/plugins4freva/climate-change-profile/-/blob/main/.gitlab-ci.yml?ref_type=heads#L53
- export SCRATCH=/tmp
- mkdir -p /home/freva
- cd /home/freva
- tar -xJvf $CI_PROJECT_DIR/data/btu-data.tar.xz
- cd $CI_PROJECT_DIR
- make prepare-freva # This command prepares the configuration files for the plugin
- ./data-crawler solr add -ds nukleus-btu
- export EVALUATION_SYSTEM_PLUGINS=$CI_PROJECT_DIR,pet-wrapper-api
- freva-plugin --list
- freva-plugin pet project=nukleus product=ceu-3 institute=clmcom-btu model=ec-earth-consortium-ec-earth3-veg-clmcom-btu-icon-2-6-5-rc-nukleus-x2yn2-v1 experiment=historical realm=atmos ensemble=r1i1p1f1 start_date=1967-01-01 end_date=1969-12-31 region=2,6,46,54 output_dir=$CI_PROJECT_DIR/output debug=True -vvv
- mkdir -p build/func_test
- FREVA_JOB_ID=$(ls plugin_env/freva_output/freva/freva/output/pet/ | head -n 1)
- cd plugin_env/freva_output/freva/freva/output/pet/$FREVA_JOB_ID
- |
desired_out_files=("APOTEVAP_S_1967010100-1968010100.ncz" "APOTEVAP_S_1968010100-1969010100.ncz" "APOTEVAP_S_1969010100-1970010100.ncz")
for file in ${desired_out_files[@]}; do
if [ ! -f APOTEVAP_S/$file ]; then
exit 1
fi
done
- echo '<html><body>' >> index.html
- echo '<h1>PET plugin Results:</h1>' >> index.html
- echo '<a href="'$CI_PROJECT_URL'/-/jobs/'$CI_JOB_ID'/artifacts/browse/build/func_test/APOTEVAP_S/" target="_blank">Link to data</a>' >> index.html
- echo '</body></html>' >> index.html
- ls -la
- cp -r * $CI_PROJECT_DIR/build/func_test
artifacts:
when: always
paths:
- build/func_test
prod-test:
id_tokens:
SITE_ID_TOKEN:
aud: https://gitlab.dkrz.de
tags:
- levante
variables:
SCHEDULER_PARAMETERS: "--account=$ACCOUNT --partition=shared --mem=16G"
script:
- module load clint $PROJECT_MODULE
- source /etc/profile.d/modules.sh
- module use /sw/spack-levante/spack/modules
- module load cdo/2.2.2-gcc-11.2.0 nco/5.0.6-gcc-11.2.0
- export EVALUATION_SYSTEM_PLUGINS=$CI_PROJECT_DIR,pet-wrapper-api
- freva-plugin --list
- freva-plugin pet project=nukleus product=ceu-3 institute=clmcom-btu model=ec-earth-consortium-ec-earth3-veg-clmcom-btu-icon-2-6-5-rc-nukleus-x2yn2-v1 experiment=historical realm=atmos ensemble=r1i1p1f1 start_date=1970-01-01 end_date=1971-12-31 region=2,6,46,54 caption="PET production test from CI piepline https://gitlab.dkrz.de/ch1187/plugins4freva/pet/-/jobs/$CI_JOB_ID"-vvv
- mkdir -p build/prod_test
- REGIKLIM_JOB_ID=$(ls -t /work/$ACCOUNT/regiklim-work/$GITLAB_USER_LOGIN/regiklim-ces/output/pet/ | head -n 1)
- cd /work/$ACCOUNT/regiklim-work/$GITLAB_USER_LOGIN/regiklim-ces/output/pet/$REGIKLIM_JOB_ID
- echo "<!DOCTYPE html><html><head>" >> index.html
- echo "<meta http-equiv=\"refresh\" content=\"0; url=https://www-regiklim.dkrz.de/history/$REGIKLIM_JOB_ID/results/\">" >> index.html
- echo "<title>Redirecting...</title>" >> index.html
- echo "</head><body>" >> index.html
- echo "<p>If you are not redirected, <a href=\"https://www-regiklim.dkrz.de/history/$REGIKLIM_JOB_ID/results/\">click here</a>.</p>" >> index.html
- echo "</body></html>" >> index.html
- ls -la
- cp -r * $CI_PROJECT_DIR/build/prod_test
artifacts:
when: always
paths:
- build/prod_test
pages:
stage: pages
tags:
- sphinx
needs:
- func-test
- prod-test
script:
- mkdir -p public/docs
- cp -r docs/_build/html/* public/docs/
- mkdir -p public/func_test
- cp -r build/func_test/* public/func_test/
- mkdir -p public/prod-test
- cp -r build/prod-test/* public/prod-test
artifacts:
paths:
- public
only:
- main
- master
# SPDX-FileCopyrightText: 2024 Brandenburgische Technische Universität Cottbus-Senftenberg
#
# SPDX-License-Identifier: CC0-1.0
# https://pre-commit.com/
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- repo: https://github.com/fsfe/reuse-tool
rev: v3.0.2
hooks:
- id: reuse
files: ^src/pet
- repo: https://github.com/citation-file-format/cff-converter-python
# there is no release with this hook yet
rev: "44e8fc9"
hooks:
- id: validate-cff
files: ^src/pet
"""Helper script to add licenses to files.
This script can be used to apply the licenses and default copyright holders
to files in the repository.
It uses the short cuts from the ``.reuse/shortcuts.yaml`` file and
adds them to the call of ``reuse annotate``. Any command line option however
overwrites the config in ``shortcuts.yaml``
Usage::
python .reuse/add_license.py <shortcut> <path> [OPTIONS]
"""
import os.path as osp
from argparse import ArgumentParser
from pathlib import Path
from textwrap import dedent
from typing import Dict, Optional, TypedDict
import yaml
from reuse.project import Project
try:
from reuse._annotate import add_arguments as _orig_add_arguments
from reuse._annotate import run
except ImportError:
# reuse < 3.0
from reuse.header import add_arguments as _orig_add_arguments
from reuse.header import run
class LicenseShortCut(TypedDict):
"""Shortcut to add a copyright statement"""
#: The copyright statement
copyright: str
#: year of copyright statement
year: str
#: SPDX Identifier of the license
license: Optional[str]
def load_shortcuts() -> Dict[str, LicenseShortCut]:
"""Load the ``shortcuts.yaml`` file."""
with open(osp.join(osp.dirname(__file__), "shortcuts.yaml")) as f:
return yaml.safe_load(f)
def add_arguments(
parser: ArgumentParser, shortcuts: Dict[str, LicenseShortCut]
):
parser.add_argument(
"shortcut",
choices=[key for key in shortcuts if not key.startswith(".")],
help=(
"What license should be applied? Shortcuts are loaded from "
".reuse/shortcuts.yaml. Possible shortcuts are %(choices)s"
),
)
_orig_add_arguments(parser)
parser.set_defaults(func=run)
parser.set_defaults(parser=parser)
def main(argv=None):
shortcuts = load_shortcuts()
parser = ArgumentParser(
prog=".reuse/add_license.py",
description=dedent(
"""
Add copyright and licensing into the header of files with shortcuts
This script uses the ``reuse annotate`` command to add copyright
and licensing information into the header the specified files.
It accepts the same arguments as ``reuse annotate``, plus an
additional required `shortcuts` argument. The given `shortcut`
comes from the file at ``.reuse/shortcuts.yaml`` to fill in
copyright, year and license identifier.
For further information, please type ``reuse annotate --help``"""
),
)
add_arguments(parser, shortcuts)
args = parser.parse_args(argv)
shortcut = shortcuts[args.shortcut]
if args.year is None:
args.year = []
if args.copyright is None:
args.copyright = []
if args.license is None and shortcut.get("license"):
args.license = [shortcut["license"]]
elif args.license and shortcut.get("license"):
args.license.append(shortcut["license"])
args.year.append(shortcut["year"])
args.copyright.append(shortcut["copyright"])
project = Project(Path(__file__).parent.parent)
args.func(args, project)
if __name__ == "__main__":
main()
# SPDX-FileCopyrightText: 2024 Brandenburgische Technische Universität Cottbus-Senftenberg
#
# SPDX-License-Identifier: CC0-1.0
.defaults: &defaults
year: "2024"
copyright: "Brandenburgische Technische Universität Cottbus-Senftenberg"
# The following dictionaries items map to dictionaries with three possible
# keys:
#
# copyright: The copyright statement
# year: year of copyright statement
# license: SPDX Identifier
docs:
<<: *defaults
license: "CC-BY-4.0"
code:
<<: *defaults
license: "EUPL-1.2"
supp:
<<: *defaults
license: "CC0-1.0"
<!--
SPDX-FileCopyrightText: 2024 Brandenburgische Technische Universität Cottbus-Senftenberg
SPDX-License-Identifier: CC0-1.0
-->
# Changelog
## v2025.01.10: Initial release
### Added
* Added licencing information
* Added test data and tests
* Added README, Makefile, Changelog, Manifest and Citation information
* Added pre-commit hooks and GitLa Pipeline
* Added basic configuration parameters (`.cruft.json`)
* Added plugin wrapper utilizing the databrowser to search for CMORized data files based on generalized varaible names
* Added HTML representation explaining where to find results and how to access them
### Changed
* Moved scientific calculation scripts into `src/pet/`
* Adapted main calculation script to follow dry principle and provide more logging: `src/pet/calculation.sh`
* Outsourced definition of calculation functions into seperate file: `src/pet/pet_functions.sh`
* Outsourced basic configurations into seperate file: `src/pet/utils.sh`
* Outsourced additional expression files into own directory: `src/pet/helper`
# SPDX-FileCopyrightText: 2024 2024 Brandenburgische Technische Universität Cottbus-Senftenberg
#
# SPDX-License-Identifier: CC0-1.0
authors:
# list author information. see
# https://github.com/citation-file-format/citation-file-format/blob/main/schema-guide.md#definitionsperson
# for metadata
- family-names: "Beier"
given-names: "Christian"
affiliation: "Brandenburgische Technische Universität Cottbus-Senftenberg"
# orcid: null
email: "christian.beier@b-tu.de"
cff-version: 1.2.0
message: "If you use this software, please cite it using these metadata."
title: "PET"
keywords:
- "freva"
- "plugin"
- "climate"
- "regiklim"
- "nukleus"
license: 'BSD-3-Clause'
repository-code: "https://gitlab.dkrz.de/ch1187/plugins4freva/pet"
url: "https://gitlab.dkrz.de/ch1187/plugins4freva/pet"
contact:
# list maintainer information. see
# https://github.com/citation-file-format/citation-file-format/blob/main/schema-guide.md#definitionsperson
# for metadata
- family-names: "Beier"
given-names: "Christian"
affiliation: "Brandenburgische Technische Universität Cottbus-Senftenberg"
# orcid: null
email: "christian.beier@b-tu.de"
- family-names: "Hadizadeh"
given-names: "Mostafa"
affiliation: "Deutsche Klimarechenzentrum"
# orcid: null
email: "hadizadeh@dkrz.de"
- family-names: "Wentzel"
given-names: "Bianca"
affiliation: "Deutsches Klimarechenzentrum"
# orcid: null
email: "wentzel@dkrz.de"
abstract: |
PET
Copyright (c) <year> <owner>.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.
EUROPEAN UNION PUBLIC LICENCE v. 1.2
EUPL © the European Union 2007, 2016
This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined below) which is provided under the
terms of this Licence. Any use of the Work, other than as authorised under this Licence is prohibited (to the extent such
use is covered by a right of the copyright holder of the Work).
The Work is provided under the terms of this Licence when the Licensor (as defined below) has placed the following
notice immediately following the copyright notice for the Work:
Licensed under the EUPL
or has expressed by any other means his willingness to license under the EUPL.
1.Definitions
In this Licence, the following terms have the following meaning:
— ‘The Licence’:this Licence.
— ‘The Original Work’:the work or software distributed or communicated by the Licensor under this Licence, available
as Source Code and also as Executable Code as the case may be.
— ‘Derivative Works’:the works or software that could be created by the Licensee, based upon the Original Work or
modifications thereof. This Licence does not define the extent of modification or dependence on the Original Work
required in order to classify a work as a Derivative Work; this extent is determined by copyright law applicable in
the country mentioned in Article 15.
— ‘The Work’:the Original Work or its Derivative Works.
— ‘The Source Code’:the human-readable form of the Work which is the most convenient for people to study and
modify.
— ‘The Executable Code’:any code which has generally been compiled and which is meant to be interpreted by
a computer as a program.
— ‘The Licensor’:the natural or legal person that distributes or communicates the Work under the Licence.
— ‘Contributor(s)’:any natural or legal person who modifies the Work under the Licence, or otherwise contributes to
the creation of a Derivative Work.
— ‘The Licensee’ or ‘You’:any natural or legal person who makes any usage of the Work under the terms of the
Licence.
— ‘Distribution’ or ‘Communication’:any act of selling, giving, lending, renting, distributing, communicating,
transmitting, or otherwise making available, online or offline, copies of the Work or providing access to its essential
functionalities at the disposal of any other natural or legal person.
2.Scope of the rights granted by the Licence
The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, sublicensable licence to do the following, for
the duration of copyright vested in the Original Work:
— use the Work in any circumstance and for all usage,
— reproduce the Work,
— modify the Work, and make Derivative Works based upon the Work,
— communicate to the public, including the right to make available or display the Work or copies thereof to the public
and perform publicly, as the case may be, the Work,
— distribute the Work or copies thereof,
— lend and rent the Work or copies thereof,
— sublicense rights in the Work or copies thereof.
Those rights can be exercised on any media, supports and formats, whether now known or later invented, as far as the
applicable law permits so.
In the countries where moral rights apply, the Licensor waives his right to exercise his moral right to the extent allowed
by law in order to make effective the licence of the economic rights here above listed.
The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to any patents held by the Licensor, to the
extent necessary to make use of the rights granted on the Work under this Licence.
3.Communication of the Source Code
The Licensor may provide the Work either in its Source Code form, or as Executable Code. If the Work is provided as
Executable Code, the Licensor provides in addition a machine-readable copy of the Source Code of the Work along with
each copy of the Work that the Licensor distributes or indicates, in a notice following the copyright notice attached to
the Work, a repository where the Source Code is easily and freely accessible for as long as the Licensor continues to
distribute or communicate the Work.
4.Limitations on copyright
Nothing in this Licence is intended to deprive the Licensee of the benefits from any exception or limitation to the
exclusive rights of the rights owners in the Work, of the exhaustion of those rights or of other applicable limitations
thereto.
5.Obligations of the Licensee
The grant of the rights mentioned above is subject to some restrictions and obligations imposed on the Licensee. Those
obligations are the following:
Attribution right: The Licensee shall keep intact all copyright, patent or trademarks notices and all notices that refer to
the Licence and to the disclaimer of warranties. The Licensee must include a copy of such notices and a copy of the
Licence with every copy of the Work he/she distributes or communicates. The Licensee must cause any Derivative Work
to carry prominent notices stating that the Work has been modified and the date of modification.
Copyleft clause: If the Licensee distributes or communicates copies of the Original Works or Derivative Works, this
Distribution or Communication will be done under the terms of this Licence or of a later version of this Licence unless
the Original Work is expressly distributed only under this version of the Licence — for example by communicating
‘EUPL v. 1.2 only’. The Licensee (becoming Licensor) cannot offer or impose any additional terms or conditions on the
Work or Derivative Work that alter or restrict the terms of the Licence.
Compatibility clause: If the Licensee Distributes or Communicates Derivative Works or copies thereof based upon both
the Work and another work licensed under a Compatible Licence, this Distribution or Communication can be done
under the terms of this Compatible Licence. For the sake of this clause, ‘Compatible Licence’ refers to the licences listed
in the appendix attached to this Licence. Should the Licensee's obligations under the Compatible Licence conflict with
his/her obligations under this Licence, the obligations of the Compatible Licence shall prevail.
Provision of Source Code: When distributing or communicating copies of the Work, the Licensee will provide
a machine-readable copy of the Source Code or indicate a repository where this Source will be easily and freely available
for as long as the Licensee continues to distribute or communicate the Work.
Legal Protection: This Licence does not grant permission to use the trade names, trademarks, service marks, or names
of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and
reproducing the content of the copyright notice.
6.Chain of Authorship
The original Licensor warrants that the copyright in the Original Work granted hereunder is owned by him/her or
licensed to him/her and that he/she has the power and authority to grant the Licence.
Each Contributor warrants that the copyright in the modifications he/she brings to the Work are owned by him/her or
licensed to him/her and that he/she has the power and authority to grant the Licence.
Each time You accept the Licence, the original Licensor and subsequent Contributors grant You a licence to their contributions
to the Work, under the terms of this Licence.
7.Disclaimer of Warranty
The Work is a work in progress, which is continuously improved by numerous Contributors. It is not a finished work
and may therefore contain defects or ‘bugs’ inherent to this type of development.
For the above reason, the Work is provided under the Licence on an ‘as is’ basis and without warranties of any kind
concerning the Work, including without limitation merchantability, fitness for a particular purpose, absence of defects or
errors, accuracy, non-infringement of intellectual property rights other than copyright as stated in Article 6 of this
Licence.
This disclaimer of warranty is an essential part of the Licence and a condition for the grant of any rights to the Work.
8.Disclaimer of Liability
Except in the cases of wilful misconduct or damages directly caused to natural persons, the Licensor will in no event be
liable for any direct or indirect, material or moral, damages of any kind, arising out of the Licence or of the use of the
Work, including without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, loss
of data or any commercial damage, even if the Licensor has been advised of the possibility of such damage. However,
the Licensor will be liable under statutory product liability laws as far such laws apply to the Work.
9.Additional agreements
While distributing the Work, You may choose to conclude an additional agreement, defining obligations or services
consistent with this Licence. However, if accepting obligations, You may act only on your own behalf and on your sole
responsibility, not on behalf of the original Licensor or any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against such Contributor by
the fact You have accepted any warranty or additional liability.
10.Acceptance of the Licence
The provisions of this Licence can be accepted by clicking on an icon ‘I agree’ placed under the bottom of a window
displaying the text of this Licence or by affirming consent in any other similar way, in accordance with the rules of
applicable law. Clicking on that icon indicates your clear and irrevocable acceptance of this Licence and all of its terms
and conditions.
Similarly, you irrevocably accept this Licence and all of its terms and conditions by exercising any rights granted to You
by Article 2 of this Licence, such as the use of the Work, the creation by You of a Derivative Work or the Distribution
or Communication by You of the Work or copies thereof.
11.Information to the public
In case of any Distribution or Communication of the Work by means of electronic communication by You (for example,
by offering to download the Work from a remote location) the distribution channel or media (for example, a website)
must at least provide to the public the information requested by the applicable law regarding the Licensor, the Licence
and the way it may be accessible, concluded, stored and reproduced by the Licensee.
12.Termination of the Licence
The Licence and the rights granted hereunder will terminate automatically upon any breach by the Licensee of the terms
of the Licence.
Such a termination will not terminate the licences of any person who has received the Work from the Licensee under
the Licence, provided such persons remain in full compliance with the Licence.
13.Miscellaneous
Without prejudice of Article 9 above, the Licence represents the complete agreement between the Parties as to the
Work.
If any provision of the Licence is invalid or unenforceable under applicable law, this will not affect the validity or
enforceability of the Licence as a whole. Such provision will be construed or reformed so as necessary to make it valid
and enforceable.
The European Commission may publish other linguistic versions or new versions of this Licence or updated versions of
the Appendix, so far this is required and reasonable, without reducing the scope of the rights granted by the Licence.
New versions of the Licence will be published with a unique version number.
All linguistic versions of this Licence, approved by the European Commission, have identical value. Parties can take
advantage of the linguistic version of their choice.
14.Jurisdiction
Without prejudice to specific agreement between parties,
— any litigation resulting from the interpretation of this License, arising between the European Union institutions,
bodies, offices or agencies, as a Licensor, and any Licensee, will be subject to the jurisdiction of the Court of Justice
of the European Union, as laid down in article 272 of the Treaty on the Functioning of the European Union,
— any litigation arising between other parties and resulting from the interpretation of this License, will be subject to
the exclusive jurisdiction of the competent court where the Licensor resides or conducts its primary business.
15.Applicable Law
Without prejudice to specific agreement between parties,
— this Licence shall be governed by the law of the European Union Member State where the Licensor has his seat,
resides or has his registered office,
— this licence shall be governed by Belgian law if the Licensor has no seat, residence or registered office inside
a European Union Member State.
Appendix
‘Compatible Licences’ according to Article 5 EUPL are:
— GNU General Public License (GPL) v. 2, v. 3
— GNU Affero General Public License (AGPL) v. 3
— Open Software License (OSL) v. 2.1, v. 3.0
— Eclipse Public License (EPL) v. 1.0
— CeCILL v. 2.0, v. 2.1
— Mozilla Public Licence (MPL) v. 2
— GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3
— Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for works other than software
— European Union Public Licence (EUPL) v. 1.1, v. 1.2
— Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong Reciprocity (LiLiQ-R+).
The European Commission may update this Appendix to later versions of the above licences without producing
a new version of the EUPL, as long as they provide the rights granted in Article 2 of this Licence and protect the
covered Source Code from exclusive appropriation.
All other changes or additions to this Appendix require the production of a new EUPL version.
# SPDX-FileCopyrightText: 2024 Brandenburgische Technische Universität Cottbus-Senftenberg
#
# SPDX-License-Identifier: CC0-1.0
include versioneer.py
include pet/_version.py
Makefile 0 → 100644
# SPDX-FileCopyrightText: 2024 Brandenburgische Technische Universität Cottbus-Senftenberg
#
# SPDX-License-Identifier: CC0-1.0
.PHONY: clean clean-build clean-pyc clean-test coverage dist docs help install lint lint/flake8 lint/black
.DEFAULT_GOAL := help
# ANSI color codes
RED := \033[31m
GREEN := \033[32m
YELLOW := \033[33m
BLUE := \033[34m
BOLD := \033[1m
RESET := \033[0m
define BROWSER_PYSCRIPT
import os, webbrowser, sys
from urllib.request import pathname2url
webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1])))
endef
export BROWSER_PYSCRIPT
define PRINT_HELP_PYSCRIPT
import re, sys
for line in sys.stdin:
match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line)
if match:
target, help = match.groups()
print("\033[32m%-20s\033[0m %s" % (target, help))
endef
export PRINT_HELP_PYSCRIPT
BROWSER := python -c "$$BROWSER_PYSCRIPT"
help:
@echo "${BOLD}Available commands:${RESET}"
@python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST)
clean: clean-build clean-pyc clean-test clean-venv ## remove all build, virtual environments, test, coverage and Python artifacts
clean-build: ## remove build artifacts
rm -fr build/
rm -fr dist/
rm -fr .eggs/
find . -name '*.egg-info' -exec rm -fr {} +
find . -name '*.egg' -exec rm -rf {} +
clean-pyc: ## remove Python file artifacts
find . -name '*.pyc' -exec rm -f {} +
find . -name '*.pyo' -exec rm -f {} +
find . -name '*~' -exec rm -f {} +
find . -name '__pycache__' -exec rm -fr {} +
clean-test: ## remove test and coverage artifacts
rm -fr .tox/
rm -f .coverage
rm -fr htmlcov/
rm -fr .pytest_cache
clean-venv: # remove the virtual environment
rm -rf venv
docs: ## generate Sphinx HTML documentation, including API docs
$(MAKE) -C docs clean
$(MAKE) -C docs html
$(BROWSER) docs/_build/html/index.html
test-docs: ## generate Sphinx HTML documentation, including API docs
$(MAKE) -C docs clean
$(MAKE) -C docs linkcheck
servedocs: docs ## compile the docs watching for changes
watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D .
release: dist ## package and upload a release
twine upload dist/*
dist: clean ## builds source and wheel package
python -m build
ls -l dist
install: clean ## install the package to the active Python's site-packages
python -m pip install .
dev-install: clean ## install the package and development section
python -m pip install -r docs/requirements.txt
python -m pip install -e .[dev]
venv-install: clean ## install the package in a virtual environment
python -m venv venv
venv/bin/python -m pip install -r docs/requirements.txt
venv/bin/python -m pip install -e .[dev]
venv/bin/pre-commit install
prepare-freva: clean ## prepare the configuration files for FREVA
pytest src/tests/test_config_updates.py::test_prepare_freva -s
\ No newline at end of file
README.md 0 → 100644
<!--
SPDX-FileCopyrightText: 2024 Brandenburgische Technische Universität Cottbus-Senftenberg
SPDX-License-Identifier: BSD-3-Clause
-->
# PET
[![CI](https://gitlab.dkrz.de/ch1187/plugins4freva/pet/badges/master/pipeline.svg)](https://gitlab.dkrz.de/ch1187/plugins4freva/pet/-/pipelines?page=1&scope=all&ref=master)
<!-- [![Code coverage](https://gitlab.dkrz.de/ch1187/plugins4freva/pet/badges/main/coverage.svg)](https://gitlab.dkrz.de/ch1187/plugins4freva/pet/-/graphs/main/charts) -->
<!-- TODO: uncomment the following line when the package is registered at https://readthedocs.org -->
<!-- [![Docs](https://readthedocs.org/projects/pet/badge/?version=latest)](https://pet.readthedocs.io/en/latest/) -->
<!-- [![Latest Release](https://gitlab.dkrz.de/ch1187/plugins4freva/pet/-/badges/release.svg)](https://gitlab.dkrz.de/ch1187/plugins4freva/pet) -->
<!-- TODO: uncomment the following line when the package is published at https://pypi.org -->
<!-- [![PyPI version](https://img.shields.io/pypi/v/pet.svg)](https://pypi.python.org/pypi/pet/) -->
[![Functional](https://img.shields.io/badge/Functional-Test-brown.svg)](https://ch1187.gitlab-pages.dkrz.de/plugins4freva/pet/func_test/)
[![Production](https://img.shields.io/badge/Production-Test-ff33fc.svg)](https://ch1187.gitlab-pages.dkrz.de/plugins4freva/pet/prod_test/)
<!-- [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) -->
<!-- [![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://pycqa.github.io/isort/) -->
<!-- [![PEP8](https://img.shields.io/badge/code%20style-pep8-orange.svg)](https://www.python.org/dev/peps/pep-0008/) -->
<!-- [![Checked with mypy](http://www.mypy-lang.org/static/mypy_badge.svg)](http://mypy-lang.org/) -->
<!-- TODO: uncomment the following line when the package is registered at https://api.reuse.software -->
[![REUSE status](https://api.reuse.software/badge/gitlab.dkrz.de/ch1187/plugins4freva/pet)](https://api.reuse.software/info/gitlab.dkrz.de/ch1187/plugins4freva/pet)
## Connection and Module Loading
To connect to the server and load the necessary modules for the project, use the following commands:
```bash
ssh <user-id>@levante.dkrz.de
module load clint regiklim-ces
```
## Integrating PET with the Plugin
To integrate PET into your Freva instance, follow these steps:
1. **Clone the Plugin Repository:**
Navigate to the appropriate directory and clone the repository using the following commands:
```bash
cd /work/ch1187/regiklim-work/<username>/regiklim-ces/plugins/
git clone https://gitlab.dkrz.de/ch1187/plugins4freva/pet.git
```
2. **Install Prerequisites:**
After cloning the repository, install the required packages:
```bash
cd pet
source /etc/profile.d/modules.sh
module use /sw/spack-levante/spack/modules
module load cdo/2.2.2-gcc-11.2.0 nco/5.0.6-gcc-11.2.0
```
3. **Configure the Freva Instance:**
Use the following export command to make the plugin available in your Freva instance:
```bash
export EVALUATION_SYSTEM_PLUGINS=/work/ch1187/regiklim-work/<username>/regiklim-ces/plugins/pet,pet-wrapper-api
```
Now, the plugin is ready to be used in your Freva instance.
## Development and contribution
To use this in a development setup, clone the [source code](https://gitlab.dkrz.de/ch1187/plugins4freva/pet.git) from
gitlab, start the development server and make your changes:
```bash
git clone https://gitlab.dkrz.de/ch1187/plugins4freva/pet.git
cd pet
source /etc/profile.d/modules.sh
module use /sw/spack-levante/spack/modules
module load cdo/2.2.2-gcc-11.2.0 nco/5.0.6-gcc-11.2.0
```
In order to be able to run the given CI/CD-Pipelines two additional variables need to be defined within the repository:
| Variable Key | Description |
|----------------|-----------------------------------------------|
| ACCOUNT | Project account to run the production test CI-job. |
| PROJECT_MODULE | Name of project module which should be loaded |
## Technical note
This package has been generated from the template
[Freva Plugin Template](https://gitlab.dkrz.de/ch1187/plugins4freva/freva-plugin-template).
See the template repository for instructions on how to update the skeleton for
this package.
## License information
Copyright © 2024 Brandenburgische Technische Universität Cottbus-Senftenberg
Code files in this repository are licensed under the
BSD-3-Clause, if not stated otherwise
in the file.
Documentation files in this repository are licensed under CC-BY-4.0, if not stated otherwise in the file.
Supplementary and configuration files in this repository are licensed
under CC0-1.0, if not stated otherwise
in the file.
Please check the header of the individual files for more detailed
information.
### License management
License management is handled with [``reuse``](https://reuse.readthedocs.io/).
f you have any question on this plugin, please contact with [freva@dkrz.de](mailto:freva@dkrz.de)
File added
SPDX-FileCopyrightText: 2025 Brandenburgische Technische Universität Cottbus-Senftenberg
SPDX-License-Identifier: CC0-1.0
######################################################
#
# Calculation of daily Potential Evapotranspiration
# according to: FAO Irrigation and Drainage Paper No. 56 (Crop Evapotranspiration), Allan, Pereira 1998
#
# settings for cdo expressions by Christian Beier, February 2024
# missing/fill value must be set to NaN: cdo setmissval,nan
# no checking for units here
#
######################################################
# R script: 2 min/year
# cdo expr: 34s/year
### DECLARATION OF VARIABLES from combined input file ###
# _... local variable, not in output file
_var_tmax=tasmax;
_var_tmin=tasmin;
e_a=pvap;
_var_wind=sfcWind;
R_s=rsds;
_var_altitude=HSURF;
_var_wind_height=Wind_height;
### NATURAL CONSTANTS ###
c_p=1.013*10^(-3); # specific heat at constant pressure [MJ kg-1 C-1]
epsilon=0.622; # ratio molecular weight of water vapour/dry air
lambda=2.45; # latent heat of vaporization [MJ kg-1]
G_sc=0.0820; # solar constant [MJ m-2 d-1]
sigma=4.903*10^-9; # Stefan-Boltzmann constant [MJ K-4 m-2 d-1]
a=0.23; # albedo reflection coefficient for the hypothetical grass reference crop [-]
pi=3.14159265358979323846; # Pi
### CALCULATIONS ###
# MEAN TEMPERATURE: daily mean temperature [C]
T_mean=(_var_tmax+_var_tmin)/2; #(Eq.9)
# VAPOR PRESSURE DEFICIT [kPa]
pressure=101.3*(((293-0.0065*_var_altitude)/293)^5.26); # atmospheric pressure at altitude z [kPa] (Eq.7) 2dim
gamma=(c_p*pressure/(epsilon*lambda)); # psychrometric constant [kPa C-1] (Eq.8) 3dim? daily values equal
##cdi warning (vlistDefVarTiles): Unexpected time type -1, set to TIME_VARYING!
##where are time und time_bnds in output file from? input file
e_sat=(0.6108*exp(17.27*_var_tmax/(_var_tmax+237.3)) + 0.6108*exp(17.27*_var_tmin/(_var_tmin+237.3)))/2; # mean saturation vapour pressure [kPa] (Eq.11,12)
e_deficit=e_sat-e_a; # vapour pressure deficit
# SLOPE OF SATURATION VAPOUR PRESSURE CURVE [kPa C-1]
delta=(4098*(0.6108*exp(17.27*T_mean/(T_mean+237.3))))/((T_mean+237.3)^2); #(Eq.13)
# WIND SPEED [m s-1]
u2=_var_wind*4.87/ln(67.8*_var_wind_height-5.42); # wind speed 10m -> 2m above ground (Eq.47)
# COMPONENTS OF RADIATION [MJ m-2 d-1]
# net solar (=shortwave) radiation
R_ns=(1-a)*R_s; #(Eq.38)
# extraterrestrial radiation
lat=clat(_var_tmax); # get latitudes as variable
##cdi warning (cdfCheckVarname): Changed double entry of variable name 'lat' to 'lat_2'!
lat_rad=pi/180*(lat); # convert latitude from [] to [rad] (Eq.22)
##cdi warning (vlistDefVarTiles): Unexpected time type -1, set to TIME_VARYING!
#day_of_year=ctimestep(); # timestep number = day of year (for yearly files, not necassary to set with cdo: days since 1.1.) not in file
year=cyear();
month=cmonth();
day=cday();
N1=floor(275 * month / 9);
N2=floor((month + 9) / 12);
N3=(1 + floor((year - 4 * floor(year / 4) + 2) / 3));
day_of_year=N1-(N2 * N3) + day - 30;
### fehler -1 Tag fr 1900,2100 (kein schaltjahr) ###
dist_earth_sun=1+0.033*cos((2*pi/365)*day_of_year); # inverse relative distance Earth-Sun (Eq.23) not in file
solar_dec=0.409*sin((2*pi/365)*day_of_year-1.39); # solar declination [rad], must be -23.45 <= x <= 23.45 (Eq.24) not in file
test_var=(-tan(lat_rad)*tan(solar_dec)); #(Eq.25)
##cdi warning (vlistDefVarTiles): Unexpected time type -1, set to TIME_VARYING!
# calculate sunset_angle only for valid values of cosine function
#sunset_angle_zw=(test_var>=-1 && test_var<=1)*acos(test_var); # acos (Eq.25)
##cdi warning (vlistDefVarTiles): Unexpected time type -1, set to TIME_VARYING!
#sunset_angle=sunset_angle_zw + (test_var<-1 || test_var>1)*missval(_var_tmax); # NA
##cdi warning (vlistDefVarTiles): Unexpected time type -1, set to TIME_VARYING!
#sunset_angle_test=acos(test_var); #(Eq.25)
test_var_na=(test_var<-1 || test_var>1); # 1==not valid areas
##cdi warning (vlistDefVarTiles): Unexpected time type -1, set to TIME_VARYING!
sunset_angle=acos(test_var); #acos(>1)=NA (Eq.25)
##cdi warning (vlistDefVarTiles): Unexpected time type -1, set to TIME_VARYING!
R_a=(24*60)/pi*G_sc*dist_earth_sun*(sunset_angle*sin(lat_rad)*sin(solar_dec)+cos(lat_rad)*cos(solar_dec)*sin(sunset_angle)); # extraterrestrial radiation (Eq.21)
##cdi warning (vlistDefVarTiles): Unexpected time type -1, set to TIME_VARYING!
# clear sky solar radiation [MJ m-2 d-1]
R_so=(0.75+2*10^(-5)*_var_altitude)*R_a; # _var_altitude (HSURF, z_station) (Eq.37)
##cdi warning (vlistDefVarTiles): Unexpected time type -1, set to TIME_VARYING!
# net long wave radiation [MJ m-2 d-1]
T_max_K=_var_tmax+273.15;
T_min_K=_var_tmin+273.15;
test_var2=R_s/R_so; # is limited to be <=1, if greater: will be set to 1 (Eq.39)
#test_var3=(test_var2>1);
#test_var4=test_var3+(test_var2<=1)*test_var2;
test_var3=(test_var2>1)+(test_var2<=1)*test_var2;
R_nl=sigma*((T_max_K^4+T_min_K^4)/2)*(0.34-0.14*sqrt(e_a))*(1.35*test_var3-0.35); #(Eq.39)
# net radiation [MJ m-2 d-1]
R_n=R_ns-R_nl; #(Eq.40)
G=0; # estimated soil heat flux for daily periods [MJ m-2] (Eq.42)
# daily potential evapotranspiration ET0 [mm d-1]
ET0=(0.408*delta*(R_n-G)+gamma*(900/(T_mean+273))*u2*e_deficit)/(delta+gamma*(1+0.34*u2)); #(Eq.6)
# SPDX-FileCopyrightText: 2024 Brandenburgische Technische Universität Cottbus-Senftenberg
#
# SPDX-License-Identifier: EUPL-1.2
"""
PET plugin API wrapper.
"""
######################################################
# import commonly used libraries. You can add/remove
# libraries as needed
######################################################
import os
import json
from pathlib import Path
import subprocess
# from evaluation_system.api.exceptions import PluginError
from typing import List, Optional
from evaluation_system.api import plugin
from evaluation_system.api.parameters import (
Directory,
Integer,
ParameterDictionary,
File,
SolrField,
String,
Bool,
Date
)
from evaluation_system.model.user import User
from evaluation_system.misc import logger
import freva
class PET(plugin.PluginAbstract):
######################################################
# Define the details for the plugin
######################################################
__version__ = (2025, 1, 10)
__short_description__: str = (
"Calculation of daily Potential Evatransporation"
)
__category__: Optional[str] = "postproc"
__tags__: Optional[List[str]] = ["Potential Evatranspiration"]
tool_developer = {
"name": "Christian Beier",
"email": "christian.beier@b-tu.de",
}
__long_description__: Optional[
str
] = "This plugin calculates daily Potential Evapotranspiration (PET) based on the methodology outlined in FAO Irrigation and Drainage Paper No. 56 (Crop Evapotranspiration) by Allen, Pereira et al., 1998.\n\nFor more details, refer to the official publication: https://www.fao.org/4/x0490e/x0490e00.htm"
######################################################
# Define the parameters for the plugin * Mandatory
######################################################
__parameters__ = ParameterDictionary(
SolrField(
name="project",
facet="project",
mandatory=True,
help="Project facet for input data search.",
predefined_facets={
"time_frequency": ["1day"],
"variable": ["tasmax", "tasmin", "sfcWind", "pvap", "rsds", "orog"],
},
),
SolrField(
name="product",
facet="product",
mandatory=True,
help="Product facet for input data search.",
predefined_facets={
"time_frequency": ["1day"],
"variable": ["tasmax", "tasmin", "sfcWind", "pvap", "rsds", "orog"],
}),
SolrField(
name="institute",
facet="institute",
mandatory=True,
help="Institute facet for input data search.",
predefined_facets={
"time_frequency": ["1day"],
"variable": ["tasmax", "tasmin", "sfcWind", "pvap", "rsds", "orog"],
},
),
SolrField(
name="model",
facet="model",
mandatory=True,
help="Model facet for input data search.",
predefined_facets={
"time_frequency": ["1day"],
"variable": ["tasmax", "tasmin", "sfcWind", "pvap", "rsds", "orog"],
},
),
SolrField(
name="experiment",
facet="experiment",
mandatory=True,
help="Experiment facet for input data search.",
predefined_facets={
"time_frequency": ["1day"],
"variable": ["tasmax", "tasmin", "sfcWind", "pvap", "rsds", "orog"],
},
),
SolrField(
name="realm",
facet="realm",
mandatory=True,
help="Realm facet for input data search.",
predefined_facets={
"time_frequency": ["1day"],
"variable": ["tasmax", "tasmin", "sfcWind", "pvap", "rsds", "orog"],
},
),
SolrField(
name="ensemble",
facet="ensemble",
mandatory=True,
help="ensemble facet for input data search.",
predefined_facets={
"time_frequency": ["1day"],
"variable": ["tasmax", "tasmin", "sfcWind", "pvap", "rsds", "orog"],
},
),
Date(
name="start_date",
mandatory=True,
help="Insert start date you want to select (YYYY-MM-DD)"
),
Date(
name="end_date",
mandatory=True,
help="Insert end date you want to select (YYYY-MM-DD)"
),
String(
name="region",
default=None,
help="Region box to be processed. The format have to be W,E,S,N (e.g. -180,180,0,90 for NH).\nLeave empty to select the region from input grid."
),
Directory(
name="output_dir",
default="$USER_OUTPUT_DIR",
help="Directory where output will be stored.",
),
Bool(
name="debug",
default=False,
help="Turn on to get better detailed debug information in case you face any issue."
)
)
def find_files(self, config_dict, variables: List[str], time_frequency: str, time: Optional[str] = None):
'''
Selects data files based on the given parameters using the freva databrowser
Parameters:
config_dict (dict): Dictionary containing values used for searching the database
variables (list): List of variables used to search data files within the database
time_frequency (str): Abbreviation for time frequency the data should cover
time (str): Time period the data should cover
Returns:
file_dict (dict): Dictionary containing list of files for each variable
'''
search_keys = (
"project",
"product",
"institute",
"model",
"experiment",
"realm",
"ensemble"
)
search_args = {key: config_dict[key] for key in search_keys}
search_args["time_frequency"] = time_frequency
search_args["time"] = time
file_dict = {}
for variable in variables:
search_args["variable"] = variable
if variable == "orog":
del search_args["ensemble"] ## orog files are part of another ensemble than the other variables
files = list(freva.databrowser(**search_args))
file_dict[variable] = files
return file_dict
def prepare_html_output(self, path_output):
"""
Prepare the HTML output for the plugin in
the result section.
"""
result = subprocess.run(
["ls", "-la", path_output], capture_output=True, text=True
)
ls_output = result.stdout
current_user = User()
html_content = f"""<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<style>
body {{
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
margin: 0;
padding: 20px;
line-height: 1.6;
background-color: white;
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
}}
.info-text {{
font-size: 16px;
max-width: 800px;
margin: 0 auto 20px auto;
color: #0c5460;
background-color: #d1ecf1;
border: 1px solid #bee5eb;
padding: 20px;
border-radius: 8px;
width: 100%;
box-sizing: border-box;
}}
.terminal {{
background-color: #2d2d2d;
border-radius: 8px;
box-shadow: 0 10px 20px rgba(0,0,0,0.3);
width: 100%;
max-width: 800px;
overflow: hidden;
}}
.terminal-header {{
background-color: #3d3d3d;
padding: 10px;
display: flex;
align-items: center;
}}
.terminal-buttons {{
display: flex;
gap: 8px;
}}
.terminal-button {{
width: 12px;
height: 12px;
border-radius: 50%;
}}
.terminal-button.close {{background-color: #ff5f56;}}
.terminal-button.minimize {{background-color: #ffbd2e;}}
.terminal-button.maximize {{background-color: #27c93f;}}
.terminal-title {{
color: #ababab;
font-size: 14px;
margin-left: 20px;
}}
.terminal-body {{
padding: 20px;
font-family: "Menlo", "Monaco", "Consolas", monospace;
font-size: 14px;
line-height: 1.5;
color: #fff;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}}
.prompt {{
color: #98c379;
margin-bottom: 10px;
word-break: break-all;
}}
.command {{
color: #61afef;
margin-left: 8px;
}}
.output {{
color: #abb2bf;
white-space: pre-wrap;
margin: 10px 0 20px 0;
}}
@media (max-width: 480px) {{
body {{ padding: 10px; }}
.terminal-body {{ padding: 15px; }}
}}
</style>
</head>
<body>
<div class="info-text">
You can directly download the produced data from the link above or login to levante and and proceed with the exploration of the data.
</div>
<div class="terminal">
<div class="terminal-header">
<div class="terminal-buttons">
<div class="terminal-button close"></div>
<div class="terminal-button minimize"></div>
<div class="terminal-button maximize"></div>
</div>
<span class="terminal-title">Terminal</span>
</div>
<div class="terminal-body">
<div class="prompt">
local:~$ <span class="command">ssh {current_user.getName()}@levante.dkrz.de</span>
</div>
<div class="prompt">
{current_user.getName()}@levante.dkrz.de:~$ <span class="command">cd {path_output}</span>
</div>
<div class="prompt">
{current_user.getName()}@levante.dkrz.de:{path_output}$ <span class="command">ls -la {path_output}</span>
</div>
<div class="output">{ls_output}</div>
</div>
</div>
</body>
</html>"""
html_output_path = os.path.join(path_output, "02_view.html")
with open(html_output_path, "w") as f:
f.write(html_content)
def run_tool(self, config_dict=None):
config_dict["files"] = self.find_files(config_dict, ["tasmax", "tasmin", "sfcWind", "pvap", "rsds"], "day", config_dict["start_date"] + " to " + config_dict["end_date"])
config_dict["alti_file"] = self.find_files(config_dict, ["orog"], "fx")["orog"]
if "alti_file" not in config_dict or not config_dict["alti_file"]:
logger.error("Can't find altitude file")
out_dir = self._special_variables.substitute({"d": "$USER_OUTPUT_DIR"})
out_dir = Path(out_dir["d"]) / str(self.rowid)
out_dir.mkdir(exist_ok=True, parents=True)
config_dict["output_dir"] = str(out_dir)
user = User()
scratch = os.getenv("SCRATCH", f"/scratch/{user.getName()[0]}/{user.getName()}")
cache_dir = Path(f"{scratch}/pet/{self.rowid}")
cache_dir.mkdir(exist_ok=True, parents=True)
config_dict["cache_dir"] = str(cache_dir)
json_file = Path(config_dict["cache_dir"]) / "out.json"
error_file = Path(config_dict["cache_dir"]) / "error.log"
with json_file.open("w") as json_f:
json.dump(config_dict, json_f, indent=4)
tool_path = Path(__file__).parent / "src" / "pet" / "calculate_pet.sh"
with error_file.open("w") as error_f:
self.call(
f"{tool_path} {json_file}",
stderr=error_f,
)
self.prepare_html_output(config_dict["output_dir"])
return self.prepare_output(config_dict["output_dir"])
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment