π§οΈ CHIRPS Rainfall Data Download Tutorial¶
Learn how to download CHIRPS (Climate Hazards Group InfraRed Precipitation with Station data) rainfall datasets for climate and malaria modeling.
π Overview¶
This tutorial provides a complete Python script to download, clip, and merge CHIRPS daily rainfall data for any region and time period.
CHIRPS Dataset
CHIRPS v2.0 is a quasi-global (50Β°Sβ50Β°N) rainfall dataset combining satellite imagery with in-situ station data.
- Temporal Coverage: 1981βpresent (updated every 2 weeks)
- Temporal Resolution: Daily
- Spatial Resolution: 0.05Β° (~5 km) or 0.25Β° (~25 km)
- Format: NetCDF
- Best For: High-resolution rainfall analysis in Africa
π― What This Script Does¶
The download script performs four main operations:
- π₯ Downloads CHIRPS yearly NetCDF files from the official repository
- βοΈ Clips data to your region of interest (optional)
- π Merges multiple years into a single NetCDF file
- πΎ Saves compressed output for efficient storage
graph LR
A[Start Year] --> B[Download Yearly Files]
B --> C{Clip Region?}
C -->|Yes| D[Clip to Bounding Box]
C -->|No| E[Use Full Files]
D --> F[Merge All Years]
E --> F
F --> G[Save Single NetCDF] π Quick Start¶
1. Installation¶
First, install the required Python packages:
2. Save the Script¶
Create a new file called download_chirps.py and copy the script below into it.
3. Run Examples¶
Download 3 years without clipping:
Download and clip to East Africa (Ethiopia region):
python download_chirps.py --start 2013 --end 2019 \
--clip 15 3 33 48 \
--outdir data/chirps_ethiopia \
--res p05
Download with custom merged filename:
python download_chirps.py --start 2015 --end 2017 \
--clip 15 -5 30 50 \
--outdir data/chirps_ea \
--merge-name chirps_east_africa.nc
π The Complete Python Script¶
Click the tabs below to view different sections of the script, or scroll down for the complete code.
This is the complete, production-ready script you can use immediately.
| download_chirps.py | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 | |
π₯ Download Function¶
def download_file(url: str, dest: Path, chunk=2**20):
"""Downloads file in chunks with atomic write."""
dest.parent.mkdir(parents=True, exist_ok=True)
tmp = dest.with_suffix(dest.suffix + ".part")
with requests.get(url, stream=True, timeout=180) as r:
r.raise_for_status()
with open(tmp, "wb") as f:
for blk in r.iter_content(chunk_size=chunk):
if blk:
f.write(blk)
tmp.replace(dest) # Atomic rename
Features:
- Streams large files (doesn't load all into memory)
- Uses temporary
.partfile during download - Atomic rename ensures complete files only
- 180-second timeout for slow connections
π URL Builder¶
def build_url(year: int, res: str) -> str:
"""Constructs CHIRPS URL for year and resolution."""
base = f"https://data.chc.ucsb.edu/products/CHIRPS-2.0/global_daily/netcdf/{res}"
return f"{base}/chirps-v2.0.{year}.days_{res}.nc"
Example URLs:
- 0.25Β°:
...netcdf/p25/chirps-v2.0.2018.days_p25.nc - 0.05Β°:
...netcdf/p05/chirps-v2.0.2018.days_p05.nc
βοΈ Clipping Function¶
def clip_box(ds, N, S, W, E):
"""Clips dataset to bounding box [N, S, W, E]."""
# Handles:
# - Coordinate name variations (lat/latitude)
# - Longitude wrapping (dateline crossing)
# - Standardization for merging
Bounding Box Format:
- N = Northern latitude (e.g., 15Β°N)
- S = Southern latitude (e.g., 3Β°N)
- W = Western longitude (e.g., 33Β°E)
- E = Eastern longitude (e.g., 48Β°E)
π Merge Function¶
def merge_to_netcdf(nc_paths, out_path: Path):
"""Merges multiple years into single NetCDF."""
ds = xr.open_mfdataset(
nc_paths,
combine="by_coords", # Merge along time
preprocess=standardize_for_merge,
parallel=False,
)
# Compress output (zlib level 3)
enc = {v: {"zlib": True, "complevel": 3} for v in ds.data_vars}
ds.to_netcdf(out_path, encoding=enc)
Benefits:
- Concatenates along time dimension automatically
- Compresses output (smaller file size)
- Standardizes coordinates across years
The script accepts several command-line arguments:
| Argument | Required | Description | Example |
|---|---|---|---|
--start | β | Starting year | --start 2018 |
--end | β | Ending year (inclusive) | --end 2020 |
--outdir | β | Output directory | --outdir data/chirps |
--res | β | Resolution (p25 or p05) | --res p05 |
--clip | β | Bounding box [N S W E] | --clip 15 3 33 48 |
--merge-name | β | Custom merged filename | --merge-name ethiopia.nc |
--overwrite | β | Overwrite existing files | --overwrite |
Default Values:
outdir:"chirps_downloads"res:"p25"(0.25Β° resolution)merge-name: Auto-generated (e.g.,chirps_p25_2018-2020.nc)
π Regional Bounding Boxes¶
Use these bounding boxes for common regions:
π‘ Usage Examples¶
Example 1: Amhara Region (2013-2019) - High Resolution¶
Download high-resolution (0.05Β°) CHIRPS data for the Amhara case study:
python download_chirps.py \
--start 2013 \
--end 2019 \
--res p05 \
--clip 13.5 9.0 36.0 40.5 \
--outdir data/chirps_amhara \
--merge-name chirps_amhara_2013-2019.nc
Output:
- Individual years:
data/chirps_amhara/chirps-v2.0.2013.days_p05_clip.nc, etc. - Merged file:
data/chirps_amhara/chirps_amhara_2013-2019.nc
Example 2: Ethiopia - Multiple Resolutions¶
Download both resolutions for comparison:
# 0.25Β° resolution (faster download)
python download_chirps.py \
--start 2015 \
--end 2020 \
--res p25 \
--clip 15 3 33 48 \
--outdir data/chirps_ethiopia_p25
# 0.05Β° resolution (higher detail)
python download_chirps.py \
--start 2015 \
--end 2020 \
--res p05 \
--clip 15 3 33 48 \
--outdir data/chirps_ethiopia_p05
Example 3: Global Data (No Clipping)¶
Download global CHIRPS without clipping:
Note: Global files are large (~1.5 GB per year at 0.25Β°, ~8 GB at 0.05Β°)
π Understanding the Output¶
File Structure¶
After running the script, you'll have:
data/chirps_amhara/
βββ chirps-v2.0.2013.days_p05.nc # Raw yearly file
βββ chirps-v2.0.2013.days_p05_clip.nc # Clipped yearly file
βββ chirps-v2.0.2014.days_p05.nc
βββ chirps-v2.0.2014.days_p05_clip.nc
βββ ...
βββ chirps_amhara_2013-2019.nc # Merged file (use this!)
NetCDF Structure¶
Open the merged file to inspect:
Expected Structure:
<xarray.Dataset>
Dimensions: (time: 2557, lat: 47, lon: 46)
Coordinates:
* time (time) datetime64[ns] 2013-01-01 ... 2019-12-31
* lat (lat) float32 9.025 9.075 9.125 ... 13.375 13.425 13.475
* lon (lon) float32 36.025 36.075 ... 40.425 40.475
Data variables:
precip (time, lat, lon) float32 ...
Attributes:
...
π Advanced Usage¶
Processing After Download¶
Once you have the merged NetCDF, you can:
1. Calculate Monthly Totals:
import xarray as xr
ds = xr.open_dataset("chirps_amhara_2013-2019.nc")
monthly = ds.resample(time="MS").sum()
monthly.to_netcdf("chirps_amhara_monthly.nc")
2. Extract Specific Location:
# Extract time series for Addis Ababa (9.03Β°N, 38.74Β°E)
point = ds.sel(lat=9.03, lon=38.74, method="nearest")
precip_ts = point["precip"].values
3. Calculate Seasonal Means:
# Kiremt season (June-September)
kiremt = ds.sel(time=ds.time.dt.month.isin([6, 7, 8, 9]))
kiremt_mean = kiremt.groupby("time.year").sum("time")
β οΈ Troubleshooting¶
Common Issues and Solutions¶
Download Timeout
Problem: requests.exceptions.Timeout
Solution:
- Check your internet connection
- Try again later (server may be busy)
- Increase timeout: modify
timeout=180totimeout=300
Out of Memory
Problem: Script crashes with memory error
Solution:
- Use lower resolution (
--res p25instead ofp05) - Clip to smaller region
- Download fewer years at once
- Close other applications
File Already Exists
Problem: Script skips downloading existing files
Solution:
- Use
--overwriteflag to force re-download - Or manually delete old files
Invalid Bounding Box
Problem: ValueError: Invalid latitude bounds
Solution:
- Ensure South < North
- Check coordinates are in valid range:
- Latitude: -50 to 50 (CHIRPS coverage)
- Longitude: -180 to 180
π Data Quality Notes¶
CHIRPS Data Quality
Strengths:
- High spatial resolution (0.05Β°)
- Long temporal record (1981βpresent)
- Blends satellite and station data
- Regular updates (every 2 weeks)
- Quasi-global coverage
Limitations:
- 2-week lag for final product
- Station density varies by region
- Better over land than ocean
- May underestimate extreme events
Recommended For:
- Climate analysis and trends
- Model forcing (e.g., VECTRI)
- Drought monitoring
- Agricultural applications
π Additional Resources¶
- CHIRPS Homepage: https://www.chc.ucsb.edu/data/chirps
- CHIRPS Documentation: Technical Documentation
- Data Portal: https://data.chc.ucsb.edu/products/CHIRPS-2.0/
- Publication: Funk et al. (2015), Scientific Data
- Xarray Documentation: https://docs.xarray.dev/
π Support¶
Need help with the download script?
- Workshop Support: yonas.mersha14@gmail.com
- CHIRPS Support: chc@ucsb.edu
- Technical Issues: Check the GitHub Issues
π― Next Steps¶
After downloading CHIRPS data:
- Quality Check: Inspect the NetCDF file with
xarray - Visualization: Plot spatial and temporal patterns
- Integration: Combine with temperature data (ERA5)
- VECTRI Setup: Prepare climate forcing files