Metadata-Version: 2.5
Name: the-hawkes-package
Version: 1.0.0
Summary: Simulation and Bayesian inference for temporal and spatio-temporal Hawkes processes.
Project-URL: Homepage, https://github.com/jeMATHfischer/TheHawkesPackage
Project-URL: Documentation, https://jeMATHfischer.github.io/TheHawkesPackage/
Project-URL: Repository, https://github.com/jeMATHfischer/TheHawkesPackage
Project-URL: Issues, https://github.com/jeMATHfischer/TheHawkesPackage/issues
Project-URL: Changelog, https://github.com/jeMATHfischer/TheHawkesPackage/blob/master/CHANGELOG.md
Author-email: Jens Fischer <jefischer@posteo.de>
Maintainer-email: Jens Fischer <jefischer@posteo.de>
License-Expression: MIT
License-File: LICENSE
Keywords: bayesian-inference,hawkes-process,mcmc,metropolis-hastings,ogata-thinning,parameter-estimation,particle-filter,point-process,self-exciting,sequential-monte-carlo,spatio-temporal,stochastic-simulation
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
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: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: numpy>=1.22
Requires-Dist: scipy>=1.8
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: furo>=2024.5.6; extra == 'dev'
Requires-Dist: ipykernel>=6.29; extra == 'dev'
Requires-Dist: matplotlib>=3.7; extra == 'dev'
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: myst-nb>=1.1; extra == 'dev'
Requires-Dist: nbstripout>=0.7; extra == 'dev'
Requires-Dist: numpydoc>=1.7; extra == 'dev'
Requires-Dist: plotly>=5.18; extra == 'dev'
Requires-Dist: pre-commit>=3.7; extra == 'dev'
Requires-Dist: pytest-cov>=4.1; extra == 'dev'
Requires-Dist: pytest-randomly>=3.15; extra == 'dev'
Requires-Dist: pytest>=7.4; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Requires-Dist: scikit-learn>=1.4; extra == 'dev'
Requires-Dist: sphinx-copybutton>=0.5; extra == 'dev'
Requires-Dist: sphinx-design>=0.6; extra == 'dev'
Requires-Dist: sphinx>=7.3; extra == 'dev'
Requires-Dist: twine>=6.1; extra == 'dev'
Provides-Extra: docs
Requires-Dist: furo>=2024.5.6; extra == 'docs'
Requires-Dist: ipykernel>=6.29; extra == 'docs'
Requires-Dist: matplotlib>=3.7; extra == 'docs'
Requires-Dist: myst-nb>=1.1; extra == 'docs'
Requires-Dist: numpydoc>=1.7; extra == 'docs'
Requires-Dist: plotly>=5.18; extra == 'docs'
Requires-Dist: sphinx-copybutton>=0.5; extra == 'docs'
Requires-Dist: sphinx-design>=0.6; extra == 'docs'
Requires-Dist: sphinx>=7.3; extra == 'docs'
Provides-Extra: test
Requires-Dist: plotly>=5.18; extra == 'test'
Requires-Dist: pytest-cov>=4.1; extra == 'test'
Requires-Dist: pytest-randomly>=3.15; extra == 'test'
Requires-Dist: pytest>=7.4; extra == 'test'
Requires-Dist: scikit-learn>=1.4; extra == 'test'
Provides-Extra: viz
Requires-Dist: plotly>=5.18; extra == 'viz'
Description-Content-Type: text/markdown

# the-hawkes-package

[![CI](https://github.com/jeMATHfischer/TheHawkesPackage/actions/workflows/ci.yml/badge.svg)](https://github.com/jeMATHfischer/TheHawkesPackage/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/the-hawkes-package.svg)](https://pypi.org/project/the-hawkes-package/)
[![Python](https://img.shields.io/badge/python-3.10%20%E2%80%93%203.14-blue)](https://pypi.org/project/the-hawkes-package/)
[![Docs](https://img.shields.io/badge/docs-latest-blue)](https://jeMATHfischer.github.io/TheHawkesPackage/)
[![License: MIT](https://img.shields.io/badge/license-MIT-green)](https://github.com/jeMATHfischer/TheHawkesPackage/blob/master/LICENSE)

Simulation and Bayesian inference for temporal and spatio-temporal Hawkes processes.

A Hawkes process is a self-exciting point process: every event raises the probability of further
events for a while afterwards. This package simulates them for a range of kernel shapes — including
non-monotone ("bell-shaped") kernels and nonlinear intensities, where the naive thinning bound is
wrong — extends the construction to **any closed surface**, and **fits them to observed events**
by sequential Monte Carlo.

```
λ(t | H_t) = φ( μ + Σ_{t_i < t} κ(t − t_i) )
```

## Installation

```bash
pip install the-hawkes-package
```

Requires Python 3.10+, NumPy and SciPy. To draw the intensity as an animated 3-D surface, add the
optional renderer: `pip install "the-hawkes-package[viz]"`.

## Quickstart

```python
import numpy as np
import hawkes_package as hp

# Linear Hawkes with an exponential kernel: param = [mu, alpha, beta]
process = hp.ExponentialHawkes(np.array([2.0, 0.5, 1.0]), rng=42)
process.simulate(100)

times, intensity = process.intensity_over_interval(np.linspace(0, process.events[-1], 1000))
```

The constructor enforces the stationarity condition `alpha / beta < 1` and raises `ValueError`
otherwise — an unstable process would not terminate.

### Available processes

| Class | Use when |
|---|---|
| `ExponentialHawkes` | Linear intensity, exponential kernel. The classic case. |
| `MonotoneKernelHawkes` | Any monotone-decreasing kernel, with a monotone-increasing nonlinearity `φ`. |
| `BellShapeHawkes` | Kernels with a single interior maximum, where the excitation ramps up before decaying. |
| `MultivariateHawkes` | Several event types exciting one another, with any monotone or bell-shaped kernel. |
| `MultivariateExponentialHawkes` | The same with a shared exponential kernel — the classic mutually-exciting case. |
| `MarkedHawkes` | Events carry a magnitude that scales how much excitation they produce. |
| `ExponentialMarkedHawkes` | The same with an exponential kernel and Gutenberg–Richter marks — the ETAS shape. |
| `SpatioTemporalHawkesProcess` | Events carry a location on a surface: `Circle`, `Sphere`, `Torus2D` or any `FundamentalDomain`. |

Kernel *shapes* are separate from process classes: any of them takes a plain callable, and
`hawkes_package.inference` ships parameterised families for fitting — exponential and gamma in
time, `OmoriUtsuKernel` for the power-law decay real catalogues show, `GaussianSpatial`,
`ParetoSpatial` and `CompactSpatial` in space.

A multivariate process takes a background rate per type and a non-negative `(d, d)` excitation
matrix, `A[i, j]` scaling the excitation type *j* exerts on type *i*, against **one shared kernel
shape**. Its record is `(2, n)` — times in row 0, the type in row 1 — and `process.types` reads
the second row back as integers. Stationarity is the spectral radius of `A ∫κ` rather than a
scalar ratio, and reduces to `α/β` at one type. Negative matrix entries are refused: the thinning
bound takes a supremum term by term and `sup(a·f) = a·sup(f)` only for `a ≥ 0`, so inhibitory
cross-excitation is a different bound argument rather than a different value.

```python
process = hp.MultivariateExponentialHawkes(
    mu=[0.6, 0.3], excitation=[[0.5, 0.2], [0.4, 0.6]], beta=2.0, rng=0
)
process.simulate(500)
process.events.shape  # (2, 500)
process.types  # 0 or 1 per event
```

A marked process attaches a magnitude to every event and multiplies that event's excitation by
`g(m) = exp(a (m − m0))`. Its record is `(2, n)` too — times in row 0, marks in row 1 — and
`process.marks` reads them back. The stability condition gains a factor: the branching ratio is
`α/β · E[g(m)]`, and for exponential marks of rate `b` that expectation is `b / (b − a)`, which
is **infinite once `a ≥ b`** while every mark in every realisation stays finite. A catalogue
simulated there looks entirely ordinary, so the constructor refuses the parameter.

```python
process = hp.ExponentialMarkedHawkes(mu=1.0, alpha=0.3, beta=2.0, scale=0.5, b_value=1.5, rng=0)
process.simulate(500)
process.marks  # one magnitude per event
```

An unbounded productivity is not a problem for the thinning bound, which is worth saying because
it looks like one: the bound sums over marks that have **already been drawn**, so the supremum of
`g` over the mark distribution never enters it, and an accepted candidate draws its mark
afterwards.

`simulate(k)` stops after `k` events; `simulate_until(T)` stops at a horizon, and is what a
forecast needs — a fixed-count simulation cannot express "no events at all in the window". Its
`start=` may sit *later* than the last recorded event, which conditions on the observed fact that
nothing happened in between; that is how a forecast continues from the end of a window rather than
from the last thing that happened.

### Spatial domains

```python
import hawkes_package as hp

process = hp.SpatioTemporalHawkesProcess(
    base=lambda x: 0.5,
    spatial=lambda d: max(0.0, 1 - d / np.pi),
    temporal=lambda dt: 0.9 * np.exp(-5 * dt),
    domain=hp.Circle(),
    monotone_temporal_kernel=True,
    rng=42,
)
process.simulate(50)
```

The background may vary in space — `base=lambda x: 0.5 + 0.2*np.cos(x[0])` — and generalises
unchanged to two dimensions, since a callable always receives a shape-`(ndim,)` point.

`SpatialDomain` is an ABC — implement `distance`, `wrap`, `sample_uniform`, `volume` and `bounds`
to simulate on your own geometry. A domain need not fill its bounding box: override the optional
`contains` and `volume_element` hooks, and `volume` must then equal the integral of
`volume_element` over the part of `bounds` that `contains` admits. For a domain that does fill its
box — the default — that reduces to `volume == prod(bounds widths)`.

### Bounded domains

`Rectangle` and `Polygon` are the domains with a real **boundary** — everything else here is a
closed surface, periodic or a quotient. That distinction is not cosmetic: on a bounded region an
event near the edge spreads offspring into space that is partly outside, so it produces fewer of
them, and a fit that ignores this blames a weaker kernel. Measured on a 4x3 rectangle, omitting
the correction over-estimates the excitation by **64%**.

```python
process = hp.SpatioTemporalHawkesProcess(
    base=lambda x: 0.5,
    spatial=lambda d: max(0.0, 1 - d / np.pi),
    temporal=lambda dt: 0.9 * np.exp(-2 * dt),
    domain=hp.Rectangle(4.0, 3.0),  # or hp.Polygon([[0, 0], [4, 0], [0, 3]])
    monotone_temporal_kernel=True,
    edge_correction="auto",  # the default
)
```

`edge_correction` divides each event's spatial kernel by its own in-domain mass, so every event
excites the same total amount wherever it sits — which also makes the stationarity condition
exact rather than merely conservative. `"auto"` corrects exactly where the domain sets
`has_boundary`, so no closed surface is touched; `"none"` leaves the intensity as written, which
is what you want when the boundary is physical rather than an observation window.

Note that `Rectangle(4, 3)` and `FundamentalDomain.rectangle(4, 3)` share a bounding box and
nothing else: the second glues opposite sides together and is a **torus**, with no boundary at all.

`Circle`, `Torus2D` and `Sphere` are written out by hand. `FundamentalDomain` is the general
construction the first two are instances of — a convex geodesic polygon plus the side-pairing
isometries that identify its boundary — and between them they reach **every closed surface**:

```python
hp.Sphere()  # the sphere
hp.FundamentalDomain.hexagon(1.0)  # the hexagonal torus, which no rectangle expresses
hp.FundamentalDomain.klein_bottle(3, 5)  # non-orientable, and still flat
hp.FundamentalDomain.projective_plane()  # a hemisphere, antipodes identified
hp.FundamentalDomain.genus(2)  # two handles, so hyperbolic — necessarily
hp.FundamentalDomain.crosscaps(3)  # three crosscaps, hyperbolic too
```

Which geometry a surface gets is not a setting: Gauss–Bonnet ties the sign of the curvature to the
Euler characteristic, so the torus and the Klein bottle are flat, the sphere and the projective
plane are spherical, and everything else is hyperbolic. Each domain reports what it built, through
`domain.topology`, and refuses at construction to build something that is not a closed surface.

`make_periodic` wraps an isotropic kernel so it sums correctly over the domain's image points, and
can be passed straight in as `spatial=`:

```python
kernel = hp.make_periodic(lambda d: np.exp(-(d**2)), hp.Circle())
process = hp.SpatioTemporalHawkesProcess(base, kernel, temporal, domain=hp.Circle())
```

## Inference

`hawkes_package.inference` estimates parameters from observed events, in blocks as they arrive,
by sequential Monte Carlo with MCMC rejuvenation. The likelihood is computed from the simulator's
own intensity hooks, so what is fitted is exactly what would be drawn.

```python
from hawkes_package.inference import (
    ConstrainedPrior,
    ExponentialLogLikelihood,
    History,
    IndependentPrior,
    LogNormal,
    SMCSampler,
    exponential_model,
    ks_exponential,
    residuals,
)

history = History.from_simulation(process)  # events *and* their window
model = exponential_model()  # theta -> process, and where it is defined
prior = ConstrainedPrior(
    IndependentPrior((LogNormal(0.5, 1.0), LogNormal(-1.0, 1.0), LogNormal(0.0, 1.0))),
    model.support,  # excludes alpha >= beta
)

smc = SMCSampler(ExponentialLogLikelihood(model), prior, n_particles=256, rng=0)
cloud = smc.run(history, blocks=8)  # or smc.update(...) as data arrives

print(cloud.summary())  # marginals and 90% intervals
print(smc.diagnostics.summary())  # ESS, acceptance, move size, evidence
print(ks_exponential(residuals(smc.likelihood, cloud.mean(), history)))  # does it fit?
```

The same fit is also available behind a scikit-learn-shaped surface, for when one object beats
four:

```python
from hawkes_package.inference import HawkesEstimator

est = HawkesEstimator(model, prior, n_particles=256, rng=0).fit(history)

est.theta_  # posterior mean
est.predict(times)  # intensity, averaged over the particles
est.partial_fit(new_events, end=T)  # the filter is genuinely online
est.score(held_out, end=T2)  # log posterior-predictive density
```

`predict` averages the intensity **over the posterior** rather than evaluating it at `theta_`; the
two differ, and the plug-in is the one biased low. It refuses times past `history.end`, where the
intensity computed from the observed record is the intensity given that nothing has happened
since — `forecast` answers that question properly, by simulating forward. scikit-learn is not a
dependency and is never imported.

Spatio-temporal fits work the same way through `spatio_temporal_model` and
`SpatioTemporalLogLikelihood`, on any `SpatialDomain`. `posterior_predictive` forecasts from the
posterior by simulating forward, carrying the parameter uncertainty rather than plugging in a
point estimate.

`History.end` is keyword-required and has no default: "observed on `[0, T]`" and "stopped at the
n-th event" are different experiments, and defaulting it would switch between them silently.

## Validation

`hawkes_package.inference.validation` asks whether a fitted model is any good — judged without
reusing the arithmetic that produced it.

```python
from hawkes_package.inference.validation import (
    cell_residuals,
    compare_with_baseline,
    compensator_agreement,
    rolling_origin,
)

print(compensator_agreement(likelihood, theta, history))  # is the integral itself right?
print(cell_residuals(likelihood, theta, history).summary())  # right amounts, where and when?
print(compare_with_baseline(likelihood, theta, history).summary())  # better than a constant rate?
print(rolling_origin(likelihood, history, fit, origins=[...]).summary())  # any use prospectively?
```

The first of those exists because of one cancellation. `residuals` takes its compensator from
the likelihood it is handed, which is right for checking two implementations against each other
and wrong for validation: **a fit made with a compensator 20% too small inflates the intensity,
and rescaling through that same broken integral gives unit-rate gaps.** Measured on 400 events —
the broken compensator passes the KS test at `p = 0.46`, an honest one rejects at `p = 3.3e-05`.

The baseline is the homogeneous Poisson process at its *own* maximum likelihood, not at a
convenient rate: a baseline handed a bad parameter is worse than none, because beating it reads
as evidence. Over seeds 0–20 a Hawkes fit beats it on 21 of 21 runs of Hawkes data and on 0 of 21
runs with the excitation switched off.

## Visualization

`hawkes_package.viz` draws the surface a spatio-temporal process lives on, colours it by
`λ(t, x | H_t)`, and animates it over time into one self-contained interactive page — play
button, frame slider, orbitable camera.

```python
from hawkes_package.viz import animate_intensity

frames = animate_intensity(process, np.linspace(0, horizon, 40), "surface.html")
print(frames.summary())
```

Four surfaces: the sphere and the projective plane are drawn **exactly**, the flat torus and the
Klein bottle as immersions — neither admits an isometric embedding in three-space, so the
distances on screen are not the geodesic distances driving the intensity, and each figure's
caption says so. Hyperbolic surfaces are refused rather than drawn misleadingly.

The renderer is an optional extra; the field itself is computed with numpy alone, through the same
intensity hooks the simulator thins against.

## Reproducibility

Every process takes `rng=`, accepting `None`, an `int` seed, or an existing `numpy.random.Generator`:

```python
hp.ExponentialHawkes(param, rng=42)  # reproducible
hp.ExponentialHawkes(param, rng=my_generator)  # share one stream
```

`np.random.seed(...)` does **not** control simulations. See [CHANGELOG.md](https://github.com/jeMATHfischer/TheHawkesPackage/blob/master/CHANGELOG.md).

## Migrating

The import name is `hawkes_package`. The `TheHawkesPackage` shim was **removed in 0.4.0**, together
with `propagate_by_amount`, `propagate_by_k_events`, the `propogate_by_amount` typo,
`Spatio_Temporal_Hawkes_Process` and `LegacySpatioTemporalHawkesProcess`. `simulate(k)` is the
method on every process class.

0.4.0 renamed the frozen public names, keeping each old spelling as a deprecated alias:
`Events` → `events`, `Sim_num` → `n_simulated`, and `L1`/`L2` → `width`/`height`. **0.5.0 removed
those aliases**, along with the `n_images` argument of `FundamentalDomain` and the internal
`_deprecation` module that served them — the package now carries no deprecations at all.

One case is worth knowing because Python cannot refuse it: `process.Events = history` now binds a
plain attribute instead of seeding the realisation. Assign to `process.events`.

[docs/migration.md](https://jeMATHfischer.github.io/TheHawkesPackage/migration.html) has the rest,
including the changes that alter previously produced numbers.

## Documentation

<https://jeMATHfischer.github.io/TheHawkesPackage/>

Five executed notebooks, run on every documentation build:
[temporal processes](https://jeMATHfischer.github.io/TheHawkesPackage/examples/temporal_processes.html),
[spatio-temporal](https://jeMATHfischer.github.io/TheHawkesPackage/examples/spatio_temporal.html),
[compact surfaces](https://jeMATHfischer.github.io/TheHawkesPackage/examples/surfaces.html),
[intensity surfaces](https://jeMATHfischer.github.io/TheHawkesPackage/examples/intensity_surfaces.html) and
[fitting to data](https://jeMATHfischer.github.io/TheHawkesPackage/examples/online_inference.html).

## License

MIT — see [LICENSE](https://github.com/jeMATHfischer/TheHawkesPackage/blob/master/LICENSE).
