API Reference

Contents

API Reference#

Cutout#

class atlite.Cutout(path: PathLike, **cutoutparams: Any)#

Cutout base class.

This class builds the starting point for most atlite functionalities.

area(crs: CrsLike | None = None) xr.DataArray#

Get the area per grid cell as a DataArray with coords (x,y).

Parameters:

crs (int, optional) – The coordinate reference system (CRS) to use for the calculation. Defaults to the crs of the cutout.

Returns:

A DataArray containing the area per grid cell with coordinates (x,y).

Return type:

xr.DataArray

availabilitymatrix(shapes: GeoDataFrame | GeoSeries, excluder: ExclusionContainer, nprocesses: int | None = None, disable_progressbar: bool = True) DataArray#

Compute the eligible share within cutout cells in the overlap with shapes.

For parallel calculation (nprocesses not None) the excluder must not be initialized and all raster references must be strings. Otherwise processes are colliding when reading from one common rasterio.DatasetReader.

Parameters:
  • cutout (atlite.Cutout) – Cutout which the availability matrix is aligned to.

  • shapes (geopandas.Series/geopandas.DataFrame) – Geometries for which the availabilities are calculated.

  • excluder (atlite.gis.ExclusionContainer) – Container of all meta data or objects which to exclude, i.e. rasters and geometries.

  • nprocesses (int, optional) – Number of processes to use for calculating the matrix. The paralle- lization can heavily boost the calculation speed. The default is None.

  • disable_progressbar (bool, optional) – Disable the progressbar if nprocesses is not None. Then the map function instead of the imap function is used for the multiprocessing pool. This speeds up the calculation.

Returns:

availabilities – DataArray of shape (|shapes|, |y|, |x|) containing all the eligible share of cutout cell (x,y) in the overlap with shape i.

Return type:

xr.DataArray

Notes

The rasterio (or GDAL) average downsampling returns different results dependent on how the target raster (the cutout raster) is spanned. Either it is spanned from the top left going downwards, e.g. Affine(0.25, 0, 0, 0, -0.25, 50), or starting in the lower left corner and going up, e.g. Affine(0.25, 0, 0, 0, 0.25, 50). Here we stick to the top down version which is why we use cutout.transform_r and flipping the y-axis in the end.

property available_features: Index#

List of available weather data features for the cutout.

property bounds: NDArray#

Total bounds of the area covered by the cutout (x, y, X, Y).

property chunks: dict[str, int] | None#

Chunking of the cutout data used by dask.

coefficient_of_performance(source: HeatPumpSource = 'air', sink_T: float = 55.0, c0: float | None = None, c1: float | None = None, c2: float | None = None, **params: Any) ConvertResult#

Convert temperature to heat pump coefficient of performance (COP).

The COP is modelled as a quadratic function of the temperature difference dT = sink_T - source_T: COP = c0 + c1 * dT + c2 * dT**2.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • source ({"air", "soil"}) –

    Heat source type. Default coefficients per source:

    • "air": c0=6.81, c1=-0.121, c2=0.000630

    • "soil": c0=8.77, c1=-0.150, c2=0.000734

  • sink_T (float, default 55.0) – Heat sink temperature in °C.

  • c0 (float or None) – Constant regression coefficient. If None, uses source default.

  • c1 (float or None) – Linear regression coefficient. If None, uses source default.

  • c2 (float or None) – Quadratic regression coefficient. If None, uses source default.

  • **params (Any) – Additional keyword arguments passed to convert_and_aggregate().

Returns:

Coefficient of performance time-series (dimensionless).

Return type:

xr.DataArray

See also

heat_demand

Compute heating degree-day demand.

Note

This function also accepts all keyword arguments of convert_and_aggregate().

References

[1] Staffell, Brett, Brandon, Hawkes, A review of domestic heat pumps, Energy & Environmental Science (2012), 5, 9291-9306, https://doi.org/10.1039/C2EE22653G.

convert_and_aggregate(convert_func: Callable[..., Any], matrix: Any = None, index: Any = None, layout: Any = None, shapes: Any = None, shapes_crs: int = 4326, per_unit: bool = False, return_capacity: bool = False, aggregate_time: Literal['sum', 'mean', 'legacy'] | None = 'legacy', capacity_factor: bool = False, capacity_factor_timeseries: bool = False, show_progress: bool = False, dask_kwargs: dict[str, Any] | None = None, **convert_kwds: Any) ConvertResult#

Convert and aggregate a weather-based renewable generation time-series.

This is a gateway function called by the individual time-series generation functions like pv and wind. All parameters documented here are also available from those functions.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • convert_func (callable) – Callback like convert_wind, convert_pv.

  • matrix (N x S - xr.DataArray or sp.sparse.csr_matrix or None) – If given, it is used to aggregate the grid cells to buses. N is the number of buses, S the number of spatial coordinates, in the order of cutout.grid.

  • index (pd.Index) – Index of Buses.

  • layout (X x Y - xr.DataArray) – The capacity to be build in each of the grid_cells.

  • shapes (list or pd.Series of shapely.geometry.Polygon) – If given, matrix is constructed as indicatormatrix of the polygons, its index determines the bus index on the time-series.

  • shapes_crs (pyproj.CRS or compatible) – If different to the map crs of the cutout, the shapes are transformed to match cutout.crs (defaults to EPSG:4326).

  • per_unit (boolean) – Returns the time-series in per-unit units, instead of in MW (defaults to False).

  • return_capacity (boolean) – Additionally returns the installed capacity at each bus corresponding to layout (defaults to False).

  • aggregate_time ("sum", "mean", "legacy", or None) – Controls temporal aggregation of results. "sum" sums over time, "mean" averages over time, None returns full timeseries. "legacy" (default) preserves historical behavior: time-summed without spatial aggregation and full timeseries with spatial aggregation; this option is deprecated and will be removed in a future release. Replaces the deprecated capacity_factor and capacity_factor_timeseries parameters.

  • capacity_factor (boolean) – Deprecated. Use aggregate_time="mean" instead.

  • capacity_factor_timeseries (boolean) – Deprecated. Use aggregate_time=None instead (which is the default).

  • show_progress (boolean, default False) – Whether to show a progress bar.

  • dask_kwargs (dict, default {}) – Dict with keyword arguments passed to dask.compute.

  • **convert_kwds (Any) – Additional keyword arguments passed to convert_func.

Returns:

  • resource (xr.DataArray) – The return value depends on which arguments are provided:

    With aggregation (matrix, shapes, or layout given): Time-series of renewable generation aggregated to buses, with dimensions (bus, time). If aggregate_time is set, the time dimension is reduced accordingly.

    Without aggregation (none of the above given):

    • aggregate_time=None: per-cell timeseries (time, y, x).

    • aggregate_time="mean": time-averaged per cell (y, x).

    • aggregate_time="sum": time-summed per cell (y, x).

    Legacy behavior (deprecated):

    • aggregate_time="legacy": historical context-dependent default.

    • capacity_factor_timeseries=True: equivalent to aggregate_time=None.

    • capacity_factor=True: equivalent to aggregate_time="mean".

  • units (xr.DataArray (optional)) – The installed units per bus in MW corresponding to layout (only if return_capacity is True).

Raises:

ValueError – If deprecated parameters conflict or invalid arguments are provided.

See also

wind

Generate wind generation time-series.

pv

Generate solar PV generation time-series.

cooling_demand(threshold: float = 23.0, a: float = 1.0, constant: float = 0.0, hour_shift: float = 0.0, **params: Any) ConvertResult#

Convert outside temperature into daily cooling demand using degree-day approximation.

The formula is max(0, a * (T_daily_mean - threshold)) + constant where T_daily_mean is the daily-averaged temperature. Output is in degree-day-like units (scaled by a).

Since “daily average temperature” means different things in different time zones, you can provide hour_shift to redefine when the day starts. E.g. for Moscow in summer hour_shift=3, for New York hour_shift=-4. The shift applies uniformly across all grid cells and times.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • threshold (float, default 23.0) – Outside temperature in °C below which there is no cooling demand. The default follows European computational practices (UK Met Office uses 22 °C, European Commission uses 24 °C).

  • a (float, default 1.0) – Linear factor relating cooling demand to outside temperature.

  • constant (float, default 0.0) – Constant part of cooling demand independent of outside temperature (e.g. ventilation).

  • hour_shift (float, default 0.0) – Time shift in hours relative to UTC for daily averaging.

  • **params (Any) – Additional keyword arguments passed to convert_and_aggregate().

Returns:

Daily cooling demand time-series in degree-day-like units.

Return type:

xr.DataArray

Warning

Because the original data is provided per month, at month boundaries there is untidiness when using a time shift. The resulting array will have duplicate indices for parts of the day at each boundary. You must re-average these based on the number of hours in each month.

See also

heat_demand

Degree-day heating demand.

Note

This function also accepts all keyword arguments of convert_and_aggregate().

property coords: Coordinates#

Geographic coordinates of the cutout.

property crs: CRS#

Coordinate Reference System of the cutout.

csp(installation: str | CSPConfig, technology: Literal['parabolic trough', 'solar tower'] | None = None, **params: Any) ConvertResult#

Convert direct radiation into CSP generation time series.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • installation (str or xr.DataArray) – CSP installation details determining the solar field efficiency dependent on the local solar position. Can be a name accepted by atlite.resource.get_cspinstallationconfig() or an xr.DataArray with 'azimuth' (rad) and 'altitude' (rad) coordinates and an 'efficiency' (p.u.) entry.

  • technology ({"parabolic trough", "solar tower"} or None) – Overwrite CSP technology from the installation configuration. 'parabolic trough' uses direct horizontal irradiance (DHI), 'solar tower' uses direct normal irradiance (DNI).

  • **params – Additional keyword arguments passed to convert_and_aggregate.

Returns:

csp – CSP generation time-series in specific yield (kWh/kW_ref), clipped to [0, 1]. See convert_and_aggregate() for details on aggregation behaviour.

Return type:

xr.DataArray

Note

This function also accepts all keyword arguments of convert_and_aggregate().

References

[1] Tobias Hirsch (ed.). SolarPACES Guideline for Bankable STE Yield Assessment, IEA Technology Collaboration Programme SolarPACES, 2017. URL: https://www.solarpaces.org/csp-research-tasks/task-annexes-iea/task-i-solar-thermal-electric-systems/solarpaces-guideline-for-bankable-ste-yield-assessment/

[2] Tobias Hirsch (ed.). CSPBankability Project Report, DLR, 2017. URL: https://www.dlr.de/sf/en/desktopdefault.aspx/tabid-11126/19467_read-48251/

dewpoint_temperature(**params: Any) ConvertResult#

Return dew point temperature converted from Kelvin to degrees Celsius.

Parameters:
Returns:

Dew point temperature in °C.

Return type:

xr.DataArray

Note

This function also accepts all keyword arguments of convert_and_aggregate().

property dt: str | None#

Time resolution of the cutout.

property dx: float#

Spatial resolution on the x coordinates.

property dy: float#

Spatial resolution on the y coordinates.

equals(other: Any) bool#

Compare equality with another cutout, ignoring the path attribute.

Returns:

Whether the two cutouts are equal.

Return type:

bool

property extent: NDArray#

Total extent of the area covered by the cutout (x, X, y, Y).

grid#

Cutout grid with coordinates and geometries.

The coordinates represent the centers of the grid cells.

Returns:

Frame with coordinate columns ‘x’ and ‘y’, and geometries of the corresponding grid cells.

Return type:

geopandas.GeoDataFrame

heat_demand(threshold: float = 15.0, a: float = 1.0, constant: float = 0.0, hour_shift: float = 0.0, **params: Any) ConvertResult#

Convert outside temperature into daily heat demand using degree-day approximation.

The formula is max(0, a * (threshold - T_daily_mean)) + constant where T_daily_mean is the daily-averaged temperature. Output is in degree-day-like units (scaled by a).

Since “daily average temperature” means different things in different time zones, you can provide hour_shift to redefine when the day starts. E.g. for Moscow in winter hour_shift=4, for New York hour_shift=-5. The shift applies uniformly across all grid cells and times.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • threshold (float, default 15.0) – Outside temperature in °C above which there is no heat demand.

  • a (float, default 1.0) – Linear factor relating heat demand to outside temperature.

  • constant (float, default 0.0) – Constant part of heat demand independent of outside temperature (e.g. water heating).

  • hour_shift (float, default 0.0) – Time shift in hours relative to UTC for daily averaging.

  • **params (Any) – Additional keyword arguments passed to convert_and_aggregate().

Returns:

Daily heat demand time-series in degree-day-like units.

Return type:

xr.DataArray

Warning

Because the original data is provided per month, at month boundaries there is untidiness when using a time shift. The resulting array will have duplicate indices for parts of the day at each boundary. You must re-average these based on the number of hours in each month.

See also

cooling_demand

Degree-day cooling demand.

Note

This function also accepts all keyword arguments of convert_and_aggregate().

hydro(plants, hydrobasins, flowspeed=1, weight_with_height=False, show_progress=False, **kwargs)#

Compute inflow time series for plants by aggregating over catchment basins.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • plants (pd.DataFrame) – Run-of-river plants or dams with lon, lat columns.

  • hydrobasins (str|gpd.GeoDataFrame) – Filename or GeoDataFrame of one level of the HydroBASINS dataset.

  • flowspeed (float) – Average speed of water flows to estimate the water travel time from basin to plant (default: 1 m/s).

  • weight_with_height (bool) – Whether surface runoff should be weighted by potential height (probably better for coarser resolution).

  • show_progress (bool) – Whether to display progressbars.

  • **kwargs – Additional keyword arguments passed to convert_and_aggregate.

Returns:

Inflow time-series for each plant.

Return type:

xr.DataArray

References

[1] Liu, Hailiang, et al. “A validated high-resolution hydro power time-series model for energy systems analysis.” arXiv preprint arXiv:1901.08476 (2019).

[2] Lehner, B., Grill G. (2013): Global river hydrography and network routing: baseline data and new approaches to study the world’s large river systems. Hydrological Processes, 27(15): 2171–2186. Data is available at www.hydrosheds.org.

indicatormatrix(shapes: Sequence[BaseGeometry], shapes_crs: CrsLike = 4326) sp.lil_matrix | sp.csr_matrix#

Compute the indicatormatrix.

The indicatormatrix I[i,j] is a sparse representation of the ratio of the area in orig[j] lying in dest[i], where orig and dest are collections of polygons, i.e.

A value of I[i,j] = 1 indicates that the shape orig[j] is fully contained in shape dest[j].

Note that the polygons must be in the same crs.

Parameters:
  • shapes (Collection of shapely polygons) – Shapes to compute the indicator matrix for.

  • shapes_crs (int or CRS, default 4326) – CRS of the shapes.

Returns:

I – Indicatormatrix

Return type:

sp.sparse.lil_matrix

intersectionmatrix(shapes: Sequence[BaseGeometry], shapes_crs: CrsLike = 4326) sp.lil_matrix | sp.csr_matrix#

Compute the intersectionmatrix.

The intersectionmatrix is a sparse matrix with entries (i,j) being one if shapes orig[j] and dest[i] are intersecting, and zero otherwise.

Note that the polygons must be in the same crs.

Parameters:
  • shapes (Collection of shapely polygons) – Shapes to compute the intersection matrix for.

  • shapes_crs (int or CRS, default 4326) – CRS of the shapes.

Returns:

I – Intersectionmatrix

Return type:

sp.sparse.lil_matrix

irradiation(orientation: OrientationName | dict[str, float] | Callable, irradiation: IrradiationType = 'total', tracking: TrackingType | None = None, clearsky_model: ClearskyModel | None = None, **params: Any) ConvertResult#

Calculate irradiation on a tilted surface.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • orientation (str, dict or callback) – Panel orientation can be chosen from either ‘latitude_optimal’, a constant orientation {‘slope’: 0.0, ‘azimuth’: 0.0} or a callback function with the same signature as the callbacks generated by the ‘atlite.pv.orientation.make_*’ functions.

  • irradiation (str) – The irradiation quantity to be returned. Defaults to “total” for total combined irradiation. Other options include “direct” for direct irradiation, “diffuse” for diffuse irradation, and “ground” for irradiation reflected by the ground via albedo. NOTE: “ground” irradiation is not calculated by all trigon_model options in the convert_irradiation method, so use with caution!

  • tracking (None or str:) – None for no tracking, default ‘horizontal’ for 1-axis horizontal tracking ‘tilted_horizontal’ for 1-axis horizontal tracking with tilted axis ‘vertical’ for 1-axis vertical tracking ‘dual’ for 2-axis tracking

  • clearsky_model (str or None) – Either the ‘simple’ or the ‘enhanced’ Reindl clearsky model. The default choice of None will choose dependending on data availability, since the ‘enhanced’ model also incorporates ambient air temperature and relative humidity.

  • **params (Any) – Additional keyword arguments passed to convert_and_aggregate.

Returns:

irradiation – Irradiation on the tilted surface in W/m².

Return type:

xr.DataArray

See also

pv

Photovoltaic generation.

solar_thermal

Solar thermal collector output.

Notes

The trigon_model is fixed to 'simple' internally.

Note

This function also accepts all keyword arguments of convert_and_aggregate().

References

[1] D.T. Reindl, W.A. Beckman, and J.A. Duffie. Diffuse fraction correla- tions. Solar Energy, 45(1):1 – 7, 1990.

layout_from_capacity_list(data, col='Capacity')#

Get a capacity layout aligned to the cutout based on a capacity list.

Parameters:
  • data (pandas.DataFrame) – Capacity list with columns ‘x’, ‘y’ and col. Each capacity entry is added to the grid cell intersecting with the coordinate (x,y).

  • col (str, optional) – Name of the column with capacity values. The default is ‘Capacity’.

Returns:

Capacity layout with dimensions ‘x’ and ‘y’ indicating the total capacity placed within one grid cell.

Return type:

xr.DataArray

Example

>>> import atlite
>>> import powerplantmatching as pm
>>> data = pm.data.OPSD_VRE_country('DE')
>>> data = (data.query('Fueltype == "Solar"')
            .rename(columns={'lon':'x', 'lat':'y'}))
>>> cutout = atlite.Cutout('Germany', x = slice(-5, 15), y = slice(40, 55),
               time='2013-06-01', module='era5')
>>> cutout.prepare(features=['influx', 'temperature'])
>>> layout = cutout.layout_from_capacity_list(data)
>>> pv = cutout.pv('CdTe', 'latitude_optimal', layout=layout)
>>> pv.plot()
line_rating(shapes, line_resistance, show_progress=False, dask_kwargs=None, **params)#

Create a dynamic line rating time series based on the IEEE-738 standard.

[1].

The steady-state capacity is derived from the balance between heat losses due to radiation and convection, and heat gains due to solar influx and conductur resistance. For more information on assumptions and modifications see convert_line_rating.

[1]“IEEE Std 738™-2012 (Revision of IEEE Std 738-2006/Incorporates IEEE Std

738-2012/Cor 1-2013), IEEE Standard for Calculating the Current-Temperature Relationship of Bare Overhead Conductors,” p. 72.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • shapes (geopandas.GeoSeries) – Line shapes of the lines.

  • line_resistance (float/series) – Resistance of the lines in Ohm/meter. Alternatively in p.u. system in Ohm/1000km (see example below).

  • show_progress (boolean, default False) – Whether to show a progress bar.

  • dask_kwargs (dict, default {}) – Dict with keyword arguments passed to dask.compute.

  • D (float, default 0.028) – Conductor diameter in meters.

  • Ts (float, default 373) – Maximum allowed conductor surface temperature in Kelvin.

  • epsilon (float, default 0.6) – Conductor emissivity (dimensionless).

  • alpha (float, default 0.6) – Conductor absorptivity (dimensionless).

  • **params (Any) – Additional keyword arguments passed to convert_line_rating().

Returns:

Thermal current limit time-series with dimensions (time, lines) in ampere.

Return type:

xr.DataArray

Note

This function also accepts all keyword arguments of convert_and_aggregate().

Example

>>> import pypsa
>>> import xarray as xr
>>> import atlite
>>> import numpy as np
>>> import geopandas as gpd
>>> from shapely.geometry import Point, LineString as Line
>>> n = pypsa.examples.scigrid_de()
>>> n.calculate_dependent_values()
>>> x = n.buses.x
>>> y = n.buses.y
>>> buses = n.lines[["bus0", "bus1"]].values
>>> shapes = [Line([Point(x[b0], y[b0]), Point(x[b1], y[b1])]) for (b0, b1) in buses]
>>> shapes = gpd.GeoSeries(shapes, index=n.lines.index)
>>> cutout = atlite.Cutout('test', x=slice(x.min(), x.max()), y=slice(y.min(), y.max()),
                        time='2020-01-01', module='era5', dx=1, dy=1)
>>> cutout.prepare()
>>> i = cutout.line_rating(shapes, n.lines.r/n.lines.length)
>>> v = xr.DataArray(n.lines.v_nom, dims='name')
>>> s = np.sqrt(3) * i * v / 1e3 # in MW
merge(other: Cutout, path: PathLike | None = None, **kwargs: Any) Cutout#

Merge two cutouts into a single cutout.

Parameters:
  • other (atlite.Cutout) – Other cutout to merge.

  • path (str | path-like) – File where to store the merged cutout. Defaults to a temporary file.

  • **kwargs – Keyword arguments passed to xarray.merge().

Returns:

merged – Merged cutout.

Return type:

Cutout

property module: str | list[str]#

Data module of the cutout.

property name: str#

Name of the cutout.

prepare(features: str | Sequence[str] | None = None, tmpdir: PathLike | None = None, data_format: DataFormat = 'grib', overwrite: bool = False, compression: dict[str, Any] | None = None, show_progress: bool = False, dask_kwargs: dict[str, Any] | None = None, monthly_requests: bool = False, concurrent_requests: bool = False) Cutout#

Prepare all or a selection of features in a cutout.

This function loads the feature data of a cutout, e.g. influx or runoff. When not specifying the feature argument, all available features will be loaded. The function compares the variables which are already included in the cutout with the available variables of the modules specified by the cutout. It detects missing variables and stores them into the netcdf file of the cutout.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • features (str/list, optional) – Feature(s) to be prepared. The default slice(None) results in all available features.

  • tmpdir (str/Path, optional) – Directory in which temporary files (for example retrieved ERA5 netcdf files) are stored. If set, the directory will not be deleted and the intermediate files can be examined. The path must be a valid path.

  • data_format (str, optional) – The data format used to retrieve the data. Only relevant for ERA5 data. The default is ‘grib’.

  • overwrite (bool, optional) – Whether to overwrite variables which are already included in the cutout. The default is False.

  • compression (None/dict, optional) – Compression level to use for all features which are being prepared. The compression is handled via xarray.Dataset.to_netcdf(…), for details see: https://docs.xarray.dev/en/stable/generated/xarray.Dataset.to_netcdf.html . To efficiently reduce cutout sizes, specify the number of ‘least_significant_digits’: n here. To disable compression, set “complevel” to None. Default is {‘zlib’: True, ‘complevel’: 9, ‘shuffle’: True}.

  • show_progress (bool, optional) – If True, a progress bar is shown. The default is False.

  • dask_kwargs (dict, default {}) – Dict with keyword arguments passed to dask.compute.

  • monthly_requests (bool, optional) – If True, the data is requested on a monthly basis in ERA5. This is useful for large cutouts, where the data is requested in smaller chunks. The default is False

  • concurrent_requests (bool, optional) – If True, the monthly data requests are posted concurrently. Only has an effect if monthly_requests is True. The default is False.

Returns:

cutout – Cutout with prepared data. The variables are stored in cutout.data.

Return type:

atlite.Cutout

Raises:
property prepared: bool#

Boolean indicating whether all available features are prepared.

property prepared_features: pd.Series[Any]#

Get the list of prepared features in the cutout.

pv(panel: str | PanelConfig, orientation: OrientationName | dict[str, float] | Callable, tracking: TrackingType | None = None, clearsky_model: ClearskyModel | None = None, **params: Any) ConvertResult#

Convert radiation and temperature into PV generation time series.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • panel (str or dict) – Panel config dictionary with the parameters for the electrical model in [3]. Alternatively, a name accepted by atlite.resource.get_solarpanelconfig().

  • orientation (str, dict or callback) – Panel orientation can be chosen from either ‘latitude_optimal’, a constant orientation {‘slope’: 0.0, ‘azimuth’: 0.0} or a callback function with the same signature as the callbacks generated by the ‘atlite.pv.orientation.make_*’ functions.

  • tracking (None or str:) – None for no tracking, default ‘horizontal’ for 1-axis horizontal tracking ‘tilted_horizontal’ for 1-axis horizontal tracking with tilted axis ‘vertical’ for 1-axis vertical tracking ‘dual’ for 2-axis tracking

  • clearsky_model (str or None) – Either the ‘simple’ or the ‘enhanced’ Reindl clearsky model. The default choice of None will choose dependending on data availability, since the ‘enhanced’ model also incorporates ambient air temperature and relative humidity.

  • **params (Any) – Additional keyword arguments passed to convert_and_aggregate.

Returns:

pv – PV generation time-series. Without aggregation, values are capacity factors (unitless, 0–1). With aggregation and per_unit=False, values are in MW. See convert_and_aggregate() for details.

Return type:

xr.DataArray

See also

wind

Wind generation.

irradiation

Tilted surface irradiation.

solar_thermal

Solar thermal collector output.

Note

This function also accepts all keyword arguments of convert_and_aggregate().

References

[1] Soteris A. Kalogirou. Solar Energy Engineering: Processes and Systems, pages 49–117,469–516. Academic Press, 2009. ISBN 0123745012.

[2] D.T. Reindl, W.A. Beckman, and J.A. Duffie. Diffuse fraction correla- tions. Solar Energy, 45(1):1 – 7, 1990.

[3] Hans Georg Beyer, Gerd Heilscher and Stefan Bofinger. A Robust Model for the MPP Performance of Different Types of PV-Modules Applied for the Performance Check of Grid Connected Systems, Freiburg, June 2004. Eurosun (ISES Europe Solar Congress).

Examples

Aggregate PV generation to bus regions:

>>> pv = cutout.pv(panel="CSi", orientation="latitude_optimal",
...                matrix=matrix, index=buses, per_unit=True)

Get per-cell capacity factor time series (no aggregation):

>>> cf = cutout.pv(panel="CSi", orientation="latitude_optimal",
...                aggregate_time=None)
>>> location_cf = cf.sel(x=6.9, y=53.1, method="nearest")
runoff(smooth=None, lower_threshold_quantile=None, normalize_using_yearly=None, **params)#

Compute aggregated surface runoff with optional smoothing and normalization.

Parameters:
  • cutout (atlite.Cutout) – Cutout providing weather data with runoff variables.

  • smooth (bool or int, optional) – If True, apply a rolling mean with the default window of 24 * 7 time steps. If an integer, use it as the rolling window size. Default None (no smoothing).

  • lower_threshold_quantile (bool or float, optional) – If True, use the default quantile 5e-3. If a float, set values below that quantile to zero. Default None (no thresholding).

  • normalize_using_yearly (pd.Series, optional) – Annual country totals used to scale countries-indexed results over overlapping full years. One factor per country is derived from the summed reference values across the overlap.

  • **params – Additional keyword arguments passed to convert_and_aggregate(), including weight_with_height for the underlying runoff conversion.

Returns:

Runoff output from convert_and_aggregate. Smoothing also supports the tuple return form used with return_capacity=True. Thresholding and normalization are only supported for xr.DataArray results.

Return type:

xr.DataArray or tuple[xr.DataArray, xr.DataArray]

See also

convert_and_aggregate

General conversion/aggregation arguments.

sel(path: PathLike | None = None, bounds: Sequence[float] | None = None, buffer: float = 0, **kwargs: Any) Cutout#

Select parts of the cutout.

Parameters:
  • path (str | path-like) – File where to store the sub-cutout. Defaults to a temporary file.

  • bounds (gpd.GeoSeries.bounds | DataFrame, optional) – The outer bounds of the cutout or as a DataFrame containing (min.long, min.lat, max.long, max.lat).

  • buffer (float, optional) – Buffer around the bounds. The default is 0.

  • **kwargs – Passed to xr.Dataset.sel for data selection.

Returns:

selected – Selected cutout.

Return type:

Cutout

property shape: tuple[int, int]#

Size of spatial dimensions (y, x) of the cutout data.

soil_temperature(**params: Any) ConvertResult#

Return soil temperature converted from Kelvin to degrees Celsius.

Sea grid cells, where soil temperature is undefined, are filled with 0.0 so they do not contribute during spatial aggregation.

Parameters:
Returns:

Soil temperature in °C.

Return type:

xr.DataArray

Note

This function also accepts all keyword arguments of convert_and_aggregate().

solar_thermal(orientation: OrientationName | dict[str, float] | Callable | None = None, trigon_model: TrigonModel = 'simple', clearsky_model: ClearskyModel = 'simple', c0: float = 0.8, c1: float = 3.0, t_store: float = 80.0, **params: Any) ConvertResult#

Convert radiation and temperature into solar thermal collector time series.

Collector efficiency is eta = c0 - c1 * (T_store - T_amb) / G. Mathematical model and defaults for c0, c1 based on [1].

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • orientation (dict, str, or callable, optional) – Panel orientation. A dict with 'slope' and 'azimuth' keys in degrees, the string 'latitude_optimal', or a callable with the same signature as callbacks from atlite.pv.orientation.make_*. Default: {'slope': 45.0, 'azimuth': 180.0}.

  • trigon_model ({"simple", "perez"}, default "simple") – Trigonometric model for tilted irradiation decomposition.

  • clearsky_model ({"simple", "enhanced"} or None, default "simple") – Clear-sky model for diffuse irradiation. 'enhanced' also uses ambient temperature and relative humidity.

  • c0 (float, default 0.8) – Optical efficiency parameter.

  • c1 (float, default 3.0) – Thermal loss coefficient in W/(m² K).

  • t_store (float, default 80.0) – Storage temperature in °C.

  • **params (Any) – Additional keyword arguments passed to convert_and_aggregate().

Returns:

Solar thermal generation time-series.

Return type:

xr.DataArray

See also

pv

Photovoltaic generation.

irradiation

Tilted surface irradiation.

Note

This function also accepts all keyword arguments of convert_and_aggregate().

References

[1] Henning and Palzer, Renewable and Sustainable Energy Reviews 30 (2014) 1003-1018

temperature(**params: Any) ConvertResult#

Return ambient air temperature converted from Kelvin to degrees Celsius.

Parameters:
Returns:

Ambient temperature in °C.

Return type:

xr.DataArray

Note

This function also accepts all keyword arguments of convert_and_aggregate().

to_file(fn: PathLike | None = None) None#

Save cutout to a NetCDF file.

Parameters:

fn (str | path-like) – File name where to store the cutout, defaults to cutout.path.

property transform: Affine#

Get the affine transform of the cutout.

property transform_r: Affine#

Get the affine transform of the cutout with reverse y-order.

uniform_density_layout(capacity_density: float, crs: CrsLike | None = None) xr.DataArray#

Get a capacity layout from a uniform capacity density.

Parameters:
  • capacity_density (float) – Capacity density in capacity/projection unit squared.

  • crs (int, optional) – CRS to calculate the total area of grid cells. Passed to Cutout.area().

Returns:

Capacity layout with dimensions ‘x’ and ‘y’ indicating the total capacity placed within one grid cell.

Return type:

xr.DataArray

uniform_layout() DataArray#

Get a uniform capacity layout for all grid cells.

Returns:

Layout with value 1 for all grid cells.

Return type:

xr.DataArray

wind(turbine: str | Path | dict[str, Any], smooth: bool | dict[str, Any] = False, add_cutout_windspeed: bool = False, interpolation_method: Literal['logarithmic', 'power'] = 'logarithmic', **params: Any) ConvertResult#

Generate wind generation time-series.

Extrapolates wind speed to hub height (using logarithmic or power law) and evaluates the power curve.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • turbine (str or dict) –

    A turbineconfig dictionary with the keys ‘hub_height’ for the hub height and ‘V’, ‘POW’ defining the power curve. Alternatively a str refering to a local or remote turbine configuration as accepted by atlite.resource.get_windturbineconfig(). Locally stored turbine configurations can also be modified with this function. E.g. to setup a different hub height from the one used in the yaml file,one would write

    ”turbine=get_windturbineconfig(“NREL_ReferenceTurbine_5MW_offshore”)|{“hub_height”:120}”

  • smooth (bool or dict) – If True smooth power curve with a gaussian kernel as determined for the Danish wind fleet to Delta_v = 1.27 and sigma = 2.29. A dict allows to tune these values.

  • add_cutout_windspeed (bool) – If True and in case the power curve does not end with a zero, will add zero power output at the highest wind speed in the power curve. If False, a warning will be raised if the power curve does not have a cut-out wind speed. The default is False.

  • interpolation_method ({"logarithmic", "power"}) – Law to interpolate wind speed to turbine hub height. Refer to atlite.wind.extrapolate_wind_speed().

  • **params (Any) – Additional keyword arguments passed to convert_and_aggregate.

Returns:

resource – Wind generation time-series. Without aggregation, values are capacity factors (MWh/MWp). With aggregation and per_unit=False, values are in MW. See convert_and_aggregate() for details.

Return type:

xr.DataArray

See also

pv

Photovoltaic generation.

Note

This function also accepts all keyword arguments of convert_and_aggregate().

References

Examples

Aggregate wind generation to bus regions:

>>> wind = cutout.wind(turbine="Vestas_V112_3MW", matrix=matrix,
...                    index=buses, per_unit=True)

Get per-cell capacity factor time series (no aggregation):

>>> cf = cutout.wind(turbine="Vestas_V112_3MW",
...                  aggregate_time=None)
>>> cf.dims
('time', 'y', 'x')
>>> location_cf = cf.sel(x=6.9, y=53.1, method="nearest")

Data#

Management of data retrieval and structure.

atlite.data.available_features(module: str | Sequence[str] | None = None) pd.Series[str]#

Inspect the available features of all or a selection of modules.

Parameters:

module (str/list, optional) – Module name(s) which to inspect. The default None will result in all modules

Returns:

A Series of all variables. The MultiIndex indicated which module provides the variable and with which feature name the variable can be obtained.

Return type:

pd.Series

atlite.data.cutout_prepare(cutout: Cutout, features: str | Sequence[str] | None = None, tmpdir: PathLike | None = None, data_format: DataFormat = 'grib', overwrite: bool = False, compression: dict[str, Any] | None = None, show_progress: bool = False, dask_kwargs: dict[str, Any] | None = None, monthly_requests: bool = False, concurrent_requests: bool = False) Cutout#

Prepare all or a selection of features in a cutout.

This function loads the feature data of a cutout, e.g. influx or runoff. When not specifying the feature argument, all available features will be loaded. The function compares the variables which are already included in the cutout with the available variables of the modules specified by the cutout. It detects missing variables and stores them into the netcdf file of the cutout.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • features (str/list, optional) – Feature(s) to be prepared. The default slice(None) results in all available features.

  • tmpdir (str/Path, optional) – Directory in which temporary files (for example retrieved ERA5 netcdf files) are stored. If set, the directory will not be deleted and the intermediate files can be examined. The path must be a valid path.

  • data_format (str, optional) – The data format used to retrieve the data. Only relevant for ERA5 data. The default is ‘grib’.

  • overwrite (bool, optional) – Whether to overwrite variables which are already included in the cutout. The default is False.

  • compression (None/dict, optional) – Compression level to use for all features which are being prepared. The compression is handled via xarray.Dataset.to_netcdf(…), for details see: https://docs.xarray.dev/en/stable/generated/xarray.Dataset.to_netcdf.html . To efficiently reduce cutout sizes, specify the number of ‘least_significant_digits’: n here. To disable compression, set “complevel” to None. Default is {‘zlib’: True, ‘complevel’: 9, ‘shuffle’: True}.

  • show_progress (bool, optional) – If True, a progress bar is shown. The default is False.

  • dask_kwargs (dict, default {}) – Dict with keyword arguments passed to dask.compute.

  • monthly_requests (bool, optional) – If True, the data is requested on a monthly basis in ERA5. This is useful for large cutouts, where the data is requested in smaller chunks. The default is False

  • concurrent_requests (bool, optional) – If True, the monthly data requests are posted concurrently. Only has an effect if monthly_requests is True. The default is False.

Returns:

cutout – Cutout with prepared data. The variables are stored in cutout.data.

Return type:

atlite.Cutout

Raises:
atlite.data.get_features(cutout: Cutout, module: str, features: Iterable[str], data_format: DataFormat, tmpdir: PathLike | None = None, monthly_requests: bool = False, concurrent_requests: bool = False) xr.Dataset#

Load feature datasets for a cutout module.

Parameters:
  • cutout (atlite.Cutout) – Cutout for which data is retrieved.

  • module (str) – Name of the dataset module.

  • features (iterable of str) – Feature names to retrieve from the module.

  • data_format (str) – Data format requested from the dataset backend.

  • tmpdir (str or pathlib.Path, optional) – Directory for intermediate files.

  • monthly_requests (bool, optional) – Whether to split requests into monthly chunks.

  • concurrent_requests (bool, optional) – Whether to issue monthly requests concurrently.

Returns:

Merged dataset containing the requested features.

Return type:

xarray.Dataset

atlite.data.maybe_remove_tmpdir(func: Callable[..., Any]) Callable[..., Any]#

Wrap a function to manage a temporary directory.

Parameters:

func (callable) – Function accepting a tmpdir keyword argument.

Returns:

Wrapped function that creates and removes a temporary directory when tmpdir is not provided.

Return type:

callable

atlite.data.non_bool_dict(d: dict[str, Any]) dict[str, Any]#

Convert boolean dictionary values to integers.

Parameters:

d (dict) – Dictionary to convert.

Returns:

Dictionary with boolean values replaced by 0 or 1.

Return type:

dict

Convert#

All functions for converting weather data into energy system model data.

atlite.convert.coefficient_of_performance(cutout: Cutout, source: HeatPumpSource = 'air', sink_T: float = 55.0, c0: float | None = None, c1: float | None = None, c2: float | None = None, **params: Any) ConvertResult#

Convert temperature to heat pump coefficient of performance (COP).

The COP is modelled as a quadratic function of the temperature difference dT = sink_T - source_T: COP = c0 + c1 * dT + c2 * dT**2.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • source ({"air", "soil"}) –

    Heat source type. Default coefficients per source:

    • "air": c0=6.81, c1=-0.121, c2=0.000630

    • "soil": c0=8.77, c1=-0.150, c2=0.000734

  • sink_T (float, default 55.0) – Heat sink temperature in °C.

  • c0 (float or None) – Constant regression coefficient. If None, uses source default.

  • c1 (float or None) – Linear regression coefficient. If None, uses source default.

  • c2 (float or None) – Quadratic regression coefficient. If None, uses source default.

  • **params (Any) – Additional keyword arguments passed to convert_and_aggregate().

Returns:

Coefficient of performance time-series (dimensionless).

Return type:

xr.DataArray

See also

heat_demand

Compute heating degree-day demand.

Note

This function also accepts all keyword arguments of convert_and_aggregate().

References

[1] Staffell, Brett, Brandon, Hawkes, A review of domestic heat pumps, Energy & Environmental Science (2012), 5, 9291-9306, https://doi.org/10.1039/C2EE22653G.

atlite.convert.convert_and_aggregate(cutout: Cutout, convert_func: Callable[..., Any], matrix: Any = None, index: Any = None, layout: Any = None, shapes: Any = None, shapes_crs: int = 4326, per_unit: bool = False, return_capacity: bool = False, aggregate_time: Literal['sum', 'mean', 'legacy'] | None = 'legacy', capacity_factor: bool = False, capacity_factor_timeseries: bool = False, show_progress: bool = False, dask_kwargs: dict[str, Any] | None = None, **convert_kwds: Any) ConvertResult#

Convert and aggregate a weather-based renewable generation time-series.

This is a gateway function called by the individual time-series generation functions like pv and wind. All parameters documented here are also available from those functions.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • convert_func (callable) – Callback like convert_wind, convert_pv.

  • matrix (N x S - xr.DataArray or sp.sparse.csr_matrix or None) – If given, it is used to aggregate the grid cells to buses. N is the number of buses, S the number of spatial coordinates, in the order of cutout.grid.

  • index (pd.Index) – Index of Buses.

  • layout (X x Y - xr.DataArray) – The capacity to be build in each of the grid_cells.

  • shapes (list or pd.Series of shapely.geometry.Polygon) – If given, matrix is constructed as indicatormatrix of the polygons, its index determines the bus index on the time-series.

  • shapes_crs (pyproj.CRS or compatible) – If different to the map crs of the cutout, the shapes are transformed to match cutout.crs (defaults to EPSG:4326).

  • per_unit (boolean) – Returns the time-series in per-unit units, instead of in MW (defaults to False).

  • return_capacity (boolean) – Additionally returns the installed capacity at each bus corresponding to layout (defaults to False).

  • aggregate_time ("sum", "mean", "legacy", or None) – Controls temporal aggregation of results. "sum" sums over time, "mean" averages over time, None returns full timeseries. "legacy" (default) preserves historical behavior: time-summed without spatial aggregation and full timeseries with spatial aggregation; this option is deprecated and will be removed in a future release. Replaces the deprecated capacity_factor and capacity_factor_timeseries parameters.

  • capacity_factor (boolean) – Deprecated. Use aggregate_time="mean" instead.

  • capacity_factor_timeseries (boolean) – Deprecated. Use aggregate_time=None instead (which is the default).

  • show_progress (boolean, default False) – Whether to show a progress bar.

  • dask_kwargs (dict, default {}) – Dict with keyword arguments passed to dask.compute.

  • **convert_kwds (Any) – Additional keyword arguments passed to convert_func.

Returns:

  • resource (xr.DataArray) – The return value depends on which arguments are provided:

    With aggregation (matrix, shapes, or layout given): Time-series of renewable generation aggregated to buses, with dimensions (bus, time). If aggregate_time is set, the time dimension is reduced accordingly.

    Without aggregation (none of the above given):

    • aggregate_time=None: per-cell timeseries (time, y, x).

    • aggregate_time="mean": time-averaged per cell (y, x).

    • aggregate_time="sum": time-summed per cell (y, x).

    Legacy behavior (deprecated):

    • aggregate_time="legacy": historical context-dependent default.

    • capacity_factor_timeseries=True: equivalent to aggregate_time=None.

    • capacity_factor=True: equivalent to aggregate_time="mean".

  • units (xr.DataArray (optional)) – The installed units per bus in MW corresponding to layout (only if return_capacity is True).

Raises:

ValueError – If deprecated parameters conflict or invalid arguments are provided.

See also

wind

Generate wind generation time-series.

pv

Generate solar PV generation time-series.

atlite.convert.convert_coefficient_of_performance(ds: xr.Dataset, source: HeatPumpSource, sink_T: float, c0: float | None, c1: float | None, c2: float | None) xr.DataArray#

Convert source temperatures to heat pump COP values.

Parameters:
  • ds (xr.Dataset) – Dataset containing the required temperature variables.

  • source ({"air", "soil"}) – Heat source used for the heat pump.

  • sink_T (float) – Sink temperature in degrees Celsius.

  • c0 (float or None) – Quadratic regression coefficients. If None, source-specific defaults are used.

  • c1 (float or None) – Quadratic regression coefficients. If None, source-specific defaults are used.

  • c2 (float or None) – Quadratic regression coefficients. If None, source-specific defaults are used.

Returns:

Coefficient of performance for each time step and grid cell.

Return type:

xr.DataArray

atlite.convert.convert_cooling_demand(ds: Dataset, threshold: float, a: float, constant: float, hour_shift: float) DataArray#

Convert ambient temperature to daily cooling demand by degree days.

Parameters:
  • ds (xr.Dataset) – Dataset containing temperature.

  • threshold (float) – Cooling threshold temperature in degrees Celsius.

  • a (float) – Linear scaling factor.

  • constant (float) – Constant demand component added to the result.

  • hour_shift (float) – Time shift in hours applied before daily averaging.

Returns:

Daily cooling demand in degree-day-like units.

Return type:

xr.DataArray

Notes

The formula is max(0, a * (T_daily_mean - threshold)) + constant where T_daily_mean is the daily-averaged temperature.

atlite.convert.convert_csp(ds, installation)#

Convert direct solar radiation to CSP specific generation.

Parameters:
  • ds (xr.Dataset) – Dataset containing direct radiation variables.

  • installation (dict) – CSP installation configuration.

Returns:

CSP output as specific yield (kWh/kW_ref), clipped to [0, 1].

Return type:

xr.DataArray

Raises:

ValueError – If the CSP technology option is not recognized.

atlite.convert.convert_dewpoint_temperature(ds: Dataset) DataArray#

Convert dew point temperature from Kelvin to degrees Celsius.

Parameters:

ds (xr.Dataset) – Dataset containing dewpoint temperature.

Returns:

Dew point temperature in degrees Celsius.

Return type:

xr.DataArray

atlite.convert.convert_heat_demand(ds: Dataset, threshold: float, a: float, constant: float, hour_shift: float) DataArray#

Convert ambient temperature to daily heat demand by degree days.

Parameters:
  • ds (xr.Dataset) – Dataset containing temperature.

  • threshold (float) – Heating threshold temperature in degrees Celsius.

  • a (float) – Linear scaling factor.

  • constant (float) – Constant demand component added to the result.

  • hour_shift (float) – Time shift in hours applied before daily averaging.

Returns:

Daily heat demand in degree-day-like units.

Return type:

xr.DataArray

Notes

The formula is max(0, a * (threshold - T_daily_mean)) + constant where T_daily_mean is the daily-averaged temperature.

atlite.convert.convert_irradiation(ds: xr.Dataset, orientation: Callable, tracking: TrackingType | None = None, irradiation: IrradiationType = 'total', trigon_model: TrigonModel = 'simple', clearsky_model: ClearskyModel | None = 'simple') xr.DataArray#

Convert weather data to irradiation on a tilted surface.

Parameters:
  • ds (xr.Dataset) – Dataset containing radiation and meteorological variables.

  • orientation (callable) – Surface orientation callback.

  • tracking ({None, "horizontal", "tilted_horizontal", "vertical", "dual"}, optional) – Tracking mode of the surface.

  • irradiation ({"total", "direct", "diffuse", "ground"}, default "total") – Irradiation component to return.

  • trigon_model (str, default "simple") – Trigonometric irradiation model.

  • clearsky_model (str or None, default "simple") – Clear-sky model used for diffuse irradiation.

Returns:

Tilted surface irradiation in W/m².

Return type:

xr.DataArray

atlite.convert.convert_line_rating(ds, psi, R, D=0.028, Ts=373, epsilon=0.6, alpha=0.6, per_unit=False)#

Convert weather data to dynamic line rating time series.

The formulation is based on: [1] “IEEE Std 738™-2012 (Revision of IEEE Std 738-2006/Incorporates IEEE Std

738-2012/Cor 1-2013), IEEE Standard for Calculating the Current-Temperature Relationship of Bare Overhead Conductors,” p. 72.

Simplifications: 1. Wind speed is taken at 100 m above ground, whereas transmission lines are

typically at 50-60 m.

  1. Solar heat influx is set proportional to solar short wave influx.

  2. Incidence angle of the solar heat influx is assumed to be 90°.

Parameters:
  • ds (xr.Dataset) – Dataset for the cells intersecting a line.

  • psi (float) – Line azimuth in degrees clockwise from north.

  • R (float) – Conductor resistance in Ω/m at temperature Ts.

  • D (float, default 0.028) – Conductor diameter in meters.

  • Ts (float, default 373) – Maximum conductor surface temperature in Kelvin.

  • epsilon (float, default 0.6) – Conductor emissivity (dimensionless).

  • alpha (float, default 0.6) – Conductor absorptivity (dimensionless).

  • per_unit (bool, default False) – Unused compatibility parameter.

Returns:

Maximum current per time step in ampere. When ds is an xr.Dataset the result is aggregated across intersecting cells via .min("spatial").

Return type:

xr.DataArray or numpy.ndarray

atlite.convert.convert_pv(ds: xr.Dataset, panel: dict[str, Any], orientation: Callable, tracking: TrackingType, trigon_model: TrigonModel = 'simple', clearsky_model: ClearskyModel | None = 'simple') xr.DataArray#

Convert weather data to photovoltaic specific generation.

Parameters:
  • ds (xr.Dataset) – Dataset containing radiation and temperature variables.

  • panel (dict) – Solar panel configuration.

  • orientation (callable) – Surface orientation callback.

  • tracking ({None, "horizontal", "tilted_horizontal", "vertical", "dual"}) – Tracking mode of the panel.

  • trigon_model (str, default "simple") – Trigonometric irradiation model.

  • clearsky_model (str or None, default "simple") – Clear-sky model used for diffuse irradiation.

Returns:

PV power output as capacity factors (unitless, 0–1).

Return type:

xr.DataArray

atlite.convert.convert_runoff(ds, weight_with_height=True)#

Convert runoff data, optionally weighting by surface height.

Parameters:
  • ds (xr.Dataset) – Dataset containing runoff and, if needed, height.

  • weight_with_height (bool, default True) – Whether to weight runoff by terrain height.

Returns:

Runoff field, optionally weighted by surface height.

Return type:

xr.DataArray

atlite.convert.convert_soil_temperature(ds: Dataset) DataArray#

Convert soil temperature from Kelvin to degrees Celsius.

Parameters:

ds (xr.Dataset) – Dataset containing soil temperature.

Returns:

Soil temperature in degrees Celsius with missing values filled by zero.

Return type:

xr.DataArray

atlite.convert.convert_solar_thermal(ds: xr.Dataset, orientation: Callable, trigon_model: TrigonModel, clearsky_model: ClearskyModel | None, c0: float, c1: float, t_store: float) xr.DataArray#

Convert weather data to solar thermal collector output.

Parameters:
  • ds (xr.Dataset) – Dataset containing radiation and temperature variables.

  • orientation (callable) – Surface orientation callback.

  • trigon_model (str) – Trigonometric irradiation model.

  • clearsky_model (str or None) – Clear-sky model used for diffuse irradiation.

  • c0 (float) – Collector efficiency parameters.

  • c1 (float) – Collector efficiency parameters.

  • t_store (float) – Storage temperature in degrees Celsius.

Returns:

Specific solar thermal output in W/m².

Return type:

xr.DataArray

Notes

Collector efficiency is eta = c0 - c1 * (T_store - T_amb) / G where G is the tilted irradiation. Output is max(0, G * eta).

atlite.convert.convert_temperature(ds: Dataset) DataArray#

Convert ambient air temperature from Kelvin to degrees Celsius.

Parameters:

ds (xr.Dataset) – Dataset containing temperature.

Returns:

Ambient temperature in degrees Celsius.

Return type:

xr.DataArray

atlite.convert.convert_wind(ds: xr.Dataset, turbine: TurbineConfig, interpolation_method: Literal['logarithmic', 'power']) xr.Dataset | xr.DataArray#

Convert wind speeds to turbine-specific generation.

Parameters:
  • ds (xr.Dataset) – Dataset containing wind speed data.

  • turbine (TurbineConfig) – Turbine configuration with power curve and hub height.

  • interpolation_method ({"logarithmic", "power"}) – Method used to extrapolate wind speed to hub height.

Returns:

Wind power output as specific yield per unit of installed capacity.

Return type:

xr.DataArray

atlite.convert.cooling_demand(cutout: Cutout, threshold: float = 23.0, a: float = 1.0, constant: float = 0.0, hour_shift: float = 0.0, **params: Any) ConvertResult#

Convert outside temperature into daily cooling demand using degree-day approximation.

The formula is max(0, a * (T_daily_mean - threshold)) + constant where T_daily_mean is the daily-averaged temperature. Output is in degree-day-like units (scaled by a).

Since “daily average temperature” means different things in different time zones, you can provide hour_shift to redefine when the day starts. E.g. for Moscow in summer hour_shift=3, for New York hour_shift=-4. The shift applies uniformly across all grid cells and times.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • threshold (float, default 23.0) – Outside temperature in °C below which there is no cooling demand. The default follows European computational practices (UK Met Office uses 22 °C, European Commission uses 24 °C).

  • a (float, default 1.0) – Linear factor relating cooling demand to outside temperature.

  • constant (float, default 0.0) – Constant part of cooling demand independent of outside temperature (e.g. ventilation).

  • hour_shift (float, default 0.0) – Time shift in hours relative to UTC for daily averaging.

  • **params (Any) – Additional keyword arguments passed to convert_and_aggregate().

Returns:

Daily cooling demand time-series in degree-day-like units.

Return type:

xr.DataArray

Warning

Because the original data is provided per month, at month boundaries there is untidiness when using a time shift. The resulting array will have duplicate indices for parts of the day at each boundary. You must re-average these based on the number of hours in each month.

See also

heat_demand

Degree-day heating demand.

Note

This function also accepts all keyword arguments of convert_and_aggregate().

atlite.convert.csp(cutout: Cutout, installation: str | CSPConfig, technology: Literal['parabolic trough', 'solar tower'] | None = None, **params: Any) ConvertResult#

Convert direct radiation into CSP generation time series.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • installation (str or xr.DataArray) – CSP installation details determining the solar field efficiency dependent on the local solar position. Can be a name accepted by atlite.resource.get_cspinstallationconfig() or an xr.DataArray with 'azimuth' (rad) and 'altitude' (rad) coordinates and an 'efficiency' (p.u.) entry.

  • technology ({"parabolic trough", "solar tower"} or None) – Overwrite CSP technology from the installation configuration. 'parabolic trough' uses direct horizontal irradiance (DHI), 'solar tower' uses direct normal irradiance (DNI).

  • **params – Additional keyword arguments passed to convert_and_aggregate.

Returns:

csp – CSP generation time-series in specific yield (kWh/kW_ref), clipped to [0, 1]. See convert_and_aggregate() for details on aggregation behaviour.

Return type:

xr.DataArray

Note

This function also accepts all keyword arguments of convert_and_aggregate().

References

[1] Tobias Hirsch (ed.). SolarPACES Guideline for Bankable STE Yield Assessment, IEA Technology Collaboration Programme SolarPACES, 2017. URL: https://www.solarpaces.org/csp-research-tasks/task-annexes-iea/task-i-solar-thermal-electric-systems/solarpaces-guideline-for-bankable-ste-yield-assessment/

[2] Tobias Hirsch (ed.). CSPBankability Project Report, DLR, 2017. URL: https://www.dlr.de/sf/en/desktopdefault.aspx/tabid-11126/19467_read-48251/

atlite.convert.dewpoint_temperature(cutout: Cutout, **params: Any) ConvertResult#

Return dew point temperature converted from Kelvin to degrees Celsius.

Parameters:
Returns:

Dew point temperature in °C.

Return type:

xr.DataArray

Note

This function also accepts all keyword arguments of convert_and_aggregate().

atlite.convert.heat_demand(cutout: Cutout, threshold: float = 15.0, a: float = 1.0, constant: float = 0.0, hour_shift: float = 0.0, **params: Any) ConvertResult#

Convert outside temperature into daily heat demand using degree-day approximation.

The formula is max(0, a * (threshold - T_daily_mean)) + constant where T_daily_mean is the daily-averaged temperature. Output is in degree-day-like units (scaled by a).

Since “daily average temperature” means different things in different time zones, you can provide hour_shift to redefine when the day starts. E.g. for Moscow in winter hour_shift=4, for New York hour_shift=-5. The shift applies uniformly across all grid cells and times.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • threshold (float, default 15.0) – Outside temperature in °C above which there is no heat demand.

  • a (float, default 1.0) – Linear factor relating heat demand to outside temperature.

  • constant (float, default 0.0) – Constant part of heat demand independent of outside temperature (e.g. water heating).

  • hour_shift (float, default 0.0) – Time shift in hours relative to UTC for daily averaging.

  • **params (Any) – Additional keyword arguments passed to convert_and_aggregate().

Returns:

Daily heat demand time-series in degree-day-like units.

Return type:

xr.DataArray

Warning

Because the original data is provided per month, at month boundaries there is untidiness when using a time shift. The resulting array will have duplicate indices for parts of the day at each boundary. You must re-average these based on the number of hours in each month.

See also

cooling_demand

Degree-day cooling demand.

Note

This function also accepts all keyword arguments of convert_and_aggregate().

atlite.convert.hydro(cutout, plants, hydrobasins, flowspeed=1, weight_with_height=False, show_progress=False, **kwargs)#

Compute inflow time series for plants by aggregating over catchment basins.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • plants (pd.DataFrame) – Run-of-river plants or dams with lon, lat columns.

  • hydrobasins (str|gpd.GeoDataFrame) – Filename or GeoDataFrame of one level of the HydroBASINS dataset.

  • flowspeed (float) – Average speed of water flows to estimate the water travel time from basin to plant (default: 1 m/s).

  • weight_with_height (bool) – Whether surface runoff should be weighted by potential height (probably better for coarser resolution).

  • show_progress (bool) – Whether to display progressbars.

  • **kwargs – Additional keyword arguments passed to convert_and_aggregate.

Returns:

Inflow time-series for each plant.

Return type:

xr.DataArray

References

[1] Liu, Hailiang, et al. “A validated high-resolution hydro power time-series model for energy systems analysis.” arXiv preprint arXiv:1901.08476 (2019).

[2] Lehner, B., Grill G. (2013): Global river hydrography and network routing: baseline data and new approaches to study the world’s large river systems. Hydrological Processes, 27(15): 2171–2186. Data is available at www.hydrosheds.org.

atlite.convert.irradiation(cutout: Cutout, orientation: OrientationName | dict[str, float] | Callable, irradiation: IrradiationType = 'total', tracking: TrackingType | None = None, clearsky_model: ClearskyModel | None = None, **params: Any) ConvertResult#

Calculate irradiation on a tilted surface.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • orientation (str, dict or callback) – Panel orientation can be chosen from either ‘latitude_optimal’, a constant orientation {‘slope’: 0.0, ‘azimuth’: 0.0} or a callback function with the same signature as the callbacks generated by the ‘atlite.pv.orientation.make_*’ functions.

  • irradiation (str) – The irradiation quantity to be returned. Defaults to “total” for total combined irradiation. Other options include “direct” for direct irradiation, “diffuse” for diffuse irradation, and “ground” for irradiation reflected by the ground via albedo. NOTE: “ground” irradiation is not calculated by all trigon_model options in the convert_irradiation method, so use with caution!

  • tracking (None or str:) – None for no tracking, default ‘horizontal’ for 1-axis horizontal tracking ‘tilted_horizontal’ for 1-axis horizontal tracking with tilted axis ‘vertical’ for 1-axis vertical tracking ‘dual’ for 2-axis tracking

  • clearsky_model (str or None) – Either the ‘simple’ or the ‘enhanced’ Reindl clearsky model. The default choice of None will choose dependending on data availability, since the ‘enhanced’ model also incorporates ambient air temperature and relative humidity.

  • **params (Any) – Additional keyword arguments passed to convert_and_aggregate.

Returns:

irradiation – Irradiation on the tilted surface in W/m².

Return type:

xr.DataArray

See also

pv

Photovoltaic generation.

solar_thermal

Solar thermal collector output.

Notes

The trigon_model is fixed to 'simple' internally.

Note

This function also accepts all keyword arguments of convert_and_aggregate().

References

[1] D.T. Reindl, W.A. Beckman, and J.A. Duffie. Diffuse fraction correla- tions. Solar Energy, 45(1):1 – 7, 1990.

atlite.convert.line_azimuth_degrees(shape: Any) float#

Return the line azimuth in degrees, measured clockwise from north.

Parameters:

shape (shapely.geometry.base.BaseGeometry) – Line geometry with at least two coordinates.

Returns:

Azimuth in degrees in the range (-180, 180].

Return type:

float

atlite.convert.line_rating(cutout, shapes, line_resistance, show_progress=False, dask_kwargs=None, **params)#

Create a dynamic line rating time series based on the IEEE-738 standard.

[1].

The steady-state capacity is derived from the balance between heat losses due to radiation and convection, and heat gains due to solar influx and conductur resistance. For more information on assumptions and modifications see convert_line_rating.

[1]“IEEE Std 738™-2012 (Revision of IEEE Std 738-2006/Incorporates IEEE Std

738-2012/Cor 1-2013), IEEE Standard for Calculating the Current-Temperature Relationship of Bare Overhead Conductors,” p. 72.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • shapes (geopandas.GeoSeries) – Line shapes of the lines.

  • line_resistance (float/series) – Resistance of the lines in Ohm/meter. Alternatively in p.u. system in Ohm/1000km (see example below).

  • show_progress (boolean, default False) – Whether to show a progress bar.

  • dask_kwargs (dict, default {}) – Dict with keyword arguments passed to dask.compute.

  • D (float, default 0.028) – Conductor diameter in meters.

  • Ts (float, default 373) – Maximum allowed conductor surface temperature in Kelvin.

  • epsilon (float, default 0.6) – Conductor emissivity (dimensionless).

  • alpha (float, default 0.6) – Conductor absorptivity (dimensionless).

  • **params (Any) – Additional keyword arguments passed to convert_line_rating().

Returns:

Thermal current limit time-series with dimensions (time, lines) in ampere.

Return type:

xr.DataArray

Note

This function also accepts all keyword arguments of convert_and_aggregate().

Example

>>> import pypsa
>>> import xarray as xr
>>> import atlite
>>> import numpy as np
>>> import geopandas as gpd
>>> from shapely.geometry import Point, LineString as Line
>>> n = pypsa.examples.scigrid_de()
>>> n.calculate_dependent_values()
>>> x = n.buses.x
>>> y = n.buses.y
>>> buses = n.lines[["bus0", "bus1"]].values
>>> shapes = [Line([Point(x[b0], y[b0]), Point(x[b1], y[b1])]) for (b0, b1) in buses]
>>> shapes = gpd.GeoSeries(shapes, index=n.lines.index)
>>> cutout = atlite.Cutout('test', x=slice(x.min(), x.max()), y=slice(y.min(), y.max()),
                        time='2020-01-01', module='era5', dx=1, dy=1)
>>> cutout.prepare()
>>> i = cutout.line_rating(shapes, n.lines.r/n.lines.length)
>>> v = xr.DataArray(n.lines.v_nom, dims='name')
>>> s = np.sqrt(3) * i * v / 1e3 # in MW
atlite.convert.maybe_progressbar(ds: Dataset | DataArray, show_progress: bool, **kwargs: Any) Dataset | DataArray#

Load a dataset or data array, optionally showing a dask progress bar.

Parameters:
  • ds (xr.Dataset or xr.DataArray) – Object backed by dask arrays.

  • show_progress (bool) – Whether to display a progress bar while loading.

  • **kwargs – Keyword arguments passed to load.

Returns:

Loaded object.

Return type:

xr.Dataset or xr.DataArray

atlite.convert.pv(cutout: Cutout, panel: str | PanelConfig, orientation: OrientationName | dict[str, float] | Callable, tracking: TrackingType | None = None, clearsky_model: ClearskyModel | None = None, **params: Any) ConvertResult#

Convert radiation and temperature into PV generation time series.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • panel (str or dict) – Panel config dictionary with the parameters for the electrical model in [3]. Alternatively, a name accepted by atlite.resource.get_solarpanelconfig().

  • orientation (str, dict or callback) – Panel orientation can be chosen from either ‘latitude_optimal’, a constant orientation {‘slope’: 0.0, ‘azimuth’: 0.0} or a callback function with the same signature as the callbacks generated by the ‘atlite.pv.orientation.make_*’ functions.

  • tracking (None or str:) – None for no tracking, default ‘horizontal’ for 1-axis horizontal tracking ‘tilted_horizontal’ for 1-axis horizontal tracking with tilted axis ‘vertical’ for 1-axis vertical tracking ‘dual’ for 2-axis tracking

  • clearsky_model (str or None) – Either the ‘simple’ or the ‘enhanced’ Reindl clearsky model. The default choice of None will choose dependending on data availability, since the ‘enhanced’ model also incorporates ambient air temperature and relative humidity.

  • **params (Any) – Additional keyword arguments passed to convert_and_aggregate.

Returns:

pv – PV generation time-series. Without aggregation, values are capacity factors (unitless, 0–1). With aggregation and per_unit=False, values are in MW. See convert_and_aggregate() for details.

Return type:

xr.DataArray

See also

wind

Wind generation.

irradiation

Tilted surface irradiation.

solar_thermal

Solar thermal collector output.

Note

This function also accepts all keyword arguments of convert_and_aggregate().

References

[1] Soteris A. Kalogirou. Solar Energy Engineering: Processes and Systems, pages 49–117,469–516. Academic Press, 2009. ISBN 0123745012.

[2] D.T. Reindl, W.A. Beckman, and J.A. Duffie. Diffuse fraction correla- tions. Solar Energy, 45(1):1 – 7, 1990.

[3] Hans Georg Beyer, Gerd Heilscher and Stefan Bofinger. A Robust Model for the MPP Performance of Different Types of PV-Modules Applied for the Performance Check of Grid Connected Systems, Freiburg, June 2004. Eurosun (ISES Europe Solar Congress).

Examples

Aggregate PV generation to bus regions:

>>> pv = cutout.pv(panel="CSi", orientation="latitude_optimal",
...                matrix=matrix, index=buses, per_unit=True)

Get per-cell capacity factor time series (no aggregation):

>>> cf = cutout.pv(panel="CSi", orientation="latitude_optimal",
...                aggregate_time=None)
>>> location_cf = cf.sel(x=6.9, y=53.1, method="nearest")
atlite.convert.runoff(cutout, smooth=None, lower_threshold_quantile=None, normalize_using_yearly=None, **params)#

Compute aggregated surface runoff with optional smoothing and normalization.

Parameters:
  • cutout (atlite.Cutout) – Cutout providing weather data with runoff variables.

  • smooth (bool or int, optional) – If True, apply a rolling mean with the default window of 24 * 7 time steps. If an integer, use it as the rolling window size. Default None (no smoothing).

  • lower_threshold_quantile (bool or float, optional) – If True, use the default quantile 5e-3. If a float, set values below that quantile to zero. Default None (no thresholding).

  • normalize_using_yearly (pd.Series, optional) – Annual country totals used to scale countries-indexed results over overlapping full years. One factor per country is derived from the summed reference values across the overlap.

  • **params – Additional keyword arguments passed to convert_and_aggregate(), including weight_with_height for the underlying runoff conversion.

Returns:

Runoff output from convert_and_aggregate. Smoothing also supports the tuple return form used with return_capacity=True. Thresholding and normalization are only supported for xr.DataArray results.

Return type:

xr.DataArray or tuple[xr.DataArray, xr.DataArray]

See also

convert_and_aggregate

General conversion/aggregation arguments.

atlite.convert.soil_temperature(cutout: Cutout, **params: Any) ConvertResult#

Return soil temperature converted from Kelvin to degrees Celsius.

Sea grid cells, where soil temperature is undefined, are filled with 0.0 so they do not contribute during spatial aggregation.

Parameters:
Returns:

Soil temperature in °C.

Return type:

xr.DataArray

Note

This function also accepts all keyword arguments of convert_and_aggregate().

atlite.convert.solar_thermal(cutout: Cutout, orientation: OrientationName | dict[str, float] | Callable | None = None, trigon_model: TrigonModel = 'simple', clearsky_model: ClearskyModel = 'simple', c0: float = 0.8, c1: float = 3.0, t_store: float = 80.0, **params: Any) ConvertResult#

Convert radiation and temperature into solar thermal collector time series.

Collector efficiency is eta = c0 - c1 * (T_store - T_amb) / G. Mathematical model and defaults for c0, c1 based on [1].

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • orientation (dict, str, or callable, optional) – Panel orientation. A dict with 'slope' and 'azimuth' keys in degrees, the string 'latitude_optimal', or a callable with the same signature as callbacks from atlite.pv.orientation.make_*. Default: {'slope': 45.0, 'azimuth': 180.0}.

  • trigon_model ({"simple", "perez"}, default "simple") – Trigonometric model for tilted irradiation decomposition.

  • clearsky_model ({"simple", "enhanced"} or None, default "simple") – Clear-sky model for diffuse irradiation. 'enhanced' also uses ambient temperature and relative humidity.

  • c0 (float, default 0.8) – Optical efficiency parameter.

  • c1 (float, default 3.0) – Thermal loss coefficient in W/(m² K).

  • t_store (float, default 80.0) – Storage temperature in °C.

  • **params (Any) – Additional keyword arguments passed to convert_and_aggregate().

Returns:

Solar thermal generation time-series.

Return type:

xr.DataArray

See also

pv

Photovoltaic generation.

irradiation

Tilted surface irradiation.

Note

This function also accepts all keyword arguments of convert_and_aggregate().

References

[1] Henning and Palzer, Renewable and Sustainable Energy Reviews 30 (2014) 1003-1018

atlite.convert.temperature(cutout: Cutout, **params: Any) ConvertResult#

Return ambient air temperature converted from Kelvin to degrees Celsius.

Parameters:
Returns:

Ambient temperature in °C.

Return type:

xr.DataArray

Note

This function also accepts all keyword arguments of convert_and_aggregate().

atlite.convert.wind(cutout: Cutout, turbine: str | Path | dict[str, Any], smooth: bool | dict[str, Any] = False, add_cutout_windspeed: bool = False, interpolation_method: Literal['logarithmic', 'power'] = 'logarithmic', **params: Any) ConvertResult#

Generate wind generation time-series.

Extrapolates wind speed to hub height (using logarithmic or power law) and evaluates the power curve.

Parameters:
  • cutout (atlite.Cutout) – The cutout to process.

  • turbine (str or dict) –

    A turbineconfig dictionary with the keys ‘hub_height’ for the hub height and ‘V’, ‘POW’ defining the power curve. Alternatively a str refering to a local or remote turbine configuration as accepted by atlite.resource.get_windturbineconfig(). Locally stored turbine configurations can also be modified with this function. E.g. to setup a different hub height from the one used in the yaml file,one would write

    ”turbine=get_windturbineconfig(“NREL_ReferenceTurbine_5MW_offshore”)|{“hub_height”:120}”

  • smooth (bool or dict) – If True smooth power curve with a gaussian kernel as determined for the Danish wind fleet to Delta_v = 1.27 and sigma = 2.29. A dict allows to tune these values.

  • add_cutout_windspeed (bool) – If True and in case the power curve does not end with a zero, will add zero power output at the highest wind speed in the power curve. If False, a warning will be raised if the power curve does not have a cut-out wind speed. The default is False.

  • interpolation_method ({"logarithmic", "power"}) – Law to interpolate wind speed to turbine hub height. Refer to atlite.wind.extrapolate_wind_speed().

  • **params (Any) – Additional keyword arguments passed to convert_and_aggregate.

Returns:

resource – Wind generation time-series. Without aggregation, values are capacity factors (MWh/MWp). With aggregation and per_unit=False, values are in MW. See convert_and_aggregate() for details.

Return type:

xr.DataArray

See also

pv

Photovoltaic generation.

Note

This function also accepts all keyword arguments of convert_and_aggregate().

References

Examples

Aggregate wind generation to bus regions:

>>> wind = cutout.wind(turbine="Vestas_V112_3MW", matrix=matrix,
...                    index=buses, per_unit=True)

Get per-cell capacity factor time series (no aggregation):

>>> cf = cutout.wind(turbine="Vestas_V112_3MW",
...                  aggregate_time=None)
>>> cf.dims
('time', 'y', 'x')
>>> location_cf = cf.sel(x=6.9, y=53.1, method="nearest")

Resource#

Module for accessing external resources like wind turbine and PV panel configurations.

atlite.resource.get_cspinstallationconfig(installation: str | PathLike) CSPConfig#

Load a CSP installation configuration from a YAML file.

Parameters:

installation (str or pathlib.Path) –

if str is provided the name of a preshipped CSP installation

from alite.resources.cspinstallation is expected.

if pathlib.Path is provided the configuration

is read from this local path instead

Returns:

config – Config with details on the CSP installation.

Return type:

dict

atlite.resource.get_oedb_windturbineconfig(search: int | str | None = None, **search_params: Any) TurbineConfig#

Download a windturbine configuration from the OEDB database.

Download the configuration of a windturbine model from the OEDB database into the local ‘windturbine_dir’. The OEDB database can be viewed here: https://openenergy-platform.org/dataedit/view/supply/wind_turbine_library (2019-07-22) Only one turbine configuration is downloaded at a time, if the search parameters yield an ambigious result, no data is downloaded.

Parameters:
  • search (int|str) – Smart search parameter, if int use as model id, if str look in name or turbine_type

  • **search_params (dict) – Recognized arguments are ‘id’, ‘name’, ‘turbine_type’ and ‘manufacturer’

Returns:

turbineconfig – The turbine configuration in the format from ‘atlite.ressource.get_turbineconf(name)’.

Return type:

dict

Example

>>> get_oedb_windturbineconfig(10)
{'V': ..., 'POW': ..., ...}
>>> get_oedb_windturbineconfig(name="E-53/800", manufacturer="Enercon")
{'V': ..., 'POW': ..., ...}
Raises:

RuntimeError – If no turbine or multiple turbines match the search.

atlite.resource.get_solarpanelconfig(panel: str | PathLike) PanelConfig#

Load the ‘panel’.yaml file from local disk and provide a solar panel dict.

Parameters:

panel (str or pathlib.Path) –

if str is provided the name of a preshipped panel

from alite.resources.solarpanel is expected.

if pathlib.Path is provided the configuration

is read from this local path instead

Returns:

config – Config with details on the solarpanel

Return type:

dict

atlite.resource.get_windturbineconfig(turbine: str | PathLike | dict[str, Any], add_cutout_windspeed: bool = True) TurbineConfig#

Load the wind ‘turbine’ configuration.

Parameters:
  • turbine (str or pathlib.Path or dict) –

    if str:

    The name of a preshipped turbine from alite.resources.windturbine . Alternatively, if a str starting with ‘oedb:<name>’ is passed the Open Energy Database is searched for a turbine with the matching ‘<name>’ and if found that turbine configuration is used. See atlite.resource.get_oedb_windturbineconfig(…)

    if pathlib.Path is provided the configuration is read from this local

    path instead

    if dict:

    a user provided config dict. Needs to have the keys “POW”, “V”, “P”, and “hub_height”. Values for “POW” and “V” need to be list or np.ndarray with equal length.

  • add_cutout_windspeed (bool = True) – If True and in case the power curve does not end with a zero, will add zero power output at the highest wind speed in the power curve. If False, a warning will be raised if the power curve does not have a cut-out wind speed.

Returns:

config – Config with details on the turbine

Return type:

dict

Raises:

KeyError – If turbine is not a str, Path, or dict.

atlite.resource.solarpanel_rated_capacity_per_unit(panel: str | PathLike | PanelConfig) float#

Return the rated capacity per unit of a solar panel configuration.

Parameters:

panel (str or pathlib.Path or dict) – Solar panel configuration or reference to one.

Returns:

Rated capacity per unit area or per panel, depending on the model.

Return type:

float

Raises:

ValueError – If the panel model is unknown.

atlite.resource.windturbine_rated_capacity_per_unit(turbine: str | PathLike | TurbineConfig) float#

Return the rated capacity of a wind turbine configuration.

Parameters:

turbine (str or pathlib.Path or dict) – Wind turbine configuration or reference to one.

Returns:

Rated turbine capacity.

Return type:

float

atlite.resource.windturbine_smooth(turbine: TurbineConfig, params: dict[str, float] | None | bool = None) TurbineConfig#

Smooth the powercurve in turbine with a gaussian kernel.

Parameters:
  • turbine (dict) – Turbine config with at least V and POW

  • params (dict) – Allows adjusting fleet availability eta, mean Delta_v and stdev sigma. Defaults to values from Andresen’s paper: 0.95, 1.27 and 2.29, respectively.

Returns:

turbine – Turbine config with a smoothed power curve

Return type:

dict

References

G. B. Andresen, A. A. Søndergaard, M. Greiner, Validation of Danish wind time series from a new global renewable energy atlas for energy system analysis, Energy 93, Part 1 (2015) 1074–1088.

Wind#

Functions for use in conjunction with wind data generation.

atlite.wind.extrapolate_wind_speed(ds: xr.Dataset, to_height: int | float, from_height: int | None = None, method: Literal['logarithmic', 'power'] = 'logarithmic') xr.DataArray#

Extrapolate the wind speed from a given height above ground to another.

If ds already contains a key refering to wind speeds at the desired to_height, no conversion is done and the wind speeds are directly returned.

Extrapolation of the wind speed can either use the “logarithmic” law as described in [1]_ or the “power” law as described in [2]. See also discussion in GH issue: PyPSA/atlite#231 .

Parameters:
  • ds (xarray.Dataset) – Dataset containing the wind speed time-series at ‘from_height’ with key ‘wnd{height:d}m’ and the surface orography with key ‘roughness’ at the geographic locations of the wind speeds.

  • to_height (int|float) – Height (m) to which the wind speeds are extrapolated to.

  • from_height (int, optional) – Height (m) from which the wind speeds are interpolated to ‘to_height’. If not provided, the closest height to ‘to_height’ is selected.

  • method ({"logarithmic", "power"}) – Method to use for extra/interpolating wind speeds

Returns:

da – DataArray containing the extrapolated wind speeds. Name of the DataArray is ‘wnd{to_height:d}’.

Return type:

xarray.DataArray

Raises:
  • AssertionError – If no wind speed variables are found in the dataset.

  • RuntimeError – If the cutout is missing the data for the chosen method.

  • ValueError – If method is not 'logarithmic' or 'power'.

References

GIS#

Functions for Geographic Information System.

class atlite.gis.ExclusionContainer(crs: CrsLike = 3035, res: float = 100)#

Container for exclusion objects and meta data.

add_geometry(geometry: PathLike | gpd.GeoDataFrame | gpd.GeoSeries, buffer: float = 0, invert: bool = False) None#

Register a collection of geometries to the ExclusionContainer.

Parameters:
  • geometry (str/path/geopandas.GeoDataFrame) – Path to geometries or geometries which to exclude.

  • buffer (float, optional) – Buffer around the excluded areas in units of ExclusionContainer.crs. The default is 0.

  • invert (bool, optional) – Whether to exclude (False) or include (True) the specified areas of the geometries. The default is False.

add_raster(raster: PathLike | rio.DatasetReader, codes: int | list[int] | Sequence[int] | Callable[[NDArray], NDArray] | None = None, buffer: float = 0, invert: bool = False, nodata: int = 255, allow_no_overlap: bool = False, crs: CrsLike | None = None) None#

Register a raster to the ExclusionContainer.

Parameters:
  • raster (str/rasterio.DatasetReader) – Raster or path to raster which to exclude.

  • codes (int/list/function, optional) – Codes in the raster which to exclude. Can be a callable function which takes the mask (np.array) as argument and performs a elementwise condition (must not change the shape). The function may not be an anonymous (lambda) function. The default is 1.

  • buffer (int, optional) – Buffer around the excluded areas in units of ExclusionContainer.crs. Use this to create a buffer around the excluded/included area. The default is 0.

  • nodata (int, optional) – Value to use for nodata pixels. The default is 255.

  • invert (bool, optional) – Whether to exclude (False) or include (True) the specified areas of the raster. The default is False.

  • allow_no_overlap – Allow that a raster and a shape (for which the raster will be used as a mask) do not overlap. In this case an array with only nodata is returned.

  • crs (rasterio.CRS/EPSG) – CRS of the raster. Specify this if the raster has invalid crs.

property all_closed: bool#

Check whether all files in the raster container are closed.

property all_open: bool#

Check whether all files in the raster container are open.

compute_shape_availability(geometry: gpd.GeoDataFrame | gpd.GeoSeries, dst_transform: rio.Affine | None = None, dst_crs: CrsLike | None = None, dst_shape: tuple[int, int] | None = None) tuple[NDArray, rio.Affine]#

Compute the eligible area in one or more geometries.

Parameters:
  • geometry (geopandas.Series) – Geometry of which the eligible area is computed. If the series contains more than one geometry, the eligible area of the combined geometries is computed.

  • dst_transform (rasterio.Affine) – Transform of the target raster. Define if the availability should be reprojected. Defaults to None.

  • dst_crs (rasterio.CRS/proj.CRS) – CRS of the target raster. Define if the availability should be reprojected. Defaults to None.

  • dst_shape (tuple) – Shape of the target raster. Define if the availability should be reprojected. Defaults to None.

Returns:

  • masked (np.array) – Mask whith eligible raster cells indicated by 1 and excluded cells by 0.

  • transform (rasterio.Affine) – Affine transform of the mask.

Raises:

ValueError – If only some of dst_transform, dst_crs, dst_shape are given.

open_files() None#

Open rasters and load geometries.

Raises:

ValueError – If a raster has an invalid CRS and none is provided.

plot_shape_availability(geometry: gpd.GeoDataFrame | gpd.GeoSeries, ax: Axes | None = None, set_title: bool = True, dst_transform: rio.Affine | None = None, dst_crs: CrsLike | None = None, dst_shape: tuple[int, int] | None = None, show_kwargs: dict[str, Any] | None = None, plot_kwargs: dict[str, Any] | None = None) Axes#

Plot the eligible area for one or more geometries.

This function uses its own default values for rasterio.plot.show and geopandas.GeoSeries.plot. Therefore eligible land is drawn in green Note that this function will likely fail if another CRS than the one of the ExclusionContainer is used in the axis (e.g. cartopy projections).

Parameters:
  • geometry (geopandas.Series) – Geometry of which the eligible area is computed. If the series contains more than one geometry, the eligible area of the combined geometries is computed.

  • ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, a new figure is created.

  • set_title (boolean, optional) – Whether to set the title with additional information on the share of eligible land.

  • dst_transform (rasterio.Affine) – Transform of the target raster. Define if the availability should be reprojected. Defaults to None.

  • dst_crs (rasterio.CRS/proj.CRS) – CRS of the target raster. Define if the availability should be reprojected. Defaults to None.

  • dst_shape (tuple) – Shape of the target raster. Define if the availability should be reprojected. Defaults to None.

  • show_kwargs (dict, optional) – Keyword arguments passed to rasterio.plot.show, by default {}

  • plot_kwargs (dict, optional) – Keyword arguments passed to geopandas.GeoSeries.plot, by default {}

Returns:

Axes with the plotted availability.

Return type:

matplotlib.axes.Axes

atlite.gis.compute_availabilitymatrix(cutout: Any, shapes: GeoDataFrame | GeoSeries, excluder: ExclusionContainer, nprocesses: int | None = None, disable_progressbar: bool = True) DataArray#

Compute the eligible share within cutout cells in the overlap with shapes.

For parallel calculation (nprocesses not None) the excluder must not be initialized and all raster references must be strings. Otherwise processes are colliding when reading from one common rasterio.DatasetReader.

Parameters:
  • cutout (atlite.Cutout) – Cutout which the availability matrix is aligned to.

  • shapes (geopandas.Series/geopandas.DataFrame) – Geometries for which the availabilities are calculated.

  • excluder (atlite.gis.ExclusionContainer) – Container of all meta data or objects which to exclude, i.e. rasters and geometries.

  • nprocesses (int, optional) – Number of processes to use for calculating the matrix. The paralle- lization can heavily boost the calculation speed. The default is None.

  • disable_progressbar (bool, optional) – Disable the progressbar if nprocesses is not None. Then the map function instead of the imap function is used for the multiprocessing pool. This speeds up the calculation.

Returns:

availabilities – DataArray of shape (|shapes|, |y|, |x|) containing all the eligible share of cutout cell (x,y) in the overlap with shape i.

Return type:

xr.DataArray

Notes

The rasterio (or GDAL) average downsampling returns different results dependent on how the target raster (the cutout raster) is spanned. Either it is spanned from the top left going downwards, e.g. Affine(0.25, 0, 0, 0, -0.25, 50), or starting in the lower left corner and going up, e.g. Affine(0.25, 0, 0, 0, 0.25, 50). Here we stick to the top down version which is why we use cutout.transform_r and flipping the y-axis in the end.

atlite.gis.compute_indicatormatrix(orig: gpd.GeoDataFrame | gpd.GeoSeries | Iterable[BaseGeometry], dest: gpd.GeoDataFrame | gpd.GeoSeries | Iterable[BaseGeometry], orig_crs: CrsLike = 4326, dest_crs: CrsLike = 4326) sp.sparse.lil_matrix#

Compute the indicatormatrix.

The indicatormatrix I[i,j] is a sparse representation of the ratio of the area in orig[j] lying in dest[i], where orig and dest are collections of polygons, i.e.

A value of I[i,j] = 1 indicates that the shape orig[j] is fully contained in shape dest[j].

Note that the polygons must be in the same crs.

Parameters:
  • orig (Collection of shapely polygons) – Origin polygons.

  • dest (Collection of shapely polygons) – Destination polygons.

  • orig_crs (int or CRS, default 4326) – CRS of the origin polygons.

  • dest_crs (int or CRS, default 4326) – CRS of the destination polygons.

Returns:

I – Indicatormatrix

Return type:

sp.sparse.lil_matrix

atlite.gis.compute_intersectionmatrix(orig: gpd.GeoDataFrame | gpd.GeoSeries | Iterable[BaseGeometry], dest: gpd.GeoDataFrame | gpd.GeoSeries | Iterable[BaseGeometry], orig_crs: CrsLike = 4326, dest_crs: CrsLike = 4326) sp.sparse.lil_matrix#

Compute the intersectionmatrix.

The intersectionmatrix is a sparse matrix with entries (i,j) being one if shapes orig[j] and dest[i] are intersecting, and zero otherwise.

Note that the polygons must be in the same crs.

Parameters:
  • orig (Collection of shapely polygons) – Origin polygons.

  • dest (Collection of shapely polygons) – Destination polygons.

  • orig_crs (int or CRS, default 4326) – CRS of the origin polygons.

  • dest_crs (int or CRS, default 4326) – CRS of the destination polygons.

Returns:

I – Intersectionmatrix

Return type:

sp.sparse.lil_matrix

atlite.gis.get_coords(x: slice, y: slice, time: slice, dx: float = 0.25, dy: float = 0.25, dt: str = 'h', **kwargs: Any) Dataset#

Create cutout coordinates from slices and resolutions.

Parameters:
  • x (slice) – Bounds of the x dimension.

  • y (slice) – Bounds of the y dimension.

  • time (slice) – Bounds of the time dimension.

  • dx (float, optional) – Step size of the x coordinate.

  • dy (float, optional) – Step size of the y coordinate.

  • dt (str, optional) – Frequency of the time coordinate.

  • **kwargs – Unused keyword arguments.

Returns:

Dataset containing x, y, and time coordinates.

Return type:

xarray.Dataset

atlite.gis.maybe_swap_spatial_dims(ds: Dataset | DataArray, namex: str = 'x', namey: str = 'y') Dataset | DataArray#

Ensure spatial coordinates follow atlite’s axis ordering.

Parameters:
  • ds (xarray.Dataset or xarray.DataArray) – Object with spatial coordinates.

  • namex (str, optional) – Name of the x dimension.

  • namey (str, optional) – Name of the y dimension.

Returns:

Input object with spatial dimensions reversed if needed.

Return type:

xarray.Dataset or xarray.DataArray

atlite.gis.pad_extent(src: NDArray, src_transform: rio.Affine, dst_transform: rio.Affine, src_crs: CrsLike, dst_crs: CrsLike, **kwargs: Any) tuple[NDArray, rio.Affine]#

Pad the extent of src by an equivalent of one cell of the target raster.

This ensures that the array is large enough to not be treated as nodata in all cells of the destination raster. If src.ndim > 2, the function expects the last two dimensions to be y, x.

Parameters:
  • src (numpy.ndarray) – Source array with spatial axes in the last two dimensions.

  • src_transform (rasterio.Affine) – Transform of the source array.

  • dst_transform (rasterio.Affine) – Transform of the destination raster.

  • src_crs (any) – Source coordinate reference system.

  • dst_crs (any) – Destination coordinate reference system.

  • **kwargs – Keyword arguments passed to numpy.pad.

Returns:

Padded array and updated affine transform.

Return type:

tuple

atlite.gis.padded_transform_and_shape(bounds: tuple[float, float, float, float], res: float) tuple[Affine, tuple[int, int]]#

Return a padded raster transform and shape.

Parameters:
  • bounds (tuple) – Bounding box as (left, bottom, right, top).

  • res (float) – Raster resolution.

Returns:

Affine transform and raster shape covering the padded bounds.

Return type:

tuple

atlite.gis.projected_mask(raster: rio.DatasetReader, geom: gpd.GeoSeries, transform: rio.Affine | None = None, shape: tuple[int, int] | None = None, crs: CrsLike | None = None, allow_no_overlap: bool = False, **kwargs: Any) tuple[NDArray, rio.Affine]#

Load a raster mask and optionally reproject it.

Parameters:
  • raster (rasterio.DatasetReader) – Raster source used to build the mask.

  • geom (geopandas.GeoSeries) – Geometry used for masking.

  • transform (rasterio.Affine, optional) – Target transform.

  • shape (tuple, optional) – Target array shape.

  • crs (any, optional) – Target coordinate reference system.

  • allow_no_overlap (bool, optional) – Whether to return a nodata mask when geometry and raster do not overlap.

  • **kwargs – Additional keyword arguments passed to rasterio.mask.mask.

Returns:

Masked array and its affine transform.

Return type:

tuple

atlite.gis.regrid(ds: Dataset | DataArray, dimx: Index, dimy: Index, **kwargs: Any) Dataset | DataArray#

Interpolate ds to a new spatial grid using rasterio’s reproject.

See also: https://mapbox.github.io/rasterio/topics/resampling.html

Parameters:
  • ds (xarray.Dataset or xarray.DataArray) – Data on a spatial grid.

  • dimx (pandas.Index) – Target x coordinates. dimx.name must match the source x dimension.

  • dimy (pandas.Index) – Target y coordinates. dimy.name must match the source y dimension.

  • **kwargs – Keyword arguments passed to rasterio.warp.reproject; of note: resampling is one of gis.Resampling.{average,cubic,bilinear,nearest}; src_crs and dst_crs define the source/target CRS (default: EPSG 4326, latlong).

Returns:

Regridded object on the target coordinates.

Return type:

xarray.Dataset or xarray.DataArray

atlite.gis.reproject_shapes(shapes: Iterable[BaseGeometry] | pd.Series | dict[Any, BaseGeometry], crs1: CrsLike, crs2: CrsLike) Iterable[BaseGeometry] | pd.Series | OrderedDict[Any, BaseGeometry]#

Reproject a collection of geometries.

Parameters:
  • shapes (iterable, pandas.Series, or dict) – Shapes to reproject.

  • crs1 (any) – Source coordinate reference system.

  • crs2 (any) – Target coordinate reference system.

Returns:

Reprojected shapes with the same container type where applicable.

Return type:

iterable, pandas.Series, or collections.OrderedDict

atlite.gis.shape_availability(geometry: gpd.GeoSeries, excluder: ExclusionContainer) tuple[NDArray, rio.Affine]#

Compute the eligible area in one or more geometries.

Parameters:
  • geometry (geopandas.Series) – Geometry of which the eligible area is computed. If the series contains more than one geometry, the eligible area of the combined geometries is computed.

  • excluder (atlite.gis.ExclusionContainer) – Container of all meta data or objects which to exclude, i.e. rasters and geometries.

Returns:

  • masked (np.array) – Mask whith eligible raster cells indicated by 1 and excluded cells by 0.

  • transform (rasterio.Affine) – Affine transform of the mask.

atlite.gis.shape_availability_reprojected(geometry: gpd.GeoSeries, excluder: ExclusionContainer, dst_transform: rio.Affine, dst_crs: CrsLike, dst_shape: tuple[int, int]) tuple[NDArray, rio.Affine]#

Compute and reproject the eligible area of one or more geometries.

The function executes shape_availability and reprojects the calculated mask onto a new raster defined by (dst_transform, dst_crs, dst_shape). Before reprojecting, the function pads the mask such that all non-nodata data points are projected in full cells of the target raster. This ensures that all data within the mask are projected correctly (GDAL inherent ‘problem’).

Parameters:
  • geometry (geopandas.GeoSeries) – Geometry for which availability is computed.

  • excluder (atlite.gis.ExclusionContainer) – Exclusion container defining masked areas.

  • dst_transform (rasterio.Affine) – Transform of the target raster.

  • dst_crs (any) – Coordinate reference system of the target raster.

  • dst_shape (tuple) – Shape of the target raster.

Returns:

Reprojected availability array and destination transform.

Return type:

tuple

atlite.gis.spdiag(v: NDArray | Sequence[float]) sp.sparse.csr_matrix#

Create a sparse diagonal matrix.

Parameters:

v (array-like) – Values placed on the diagonal.

Returns:

Sparse diagonal matrix with v on the diagonal.

Return type:

scipy.sparse.csr_matrix

Utils#

General utility functions for internal use.

class atlite.utils.CachedAttribute(method: Callable[[Any], Any], name: str | None = None, doc: str | None = None)#

Descriptor that computes an attribute value once and caches it on the instance.

Based on the Python Cookbook recipe by Denis Otkidach.

class atlite.utils.arrowdict#

Dict subclass enabling attribute-style access to items.

atlite.utils.ensure_coords(index: Index | Coordinates) Coordinates#

Convert an index or multiindex to coordinates.

Parameters:

index (pd.Index or xr.Coordinates) – The index or multiindex to convert.

Returns:

The converted coordinates.

Return type:

xr.Coordinates

Raises:

ValueError – If the index is not a pandas index or xarray coordinates.

atlite.utils.migrate_from_cutout_directory(old_cutout_dir: str | Path, path: str | Path) Dataset#

Convert an old-style cutout directory to a new-style netCDF file.

Parameters:
  • old_cutout_dir (str or Path) – Path to the legacy cutout directory containing meta.nc.

  • path (str or Path) – Output path for the migrated .nc file.

Returns:

The migrated cutout data.

Return type:

xr.Dataset

Raises:

MergeError – If automatic migration of multi-file datasets fails.

atlite.utils.timeindex_from_slice(timeslice: Any) DatetimeIndex#

Create an hourly DatetimeIndex from a slice with start/end month strings.

Parameters:

timeslice (slice) – Slice with start and end as month strings (e.g. "2013-01").

Returns:

Hourly index spanning the given months.

Return type:

pd.DatetimeIndex