Metadata-Version: 2.2
Name: LaplaceX
Version: 1.1.0
Summary: Numerical Laplace transforms and log-plane wavelet exponential decomposition
Keywords: laplace-transform,inverse-laplace,signal-processing,numerical-methods,exponential-decomposition,wavelet,scientific-computing
Author: Vozmishchev Artem
License: MIT
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
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 :: C++
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Topic :: Scientific/Engineering :: Physics
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Project-URL: Homepage, https://github.com/BRUTALLOLOL/LaplaceX
Project-URL: Documentation, https://github.com/BRUTALLOLOL/LaplaceX#readme
Project-URL: Repository, https://github.com/BRUTALLOLOL/LaplaceX
Project-URL: Bug Tracker, https://github.com/BRUTALLOLOL/LaplaceX/issues
Requires-Python: >=3.10
Requires-Dist: numpy>=1.24
Provides-Extra: plot
Requires-Dist: matplotlib>=3.7; extra == "plot"
Provides-Extra: data
Requires-Dist: pandas>=2.0; extra == "data"
Provides-Extra: benchmark
Requires-Dist: scipy>=1.10; extra == "benchmark"
Requires-Dist: mpmath>=1.3; extra == "benchmark"
Requires-Dist: matplotlib>=3.7; extra == "benchmark"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-benchmark; extra == "dev"
Requires-Dist: hypothesis; extra == "dev"
Requires-Dist: scipy; extra == "dev"
Requires-Dist: matplotlib>=3.7; extra == "dev"
Requires-Dist: pandas>=2.0; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Provides-Extra: all
Requires-Dist: LaplaceX[benchmark,data,dev,plot]; extra == "all"
Description-Content-Type: text/markdown

# LaplaceX 1.1.0

**Python library for exponential-mixture fitting and numerical Laplace transforms.**

LaplaceX combines adaptive Gauss–Kronrod forward quadrature, Weeks–Laguerre
inversion, and exponential fitting seeded by wavelet analysis in logarithmic
time. Accuracy depends on the signal, sampling window, and configuration;
see [evaluation and limitations](benchmarks/research/REPORT.md).

Version 1.1.0 is a recent research release. Tests establish a checked software
snapshot; the experimental example and single-machine timings do not establish
broad experimental validation or long-term adoption.

| Operation | Implementation |
|---|---|
| Callable forward transform | Adaptive embedded G7–K15 quadrature |
| Sampled forward transform | Natural cubic spline, integrated at every knot |
| Inverse transform | Weeks–Laguerre expansion with automatic scale search |
| Exponential decomposition | Persistent log-wavelet ridges, joint QR/LM fitting, BIC |
| Python interface | NumPy arrays and a compiled C++ core via pybind11 |

---


**Requirements:** Python ≥ 3.10, NumPy ≥ 1.24.
Optional extras: `matplotlib` (plotting), `pandas` (DataFrame export).

---

<!-- comparison:start -->
## Component recovery: scope and evidence

Decomposition fits real decaying exponentials and selects a count up to the
component budget. It estimates amplitudes and rates; oscillation frequencies
are not estimated. Log-time wavelet proposals initialize a joint fit to the
original samples. Forward quadrature and Weeks inversion are separate routines.

The expanded evaluation keeps the 1.0.0 numerical core fixed. Its main route
disables the rate-grid retry in every section; public-default retry is a
separate sensitivity check. Every comparator's outcomes and failures are retained.

| Evaluation | Log wavelets | Variable projection + BIC | Matrix pencil + refinement |
|---|---:|---:|---:|
| Reused validation/regression mixtures: correct counts | 480/480 | 479/480 | 235/240 |
| New noise/separation sweep: correct counts | 708/960 | 737/960 | 323/480 |
| New sweep: correct count **and** rate/reconstruction target | 573/960 | 613/960 | 280/480 |

Matrix-pencil denominators include only originally uniform grids. The reused
sets include cases that informed development; the new sweep protocol was frozen
before evaluation. It uses two components, six rate ratios (1.1–10), four Gaussian
noise levels (0.0001–0.05), two sampling grids, and twenty realizations per cell.
Neither result establishes reliability for arbitrary decay data.

### What wavelet initialization improves

An external harness compiles log-time, linear-coordinate, and rate-grid routes
with the **same native optimizer, selection rules, compiler, and wrapper**.
Both coordinate detectors target peaks of the negative log-time derivative;
their point/scale budgets and relative filter widths match.

On the separated three-mode B fixture, the log route takes **1.23 ms**, versus
**8.88 ms** for linear coordinates and **12.29 ms** for rate-grid proposals
(**7.22×** and **9.99×** ratios). On the close pair, **linear coordinates are
faster: 6.80 ms versus 7.96 ms**. Times are medians of seven shuffled runs on
one Intel i7-7700HQ/Windows machine. All twelve development-exposed fixtures,
timings, and accuracy checks are reported; the single-mode shortcut is shared.

These controls support a reduction in proposal-search cost for some multiscale
signals. The earlier SciPy timing ratios include Python callback and solver
differences and are not used to isolate the wavelet contribution.

### Count recovery and parameter uncertainty

Correct counts do not ensure correct individual rates. The new sweep's
95th-percentile rate error among correctly counted log-wavelet fits is **31.85%**,
with extreme failures retained in the raw records. The joint target above
requires maximum rate error ≤10% and clean-signal RMSE ≤noise standard deviation.
The old 21.07% worst noisy case is also reproduced by a true-count variable-
projection fit; a local information calculation indicates weak identifiability.
Cramér–Rao diagnostics assume known count and independent Gaussian noise and do
not certify automatic model selection.

The clean 1000:1 weak-mode examples distinguish a premature residual-stop rule
from stronger count selection: SciPy BIC and known-count fits also recover the
weak modes. Successful clean fits generally reach comparable float64 accuracy.

Two openly licensed measured fluorescence tails add an application example.
Their true component counts are unknown, and an additional gate delay changes
the delayed-fluorescence count. Instrument response, background, and photon-noise
models matter before assigning physical lifetimes.

[Expanded report and reproduction instructions](benchmarks/research/REPORT.md) ·
[Frozen protocol](benchmarks/research/PROTOCOL.md) ·
[Release comparisons and historical measurements](benchmarks/COMPARISON.md) ·
[Historical numerical audit](benchmarks/ACCURACY.md)
<!-- comparison:end -->

## Quick Start

```python
import numpy as np
from laplacex import laplace, inverse, decompose, reconstruct, utils

# --- 1. Forward transform ---------------------------------------------------
# F(s) for f(t) = exp(-2t)  →  should equal 1/(s+2)
s_vals = np.array([1+0j, 2+0j, 3+1j])
F = laplace(lambda t: np.exp(-2*t), s_vals)

# --- 2. Inverse transform  ---------------------------
t = np.linspace(0.1, 5, 100)
f_rec = inverse(lambda s: 1/(s+2), t)          # recovers exp(-2t)

# --- 3. Decompose a noisy multi-exponential signal --------------------------
t   = np.linspace(0.01, 15, 600)
f   = utils.gen_exp_sum(t, [2.0, 0.5], [0.5, 5.0])
f_n = utils.add_noise(f, sigma=0.02, seed=0)

ec = decompose(t, f_n)       # → ExponentialComponents
print(ec)
# ExponentialComponents(2 components, significances=[0.832, 0.168])

for c in ec:
    print(f"  τ = {c.decay_time:.3f}   A = {c.amplitude:.3f}")

# --- 4. Reconstruct ---------------------------------------------------------
f_hat = reconstruct(ec, t)

# --- 5. Plot (requires matplotlib) -----------------------------------------
ec.plot(t_eval=t, t_original=t, f_original=f_n)
```

---

## API Reference

### Free functions

| Function | Description |
|---|---|
| `laplace(f, s, t=None)` | Forward Laplace transform F(s) |
| `inverse(F, t_eval, ...)` | Inverse Laplace transform f(t) |
| `decompose(t, f, cfg=None)` | Wavelet decomposition into `ExponentialComponents` |
| `reconstruct(comps, t_eval)` | Reconstruct f(t) from components |

### Classes

#### `LaplaceTransform`

Stateful engine — configure once, call many times. Caches decomposition
results so that `inverse(None, ..., method='auto')` uses the component
representation. An explicitly supplied transform callable takes precedence.

```python
from laplacex import LaplaceTransform

lt = LaplaceTransform(tol=1e-12, weeks_N=128)
F  = lt.laplace(lambda t: np.exp(-t), s=2+1j)
ec = lt.decompose(t, f)             # cached internally
f_rec = lt.inverse(None, t_eval, method='auto')
```

#### `ExponentialComponents`

Container for decomposition results with NumPy arrays, filtering, export,
and visualisation.

```python
ec.amplitudes    # ndarray, shape (n,)
ec.rates         # ndarray, decay rates λ_k
ec.decay_times   # ndarray, τ_k = 1/λ_k
ec.significances # ndarray, normalized absolute amplitudes; not p-values

ec.filter(min_significance=0.1)
ec.top(3)
ec.reconstruct(t_eval)
ec.reconstruct_laplace(s_eval)
ec.to_dict()
ec.to_dataframe()   # requires pandas
ec.plot(t_eval, t_original, f_original)
```

### Configuration

```python
from laplacex import TransformConfig, DecomposeConfig

cfg = TransformConfig()
cfg.tol        = 1e-12     # absolute quadrature tolerance
cfg.rel_tol    = 1e-10
cfg.max_levels = 25
cfg.t_max      = 1e8

dcfg = DecomposeConfig()
dcfg.n_scales      = 16    # wavelet scales (default)
dcfg.n_log_points  = 256   # log-plane initialization grid (default)
dcfg.scale_min     = 0.05
dcfg.scale_max     = 0.5
dcfg.wavelet       = "mexh"
dcfg.snr_threshold = 5.0
dcfg.model_selection = "bic"  # or "aicc"
dcfg.use_aic       = True   # legacy name: enable information-criterion pruning
```

### Utilities (`laplacex.utils`)

```python
from laplacex import utils

t = np.linspace(0.01, 10, 500)
f = utils.gen_exp_sum(t, [1.0, 0.5], [1.0, 3.0])
f = utils.add_noise(f, sigma=0.05, seed=42)
s = utils.estimate_noise(f)
x, ft = utils.to_log_plane(t, f, n=512)
```

---

## Theoretical Background

Logarithmic coordinates `x = ln(t)` help analyse signals with widely separated
decay times. This does not remove the ill-conditioning of inverse Laplace
transforms or guarantee recovery of components from noisy data.

The decomposition algorithm:

1. Resamples `g(x) = f(exp(x))` with constant boundary extension.
2. Finds persistent Mexican-Hat zero crossings at extrema of the smoothed log derivative.
3. Tracks ridges from fine to coarse scales, retaining branches when they merge.
4. Fits all persistent components together on the original samples using an
   analytic Jacobian, Levenberg–Marquardt steps and scaled Householder QR.
5. Searches residual ridges for weak components and propagates sample noise
   through both interpolation and wavelet weights.
6. Selects component count using BIC by default, with uncertainty screening and
   refitted deletions; uses rate-grid proposals if the residual warrants a retry.

For `f(t) = A exp(-rate*t)`, the negative log derivative is
`A exp(z-exp(z))`, where `z=x+log(rate)`. Rates translate the same profile along
the log axis while preserving its height. This lets one wavelet scale range
initialize modes across several orders of magnitude. Log-grid estimates are
initial guesses; final rates and amplitudes are fitted to the original observations.

Only the Mexican Hat (`"mexh"`) wavelet is currently implemented.
Decomposition fits real decaying exponentials with signed amplitudes and recognizes
constant-only signals; it does not estimate oscillation frequencies. Explicitly supplied
oscillatory components can still be reconstructed in time and Laplace space.

## Numerical behaviour

Callable forward transforms integrate from zero to `cfg.t_max`. The tolerance
controls quadrature error, not the omitted tail: increase `t_max` when the
signal decays slowly. Failed adaptive convergence raises `RuntimeError`.

Sampled transforms integrate a natural cubic spline up to
`min(t[-1], cfg.t_max)`. If the first sample is after zero, the first spline
segment is extrapolated to zero. Samples imply zero signal beyond the final
time; include enough of the tail in your data. Times must be finite, increasing,
and nonnegative (strictly positive for decomposition).

The inverse returns real signals and uses the actual Weeks method. `N` controls
the number of Laguerre terms, `sigma` selects the contour to the right of all
singularities, and `b` selects the scale. Zero requests automatic selection
(`sigma = 4 / max(t_eval)`, with a search for `b`). Highly oscillatory signals
can require larger `N`; check convergence by increasing it. Automatic choices
are heuristics and do not provide an error guarantee. Use explicit parameters
for growing signals or difficult transforms. At `t=0` the returned value is
the finite expansion's right-limit estimate, when that limit exists.

Forward frequencies, inverse times, and component evaluation arrays preserve
their shapes, including scalars and NumPy slices. Sample data are one-dimensional.

## Development and verification

```bash
python -m pip install ".[dev]"
python -m pytest
python benchmarks/accuracy.py --output benchmarks/local.json
```

Building from source requires a C++17 compiler. The accuracy script uses known
analytic transform pairs; installing `mpmath` enables 60-digit reference
evaluation. [The verification report](benchmarks/ACCURACY.md) includes before
and after measurements and compatibility changes.

---

## License

MIT © 2026 Vozmishchev Artem
