| """ |
| This module contains functions for plotting rainfall rate data using Cartopy and Matplotlib. |
| It includes utilities for color mapping, coordinate transformations, and plotting. |
| """ |
|
|
| from pathlib import Path |
| from typing import Tuple |
|
|
| import cartopy.feature as cfeature |
| import matplotlib.colors as mcolors |
| import matplotlib.pyplot as plt |
| import numpy as np |
| import xarray as xr |
| from cartopy.crs import Globe, PlateCarree, Stereographic |
| from matplotlib.axes import Axes |
| from pyproj import CRS, Transformer |
| from scipy.interpolate import griddata |
| from scipy.spatial import cKDTree |
|
|
| |
| |
| |
|
|
| |
| PROJ_WKT = """ |
| PROJCS["unknown",GEOGCS["unknown",DATUM["unknown",SPHEROID["unknown",6378137,298.252840776245]], |
| PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]]], |
| PROJECTION["Polar_Stereographic"],PARAMETER["latitude_of_origin",45], |
| PARAMETER["central_meridian",0],PARAMETER["false_easting",0],PARAMETER["false_northing",0], |
| UNIT["metre",1],AXIS["Easting",SOUTH],AXIS["Northing",SOUTH]] |
| """ |
| GEOTRANSFORM = ( |
| -619652.0953618084, |
| 1000.0, |
| 0.0, |
| -3526818.459196719, |
| 0.0, |
| -999.9999999999997, |
| ) |
|
|
|
|
| def project_to_latlon(arr: np.ndarray) -> xr.DataArray: |
| """Convert a 2D array from the original projection to lat/lon coordinates.""" |
| x0, dx, _, y0, _, dy = GEOTRANSFORM |
| height, width = arr.shape |
|
|
| |
| x_coords = x0 + np.arange(width) * dx |
| y_coords = y0 + np.arange(height) * dy |
| xx, yy = np.meshgrid(x_coords, y_coords) |
|
|
| |
| crs_src = CRS.from_wkt(PROJ_WKT) |
| crs_dst = CRS.from_epsg(4326) |
| to_latlon = Transformer.from_crs(crs_src, crs_dst, always_xy=True) |
| lon, lat = to_latlon.transform(xx, yy) |
|
|
| |
| da_src = xr.DataArray(arr, dims=("y", "x"), coords={"x": x_coords, "y": y_coords}) |
| da_src = da_src.assign_coords(lon=(("y", "x"), lon), lat=(("y", "x"), lat)) |
|
|
| |
| res_deg = 0.01 |
| lat_target = np.arange(lat.min(), lat.max(), res_deg) |
| lon_target = np.arange(lon.min(), lon.max(), res_deg) |
| lon_grid, lat_grid = np.meshgrid(lon_target, lat_target) |
|
|
| |
| points = np.column_stack((lon.ravel(), lat.ravel())) |
| values = arr.ravel() |
| data_interp = griddata(points, values, (lon_grid, lat_grid), method="nearest") |
|
|
| |
| |
| tree = cKDTree(points) |
| distances, _ = tree.query( |
| np.column_stack((lon_grid.ravel(), lat_grid.ravel())), k=1 |
| ) |
|
|
| |
| max_dist = np.sqrt(2) * res_deg |
| mask = distances > max_dist |
|
|
| |
| data_interp_flat = data_interp.ravel() |
| data_interp_flat[mask] = np.nan |
| data_interp = data_interp_flat.reshape(lon_grid.shape) |
|
|
| |
| da_reproj = xr.DataArray( |
| data_interp, |
| dims=("lat", "lon"), |
| coords={"lat": lat_target, "lon": lon_target}, |
| name="data", |
| ) |
| |
| da_reproj = da_reproj[::-1, :] |
| return da_reproj |
|
|
|
|
| |
| |
| |
|
|
|
|
| def hex_to_rgb(hex): |
| """Converts a hexadecimal color to RGB.""" |
| return tuple(int(hex[i : i + 2], 16) / 255 for i in (0, 2, 4)) |
|
|
|
|
| COLORS_RR = [ |
| hex_to_rgb("E5E5E5"), |
| hex_to_rgb("6600CBFF"), |
| hex_to_rgb("0000FFFF"), |
| hex_to_rgb("00B2FFFF"), |
| hex_to_rgb("00FFFFFF"), |
| hex_to_rgb("0EDCD2FF"), |
| hex_to_rgb("1CB8A5FF"), |
| hex_to_rgb("6BA530FF"), |
| hex_to_rgb("FFFF00FF"), |
| hex_to_rgb("FFD800FF"), |
| hex_to_rgb("FFA500FF"), |
| hex_to_rgb("FF0000FF"), |
| hex_to_rgb("991407FF"), |
| hex_to_rgb("FF00FFFF"), |
| ] |
| """list of str: list of colors for the rainfall rate colormap""" |
|
|
| CMAP_RR = mcolors.ListedColormap(COLORS_RR) |
| """ListedColormap : rainfall rate colormap""" |
|
|
| BOUNDARIES_RR = [ |
| 0, |
| 0.1, |
| 0.4, |
| 0.6, |
| 1.2, |
| 2.1, |
| 3.6, |
| 6.5, |
| 12, |
| 21, |
| 36, |
| 65, |
| 120, |
| 205, |
| 360, |
| ] |
| """list of float: boundaries of the rainfall rate colormap""" |
|
|
| NORM_RR = mcolors.BoundaryNorm(BOUNDARIES_RR, CMAP_RR.N, clip=True) |
| """BoundaryNorm: norm for the reflectivity colormap""" |
|
|
| |
| |
| |
|
|
|
|
| def plot_ax_rainfall_rate( |
| ax: Axes, |
| data: np.ndarray, |
| extent: Tuple[float], |
| cmap=CMAP_RR, |
| norm=NORM_RR, |
| title: str = "", |
| ): |
| """Plot a rainfall rate image on a given axis.""" |
| img = ax.imshow(data, extent=extent, cmap=cmap, norm=norm, interpolation="none") |
| states_provinces = cfeature.NaturalEarthFeature( |
| category="cultural", |
| name="admin_1_states_provinces_lines", |
| scale="10m", |
| facecolor="none", |
| ) |
| ax.add_feature(states_provinces, edgecolor="lightgrey", linewidth=0.5) |
| ax.add_feature(cfeature.BORDERS.with_scale("10m"), edgecolor="black", linewidth=1) |
| ax.coastlines(resolution="10m", color="black", linewidth=1) |
| ax.set_title(title, fontsize=15) |
| ax.gridlines( |
| crs=PlateCarree(), |
| draw_labels=True, |
| linewidth=0.4, |
| color="lightgrey", |
| linestyle=":", |
| ) |
| return img |
|
|
|
|
| def plot_map_rain(data: xr.DataArray, title: str, path: Path) -> None: |
| """Plot a rainfall rate map.""" |
| projection = PlateCarree() |
| extent = [data.lon.min(), data.lon.max(), data.lat.min(), data.lat.max()] |
| fig, ax = plt.subplots(subplot_kw={"projection": projection}, figsize=(10, 7)) |
| img = plot_ax_rainfall_rate(ax, data.values, title=title, extent=extent) |
| cb = fig.colorbar(img, ax=ax, orientation="horizontal", fraction=0.04, pad=0.05) |
| cb.set_label(label="Precipitation in mm/h", fontsize=12) |
| plt.tight_layout() |
| plt.savefig(path) |
| plt.close() |
|
|