"""Routines for working with Weibull distributions"""
import logging
import xarray as xr
from windkit.binned_wind_climate import (
bwc_validate_wrapper,
wv_count_wrapper,
)
from windkit.metadata import _WEIB_ATTRS, _MET_ATTRS, update_var_attrs, update_history
from windkit.sector import create_sector_coords
from windkit.spatial import spatial_stack, spatial_unstack
from windkit.empty import empty_bwc
from .wind_climate import add_met_fields
from ..wasp.binned_wind_climate import bwc_resample_sectors
from ..core import Rvea0326
from .._errors import _handle_fort_errors
# Rename fortran functions for ease of use
_WEIB_FIT_POINTS = Rvea0326.calc_points.weibull_fit_points
logger = logging.getLogger(__name__)
[docs]
@wv_count_wrapper
@bwc_validate_wrapper
def weibull_fit(bwc, include_met_fields=None, keep_attrs=True, nsecs=None):
"""
Returns sectorwise Weibull parameters using WAsP's fitting algorithm
.. warning::
This function is experimental and its signature may change.
Parameters
----------
bwc: xarray.Dataset
Binned wind climate xr.Dataset object
include_met_fields: list of str
Calculate the included meteorological variables, see fields argument to
pywasp.wasp.wind_climate.add_met_fields for more details. (Default: None, which
means to not include any meteorological fields)
keep_attrs: bool
Should we keep the attributes from the Binned Wind Climate (Default: True)
nsecs: int
Number of sectors to fit the weibull, if different from number of sectors in bwc
(Default: None, which means to keep the same number of sectors as in the bwc)
Returns
-------
xarray.Dataset
Weibull Wind Climate of same spatial extent as the input bwc
"""
bwc = spatial_stack(bwc)
if keep_attrs:
bwc_attrs = bwc.attrs.copy()
if nsecs is not None:
bwc = bwc_resample_sectors(bwc, nsecs)
bwc = bwc.transpose("wsbin", "sector", "point")
A, k, ierr = _WEIB_FIT_POINTS(bwc["wsfreq"], bwc["wsbin"])
_handle_fort_errors(ierr)
wwc = bwc[["sector", "point"]].drop_vars("point")
wwc["A"] = (("sector", "point"), A)
wwc["k"] = (("sector", "point"), k)
wwc["wdfreq"] = bwc.wdfreq
if keep_attrs:
wwc.attrs.update(bwc_attrs)
if include_met_fields:
wwc = add_met_fields(wwc, include_met_fields, air_dens=1.225)
var_attrs = {**_WEIB_ATTRS, **_MET_ATTRS}
else:
var_attrs = _WEIB_ATTRS
# Update metadata
update_var_attrs(wwc, var_attrs)
wwc.attrs["title"] = "Weibull wind climate from binned wind climate"
res = spatial_unstack(wwc)
return update_history(res)