atlite 0.2.5__0-py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. atlite/__init__.py +31 -0
  2. atlite/aggregate.py +31 -0
  3. atlite/convert.py +617 -0
  4. atlite/cutout.py +607 -0
  5. atlite/data.py +188 -0
  6. atlite/datasets/__init__.py +9 -0
  7. atlite/datasets/cordex.py +221 -0
  8. atlite/datasets/era5.py +342 -0
  9. atlite/datasets/gebco.py +79 -0
  10. atlite/datasets/ncep.py +309 -0
  11. atlite/datasets/sarah.py +216 -0
  12. atlite/gis.py +674 -0
  13. atlite/hydro.py +108 -0
  14. atlite/pv/__init__.py +5 -0
  15. atlite/pv/irradiation.py +209 -0
  16. atlite/pv/orientation.py +125 -0
  17. atlite/pv/solar_panel_model.py +85 -0
  18. atlite/pv/solar_position.py +94 -0
  19. atlite/resource.py +321 -0
  20. atlite/resources/solarpanel/CSi.yaml +30 -0
  21. atlite/resources/solarpanel/CdTe.yaml +30 -0
  22. atlite/resources/solarpanel/KANENA.yaml +45 -0
  23. atlite/resources/windturbine/Bonus_B1000_1000kW.yaml +19 -0
  24. atlite/resources/windturbine/Enercon_E101_3000kW.yaml +19 -0
  25. atlite/resources/windturbine/Enercon_E126_7500kW.yaml +19 -0
  26. atlite/resources/windturbine/Enercon_E82_3000kW.yaml +19 -0
  27. atlite/resources/windturbine/NREL_ReferenceTurbine_5MW_offshore.yaml +19 -0
  28. atlite/resources/windturbine/Siemens_SWT_107_3600kW.yaml +19 -0
  29. atlite/resources/windturbine/Siemens_SWT_2300kW.yaml +19 -0
  30. atlite/resources/windturbine/Suzlon_S82_1.5_MW.yaml +19 -0
  31. atlite/resources/windturbine/Vestas_V112_3MW.yaml +19 -0
  32. atlite/resources/windturbine/Vestas_V112_3MW_offshore.yaml +19 -0
  33. atlite/resources/windturbine/Vestas_V164_7MW_offshore.yaml +19 -0
  34. atlite/resources/windturbine/Vestas_V25_200kW.yaml +19 -0
  35. atlite/resources/windturbine/Vestas_V47_660kW.yaml +19 -0
  36. atlite/resources/windturbine/Vestas_V66_1750kW.yaml +19 -0
  37. atlite/resources/windturbine/Vestas_V80_2MW_gridstreamer.yaml +19 -0
  38. atlite/resources/windturbine/Vestas_V90_3MW.yaml +19 -0
  39. atlite/utils.py +173 -0
  40. atlite/version.py +5 -0
  41. atlite/wind.py +85 -0
  42. atlite-0.2.5.0.dist-info/AUTHORS.rst +37 -0
  43. atlite-0.2.5.0.dist-info/METADATA +222 -0
  44. atlite-0.2.5.0.dist-info/RECORD +46 -0
  45. atlite-0.2.5.0.dist-info/WHEEL +6 -0
  46. atlite-0.2.5.0.dist-info/top_level.txt +1 -0
atlite/__init__.py ADDED
@@ -0,0 +1,31 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # SPDX-FileCopyrightText: 2016-2019 The Atlite Authors
4
+ #
5
+ # SPDX-License-Identifier: GPL-3.0-or-later
6
+
7
+ """
8
+ Atlite helps you to convert weather data into energy systems model data.
9
+
10
+ Atlite is a free software, xarray-based Python library for converting weather data
11
+ (like wind speeds) into energy systems data. It is designed to by lightweight and
12
+ work with big weather datasets while keeping the resource requirements especially
13
+ on CPU and RAM resources low.
14
+ """
15
+
16
+ from .cutout import Cutout
17
+ from .gis import compute_indicatormatrix, regrid, ExclusionContainer
18
+ from .resource import windturbines, solarpanels
19
+
20
+ from .version import version as __version__
21
+
22
+ __author__ = (
23
+ "The Atlite Authors: Gorm Andresen (Aarhus University), "
24
+ "Jonas Hoersch (FIAS/KIT/RLI), "
25
+ "Johannes Hampp (JLUG),"
26
+ "Fabian Hofmann (FIAS)"
27
+ "Tom Brown (FIAS/KIT), "
28
+ "Markus Schlott (FIAS), "
29
+ "David Schlachtberger (FIAS), "
30
+ )
31
+ __copyright__ = "Copyright 2016-2021 The Atlite Authors"
atlite/aggregate.py ADDED
@@ -0,0 +1,31 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # SPDX-FileCopyrightText: 2016-2019 The Atlite Authors
4
+ #
5
+ # SPDX-License-Identifier: GPL-3.0-or-later
6
+
7
+ """
8
+ Functions for aggregating results.
9
+ """
10
+
11
+ import xarray as xr
12
+ import dask
13
+
14
+
15
+ def aggregate_matrix(da, matrix, index):
16
+ if index.name is None:
17
+ index = index.rename("dim_0")
18
+ if isinstance(da.data, dask.array.core.Array):
19
+ da = da.stack(spatial=("y", "x"))
20
+ return xr.apply_ufunc(
21
+ lambda da: da * matrix.T,
22
+ da,
23
+ input_core_dims=[["spatial"]],
24
+ output_core_dims=[[index.name]],
25
+ dask="parallelized",
26
+ output_dtypes=[da.dtype],
27
+ dask_gufunc_kwargs=dict(output_sizes={index.name: index.size}),
28
+ ).assign_coords(**{index.name: index})
29
+ else:
30
+ da = da.stack(spatial=("y", "x")).transpose("spatial", "time")
31
+ return xr.DataArray(matrix * da, [index, da.coords["time"]])
atlite/convert.py ADDED
@@ -0,0 +1,617 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # SPDX-FileCopyrightText: 2016-2019 The Atlite Authors
4
+ #
5
+ # SPDX-License-Identifier: GPL-3.0-or-later
6
+
7
+ """
8
+ All functions for converting weather data into energy system model data.
9
+ """
10
+
11
+ import xarray as xr
12
+ import numpy as np
13
+ import pandas as pd
14
+ import geopandas as gpd
15
+ import datetime as dt
16
+ from operator import itemgetter
17
+ from pathlib import Path
18
+ from dask.diagnostics import ProgressBar
19
+ from scipy.sparse import csr_matrix
20
+
21
+ import logging
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ from .aggregate import aggregate_matrix
26
+ from .gis import spdiag
27
+
28
+ from .pv.solar_position import SolarPosition
29
+ from .pv.irradiation import TiltedIrradiation
30
+ from .pv.solar_panel_model import SolarPanelModel
31
+ from .pv.orientation import get_orientation, SurfaceOrientation
32
+
33
+ from . import hydro as hydrom
34
+ from . import wind as windm
35
+
36
+ from .resource import get_windturbineconfig, get_solarpanelconfig, windturbine_smooth
37
+
38
+
39
+ def convert_and_aggregate(
40
+ cutout,
41
+ convert_func,
42
+ matrix=None,
43
+ index=None,
44
+ layout=None,
45
+ shapes=None,
46
+ shapes_crs=4326,
47
+ per_unit=False,
48
+ return_capacity=False,
49
+ capacity_factor=False,
50
+ show_progress=True,
51
+ dask_kwargs={},
52
+ **convert_kwds,
53
+ ):
54
+ """
55
+ Convert and aggregate a weather-based renewable generation time-series.
56
+
57
+ NOTE: Not meant to be used by the user him or herself. Rather it is a
58
+ gateway function that is called by all the individual time-series
59
+ generation functions like pv and wind. Thus, all its parameters are also
60
+ available from these.
61
+
62
+ Parameters
63
+ -----------
64
+ matrix : N x S - xr.DataArray or sp.sparse.csr_matrix or None
65
+ If given, it is used to aggregate the grid cells to buses.
66
+ N is the number of buses, S the number of spatial coordinates, in the
67
+ order of `cutout.grid`.
68
+ index : pd.Index
69
+ Index of Buses.
70
+ layout : X x Y - xr.DataArray
71
+ The capacity to be build in each of the `grid_cells`.
72
+ shapes : list or pd.Series of shapely.geometry.Polygon
73
+ If given, matrix is constructed as indicatormatrix of the polygons, its
74
+ index determines the bus index on the time-series.
75
+ shapes_crs : pyproj.CRS or compatible
76
+ If different to the map crs of the cutout, the shapes are
77
+ transformed to match cutout.crs (defaults to EPSG:4326).
78
+ per_unit : boolean
79
+ Returns the time-series in per-unit units, instead of in MW (defaults
80
+ to False).
81
+ return_capacity : boolean
82
+ Additionally returns the installed capacity at each bus corresponding
83
+ to `layout` (defaults to False).
84
+ capacity_factor : boolean
85
+ If True, the static capacity factor of the chosen resource for each
86
+ grid cell is computed.
87
+ show_progress : boolean, default True
88
+ Whether to show a progress bar.
89
+ dask_kwargs : dict, default {}
90
+ Dict with keyword arguments passed to `dask.compute`.
91
+
92
+ Other Parameters
93
+ -----------------
94
+ convert_func : Function
95
+ Callback like convert_wind, convert_pv
96
+
97
+
98
+ Returns
99
+ -------
100
+ resource : xr.DataArray
101
+ Time-series of renewable generation aggregated to buses, if
102
+ `matrix` or equivalents are provided else the total sum of
103
+ generated energy.
104
+ units : xr.DataArray (optional)
105
+ The installed units per bus in MW corresponding to `layout`
106
+ (only if `return_capacity` is True).
107
+
108
+ """
109
+
110
+ func_name = convert_func.__name__.replace("convert_", "")
111
+ logger.info(f"Convert and aggregate '{func_name}'.")
112
+ da = convert_func(cutout.data, **convert_kwds)
113
+
114
+ no_args = all(v is None for v in [layout, shapes, matrix])
115
+
116
+ if no_args:
117
+ if per_unit or return_capacity:
118
+ raise ValueError(
119
+ "One of `matrix`, `shapes` and `layout` must be "
120
+ "given for `per_unit` or `return_capacity`"
121
+ )
122
+ if capacity_factor:
123
+ return maybe_progressbar(da.mean("time"), show_progress, **dask_kwargs)
124
+ else:
125
+ return maybe_progressbar(da.sum("time"), show_progress, **dask_kwargs)
126
+
127
+ if shapes is not None:
128
+ geoseries_like = (pd.Series, gpd.GeoDataFrame, gpd.GeoSeries)
129
+ if isinstance(shapes, geoseries_like) and index is None:
130
+ index = shapes.index
131
+ matrix = cutout.indicatormatrix(shapes, shapes_crs)
132
+
133
+ if layout is not None:
134
+ assert isinstance(layout, xr.DataArray)
135
+ layout = layout.reindex_like(cutout.data).stack(spatial=["y", "x"])
136
+ if matrix is None:
137
+ matrix = layout.expand_dims("new")
138
+ else:
139
+ matrix = csr_matrix(matrix) * spdiag(layout)
140
+
141
+ index = pd.RangeIndex(matrix.shape[0]) if index is None else index
142
+ matrix = csr_matrix(matrix)
143
+ results = aggregate_matrix(da, matrix=matrix, index=index)
144
+
145
+ if per_unit or return_capacity:
146
+ caps = matrix.sum(-1)
147
+ capacity = xr.DataArray(np.asarray(caps).flatten(), [index])
148
+ capacity.attrs["units"] = "MW"
149
+
150
+ if per_unit:
151
+ results = (results / capacity.where(capacity != 0)).fillna(0.0)
152
+ results.attrs["units"] = "p.u."
153
+ else:
154
+ results.attrs["units"] = "MW"
155
+
156
+ if return_capacity:
157
+ return maybe_progressbar(results, show_progress, **dask_kwargs), capacity
158
+ else:
159
+ return maybe_progressbar(results, show_progress, **dask_kwargs)
160
+
161
+
162
+ def maybe_progressbar(ds, show_progress, **kwargs):
163
+ """Load a xr.dataset with dask arrays either with or without progressbar."""
164
+ if show_progress:
165
+ with ProgressBar(minimum=2):
166
+ ds.load(**kwargs)
167
+ else:
168
+ ds.load(**kwargs)
169
+ return ds
170
+
171
+
172
+ # temperature
173
+ def convert_temperature(ds):
174
+ """Return outside temperature (useful for e.g. heat pump T-dependent
175
+ coefficient of performance).
176
+ """
177
+
178
+ # Temperature is in Kelvin
179
+ return ds["temperature"] - 273.15
180
+
181
+
182
+ def temperature(cutout, **params):
183
+ return cutout.convert_and_aggregate(convert_func=convert_temperature, **params)
184
+
185
+
186
+ # soil temperature
187
+ def convert_soil_temperature(ds):
188
+ """Return soil temperature (useful for e.g. heat pump T-dependent
189
+ coefficient of performance).
190
+ """
191
+
192
+ # Temperature is in Kelvin
193
+
194
+ # There are nans where there is sea; by setting them
195
+ # to zero we guarantee they do not contribute when multiplied
196
+ # by matrix in atlite/aggregate.py
197
+ return (ds["soil temperature"] - 273.15).fillna(0.0)
198
+
199
+
200
+ def soil_temperature(cutout, **params):
201
+ return cutout.convert_and_aggregate(convert_func=convert_soil_temperature, **params)
202
+
203
+
204
+ # heat demand
205
+ def convert_heat_demand(ds, threshold, a, constant, hour_shift):
206
+ # Temperature is in Kelvin; take daily average
207
+ T = ds["temperature"]
208
+ T = T.assign_coords(
209
+ time=(T.coords["time"] + np.timedelta64(dt.timedelta(hours=hour_shift)))
210
+ )
211
+
212
+ T = T.resample(time="1D").mean(dim="time")
213
+ threshold += 273.15
214
+ heat_demand = a * (threshold - T)
215
+
216
+ heat_demand = heat_demand.clip(min=0.0)
217
+
218
+ return (constant + heat_demand).rename("heat_demand")
219
+
220
+
221
+ def heat_demand(cutout, threshold=15.0, a=1.0, constant=0.0, hour_shift=0.0, **params):
222
+ """
223
+ Convert outside temperature into daily heat demand using the
224
+ degree-day approximation.
225
+
226
+ Since "daily average temperature" means different things in
227
+ different time zones and since xarray coordinates do not handle
228
+ time zones gracefully like pd.DateTimeIndex, you can provide an
229
+ hour_shift to redefine when the day starts.
230
+
231
+ E.g. for Moscow in winter, hour_shift = 4, for New York in winter,
232
+ hour_shift = -5
233
+
234
+ This time shift applies across the entire spatial scope of ds for
235
+ all times. More fine-grained control will be built in a some
236
+ point, i.e. space- and time-dependent time zones.
237
+
238
+ WARNING: Because the original data is provided every month, at the
239
+ month boundaries there is untidiness if you use a time shift. The
240
+ resulting xarray will have duplicates in the index for the parts
241
+ of the day in each month at the boundary. You will have to
242
+ re-average these based on the number of hours in each month for
243
+ the duplicated day.
244
+
245
+ Parameters
246
+ ----------
247
+ threshold : float
248
+ Outside temperature in degrees Celsius above which there is no
249
+ heat demand.
250
+ a : float
251
+ Linear factor relating heat demand to outside temperature.
252
+ constant : float
253
+ Constant part of heat demand that does not depend on outside
254
+ temperature (e.g. due to water heating).
255
+ hour_shift : float
256
+ Time shift relative to UTC for taking daily average
257
+
258
+ Note
259
+ ----
260
+ You can also specify all of the general conversion arguments
261
+ documented in the `convert_and_aggregate` function.
262
+ """
263
+
264
+ return cutout.convert_and_aggregate(
265
+ convert_func=convert_heat_demand,
266
+ threshold=threshold,
267
+ a=a,
268
+ constant=constant,
269
+ hour_shift=hour_shift,
270
+ **params,
271
+ )
272
+
273
+
274
+ # solar thermal collectors
275
+ def convert_solar_thermal(
276
+ ds, orientation, trigon_model, clearsky_model, c0, c1, t_store
277
+ ):
278
+ # convert storage temperature to Kelvin in line with reanalysis data
279
+ t_store += 273.15
280
+
281
+ # Downward shortwave radiation flux is in W/m^2
282
+ # http://rda.ucar.edu/datasets/ds094.0/#metadata/detailed.html?_do=y
283
+ solar_position = SolarPosition(ds)
284
+ surface_orientation = SurfaceOrientation(ds, solar_position, orientation)
285
+ irradiation = TiltedIrradiation(
286
+ ds, solar_position, surface_orientation, trigon_model, clearsky_model
287
+ )
288
+
289
+ # overall efficiency; can be negative, so need to remove negative values
290
+ # below
291
+ eta = c0 - c1 * (
292
+ (t_store - ds["temperature"]) / irradiation.where(irradiation != 0)
293
+ ).fillna(0)
294
+
295
+ output = irradiation * eta
296
+
297
+ return output.where(output > 0.0, 0.0)
298
+
299
+
300
+ def solar_thermal(
301
+ cutout,
302
+ orientation={"slope": 45.0, "azimuth": 180.0},
303
+ trigon_model="simple",
304
+ clearsky_model="simple",
305
+ c0=0.8,
306
+ c1=3.0,
307
+ t_store=80.0,
308
+ **params,
309
+ ):
310
+ """
311
+ Convert downward short-wave radiation flux and outside temperature
312
+ into time series for solar thermal collectors.
313
+
314
+ Mathematical model and defaults for c0, c1 based on model in [1].
315
+
316
+ Parameters
317
+ ----------
318
+ cutout : cutout
319
+ orientation : dict or str or function
320
+ Panel orientation with slope and azimuth (units of degrees), or
321
+ 'latitude_optimal'.
322
+ trigon_model : str
323
+ Type of trigonometry model
324
+ clearsky_model : str or None
325
+ Type of clearsky model for diffuse irradiation. Either
326
+ 'simple' or 'enhanced'.
327
+ c0, c1 : float
328
+ Parameters for model in [1] (defaults to 0.8 and 3., respectively)
329
+ t_store : float
330
+ Store temperature in degree Celsius
331
+
332
+ Note
333
+ ----
334
+ You can also specify all of the general conversion arguments
335
+ documented in the `convert_and_aggregate` function.
336
+
337
+ References
338
+ ----------
339
+ [1] Henning and Palzer, Renewable and Sustainable Energy Reviews 30
340
+ (2014) 1003-1018
341
+ """
342
+
343
+ if not callable(orientation):
344
+ orientation = get_orientation(orientation)
345
+
346
+ return cutout.convert_and_aggregate(
347
+ convert_func=convert_solar_thermal,
348
+ orientation=orientation,
349
+ trigon_model=trigon_model,
350
+ clearsky_model=clearsky_model,
351
+ c0=c0,
352
+ c1=c1,
353
+ t_store=t_store,
354
+ **params,
355
+ )
356
+
357
+
358
+ # wind
359
+ def convert_wind(ds, turbine):
360
+ """Convert wind speeds for turbine to wind energy generation."""
361
+
362
+ V, POW, hub_height, P = itemgetter("V", "POW", "hub_height", "P")(turbine)
363
+
364
+ wnd_hub = windm.extrapolate_wind_speed(ds, to_height=hub_height)
365
+
366
+ def _interpolate(da):
367
+ return np.interp(da, V, POW / P)
368
+
369
+ return xr.apply_ufunc(
370
+ _interpolate,
371
+ wnd_hub,
372
+ input_core_dims=[[]],
373
+ output_core_dims=[[]],
374
+ output_dtypes=[wnd_hub.dtype],
375
+ dask="parallelized",
376
+ )
377
+
378
+
379
+ def wind(cutout, turbine, smooth=False, **params):
380
+ """
381
+ Generate wind generation time-series
382
+
383
+ Extrapolates 10m wind speed with monthly surface roughness to hub
384
+ height and evaluates the power curve.
385
+
386
+ Parameters
387
+ ----------
388
+ turbine : str or dict
389
+ A turbineconfig dictionary with the keys 'hub_height' for the
390
+ hub height and 'V', 'POW' defining the power curve.
391
+ Alternatively a str refering to a local or remote turbine configuration
392
+ as accepted by atlite.resource.get_windturbineconfig().
393
+ smooth : bool or dict
394
+ If True smooth power curve with a gaussian kernel as
395
+ determined for the Danish wind fleet to Delta_v = 1.27 and
396
+ sigma = 2.29. A dict allows to tune these values.
397
+
398
+ Note
399
+ ----
400
+ You can also specify all of the general conversion arguments
401
+ documented in the `convert_and_aggregate` function.
402
+
403
+ References
404
+ ----------
405
+ [1] Andresen G B, Søndergaard A A and Greiner M 2015 Energy 93, Part 1
406
+ 1074 – 1088. doi:10.1016/j.energy.2015.09.071
407
+ """
408
+
409
+ if isinstance(turbine, (str, Path)):
410
+ turbine = get_windturbineconfig(turbine)
411
+
412
+ if smooth:
413
+ turbine = windturbine_smooth(turbine, params=smooth)
414
+
415
+ return cutout.convert_and_aggregate(
416
+ convert_func=convert_wind, turbine=turbine, **params
417
+ )
418
+
419
+
420
+ # solar PV
421
+ def convert_pv(ds, panel, orientation, trigon_model="simple", clearsky_model="simple"):
422
+ solar_position = SolarPosition(ds)
423
+ surface_orientation = SurfaceOrientation(ds, solar_position, orientation)
424
+ irradiation = TiltedIrradiation(
425
+ ds,
426
+ solar_position,
427
+ surface_orientation,
428
+ trigon_model=trigon_model,
429
+ clearsky_model=clearsky_model,
430
+ )
431
+ solar_panel = SolarPanelModel(ds, irradiation, panel)
432
+ return solar_panel
433
+
434
+
435
+ def pv(cutout, panel, orientation, clearsky_model=None, **params):
436
+ """
437
+ Convert downward-shortwave, upward-shortwave radiation flux and
438
+ ambient temperature into a pv generation time-series.
439
+
440
+ Parameters
441
+ ----------
442
+ panel : str or dict
443
+ Panel config dictionary with the parameters for the electrical
444
+ model in [3]. Alternatively, name of yaml file stored in
445
+ atlite.config.solarpanel_dir.
446
+ orientation : str, dict or callback
447
+ Panel orientation can be chosen from either
448
+ 'latitude_optimal', a constant orientation {'slope': 0.0,
449
+ 'azimuth': 0.0} or a callback function with the same signature
450
+ as the callbacks generated by the
451
+ 'atlite.pv.orientation.make_*' functions.
452
+ clearsky_model : str or None
453
+ Either the 'simple' or the 'enhanced' Reindl clearsky
454
+ model. The default choice of None will choose dependending on
455
+ data availability, since the 'enhanced' model also
456
+ incorporates ambient air temperature and relative humidity.
457
+
458
+ Returns
459
+ -------
460
+ pv : xr.DataArray
461
+ Time-series or capacity factors based on additional general
462
+ conversion arguments.
463
+
464
+ Note
465
+ ----
466
+ You can also specify all of the general conversion arguments
467
+ documented in the `convert_and_aggregate` function.
468
+
469
+ References
470
+ ----------
471
+ [1] Soteris A. Kalogirou. Solar Energy Engineering: Processes and Systems,
472
+ pages 49–117,469–516. Academic Press, 2009. ISBN 0123745012.
473
+
474
+ [2] D.T. Reindl, W.A. Beckman, and J.A. Duffie. Diffuse fraction correla-
475
+ tions. Solar Energy, 45(1):1 – 7, 1990.
476
+
477
+ [3] Hans Georg Beyer, Gerd Heilscher and Stefan Bofinger. A Robust Model
478
+ for the MPP Performance of Different Types of PV-Modules Applied for
479
+ the Performance Check of Grid Connected Systems, Freiburg, June 2004.
480
+ Eurosun (ISES Europe Solar Congress).
481
+ """
482
+
483
+ if isinstance(panel, (str, Path)):
484
+ panel = get_solarpanelconfig(panel)
485
+ if not callable(orientation):
486
+ orientation = get_orientation(orientation)
487
+
488
+ return cutout.convert_and_aggregate(
489
+ convert_func=convert_pv,
490
+ panel=panel,
491
+ orientation=orientation,
492
+ clearsky_model=clearsky_model,
493
+ **params,
494
+ )
495
+
496
+
497
+ # hydro
498
+ def convert_runoff(ds, weight_with_height=True):
499
+ runoff = ds["runoff"]
500
+
501
+ if weight_with_height:
502
+ runoff = runoff * ds["height"]
503
+
504
+ return runoff
505
+
506
+
507
+ def runoff(
508
+ cutout,
509
+ smooth=None,
510
+ lower_threshold_quantile=None,
511
+ normalize_using_yearly=None,
512
+ **params,
513
+ ):
514
+ result = cutout.convert_and_aggregate(convert_func=convert_runoff, **params)
515
+
516
+ if smooth is not None:
517
+ if smooth is True:
518
+ smooth = 24 * 7
519
+ if "return_capacity" in params.keys():
520
+ result = result[0].rolling(time=smooth, min_periods=1).mean(), result[1]
521
+ else:
522
+ result = result.rolling(time=smooth, min_periods=1).mean()
523
+
524
+ if lower_threshold_quantile is not None:
525
+ if lower_threshold_quantile is True:
526
+ lower_threshold_quantile = 5e-3
527
+ lower_threshold = pd.Series(result.values.ravel()).quantile(
528
+ lower_threshold_quantile
529
+ )
530
+ result = result.where(result >= lower_threshold, 0.0)
531
+
532
+ if normalize_using_yearly is not None:
533
+ normalize_using_yearly_i = normalize_using_yearly.index
534
+ if isinstance(normalize_using_yearly_i, pd.DatetimeIndex):
535
+ normalize_using_yearly_i = normalize_using_yearly_i.year
536
+ else:
537
+ normalize_using_yearly_i = normalize_using_yearly_i.astype(int)
538
+
539
+ years = (
540
+ pd.Series(pd.to_datetime(result.coords["time"].values).year)
541
+ .value_counts()
542
+ .loc[lambda x: x > 8700]
543
+ .index.intersection(normalize_using_yearly_i)
544
+ )
545
+ assert len(years), "Need at least a full year of data (more is better)"
546
+ years_overlap = slice(str(min(years)), str(max(years)))
547
+
548
+ dim = result.dims[1 - result.get_axis_num("time")]
549
+ result *= (
550
+ xr.DataArray(normalize_using_yearly.loc[years_overlap].sum(), dims=[dim])
551
+ / result.sel(time=years_overlap).sum("time")
552
+ ).reindex(countries=result.coords["countries"])
553
+
554
+ return result
555
+
556
+
557
+ def hydro(
558
+ cutout,
559
+ plants,
560
+ hydrobasins,
561
+ flowspeed=1,
562
+ weight_with_height=False,
563
+ show_progress=True,
564
+ **kwargs,
565
+ ):
566
+ """
567
+ Compute inflow time-series for `plants` by aggregating over catchment
568
+ basins from `hydrobasins`
569
+
570
+ Parameters
571
+ ----------
572
+ plants : pd.DataFrame
573
+ Run-of-river plants or dams with lon, lat columns.
574
+ hydrobasins : str|gpd.GeoDataFrame
575
+ Filename or GeoDataFrame of one level of the HydroBASINS dataset.
576
+ flowspeed : float
577
+ Average speed of water flows to estimate the water travel time from
578
+ basin to plant (default: 1 m/s).
579
+ weight_with_height : bool
580
+ Whether surface runoff should be weighted by potential height (probably
581
+ better for coarser resolution).
582
+ show_progress : bool
583
+ Whether to display progressbars.
584
+
585
+ References
586
+ ----------
587
+ [1] Liu, Hailiang, et al. "A validated high-resolution hydro power
588
+ time-series model for energy systems analysis." arXiv preprint
589
+ arXiv:1901.08476 (2019).
590
+
591
+ [2] Lehner, B., Grill G. (2013): Global river hydrography and network
592
+ routing: baseline data and new approaches to study the world’s large river
593
+ systems. Hydrological Processes, 27(15): 2171–2186. Data is available at
594
+ www.hydrosheds.org.
595
+ """
596
+ basins = hydrom.determine_basins(plants, hydrobasins, show_progress=show_progress)
597
+
598
+ matrix = cutout.indicatormatrix(basins.shapes)
599
+ # compute the average surface runoff in each basin
600
+ matrix_normalized = matrix / matrix.sum(axis=1)
601
+ runoff = cutout.runoff(
602
+ matrix=matrix_normalized,
603
+ index=basins.shapes.index,
604
+ weight_with_height=weight_with_height,
605
+ show_progress=show_progress,
606
+ **kwargs,
607
+ )
608
+ # The hydrological parameters are in units of "m of water per day" and so
609
+ # they should be multiplied by 1000 and the basin area to convert to m3
610
+ # d-1 = m3 h-1 / 24
611
+ runoff *= (1000.0 / 24.0) * xr.DataArray(
612
+ basins.shapes.to_crs(dict(proj="cea")).area
613
+ )
614
+
615
+ return hydrom.shift_and_aggregate_runoff_for_plants(
616
+ basins, runoff, flowspeed, show_progress
617
+ )