|
1 | 1 | import os |
2 | 2 | import cdsapi |
3 | | -import concurrent.futures |
4 | | - |
5 | | -# Most of the code here comes from Abdelrahman's library. |
6 | | -# https://github.com/AbdelrahmanAmr3/earthstat |
| 3 | +import zipfile |
| 4 | +import argparse |
7 | 5 |
|
| 6 | +# Mapping of parameters to ERA5 variable/statistic |
8 | 7 | AgERA5_params = { |
9 | 8 | "Maximum_Temperature": ("2m_temperature", "24_hour_maximum"), |
10 | 9 | "Minimum_Temperature": ("2m_temperature", "24_hour_minimum"), |
11 | 10 | "Mean_Temperature": ("2m_temperature", "24_hour_mean"), |
12 | 11 | "Solar_Radiation_Flux": ("solar_radiation_flux", None), |
13 | 12 | "Precipitation_Flux": ("precipitation_flux", None), |
14 | | - # NOTE: Not used. Uncomment if required. |
15 | | - # 'Wind_Speed': {'10m_wind_speed': '24_hour_mean'}, |
16 | | - # 'Vapour_Pressure': {'vapour_pressure': '24_hour_mean'}, |
| 13 | + "Reference_Evapotranspiration": ("reference_evapotranspiration", None), |
| 14 | + "Vapour_Pressure_Deficit": ("vapour_pressure_deficit_at_maximum_temperature", None) |
17 | 15 | } |
18 | 16 |
|
| 17 | +download_root = '/lustre/backup/SHARED/AIN/agml/predictors/AgERA5/v2.0' |
| 18 | + |
| 19 | +def get_agera5_params(sel_param, year): |
| 20 | + var, stat = AgERA5_params[sel_param] |
| 21 | + retrieve_params = { |
| 22 | + "version": "2_0", |
| 23 | + "format": "zip", |
| 24 | + "variable": var, |
| 25 | + "year": [str(year)], |
| 26 | + "month": [f"{m:02d}" for m in range(1, 13)], |
| 27 | + "day": [f"{d:02d}" for d in range(1, 32)], |
| 28 | + } |
| 29 | + if stat is not None: |
| 30 | + retrieve_params["statistic"] = [stat] |
| 31 | + return retrieve_params |
| 32 | + |
| 33 | +def is_zip_ok(zip_path): |
| 34 | + return os.path.isfile(zip_path) and zipfile.is_zipfile(zip_path) |
| 35 | + |
| 36 | +def download_agera5(cds, year, param): |
| 37 | + zipfile_path = os.path.join(download_root, param, f"{param}_{year}.zip") |
| 38 | + if is_zip_ok(zipfile_path): |
| 39 | + print(f"Skipping {zipfile_path} (already exists and OK)") |
| 40 | + return |
| 41 | + |
| 42 | + os.makedirs(os.path.join(download_root, param), exist_ok=True) |
| 43 | + retrieve_params = get_agera5_params(param, year) |
| 44 | + |
| 45 | + try: |
| 46 | + print(f"Downloading {param} {year} ...") |
| 47 | + cds.retrieve("sis-agrometeorological-indicators", retrieve_params).download(zipfile_path) |
| 48 | + print(f"Download complete: {param} {year}") |
| 49 | + except Exception as e: |
| 50 | + print(f"Error downloading {param} {year}: {e}") |
| 51 | + |
| 52 | +if __name__ == "__main__": |
| 53 | + parser = argparse.ArgumentParser() |
| 54 | + parser.add_argument("--year", type=int, required=True) |
| 55 | + parser.add_argument("--param", type=str, required=True, choices=list(AgERA5_params.keys())) |
| 56 | + args = parser.parse_args() |
| 57 | + |
| 58 | + cds = cdsapi.Client(progress=True) |
| 59 | + download_agera5(cds, args.year, args.param) |
19 | 60 |
|
20 | | -# @author: Abdelrahman Saleh |
21 | | -def get_agera5_params(sel_param, year, area=None): |
22 | | - if sel_param in AgERA5_params: |
23 | | - var, stat = AgERA5_params[sel_param] |
24 | | - |
25 | | - # Construct the return dictionary |
26 | | - retrieve_params = { |
27 | | - "version": "1_1", |
28 | | - "format": "zip", |
29 | | - "variable": var, |
30 | | - "year": str(year), |
31 | | - "month": [ |
32 | | - "01", |
33 | | - "02", |
34 | | - "03", |
35 | | - "04", |
36 | | - "05", |
37 | | - "06", |
38 | | - "07", |
39 | | - "08", |
40 | | - "09", |
41 | | - "10", |
42 | | - "11", |
43 | | - "12", |
44 | | - ], |
45 | | - "day": [ |
46 | | - "01", |
47 | | - "02", |
48 | | - "03", |
49 | | - "04", |
50 | | - "05", |
51 | | - "06", |
52 | | - "07", |
53 | | - "08", |
54 | | - "09", |
55 | | - "10", |
56 | | - "11", |
57 | | - "12", |
58 | | - "13", |
59 | | - "14", |
60 | | - "15", |
61 | | - "16", |
62 | | - "17", |
63 | | - "18", |
64 | | - "19", |
65 | | - "20", |
66 | | - "21", |
67 | | - "22", |
68 | | - "23", |
69 | | - "24", |
70 | | - "25", |
71 | | - "26", |
72 | | - "27", |
73 | | - "28", |
74 | | - "29", |
75 | | - "30", |
76 | | - "31", |
77 | | - ], |
78 | | - } |
79 | | - |
80 | | - if stat is not None: |
81 | | - retrieve_params["statistic"] = stat |
82 | | - |
83 | | - if area is not None: |
84 | | - retrieve_params["area"] = area |
85 | | - |
86 | | - return retrieve_params |
87 | | - else: |
88 | | - raise Exception(f"parameter '{sel_param}' is not supported") |
89 | | - |
90 | | - |
91 | | -def download_agera5_year(cds, year, sel_param, download_path): |
92 | | - download_dir = os.path.join(download_path, sel_param) |
93 | | - os.makedirs(download_dir, exist_ok=True) |
94 | | - retrieve_params = get_agera5_params(sel_param, year) |
95 | | - cds.retrieve( |
96 | | - "sis-agrometeorological-indicators", |
97 | | - retrieve_params, |
98 | | - f"{download_dir}/{sel_param}_{year}.zip", |
99 | | - ) |
100 | | - |
101 | | - |
102 | | -def download_agera5(cds, num_requests, start_year, end_year, download_path): |
103 | | - # NOTE: $HOME/.cdsapirc needs to contain API key |
104 | | - # Example contents of .cdsapirc: |
105 | | - # url: https://cds.climate.copernicus.eu/api |
106 | | - # key: {cdsapi.api_key} |
107 | | - # NOTE: To get a cdsapi token, you will need an ECMWF account. |
108 | | - # See here for details: |
109 | | - # https://confluence.ecmwf.int/x/uINmFw and |
110 | | - # https://cds.climate.copernicus.eu/how-to-api |
111 | | - # Also you need to accept license terms before you can actually download data. |
112 | | - # For AgERA5, accept terms here: |
113 | | - # https://cds.climate.copernicus.eu/datasets/sis-agrometeorological-indicators?tab=download#manage-licenses |
114 | | - if not os.path.exists(os.path.join(os.environ["HOME"], ".cdsapirc")): |
115 | | - raise Exception(".cdsapirc not found in $HOME") |
116 | | - |
117 | | - assert num_requests <= 16, Exception("Suggested number of requests is <= 16") |
118 | | - with concurrent.futures.ThreadPoolExecutor(max_workers=num_requests) as executor: |
119 | | - tasks = [ |
120 | | - executor.submit(download_agera5_year, cds, year, parameter, download_path) |
121 | | - for year in range(start_year, end_year + 1) |
122 | | - for parameter in AgERA5_params |
123 | | - ] |
124 | | - |
125 | | - for future in concurrent.futures.as_completed(tasks): |
126 | | - future.result() |
127 | | - |
128 | | - |
129 | | -# NOTE: |
130 | | -# 1. Make sure you have enough disk space when you run the full script. |
131 | | -# 2. Some zip files seem to have errors. You may need to download them again. |
132 | | -cds = cdsapi.Client(progress=False) |
133 | | -download_path = "/path/to/downloads" |
134 | | -download_agera5(cds, 16, 2001, 2023, download_path) |
135 | | - |
136 | | -# NOTE: |
137 | | -# After downloading data, you need 2 more steps before you can |
138 | | -# use `../predictor_data_prep.py` to mask and aggregate AgERA5 data to admin regions. |
139 | | -# 1. Data will be downloaded to folders named "Maximum_Temperature", |
140 | | -# "Minimum_Temperature", etc. Run the `rename_agera5_files.py` in each folder. |
141 | | -# 2. Rename folder names as follows: |
142 | | -# "Maximum_Temperature" -> tmax |
143 | | -# "Minimum_Temperature" -> tmin |
144 | | -# "Mean_Temperature" -> tavg |
145 | | -# "Precipitation_Flux" -> prec |
146 | | -# "Solar_Radiation_Flux" -> rad |
0 commit comments