<jupyter_start><jupyter_text>Extracting historical climate (rainfall) data over selected basins* **Products used:** ERA5  Getting startedTo run this analysis, run all the cells in the notebook, starting with the "Load packages" cell.   Load packagesImport Python packages that are used for the analysis.<jupyter_code>%matplotlib inline

import datacube
import matplotlib.pyplot as plt
import numpy as np
import geopandas as gpd

from deafrica_tools.spatial import xr_rasterize
from deafrica_tools.load_era5 import load_era5<jupyter_output>/env/lib/python3.8/site-packages/geopandas/_compat.py:106: UserWarning: The Shapely GEOS version (3.8.0-CAPI-1.13.1 ) is incompatible with the GEOS version PyGEOS was compiled with (3.9.1-CAPI-1.14.2). Conversions between both will be slow.
  warnings.warn(<jupyter_text>Analysis Parameters<jupyter_code># Original shapefile from https://data.apps.fao.org/map/catalog/srv/api/records/57bb1c95-2f00-4def-886f
vector_file = 'data/OB_FWR_Hydrography_Okavango_Subasins_polygon.geojson'

# define time period of interest
time_range = '2013-12', '2021-05-31'<jupyter_output><empty_output><jupyter_text>Define areas of interest in the Okavango Basin<jupyter_code># load basin polygons
# Original shapefile from https://data.apps.fao.org/map/catalog/srv/api/records/57bb1c95-2f00-4def-886f-caee3d756da9
basin = gpd.read_file(vector_file)

# upstream include Cuito and Cubango subbasins
upstream = basin[basin.Subbasin.isin(['Cuito', 'Cubango'])]

# delta is part of the Okavango subbasin
delta = basin[basin.Subbasin.isin(['Okavango'])]

print(upstream)<jupyter_output>CLASS_ID  Longitude   Latitude Subbasin      Sph_Area      Sph_Len  Parts  \
0         0  19.003252 -15.179938    Cuito  5.902293e+10  2285720.103    1.0   
1         0  17.870032 -15.740153  Cubango  1.078813e+11  3071839.684    1.0   

   Vertices                                           geometry  
0    9326.0  POLYGON ((17.85205 -13.53846, 17.85205 -13.536...  
1   11314.0  POLYGON ((15.99370 -13.93323, 15.99370 -13.931...<jupyter_text>Retrieve historical rainfall data over all areas of interest<jupyter_code># get historical rainfall for upstream and delta
bounds = upstream.append(delta).total_bounds
lat = bounds[1], bounds[3]
lon = bounds[0], bounds[2]
# download ERA5 rainfall and aggregate to monthly
var = 'precipitation_amount_1hour_Accumulation'
precip_1W = load_era5(var, lat, lon, time_range, reduce_func=np.sum, resample='1W').compute()

#resample to 3 month seasons
precip = precip_1W.resample(time='3M').sum()

# fix inconsistency in axis names
precip = precip.rename({'lat':'latitude', 'lon':'longitude'})
precip_1W = precip_1W.rename({'lat':'latitude', 'lon':'longitude'})<jupyter_output><empty_output><jupyter_text>Create area mask for upstream and okavango regions<jupyter_code>upstream_raster = xr_rasterize(upstream, precip)
delta_raster = xr_rasterize(delta, precip)<jupyter_output><empty_output><jupyter_text>Calculate the total rainfall over each area<jupyter_code>upstream_rainfall = precip[var].where(upstream_raster).sum(['latitude','longitude'])
okavango_rainfall = precip[var].where(delta_raster).sum(['latitude','longitude'])

upstream_rainfall_1W = precip_1W[var].where(upstream_raster).sum(['latitude','longitude'])
upstream_rainfall_1W = precip_1W[var].where(upstream_raster).sum(['latitude','longitude'])<jupyter_output><empty_output><jupyter_text>Export results as csv<jupyter_code>upstream_rainfall.to_dataframe().drop('spatial_ref',axis=1).rename({'precipitation_amount_1hour_Accumulation':'cumulative 3-month rainfall (mm)'},axis=1).to_csv(f'results/upstream_rainfall_{time_range[0]}_to_{time_range[1]}.csv')
okavango_rainfall.to_dataframe().drop('spatial_ref',axis=1).rename({'precipitation_amount_1hour_Accumulation':'cumulative 3-month rainfall (mm)'},axis=1).to_csv(f'results/okavango_rainfall_{time_range[0]}_to_{time_range[1]}.csv')

upstream_rainfall_1W.to_dataframe().drop('spatial_ref',axis=1).rename({'precipitation_amount_1hour_Accumulation':'cumulative 1-week rainfall (mm)'},axis=1).to_csv(f'results/upstream_rainfall_1W_{time_range[0]}_to_{time_range[1]}.csv')<jupyter_output><empty_output><jupyter_text>Visualize historical rainfall and compare to water extent changes<jupyter_code>upstream_rainfall.plot(label='Cuito + Cubango', marker='o', figsize=(20,8));
okavango_rainfall.plot(label='Okavango', marker='o');
plt.legend();<jupyter_output><empty_output><jupyter_text>*** Additional information**License:** The code in this notebook is licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0). Digital Earth Africa data is licensed under the [Creative Commons by Attribution 4.0](https://creativecommons.org/licenses/by/4.0/) license.**Contact:** If you need assistance, please post a question on the [Open Data Cube Slack channel](http://slack.opendatacube.org/) or on the [GIS Stack Exchange](https://gis.stackexchange.com/questions/ask?tags=open-data-cube) using the `open-data-cube` tag (you can view previously asked questions [here](https://gis.stackexchange.com/questions/tagged/open-data-cube)).If you would like to report an issue with this notebook, you can file one on [Github](https://github.com/digitalearthafrica/deafrica-sandbox-notebooks).**Compatible datacube version:**<jupyter_code>print(datacube.__version__)<jupyter_output>1.8.5<jupyter_text>**Last Tested:**<jupyter_code>from datetime import datetime
datetime.today().strftime('%Y-%m-%d')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12568306010928962, 'fraction_numerical': 0.04735883424408015, 'mean_word_length': 6.605263157894737, 'pattern_counts': {'":': 0, '<': 38, '<?xml version=': 0, '>': 38, 'https://': 7, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '547888', 'license': 'Apache-2.0', 'n_tokens_mistral': 2088, 'n_tokens_neox': 1914, 'n_words': 368, 'path': 'Use_cases/Okavango/3_Historical_rainfall.ipynb', 'repo_name': 'FlexiGroBots-H2020/deafrica-sandbox-notebooks', 'size': '5490'}