pad-on-sphere 6.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pad_on_sphere-6.0.0/LICENSE +50 -0
- pad_on_sphere-6.0.0/MANIFEST.in +10 -0
- pad_on_sphere-6.0.0/PKG-INFO +235 -0
- pad_on_sphere-6.0.0/README.md +201 -0
- pad_on_sphere-6.0.0/examples/example_PAD_on_sphere.py +368 -0
- pad_on_sphere-6.0.0/examples/example_PAD_on_sphere_on_numpy_arrays.ipynb +576 -0
- pad_on_sphere-6.0.0/examples/example_PAD_on_sphere_on_xarrays.ipynb +2608 -0
- pad_on_sphere-6.0.0/examples/sample_data/example_field_A.nc +0 -0
- pad_on_sphere-6.0.0/examples/sample_data/example_field_B.nc +0 -0
- pad_on_sphere-6.0.0/pyproject.toml +42 -0
- pad_on_sphere-6.0.0/setup.cfg +4 -0
- pad_on_sphere-6.0.0/setup.py +44 -0
- pad_on_sphere-6.0.0/src/pad_on_sphere.egg-info/PKG-INFO +235 -0
- pad_on_sphere-6.0.0/src/pad_on_sphere.egg-info/SOURCES.txt +22 -0
- pad_on_sphere-6.0.0/src/pad_on_sphere.egg-info/dependency_links.txt +1 -0
- pad_on_sphere-6.0.0/src/pad_on_sphere.egg-info/requires.txt +11 -0
- pad_on_sphere-6.0.0/src/pad_on_sphere.egg-info/top_level.txt +2 -0
- pad_on_sphere-6.0.0/src/pad_on_sphere.py +713 -0
- pad_on_sphere-6.0.0/src/source_for_Cxx_shared_library/CC_PAD_on_sphere_python_lib.cc +224 -0
- pad_on_sphere-6.0.0/src/source_for_Cxx_shared_library/CU_PAD_on_sphere_code.cc +489 -0
- pad_on_sphere-6.0.0/src/source_for_Cxx_shared_library/CU_kdtree_with_index.cc +1307 -0
- pad_on_sphere-6.0.0/src/source_for_Cxx_shared_library/_pad_on_sphere_native.cc +25 -0
- pad_on_sphere-6.0.0/tests/test_examples.py +236 -0
- pad_on_sphere-6.0.0/tests/test_pad_on_sphere.py +652 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Gregor Skok
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
KD-tree implementation
|
|
24
|
+
======================
|
|
25
|
+
|
|
26
|
+
src/source_for_Cxx_shared_library/CU_kdtree_with_index.cc contains an implementation
|
|
27
|
+
originally by SuYuxi, subsequently modified by Gregor Skok. The original notice
|
|
28
|
+
is preserved in that file and reproduced here for installed distributions.
|
|
29
|
+
|
|
30
|
+
MIT License
|
|
31
|
+
|
|
32
|
+
Copyright (c) 2019 SuYuxi
|
|
33
|
+
|
|
34
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
35
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
36
|
+
in the Software without restriction, including without limitation the rights
|
|
37
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
38
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
39
|
+
furnished to do so, subject to the following conditions:
|
|
40
|
+
|
|
41
|
+
The above copyright notice and this permission notice shall be included in all
|
|
42
|
+
copies or substantial portions of the Software.
|
|
43
|
+
|
|
44
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
45
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
46
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
47
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
48
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
49
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
50
|
+
SOFTWARE.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
include pyproject.toml setup.py README.md LICENSE
|
|
2
|
+
recursive-include src *.py
|
|
3
|
+
recursive-include src/source_for_Cxx_shared_library *.cc
|
|
4
|
+
recursive-include examples *.py *.ipynb *.nc
|
|
5
|
+
include tests/test_pad_on_sphere.py
|
|
6
|
+
include tests/test_examples.py
|
|
7
|
+
global-exclude *.so *.pyd *.dll *.dylib *.o *.obj *.py[cod]
|
|
8
|
+
prune build
|
|
9
|
+
prune dist
|
|
10
|
+
prune .github
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pad_on_sphere
|
|
3
|
+
Version: 6.0.0
|
|
4
|
+
Summary: Precipitation Attribution Distance for fields on a sphere
|
|
5
|
+
Author: Llorenç Lledó
|
|
6
|
+
Author-email: Gregor Skok <Gregor.Skok@fmf.uni-lj.si>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Project-URL: Homepage, https://github.com/skokg/PAD_on_Sphere
|
|
9
|
+
Project-URL: Repository, https://github.com/skokg/PAD_on_Sphere
|
|
10
|
+
Project-URL: Issues, https://github.com/skokg/PAD_on_Sphere/issues
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
14
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
15
|
+
Classifier: Operating System :: MacOS :: MacOS X
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: C++
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Requires-Dist: numpy>=1.23
|
|
24
|
+
Requires-Dist: pandas>=1.5
|
|
25
|
+
Requires-Dist: xarray>=2023.1
|
|
26
|
+
Provides-Extra: examples
|
|
27
|
+
Requires-Dist: netCDF4; extra == "examples"
|
|
28
|
+
Requires-Dist: matplotlib>=3.5; extra == "examples"
|
|
29
|
+
Requires-Dist: cartopy; extra == "examples"
|
|
30
|
+
Requires-Dist: scipy; extra == "examples"
|
|
31
|
+
Requires-Dist: regionmask; extra == "examples"
|
|
32
|
+
Requires-Dist: jupyterlab; extra == "examples"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# PAD on Sphere
|
|
36
|
+
|
|
37
|
+
Precipitation Attribution Distance (PAD) measures spatial displacement between
|
|
38
|
+
precipitation fields on a sphere. This package provides NumPy and xarray
|
|
39
|
+
interfaces to the C++ attribution implementation.
|
|
40
|
+
|
|
41
|
+
The official project title is **PAD on Sphere**. Both the pip distribution name
|
|
42
|
+
and the Python import name are `pad_on_sphere`.
|
|
43
|
+
|
|
44
|
+
GitHub repository: [skokg/PAD_on_Sphere](https://github.com/skokg/PAD_on_Sphere).
|
|
45
|
+
|
|
46
|
+
## Installation
|
|
47
|
+
|
|
48
|
+
Python 3.10 or newer is required. Install the package with:
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
pip install pad_on_sphere
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
To install from source:
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
pip install --no-binary=pad_on_sphere pad_on_sphere
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
This requires a C++ compiler and matching Python development headers.
|
|
61
|
+
|
|
62
|
+
## Usage
|
|
63
|
+
|
|
64
|
+
Use `calculate_attributions_from_numpy` with one-dimensional arrays of amounts
|
|
65
|
+
and latitude/longitude coordinates in degrees. Amounts must be nonnegative.
|
|
66
|
+
Pass precipitation volumes if volume weighting is required; this function does
|
|
67
|
+
not automatically normalize amounts or multiply them by grid-cell areas.
|
|
68
|
+
Attributions contain four columns: great-circle distance in metres, amount,
|
|
69
|
+
first-field positional index, and second-field positional index. The two
|
|
70
|
+
residual arrays use the units of the supplied amounts.
|
|
71
|
+
|
|
72
|
+
Pass the returned attribution array to
|
|
73
|
+
`calculate_PAD_on_sphere_from_attributions` to calculate the amount-weighted
|
|
74
|
+
mean attribution distance in metres. The attributions must be nonempty.
|
|
75
|
+
|
|
76
|
+
Use `calculate_attributions_from_xarrays` for precipitation in mm and cell
|
|
77
|
+
areas in km². Inputs use a `gridpoint` dimension with `lat` and `lon`
|
|
78
|
+
coordinates. This interface handles volume conversion and returns transport
|
|
79
|
+
and residual/gridded summaries. Its cutoff is in **km**, while the NumPy
|
|
80
|
+
interface's cutoff is in **metres**. See the function docstrings for details.
|
|
81
|
+
|
|
82
|
+
Import these functions from `pad_on_sphere`:
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from pad_on_sphere import (
|
|
86
|
+
calculate_attributions_from_numpy,
|
|
87
|
+
calculate_attributions_from_xarrays,
|
|
88
|
+
calculate_PAD_on_sphere_from_attributions,
|
|
89
|
+
)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
All public calculation and postprocessing functions, along with `Earth_radius`,
|
|
93
|
+
are exposed through the single `pad_on_sphere` module.
|
|
94
|
+
|
|
95
|
+
## Examples
|
|
96
|
+
|
|
97
|
+
The source distribution includes notebooks, sample NetCDF files,
|
|
98
|
+
and a Python example under `examples/`. To use their optional dependencies:
|
|
99
|
+
|
|
100
|
+
```sh
|
|
101
|
+
pip install "pad_on_sphere[examples]"
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
The examples extra includes SciPy for Cartopy's image reprojection, used by
|
|
105
|
+
the map plots. It is not required for the PAD calculations or correctness tests.
|
|
106
|
+
|
|
107
|
+
Run the script or open the notebooks with `examples/` as the working directory
|
|
108
|
+
so their `sample_data/` paths resolve.
|
|
109
|
+
Examples and sample data are included in the source archive rather than
|
|
110
|
+
installed into `site-packages`.
|
|
111
|
+
|
|
112
|
+
### Idealized Global field example
|
|
113
|
+
|
|
114
|
+
This example uses a global 1-degree grid (180 latitude rows by 360 longitude
|
|
115
|
+
columns). A rectangular region has 10 mm of observed rainfall; the forecast
|
|
116
|
+
contains the same region shifted 60 degrees east, leaving a 20-degree gap
|
|
117
|
+
between the rectangles. An attribution cutoff of 5500 km leaves the outer
|
|
118
|
+
edges unmatched.
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
import numpy as np
|
|
122
|
+
from pad_on_sphere import (
|
|
123
|
+
Earth_radius,
|
|
124
|
+
calculate_attributions_from_numpy,
|
|
125
|
+
calculate_PAD_on_sphere_from_attributions,
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
# Global grid-cell centres in degrees, without duplicating the date line.
|
|
129
|
+
spacing = 1.0
|
|
130
|
+
cutoff_km = 5500
|
|
131
|
+
lon, lat = np.meshgrid(np.arange(-180 + spacing / 2, 180, spacing),
|
|
132
|
+
np.arange(-90 + spacing / 2, 90, spacing))
|
|
133
|
+
|
|
134
|
+
# A rainy rectangle from 20°S to 20°N and 40°W to 0°; dry elsewhere.
|
|
135
|
+
observed = np.zeros_like(lat)
|
|
136
|
+
observed[(lat >= -20) & (lat < 20) & (lon >= -40) & (lon < 0)] = 10.0
|
|
137
|
+
forecast = np.roll(observed, shift=round(60 / spacing), axis=1) # 60° east.
|
|
138
|
+
|
|
139
|
+
# Spherical grid-cell areas in m², accounting for latitude.
|
|
140
|
+
area_m2 = Earth_radius ** 2 * np.deg2rad(spacing) * (
|
|
141
|
+
np.sin(np.deg2rad(lat + spacing / 2))
|
|
142
|
+
- np.sin(np.deg2rad(lat - spacing / 2))
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
# Convert rainfall depth in mm to water volume in m³.
|
|
146
|
+
forecast_m3 = forecast / 1000.0 * area_m2
|
|
147
|
+
observed_m3 = observed / 1000.0 * area_m2
|
|
148
|
+
|
|
149
|
+
# The NumPy interface takes flattened fields and matching coordinates.
|
|
150
|
+
attributions, remaining_forecast, remaining_observed = calculate_attributions_from_numpy(
|
|
151
|
+
forecast_m3.ravel(), observed_m3.ravel(), lat.ravel(), lon.ravel(),
|
|
152
|
+
distance_cutoff=cutoff_km * 1000, # NumPy cutoff is in metres.
|
|
153
|
+
random_seed=42,
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
distance_m = calculate_PAD_on_sphere_from_attributions(attributions)
|
|
157
|
+
print(f"PAD: {distance_m / 1000:.2f} km")
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
To display the fields, attributions and unattributed precipitation, append:
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
import matplotlib.pyplot as plt
|
|
164
|
+
import cartopy.crs as ccrs
|
|
165
|
+
|
|
166
|
+
# Convert each field's residual volume to rainfall depth in mm.
|
|
167
|
+
residual_observed = remaining_observed.reshape(lat.shape) * 1000 / area_m2
|
|
168
|
+
residual_forecast = remaining_forecast.reshape(lat.shape) * 1000 / area_m2
|
|
169
|
+
|
|
170
|
+
fig = plt.figure(figsize=(12, 11), layout="constrained")
|
|
171
|
+
grid = fig.add_gridspec(3, 1)
|
|
172
|
+
axes = [fig.add_subplot(grid[row], projection=ccrs.PlateCarree()) for row in range(2)]
|
|
173
|
+
ax_pdf = fig.add_subplot(grid[2])
|
|
174
|
+
ax_pdf.set_box_aspect(0.5)
|
|
175
|
+
ax_pdf.set_anchor("E")
|
|
176
|
+
for ax, fields, title in zip(axes,
|
|
177
|
+
[(observed, forecast), (residual_observed, residual_forecast)],
|
|
178
|
+
[f"Rainfall and sampled attributions (used cutoff: {cutoff_km:,} km)",
|
|
179
|
+
f"Unattributed precipitation (used cutoff: {cutoff_km:,} km)"]):
|
|
180
|
+
for rain, cmap, label in zip(fields, ["Blues", "Reds"], ["Observed", "Forecast"]):
|
|
181
|
+
image = ax.pcolormesh(lon, lat, np.ma.masked_equal(rain, 0), cmap=cmap,
|
|
182
|
+
vmin=0, vmax=10, alpha=0.6, transform=ccrs.PlateCarree())
|
|
183
|
+
fig.colorbar(image, ax=ax, location="right", label=f"{label} (mm)", shrink=0.7)
|
|
184
|
+
ax.coastlines()
|
|
185
|
+
ax.set_global()
|
|
186
|
+
ax.set_title(title)
|
|
187
|
+
|
|
188
|
+
# Plot at most 100 attributions; all are still used to calculate PAD.
|
|
189
|
+
indices = np.random.default_rng(42).choice(len(attributions),
|
|
190
|
+
min(100, len(attributions)), replace=False)
|
|
191
|
+
for distance, amount, source, target in attributions[indices]:
|
|
192
|
+
i, j = int(source), int(target)
|
|
193
|
+
axes[0].plot([lon.flat[i], lon.flat[j]], [lat.flat[i], lat.flat[j]],
|
|
194
|
+
"k.-", linewidth=0.8, markersize=3, transform=ccrs.Geodetic())
|
|
195
|
+
|
|
196
|
+
# Volume-weighted PDF using all attributions.
|
|
197
|
+
ax_pdf.hist(attributions[:, 0] / 1000, bins=25,
|
|
198
|
+
weights=attributions[:, 1], density=True, color="steelblue")
|
|
199
|
+
ax_pdf.axvline(distance_m / 1000, color="black", linestyle="--",
|
|
200
|
+
label=f"PAD distance: {distance_m / 1000:.1f} km")
|
|
201
|
+
ax_pdf.legend()
|
|
202
|
+
ax_pdf.set_xlabel("Attribution distance (km)")
|
|
203
|
+
ax_pdf.set_ylabel("Probability density (km⁻¹)")
|
|
204
|
+
ax_pdf.set_title(f"Attribution PDF (used cutoff: {cutoff_km:,} km)")
|
|
205
|
+
plt.show()
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Observed rainfall is blue and forecast rainfall is red. Dry cells are
|
|
209
|
+
transparent. The upper map shows a reproducible
|
|
210
|
+
random sample of up to 100 attributions in black; zero-distance matches appear
|
|
211
|
+
as points. The lower map shows observed residuals in blue and forecast residuals
|
|
212
|
+
in red, both as nonnegative rainfall depths in mm. Each map has two colourbars
|
|
213
|
+
on the right. Cartopy may download coastline data the first time it is used.
|
|
214
|
+
The bottom panel is a volume-weighted PDF histogram of all attribution
|
|
215
|
+
distances; unattributed precipitation is excluded.
|
|
216
|
+
|
|
217
|
+
PAD is the volume-weighted mean attribution distance.
|
|
218
|
+
It is not simply the longitude shift converted to kilometres.
|
|
219
|
+
The forecast column at 59.5°E and observed column at 39.5°W are more than
|
|
220
|
+
5500 km from any counterpart and remain unattributed.
|
|
221
|
+
Other residuals depend on the attribution. PAD averages only attributed amounts.
|
|
222
|
+
Returned residuals are in m³; the lower map converts them to mm.
|
|
223
|
+
|
|
224
|
+
## Authors and license
|
|
225
|
+
|
|
226
|
+
Gregor Skok, Faculty of Mathematics and Physics, University of Ljubljana,
|
|
227
|
+
Slovenia; and Llorenç Lledó, ECMWF (xarray/NumPy wrappers and notebooks).
|
|
228
|
+
|
|
229
|
+
Licensed under the MIT License. See [LICENSE](LICENSE).
|
|
230
|
+
|
|
231
|
+
## Reference
|
|
232
|
+
|
|
233
|
+
Skok, G. & Lledó, L. (2025). Spatial verification of global precipitation
|
|
234
|
+
forecasts. Quarterly Journal of the Royal Meteorological Society.
|
|
235
|
+
[https://doi.org/10.1002/qj.5006](https://doi.org/10.1002/qj.5006)
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
# PAD on Sphere
|
|
2
|
+
|
|
3
|
+
Precipitation Attribution Distance (PAD) measures spatial displacement between
|
|
4
|
+
precipitation fields on a sphere. This package provides NumPy and xarray
|
|
5
|
+
interfaces to the C++ attribution implementation.
|
|
6
|
+
|
|
7
|
+
The official project title is **PAD on Sphere**. Both the pip distribution name
|
|
8
|
+
and the Python import name are `pad_on_sphere`.
|
|
9
|
+
|
|
10
|
+
GitHub repository: [skokg/PAD_on_Sphere](https://github.com/skokg/PAD_on_Sphere).
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
Python 3.10 or newer is required. Install the package with:
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
pip install pad_on_sphere
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
To install from source:
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
pip install --no-binary=pad_on_sphere pad_on_sphere
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
This requires a C++ compiler and matching Python development headers.
|
|
27
|
+
|
|
28
|
+
## Usage
|
|
29
|
+
|
|
30
|
+
Use `calculate_attributions_from_numpy` with one-dimensional arrays of amounts
|
|
31
|
+
and latitude/longitude coordinates in degrees. Amounts must be nonnegative.
|
|
32
|
+
Pass precipitation volumes if volume weighting is required; this function does
|
|
33
|
+
not automatically normalize amounts or multiply them by grid-cell areas.
|
|
34
|
+
Attributions contain four columns: great-circle distance in metres, amount,
|
|
35
|
+
first-field positional index, and second-field positional index. The two
|
|
36
|
+
residual arrays use the units of the supplied amounts.
|
|
37
|
+
|
|
38
|
+
Pass the returned attribution array to
|
|
39
|
+
`calculate_PAD_on_sphere_from_attributions` to calculate the amount-weighted
|
|
40
|
+
mean attribution distance in metres. The attributions must be nonempty.
|
|
41
|
+
|
|
42
|
+
Use `calculate_attributions_from_xarrays` for precipitation in mm and cell
|
|
43
|
+
areas in km². Inputs use a `gridpoint` dimension with `lat` and `lon`
|
|
44
|
+
coordinates. This interface handles volume conversion and returns transport
|
|
45
|
+
and residual/gridded summaries. Its cutoff is in **km**, while the NumPy
|
|
46
|
+
interface's cutoff is in **metres**. See the function docstrings for details.
|
|
47
|
+
|
|
48
|
+
Import these functions from `pad_on_sphere`:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from pad_on_sphere import (
|
|
52
|
+
calculate_attributions_from_numpy,
|
|
53
|
+
calculate_attributions_from_xarrays,
|
|
54
|
+
calculate_PAD_on_sphere_from_attributions,
|
|
55
|
+
)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
All public calculation and postprocessing functions, along with `Earth_radius`,
|
|
59
|
+
are exposed through the single `pad_on_sphere` module.
|
|
60
|
+
|
|
61
|
+
## Examples
|
|
62
|
+
|
|
63
|
+
The source distribution includes notebooks, sample NetCDF files,
|
|
64
|
+
and a Python example under `examples/`. To use their optional dependencies:
|
|
65
|
+
|
|
66
|
+
```sh
|
|
67
|
+
pip install "pad_on_sphere[examples]"
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
The examples extra includes SciPy for Cartopy's image reprojection, used by
|
|
71
|
+
the map plots. It is not required for the PAD calculations or correctness tests.
|
|
72
|
+
|
|
73
|
+
Run the script or open the notebooks with `examples/` as the working directory
|
|
74
|
+
so their `sample_data/` paths resolve.
|
|
75
|
+
Examples and sample data are included in the source archive rather than
|
|
76
|
+
installed into `site-packages`.
|
|
77
|
+
|
|
78
|
+
### Idealized Global field example
|
|
79
|
+
|
|
80
|
+
This example uses a global 1-degree grid (180 latitude rows by 360 longitude
|
|
81
|
+
columns). A rectangular region has 10 mm of observed rainfall; the forecast
|
|
82
|
+
contains the same region shifted 60 degrees east, leaving a 20-degree gap
|
|
83
|
+
between the rectangles. An attribution cutoff of 5500 km leaves the outer
|
|
84
|
+
edges unmatched.
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
import numpy as np
|
|
88
|
+
from pad_on_sphere import (
|
|
89
|
+
Earth_radius,
|
|
90
|
+
calculate_attributions_from_numpy,
|
|
91
|
+
calculate_PAD_on_sphere_from_attributions,
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
# Global grid-cell centres in degrees, without duplicating the date line.
|
|
95
|
+
spacing = 1.0
|
|
96
|
+
cutoff_km = 5500
|
|
97
|
+
lon, lat = np.meshgrid(np.arange(-180 + spacing / 2, 180, spacing),
|
|
98
|
+
np.arange(-90 + spacing / 2, 90, spacing))
|
|
99
|
+
|
|
100
|
+
# A rainy rectangle from 20°S to 20°N and 40°W to 0°; dry elsewhere.
|
|
101
|
+
observed = np.zeros_like(lat)
|
|
102
|
+
observed[(lat >= -20) & (lat < 20) & (lon >= -40) & (lon < 0)] = 10.0
|
|
103
|
+
forecast = np.roll(observed, shift=round(60 / spacing), axis=1) # 60° east.
|
|
104
|
+
|
|
105
|
+
# Spherical grid-cell areas in m², accounting for latitude.
|
|
106
|
+
area_m2 = Earth_radius ** 2 * np.deg2rad(spacing) * (
|
|
107
|
+
np.sin(np.deg2rad(lat + spacing / 2))
|
|
108
|
+
- np.sin(np.deg2rad(lat - spacing / 2))
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
# Convert rainfall depth in mm to water volume in m³.
|
|
112
|
+
forecast_m3 = forecast / 1000.0 * area_m2
|
|
113
|
+
observed_m3 = observed / 1000.0 * area_m2
|
|
114
|
+
|
|
115
|
+
# The NumPy interface takes flattened fields and matching coordinates.
|
|
116
|
+
attributions, remaining_forecast, remaining_observed = calculate_attributions_from_numpy(
|
|
117
|
+
forecast_m3.ravel(), observed_m3.ravel(), lat.ravel(), lon.ravel(),
|
|
118
|
+
distance_cutoff=cutoff_km * 1000, # NumPy cutoff is in metres.
|
|
119
|
+
random_seed=42,
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
distance_m = calculate_PAD_on_sphere_from_attributions(attributions)
|
|
123
|
+
print(f"PAD: {distance_m / 1000:.2f} km")
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
To display the fields, attributions and unattributed precipitation, append:
|
|
127
|
+
|
|
128
|
+
```python
|
|
129
|
+
import matplotlib.pyplot as plt
|
|
130
|
+
import cartopy.crs as ccrs
|
|
131
|
+
|
|
132
|
+
# Convert each field's residual volume to rainfall depth in mm.
|
|
133
|
+
residual_observed = remaining_observed.reshape(lat.shape) * 1000 / area_m2
|
|
134
|
+
residual_forecast = remaining_forecast.reshape(lat.shape) * 1000 / area_m2
|
|
135
|
+
|
|
136
|
+
fig = plt.figure(figsize=(12, 11), layout="constrained")
|
|
137
|
+
grid = fig.add_gridspec(3, 1)
|
|
138
|
+
axes = [fig.add_subplot(grid[row], projection=ccrs.PlateCarree()) for row in range(2)]
|
|
139
|
+
ax_pdf = fig.add_subplot(grid[2])
|
|
140
|
+
ax_pdf.set_box_aspect(0.5)
|
|
141
|
+
ax_pdf.set_anchor("E")
|
|
142
|
+
for ax, fields, title in zip(axes,
|
|
143
|
+
[(observed, forecast), (residual_observed, residual_forecast)],
|
|
144
|
+
[f"Rainfall and sampled attributions (used cutoff: {cutoff_km:,} km)",
|
|
145
|
+
f"Unattributed precipitation (used cutoff: {cutoff_km:,} km)"]):
|
|
146
|
+
for rain, cmap, label in zip(fields, ["Blues", "Reds"], ["Observed", "Forecast"]):
|
|
147
|
+
image = ax.pcolormesh(lon, lat, np.ma.masked_equal(rain, 0), cmap=cmap,
|
|
148
|
+
vmin=0, vmax=10, alpha=0.6, transform=ccrs.PlateCarree())
|
|
149
|
+
fig.colorbar(image, ax=ax, location="right", label=f"{label} (mm)", shrink=0.7)
|
|
150
|
+
ax.coastlines()
|
|
151
|
+
ax.set_global()
|
|
152
|
+
ax.set_title(title)
|
|
153
|
+
|
|
154
|
+
# Plot at most 100 attributions; all are still used to calculate PAD.
|
|
155
|
+
indices = np.random.default_rng(42).choice(len(attributions),
|
|
156
|
+
min(100, len(attributions)), replace=False)
|
|
157
|
+
for distance, amount, source, target in attributions[indices]:
|
|
158
|
+
i, j = int(source), int(target)
|
|
159
|
+
axes[0].plot([lon.flat[i], lon.flat[j]], [lat.flat[i], lat.flat[j]],
|
|
160
|
+
"k.-", linewidth=0.8, markersize=3, transform=ccrs.Geodetic())
|
|
161
|
+
|
|
162
|
+
# Volume-weighted PDF using all attributions.
|
|
163
|
+
ax_pdf.hist(attributions[:, 0] / 1000, bins=25,
|
|
164
|
+
weights=attributions[:, 1], density=True, color="steelblue")
|
|
165
|
+
ax_pdf.axvline(distance_m / 1000, color="black", linestyle="--",
|
|
166
|
+
label=f"PAD distance: {distance_m / 1000:.1f} km")
|
|
167
|
+
ax_pdf.legend()
|
|
168
|
+
ax_pdf.set_xlabel("Attribution distance (km)")
|
|
169
|
+
ax_pdf.set_ylabel("Probability density (km⁻¹)")
|
|
170
|
+
ax_pdf.set_title(f"Attribution PDF (used cutoff: {cutoff_km:,} km)")
|
|
171
|
+
plt.show()
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Observed rainfall is blue and forecast rainfall is red. Dry cells are
|
|
175
|
+
transparent. The upper map shows a reproducible
|
|
176
|
+
random sample of up to 100 attributions in black; zero-distance matches appear
|
|
177
|
+
as points. The lower map shows observed residuals in blue and forecast residuals
|
|
178
|
+
in red, both as nonnegative rainfall depths in mm. Each map has two colourbars
|
|
179
|
+
on the right. Cartopy may download coastline data the first time it is used.
|
|
180
|
+
The bottom panel is a volume-weighted PDF histogram of all attribution
|
|
181
|
+
distances; unattributed precipitation is excluded.
|
|
182
|
+
|
|
183
|
+
PAD is the volume-weighted mean attribution distance.
|
|
184
|
+
It is not simply the longitude shift converted to kilometres.
|
|
185
|
+
The forecast column at 59.5°E and observed column at 39.5°W are more than
|
|
186
|
+
5500 km from any counterpart and remain unattributed.
|
|
187
|
+
Other residuals depend on the attribution. PAD averages only attributed amounts.
|
|
188
|
+
Returned residuals are in m³; the lower map converts them to mm.
|
|
189
|
+
|
|
190
|
+
## Authors and license
|
|
191
|
+
|
|
192
|
+
Gregor Skok, Faculty of Mathematics and Physics, University of Ljubljana,
|
|
193
|
+
Slovenia; and Llorenç Lledó, ECMWF (xarray/NumPy wrappers and notebooks).
|
|
194
|
+
|
|
195
|
+
Licensed under the MIT License. See [LICENSE](LICENSE).
|
|
196
|
+
|
|
197
|
+
## Reference
|
|
198
|
+
|
|
199
|
+
Skok, G. & Lledó, L. (2025). Spatial verification of global precipitation
|
|
200
|
+
forecasts. Quarterly Journal of the Royal Meteorological Society.
|
|
201
|
+
[https://doi.org/10.1002/qj.5006](https://doi.org/10.1002/qj.5006)
|