# (c) 2026 DTU Wind Energy
"""
Wind climate functions.
"""
__all__ = [
"create_met_fields",
"mean_ws_moment",
"ws_cdf",
"ws_freq_gt_mean",
"mean_wind_speed",
"mean_power_density",
"get_cross_predictions",
"extrapolate_to_height",
]
import random
from itertools import product
import numpy as np
import xarray as xr
from windkit.xarray_structures.empty import (
_copy_chunks,
_native_batch,
_native_frame,
_native_store,
)
from windkit.xarray_structures.metadata import (
_MEAN_BARO_ATTRS,
_MEAN_STAB_ATTRS,
_MET_ATTRS,
_WC_STATS_ATTRS,
_update_history,
_update_var_attrs,
)
from windkit.xarray_structures.sector import create_sector_coords
from windkit.spatial import create_dataset, get_crs, is_cuboid, to_point
from windkit.wind_climate import binned_wind_climate as wk_bwc
from windkit.wind_climate import time_series_wind_climate as wk_tswc
from windkit.wind_climate import weibull_wind_climate as wk_wwc
_metvars_3d_nosec = [
"wspd", # same as A
"power_density", # 100 - 600
"air_density", # 1.225, 0.2 stddev
"wspd_emergent", # same as A
"power_density_emergent", # same as power density
"A_combined", # same as A
"k_combined", # same as k
]
_metvars_4d = ["wspd_sector", "power_density_sector"] # same as wspd, power_density
[docs]
def create_met_fields(
output_locs,
n_sectors=12,
not_empty=True,
seed=9876538,
met_fields=["wspd", "power_density"],
**kwargs,
):
"""Create empty dataset filled with met_fields
Parameters
----------
output_locs : xarray.Dataset
Output geospatial information
n_sectors : int
Number of sectors, defaults to 12
met_fields : list of strings, or string
List of variables to include in the output, or a string "all" with
all the variables. Defaults to ["wspd", "power_dens"]
kwargs : dict
Additional arguments.
Returns
-------
ds : xarray.Dataset
empty met fields dataset
Notes
-----
Data variables are stored float32, C-contiguous, with ``sector`` (for the
variables that carry one) trailing the spatial batch dimensions — the
reverse of the compiled core's declared order — so PyWAsP's compiled
boundary can take a Fortran-ordered view instead of converting a copy
(windkit#807). Neither the dtype nor the dimension order is a supported
API contract: ``create_met_fields`` is a test-data utility.
"""
dims, shape = _native_batch(output_locs)
n_pt = int(np.prod(shape, dtype=int))
random_param_dict = {
"wspd": (5, 10),
"power_density": (100, 600),
"air_density": ("gaussian", 1.225, 0.2),
"wspd_emergent": (5, 10),
"power_density_emergent": (100, 600),
"A_combined": (5, 10),
"k_combined": (5, 10),
"wspd_sector": (5, 10),
"power_density_sector": (100, 600),
}
if met_fields == "all":
met_fields = _metvars_4d + _metvars_3d_nosec
ds = _native_frame(output_locs)
if any(var in _metvars_4d for var in met_fields):
ds = ds.assign_coords(create_sector_coords(n_sectors).coords)
rng = np.random.default_rng(seed) if not_empty else None
for var in met_fields:
if var in _metvars_4d:
core_dims, raw_shape = ("sector",), [n_sectors, n_pt]
elif var in _metvars_3d_nosec:
core_dims, raw_shape = (), [n_pt]
else:
raise ValueError(f"Unknown met_field {var}, cannot add to result")
if rng is None:
values = np.full(raw_shape, np.nan)
else:
rand_param = random_param_dict[var]
if len(rand_param) == 2:
values = rng.uniform(*rand_param, raw_shape)
else:
values = rng.normal(*rand_param[1:], raw_shape)
out_dims, array = _native_store(values, dims, shape, core_dims=core_dims)
ds[var] = xr.DataArray(
array, dims=out_dims, attrs={"height_dim_policy": "optional"}
)
ds = _update_var_attrs(_copy_chunks(output_locs, ds), _MET_ATTRS)
return _update_history(ds)
def _create_baro(output_locs, n_sectors=12, not_empty=True, seed=9876538, **kwargs):
"""Create empty baro.
If not_empty=True,the data variables are filled with meaninful random numbers
Parameters
----------
output_locs : xarray.Dataset
Output geospatial information, it should be a cuboid.
n_sectors : int
Number of sectors, defaults to 12.
not_empty : bool
If true, the empty dataset is filled with random
meaningful data. Defaults to True.
seed : int
Seed for the random data, defaults to 9876538.
kwargs : dict
Additional arguments.
Returns
-------
ds : xarray.Dataset
baro dataset either empty or filled with random numbers.
Notes
-----
``mean_dgdz_dir`` and ``mean_dgdz`` are stored float32, C-contiguous, with
``sector`` trailing the spatial batch dimensions — the reverse of the
compiled core's declared order — so PyWAsP's compiled boundary can take a
Fortran-ordered view instead of converting a copy (windkit#807). Neither
the dtype nor the dimension order is a supported API contract:
``_create_baro`` is a test-data utility.
"""
dims, shape = _native_batch(output_locs)
n_pt = int(np.prod(shape, dtype=int))
if not_empty:
rng = np.random.default_rng(seed)
mean_dgdz_dir = rng.uniform(-180.0, 180.0, [n_sectors, n_pt])
mean_dgdz = rng.uniform(0.0, 0.015, [n_sectors, n_pt])
else:
mean_dgdz_dir = mean_dgdz = np.full((n_sectors, n_pt), np.nan)
ds = _native_frame(output_locs).assign_coords(
create_sector_coords(n_sectors).coords
)
for name, values in (("mean_dgdz_dir", mean_dgdz_dir), ("mean_dgdz", mean_dgdz)):
out_dims, array = _native_store(values, dims, shape, core_dims=("sector",))
ds[name] = xr.DataArray(
array, dims=out_dims, attrs={"height_dim_policy": "optional"}
)
ds = _update_var_attrs(_copy_chunks(output_locs, ds), _MEAN_BARO_ATTRS)
return _update_history(ds)
def _create_stab(output_locs, n_sectors=12, not_empty=True, seed=9876538, **kwargs):
"""Create empty stab.
If not_empty=True,the data variables are filled with meaninful random numbers
Parameters
----------
output_locs : xarray.Dataset
Output geospatial information, it should be a cuboid with 1 height
n_sectors : int
Number of sectors, defaults to 12.
not_empty : bool
If true, the empty dataset is filled with random
meaningful data. Defaults to True.
seed : int
Seed for the random data, defaults to 9876538.
kwargs : dict
Additional arguments.
Returns
-------
ds : xarray.Dataset
stab dataset either empty or filled with random numbers.
Notes
-----
The six temperature- and PBLH-scale variables are stored float32,
C-contiguous, with ``sector`` trailing the spatial batch dimensions — the
reverse of the compiled core's declared order — so PyWAsP's compiled
boundary can take a Fortran-ordered view instead of converting a copy
(windkit#807). Neither the dtype nor the dimension order is a supported
API contract: ``_create_stab`` is a test-data utility.
"""
if not is_cuboid(output_locs):
raise ValueError("output_locs must be a cuboid")
dims, shape = _native_batch(output_locs)
n_pt = int(np.prod(shape, dtype=int))
if not_empty:
rng = np.random.default_rng(seed)
values_by_name = {
"mean_temp_scale_land": rng.uniform(-0.9, 0.22, [n_sectors, n_pt]),
"rms_temp_scale_land": rng.uniform(0.0, 0.45, [n_sectors, n_pt]),
"mean_pblh_scale_land": rng.uniform(15.0, 9707.0, [n_sectors, n_pt]),
"mean_temp_scale_sea": rng.uniform(-0.19, 0.19, [n_sectors, n_pt]),
"rms_temp_scale_sea": rng.uniform(0.0, 0.12, [n_sectors, n_pt]),
"mean_pblh_scale_sea": rng.uniform(67, 1000, [n_sectors, n_pt]),
}
else:
nan = np.full((n_sectors, n_pt), np.nan)
values_by_name = {
name: nan
for name in (
"mean_temp_scale_land",
"rms_temp_scale_land",
"mean_pblh_scale_land",
"mean_temp_scale_sea",
"rms_temp_scale_sea",
"mean_pblh_scale_sea",
)
}
ds = _native_frame(output_locs).assign_coords(
create_sector_coords(n_sectors).coords
)
for name, values in values_by_name.items():
out_dims, array = _native_store(values, dims, shape, core_dims=("sector",))
ds[name] = xr.DataArray(
array, dims=out_dims, attrs={"height_dim_policy": "optional"}
)
ds = _update_var_attrs(_copy_chunks(output_locs, ds), _MEAN_STAB_ATTRS)
return _update_history(ds)
def _has_binned_freqs(ds):
"""Dataset has binned wind speed frequencies (wsfreq + wdfreq + wsbin + sector)."""
return (
isinstance(ds, xr.Dataset)
and {"wsfreq", "wdfreq"} <= set(ds.data_vars)
and {"wsbin", "sector"} <= set(ds.dims)
)
def _has_geo_binned_freqs(ds):
"""Dataset has geostrophic binned frequency data (geo_wv_freq + wsbin + sector)."""
return (
isinstance(ds, xr.Dataset)
and "geo_wv_freq" in ds.data_vars
and {"wsbin", "sector"} <= set(ds.dims)
)
def _has_weibull_params(ds):
"""Dataset has Weibull parameters (A + k + wdfreq + sector)."""
return (
isinstance(ds, xr.Dataset)
and {"A", "k", "wdfreq"} <= set(ds.data_vars)
and "sector" in ds.dims
)
def _has_timeseries(ds):
"""Dataset has time series wind data (wind_speed + time)."""
return (
isinstance(ds, xr.Dataset)
and "wind_speed" in ds.data_vars
and "time" in ds.dims
)
def _normalize_geowc(ds):
"""Convert GEOWC geo_wv_freq to BWC-compatible wsfreq/wdfreq format."""
return wk_bwc._bwc_from_counts(ds["geo_wv_freq"].rename("wv_count"))
# (name, check_fn, normalizer_or_None)
# Ordered most-specific first — first match wins
_CAPABILITIES = [
("binned", _has_binned_freqs, None),
("geo_binned", _has_geo_binned_freqs, _normalize_geowc),
("weibull", _has_weibull_params, None),
("timeseries", _has_timeseries, None),
]
def _dispatch(dispatch_table, wc_obj, *, bysector, n_sectors, **kwargs):
"""Dispatch to the correct handler based on dataset capabilities.
``n_sectors`` only reaches the time series handler with ``bysector=True``,
the one case that bins wind directions into sectors.
"""
for cap_name, check, normalizer in _CAPABILITIES:
if cap_name in dispatch_table and check(wc_obj):
if normalizer is not None:
wc_obj = normalizer(wc_obj)
if n_sectors is not None:
if not (cap_name == "timeseries" and bysector):
raise ValueError(
"n_sectors is only used for a time series wind climate "
"with bysector=True."
)
is_int = isinstance(n_sectors, (int, np.integer))
if isinstance(n_sectors, bool) or not is_int or n_sectors < 1:
raise ValueError(
f"n_sectors must be a positive integer, got {n_sectors!r}."
)
kwargs["n_sectors"] = n_sectors
return dispatch_table[cap_name](wc_obj, bysector=bysector, **kwargs)
raise ValueError(
"Dataset does not match any known wind climate capability. "
"Expected one of: binned (wsfreq, wdfreq, wsbin, sector), "
"weibull (A, k, wdfreq, sector), or timeseries (wind_speed, time)."
)
def _bwc_ws_cdf(bwc, *, bysector=False, ws_bins=None):
"""CDF of a binned wind climate, whose histogram fixes the wind speed bins."""
if ws_bins is not None:
raise ValueError(
"ws_bins cannot be used with a binned wind climate: its histogram "
"fixes the wind speed bins."
)
return wk_bwc._ws_cdf(bwc, bysector=bysector)
def _named_stat(result, name):
"""Name a statistic and give it exactly its registry attributes.
Attributes inherited from the input by xarray arithmetic are dropped.
"""
# rename shares the variable, so copy first to leave the input untouched
result = result.copy(deep=False).rename(name)
result.attrs = {}
return _update_var_attrs(result, _WC_STATS_ATTRS)
def _moment_units(moment):
"""CF units of the ``moment``-th power of a wind speed, e.g. ``m3 s-3``."""
if moment == 0:
return "1"
if moment == 1:
return "m s-1"
return f"m{moment:g} s{-moment:g}"
_MEAN_WIND_SPEED = {
"binned": wk_bwc._mean_wind_speed,
"geo_binned": wk_bwc._mean_wind_speed,
"weibull": wk_wwc._mean_wind_speed,
"timeseries": wk_tswc._mean_wind_speed,
}
_MEAN_WS_MOMENT = {
"binned": wk_bwc._mean_ws_moment,
"geo_binned": wk_bwc._mean_ws_moment,
"weibull": wk_wwc._mean_ws_moment,
"timeseries": wk_tswc._mean_ws_moment,
}
_MEAN_POWER_DENSITY = {
"binned": wk_bwc._mean_power_density,
"geo_binned": wk_bwc._mean_power_density,
"weibull": wk_wwc._mean_power_density,
"timeseries": wk_tswc._mean_power_density,
}
_WS_CDF = {
"binned": _bwc_ws_cdf,
"geo_binned": _bwc_ws_cdf,
"weibull": wk_wwc._ws_cdf,
"timeseries": wk_tswc._ws_cdf,
}
_WS_FREQ_GT_MEAN = {
"binned": wk_bwc._ws_freq_gt_mean,
"geo_binned": wk_bwc._ws_freq_gt_mean,
"weibull": wk_wwc._ws_freq_gt_mean,
"timeseries": wk_tswc._ws_freq_gt_mean,
}
[docs]
def mean_ws_moment(wc_obj, moment=1, *, bysector=False, n_sectors=None):
"""Calculate the mean wind speed moment from a wind climate.
Parameters
----------
wc_obj: xarray.Dataset
Binned, Weibull or time series wind climate.
moment: float
Moment to calculate, defaults to 1.
bysector: bool
Calculate the moment by sector, defaults to False. A time series
wind climate is binned into sectors with
:func:`windkit.wd_to_sector`, skipping samples without a direction.
n_sectors: int, optional
Number of sectors to bin a time series wind climate into when
``bysector`` is True. Defaults to 12.
Returns
-------
xarray.DataArray
``wind_speed_moment``, the mean of the wind speed raised to
``moment``, which is also stored as an attribute. Missing samples of a
time series are skipped, and a sector without samples gives NaN.
Raises
------
ValueError
If ``wc_obj`` is not a known wind climate, ``moment`` is not a
scalar, or ``n_sectors`` is given for anything but a time series wind
climate with ``bysector=True`` or is not a positive integer.
"""
if np.ndim(moment) != 0:
raise ValueError("moment must be a scalar.")
result = _dispatch(
_MEAN_WS_MOMENT, wc_obj, bysector=bysector, n_sectors=n_sectors, moment=moment
)
result = _named_stat(result, "wind_speed_moment")
result.attrs.update(moment=moment, units=_moment_units(moment))
return _update_history(result)
[docs]
def ws_cdf(wc_obj, *, bysector=False, ws_bins=None, n_sectors=None):
"""Calculate the wind speed cumulative distribution function from a wind climate.
Parameters
----------
wc_obj: xarray.Dataset
Binned, Weibull or time series wind climate.
bysector: bool
Calculate the CDF by sector, defaults to False. For a Weibull wind
climate the all-sector CDF is the ``wdfreq``-weighted sum of the
sectorwise CDFs. A time series wind climate is binned into sectors
with :func:`windkit.wd_to_sector`, skipping samples without a
direction.
ws_bins: int or array_like, optional
Wind speed bins to evaluate the CDF of a Weibull or time series wind
climate on, as accepted by :func:`windkit.create_wsbin_coords`.
Defaults to its default bins. A binned wind climate uses its own bins.
n_sectors: int, optional
Number of sectors to bin a time series wind climate into when
``bysector`` is True. Defaults to 12.
Returns
-------
xarray.DataArray
``wind_speed_cdf``, the CDF at the ``wsceil`` of each ``wsbin``. For
a Weibull or time series wind climate this is the exact CDF: the
frequency below the ceiling, which stays below 1 if some wind speeds
exceed the last ceiling. A binned wind climate holds only the
frequencies within its bins, so its CDF reaches 1 at the last ceiling.
A time series counts the samples strictly below each ceiling, so a
speed on a ceiling counts in the bin above, as in
:func:`windkit.bwc_from_tswc`, except that its last bin also holds
speeds equal to the last ceiling.
Raises
------
ValueError
If ``wc_obj`` is not a known wind climate, ``ws_bins`` is given for a
binned wind climate, or ``n_sectors`` is given for anything but a
time series wind climate with ``bysector=True`` or is not a positive
integer.
"""
result = _dispatch(
_WS_CDF, wc_obj, bysector=bysector, n_sectors=n_sectors, ws_bins=ws_bins
)
return _update_history(_named_stat(result, "wind_speed_cdf"))
[docs]
def ws_freq_gt_mean(wc_obj, *, bysector=False, n_sectors=None):
"""Calculate the wind speed frequency greater than the mean from a wind climate.
Parameters
----------
wc_obj: xarray.Dataset
Binned, Weibull or time series wind climate.
bysector: bool
Calculate the frequency by sector, relative to the mean of each
sector, defaults to False. For a Weibull wind climate the all-sector
value is the frequency of the ``wdfreq``-weighted sum of the
sectorwise distributions above its mean. A time series wind climate
is binned into sectors with :func:`windkit.wd_to_sector`, skipping
samples without a direction.
n_sectors: int, optional
Number of sectors to bin a time series wind climate into when
``bysector`` is True. Defaults to 12.
Returns
-------
xarray.DataArray
``wind_speed_fgtm``, the frequency of wind speeds greater than the
mean wind speed. Missing samples of a time series are skipped, and a
sector without samples gives NaN.
Raises
------
ValueError
If ``wc_obj`` is not a known wind climate, or ``n_sectors`` is given
for anything but a time series wind climate with ``bysector=True``
or is not a positive integer.
"""
result = _dispatch(_WS_FREQ_GT_MEAN, wc_obj, bysector=bysector, n_sectors=n_sectors)
return _update_history(_named_stat(result, "wind_speed_fgtm"))
[docs]
def mean_wind_speed(wc_obj, *, bysector=False, n_sectors=None):
"""Calculate the mean wind speed from a wind climate.
Parameters
----------
wc_obj: xarray.Dataset
Binned, Weibull or time series wind climate.
bysector: bool
Calculate the mean by sector, defaults to False. A time series wind
climate is binned into sectors with :func:`windkit.wd_to_sector`,
skipping samples without a direction.
n_sectors: int, optional
Number of sectors to bin a time series wind climate into when
``bysector`` is True. Defaults to 12.
Returns
-------
xarray.DataArray
``mean_wind_speed``. Missing samples of a time series are skipped,
and a sector without samples gives NaN.
Raises
------
ValueError
If ``wc_obj`` is not a known wind climate, or ``n_sectors`` is given
for anything but a time series wind climate with ``bysector=True``
or is not a positive integer.
"""
result = _dispatch(_MEAN_WIND_SPEED, wc_obj, bysector=bysector, n_sectors=n_sectors)
return _update_history(_named_stat(result, "mean_wind_speed"))
[docs]
def mean_power_density(wc_obj, *, bysector=False, air_density=1.225, n_sectors=None):
"""Calculate the power density of wind climate object
Parameters
----------
wc_obj: xarray.Dataset
Binned, Weibull or time series wind climate.
bysector: bool
Calculate the power density by sector, defaults to False. A time
series wind climate is binned into sectors with
:func:`windkit.wd_to_sector`, skipping samples without a direction.
air_density: float or xarray.DataArray
Air density, defaults to 1.225.
n_sectors: int, optional
Number of sectors to bin a time series wind climate into when
``bysector`` is True. Defaults to 12.
Returns
-------
xarray.DataArray
``mean_power_density``. Missing samples of a time series are skipped,
and a sector without samples gives NaN.
Raises
------
ValueError
If ``wc_obj`` is not a known wind climate, or ``n_sectors`` is given
for anything but a time series wind climate with ``bysector=True``
or is not a positive integer.
"""
result = _dispatch(
_MEAN_POWER_DENSITY,
wc_obj,
bysector=bysector,
n_sectors=n_sectors,
air_density=air_density,
)
return _update_history(_named_stat(result, "mean_power_density"))
def _not_equal(points):
"""Return if not a self-prediction"""
for x, y in points:
if x != y:
yield (x, y)
def _higher(points):
"""Return if the target observation higher or equal than the source"""
for x, y in points:
if y[2] >= x[2]:
yield (x, y)
def _in_range(points, filter_range):
"""Return if the observation is within the chosen range"""
for x, y in points:
bottom, top = filter_range
if x[2] >= bottom and x[2] < top and y[2] >= bottom and y[2] < top:
yield (x, y)
[docs]
def get_cross_predictions(
wcs,
wcs_src=None,
include_self_predictions=True,
only_upward_extrapolations=True,
filter_range=None,
sample_size=None,
seed=4,
):
"""Get cross predictions from a dataset
Given the filtering options, return a dataset with the points
where we want to predict from and where we want to predict to.
Parameters
----------
wcs: :py:class:`xarray.Dataset`
wind climate `xarray.Dataset` for which we want to do cross predictions
wcs_src: :py:class:`xarray.Dataset`
wind climate :py:class:`xarray.Dataset` used as source for the cross predictions.
If None, 'wcs' is used as source and as target. Defaults to None.
include_self_predictions: bool
A self prediction is a pair of points where the input point is
the exact same as the output point. Keep self predictions in the dataset?
only_upward_extrapolations: bool
Keep only the cross predictions where
the height of point_in >= the height of point_out?
filter_range: list
height range that we want to retain from the input dataset
sample_size: int
Number of samples to take from the input dataset
seed: int
Seed number for the random sampling, if applied
Returns
-------
from_locs: :py:class:`xr.Dataset`
xarray dataset with input locations
to_locs: :py:class:`xr.Dataset`
xarray dataset with target locations
"""
def point_to_multiindex(ds):
"""Convert to windkit 'point' structure
Parameters
----------
ds: :any:`xr.Dataset`
xarray dataset with windkit 'point' structure
Returns
-------
points: :any:`xr.Dataset`
xarray dataset with multiindex point coordinate
"""
pp = to_point(ds)
return pp.set_index(point=["west_east", "south_north", "height"])
def reindex_points(ds, locs):
"""Reindex ds by using point indices from locs
Returns the dataset 'ds' but on the points in 'locs'.
Parameters
----------
ds: :any:`xr.Dataset`
xarray dataset with windkit 'point' structure
locs: :any:`xr.Dataset`
xarray dataset with the desired windkit 'point' structure
Returns
-------
points: :any:`xr.Dataset`
xarray dataset with the variables from 'ds' but at points from 'locs'
"""
points = ds.sel(
point=locs.set_index(point=["west_east", "south_north", "height"])["point"]
)
return points.reset_index("point")
point_bwc = point_to_multiindex(wcs)
index = point_bwc.point.values
points = ((i[0], i[1]) for i in product(index, index))
if not include_self_predictions:
points = _not_equal(points)
if only_upward_extrapolations:
points = _higher(points)
if filter_range is not None:
points = _in_range(points, filter_range)
# if lp is an empty list we have filtered out all measurements
# so we return None
lp = list(points)
if lp:
if sample_size is not None:
# take sample_size from the points, if the number of samples exceeds
# the length of the list, take all points
random.seed(seed)
point_from, point_to = zip(*random.sample(lp, min(sample_size, len(lp))))
else:
point_from, point_to = zip(*lp)
dataset_from = create_dataset(
np.array(point_from).T[0],
np.array(point_from).T[1],
np.array(point_from).T[2],
crs=get_crs(point_bwc),
)
dataset_to = create_dataset(
np.array(point_to).T[0],
np.array(point_to).T[1],
np.array(point_to).T[2],
crs=get_crs(point_bwc),
)
to_locs = reindex_points(point_bwc, dataset_to)
if wcs_src is None:
from_locs = reindex_points(point_bwc, dataset_from)
else:
point_wcs_src = point_to_multiindex(wcs_src)
from_locs = reindex_points(point_wcs_src, dataset_from)
return (from_locs, to_locs)
else:
return (None, None)