Metadata-Version: 2.4
Name: pad_on_sphere
Version: 6.0.1
Summary: Precipitation Attribution Distance for fields on a sphere
Author-email: Gregor Skok <Gregor.Skok@fmf.uni-lj.si>
License-Expression: MIT
Project-URL: Homepage, https://github.com/skokg/PAD_on_Sphere
Project-URL: Repository, https://github.com/skokg/PAD_on_Sphere
Project-URL: Issues, https://github.com/skokg/PAD_on_Sphere/issues
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: C++
Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.23
Requires-Dist: pandas>=1.5
Requires-Dist: xarray>=2023.1
Provides-Extra: examples
Requires-Dist: netCDF4; extra == "examples"
Requires-Dist: matplotlib>=3.5; extra == "examples"
Requires-Dist: cartopy; extra == "examples"
Requires-Dist: scipy; extra == "examples"
Requires-Dist: regionmask; extra == "examples"
Requires-Dist: jupyterlab; extra == "examples"
Dynamic: license-file

# PAD on Sphere

Precipitation Attribution Distance (PAD) measures spatial displacement between
precipitation fields on a sphere. This package provides NumPy and xarray
interfaces to the C++ attribution implementation.

The official project title is **PAD on Sphere**. Both the pip distribution name
and the Python import name are `pad_on_sphere`.

GitHub repository: [skokg/PAD_on_Sphere](https://github.com/skokg/PAD_on_Sphere).

## Installation

Python 3.10 or newer is required. Install the package with:

```sh
pip install pad_on_sphere
```

To install from source:

```sh
pip install --no-binary=pad_on_sphere pad_on_sphere
```

Compiling from source requires a C++ compiler: GCC on Linux, MSVC Build Tools
on Windows, or Xcode Command Line Tools on macOS.

Alternatively, download the source from the
[GitHub repository](https://github.com/skokg/PAD_on_Sphere) and run `make` in the
project's root directory on Linux. This requires GNU Make and a C++ compiler.
Running `make` creates `libpad_on_sphere.so` in the `src` folder.
Copy `pad_on_sphere.py` and `libpad_on_sphere.so` from `src` into the folder
containing your Python script. NumPy, pandas and xarray must also be installed.

## Usage

Use `calculate_attributions_from_numpy` with one-dimensional arrays of amounts
and latitude/longitude coordinates in degrees. Amounts must be nonnegative.
Pass precipitation volumes if volume weighting is required; this function does
not automatically normalize amounts or multiply them by grid-cell areas.
Attributions contain four columns: great-circle distance in metres, amount,
first-field positional index, and second-field positional index. The two
residual arrays use the units of the supplied amounts.

Pass the returned attribution array to
`calculate_PAD_on_sphere_from_attributions` to calculate the amount-weighted
mean attribution distance in metres. The attributions must be nonempty.

Use `calculate_attributions_from_xarrays` for precipitation in mm and cell
areas in km². Inputs use a `gridpoint` dimension with `lat` and `lon`
coordinates. This interface handles volume conversion and returns transport
and residual/gridded summaries. Its cutoff is in **km**, while the NumPy
interface's cutoff is in **metres**. See the function docstrings for details.

Import these functions from `pad_on_sphere`:

```python
from pad_on_sphere import (
    calculate_attributions_from_numpy,
    calculate_attributions_from_xarrays,
    calculate_PAD_on_sphere_from_attributions,
)
```

All public calculation and postprocessing functions, along with `Earth_radius`,
are exposed through the single `pad_on_sphere` module.

## Examples

The source distribution includes notebooks, sample NetCDF files,
and a Python example under `examples/`. To use their optional dependencies:

```sh
pip install "pad_on_sphere[examples]"
```

The examples extra includes SciPy for Cartopy's image reprojection, used by
the map plots. It is not required for the PAD calculations or correctness tests.

Run the script or open the notebooks with `examples/` as the working directory
so their `sample_data/` paths resolve.
Examples and sample data are included in the source archive rather than
installed into `site-packages`.

### Idealized Global field example

This example uses a global 1-degree grid (180 latitude rows by 360 longitude
columns). A rectangular region has 10 mm of observed rainfall; the forecast
contains the same region shifted 60 degrees east, leaving a 20-degree gap
between the rectangles. An attribution cutoff of 5500 km leaves the outer
edges unmatched.

```python
import numpy as np
from pad_on_sphere import (
    Earth_radius,
    calculate_attributions_from_numpy,
    calculate_PAD_on_sphere_from_attributions,
)

# Global grid-cell centres in degrees, without duplicating the date line.
spacing = 1.0
cutoff_km = 5500
lon, lat = np.meshgrid(np.arange(-180 + spacing / 2, 180, spacing),
                       np.arange(-90 + spacing / 2, 90, spacing))

# A rainy rectangle from 20°S to 20°N and 40°W to 0°; dry elsewhere.
observed = np.zeros_like(lat)
observed[(lat >= -20) & (lat < 20) & (lon >= -40) & (lon < 0)] = 10.0
forecast = np.roll(observed, shift=round(60 / spacing), axis=1)  # 60° east.

# Spherical grid-cell areas in m², accounting for latitude.
area_m2 = Earth_radius ** 2 * np.deg2rad(spacing) * (
    np.sin(np.deg2rad(lat + spacing / 2))
    - np.sin(np.deg2rad(lat - spacing / 2))
)

# Convert rainfall depth in mm to water volume in m³.
forecast_m3 = forecast / 1000.0 * area_m2
observed_m3 = observed / 1000.0 * area_m2

# The NumPy interface takes flattened fields and matching coordinates.
attributions, remaining_forecast, remaining_observed = calculate_attributions_from_numpy(
    forecast_m3.ravel(), observed_m3.ravel(), lat.ravel(), lon.ravel(),
    distance_cutoff=cutoff_km * 1000,  # NumPy cutoff is in metres.
    random_seed=42,
)

distance_m = calculate_PAD_on_sphere_from_attributions(attributions)
print(f"PAD: {distance_m / 1000:.2f} km")
```

To display the fields, attributions and unattributed precipitation, append:

```python
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

# Convert each field's residual volume to rainfall depth in mm.
residual_observed = remaining_observed.reshape(lat.shape) * 1000 / area_m2
residual_forecast = remaining_forecast.reshape(lat.shape) * 1000 / area_m2

fig = plt.figure(figsize=(12, 11), layout="constrained")
grid = fig.add_gridspec(3, 1)
axes = [fig.add_subplot(grid[row], projection=ccrs.PlateCarree()) for row in range(2)]
ax_pdf = fig.add_subplot(grid[2])
ax_pdf.set_box_aspect(0.5)
ax_pdf.set_anchor("E")
for ax, fields, title in zip(axes,
        [(observed, forecast), (residual_observed, residual_forecast)],
        [f"Rainfall and sampled attributions (used cutoff: {cutoff_km:,} km)",
         f"Unattributed precipitation (used cutoff: {cutoff_km:,} km)"]):
    for rain, cmap, label in zip(fields, ["Blues", "Reds"], ["Observed", "Forecast"]):
        image = ax.pcolormesh(lon, lat, np.ma.masked_equal(rain, 0), cmap=cmap,
                              vmin=0, vmax=10, alpha=0.6, transform=ccrs.PlateCarree())
        fig.colorbar(image, ax=ax, location="right", label=f"{label} (mm)", shrink=0.7)
    ax.coastlines()
    ax.set_global()
    ax.set_title(title)

# Plot at most 100 attributions; all are still used to calculate PAD.
indices = np.random.default_rng(42).choice(len(attributions),
                                          min(100, len(attributions)), replace=False)
for distance, amount, source, target in attributions[indices]:
    i, j = int(source), int(target)
    axes[0].plot([lon.flat[i], lon.flat[j]], [lat.flat[i], lat.flat[j]],
                 "k.-", linewidth=0.8, markersize=3, transform=ccrs.Geodetic())

# Volume-weighted PDF using all attributions.
ax_pdf.hist(attributions[:, 0] / 1000, bins=25,
             weights=attributions[:, 1], density=True, color="steelblue")
ax_pdf.axvline(distance_m / 1000, color="black", linestyle="--",
               label=f"PAD distance: {distance_m / 1000:.1f} km")
ax_pdf.legend()
ax_pdf.set_xlabel("Attribution distance (km)")
ax_pdf.set_ylabel("Probability density (km⁻¹)")
ax_pdf.set_title(f"Attribution PDF (used cutoff: {cutoff_km:,} km)")
plt.show()
```

Observed rainfall is blue and forecast rainfall is red. Dry cells are
transparent. The upper map shows a reproducible
random sample of up to 100 attributions in black; zero-distance matches appear
as points. The lower map shows observed residuals in blue and forecast residuals
in red, both as nonnegative rainfall depths in mm. Each map has two colourbars
on the right. Cartopy may download coastline data the first time it is used.
The bottom panel is a volume-weighted PDF histogram of all attribution
distances; unattributed precipitation is excluded.

PAD is the volume-weighted mean attribution distance.
It is not simply the longitude shift converted to kilometres.
The forecast column at 59.5°E and observed column at 39.5°W are more than
5500 km from any counterpart and remain unattributed.
Other residuals depend on the attribution. PAD averages only attributed amounts.
Returned residuals are in m³; the lower map converts them to mm.

## Authors and license

Gregor Skok, Faculty of Mathematics and Physics, University of Ljubljana,
Slovenia; and Llorenç Lledó, ECMWF (xarray/NumPy wrappers and notebooks).

Licensed under the MIT License. See [LICENSE](LICENSE).

## Reference

Skok, G. & Lledó, L. (2025). Spatial verification of global precipitation
forecasts. Quarterly Journal of the Royal Meteorological Society.
[https://doi.org/10.1002/qj.5006](https://doi.org/10.1002/qj.5006)

