spheresmooth 0.1.1
Geometry-aware spline smoothing and geodesic modeling for spherical data in Python
Requires Python: >=3.9

# spheresmooth (Python) 

A Python port of the **spheresmooth** R package for spherical geometry and spline smoothing on the unit sphere.  
The library provides utilities for coordinate transforms, geodesics, and penalized spherical smoothing using piecewise geodesic splines.

This project is a work-in-progress port of the original R implementation, with many components rewritten in clean, modular Python.

---

## Documentation

Full documentation is available at:

https://seyoung-230.github.io/spheresmooth-python/

## Authors

- **Se-Young Lee**, Sungshin Women’s University  
  Email: 220254005@sungshin.ac.kr

- **Kwan-Young Bak**, Sungshin Women’s University  
  Email: kybak@sungshin.ac.kr  

## motivation

Spherical data arise naturally in many scientific fields, including geophysics, meteorology, biomechanics, computer vision, and robotics.
Standard Euclidean smoothing methods often fail to respect the intrinsic geometry of the sphere, leading to distorted trajectories and inaccurate inference.

`spheresmooth` aims to provide geometry-aware tools for analyzing spherical data directly on the unit sphere, avoiding ad hoc projections to Euclidean space.

---

## License

GPL-3

---

## Installation

```
pip install spheresmooth
```

---

## Requirements

`spheresmooth` requires the following dependencies:

### Core dependencies

| Package | Version (recommended) | Description |
|--------|------------------------|-------------|
| Python | 3.9+                   | Core language requirement |
| NumPy  | >= 1.24                | Numerical computations |
| pandas | >= 1.5                 | Internal data loading and handling (`import pandas as pd`) |
| importlib.resources | stdlib (Python ≥ 3.9) | Access to packaged data files |

### Optional dependencies (examples and visualization)

| Package     | Version (recommended) | Description |
|-------------|------------------------|-------------|
| matplotlib  | >= 3.7                 | Plotting and visualization in example scripts (`import matplotlib.pyplot as plt`) |
| geopandas   | >= 0.13                | Geographic data handling and map-based examples (`import geopandas as gpd`) |

The core library uses `pandas` and `importlib.resources` solely for internal
data loading.  
`importlib.resources` is part of the Python standard library (Python ≥ 3.9) and
does not need to be installed separately.

Visualization-related dependencies (`matplotlib`, `geopandas`) are required
**only** for running example scripts and generating figures. They are not
needed for using the core functionality of the library.

If you install `spheresmooth` via **pip**, the core dependencies will be
installed automatically:

```bash
pip install spheresmooth
```

To install the optional dependencies for examples and visualization, use:

```bash
pip install spheresmooth[viz]
```

---

## Features

### Coordinate Transformations
- Convert Cartesian ↔ Spherical coordinates  
- Batch processing with NumPy  
- Consistent handling of row-wise/column-wise inputs  

### Geometry Utilities
- Compute geodesics on the sphere  
- Normalize vectors  
- Spherical distance functions  
- Projection and gradient operators  

### Smoothing Functions (In Progress)
- Penalized piecewise geodesic spline smoothing  
- Python implementation of the structure of the R function `penalized_linear_spherical_spline()`  
- Full Riemannian optimization is currently under development  


## Example

```python
import numpy as np
from spheresmooth import cartesian_to_spherical

points = np.array([
    [1/np.sqrt(3), 1/np.sqrt(3), 1/np.sqrt(3)],
    [-1/np.sqrt(3), 1/np.sqrt(3), -1/np.sqrt(3)],
])

theta_phi = cartesian_to_spherical(points)
print(theta_phi)
```

---

## APW Spherical Spline Example

The following example demonstrates how to fit a penalized spherical spline to
the **Apparent Polar Wander (APW)** path and visualize the result on a world map.

The APW dataset consists of time-indexed observations on the unit sphere,
represented in spherical coordinates \((theta, phi)\).

### Workflow Overview

1. Load spherical APW data \((theta, phi)\)
2. Convert spherical coordinates to Cartesian coordinates on the unit sphere
3. Select knot locations using quantiles of the time variable
4. Fit a penalized piecewise geodesic spline using BIC-based model selection
5. Convert fitted control points back to spherical coordinates
6. Evaluate the fitted geodesic curve and visualize it on a world map

### Example Code (Simplified)

```python
import spheresmooth as ss
import numpy as np

# Load APW data: columns = (t, theta, phi)
apw = ss.load_apw()
t = apw.iloc[:, 0].values
spherical = apw.iloc[:, 1:3].values

# Spherical → Cartesian
y = ss.spherical_to_cartesian(spherical)

# Knot selection
dimension = 15
knots = ss.knots_quantile(t, dimension)
lambdas = np.exp(np.linspace(np.log(1e-7), np.log(1), 40))

# Penalized spherical spline fit
fit = ss.penalized_linear_spherical_spline(
    t=t,
    y=y,
    dimension=dimension,
    initial_knots=knots,
    lambdas=lambdas
)

```

### APW Spherical Spline Example

![APW spherical spline example](https://github.com/seyoung-230/spheresmooth-python/blob/main/assets/apw_figure.png?raw=1)

### Interpretation

The fitted model represents the APW trajectory as a sequence of connected
great-circle segments on the unit sphere.
A sparsity-inducing penalty controls changes in velocity between segments,
resulting in a smooth yet geometry-respecting trajectory.

The smoothing parameter lambda is selected using the Bayesian Information
Criterion (BIC), balancing goodness-of-fit and model complexity.

This example illustrates how `spheresmooth` performs intrinsic smoothing
directly on the sphere, avoiding ad hoc Euclidean projections.