rheon.spec.hawkes¶
- rheon.spec.hawkes(name: str, *, targets: Sequence[str | Target | FormulaTarget | _Expr], kernel_decays: list[float] | None = None, kernel_half_lives: list[float | timedelta | str | _Expr] | None = None, window_events: int | None = None, window_size: float | timedelta | str | _Expr | None = None, closed: Literal['right', 'both'] = 'right', max_state_bytes: int | None = None, **common: Unpack[CommonKwargs]) dict[str, Any][source]¶
A self-exciting point process, fitted exactly by least squares.
Use it on a stream of events, where each event makes the next likelier for a while: trades, messages, failures, posts. Each target is a node, and a value above 0 on a row is an event of that node, of that size (its mark): 1 for one event, a count for that many at once.
Parameters
The stream parameters every builder takes, such as
clock,half_life,gap_cap,min_weightandgroup, are inrheon.spec. A row’sweightonly decides whether its events are learned: 0 skips them, and any weight above 0 learns them at their marks, since an event’s excitation is a fact of the process rather than evidence to scale. A row of weight 0 counts in no clock: the next row steps as if it were not there, it is in no window, and its weight is in noweight_sum; it is still read, from the last row that counted.half_lifeis how fast the fit forgets,inffor not at all.This model’s own parameters:
kernel_decays,kernel_half_livesThe kernels, each node exciting every node through one kernel
α β exp(-β t)per decayβ, which integrates toα, so1/βis how long an event’s excitation lasts. Two or three decays a decade apart cover a short and a long memory. Give one of the two. The decaysβare rates per unit of the clock, each above 0 and no two equal; a rate has no duration form, so a temporal clock is givenkernel_half_livesinstead: each kernel’s half-lifeln 2 / βas a number of the clock’s units or a duration such as"500ms", ashalf_lifeis, andβ = ln 2 / half-lifein the clock’s unit, seconds on a temporal clock. Required: one of them.window_eventsFit only the last this many rows that carried an event, observed from the clock of the row dropped last, in place of a decay: set
half_lifetoinfbeside it. The window keeps each of its rows,8 * (2 + D + D * U)bytes each forDtargets andUdecays. Default none.window_sizeFit only the events of the last this long on the clock, observed over those same
window_sizeunits (or from the first row, until there are that many), in place of a decay: sethalf_lifetoinfbeside it. A number of the clock’s units, or of rows where the spec has no clock, or a duration such as"5m"on a temporal clock; finite and above 0. A row leaves the window when it iswindow_sizeold on the clock (decayed aftergap_cap), before the row that reaches that age reads its intensity, decided on the rows’ exact stamps (integer nanoseconds on a temporal clock). It is the window’s span on the clock wherewindow_eventsis its count of events: how many events it holds is the data’s, so its bytes are checked as the rows go in (seemax_state_bytes). Refused besidewindow_events. Default none.closedWhich edge of
window_sizeholds the row exactly that old, in Polars’ words (rolling_sum_by(closed=))."right", the default, keeps the rows less thanwindow_sizeold, so the window is(T - window_size, T], as the window operators androlling_sum_bydo."both"keeps that row too and is refused withoutwindow_size."left"and"none"would leave out the row the window ends at, which a model cannot do: both are refused.max_state_bytesThe bytes a group’s state may hold, a window’s rows included.
window_eventsfixes the size, so it is checked here: a spec past it is refused, and one past half of it is warned of (rheon.RheonWarning). Awindow_sizewindow holds the events the span has, so it is checked as the rows go in: the first row to take a group past half of it raises a warning, once for the group, naming the group and the bytes, and the row that would take it past the cap stops the run with an error naming the group and the bytes, the bank having learned part of the chunk. Each row of the window takes8 * (2 + D + D * U)bytes and a stamp of 32 beside it. Default 256 KB,262144.
Output
A value of 0 or below, or a null, is no event, so a row can be a clock tick alone. Every row reports each node’s intensity, its expected events per unit of the clock, read before the row’s events from the fit on every row before them. On a temporal clock a quantity measured on the clock reaches the output in seconds (as
holt’s trend does): the intensity and the base ratemuare events per second, andalpha, a count of events, has no unit. One output column, named after the spec, holds a record of these fields in each row. docs/OUTPUTS.md#hawkes gives each field’s type and when it is null:intensity_<t>Per target: the node’s intensity just before the row’s events, in events per unit of the clock (per second on a temporal clock), from the fit on the rows before. Null below
min_weight, and while the fit is not determined: before every node has had an event, or while two of its terms cannot be told apart, as when two nodes’ events fall on the same rows.weight_sumThe weight the model has accumulated before the row and before the row’s own decay: every row’s weight, an event or not. Under a window, the weight inside it: that of the rows with an event the window holds, as it stood after the last row and before this row takes any out.
settled_fracHow far the model had come toward its steady state under decay before the row.
withheld_reasonWhy the row’s intensities were withheld, null where they were not: a reason of the shared gates (
rheon.spec), such asbelow_min_weight. A fit not yet determined (intensity_<t>null withweight_sumpastmin_weight) gives none.coefThe fit after the row, per target
i:mu, the base rate (per unit of the clock, per second on a temporal clock), thenalpha_<j>_beta<β>for each source targetjand decayβ(alpha_<j>_h<half-life>where the kernels are given bykernel_half_lives, the half-life as written,h500ms), the events ofione event ofjcauses through that kernel.coef_index()names them. The fit is not held to 0 or above: a negativealphais an event that inhibits.
Raises
As every builder does (
rheon.spec);TypeErrorforfeatures, which this model does not take; andValueErrornaming the problem for neitherkernel_decaysnorkernel_half_livesgiven, or both;kernel_decaysempty, not above 0 or with a decay twice; akernel_half_livesentry not finite or not above 0;window_eventsbelow 1 or beside a finitehalf_life,window_sizenot finite or not above 0, beside a finitehalf_lifeorwindow_events,closedother than"right"or"both", or"both"withoutwindow_size, and ahalf_lifewhose rateln 2 / half_lifeis within 0.1% of a decay or of a sum of two.The update
With
λ_i(t) = μ_i + Σ_j Σ_u α_iju R_ju(t)and the excitationR_ju(t) = Σ β_u m_k exp(-β_u (t - t_k))over nodej’s earlier events of marksm_k, the fit minimises the least-squares contrastΣ_i ∫ w λ_i² dt - 2 ∫ w λ_i dN_i, each instant weightedw = exp(-γ (T - t))at the forgetting rateγ = ln 2 / half_life. Withφ = (1, R), it isθ_i = G⁻¹ b_i. On a rowdclock units after the last,f = exp(-γ d):R_ju ← exp(-β_u d) R_ju b ← f b Q ← f Q G₀₀ ← f G₀₀ + (1 - f) / γ (+ d where γ = 0) then, for each node j with an event of mark m_j, from R before the row's events: b_j ← b_j + m_j φ Q_jl ← Q_jl + m_j m_l R_ju ← R_ju + m_j β_u
and at each read, with
j(a)the source node of terma:G₀ₐ = (β_a b_j(a)[0] - R_a) / (β_a - γ) Gₐᵦ = (β_a b_j(a)[b] + β_b b_j(b)[a] + β_a β_b Q_j(a)j(b) - R_a R_b) / (β_a + β_b - γ)
The state is
R,b,Q,G₀₀and the weight,8 * (k + D * (1 + k) + D * (D + 1) / 2 + 2)bytes fork = D * U, whatever the stream’s length.Example
This code simulates one node from a base rate of 0.5 and a kernel of
α = 0.6atβ = 2, by Ogata’s thinning, and prints the fit:import numpy as np rng = np.random.default_rng(3) t, excite, times = 0.0, 0.0, [] while t < 5_000.0: bound = 0.5 + excite step = rng.exponential(1 / bound) excite *= np.exp(-2.0 * step) t += step if rng.uniform() * bound <= 0.5 + excite: times.append(t) excite += 0.6 * 2.0 events = pl.DataFrame({"t": times, "event": 1.0}) events.write_parquet("events.parquet") model = rp.spec.hawkes( "h", targets=["event"], kernel_decays=[2.0], clock="t", half_life=float("inf"), gap_cap=1e9, ) bank = rp.ModelBank([model]) bank.fit(pl.scan_parquet("events.parquet")) coef = {r["term"]: r["coef"] for r in bank.coef().iter_rows(named=True)} print(f"mu: true 0.50, found {coef['mu']:.2f}") print(f"alpha: true 0.60, found {coef['alpha_event_beta2']:.2f}")
mu: true 0.50, found 0.51 alpha: true 0.60, found 0.59
See also
seqtest(), to test whether one spec’s events come faster than another’s.ew_cov(), for the correlation of counts in fixed bins rather than the excitation between events.
Notes
Why the fit is exact. The intensity is linear in its parameters, so the contrast is a quadratic form in them.
Gis not kept: between eventsR_a R_bdecays atβ_a + β_b, and at a row of events it jumps by terms whose sum over the rows isbandQ, so integrating it by parts readsGfrom them. tick’sModelHawkesSumExpKernLeastSqcomputes the same contrast, divided by the number of events, and its minimiser agrees with this fit to about1e-12.Events on one row. An event excites every event on a later row, at the same clock or not, and none on its own row: those are simultaneous, as in the definition
t_k < t.The window. Dropping the oldest row takes back exactly what it added, through the sums of its excitation of the later rows. Those are kept in two blocks of rows, so that no sum is ever rescaled by a growing exponential, and
R,bandQare formed afresh from the rows each time a block turns over, so their rounding is that of one window.window_eventsdrops the oldest row once the window holds more rows than it;window_sizedrops every rowwindow_sizeold at the row it reads, and observes the interval(T - window_size, T], soG₀₀ismin(window_size, the clock since the first row). Its edge is decided on each row’s exact stamp, never a clock summed in doubles. Either way, the fit is that of the window’s events alone.