|
23 | 23 |
|
24 | 24 | import numpy as np |
25 | 25 | import rasterio |
| 26 | +from affine import Affine |
26 | 27 |
|
27 | 28 | from climada import CONFIG |
28 | 29 | from climada.util.constants import SYSTEM_DIR |
@@ -171,3 +172,53 @@ def get_gpw_file_path(gpw_version, reference_year, data_dir=None, verbose=True): |
171 | 172 | f" different folder. The data can be downloaded from {sedac_browse_url}, e.g.," |
172 | 173 | f" {sedac_file_url} (Free NASA Earthdata login required)." |
173 | 174 | ) |
| 175 | + |
| 176 | + |
| 177 | +def grid_aligned_with_gpw(reference_year, gpw_version, res_arcsec, data_dir=SYSTEM_DIR): |
| 178 | + """ |
| 179 | + Defines a grid based on population metadata. |
| 180 | +
|
| 181 | + Parameters |
| 182 | + ---------- |
| 183 | + reference_year : int |
| 184 | + The reference year for population and nightlight data. |
| 185 | + gpw_version : int |
| 186 | + Version number of GPW population data. |
| 187 | + res_arcsec : int or None |
| 188 | + Desired resolution in arcseconds. If None, aligns to population grid. |
| 189 | + data_dir : str |
| 190 | + Path to input data directory. |
| 191 | +
|
| 192 | + Returns |
| 193 | + ------- |
| 194 | + grid : dict |
| 195 | + A dictionary containing grid metadata, following the raster grid |
| 196 | + specification. |
| 197 | + """ |
| 198 | + res_deg = res_arcsec / 3600 |
| 199 | + |
| 200 | + file_path = get_gpw_file_path( |
| 201 | + gpw_version, reference_year, data_dir=data_dir, verbose=False |
| 202 | + ) |
| 203 | + with rasterio.open(file_path, "r") as src: |
| 204 | + global_crs = src.crs |
| 205 | + gpw_transform = src.transform |
| 206 | + # Align grid resolution with GPW dataset |
| 207 | + aligned_lon_min = -180 + (round((gpw_transform[2] - (-180)) / res_deg) * res_deg) |
| 208 | + aligned_lat_max = 90 - (round((90 - gpw_transform[5]) / res_deg) * res_deg) |
| 209 | + |
| 210 | + global_transform = Affine(res_deg, 0, aligned_lon_min, 0, -res_deg, aligned_lat_max) |
| 211 | + |
| 212 | + global_width = round(360 / res_deg) |
| 213 | + global_height = round(180 / res_deg) |
| 214 | + |
| 215 | + # Define the target grid using the computed values |
| 216 | + return { |
| 217 | + "driver": "GTiff", |
| 218 | + "dtype": "float32", |
| 219 | + "nodata": None, |
| 220 | + "crs": global_crs, |
| 221 | + "width": global_width, |
| 222 | + "height": global_height, |
| 223 | + "transform": global_transform, |
| 224 | + } |
0 commit comments