lebre 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
lebre/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """LEBRE — online one-step-ahead forecasting with statistically tested structural changes, at a cost of a few hundred
2
+ floating-point operations per step.
3
+
4
+ This package implements **LEBRE v0.52-r1** (canonical configuration) exactly as specified and evaluated in the research
5
+ record https://doi.org/10.5281/zenodo.23049103. In the reference environment (Windows, CPython 3.11, NumPy 2.2.5) the forecasts are bit-for-bit identical to the frozen
6
+ research code; elsewhere they agree up to floating-point rounding, with identical structural decisions in the tests.
7
+ """
8
+ from .model import Event, Forecast, Lebre
9
+
10
+ __version__ = "0.1.0"
11
+ ALGORITHM_VERSION = "LEBRE v0.52-r1"
12
+
13
+ __all__ = ["Lebre", "Forecast", "Event", "__version__", "ALGORITHM_VERSION"]
lebre/_core.py ADDED
@@ -0,0 +1,451 @@
1
+ """Core of LEBRE v0.52-r1 (canonical configuration only).
2
+
3
+ Extracted from the frozen research implementation `lebre_v052h.LebreV052H` with the canonical configuration
4
+ {scale_floor 0.1, peak_persist, evidence psiE1, lazy_halves, screen_skip_active, track_groups, mu 0.05, stagger,
5
+ screen_spread, peak_split, peak_until 200, chal_warm 250, gap_hold, out_contract}. Branches used only by research
6
+ ablations were removed; every arithmetic expression on the canonical path is kept in the same order, so the forecasts
7
+ are bit-for-bit identical (checked by the regression tests).
8
+
9
+ The only structural change is that one research `step(x, y)` is split into `predict(x)` (everything computed before
10
+ the target is read) and `observe(y)` (everything after); `step` = `predict` then `observe`.
11
+ """
12
+ import math
13
+
14
+ import numpy as np
15
+
16
+ from ._engine import ChangeEngine
17
+ from ._memory import Memory, MemoryW
18
+
19
+ POLES = (0.8, 0.95)
20
+ BANDS = ((1, 1), (2, 3), (4, 7), (8, 15), (16, 31))
21
+
22
+ # canonical constants (identical to the research defaults + canonical configuration)
23
+ M_MAX, M_SLOTS, MU, ALPHA = 4, 2, 0.05, 0.05
24
+ EPS = {"add": 0.002, "swap": 0.002, "rem": -0.002, "split": 0.002}
25
+ CLIP_K, DECIDE_EVERY, N_MIN, T_MAX, COOLDOWN, REM_PERIOD = 2.0, 10, 100, 5000, 2000, 2000
26
+ LAM, ETA, ALPHA_COV, GAMMA_Q, EVERY, CLIP_X = 0.99, 0.5, 0.1, 0.1, 8, 8.0
27
+ CHAL_WARM, SCREEN_EVERY, SCREEN_W, SCREEN_Q, SPLIT_Q, RLS_P0 = 250, 4, 0.02, 15.09, 6.63, 10.0
28
+ PEAK_UNTIL, SCALE_FLOOR, OUT_MARGIN, OUT_RHO = 200, 0.1, 0.5, 1e-3
29
+
30
+
31
+ def halves(seg):
32
+ lo, hi = seg; mid = (lo + hi) // 2
33
+ return (lo, mid), (mid + 1, hi)
34
+
35
+
36
+ class Core:
37
+ def __init__(self, d, season=None, season2=None):
38
+ self.ylast = 0.0; self.ym = 0.0; self.yv = 1.0
39
+ d = d + 1 # the target's own past is one more input
40
+ self.d, self.L = d, BANDS[-1][1]
41
+ self.M = MemoryW(season, season2) if season2 else Memory(season)
42
+ self.quar_until = -1
43
+ self.y_sm = None; self.y_sv = 0.0; self.n_y = 0
44
+ self.g_m = np.zeros(d); self.g_c = np.eye(d)
45
+ self.units = [("in", i) for i in range(d)] + [("res",)]
46
+ nb = len(BANDS)
47
+ self.H = np.zeros((self.L + 2, d)) # H[k] = x_{t-k}
48
+ self.bs = np.zeros((nb, d)) # running sums of the octave bands
49
+ self.seg = {} # (i, lo, hi) -> running sum of an active segment
50
+ self.r = np.zeros(len(POLES))
51
+ self.base = np.zeros(d + 1)
52
+ self.active = {} # unit -> {"segs": [(lo, hi)...] | None, "w": array}
53
+ self.contrib_ema = {}
54
+ self.a_c0 = np.ones(d); self.a_c1 = np.zeros(d); self.res_prev = 0.0
55
+ self.sc_xy = np.zeros((nb, d)); self.sc_xx = np.ones((nb, d)) * 1e-3; self.sc_yy = np.ones(d)
56
+ self.sr_xy = np.zeros(len(POLES)); self.sr_xx = np.ones(len(POLES)) * 1e-3; self.sr_yy = 1.0
57
+ self.sp = {} # split key -> [xy, xx, yy] EMA
58
+ self.engine = ChangeEngine(ALPHA, 2 * len(self.units), M_SLOTS, N_MIN, T_MAX)
59
+ self.last_tested = {}; self.last_rem = {}
60
+ self.events = []; self.t = 0
61
+ self.e2 = None; self.sig = 1.0; self.e2r = None; self.sigr = 1.0; self.res2 = None
62
+ self.D = 0.0; self.wS = 0.5
63
+ self.qhat = None; self.qacc = 0.0; self.hits_obs = 0; self.hits_ok = 0
64
+ self.fp = {"memory": 0.0, "structure": 0.0, "experiments": 0.0, "screening": 0.0, "control": 0.0}
65
+ self.last_obs = None; self.env_hi = None; self.env_lo = None; self.env_m = None; self.env_n = 0; self.n_clipped = 0
66
+ self._pending = None
67
+
68
+ # ---------------- segment sums
69
+ def _track(self, i, seg):
70
+ k = (i, seg[0], seg[1])
71
+ if k not in self.seg:
72
+ self.seg[k] = float(self.H[seg[0]:seg[1] + 1, i].sum())
73
+ self.fp["structure"] += seg[1] - seg[0] + 1
74
+
75
+ def _mean(self, i, seg):
76
+ k = (i, seg[0], seg[1])
77
+ if k in self.seg:
78
+ return self.seg[k] / (seg[1] - seg[0] + 1)
79
+ self.fp["structure"] += seg[1] - seg[0] + 1
80
+ return float(self.H[seg[0]:seg[1] + 1, i].sum()) / (seg[1] - seg[0] + 1)
81
+
82
+ def _retrack(self):
83
+ """keep exactly the active segments as running sums (halves are summed on demand)"""
84
+ need = set()
85
+ for u, st in self.active.items():
86
+ if u[0] == "in":
87
+ for sg in st["segs"]:
88
+ need.add((u[1],) + sg)
89
+ for k in need:
90
+ self._track(k[0], k[1:])
91
+ for k in [k for k in self.seg if k not in need]:
92
+ del self.seg[k]
93
+
94
+ # ---------------- features (values available before y_t)
95
+ def block(self, unit):
96
+ if unit[0] == "in":
97
+ i = unit[1]
98
+ st = self.active.get(unit)
99
+ if st is None:
100
+ return np.array([self.bs[b, i] / (hi - lo + 1) for b, (lo, hi) in enumerate(BANDS)])
101
+ return np.array([self._mean(i, sg) for sg in st["segs"]])
102
+ return self.r.copy()
103
+
104
+ def cfeat(self, key):
105
+ if key[0] == "split":
106
+ i, sg = key[1], key[2:]
107
+ return np.array([self._mean(i, h) for h in halves(sg)])
108
+ f = self.block(key)
109
+ return np.append(f, self.H[0, key[1]]) if key[0] == "in" else f
110
+
111
+ def _cf(self, ex):
112
+ key = ex.add_key
113
+ if key[0] == "in" and ex.kstar:
114
+ f = self.cfeat(key)
115
+ return np.concatenate([f[:-1], [self.H[ex.kstar, key[1]]], f[-1:]])
116
+ return self.cfeat(key)
117
+
118
+ def _seg_contrib(self, key):
119
+ i, sg = key[1], key[2:]
120
+ st = self.active[("in", i)]
121
+ return float(st["w"][st["segs"].index(sg)]) * self._mean(i, sg)
122
+
123
+ def response(self, unit):
124
+ st = self.active[unit]
125
+ return [(sg, float(w) / (sg[1] - sg[0] + 1)) for sg, w in zip(st["segs"], st["w"])]
126
+
127
+ def _struct_pred(self, x):
128
+ xb = np.concatenate(([1.0], x))
129
+ s = float(self.base @ xb) + sum(float(st["w"] @ self.block(u)) for u, st in self.active.items())
130
+ self.fp["structure"] += 2 * (self.d + 1) + sum(3 * len(st["w"]) for st in self.active.values())
131
+ return s, xb
132
+
133
+ def _a(self):
134
+ return np.clip(self.a_c1 / np.maximum(self.a_c0, 1e-6), -0.999, 0.999)
135
+
136
+ def _shift(self, x):
137
+ self.H = np.roll(self.H, 1, axis=0); self.H[0] = x
138
+ for b, (lo, hi) in enumerate(BANDS):
139
+ self.bs[b] += self.H[lo] - self.H[hi + 1]
140
+ for k in self.seg:
141
+ i, lo, hi = k
142
+ self.seg[k] += self.H[lo, i] - self.H[hi + 1, i]
143
+ self.fp["structure"] += 2 * len(BANDS) * self.d + 2 * len(self.seg)
144
+
145
+ # ---------------- one step, split in two halves
146
+ def predict(self, x):
147
+ """everything computed before y_t is read; returns the (bounded) forecast"""
148
+ if self._pending is not None:
149
+ raise RuntimeError("predict() called twice without observe()")
150
+ v = self.ylast
151
+ x = np.append(np.asarray(x, float), (v - self.ym) / math.sqrt(self.yv + 1e-6))
152
+ dlt = v - self.ym; self.ym += 1e-4 * dlt
153
+ self.yv = max((1 - 1e-4) * self.yv + 1e-4 * (v - self.ym) * dlt, 1e-4); self.fp["structure"] += 9
154
+ x = np.nan_to_num(x)
155
+ if np.any(np.abs(x) > CLIP_X):
156
+ self.quar_until = self.t + self.L
157
+ x = np.clip(x, -CLIP_X, CLIP_X)
158
+ self._shift(x)
159
+ m = self.M.predict()
160
+ s, xb = self._struct_pred(x)
161
+ f = m + self.wS * (s - m)
162
+ if self.env_n >= 50:
163
+ w_ = OUT_MARGIN * (self.env_hi - self.env_lo)
164
+ fc = min(max(f, self.env_lo - w_), self.env_hi + w_) if math.isfinite(f) else self.last_obs
165
+ self.n_clipped += fc != f; f = fc; self.fp["control"] += 5
166
+ ref = s
167
+ outs, rrs = [], []
168
+ for ex in self.engine.slots:
169
+ if ex.kind == "split":
170
+ c = self._seg_contrib(ex.add_key)
171
+ outs.append(ref - c + float(ex.w @ self._cf(ex))); rrs.append(c)
172
+ continue
173
+ a = float(ex.w @ self._cf(ex)) if ex.add_key else 0.0
174
+ r = float(self.active[ex.rem_key]["w"] @ self.block(ex.rem_key)) if ex.rem_key else 0.0
175
+ outs.append(ref + a - r); rrs.append(r)
176
+ self.fp["experiments"] += 6 * len(outs)
177
+ self._pending = (xb, m, s, f, ref, outs, rrs)
178
+ return f
179
+
180
+ def observe(self, y, quarantine=False):
181
+ """everything after y_t is read (None or NaN = missing target)"""
182
+ if self._pending is None:
183
+ raise RuntimeError("observe() called without a preceding predict()")
184
+ xb, m, s, f, ref, outs, rrs = self._pending; self._pending = None
185
+ y_ok = y is not None and np.isfinite(y)
186
+ mem_learn = y_ok and not quarantine
187
+ learn = mem_learn and not (self.t <= self.quar_until)
188
+ if y_ok:
189
+ e = y - f; er = y - ref
190
+ self.e2r = er * er if self.e2r is None else self.e2r + (1 - LAM) * (er * er - self.e2r)
191
+ if self.y_sm is None:
192
+ self.y_sm = y; self.n_y = 0
193
+ self.n_y += 1; ry = max(1e-4, 1.0 / self.n_y)
194
+ dy = y - self.y_sm; self.y_sm += ry * dy; self.y_sv += ry * (dy * (y - self.y_sm) - self.y_sv)
195
+ floor = SCALE_FLOOR * math.sqrt(max(self.y_sv, 0.0)) if self.t >= 200 else 0.0
196
+ B = CLIP_K * max(self.sigr, floor)
197
+ self.fp["control"] += 8
198
+ lf = min(er * er / (B * B), 1.0)
199
+ res = y - s
200
+ if learn:
201
+ for ex, g, back in zip(self.engine.slots, outs, rrs):
202
+ ex.k += 1
203
+ if ex.k > CHAL_WARM or not ex.add_key:
204
+ ex.observe(lf - min((y - g) ** 2 / (B * B), 1.0) - ex.eps)
205
+ if ex.add_key: # RLS on the residual the change would explain
206
+ rr = res + back
207
+ if ex.add_key[0] == "in" and ex.k <= PEAK_UNTIL:
208
+ self._peak_stats(ex, rr)
209
+ fx = self._cf(ex)
210
+ lam_ = 1.0
211
+ Pf = ex.P @ fx; kg = Pf / (lam_ + fx @ Pf)
212
+ ex.w = ex.w + kg * (rr - ex.w @ fx); ex.P = (ex.P - np.outer(kg, Pf)) / lam_
213
+ self.fp["experiments"] += 4 * len(fx) ** 2 + 6 * len(fx)
214
+ self.fp["experiments"] += 8 * len(outs)
215
+ blocks = {u: self.block(u) for u in self.active}
216
+ bpow = sum(float(b @ b) for b in blocks.values())
217
+ den = float(xb @ xb) + bpow + 1e-6
218
+ g_ = MU * res / den
219
+ self.base += g_ * xb
220
+ for u, b in blocks.items():
221
+ st = self.active[u]; st["w"] = st["w"] + g_ * b
222
+ c = abs(float(st["w"] @ b))
223
+ self.contrib_ema[u] = c if u not in self.contrib_ema else self.contrib_ema[u] + 0.01 * (c - self.contrib_ema[u])
224
+ self.fp["structure"] += 4 * (len(xb) + sum(len(b) for b in blocks.values())) + 4
225
+ self._screen_spread(res)
226
+ self.res_prev = res
227
+ self.res2 = res * res if self.res2 is None else self.res2 + (1 - LAM) * (res * res - self.res2)
228
+ es, em = y - s, y - m
229
+ self.D = LAM * self.D + (es * es - em * em) / (self.sig ** 2 + 1e-12)
230
+ self.fp["control"] += 7
231
+ if self.t % EVERY == 0:
232
+ z = ETA * self.D
233
+ self.wS = 1.0 / (1.0 + math.exp(z)) if z < 700 else 0.0
234
+ self.fp["control"] += 4
235
+ self.e2 = e * e if self.e2 is None else self.e2 + (1 - LAM) * (e * e - self.e2)
236
+ if self.qhat is None:
237
+ self.qhat = 1.645 * math.sqrt(self.e2)
238
+ miss = 1.0 if abs(e) > self.qhat else 0.0
239
+ self.hits_obs += 1; self.hits_ok += miss == 0.0
240
+ self.qacc += miss - ALPHA_COV
241
+ if self.t % EVERY == 0:
242
+ self.sig = math.sqrt(max(self.e2, 1e-300)); self.sigr = math.sqrt(max(self.e2r, 1e-300))
243
+ self.qhat = max(0.0, self.qhat + GAMMA_Q * self.sig * self.qacc); self.qacc = 0.0
244
+ self.fp["control"] += 10
245
+ u_ = e / self.sig
246
+ else:
247
+ u_ = 0.0
248
+ if not y_ok and self.last_obs is not None:
249
+ self.M.update(self.last_obs, m, learn=False) # hold: history gets the last observed value
250
+ else:
251
+ self.M.update(y if y_ok else None, m, learn=mem_learn)
252
+ if y_ok:
253
+ self.last_obs = float(y)
254
+ if self.env_hi is None:
255
+ self.env_hi = self.env_lo = self.env_m = float(y)
256
+ self.env_n += 1; r_ = OUT_RHO
257
+ self.env_m += max(r_, 1.0 / self.env_n) * (y - self.env_m)
258
+ self.env_hi = max(float(y), self.env_hi - r_ * (self.env_hi - self.env_m))
259
+ self.env_lo = min(float(y), self.env_lo - r_ * (self.env_lo - self.env_m))
260
+ self.fp["control"] += 10
261
+ if y_ok:
262
+ self.ylast = float(y)
263
+ self.r = np.array(POLES) * self.r + (1 - np.array(POLES)) * u_
264
+ self.fp["structure"] += 3 * len(POLES)
265
+ if self.t % DECIDE_EVERY == 0 and self.t > 0:
266
+ self._decide()
267
+ self.t += 1
268
+
269
+ def _peak_stats(self, ex, rr):
270
+ i = ex.add_key[1]; a = self._a()[i]
271
+ u = self.H[1:self.L + 1, i] - a * self.H[2:self.L + 2, i] # prewhitened lags 1..L
272
+ pr = rr - a * getattr(ex, "rprev", 0.0); ex.rprev = rr
273
+ if getattr(ex, "cxy", None) is None:
274
+ prev = ex.hyp.peak_stats
275
+ if prev is not None:
276
+ ex.cxy, ex.cxx = prev
277
+ else:
278
+ ex.cxy = np.zeros(self.L); ex.cxx = np.full(self.L, 1e-9)
279
+ ex.hyp.peak_stats = (ex.cxy, ex.cxx) # same arrays: updated in place
280
+ msk = (np.arange(self.L) + ex.k) % 2 == 0
281
+ ex.cxy[msk] += pr * u[msk]; ex.cxx[msk] += u[msk] * u[msk]
282
+ self.fp["experiments"] += 3 * self.L + 4
283
+ if ex.k == PEAK_UNTIL:
284
+ k = int(np.argmax(ex.cxy ** 2 / ex.cxx)) + 1
285
+ if k > 1: # lag 1 is already its own band
286
+ ex.kstar = k
287
+ n = len(ex.w)
288
+ w = np.insert(ex.w, n - 1, 0.0)
289
+ P = np.insert(np.insert(ex.P, n - 1, 0.0, axis=0), n - 1, 0.0, axis=1); P[n - 1, n - 1] = RLS_P0
290
+ ex.w, ex.P = w, P
291
+
292
+ # ---------------- screening (each part on its own phase, every SCREEN_EVERY steps)
293
+ def _screen_spread(self, res):
294
+ w, se, t = SCREEN_W, SCREEN_EVERY, self.t
295
+ act = {u[1] for u in self.active if u[0] == "in"}
296
+ due = [i for i in range(self.d) if (t + i) % se == 0]
297
+ x, x1, ra = self.H[0], self.H[1], 1e-3 * se
298
+ for i in due:
299
+ self.a_c0[i] += ra * (x[i] * x[i] - self.a_c0[i]); self.a_c1[i] += ra * (x[i] * x1[i] - self.a_c1[i])
300
+ self.fp["screening"] += 6
301
+ if i in act:
302
+ continue
303
+ a = float(self._a()[i]); pres = res - a * self.res_prev
304
+ for b, (lo, hi) in enumerate(BANDS):
305
+ ub = (self.bs[b, i] - a * (self.bs[b, i] - self.H[lo, i] + self.H[hi + 1, i])) / (hi - lo + 1)
306
+ self.sc_xy[b, i] += w * (pres * ub - self.sc_xy[b, i]); self.sc_xx[b, i] += w * (ub * ub - self.sc_xx[b, i])
307
+ self.sc_yy[i] += w * (pres * pres - self.sc_yy[i])
308
+ self.fp["screening"] += 11 * len(BANDS) + 5
309
+ if t % se == self.d % se: # residual latent unit
310
+ self.sr_xy += w * (res * self.r - self.sr_xy); self.sr_xx += w * (self.r * self.r - self.sr_xx)
311
+ self.sr_yy += w * (res * res - self.sr_yy); self.fp["screening"] += 12 * len(POLES)
312
+ if t % se == (self.d + 1) % se: # equivalence groups (reporting only)
313
+ gw = 1e-3 * se
314
+ self.g_m += gw * (x - self.g_m); xc = x - self.g_m
315
+ self.g_c += gw * (np.outer(xc, xc) - self.g_c)
316
+ self.fp["screening"] += 3 * self.d * (self.d + 1) // 2 + 2 * self.d
317
+ for j, key in enumerate(self.split_keys()):
318
+ if (t + j) % se:
319
+ continue
320
+ i, sg = key[1], key[2:]
321
+ l_, r_ = halves(sg); dv = self._mean(i, l_) - self._mean(i, r_)
322
+ st = self.sp.setdefault(key, [0.0, 1e-3, 1.0])
323
+ st[0] += w * (res * dv - st[0]); st[1] += w * (dv * dv - st[1]); st[2] += w * (res * res - st[2])
324
+ self.fp["screening"] += 14
325
+
326
+ def equivalents(self, unit, thr=0.95):
327
+ if unit[0] != "in":
328
+ return set()
329
+ i = unit[1]; sd = np.sqrt(np.maximum(np.diag(self.g_c), 1e-12))
330
+ r = np.abs(self.g_c[i]) / (sd[i] * sd)
331
+ return {int(j) for j in np.flatnonzero(r >= thr)}
332
+
333
+ def split_keys(self):
334
+ out = []
335
+ for u, st in self.active.items():
336
+ if u[0] == "in":
337
+ out += [("split", u[1]) + sg for sg in st["segs"] if sg[1] > sg[0]]
338
+ return out
339
+
340
+ def screen_stat(self, key):
341
+ k = SCREEN_W / (2 - SCREEN_W)
342
+ if key[0] == "split":
343
+ st = self.sp.get(key)
344
+ return 0.0 if st is None else st[0] ** 2 / (st[1] * st[2] + 1e-12) / k
345
+ if key[0] == "in":
346
+ i = key[1]
347
+ c2 = self.sc_xy[:, i] ** 2 / (self.sc_xx[:, i] * self.sc_yy[i] + 1e-12)
348
+ else:
349
+ c2 = self.sr_xy ** 2 / (self.sr_xx * self.sr_yy + 1e-12)
350
+ return float(c2.sum()) / k
351
+
352
+ # ---------------- lifecycle
353
+ @staticmethod
354
+ def unit_of(key):
355
+ return ("in", key[1]) if key[0] == "split" else key
356
+
357
+ def _open(self, kind, add_key, rem_key):
358
+ hkey = ("out", rem_key) if kind == "rem" else ("in", add_key)
359
+ ex = self.engine.open(kind, add_key, rem_key, hkey, EPS[kind], self.t)
360
+ if add_key:
361
+ n_ = len(self.cfeat(add_key)); ex.w = np.zeros(n_); ex.P = RLS_P0 * np.eye(n_)
362
+ if kind == "split": # start from the parent's weight on both halves
363
+ st = self.active[self.unit_of(add_key)]
364
+ ex.w[:] = float(st["w"][st["segs"].index(add_key[2:])])
365
+ for k in (add_key, rem_key):
366
+ if k:
367
+ self.last_tested[k] = self.t
368
+
369
+ def _decide(self):
370
+ changed = set()
371
+ for decision, ex, le in self.engine.review():
372
+ if decision == "accepted":
373
+ self._accept(ex, le)
374
+ changed |= {self.unit_of(k) for k in (ex.add_key, ex.rem_key) if k}
375
+ else:
376
+ self.events.append((self.t, "closed", ex.kind, ex.add_key, ex.rem_key, round(le, 2), ex.n))
377
+ if changed: # experiments about units that just changed no longer describe the live model
378
+ keep = []
379
+ for ex in self.engine.slots:
380
+ if {self.unit_of(k) for k in (ex.add_key, ex.rem_key) if k} & changed:
381
+ self.events.append((self.t, "superseded", ex.kind, ex.add_key, ex.rem_key, None, ex.n))
382
+ else:
383
+ keep.append(ex)
384
+ self.engine.slots = keep
385
+ self._retrack()
386
+ self.sp = {k: v for k, v in self.sp.items() if k in set(self.split_keys())}
387
+ self._fill()
388
+
389
+ def _accept(self, ex, le):
390
+ if ex.kind == "split":
391
+ u = self.unit_of(ex.add_key); st = self.active[u]; sg = ex.add_key[2:]
392
+ j = st["segs"].index(sg); l_, r_ = halves(sg)
393
+ st["segs"] = st["segs"][:j] + [l_, r_] + st["segs"][j + 1:]
394
+ st["w"] = np.concatenate([st["w"][:j], ex.w, st["w"][j + 1:]])
395
+ merged = {} # a half equal to the peak segment: one weight
396
+ for sg_, w_ in zip(st["segs"], st["w"]):
397
+ merged[sg_] = merged.get(sg_, 0.0) + float(w_)
398
+ st["segs"], st["w"] = list(merged), np.array(list(merged.values()))
399
+ else:
400
+ if ex.rem_key and ex.rem_key in self.active:
401
+ del self.active[ex.rem_key]; self.contrib_ema.pop(ex.rem_key, None)
402
+ if ex.add_key:
403
+ if ex.add_key[0] == "in":
404
+ segs = list(BANDS) + ([(ex.kstar, ex.kstar)] if ex.kstar else [])
405
+ self.active[ex.add_key] = {"segs": segs, "w": ex.w[:-1].copy()}
406
+ self.base[1 + ex.add_key[1]] += float(ex.w[-1])
407
+ else:
408
+ self.active[ex.add_key] = {"segs": None, "w": ex.w.copy()}
409
+ self.engine.consume(ex)
410
+ self._retrack()
411
+ self.events.append((self.t, "accepted", ex.kind, ex.add_key, ex.rem_key, round(le, 2), ex.hyp.n))
412
+
413
+ def _fill(self):
414
+ busy = {self.unit_of(k) for k in self.engine.busy_keys()}
415
+ while self.engine.free_slots() > 0:
416
+ due = [a for a in self.active if a not in busy and self.t - self.last_rem.get(a, -10 ** 9) >= REM_PERIOD
417
+ and self.t - self.last_tested.get(a, -10 ** 9) >= N_MIN]
418
+ if due:
419
+ a = due[0]; self.last_rem[a] = self.t; self._open("rem", None, a); busy.add(a); continue
420
+ if any(ex.add_key and ex.k <= CHAL_WARM for ex in self.engine.slots):
421
+ break # one warm-up at a time
422
+ cands = []
423
+ pool = [u for u in self.units if u not in self.active and u not in busy
424
+ and self.t - self.last_tested.get(u, -10 ** 9) >= COOLDOWN]
425
+ if pool:
426
+ c = max(pool, key=self.screen_stat)
427
+ if self.screen_stat(c) >= SCREEN_Q:
428
+ cands.append((self.screen_stat(c) / SCREEN_Q, "unit", c))
429
+ sp = [k for k in self.split_keys() if self.unit_of(k) not in busy
430
+ and self.t - self.last_tested.get(k, -10 ** 9) >= COOLDOWN]
431
+ if sp:
432
+ c = max(sp, key=self.screen_stat)
433
+ if self.screen_stat(c) >= SPLIT_Q:
434
+ cands.append((self.screen_stat(c) / SPLIT_Q, "split", c))
435
+ if not cands:
436
+ break
437
+ _, typ, c = max(cands)
438
+ if typ == "split":
439
+ self._open("split", c, None)
440
+ elif len(self.active) < M_MAX:
441
+ self._open("add", c, None)
442
+ else:
443
+ a = min((k for k in self.active if k not in busy), key=lambda k: self.contrib_ema.get(k, float("inf")), default=None)
444
+ if a is None:
445
+ break
446
+ self._open("swap", c, a); busy.add(a)
447
+ busy.add(self.unit_of(c))
448
+ self.fp["control"] += (len(self.units) + len(self.sp)) / DECIDE_EVERY
449
+
450
+ def fp_total(self):
451
+ return sum(self.fp.values()) + self.M.fp + self.engine.fp
lebre/_engine.py ADDED
@@ -0,0 +1,105 @@
1
+ """Evidence engine of LEBRE v0.52-r1: persistent hypotheses with a one-sided sub-exponential mixture e-process,
2
+ e-LOND-type acceptance levels fixed at creation, and experiment slots closed by a scan rule.
3
+
4
+ Extracted from the frozen research implementation (change_engine.py, evidence="psiE1"); arithmetic is unchanged.
5
+ """
6
+ import math
7
+
8
+ import numpy as np
9
+
10
+
11
+ def _gamma_const(n=10 ** 6):
12
+ k = np.arange(1, n + 1, dtype=float)
13
+ s = float(np.sum(1.0 / (k * np.log(k + 1) ** 2)))
14
+ return 1.0 / (s + 1.0 / math.log(n + 1)) # tail bound of the integral
15
+
16
+
17
+ GAMMA_C = _gamma_const()
18
+
19
+
20
+ def gamma_k(k):
21
+ return GAMMA_C / (k * math.log(k + 1) ** 2)
22
+
23
+
24
+ class Hypothesis:
25
+ """Weak null: over the steps at which this change was tested, the challenger did not improve the clipped loss of the
26
+ reference by more than eps on average. One-sided mixture e-process with c = 1 + max(eps, 0) and predictable
27
+ centring gamma_i = min(past mean, 0) (valid because d_i - gamma_i >= -c)."""
28
+ LAMBDAS_FRAC = 0.9 * 2.0 ** -np.arange(8) # lambda grid as a fraction of 1/c (uniform mixture)
29
+
30
+ def __init__(self, eps, alpha_level, idx):
31
+ self.eps = eps
32
+ self.c = 1.0 + max(eps, 0.0)
33
+ self.alpha = alpha_level; self.log_thr = math.log(1.0 / alpha_level); self.idx = idx
34
+ self.S = 0.0; self.V = 0.0; self.n = 0; self.mean = 0.0
35
+ self.lam = self.LAMBDAS_FRAC / self.c
36
+ self.psi = (-np.log(1 - self.c * self.lam) - self.c * self.lam) / self.c ** 2
37
+ self.peak_stats = None
38
+
39
+ def observe(self, d):
40
+ gamma = max(-self.c, min(0.0, self.mean))
41
+ self.S += d; self.V += (d - gamma) ** 2; self.n += 1
42
+ dm = d - self.mean; self.mean += dm / self.n
43
+
44
+ def log_e(self):
45
+ a = self.lam * self.S - self.psi * self.V
46
+ m = a.max()
47
+ return float(m + math.log(np.mean(np.exp(a - m))))
48
+
49
+
50
+ class Experiment:
51
+ """One episode on a slot; evidence goes to the persistent hypothesis. The challenger's parameters (w, P, k, kstar)
52
+ are owned and updated by the model."""
53
+
54
+ def __init__(self, kind, add_key, rem_key, hyp, t0):
55
+ self.kind, self.add_key, self.rem_key, self.hyp, self.t0 = kind, add_key, rem_key, hyp, t0
56
+ self.S = 0.0; self.n = 0; self.k = 0; self.kstar = None
57
+ self.eps = hyp.eps
58
+
59
+ def observe(self, d):
60
+ self.hyp.observe(d); self.S += d; self.n += 1
61
+
62
+
63
+ class ChangeEngine:
64
+ def __init__(self, alpha, family_size, m_slots, n_min, T_max):
65
+ self.alpha, self.P, self.m_slots, self.n_min, self.T_max = alpha, family_size, m_slots, n_min, T_max
66
+ self.hyps = {}; self.n_hyp = 0; self.n_accepted = 0; self.k_started = 0
67
+ self.slots = []; self.fp = 0.0
68
+
69
+ def hypothesis(self, hkey, eps):
70
+ if hkey not in self.hyps:
71
+ self.n_hyp += 1
72
+ g = 1.0 / (2 * self.P) if self.n_hyp <= self.P else 0.5 * gamma_k(self.n_hyp - self.P) # sum <= 1
73
+ self.hyps[hkey] = Hypothesis(eps, min(self.alpha * g * (self.n_accepted + 1), 0.5), self.n_hyp)
74
+ return self.hyps[hkey]
75
+
76
+ def open(self, kind, add_key, rem_key, hkey, eps, t):
77
+ self.k_started += 1
78
+ ex = Experiment(kind, add_key, rem_key, self.hypothesis(hkey, eps), t)
79
+ self.slots.append(ex)
80
+ return ex
81
+
82
+ def free_slots(self):
83
+ return self.m_slots - len(self.slots)
84
+
85
+ def review(self):
86
+ """[(decision, experiment, log_e)] with decision in {'accepted', 'closed'}; keeps the others running."""
87
+ out, keep = [], []
88
+ for ex in self.slots:
89
+ le = ex.hyp.log_e(); self.fp += 3 * len(ex.hyp.lam)
90
+ if le >= ex.hyp.log_thr:
91
+ out.append(("accepted", ex, le))
92
+ elif ex.n >= self.T_max or (ex.n >= self.n_min and ex.S <= 0.0): # scan rule: not ahead -> free the slot
93
+ out.append(("closed", ex, le))
94
+ else:
95
+ keep.append(ex)
96
+ self.slots = keep
97
+ return out
98
+
99
+ def consume(self, ex):
100
+ """an accepted change: count the discovery and retire its hypothesis (a new instance if ever retested)."""
101
+ self.n_accepted += 1
102
+ self.hyps = {k: h for k, h in self.hyps.items() if h is not ex.hyp}
103
+
104
+ def busy_keys(self):
105
+ return {k for ex in self.slots for k in (ex.add_key, ex.rem_key) if k}
lebre/_memory.py ADDED
@@ -0,0 +1,70 @@
1
+ """Memory expert M of LEBRE v0.52-r1: forecast of the target from its own past, relative to the last value
2
+ (mean reversion, last difference, seasonal naive and one-cycle increment, per-phase profile of increments, optional
3
+ second declared cycle), learned by NLMS with scale-relative floors.
4
+
5
+ Extracted from the frozen research implementation (lebre_v052.Memory and lebre_v052h.MemoryW); arithmetic is unchanged.
6
+ """
7
+ import numpy as np
8
+
9
+
10
+ class Memory:
11
+ def __init__(self, season=None, mu=0.05, a_prof=0.1, a_mean=0.01, eps_rel=1e-3):
12
+ self.s, self.mu, self.ap, self.am, self.eps_rel = season, mu, a_prof, a_mean, eps_rel
13
+ self.feats = ("mean", "d1", "sn", "si", "prof") if season else ("mean", "d1")
14
+ self.Lb = 2 * season + 2 if season else 3
15
+ self.buf = np.zeros(self.Lb); self.n = 0
16
+ self.mew = None; self.G = np.zeros(season) if season else None
17
+ self.w = np.zeros(len(self.feats)); self.phi = None; self.pp_ema = None; self.y2 = None; self.fp = 0.0
18
+
19
+ def _b(self, k):
20
+ return self.buf[(self.n - k) % self.Lb]
21
+
22
+ def predict(self):
23
+ if self.n < self.Lb:
24
+ self.phi = None
25
+ return self._b(1) if self.n else 0.0
26
+ last, s = self._b(1), self.s
27
+ v = [(self.mew - last) if self.mew is not None else 0.0, last - self._b(2)]
28
+ if s:
29
+ v += [self._b(s) - last, self._b(s - 1) - self._b(s), self.G[self.n % s]]
30
+ self.phi = np.array(v); self.fp += 3 * len(v) + 1
31
+ return last + float(self.w @ self.phi)
32
+
33
+ def update(self, y, y_hat, learn=True):
34
+ if y is None or not np.isfinite(y):
35
+ y, learn = y_hat, False
36
+ if learn and self.phi is not None:
37
+ pp = float(self.phi @ self.phi)
38
+ self.pp_ema = pp if self.pp_ema is None else self.pp_ema + 0.01 * (pp - self.pp_ema)
39
+ self.y2 = y * y if self.y2 is None else self.y2 + 1e-4 * (y * y - self.y2)
40
+ den = pp + self.eps_rel * self.pp_ema + 1e-4 * self.y2
41
+ if den > 0:
42
+ self.w += (self.mu * (y - y_hat) / den) * self.phi; self.fp += 4 * len(self.w) + 6
43
+ if learn and self.s and self.n >= 1:
44
+ ph = self.n % self.s; self.G[ph] += self.ap * ((y - self._b(1)) - self.G[ph]); self.fp += 4
45
+ if learn:
46
+ self.mew = y if self.mew is None else self.mew + self.am * (y - self.mew); self.fp += 3
47
+ self.buf[self.n % self.Lb] = y; self.n += 1
48
+
49
+
50
+ class MemoryW(Memory):
51
+ """memory with a second declared cycle (e.g. the week, 168 h, on top of the day, 24 h)"""
52
+
53
+ def __init__(self, season, season2, **kw):
54
+ super().__init__(season, **kw)
55
+ self.s2 = season2
56
+ self.feats = self.feats + ("sn2", "si2")
57
+ self.Lb = max(self.Lb, season2 + 2)
58
+ self.buf = np.zeros(self.Lb); self.w = np.zeros(len(self.feats))
59
+
60
+ def predict(self):
61
+ if self.n < self.Lb:
62
+ self.phi = None
63
+ return self._b(1) if self.n else 0.0
64
+ last, s = self._b(1), self.s
65
+ v = [(self.mew - last) if self.mew is not None else 0.0, last - self._b(2)]
66
+ if s:
67
+ v += [self._b(s) - last, self._b(s - 1) - self._b(s), self.G[self.n % s]]
68
+ v += [self._b(self.s2) - last, self._b(self.s2 - 1) - self._b(self.s2)]
69
+ self.phi = np.array(v); self.fp += 3 * len(v) + 1
70
+ return last + float(self.w @ self.phi)
lebre/model.py ADDED
@@ -0,0 +1,188 @@
1
+ """Public API of the LEBRE online forecaster (implements LEBRE v0.52-r1)."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ import pickle
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Optional, Sequence
9
+
10
+ import numpy as np
11
+
12
+ from ._core import Core
13
+
14
+ _FORMAT = "lebre-state"
15
+ _FORMAT_VERSION = 1
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class Forecast:
20
+ """One-step-ahead forecast issued before the target of that step is observed."""
21
+ value: float
22
+ lower: float # lower bound of the adaptive 90% interval (NaN until the interval is initialised)
23
+ upper: float # upper bound of the adaptive 90% interval
24
+ t: int # step index (0-based)
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class Event:
29
+ """Audit record of one structural experiment outcome."""
30
+ t: int # step at which the decision was taken
31
+ outcome: str # "accepted", "closed" (not accepted; evidence kept) or "superseded"
32
+ change: str # "add", "remove", "swap" or "split"
33
+ added: Optional[str] # unit that enters (None for a removal)
34
+ removed: Optional[str] # unit that leaves (None unless remove/swap)
35
+ log_evidence: Optional[float] # log of the e-process at the decision
36
+ samples: int # evidence samples behind the decision
37
+
38
+
39
+ class _CausalScaler:
40
+ """Causal exponential standardiser used in every LEBRE evaluation (rate 1e-4, from mean 0 / variance 1).
41
+ Missing input values (NaN) are passed on as missing and do not update the statistics."""
42
+
43
+ def __init__(self, d, alpha=1e-4, eps=1e-6):
44
+ self.alpha, self.eps = float(alpha), float(eps)
45
+ self.mean = np.zeros(d, dtype=np.float64); self.var = np.ones(d, dtype=np.float64)
46
+
47
+ def transform(self, x):
48
+ return (x - self.mean) / np.sqrt(self.var + self.eps)
49
+
50
+ def update(self, x):
51
+ ok = np.isfinite(x)
52
+ if ok.all():
53
+ delta = x - self.mean
54
+ self.mean += self.alpha * delta
55
+ self.var = (1.0 - self.alpha) * self.var + self.alpha * (x - self.mean) * delta
56
+ self.var = np.maximum(self.var, 1e-4)
57
+ else:
58
+ delta = np.where(ok, x - self.mean, 0.0)
59
+ new_mean = self.mean + self.alpha * delta
60
+ new_var = np.maximum((1.0 - self.alpha) * self.var + self.alpha * (np.where(ok, x, 0.0) - new_mean) * delta, 1e-4)
61
+ self.mean = np.where(ok, new_mean, self.mean); self.var = np.where(ok, new_var, self.var)
62
+
63
+
64
+ class Lebre:
65
+ """Online one-step-ahead forecaster for a target driven by exogenous inputs.
66
+
67
+ Parameters
68
+ ----------
69
+ n_inputs : number of exogenous inputs (the target's own past is added internally).
70
+ season : period of the declared cycle in steps (e.g. 24 for hourly data with a daily cycle), or None.
71
+ season2 : optional second declared cycle (e.g. 168 for the weekly cycle of hourly building data), or None.
72
+ standardize : standardise the inputs causally (the evaluated configuration). Set False only if the inputs are
73
+ already standardised by the caller with past-only statistics.
74
+
75
+ Usage: for each step, ``f = model.predict(x)`` with the current inputs, then ``model.observe(y)`` once the target
76
+ is known (``None``/NaN for a missing target). ``step(x, y)`` does both. Every structural change is recorded in
77
+ ``events``.
78
+ """
79
+
80
+ def __init__(self, n_inputs: int, season: Optional[int] = None, season2: Optional[int] = None, standardize: bool = True):
81
+ if n_inputs < 1:
82
+ raise ValueError("n_inputs must be >= 1")
83
+ self.n_inputs, self.season, self.season2, self.standardize = int(n_inputs), season, season2, bool(standardize)
84
+ self._core = Core(self.n_inputs, season=season, season2=season2)
85
+ self._scaler = _CausalScaler(self.n_inputs) if standardize else None
86
+ self._last: Optional[Forecast] = None
87
+
88
+ # ------------------------------------------------------------------ stepping
89
+ def predict(self, x: Sequence[float]) -> Forecast:
90
+ """Forecast of the current target from the current inputs x (length n_inputs)."""
91
+ x = np.asarray(x, dtype=np.float64).reshape(-1)
92
+ if x.shape[0] != self.n_inputs:
93
+ raise ValueError(f"expected {self.n_inputs} inputs, got {x.shape[0]}")
94
+ if self._scaler is not None:
95
+ xs = self._scaler.transform(x); self._scaler.update(x)
96
+ else:
97
+ xs = x
98
+ c = self._core
99
+ q = c.qhat
100
+ f = c.predict(xs)
101
+ lo, hi = (f - q, f + q) if q is not None else (math.nan, math.nan)
102
+ self._last = Forecast(float(f), float(lo), float(hi), c.t)
103
+ return self._last
104
+
105
+ def observe(self, y: Optional[float], quarantine: bool = False) -> None:
106
+ """Reveal the target of the step just predicted. y = None or NaN marks a missing target; quarantine=True
107
+ marks a value that must not be learned from (e.g. flagged by the data source)."""
108
+ self._core.observe(None if y is None else float(y), quarantine=bool(quarantine))
109
+
110
+ def step(self, x: Sequence[float], y: Optional[float], quarantine: bool = False) -> Forecast:
111
+ """predict(x) then observe(y); returns the forecast made before y was used."""
112
+ f = self.predict(x)
113
+ self.observe(y, quarantine)
114
+ return f
115
+
116
+ # ------------------------------------------------------------------ audit and structure
117
+ def unit_name(self, key) -> str:
118
+ if key is None:
119
+ return None
120
+ if key[0] == "in":
121
+ return "own_past" if key[1] == self.n_inputs else f"x{key[1]}"
122
+ if key[0] == "res":
123
+ return "residual_state"
124
+ if key[0] == "split":
125
+ base = "own_past" if key[1] == self.n_inputs else f"x{key[1]}"
126
+ return f"{base}[{key[2]}-{key[3]}]"
127
+ return str(key)
128
+
129
+ @property
130
+ def events(self) -> list:
131
+ kind = {"add": "add", "rem": "remove", "swap": "swap", "split": "split"}
132
+ return [Event(int(t), out, kind[k], self.unit_name(a), self.unit_name(r), le, int(n))
133
+ for t, out, k, a, r, le, n in self._core.events]
134
+
135
+ @property
136
+ def structure(self) -> list:
137
+ """active units: names of the inputs (x0, x1, ..., own_past) and/or residual_state"""
138
+ return [self.unit_name(u) for u in sorted(self._core.active)]
139
+
140
+ def response(self, unit: str) -> list:
141
+ """recovered response of an active input: [((lag_lo, lag_hi), weight per lag), ...] in standardised units"""
142
+ for u in self._core.active:
143
+ if self.unit_name(u) == unit and u[0] == "in":
144
+ return self._core.response(u)
145
+ raise KeyError(f"{unit} is not an active input")
146
+
147
+ def equivalent_inputs(self, unit: str) -> list:
148
+ """inputs whose causal correlation with `unit` is >= 0.95 (the accepted input may stand for any of them)"""
149
+ for u in self._core.units:
150
+ if self.unit_name(u) == unit:
151
+ return [self.unit_name(("in", j)) for j in sorted(self._core.equivalents(u))]
152
+ raise KeyError(unit)
153
+
154
+ @property
155
+ def n_steps(self) -> int:
156
+ return self._core.t
157
+
158
+ @property
159
+ def coverage(self) -> float:
160
+ """empirical coverage of the 90% interval so far"""
161
+ c = self._core
162
+ return c.hits_ok / c.hits_obs if c.hits_obs else math.nan
163
+
164
+ @property
165
+ def cost_per_step(self) -> float:
166
+ """mean analytic floating-point operations per step so far (operation-count model of the research code)"""
167
+ return self._core.fp_total() / self._core.t if self._core.t else math.nan
168
+
169
+ # ------------------------------------------------------------------ persistence
170
+ def save(self, path) -> None:
171
+ """Save the full state (pickle). Only load files you trust: unpickling can execute code."""
172
+ with open(Path(path), "wb") as fh:
173
+ pickle.dump({"format": _FORMAT, "version": _FORMAT_VERSION, "model": self}, fh, protocol=pickle.HIGHEST_PROTOCOL)
174
+
175
+ @classmethod
176
+ def load(cls, path) -> "Lebre":
177
+ """Load a state saved by `save`. Only load files you trust: unpickling can execute code."""
178
+ with open(Path(path), "rb") as fh:
179
+ obj = pickle.load(fh)
180
+ if not isinstance(obj, dict) or obj.get("format") != _FORMAT:
181
+ raise ValueError("not a LEBRE state file")
182
+ if obj.get("version") != _FORMAT_VERSION:
183
+ raise ValueError(f"unsupported state format version {obj.get('version')}")
184
+ return obj["model"]
185
+
186
+ def __repr__(self):
187
+ return (f"Lebre(n_inputs={self.n_inputs}, season={self.season}, season2={self.season2}, "
188
+ f"steps={self.n_steps}, structure={self.structure})")
lebre/py.typed ADDED
File without changes
@@ -0,0 +1,85 @@
1
+ Metadata-Version: 2.5
2
+ Name: lebre
3
+ Version: 0.1.0
4
+ Summary: Online one-step-ahead forecasting with statistically tested structural changes, at a cost of a few hundred operations per step (implements LEBRE v0.52-r1).
5
+ Project-URL: Source, https://github.com/Iquitim/lebre
6
+ Project-URL: Issues, https://github.com/Iquitim/lebre/issues
7
+ Project-URL: Research record, https://github.com/Iquitim/lebre-research
8
+ Project-URL: Research DOI, https://doi.org/10.5281/zenodo.23049103
9
+ Author: Silvano Lima
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: TinyML,anytime-valid inference,e-process,exogenous inputs,online forecasting,time series
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: numpy>=1.24
20
+ Provides-Extra: test
21
+ Requires-Dist: pytest>=7; extra == 'test'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # lebre
25
+
26
+ [![tests](https://github.com/Iquitim/lebre/actions/workflows/tests.yml/badge.svg)](https://github.com/Iquitim/lebre/actions/workflows/tests.yml)
27
+
28
+ Online one-step-ahead forecasting for a target driven by exogenous inputs, with **statistically tested structural changes**, at a cost of a few hundred floating-point operations per step.
29
+
30
+ `lebre 0.1.0` implements **LEBRE v0.52-r1**, the frozen research version documented and evaluated in the research record:
31
+ - repository: https://github.com/Iquitim/lebre-research
32
+ - DOI: [10.5281/zenodo.23049103](https://doi.org/10.5281/zenodo.23049103)
33
+
34
+ The package reproduces the research code **bit for bit in the reference environment** (Windows, CPython 3.11, NumPy 2.2.5), checked against references generated from the frozen code and on real evaluation series in the research repository. On other platforms and NumPy versions, floating-point rounding differs in the last bits (~1e-14): the regression tests then require identical structural decisions and forecasts equal within 1e-9 of their scale.
35
+
36
+ ```bash
37
+ pip install lebre
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ ```python
43
+ from lebre import Lebre
44
+
45
+ model = Lebre(n_inputs=3, season=24) # season: declared cycle in steps (None if there is none)
46
+ for x_t, y_t in stream: # x_t: current inputs (length 3), y_t: target (None/NaN if missing)
47
+ f = model.predict(x_t) # Forecast(value, lower, upper, t), issued before y_t is known
48
+ model.observe(y_t)
49
+ # or: f = model.step(x_t, y_t)
50
+
51
+ model.structure # e.g. ['x0', 'own_past']
52
+ model.response("x0") # recovered lag response: [((lag_lo, lag_hi), weight per lag), ...]
53
+ model.events # audit log: Event(t, outcome, change, added, removed, log_evidence, samples)
54
+ model.equivalent_inputs("x0") # inputs indistinguishable from x0 (causal correlation >= 0.95)
55
+ model.coverage, model.cost_per_step # empirical 90%-interval coverage; analytic operations per step
56
+ model.save("state.pkl"); model = Lebre.load("state.pkl") # pickle: load only files you trust
57
+ ```
58
+
59
+ See `examples/quickstart.py`.
60
+
61
+ ## What it does
62
+
63
+ - **Live model:**
64
+ - a memory of the target's own past: level, declared cycle(s), per-phase profile;
65
+ - a linear regression on the current inputs;
66
+ - the two combined by dynamic model averaging.
67
+ - **Structural changes run in shadow as experiments:** adding, removing or swapping a whole input, or refining its lag response by hierarchical splits of octave bands.
68
+ - **Acceptance:** a change is accepted only when an anytime-valid e-process of predictive improvement crosses a level fixed by an online multiple-testing rule.
69
+ - **Output safeguards:** target gaps are held (never filled with the model's own forecasts), and forecasts stay within an envelope of the observed values.
70
+ - **Inputs:** they are standardised causally inside the model; set `standardize=False` only if you already do this with past-only statistics.
71
+
72
+ ## Scope and limits
73
+
74
+ These are the limits of the evaluated version, stated honestly (details in the specification, §19):
75
+ - evaluated on hydrology and building-energy series with 1–5 inputs, one step ahead;
76
+ - it is **not** meant to be the most accurate forecaster: in the evaluations it tied a SARIMAX with inputs fitted per series and had ~25% higher error than Chronos-2 with covariates, at a tiny fraction of the cost;
77
+ - the testing mechanism does not improve accuracy over switching all inputs on; its role is an audited, evidence-backed structure;
78
+ - an accepted input means *it improved the forecast of the current model, with evidence*, not *it is the cause*: correlated substitutes can be accepted, and near-identical inputs are indistinguishable;
79
+ - the e-values are valid under the stated assumptions; false-change control with the adaptive reference was verified empirically;
80
+ - delays of very smooth inputs are often not discovered (information limit), though forecasts remain good;
81
+ - the declared cost contract of the research version (mean ≤ 400, peak ≤ 1,000 operations per step) was narrowly not met.
82
+
83
+ ## Licence
84
+
85
+ Apache-2.0. If you use it, please cite the research record (`CITATION.cff`).
@@ -0,0 +1,10 @@
1
+ lebre/__init__.py,sha256=oZhnNgJrPezqjVmuxn-CnujBZg6GNceYfQu-M6x6NMw,746
2
+ lebre/_core.py,sha256=OCmV4uvtG076uuo2_GPrI0LNYanbxlAHoY8-lBIDrf4,22735
3
+ lebre/_engine.py,sha256=JYXu-XgjC4VPS4PGHnThlJppCwmd2xFHgBZQdkXIfKs,4294
4
+ lebre/_memory.py,sha256=6tBnXjsw2DnfEqgZ4H-6zCMDmlTVYboPBP3CMKdf8nc,3362
5
+ lebre/model.py,sha256=4eNh1ki9vOcRC79BoAg15iKBwdzo5W2yuFsiWKr_DS0,8825
6
+ lebre/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ lebre-0.1.0.dist-info/METADATA,sha256=BeHza04SMYQ7TY66tR6SurFzeabRRICnHyy5zke0oM4,5260
8
+ lebre-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
9
+ lebre-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
10
+ lebre-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.