# (c) 2026 DTU Wind Energy
"""
Wind Turbine classs defines the parameters of a certain type of wind turbine.
"""
__all__ = [
"validate_wtg",
"is_wtg",
"RegulationType",
"estimate_regulation_type",
"read_wtg",
"wtg_power",
"wtg_cp",
"wtg_ct",
]
from enum import Enum
from pathlib import Path
import numpy as np
import xarray as xr
from windkit.xarray_structures._schema import (
DataVar,
DatasetSchema,
make_is_valid,
make_validator,
)
from windkit.xarray_structures.metadata import _ALL_VARS_META, _update_var_attrs
from windkit.wind_farm.power_curve import _unify_power_curves
from windkit.utils import _infer_file_format
SUPPORTED_WTG_FILE_FORMATS_READ = ["nc", "wtg", "yml", "yaml"]
SUPPORTED_WTG_FILE_FORMATS_WRITE = []
[docs]
class RegulationType(Enum):
UNDEFINED = 0
STALL = 1
PITCH = 2
_WTG_SCHEMA = DatasetSchema(
name="wtg",
data_vars={
"power_output": DataVar(dims=("mode", "wind_speed")),
"thrust_coefficient": DataVar(dims=("mode", "wind_speed")),
"air_density": DataVar(dims=("mode",)),
"stationary_thrust_coefficient": DataVar(dims=("mode",)),
"wind_speed_cutin": DataVar(dims=("mode",)),
"wind_speed_cutout": DataVar(dims=("mode",)),
"rated_power": DataVar(dims=("mode",)),
"name": DataVar(),
"rotor_diameter": DataVar(),
"hub_height": DataVar(),
"regulation_type": DataVar(),
},
dims=("mode", "wind_speed"),
coords=("wind_speed", "mode"),
)
validate_wtg = make_validator(_WTG_SCHEMA)
is_wtg = make_is_valid(_WTG_SCHEMA)
[docs]
def estimate_regulation_type(wtg: xr.Dataset):
"""Estimate the regulation type of a WTG
Use the power_output array, to see how many points equal the max power output. This
does a good job detecting manufacturers power curves, but doesn't detect pitch
regulation from power curves derived from measurements.
Parameters
----------
wtg : xr.Dataset
Wind Turbine Generator object
Returns
-------
RegulationType
Estimated regulation type object
"""
if (wtg.power_output == wtg.power_output.max()).sum() >= 3:
return RegulationType.PITCH
else:
return RegulationType.STALL
def _stationary_thrust_coefficient(mode_dict, context):
"""Thrust coefficient of a parked turbine, for wind speeds it cannot run at.
When the file does not state one, the smallest non-zero value of the mode's
own thrust curve stands in -- the same fallback :func:`wtg_ct` applies to a
Dataset that lacks the variable. A parked rotor still has drag, so a zero
row in the curve must not be mistaken for one.
The caller must record whatever this returns on the Dataset, so that
``wtg_ct`` fills with the same value the curves were interpolated with.
Parameters
----------
mode_dict : dict
One entry of the ``"modes"`` list returned by
:func:`windkit.io.wasp.read_wtg`.
context : str
Identifier used in error messages.
Raises
------
ValueError
If the mode states no ``StationaryThrustCoEfficient`` and its thrust
curve is all zeros, leaving no value to derive.
"""
stat_ct = mode_dict["stationary_thrust_coefficient"]
if stat_ct is not None:
return stat_ct
thrust_coeff = mode_dict["thrust_coefficient"]
nonzero = thrust_coeff[thrust_coeff != 0]
if nonzero.size == 0:
raise ValueError(
f"{context}: cannot derive a stationary thrust coefficient: the "
"table states no StationaryThrustCoEfficient and its thrust curve "
"is all zeros"
)
return nonzero.min()
def _mode_dict_to_dataset(mode_dict, stat_ct, wind_speed=None):
"""Build the power and ct curves of a single turbine mode.
Parameters
----------
mode_dict : dict
One entry of the ``"modes"`` list returned by
:func:`windkit.io.wasp.read_wtg`.
stat_ct : float
Thrust coefficient to use outside the mode's wind speed range, from
:func:`_stationary_thrust_coefficient`.
wind_speed : ndarray, optional
Wind speeds to interpolate the curves onto. When None, the mode's own
wind speeds are used unchanged.
Returns
-------
xr.Dataset
power and ct curves formatted as xarray.Dataset for a
specific turbine mode
"""
wind_speed_ = mode_dict["wind_speed"]
power_output = mode_dict["power_output"]
thrust_coeff = mode_dict["thrust_coefficient"]
# interpolate to specific wind speed values, if provided.
if wind_speed is not None:
power_output = np.interp(
wind_speed, wind_speed_, power_output, left=0.0, right=0.0
)
thrust_coeff = np.interp(
wind_speed,
wind_speed_,
thrust_coeff,
left=stat_ct,
right=stat_ct,
)
else:
wind_speed = wind_speed_
return xr.Dataset(
{
"power_output": (("wind_speed",), power_output),
"thrust_coefficient": (("wind_speed",), thrust_coeff),
},
coords={"wind_speed": (("wind_speed",), wind_speed)},
)
def _combine_wind_speed_arrays(wind_speed_arrays, delta=0.00001):
"""Combine wind speed arrays from multiple WTG modes into a single array
The steps are:
1. Find all wind speed start and end points (ws minimums and maximums)
2. Make a combined wind speed array with all unique values, sorted
3. If we have different wind speed start and end points, we insert
all the end points smaller than the greatest one + a very small number
and all the start points greater than the smallest one - a very small number.
This is to ensure any interpolation near the start and end points
will have correct behavior for the tables with missing values.
For example, if one table ends at 25 m/s, but the max is at 30 m/s,
any power output interpolation at 25.1 m/s should result in the
value 0.0, not a value between P_rated and 0.0...
Parameters
----------
wind_speed_arrays : list
List of arrays to combine
delta : float
Size of small number added to inserted wind speed ends
and subtracted from inserted wind speed starts
Returns
-------
numpy.array : 1D array of floats, containing the combined wind speed values.
"""
# check if all max wind speeds are the same
if not all(
np.max(wind_speed_arrays[0]) == np.max(wind_speed_arrays[i])
for i in range(len(wind_speed_arrays))
):
ws_maxs = [np.max(wind_speed_arrays[i]) for i in range(len(wind_speed_arrays))]
else:
ws_maxs = None
# check if all min winds speeds are the same
if not all(
np.min(wind_speed_arrays[0]) == np.min(wind_speed_arrays[i])
for i in range(len(wind_speed_arrays))
):
ws_mins = [np.min(wind_speed_arrays[i]) for i in range(len(wind_speed_arrays))]
else:
ws_mins = None
# Now we get all the unique values from all the individual arrays
wind_speed = np.sort(np.unique(np.concatenate(wind_speed_arrays)))
# add any maxes mins to wind speed array by adding small max/min +/- small value
if ws_maxs is not None:
for ws_max in ws_maxs:
if ws_max + delta not in wind_speed and ws_max < wind_speed.max():
wind_speed = np.append(wind_speed, ws_max + delta)
if ws_mins is not None:
for ws_min in ws_mins:
if ws_min - delta not in wind_speed and ws_min > wind_speed.min():
wind_speed = np.append(wind_speed, ws_min - delta)
wind_speed = np.sort(wind_speed)
return wind_speed
def _wtg_dict_to_dataset(wtg_dict, context):
"""Convert the dict parsed from a WAsP .wtg file to a WindKit wtg Dataset.
Every mode is interpolated onto a shared ``wind_speed`` coordinate, and the
quantities the file only implies -- rated power, hub height, regulation
type -- are derived here.
Parameters
----------
wtg_dict : dict
As returned by :func:`windkit.io.wasp.read_wtg` or
:func:`windkit.io.wasp.parse_wtg_element`.
context : str
Identifier used in error messages, typically the source file path.
Returns
-------
xr.Dataset
Wind Turbine Generator dataset as an xarray.Dataset
Raises
------
ValueError
If a performance table states no ``StationaryThrustCoEfficient`` and its
thrust curve is all zeros, leaving no stationary thrust coefficient to
derive; or if the ``FormatVersion`` is 1.02 or later and the
``ControlSystem`` is absent or unrecognised.
"""
datasets = []
modes = wtg_dict["modes"]
wind_speed_arrays = [mode["wind_speed"] for mode in modes]
# check if all wind_speed arrays are the same:
if all(
np.array_equal(wind_speed_arrays[0], wind_speed_arrays[i])
for i in range(len(wind_speed_arrays))
):
wind_speed = None
else:
wind_speed = _combine_wind_speed_arrays(wind_speed_arrays)
for mode, mode_dict in enumerate(modes):
# Bracketed-index convention, see windkit.io.wasp.wtg. Here that index
# is also the mode coordinate: PerformanceTable[1] is ds.sel(mode=1).
stat_ct = _stationary_thrust_coefficient(
mode_dict, f"{context}: PerformanceTable[{mode}]"
)
ds = _mode_dict_to_dataset(mode_dict, stat_ct, wind_speed=wind_speed)
ds = ds.assign_coords(mode=(("mode",), [mode]))
ds["air_density"] = mode_dict["air_density"]
# Always recorded, including when derived, so that wtg_ct() fills with
# the same value the thrust curve was interpolated with.
ds["stationary_thrust_coefficient"] = stat_ct
ds["wind_speed_cutin"] = mode_dict["wind_speed_cutin"]
ds["wind_speed_cutout"] = mode_dict["wind_speed_cutout"]
ds["rated_power"] = ds["power_output"].max()
datasets.append(ds)
merged = xr.concat(
datasets, dim="mode", data_vars="all", compat="equals", join="outer"
)
merged["name"] = wtg_dict["name"]
if wtg_dict["manufacturer"] is not None:
merged["manufacturer"] = wtg_dict["manufacturer"]
merged["rotor_diameter"] = wtg_dict["rotor_diameter"]
suggested_heights = wtg_dict["suggested_heights"]
# First suggested height is the primary hub height per WAsP convention
merged["hub_height"] = suggested_heights[0]
merged["suggested_heights"] = (
("suggested_height",),
suggested_heights,
)
# ControlSystem is only written from FormatVersion 1.02 onwards; older
# files leave the regulation type for read_wtg to fill in.
if wtg_dict["format_version"] >= "1.02":
merged["regulation_type"] = _regulation_type(wtg_dict, context).value
else:
merged["regulation_type"] = RegulationType.UNDEFINED.value
return merged
def _regulation_type(wtg_dict, context):
"""Map a .wtg ``ControlSystem`` attribute onto a :class:`RegulationType`.
``ControlSystem="Undefined"`` is valid and yields
:attr:`RegulationType.UNDEFINED`, which :func:`read_wtg` then resolves from
its ``regulation_type`` argument.
Parameters
----------
wtg_dict : dict
As returned by :func:`windkit.io.wasp.read_wtg`.
context : str
Identifier used in error messages, typically the source file path.
Returns
-------
RegulationType
The enum member for the file's ``ControlSystem``.
:attr:`RegulationType.UNDEFINED` when the file states
``ControlSystem="Undefined"``, deferring the choice to
:func:`read_wtg`'s ``regulation_type`` argument. An *absent*
``ControlSystem`` raises rather than returning ``UNDEFINED``.
Raises
------
ValueError
If ``ControlSystem`` is absent or is not one of ``Pitch``, ``Stall`` or
``Undefined``.
"""
control_system = wtg_dict["control_system"]
if control_system is None:
raise ValueError(
f"{context}: FormatVersion {wtg_dict['format_version']} requires a "
"ControlSystem attribute, but the WTG has none"
)
try:
return RegulationType[control_system.upper()]
except KeyError:
raise ValueError(
f"{context}: unknown ControlSystem {control_system!r}, expected "
"'Pitch', 'Stall', or 'Undefined' to defer to read_wtg's "
"regulation_type argument"
) from None
def _read_wasp_wtg(wtg_file):
"""Read a wasp-formatted XML ".wtg" file.
Parameters
----------
wtg_file : string, pathlib.Path
A string or pathlib.Path denoting the location of the .wtg file
Returns
-------
xr.Dataset
Wind Turbine Generator dataset as an xarray.Dataset
"""
from windkit.io.wasp import wtg as _wasp_wtg
return _wtg_dict_to_dataset(_wasp_wtg.read_wtg(wtg_file), context=str(wtg_file))
def _read_windio_wtg(wtg_file, air_density=1.225, **kwargs):
"""Read a windIO turbine YAML file into a WTG dataset.
Parameters
----------
wtg_file : str or pathlib.Path
Path to windIO turbine YAML file.
air_density : float
Air density for power calculations (default: 1.225 kg/m³).
**kwargs
Additional keyword arguments (unused, for API consistency).
Returns
-------
xarray.Dataset
WTG dataset.
"""
import yaml
from windkit.io.windio.translate import wtg_from_windio_turbine
with open(wtg_file) as f:
turbine_data = yaml.safe_load(f)
return wtg_from_windio_turbine(turbine_data, air_density=air_density)
[docs]
def read_wtg(wtg_file, file_format="infer", regulation_type="pitch", **kwargs):
"""Read in Wind Turbine Generator (WTG) data from a file.
A WTG dataset contains the following:
coordinates(dim):
wind_speed(wind_speed) : wind speed
mode(mode) : each mode reprents different ct/power curves
variables(dims):
name : name of the WTG
manufacturer : manufacturer name (optional, WAsP .wtg only)
rotor_diameter : rotor diameter in meters
hub_height : hub height a.g.l. in meters (first suggested height)
suggested_heights(suggested_height) : all suggested hub heights from the WTG file
regulation_type : Regulation type (1: stall, 2: pitch)
air_density(mode) : Air density power curve table
wind_speed_cutin(mode) : Wind speed cutin
wind_speed_cutout(mode) : Wind speed cutout
rated_power(mode) : Rated power
power_output(mode, wind_speed) : Power output
thrust_coefficient(mode, wind_speed) : Thrust coefficient
Parameters
----------
wtg_file : str, pathlib.Path
WTG file to read
file_format : str
File format to use. Supported formats: "nc" for netCDF files,
"wtg" (for WAsP .wtg files), "yml" and "yaml" (for windIO turbine YAML files),
"infer" (auto-detect from extension). Default: "infer".
regulation_type : str or None
One of "stall", "pitch" or None. If None, uses es timate_regulation_type to
determine the regulation type. (Default: "pitch")
**kwargs
Additional keyword arguments passed to format-specific readers.
For windIO YAML, air_density can be specified.
Returns
-------
xr.Dataset
WTG dataset
Raises
------
ValueError
If the file format cannot be inferred or is unsupported. For WAsP
``.wtg`` files, also when a required element or attribute is missing,
when ``FormatVersion`` is not a version number, when a
``FormatVersion`` of 1.02 or later carries no ``ControlSystem`` or an
unrecognised one, or when a performance table states no
``StationaryThrustCoEfficient`` and its thrust curve is all zeros,
leaving no stationary thrust coefficient to derive.
lxml.etree.XMLSyntaxError
If a WAsP ``.wtg`` file is not well-formed XML. Subclasses
``SyntaxError``.
"""
if file_format == "infer":
file_format = _infer_file_format(wtg_file)
if file_format not in SUPPORTED_WTG_FILE_FORMATS_READ:
ext = Path(wtg_file).suffix.lower()[1:]
raise ValueError(
f"Cannot infer file format from extension '{ext}'. "
"Use file_format parameter to specify format."
)
if file_format == "nc":
# read using xarray
wtg_ds = xr.load_dataset(wtg_file)
elif file_format == "wtg":
wtg_ds = _read_wasp_wtg(wtg_file)
elif file_format in ["yaml", "yml"]:
wtg_ds = _read_windio_wtg(wtg_file, **kwargs)
else:
raise ValueError(
f"File format '{file_format}' not recognized as wind turbine generator!"
)
return _finalize_wtg_dataset(wtg_ds, regulation_type)
def _finalize_wtg_dataset(wtg_ds, regulation_type):
"""Complete a WTG dataset read from a file: regulation type, validation and metadata.
Shared by :func:`read_wtg` and ``Workspace.get_wtg``, so a turbine read from
a ``.wtg`` file and one read from a WAsP workspace come out the same.
Parameters
----------
wtg_ds : xr.Dataset
Wind turbine generator dataset as built from the file.
regulation_type : str or None
One of "stall", "pitch" or None, used when the file does not define the
regulation type. If None, it is estimated with
:func:`estimate_regulation_type`.
Returns
-------
xr.Dataset
The validated WTG dataset, with metadata.
Raises
------
WindkitValidationError
If the dataset is not a valid WTG dataset.
"""
# Update regulation type
# If undefined from the file and argument is None then estimate, else use argument
if ("regulation_type" not in wtg_ds.data_vars) or (
RegulationType(wtg_ds.regulation_type) == RegulationType.UNDEFINED
):
if regulation_type is None:
wtg_ds["regulation_type"] = estimate_regulation_type(wtg_ds).value
else:
wtg_ds["regulation_type"] = RegulationType[regulation_type.upper()].value
# Validate
validate_wtg(wtg_ds)
# Add metadata
return _update_var_attrs(wtg_ds, _ALL_VARS_META)
[docs]
def wtg_power(wtg, ws=None, *, interp_method="linear", air_density=None, use_cp=False):
"""Get power output when the inflow wind speed is ws. If the
given wind speed does not have an associated power output,
it is linearly interpolated between data points.
Parameters
----------
wtg : xr.Dataset
WindKit Wind Turbine Generator (WTG) Dataset
ws : array_like, floats
Wind speeds to obtain WTG power for.
interp_method : str
Interpolation method to use between provided table values.
Uses xr.DataArray.interp
air_density : float, optional
Air density, defaults to "air_density" from the WTG, or 1.225 kg/m^3 if it's missing.
use_cp : bool
If set to true, use the 'power_coefficient' values in the dataset to calculate the
power output. Defaults to False.
Returns
-------
xr.DataArray
Power for the given wind speeds
"""
if ws is None:
ws = wtg.wind_speed.values
if use_cp: # Special case for using power coefficient to calculate power
if air_density is None:
if "air_density" in wtg.data_vars:
air_density = wtg["air_density"]
else:
air_density = xr.DataArray(
[1.225] * wtg.mode.size,
dims=("mode",),
coords={"mode": wtg.mode},
name="air_density",
)
cp = wtg["power_coefficient"].interp(
wind_speed=ws,
method=interp_method,
kwargs={"fill_value": 0.0, "bounds_error": False},
)
if not isinstance(ws, xr.DataArray):
ws = xr.full_like(cp, 0.0) + ws
rotor_diameter = wtg["rotor_diameter"]
return cp * (0.5 * air_density * ws**3 * np.pi * (rotor_diameter / 2) ** 2)
else:
return wtg["power_output"].interp(
wind_speed=ws,
method=interp_method,
kwargs={"fill_value": 0.0, "bounds_error": False},
)
[docs]
def wtg_cp(wtg, ws=None, *, air_density=None, interp_method="linear", use_power=False):
"""Get power coefficient when the inflow wind speed is ws. If the
given wind speed does not have an associated power output,
it is linearly interpolated between data points.
Parameters
----------
wtg : xr.Dataset
WindKit Wind Turbine Generator (WTG) Dataset
ws : array_like, floats
Wind speeds to obtain WTG power for.
air_density : float, optional
Air density, defaults to "air_density" from the WTG, or 1.225 kg/m^3 if it's missing.
interp_method : str
Interpolation method to use between provided table values.
Uses xr.DataArray.interp
use_power : bool
if set to True, use the 'power_output' values in the dataset to calculate cp. Defaults
to False.
Returns
-------
xr.DataArray
Power Coefficient for the given wind speeds
"""
if ws is None:
ws = wtg.wind_speed.values
if use_power: # special case for using power to calculate power coefficient
if air_density is None:
if "air_density" in wtg.data_vars:
air_density = wtg["air_density"]
else:
air_density = xr.DataArray(
[1.225] * wtg.mode.size,
dims=("mode",),
coords={"mode": wtg.mode},
name="air_density",
)
power = wtg_power(wtg, ws, interp_method=interp_method, air_density=air_density)
if not isinstance(ws, xr.DataArray):
ws = xr.full_like(power, 0.0) + ws
rotor_diameter = wtg["rotor_diameter"]
return power / (0.5 * air_density * ws**3 * np.pi * (rotor_diameter / 2) ** 2)
else:
return wtg["power_coefficient"].interp(
wind_speed=ws,
method=interp_method,
kwargs={"fill_value": 0.0, "bounds_error": False},
)
[docs]
def wtg_ct(wtg, ws=None, *, interp_method="linear", ct_stat=None):
"""Get the thrust coefficient of a Wind Turbine Generator
for given wind speed(s). If the given wind speed(s) do not
have an associated thrust coefficient, it is interpolated
between data points.
Parameters
----------
wtg : xr.Dataset
WindKit Wind Turbine Generator (WTG) Dataset
ws : array_like, floats
Wind speeds to obtain WTG power for.
interp_method : str
Interpolation method to use between provided table values.
Uses xr.DataArray.interp
ct_stat: float
Stationary thrust coefficient to be used when the dataset does
not have it.
Returns
-------
xr.DataArray
Thrust coefficients for the given wind speeds
"""
if ws is None:
ws = wtg.wind_speed.values
if ct_stat is None:
if "stationary_thrust_coefficient" in wtg.data_vars:
ct_stat = wtg["stationary_thrust_coefficient"]
else:
ct_stat = (
wtg["thrust_coefficient"]
.where(wtg["thrust_coefficient"] != 0)
.min(dim="wind_speed")
)
# Interpolate ct, marking any extrapolated wind-speeds as NaN
interp_ct = wtg["thrust_coefficient"].interp(
wind_speed=ws,
method=interp_method,
kwargs={"bounds_error": False},
)
return interp_ct.fillna(ct_stat)
def _wtgs_to_unified_power_curve_arrays(*wtgs):
"""Convert multiple wtgs to arrays for power curve unification.
The WTGs must only have one mode (select the mode before passing
to this function).
Parameters
----------
*wtgs : xr.Dataset
Multiple Wind Turbine Generator datasets.
Returns
-------
unified_wind_speeds : np.ndarray
1D array of unified wind speeds (m/s) for all WTGs.
power_outputs: np.ndarray
2D array of power outputs (W) for each WTG. The shape is (n_wind_speeds, n_wtgs).
"""
wind_speeds_list = []
power_outputs_list = []
for wtg in wtgs:
has_mode_dim = "mode" in wtg.dims
if has_mode_dim and wtg.sizes["mode"] != 1:
raise ValueError(
"Each WTG must only have one mode for power curve unification."
)
if has_mode_dim:
wtg = wtg.isel(mode=0)
wind_speeds_list.append(wtg["wind_speed"].values)
power_outputs_list.append(wtg["power_output"].values)
unified_wind_speeds, unified_power_outputs_list = _unify_power_curves(
wind_speeds_list, power_outputs_list
)
return unified_wind_speeds, np.column_stack(unified_power_outputs_list)