Datasets:
Commit
·
6587b2c
1
Parent(s):
f23ac87
add example script
Browse files- example.py +33 -0
- plots.py +199 -0
example.py
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import matplotlib.pyplot as plt
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
from plots import plot_map_rain, project_to_latlon
|
5 |
+
|
6 |
+
# Load the file
|
7 |
+
data = np.load("2020/202004201700.npz") # Adjust path as needed
|
8 |
+
rain = data["arr_0"] # The array is stored under 'arr_0'
|
9 |
+
print("Array shape:", rain.shape) # Shape = (1536, 1536)
|
10 |
+
|
11 |
+
# Negative values indicate no data, replace them with NaN:
|
12 |
+
rain = np.where(rain < 0, np.nan, rain)
|
13 |
+
|
14 |
+
# Visualize
|
15 |
+
print("Making basic plot...")
|
16 |
+
plt.imshow(rain, cmap="Blues")
|
17 |
+
plt.colorbar(label="Rainfall (x0.01 mm / 5min)")
|
18 |
+
plt.title("Rainfall Accumulation – 2020-04-20 17:00 UTC")
|
19 |
+
plt.savefig("rainfall_20200420_1700_basic.png")
|
20 |
+
plt.close()
|
21 |
+
|
22 |
+
print("Converting and projecting rainfall data...")
|
23 |
+
rain = rain / 100 # Convert from mm10-2 to mm
|
24 |
+
rain = rain * 60 / 5 # Convert from mm to mm/h
|
25 |
+
da_reproj = project_to_latlon(rain)
|
26 |
+
print(da_reproj)
|
27 |
+
|
28 |
+
print("Plotting projected rainfall data...")
|
29 |
+
plot_map_rain(
|
30 |
+
data=da_reproj,
|
31 |
+
title="Rainfall Rate – 2020-04-20 17:00 UTC",
|
32 |
+
path="rainfall_20200420_1700_map.png",
|
33 |
+
)
|
plots.py
ADDED
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This module contains functions for plotting rainfall rate data using Cartopy and Matplotlib.
|
3 |
+
It includes utilities for color mapping, coordinate transformations, and plotting.
|
4 |
+
"""
|
5 |
+
|
6 |
+
from pathlib import Path
|
7 |
+
from typing import Tuple
|
8 |
+
|
9 |
+
import cartopy.feature as cfeature
|
10 |
+
import matplotlib.colors as mcolors
|
11 |
+
import matplotlib.pyplot as plt
|
12 |
+
import numpy as np
|
13 |
+
import xarray as xr
|
14 |
+
from cartopy.crs import Globe, PlateCarree, Stereographic
|
15 |
+
from matplotlib.axes import Axes
|
16 |
+
from pyproj import CRS, Transformer
|
17 |
+
from scipy.interpolate import griddata
|
18 |
+
from scipy.spatial import cKDTree
|
19 |
+
|
20 |
+
########################################################################################
|
21 |
+
# PROJECTIONS AND COORDINATES #
|
22 |
+
########################################################################################
|
23 |
+
|
24 |
+
# Original radar projection
|
25 |
+
PROJ_WKT = """
|
26 |
+
PROJCS["unknown",GEOGCS["unknown",DATUM["unknown",SPHEROID["unknown",6378137,298.252840776245]],
|
27 |
+
PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]]],
|
28 |
+
PROJECTION["Polar_Stereographic"],PARAMETER["latitude_of_origin",45],
|
29 |
+
PARAMETER["central_meridian",0],PARAMETER["false_easting",0],PARAMETER["false_northing",0],
|
30 |
+
UNIT["metre",1],AXIS["Easting",SOUTH],AXIS["Northing",SOUTH]]
|
31 |
+
"""
|
32 |
+
GEOTRANSFORM = (
|
33 |
+
-619652.0953618084,
|
34 |
+
1000.0,
|
35 |
+
0.0,
|
36 |
+
-3526818.459196719,
|
37 |
+
0.0,
|
38 |
+
-999.9999999999997,
|
39 |
+
)
|
40 |
+
|
41 |
+
|
42 |
+
def project_to_latlon(arr: np.ndarray) -> xr.DataArray:
|
43 |
+
"""Convert a 2D array from the original projection to lat/lon coordinates."""
|
44 |
+
x0, dx, _, y0, _, dy = GEOTRANSFORM
|
45 |
+
height, width = arr.shape
|
46 |
+
|
47 |
+
# Create meshgrid of coordinates
|
48 |
+
x_coords = x0 + np.arange(width) * dx
|
49 |
+
y_coords = y0 + np.arange(height) * dy
|
50 |
+
xx, yy = np.meshgrid(x_coords, y_coords)
|
51 |
+
|
52 |
+
# Transform grid coords to lat/lon
|
53 |
+
crs_src = CRS.from_wkt(PROJ_WKT)
|
54 |
+
crs_dst = CRS.from_epsg(4326) # WGS84
|
55 |
+
to_latlon = Transformer.from_crs(crs_src, crs_dst, always_xy=True)
|
56 |
+
lon, lat = to_latlon.transform(xx, yy)
|
57 |
+
|
58 |
+
# Creation of the source DataArray
|
59 |
+
da_src = xr.DataArray(arr, dims=("y", "x"), coords={"x": x_coords, "y": y_coords})
|
60 |
+
da_src = da_src.assign_coords(lon=(("y", "x"), lon), lat=(("y", "x"), lat))
|
61 |
+
|
62 |
+
# Regular grid in lat/lon
|
63 |
+
res_deg = 0.01 # ~1 km
|
64 |
+
lat_target = np.arange(lat.min(), lat.max(), res_deg)
|
65 |
+
lon_target = np.arange(lon.min(), lon.max(), res_deg)
|
66 |
+
lon_grid, lat_grid = np.meshgrid(lon_target, lat_target)
|
67 |
+
|
68 |
+
# Interpolation with griddata
|
69 |
+
points = np.column_stack((lon.ravel(), lat.ravel()))
|
70 |
+
values = arr.ravel()
|
71 |
+
data_interp = griddata(points, values, (lon_grid, lat_grid), method="nearest")
|
72 |
+
|
73 |
+
# The nearest neighbor interpolation can create artefacts on the edges
|
74 |
+
# so we mask values using a maximum distance
|
75 |
+
tree = cKDTree(points)
|
76 |
+
distances, _ = tree.query(
|
77 |
+
np.column_stack((lon_grid.ravel(), lat_grid.ravel())), k=1
|
78 |
+
)
|
79 |
+
|
80 |
+
# Max radius: diagonal of a target pixel
|
81 |
+
max_dist = np.sqrt(2) * res_deg
|
82 |
+
mask = distances > max_dist
|
83 |
+
|
84 |
+
# Mask the interpolated data
|
85 |
+
data_interp_flat = data_interp.ravel()
|
86 |
+
data_interp_flat[mask] = np.nan
|
87 |
+
data_interp = data_interp_flat.reshape(lon_grid.shape)
|
88 |
+
|
89 |
+
# Create the final DataArray with the reprojected data
|
90 |
+
da_reproj = xr.DataArray(
|
91 |
+
data_interp,
|
92 |
+
dims=("lat", "lon"),
|
93 |
+
coords={"lat": lat_target, "lon": lon_target},
|
94 |
+
name="data",
|
95 |
+
)
|
96 |
+
# Invert latitude axis to match the original orientation
|
97 |
+
da_reproj = da_reproj[::-1, :]
|
98 |
+
return da_reproj
|
99 |
+
|
100 |
+
|
101 |
+
########################################################################################
|
102 |
+
# COLORS AND COLORMAPS #
|
103 |
+
########################################################################################
|
104 |
+
|
105 |
+
|
106 |
+
def hex_to_rgb(hex):
|
107 |
+
"""Converts a hexadecimal color to RGB."""
|
108 |
+
return tuple(int(hex[i : i + 2], 16) / 255 for i in (0, 2, 4))
|
109 |
+
|
110 |
+
|
111 |
+
COLORS_RR = [ # 14 colors
|
112 |
+
hex_to_rgb("E5E5E5"),
|
113 |
+
hex_to_rgb("6600CBFF"),
|
114 |
+
hex_to_rgb("0000FFFF"),
|
115 |
+
hex_to_rgb("00B2FFFF"),
|
116 |
+
hex_to_rgb("00FFFFFF"),
|
117 |
+
hex_to_rgb("0EDCD2FF"),
|
118 |
+
hex_to_rgb("1CB8A5FF"),
|
119 |
+
hex_to_rgb("6BA530FF"),
|
120 |
+
hex_to_rgb("FFFF00FF"),
|
121 |
+
hex_to_rgb("FFD800FF"),
|
122 |
+
hex_to_rgb("FFA500FF"),
|
123 |
+
hex_to_rgb("FF0000FF"),
|
124 |
+
hex_to_rgb("991407FF"),
|
125 |
+
hex_to_rgb("FF00FFFF"),
|
126 |
+
]
|
127 |
+
"""list of str: list of colors for the rainfall rate colormap"""
|
128 |
+
|
129 |
+
CMAP_RR = mcolors.ListedColormap(COLORS_RR)
|
130 |
+
"""ListedColormap : rainfall rate colormap"""
|
131 |
+
|
132 |
+
BOUNDARIES_RR = [
|
133 |
+
0,
|
134 |
+
0.1,
|
135 |
+
0.4,
|
136 |
+
0.6,
|
137 |
+
1.2,
|
138 |
+
2.1,
|
139 |
+
3.6,
|
140 |
+
6.5,
|
141 |
+
12,
|
142 |
+
21,
|
143 |
+
36,
|
144 |
+
65,
|
145 |
+
120,
|
146 |
+
205,
|
147 |
+
360,
|
148 |
+
]
|
149 |
+
"""list of float: boundaries of the rainfall rate colormap"""
|
150 |
+
|
151 |
+
NORM_RR = mcolors.BoundaryNorm(BOUNDARIES_RR, CMAP_RR.N, clip=True)
|
152 |
+
"""BoundaryNorm: norm for the reflectivity colormap"""
|
153 |
+
|
154 |
+
########################################################################################
|
155 |
+
# PLOTTING FUNCTIONS #
|
156 |
+
########################################################################################
|
157 |
+
|
158 |
+
|
159 |
+
def plot_ax_rainfall_rate(
|
160 |
+
ax: Axes,
|
161 |
+
data: np.ndarray,
|
162 |
+
extent: Tuple[float],
|
163 |
+
cmap=CMAP_RR,
|
164 |
+
norm=NORM_RR,
|
165 |
+
title: str = "",
|
166 |
+
):
|
167 |
+
"""Plot a rainfall rate image on a given axis."""
|
168 |
+
img = ax.imshow(data, extent=extent, cmap=cmap, norm=norm, interpolation="none")
|
169 |
+
states_provinces = cfeature.NaturalEarthFeature(
|
170 |
+
category="cultural",
|
171 |
+
name="admin_1_states_provinces_lines",
|
172 |
+
scale="10m",
|
173 |
+
facecolor="none",
|
174 |
+
)
|
175 |
+
ax.add_feature(states_provinces, edgecolor="lightgrey", linewidth=0.5)
|
176 |
+
ax.add_feature(cfeature.BORDERS.with_scale("10m"), edgecolor="black", linewidth=1)
|
177 |
+
ax.coastlines(resolution="10m", color="black", linewidth=1)
|
178 |
+
ax.set_title(title, fontsize=15)
|
179 |
+
ax.gridlines(
|
180 |
+
crs=PlateCarree(),
|
181 |
+
draw_labels=True,
|
182 |
+
linewidth=0.4,
|
183 |
+
color="lightgrey",
|
184 |
+
linestyle=":",
|
185 |
+
)
|
186 |
+
return img
|
187 |
+
|
188 |
+
|
189 |
+
def plot_map_rain(data: xr.DataArray, title: str, path: Path) -> None:
|
190 |
+
"""Plot a rainfall rate map."""
|
191 |
+
projection = PlateCarree()
|
192 |
+
extent = [data.lon.min(), data.lon.max(), data.lat.min(), data.lat.max()]
|
193 |
+
fig, ax = plt.subplots(subplot_kw={"projection": projection}, figsize=(10, 7))
|
194 |
+
img = plot_ax_rainfall_rate(ax, data.values, title=title, extent=extent)
|
195 |
+
cb = fig.colorbar(img, ax=ax, orientation="horizontal", fraction=0.04, pad=0.05)
|
196 |
+
cb.set_label(label="Precipitation in mm/h", fontsize=12)
|
197 |
+
plt.tight_layout()
|
198 |
+
plt.savefig(path)
|
199 |
+
plt.close()
|