Datasets:
File size: 13,734 Bytes
6ce2158 |
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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "35b8f4c5-adb3-45ee-879c-4785673617e1",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 1,
"id": "340ecc63-271b-499c-82b0-4a81da89015d",
"metadata": {},
"outputs": [
{
"ename": "FileNotFoundError",
"evalue": "Cannot find 'Assam_X_Relative_Humidity.tif' in /home/aparajita/Desktop/Weather Analytics/Weather_Analytics/GridData/Assam",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[1], line 20\u001b[0m\n\u001b[1;32m 18\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m path \u001b[38;5;129;01min\u001b[39;00m (rh_tiff_path, precip_raw_tiff, precip_cat_tiff, india_shapefile):\n\u001b[1;32m 19\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m os\u001b[38;5;241m.\u001b[39mpath\u001b[38;5;241m.\u001b[39misfile(path):\n\u001b[0;32m---> 20\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mFileNotFoundError\u001b[39;00m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCannot find \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mpath\u001b[38;5;132;01m!r}\u001b[39;00m\u001b[38;5;124m in \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mos\u001b[38;5;241m.\u001b[39mgetcwd()\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 22\u001b[0m \u001b[38;5;66;03m# -----------------------------------------------------------------------------\u001b[39;00m\n\u001b[1;32m 23\u001b[0m \u001b[38;5;66;03m# 2) READ & MASK THE 20-BAND RELATIVE HUMIDITY TIFF\u001b[39;00m\n\u001b[1;32m 24\u001b[0m \u001b[38;5;66;03m# -----------------------------------------------------------------------------\u001b[39;00m\n\u001b[1;32m 25\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m rasterio\u001b[38;5;241m.\u001b[39mopen(rh_tiff_path) \u001b[38;5;28;01mas\u001b[39;00m src_rh:\n",
"\u001b[0;31mFileNotFoundError\u001b[0m: Cannot find 'Assam_X_Relative_Humidity.tif' in /home/aparajita/Desktop/Weather Analytics/Weather_Analytics/GridData/Assam"
]
}
],
"source": [
"import os\n",
"import rasterio\n",
"import numpy as np\n",
"import geopandas as gpd\n",
"import matplotlib.pyplot as plt\n",
"from matplotlib.colors import ListedColormap\n",
"from matplotlib.patches import Patch\n",
"from rasterio.features import geometry_mask\n",
"\n",
"# -----------------------------------------------------------------------------\n",
"# 1) FILE PATHS (for Assam)\n",
"# -----------------------------------------------------------------------------\n",
"rh_tiff_path = \"Assam_X_Relative_Humidity.tif\" # 20 bands (June–Sept 2020–2024)\n",
"precip_raw_tiff = \"Assam_Y_Precipitation_CHIRPS.tif\" # 25 bands (2020–2024 × 5)\n",
"precip_cat_tiff = \"Assam_Y_Precipitation_GT_geotif.tif\" # 25 bands (2020–2024 × 5)\n",
"india_shapefile = \"SateMask/gadm41_IND_1.shp\" # contains all Indian states\n",
"\n",
"for path in (rh_tiff_path, precip_raw_tiff, precip_cat_tiff, india_shapefile):\n",
" if not os.path.isfile(path):\n",
" raise FileNotFoundError(f\"Cannot find {path!r} in {os.getcwd()}\")\n",
"\n",
"# -----------------------------------------------------------------------------\n",
"# 2) READ & MASK THE 20-BAND RELATIVE HUMIDITY TIFF\n",
"# -----------------------------------------------------------------------------\n",
"with rasterio.open(rh_tiff_path) as src_rh:\n",
" rh_bands = src_rh.read().astype(np.float32) # (20, H, W)\n",
" rh_transform = src_rh.transform\n",
" rh_crs = src_rh.crs\n",
" height, width = src_rh.height, src_rh.width\n",
" rh_bounds = src_rh.bounds\n",
"\n",
"if rh_bands.shape[0] != 20:\n",
" raise ValueError(f\"Expected 20 bands in {rh_tiff_path}, but found {rh_bands.shape[0]}\")\n",
"\n",
"# 2a) Load Assam polygon and reproject if needed\n",
"gdf = gpd.read_file(india_shapefile)\n",
"gdf_assam = gdf[gdf[\"NAME_1\"].str.lower() == \"assam\"].copy()\n",
"if gdf_assam.empty:\n",
" raise ValueError(\"No feature named 'Assam' found in shapefile.\")\n",
"if gdf_assam.crs != rh_crs:\n",
" gdf_assam = gdf_assam.to_crs(rh_crs)\n",
"\n",
"# 2b) Build mask and count pixels\n",
"assam_geom = [gdf_assam.geometry.union_all()]\n",
"assam_mask = geometry_mask(\n",
" assam_geom,\n",
" transform=rh_transform,\n",
" invert=True,\n",
" out_shape=(height, width)\n",
")\n",
"total_inside = np.count_nonzero(assam_mask)\n",
"print(f\"Total pixels inside Assam boundary: {total_inside}\")\n",
"\n",
"# 2c) Mask RH outside Assam\n",
"for i in range(rh_bands.shape[0]):\n",
" band = rh_bands[i]\n",
" band[~assam_mask] = np.nan\n",
" rh_bands[i] = band\n",
"\n",
"# -----------------------------------------------------------------------------\n",
"# 3) READ & MASK RAW PRECIPITATION (25 bands)\n",
"# -----------------------------------------------------------------------------\n",
"with rasterio.open(precip_raw_tiff) as src_pr:\n",
" pr_raw_full = src_pr.read().astype(np.float32) # (25, H, W)\n",
"\n",
"if pr_raw_full.shape[0] != 25:\n",
" raise ValueError(f\"Expected 25 bands in {precip_raw_tiff}, but found {pr_raw_full.shape[0]}\")\n",
"\n",
"for i in range(25):\n",
" arr = pr_raw_full[i]\n",
" arr[~assam_mask] = np.nan\n",
" pr_raw_full[i] = arr\n",
"\n",
"# -----------------------------------------------------------------------------\n",
"# 4) READ & MASK PRECIPITATION CATEGORY (25 bands)\n",
"# -----------------------------------------------------------------------------\n",
"with rasterio.open(precip_cat_tiff) as src_pc:\n",
" pr_cat_full = src_pc.read().astype(np.int8) # (25, H, W)\n",
"\n",
"if pr_cat_full.shape[0] != 25:\n",
" raise ValueError(f\"Expected 25 bands in {precip_cat_tiff}, but found {pr_cat_full.shape[0]}\")\n",
"\n",
"for i in range(25):\n",
" arr = pr_cat_full[i]\n",
" arr[~assam_mask] = -1\n",
" pr_cat_full[i] = arr\n",
"\n",
"# -----------------------------------------------------------------------------\n",
"# 5) EXTRACT 20 MONTHLY BANDS (drop each year’s “Total”)\n",
"# -----------------------------------------------------------------------------\n",
"monthly_indices = []\n",
"for yr in range(5):\n",
" base = yr * 5\n",
" monthly_indices += [base + m for m in range(4)]\n",
"\n",
"pr_raw_bands = pr_raw_full[monthly_indices] # (20, H, W)\n",
"pr_cat_bands = pr_cat_full[monthly_indices] # (20, H, W)\n",
"\n",
"# -----------------------------------------------------------------------------\n",
"# 6) SET UP YEARS & MONTHS\n",
"# -----------------------------------------------------------------------------\n",
"years = [2020, 2021, 2022, 2023, 2024]\n",
"month_names = [\"June\", \"July\", \"August\", \"September\"]\n",
"n_years, n_months = len(years), len(month_names)\n",
"n_total = n_years * n_months # 20\n",
"\n",
"# -----------------------------------------------------------------------------\n",
"# 7) COLORMAPS & STYLE\n",
"# -----------------------------------------------------------------------------\n",
"rh_palette = [\"red\",\"orange\",\"yellow\",\"white\",\"green\",\"cyan\",\"lightblue\",\"blue\"]\n",
"rh_cmap, rh_vmin, rh_vmax = ListedColormap(rh_palette), 0, 100\n",
"\n",
"cluster_colors = [\"#ffffff\",\"#79d151\",\"#22a784\",\"#29788e\",\"#404387\",\"#440154\"]\n",
"cluster_cmap = ListedColormap(cluster_colors)\n",
"cluster_labels = {\n",
" 0: \"NoData/Outside\",\n",
" 1: \"Scarcity (<0.4×normal)\",\n",
" 2: \"Deficit (0.4–0.8×normal)\",\n",
" 3: \"Normal (0.8–1.2×normal)\",\n",
" 4: \"Excess (1.2–1.6×normal)\",\n",
" 5: \"LargeExcess (≥1.6×normal)\"\n",
"}\n",
"cluster_handles = [\n",
" Patch(facecolor=cluster_colors[i], edgecolor=\"black\", label=cluster_labels[i])\n",
" for i in range(len(cluster_colors))\n",
"]\n",
"\n",
"# -----------------------------------------------------------------------------\n",
"# 8) BUILD FIGURE\n",
"# -----------------------------------------------------------------------------\n",
"fig, axes = plt.subplots(n_total, 3, figsize=(20, n_total * 2.0), constrained_layout=True)\n",
"fig.suptitle(\"Assam 2020–2024: Monthly RH | Precip Category | RH Distribution\", fontsize=18, y=0.98)\n",
"if n_total == 1:\n",
" axes = axes[np.newaxis, :]\n",
"\n",
"# -----------------------------------------------------------------------------\n",
"# 9) LOOP & PLOT\n",
"# -----------------------------------------------------------------------------\n",
"for i in range(n_total):\n",
" yr_idx, mo_idx = divmod(i, n_months)\n",
" year, month = years[yr_idx], month_names[mo_idx]\n",
"\n",
" # RH stats + missing\n",
" rh_layer = rh_bands[i]\n",
" valid_rh = rh_layer[~np.isnan(rh_layer)]\n",
" rh_min, rh_max = (float(np.nanmin(valid_rh)), float(np.nanmax(valid_rh))) if valid_rh.size else (None,None)\n",
" miss_rh = np.count_nonzero(np.isnan(rh_layer[assam_mask]))\n",
" pct_rh = miss_rh / total_inside * 100\n",
" print(f\"{year} {month} → Missing RH: {miss_rh}/{total_inside} ({pct_rh:.2f}%)\")\n",
"\n",
" # precip stats\n",
" pr_layer = pr_raw_bands[i]\n",
" valid_pr = pr_layer[~np.isnan(pr_layer)]\n",
" pr_min, pr_max = (float(np.nanmin(valid_pr)), float(np.nanmax(valid_pr))) if valid_pr.size else (None,None)\n",
"\n",
" # category prep\n",
" cat = pr_cat_bands[i]\n",
" cat_plot = np.zeros_like(cat, dtype=np.int8)\n",
" mask_ok = (cat != -1)\n",
" cat_plot[mask_ok] = cat[mask_ok] + 1\n",
"\n",
" # --- Column 0: RH Map ---\n",
" ax0 = axes[i, 0]\n",
" im0 = ax0.imshow(rh_layer, cmap=rh_cmap, vmin=rh_vmin, vmax=rh_vmax,\n",
" extent=[rh_bounds.left, rh_bounds.right, rh_bounds.bottom, rh_bounds.top],\n",
" origin=\"upper\")\n",
" title0 = f\"{year} {month} RH (%)\"\n",
" if rh_min is not None:\n",
" title0 += f\"\\nmin={rh_min:.1f}%, max={rh_max:.1f}%\"\n",
" title0 += f\"\\nmissing={miss_rh}/{total_inside} ({pct_rh:.1f}%)\"\n",
" ax0.set_title(title0, fontsize=10, loc=\"left\")\n",
" ax0.axis(\"off\")\n",
" c0 = fig.colorbar(im0, ax=ax0, fraction=0.045, pad=0.02)\n",
" c0.set_label(\"RH (%)\", fontsize=8); c0.ax.tick_params(labelsize=6)\n",
"\n",
" # --- Column 1: Precip Category Map ---\n",
" ax1 = axes[i, 1]\n",
" im1 = ax1.imshow(cat_plot, cmap=cluster_cmap, vmin=0, vmax=5,\n",
" extent=[rh_bounds.left, rh_bounds.right, rh_bounds.bottom, rh_bounds.top],\n",
" origin=\"upper\")\n",
" title1 = f\"{year} {month} Precip Cat\\nmin={pr_min:.1f} mm, max={pr_max:.1f} mm\"\n",
" ax1.set_title(title1, fontsize=10, loc=\"left\")\n",
" ax1.axis(\"off\")\n",
" c1 = fig.colorbar(im1, ax=ax1, fraction=0.045, pad=0.02)\n",
" c1.set_ticks(list(range(6)))\n",
" c1.set_ticklabels([cluster_labels[j] for j in range(6)], fontsize=6)\n",
" c1.ax.tick_params(labelsize=6); c1.set_label(\"Precip Category\", fontsize=8)\n",
"\n",
" # --- Column 2: RH Distribution ---\n",
" ax2 = axes[i, 2]\n",
" if valid_rh.size:\n",
" ax2.hist(valid_rh.flatten(), bins=30, density=True, edgecolor=\"black\")\n",
" ax2.set_xlim(rh_vmin, rh_vmax)\n",
" else:\n",
" ax2.text(0.5, 0.5, \"No Data\", ha=\"center\", va=\"center\", fontsize=8, color=\"gray\")\n",
" ax2.set_title(f\"RH Dist\\n({year} {month})\", fontsize=10)\n",
" ax2.set_xlabel(\"RH (%)\", fontsize=8); ax2.set_ylabel(\"Density\", fontsize=8)\n",
" ax2.tick_params(labelsize=7)\n",
"\n",
"# -----------------------------------------------------------------------------\n",
"# 10) Legend\n",
"# -----------------------------------------------------------------------------\n",
"fig.legend(handles=cluster_handles, loc=\"lower center\", ncol=3,\n",
" frameon=True, title=\"Precip Category Definitions\",\n",
" bbox_to_anchor=(0.5, -0.005), fontsize=8, title_fontsize=9)\n",
"\n",
"plt.show()\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "aff1cdf1-12a4-476f-8393-6a4ebb6fa2d6",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [conda env:base] *",
"language": "python",
"name": "conda-base-py"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.7"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|