Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: template indicators with jinja #1120

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"scipy>=1.2",
"statsmodels",
"xarray>=0.17",
"Jinja2",
]

dev_requirements = []
Expand Down
8 changes: 7 additions & 1 deletion xclim/core/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@
from inspect import _empty, signature # noqa
from typing import Any, Mapping, Sequence

import numpy as np
import xarray as xr
from boltons.funcutils import wraps
from jinja2 import Environment

from xclim.core.utils import InputKind, PercentileDataArray

Expand All @@ -34,6 +36,8 @@
"pr_per_period": "{unkown}",
}

jinja_env = Environment(autoescape=True)


class AttrFormatter(string.Formatter):
"""A formatter for frequently used attribute values.
Expand Down Expand Up @@ -77,7 +81,9 @@ def format(self, format_string: str, /, *args: Any, **kwargs: dict) -> str:
for k, v in DEFAULT_FORMAT_PARAMS.items():
if k not in kwargs:
kwargs.update({k: v})
return super().format(format_string, *args, **kwargs)
kwargs.update({"np": np}) # noqa
intermediary_res = jinja_env.from_string(format_string, globals=kwargs).render()
return super().format(intermediary_res, *args, **kwargs)

def format_field(self, value, format_spec):
"""Format a value given a formatting spec.
Expand Down
4 changes: 4 additions & 0 deletions xclim/indicators/atmos/_temperature.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,11 @@ class TempWithIndexing(ResamplingIndicatorWithIndexing):
description="{freq} number of heat wave events over a given period. "
"An event occurs when the minimum and maximum daily "
"temperature both exceeds specific thresholds : "
"{% if np.isscalar(thresh_tasmin) and np.isscalar(thresh_tasmax)%}"
"(Tmin > {thresh_tasmin} and Tmax > {thresh_tasmax}) "
"{% else %}"
"(Tmin > per_gridcell_tmin_thresholds and Tmax > per_gridcell_tmax_thresholds) "
"{% endif %}"
"over a minimum number of days ({window}).",
cell_methods="",
keywords="health,",
Expand Down