Metadata-Version: 2.4
Name: skyborn-spharm
Version: 0.2.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
Classifier: Topic :: Scientific/Engineering :: Physics
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Requires-Dist: numpy>=1.24.0
Requires-Dist: skyborn-backend>=0.2.0
Requires-Dist: pytest>=7.0 ; extra == 'dev'
Requires-Dist: matplotlib ; extra == 'dev'
Requires-Dist: pandas ; extra == 'dev'
Requires-Dist: xarray ; extra == 'dev'
Provides-Extra: dev
License-File: LICENSE
License-File: LICENSE.spherepack
Summary: Rust-accelerated spherical harmonic transforms for Python (SPHEREPACK + reduced Gaussian grids)
Keywords: atmospheric-science,meteorology,spherical-harmonics,spherepack,gaussian-grid
Author-email: Qianye Su <suqianye2000@gmail.com>
License-Expression: BSD-3-Clause
Requires-Python: >=3.9
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Bug Tracker, https://github.com/skyborn-org/skyborn-spharm/issues
Project-URL: Documentation, https://skyborn.readthedocs.io/
Project-URL: Homepage, https://github.com/skyborn-org/skyborn-spharm
Project-URL: Repository, https://github.com/skyborn-org/skyborn-spharm

<p align="center">
  <img src="assets/skyborn_spharm_logo.svg" alt="skyborn-spharm" width="220">
</p>

<h1 align="center">skyborn-spharm (<code>skybornspharm</code>)</h1>

<p align="center">
  <strong>Pure-Rust spherical harmonic transforms for atmospheric &amp; oceanic sciences in Python</strong>
</p>

<p align="center">
  Part of the <a href="https://github.com/skyborn-org"><strong>Skyborn</strong> (<code>skyborn-org</code>)</a> ecosystem.
</p>

---

## Why `skyborn-spharm`?

- **Pure-Rust `_spharm_rs` Core (v0.2.0)**: Backed by `faer` SIMD matrix kernels, `realfft` / `rustfft`, and adaptive `rayon` multithreading with zero `gfortran` / `libgfortran` / OpenBLAS runtime dependencies.
- **Zero-Copy C-Order & South-to-North (`S2N`) Support**: Accepts modern `(..., nlat, nlon)` C-contiguous arrays and ERA5/CMIP6 `S2N` (`-90° -> +90°`) grids directly without Python flips or Fortran transpositions, while automatically recognizing legacy `(nlat, nlon, ...)` calls.
- **Native `float32` & `float64` Precision**: Full `f64` internal Legendre quadrature and recurrence tables supporting both fast single-precision (`~1e-6` round-trip) and machine-precision double (`~1e-14` round-trip).
- **High-Degree & Ultra-High-Resolution Stability**: Eliminates legacy `SPHEREPACK 3.2` `int32` workspace overflow (`F480` `960×1920`) and `real32` Legendre $2^{n-1-\text{nex}}$ underflow ($n \ge 149$).
- **Packed Reduced Gaussian Grids**: Native `ReducedGaussianTransform` / `ReducedGaussianSpharmt` for ECMWF IFS / ERA5 reduced Gaussian grids (`O80`–`O1280`, `N320`, etc.).
- **Drop-In `pyspharm` Compatibility**: Full Python 3.9–3.15 and NumPy 1.24–2.x support with `SpharmTransform` (C-order default) and `Spharmt` (`auto` layout).

---

## Spherical Harmonics Visual Primer: Analysis, Spectral Calculus & Synthesis

### Waves on a Sphere: Orthogonal Spherical Harmonic Basis

<p align="center"><img src="assets/skyborn_spharm_modes_primer.svg" alt="Spherical Harmonic Modes Primer" width="880"/></p>

Just as a 1D Fourier series decomposes a signal around a circle into pure sine and cosine waves, **spherical harmonics** $Y_n^m(\theta,\lambda) = \bar{P}_n^m(\sin\theta)e^{im\lambda}$ decompose global geophysical fields (such as wind, vorticity, geopotential, and temperature) into smooth, orthogonal 2D wave patterns over the entire sphere:

- **Zonal modes ($m = 0$)**: Symmetric latitude belts with no variation in longitude, capturing the pole-to-equator mean state and zonal jet bands.
- **Tesseral modes ($0 < m < n$)**: Checkerboard wave cells across midlatitudes, capturing planetary Rossby waves and storm tracks.
- **Sectorial modes ($m = n$)**: Orange-slice wave sectors peaking along the equator, capturing tropical wave trains and Walker-scale oscillations.

Because $Y_n^m(\theta,\lambda)$ are smooth global eigenfunctions of the spherical Laplacian, spectral transforms completely eliminate the latitude-longitude **"pole problem"** caused by converging meridians and polar finite-difference singularities (Swarztrauber 1979, 1993, 1996; Adams & Swarztrauber 1999; Swarztrauber & Spotz 2000).

### From Grid to Spectrum and Back: Analysis, Spectral Calculus & Synthesis

<p align="center"><img src="assets/skyborn_spharm_analysis_synthesis.svg" alt="Spherical Harmonic Analysis and Synthesis" width="880"/></p>

<p align="center"><img src="assets/skyborn_spharm_transforms_overview.svg" alt="Analysis, Synthesis, and Algebraic Spectral Calculus Overview" width="880"/></p>

---

## Pure-Rust (`_spharm_rs`) vs. Legacy Fortran (`_spherepack`) Comparison

All benchmarks below were measured after warmup (median wall time and physical peak `ru_maxrss` delta) on Apple Silicon (`arm64`, Python 3.14, `--release` build) using realistic `S2N` C-order inputs (`Fortran E2E` includes the required `S2N -> N2S` flip and Fortran-order transpose/copy).

### 1. Architecture, Numerical Precision & Packaging

<p align="center"><img src="assets/skyborn_spharm_architecture.svg" alt="Pure-Rust vs. Legacy Fortran Architecture, Precision, and Packaging" width="880"/></p>

### 2. End-to-End Speed, Round-Trip Accuracy & Peak Working Memory

<p align="center"><img src="assets/skyborn_spharm_benchmark.svg" alt="Pure-Rust vs. Legacy Fortran Speed, Accuracy, and Peak Working Memory Benchmarks" width="880"/></p>

---

## Installation

```bash
pip install skyborn-spharm
```

## Quick Start

### Modern C-order & South-to-North (`S2N`) Zero-Copy API

```python
import numpy as np
from skybornspharm import SpharmTransform

# Typical ERA5 / CMIP6 C-order batch: (time, level, lat, lon), south-to-north
nlon, nlat = 360, 181
lats_s2n = np.linspace(-90.0, 90.0, nlat)
data_s2n = np.random.randn(12, 8, nlat, nlon).astype(np.float32)

sht = SpharmTransform(
    nlon=nlon,
    nlat=nlat,
    gridtype="regular",
    lat=lats_s2n,          # auto-detects S2N with zero Python flipping
    precision="auto",      # float32 -> single, float64 -> double
)

spec = sht.grdtospec(data_s2n)       # shape: (12, 8, nmdim)
inv_spec = sht.invlap(spec)          # spectral inverse Laplacian (-a^2 / [n(n+1)])
reconstructed = sht.spectogrd(spec)  # shape: (12, 8, 181, 360), S2N preserved
```

Standalone spectral utilities such as `skybornspharm.invlap(spec, rsphere=...)` also support 1D, C-order `(..., nmdim)`, and legacy `(nmdim, ...)` spectral arrays directly.

### Legacy `pyspharm`-Compatible & Reduced Gaussian Usage

```python
import numpy as np
from skybornspharm import Spharmt, ReducedGaussianTransform

# Drop-in Spharmt (auto-detects both (lat, lon, ...) legacy and (..., lat, lon) C-order)
sht = Spharmt(nlon=144, nlat=73, gridtype="gaussian")
field = np.random.randn(73, 144)
spec = sht.grdtospec(field)
reconstructed = sht.spectogrd(spec)

# Packed ECMWF reduced Gaussian grid (C-order leading batch axes)
pl = np.array([20, 28, 36, 40, 40, 36, 28, 20], dtype=np.int32)
rg = ReducedGaussianTransform(pl, precision="double")
packed_spec = rg.grdtospec(np.random.randn(4, int(pl.sum())))
```

Note: `skyborn.spharm` and `skyborn.windspharm` in the `skyborn` package seamlessly wrap `skybornspharm` (with automatic C-order detection enabled by default).

## License

- Python wrappers, Pure-Rust engine, and modern extensions: BSD 3-Clause License ([LICENSE](LICENSE))
- SPHEREPACK mathematical reference attribution: SPHEREPACK License ([LICENSE.spherepack](LICENSE.spherepack))

