processsupport 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.
@@ -0,0 +1,1226 @@
1
+ """Constrained joint support/transport response estimation.
2
+
3
+ The response is linear in transported inputs. Alternation is biconvex, not a
4
+ global-optimum certificate. Prediction and physical identification are separate.
5
+ """
6
+
7
+ from dataclasses import dataclass
8
+ from copy import deepcopy
9
+ import hashlib
10
+ import json
11
+ import numpy as np
12
+ from scipy.linalg import lstsq
13
+ from scipy.optimize import minimize
14
+
15
+ from ._validation import array, ids, require
16
+ from .results import NumericalResult, ScientificRefusal, json_safe
17
+
18
+
19
+ def _digest(value):
20
+ return hashlib.sha256(
21
+ json.dumps(json_safe(value), sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
22
+ ).hexdigest()
23
+
24
+
25
+ def _starts(lags, regimes, seed):
26
+ """Eight feasible starts, deduplicating short-history deterministic starts."""
27
+ rng = np.random.default_rng(seed)
28
+ base = [np.ones(lags) / lags]
29
+ for centre in np.rint(np.linspace(0, lags - 1, 6)).astype(int):
30
+ weight = np.maximum(0, 1 - np.abs(np.arange(lags) - centre) / 2)
31
+ weight /= weight.sum()
32
+ if lags > 2 or not any(np.array_equal(weight, previous) for previous in base):
33
+ base.append(weight)
34
+ if lags == 1:
35
+ return [np.ones((regimes, 1)) for _ in range(8)]
36
+ while len(base) < 8:
37
+ base.append(rng.dirichlet(np.ones(lags)))
38
+ return [np.tile(w, (regimes, 1)) for w in base[:8]]
39
+
40
+
41
+ def _aggregated_history(x, support, regime_index, n_regimes):
42
+ return np.asarray(
43
+ [
44
+ np.einsum("mn,nlp->mlp", support * (regime_index == r)[None, :], x, optimize=True)
45
+ for r in range(n_regimes)
46
+ ]
47
+ )
48
+
49
+
50
+ def _objective_gradient(
51
+ kernels,
52
+ theta,
53
+ history,
54
+ support,
55
+ targets,
56
+ sigma,
57
+ regime_index,
58
+ balance_matrix=None,
59
+ balance_target=None,
60
+ balance_sigma=None,
61
+ *,
62
+ ridge=0.0,
63
+ balance_weight=0.0,
64
+ smoothness=0.0,
65
+ aggregated=None,
66
+ ):
67
+ """Exact kernel gradient in full coordinates; tests use reduced-simplex oracles."""
68
+ n_regimes, lags = kernels.shape
69
+ if aggregated is None:
70
+ aggregated = _aggregated_history(history, support, regime_index, n_regimes)
71
+ observed_input = np.einsum("rmlp,rl->mp", aggregated, kernels, optimize=True)
72
+ observed_prediction = theta[0] + observed_input @ theta[1:]
73
+ residual = observed_prediction - targets
74
+ objective = float(np.mean((residual / sigma) ** 2) + ridge * np.sum(theta[1:] ** 2))
75
+ derivative = np.einsum("rmlp,pq->rmlq", aggregated, theta[1:], optimize=True)
76
+ gradient = 2 * np.einsum("rmlq,mq->rl", derivative, residual / sigma**2, optimize=True) / targets.size
77
+ if balance_weight > 0:
78
+ transported = np.einsum("nlp,nl->np", history, kernels[regime_index], optimize=True)
79
+ grid_prediction = theta[0] + transported @ theta[1:]
80
+ balance_error = grid_prediction @ balance_matrix.T - balance_target
81
+ objective += balance_weight * float(np.mean((balance_error / balance_sigma) ** 2))
82
+ db = np.einsum("nlp,pq,kq->nlk", history, theta[1:], balance_matrix, optimize=True)
83
+ for r in range(n_regimes):
84
+ gradient[r] += (
85
+ 2
86
+ * balance_weight
87
+ * np.einsum(
88
+ "nlk,nk->l",
89
+ db * (regime_index == r)[:, None, None],
90
+ balance_error / balance_sigma**2,
91
+ optimize=True,
92
+ )
93
+ / balance_error.size
94
+ )
95
+ difference = np.diff(kernels, axis=1)
96
+ objective += smoothness * float(np.sum(difference**2))
97
+ if lags > 1:
98
+ gradient[:, :-1] -= 2 * smoothness * difference
99
+ gradient[:, 1:] += 2 * smoothness * difference
100
+ return objective, gradient
101
+
102
+
103
+ @dataclass
104
+ class _Problem:
105
+ x: np.ndarray
106
+ h: np.ndarray
107
+ y: np.ndarray
108
+ sigma: np.ndarray
109
+ r: np.ndarray
110
+ regimes: list
111
+ b: np.ndarray | None
112
+ d: np.ndarray | None
113
+ sb: np.ndarray | None
114
+ aggregated: np.ndarray
115
+
116
+
117
+ def _support(value, n):
118
+ if value is None:
119
+ raise ScientificRefusal(
120
+ "unknown-support",
121
+ "Known physical support is required; it is never inferred from labels",
122
+ "support",
123
+ )
124
+ h = array(value, "support", 2)
125
+ require(
126
+ h.shape[1] == n and np.all(h >= 0) and np.allclose(h.sum(axis=1), 1, atol=1e-10, rtol=1e-10),
127
+ "support",
128
+ "Support rows must be nonnegative, normalized and match grid histories",
129
+ )
130
+ return h
131
+
132
+
133
+ def _indices(value, n, field, empty=False):
134
+ a = np.asarray(value)
135
+ if a.size == 0 and empty:
136
+ return np.array([], dtype=int)
137
+ require(
138
+ a.ndim == 1 and a.size > 0 and np.issubdtype(a.dtype, np.integer),
139
+ "split-indices",
140
+ "Indices must be nonempty integer vectors",
141
+ field,
142
+ )
143
+ a = a.astype(int)
144
+ require(
145
+ np.all((a >= 0) & (a < n)) and len(np.unique(a)) == len(a),
146
+ "split-indices",
147
+ "Indices must be unique and within observation rows",
148
+ field,
149
+ )
150
+ return a
151
+
152
+
153
+ def _availability(mapping, n, active):
154
+ if mapping is None:
155
+ return "offline-only"
156
+ require(
157
+ isinstance(mapping, dict)
158
+ and mapping.get("timebase") in {"verified-relative-seconds", "verified-utc-seconds"},
159
+ "availability",
160
+ "Online histories need a verified common timebase",
161
+ )
162
+ released = array(mapping.get("history_release_times_s"), "history_release_times_s", finite=False)
163
+ decision = array(mapping.get("decision_times_s"), "decision_times_s", 1)
164
+ require(
165
+ len(released) == len(decision) == n and released.ndim in {1, 2},
166
+ "availability",
167
+ "Release/decision grids must match history rows",
168
+ )
169
+ latest = released if released.ndim == 1 else np.max(released, axis=1)
170
+ require(
171
+ np.isfinite(latest[active]).all() and np.all(latest[active] <= decision[active]),
172
+ "future-information",
173
+ "Required histories include unknown or future releases",
174
+ )
175
+ return "asof-known-or-upper-bound"
176
+
177
+
178
+ def _known_unit(unit):
179
+ if isinstance(unit, dict):
180
+ return {"symbol", "dimension", "basis"} <= set(unit) and all(
181
+ _known_unit(unit[k]) for k in ("symbol", "dimension", "basis")
182
+ )
183
+ return (
184
+ isinstance(unit, str)
185
+ and bool(unit.strip())
186
+ and not any(
187
+ marker in unit.lower()
188
+ for marker in ["unknown", "unspecified", "not_documented", "not-documented"]
189
+ )
190
+ )
191
+
192
+
193
+ class SupportTransportRegressor:
194
+ """Joint simplex transport kernels and physical multi-output linear response."""
195
+
196
+ def __init__(
197
+ self,
198
+ ridge=0.1,
199
+ balance_weight=1.0,
200
+ smoothness=0.01,
201
+ seed=11,
202
+ max_iter=100,
203
+ kernel_max_iter=200,
204
+ ablation="none",
205
+ ):
206
+ require(
207
+ all(np.isfinite(v) and v >= 0 for v in [ridge, balance_weight, smoothness]),
208
+ "regularization",
209
+ "Regularization weights must be finite and nonnegative",
210
+ )
211
+ require(
212
+ isinstance(max_iter, int)
213
+ and 1 <= max_iter <= 100
214
+ and isinstance(kernel_max_iter, int)
215
+ and 1 <= kernel_max_iter <= 200,
216
+ "budget",
217
+ "Alternation/kernel budgets cannot exceed 100/200",
218
+ )
219
+ require(
220
+ isinstance(seed, (int, np.integer)) and seed >= 0, "seed", "Seed must be a nonnegative integer"
221
+ )
222
+ require(
223
+ ablation in {"none", "fixed-transport", "point-support", "no-balance", "shared-regime"},
224
+ "ablation",
225
+ "Unknown transport ablation",
226
+ )
227
+ self.ridge, self.balance_weight, self.smoothness = (
228
+ float(ridge),
229
+ float(balance_weight),
230
+ float(smoothness),
231
+ )
232
+ self.seed, self.max_iter, self.kernel_max_iter, self.ablation = (
233
+ int(seed),
234
+ max_iter,
235
+ kernel_max_iter,
236
+ ablation,
237
+ )
238
+ self._profile_constraint = None
239
+
240
+ def get_params(self):
241
+ return dict(
242
+ ridge=self.ridge,
243
+ balance_weight=self.balance_weight,
244
+ smoothness=self.smoothness,
245
+ seed=self.seed,
246
+ max_iter=self.max_iter,
247
+ kernel_max_iter=self.kernel_max_iter,
248
+ ablation=self.ablation,
249
+ )
250
+
251
+ def _objective(self, w, theta, data):
252
+ return _objective_gradient(
253
+ w,
254
+ theta,
255
+ data.x,
256
+ data.h,
257
+ data.y,
258
+ data.sigma,
259
+ data.r,
260
+ data.b,
261
+ data.d,
262
+ data.sb,
263
+ ridge=self.ridge,
264
+ balance_weight=self._effective_balance,
265
+ smoothness=self.smoothness,
266
+ aggregated=data.aggregated,
267
+ )
268
+
269
+ def _theta_system(self, w, data, regularized=True):
270
+ u = np.einsum("nlp,nl->np", data.x, w[data.r], optimize=True)
271
+ z = np.column_stack([np.ones(len(u)), u])
272
+ hz = data.h @ z
273
+ q = data.y.shape[1]
274
+ coefficients = z.shape[1] * q
275
+ estimated_rows = data.y.size + (data.d.size if self._effective_balance > 0 else 0) + coefficients
276
+ require(
277
+ estimated_rows * coefficients * 8 <= 128 * 1024**2,
278
+ "overlimit",
279
+ "Augmented response matrix exceeds the declared 128 MiB allocation bound",
280
+ estimated_bytes=estimated_rows * coefficients * 8,
281
+ )
282
+ observation = np.kron(hz, np.eye(q)) / data.sigma.ravel()[:, None] / np.sqrt(data.y.size)
283
+ target = data.y.ravel() / data.sigma.ravel() / np.sqrt(data.y.size)
284
+ blocks, targets = [observation], [target]
285
+ if self._effective_balance > 0:
286
+ balance = np.einsum("na,kq->nkaq", z, data.b, optimize=True).reshape(-1, coefficients)
287
+ scale = np.sqrt(self._effective_balance / data.d.size) / data.sb.ravel()
288
+ blocks.append(balance * scale[:, None])
289
+ targets.append(data.d.ravel() * scale)
290
+ if regularized and self.ridge > 0:
291
+ penalty = np.zeros((coefficients - q, coefficients))
292
+ penalty[:, q:] = np.sqrt(self.ridge) * np.eye(coefficients - q)
293
+ blocks.append(penalty)
294
+ targets.append(np.zeros(coefficients - q))
295
+ return np.vstack(blocks), np.concatenate(targets)
296
+
297
+ def _solve_theta(self, w, data):
298
+ matrix, target = self._theta_system(w, data)
299
+ theta, _, rank, _ = lstsq(matrix, target, lapack_driver="gelsd")
300
+ require(np.isfinite(theta).all(), "nonfinite-solution", "Least-squares response is nonfinite")
301
+ return theta.reshape(data.x.shape[2] + 1, data.y.shape[1]), int(rank)
302
+
303
+ def _kernel_constraints(self, regime, lags):
304
+ constraints = [dict(type="eq", fun=lambda w: w.sum() - 1, jac=lambda w: np.ones(lags))]
305
+ if self._profile_constraint is not None and self._profile_constraint[0] == regime:
306
+ target = self._profile_constraint[1]
307
+ lag = np.arange(lags, dtype=float)
308
+ constraints.append(dict(type="eq", fun=lambda w: w @ lag - target, jac=lambda w: lag))
309
+ return constraints
310
+
311
+ def _initial_profile(self, w):
312
+ if self._profile_constraint is None:
313
+ return w
314
+ regime, mean = self._profile_constraint
315
+ lag = np.arange(w.shape[1], dtype=float)
316
+ opt = minimize(
317
+ lambda a: float(np.sum((a - w[regime]) ** 2)),
318
+ w[regime],
319
+ jac=lambda a: 2 * (a - w[regime]),
320
+ method="SLSQP",
321
+ bounds=[(0, 1)] * len(lag),
322
+ constraints=self._kernel_constraints(regime, len(lag)),
323
+ options=dict(ftol=1e-12, maxiter=200),
324
+ )
325
+ require(opt.success, "profile-feasibility", "Mean-lag profile constraint is infeasible")
326
+ w[regime] = opt.x
327
+ return w
328
+
329
+ def _run_start(self, initial, data):
330
+ w = self._initial_profile(initial.copy())
331
+ theta, rank = self._solve_theta(w, data)
332
+ objective = self._objective(w, theta, data)[0]
333
+ trace = [
334
+ dict(
335
+ iteration=0,
336
+ block="initial-theta",
337
+ objective=objective,
338
+ simplex_residual=float(np.max(np.abs(w.sum(axis=1) - 1))),
339
+ )
340
+ ]
341
+ stable = 0
342
+ solver_failure = False
343
+ converged = False
344
+ for iteration in range(1, self.max_iter + 1):
345
+ previous_w, previous_theta, previous_objective = w.copy(), theta.copy(), objective
346
+ if w.shape[1] > 1 and self.ablation != "fixed-transport":
347
+ for r in range(len(w)):
348
+
349
+ def function(part):
350
+ candidate = w.copy()
351
+ candidate[r] = part
352
+ value, grad = self._objective(candidate, theta, data)
353
+ return value, grad[r]
354
+
355
+ opt = minimize(
356
+ function,
357
+ w[r],
358
+ jac=True,
359
+ method="SLSQP",
360
+ bounds=[(0, 1)] * w.shape[1],
361
+ constraints=self._kernel_constraints(r, w.shape[1]),
362
+ options=dict(ftol=1e-10, maxiter=self.kernel_max_iter),
363
+ )
364
+ feasible = bool(
365
+ np.isfinite(opt.x).all() and opt.x.min() >= -1e-10 and abs(opt.x.sum() - 1) <= 1e-8
366
+ )
367
+ if self._profile_constraint is not None and self._profile_constraint[0] == r:
368
+ feasible &= abs(opt.x @ np.arange(w.shape[1]) - self._profile_constraint[1]) <= 1e-8
369
+ stalled = not opt.success or not feasible
370
+ step = 0.0
371
+ old = w[r].copy()
372
+ if not stalled:
373
+ step = 1.0
374
+ for _ in range(40):
375
+ candidate = w.copy()
376
+ candidate[r] = old + step * (opt.x - old)
377
+ candidate_objective = self._objective(candidate, theta, data)[0]
378
+ if candidate_objective <= objective + 1e-10 * max(abs(objective), 1e-12):
379
+ w = candidate
380
+ objective = candidate_objective
381
+ break
382
+ step *= 0.5
383
+ else:
384
+ stalled = True
385
+ step = 0.0
386
+ if stalled:
387
+ solver_failure = True
388
+ trace.append(
389
+ dict(
390
+ iteration=iteration,
391
+ block=f"kernel-{r}",
392
+ objective=objective,
393
+ step=step,
394
+ stalled=stalled,
395
+ solver_success=bool(opt.success),
396
+ solver_message=str(opt.message),
397
+ simplex_residual=float(np.max(np.abs(w.sum(axis=1) - 1))),
398
+ )
399
+ )
400
+ theta, rank = self._solve_theta(w, data)
401
+ objective = self._objective(w, theta, data)[0]
402
+ require(
403
+ objective <= previous_objective + 1e-9 * max(abs(previous_objective), 1e-12),
404
+ "nonmonotone-solve",
405
+ "Response least-squares block increased the objective",
406
+ )
407
+ change = max(float(np.max(np.abs(w - previous_w))), float(np.max(np.abs(theta - previous_theta))))
408
+ improvement = max(0.0, previous_objective - objective) / max(abs(previous_objective), 1e-12)
409
+ balance_residual = None
410
+ if self._effective_balance > 0:
411
+ u = np.einsum("nlp,nl->np", data.x, w[data.r], optimize=True)
412
+ balance_residual = float(np.max(np.abs((theta[0] + u @ theta[1:]) @ data.b.T - data.d)))
413
+ trace.append(
414
+ dict(
415
+ iteration=iteration,
416
+ block="theta",
417
+ objective=objective,
418
+ relative_improvement=improvement,
419
+ maximum_parameter_change=change,
420
+ simplex_residual=float(np.max(np.abs(w.sum(axis=1) - 1))),
421
+ balance_residual=balance_residual,
422
+ )
423
+ )
424
+ stable = stable + 1 if improvement < 1e-7 and change < 1e-6 else 0
425
+ if stable >= 3 and not solver_failure:
426
+ converged = True
427
+ break
428
+ return dict(
429
+ kernels=w,
430
+ theta=theta,
431
+ objective=objective,
432
+ trace=trace,
433
+ converged=converged,
434
+ solver_failure=solver_failure,
435
+ response_rank=rank,
436
+ iterations=iteration,
437
+ initial_kernel=initial,
438
+ )
439
+
440
+ def fit(
441
+ self,
442
+ X,
443
+ Y,
444
+ *,
445
+ support,
446
+ observation_sigma,
447
+ regime_ids,
448
+ train_indices,
449
+ validation_indices=(),
450
+ balance_matrix=None,
451
+ balance_target=None,
452
+ balance_sigma=None,
453
+ source_ids=None,
454
+ feature_names=None,
455
+ feature_units=None,
456
+ output_names=None,
457
+ output_units=None,
458
+ availability=None,
459
+ dependency_groups=None,
460
+ observation_ids=None,
461
+ ):
462
+ self.__dict__.pop("fit_result_", None)
463
+ x, y = array(X, "X", 3), array(Y, "Y", 2, finite=False)
464
+ n, lags, p = x.shape
465
+ require(
466
+ feature_units is not None and output_units is not None,
467
+ "missing-units",
468
+ "Declare known ordered feature_units and output_units before physical transport fitting",
469
+ )
470
+ require(
471
+ len(feature_units) == p
472
+ and len(output_units) == y.shape[1]
473
+ and all(_known_unit(unit) for unit in list(feature_units) + list(output_units)),
474
+ "missing-units",
475
+ "Feature/output units are unknown or do not match the numerical axes",
476
+ )
477
+ require(
478
+ 1 <= lags <= 13 and 1 <= p <= 32,
479
+ "shape",
480
+ "Transport supports 1..13 lag bins and 1..32 input quantities",
481
+ )
482
+ h = _support(support, n)
483
+ require(len(y) == len(h), "shape", "Each target must have one physical support row")
484
+ sigma = array(observation_sigma, "observation_sigma", 2)
485
+ require(
486
+ sigma.shape == y.shape and np.all(sigma > 0),
487
+ "uncertainty",
488
+ "Each physical target needs a positive declared scale",
489
+ )
490
+ train = _indices(train_indices, len(y), "train_indices")
491
+ validation = _indices(validation_indices, len(y), "validation_indices", empty=True)
492
+ require(
493
+ not np.intersect1d(train, validation).size,
494
+ "split-overlap",
495
+ "Training and validation observations overlap",
496
+ )
497
+ require(np.isfinite(y[train]).all(), "nonfinite-target", "Training targets must be finite")
498
+ untouched = np.setdiff1d(np.arange(len(y)), train)
499
+ active = np.flatnonzero(np.any(h[train] > 0, axis=0))
500
+ if len(untouched):
501
+ require(
502
+ not np.any(h[untouched][:, active] > 0),
503
+ "support-leakage",
504
+ "Training supports overlap held-out grid regions",
505
+ )
506
+ names = ids(observation_ids, len(y))
507
+ if dependency_groups is not None:
508
+ groups = np.asarray(dependency_groups, dtype=str)
509
+ require(
510
+ groups.shape == (len(y),), "split-groups", "Dependency groups must match observation rows"
511
+ )
512
+ require(
513
+ not set(groups[train]) & set(groups[untouched]),
514
+ "split-groups",
515
+ "A dependency group crosses training and held-out roles",
516
+ )
517
+ else:
518
+ groups = None
519
+ policy = _availability(availability, n, active)
520
+ regime = np.asarray(regime_ids, dtype=str)
521
+ require(
522
+ regime.shape == (n,) and np.all(regime != "") and np.all(regime != "None"),
523
+ "regime",
524
+ "Available regime IDs must match grid rows",
525
+ )
526
+ if self.ablation == "shared-regime":
527
+ regime = np.repeat("pooled", n)
528
+ regimes = sorted(set(regime[active]))
529
+ regime_index = np.array([regimes.index(v) for v in regime[active]])
530
+ self.mean_ = x[active].mean(axis=(0, 1))
531
+ self.scale_ = x[active].std(axis=(0, 1))
532
+ self.mask_ = self.scale_ > 0
533
+ require(
534
+ self.mask_.any(),
535
+ "constant-features",
536
+ "No variable training feature can identify a response or transport",
537
+ )
538
+ scaled = (x[active][:, :, self.mask_] - self.mean_[self.mask_]) / self.scale_[self.mask_]
539
+ ht = h[train][:, active].copy()
540
+ if self.ablation == "point-support":
541
+ for row in ht:
542
+ indices = np.flatnonzero(row)
543
+ centre = np.sum(indices * row[indices])
544
+ chosen = indices[np.argmin(np.abs(indices - centre))]
545
+ row[:] = 0
546
+ row[chosen] = 1
547
+ self._effective_balance = 0.0 if self.ablation == "no-balance" else self.balance_weight
548
+ b = d = sb = None
549
+ if self._effective_balance > 0:
550
+ require(
551
+ balance_matrix is not None and balance_target is not None and balance_sigma is not None,
552
+ "missing-balance",
553
+ "Positive balance weight requires genuinely available balance rows and scales",
554
+ )
555
+ b, d, sb = (
556
+ array(balance_matrix, "balance_matrix", 2),
557
+ array(balance_target, "balance_target", 2),
558
+ array(balance_sigma, "balance_sigma", 2),
559
+ )
560
+ require(
561
+ b.shape[1] == y.shape[1] and d.shape == sb.shape == (n, len(b)) and np.all(sb > 0),
562
+ "balance-shape",
563
+ "Balance dimensions and positive physical scales must match grid and outputs",
564
+ )
565
+ require(np.linalg.matrix_rank(b) == len(b), "balance-rank", "Balance rows must be independent")
566
+ d, sb = d[active], sb[active]
567
+ data = _Problem(
568
+ scaled,
569
+ ht,
570
+ y[train],
571
+ sigma[train],
572
+ regime_index,
573
+ regimes,
574
+ b,
575
+ d,
576
+ sb,
577
+ _aggregated_history(scaled, ht, regime_index, len(regimes)),
578
+ )
579
+ starts = _starts(lags, len(regimes), self.seed)
580
+ runs = []
581
+ for start in starts:
582
+ try:
583
+ runs.append(self._run_start(start, data))
584
+ except ScientificRefusal as exc:
585
+ if exc.code == "overlimit":
586
+ raise
587
+ runs.append(
588
+ dict(
589
+ converged=False, objective=None, trace=[], failure=exc.to_dict(), initial_kernel=start
590
+ )
591
+ )
592
+ converged = [run for run in runs if run["converged"]]
593
+ if not converged:
594
+ raise ScientificRefusal(
595
+ "nonconvergence",
596
+ "No feasible start met the full three-step convergence criterion",
597
+ details={"starts": json_safe(runs), "max_alternations": self.max_iter},
598
+ reference={"name": "unaccepted-feasible-starts", "status": "diagnostic-only"},
599
+ )
600
+ best = min(converged, key=lambda run: run["objective"])
601
+ self.theta_, self.kernels_, self.regimes_ = best["theta"], best["kernels"], regimes
602
+ identification = self._identification(data, runs, best)
603
+ self.lag_bins_, self.n_features_, self.n_outputs_ = lags, p, y.shape[1]
604
+ f_names = list(feature_names) if feature_names is not None else [f"feature-{i}" for i in range(p)]
605
+ f_units = list(feature_units) if feature_units is not None else ["unspecified"] * p
606
+ o_names = (
607
+ list(output_names) if output_names is not None else [f"output-{i}" for i in range(y.shape[1])]
608
+ )
609
+ o_units = list(output_units) if output_units is not None else ["unspecified"] * y.shape[1]
610
+ require(
611
+ len(f_names) == len(f_units) == p
612
+ and len(o_names) == len(o_units) == y.shape[1]
613
+ and all(isinstance(name, str) and name.strip() for name in f_names + o_names)
614
+ and len(set(f_names)) == p
615
+ and len(set(o_names)) == y.shape[1],
616
+ "feature-order",
617
+ "Ordered names and units must match model axes",
618
+ )
619
+ self.metadata_ = dict(
620
+ feature_names=f_names,
621
+ feature_units=f_units,
622
+ output_names=o_names,
623
+ output_units=o_units,
624
+ source_ids=list(source_ids or ()),
625
+ training_observation_ids=[names[i] for i in train],
626
+ validation_observation_ids=[names[i] for i in validation],
627
+ observation_ids_supplied=observation_ids is not None,
628
+ training_grid_indices=active,
629
+ availability_policy=policy,
630
+ output_normalization="physical-unscaled",
631
+ mean_lag_profile_constraint=self._profile_constraint,
632
+ regime_policy="available-input-categories",
633
+ training_groups=None if groups is None else groups[train],
634
+ training_ids_sha256=_digest([names[i] for i in train]),
635
+ support_sha256=_digest(h[train]),
636
+ training_data_sha256=_digest(dict(x=x[active], y=y[train], sigma=sigma[train])),
637
+ diagnostic_context_sha256=_digest(
638
+ dict(train_indices=train, regime=regime[active], b=b, d=d, sb=sb, policy=policy)
639
+ ),
640
+ balance_matrix=b,
641
+ effective_balance_weight=self._effective_balance,
642
+ constraints={
643
+ "simplex": True,
644
+ "output_nonnegative_constraint": False,
645
+ "physical_balance": "soft-declared-uncertainty",
646
+ },
647
+ )
648
+ prediction = data.h @ (
649
+ self.theta_[0] + np.einsum("nlp,nl->np", data.x, self.kernels_[data.r]) @ self.theta_[1:]
650
+ )
651
+ self.fit_result_ = NumericalResult(
652
+ prediction,
653
+ dict(
654
+ converged=True,
655
+ objective=best["objective"],
656
+ selected_start=next(i for i, run in enumerate(runs) if run is best),
657
+ starts=runs,
658
+ identification=identification,
659
+ dropped_feature_indices=np.flatnonzero(~self.mask_),
660
+ simplex_residual=float(np.max(np.abs(self.kernels_.sum(axis=1) - 1))),
661
+ mean_lag_bins=self.kernels_ @ np.arange(lags),
662
+ metadata=self.metadata_,
663
+ research_status="proposal; novelty and superiority unverified",
664
+ ),
665
+ source_ids or (),
666
+ status="available" if identification["identified"] else "partial",
667
+ )
668
+ return self
669
+
670
+ def _identification(self, data, runs, best):
671
+ theta_matrix, _ = self._theta_system(best["kernels"], data, regularized=False)
672
+ w, theta = best["kernels"], best["theta"]
673
+ obs = np.einsum("rmlp,pq->rmlq", data.aggregated, theta[1:], optimize=True)
674
+ columns, faces = [], []
675
+ if self._effective_balance > 0:
676
+ db = np.einsum("nlp,pq,kq->nlk", data.x, theta[1:], data.b, optimize=True)
677
+ for r in range(len(w)):
678
+ active = np.flatnonzero(w[r] > 1e-8)
679
+ faces.append(active.tolist())
680
+ for lag in active[:-1]:
681
+ observed = (
682
+ (obs[r, :, lag] - obs[r, :, active[-1]]) / data.sigma / np.sqrt(data.y.size)
683
+ ).ravel()
684
+ parts = [observed]
685
+ if self._effective_balance > 0:
686
+ balance = (db[:, lag] - db[:, active[-1]]) * (data.r == r)[:, None]
687
+ parts.append((balance / data.sb * np.sqrt(self._effective_balance / data.d.size)).ravel())
688
+ columns.append(np.concatenate(parts))
689
+ matrix = np.column_stack([theta_matrix, *columns])
690
+ norms = np.linalg.norm(matrix, axis=0)
691
+ nonzero = norms > np.finfo(float).tiny
692
+ normalized = np.zeros_like(matrix)
693
+ normalized[:, nonzero] = matrix[:, nonzero] / norms[nonzero]
694
+ singular = np.linalg.svd(normalized, compute_uv=False)
695
+ rank = int(np.linalg.matrix_rank(normalized, tol=singular[0] * 1e-8)) if len(singular) else 0
696
+ relative = (
697
+ float(singular[-1] / singular[0])
698
+ if len(singular) and singular[0] > 0 and matrix.shape[0] >= matrix.shape[1]
699
+ else 0.0
700
+ )
701
+ identified = bool(nonzero.all() and rank == matrix.shape[1] and relative >= 1e-8)
702
+ reasons = [] if identified else ["unregularized-jacobian-rank-or-excitation"]
703
+ lag = np.arange(w.shape[1])
704
+ equally_good = [
705
+ run
706
+ for run in runs
707
+ if run.get("converged")
708
+ and run["objective"] <= best["objective"] + 1e-7 * max(abs(best["objective"]), 1e-12)
709
+ ]
710
+ means = np.asarray([run["kernels"] @ lag for run in equally_good])
711
+ ambiguous = bool(len(means) > 1 and np.any(np.ptp(means, axis=0) > (w.shape[1] - 1) / 2))
712
+ if ambiguous:
713
+ identified = False
714
+ reasons.append("equally-good-start-mean-lag-ambiguity")
715
+ if w.shape[1] == 1:
716
+ identified = False
717
+ reasons.append("single-lag-has-no-free-transport-parameter")
718
+ return dict(
719
+ identified=identified,
720
+ reasons=reasons,
721
+ unregularized=True,
722
+ rank=rank,
723
+ free_coefficients=matrix.shape[1],
724
+ rows=matrix.shape[0],
725
+ relative_smallest_singular_value=relative,
726
+ condition=None if relative == 0 else 1 / relative,
727
+ column_normalization="training-weighted-Jacobian unit-norm columns",
728
+ active_faces=faces,
729
+ active_face_assumption="zero kernel entries held fixed for local diagnostic",
730
+ equivalent_start_mean_lags=means,
731
+ bootstrap_status="not-run",
732
+ profile_status="not-run",
733
+ profile_by_regime={},
734
+ )
735
+
736
+ def predict(
737
+ self,
738
+ X,
739
+ *,
740
+ support,
741
+ regime_ids,
742
+ availability=None,
743
+ feature_names=None,
744
+ feature_units=None,
745
+ source_ids=(),
746
+ require_identified=False,
747
+ observation_ids=None,
748
+ ):
749
+ require(hasattr(self, "fit_result_"), "not-fitted", "Fit or restore a converged model first")
750
+ x = array(X, "X", 3)
751
+ require(
752
+ x.shape[1:] == (self.lag_bins_, self.n_features_),
753
+ "shape",
754
+ "Query history axes differ from the fitted model",
755
+ )
756
+ h = _support(support, len(x))
757
+ active = np.flatnonzero(np.any(h > 0, axis=0))
758
+ policy = _availability(availability, len(x), active)
759
+ if feature_names is not None:
760
+ require(
761
+ list(feature_names) == self.metadata_["feature_names"],
762
+ "feature-order",
763
+ "Query feature names changed",
764
+ )
765
+ if feature_units is not None:
766
+ require(
767
+ list(feature_units) == self.metadata_["feature_units"],
768
+ "feature-units",
769
+ "Query feature units changed without a declared conversion",
770
+ )
771
+ if (~self.mask_).any():
772
+ reference = self.mean_[~self.mask_]
773
+ tolerance = 1e-12 * np.maximum(np.abs(reference), np.finfo(float).tiny)
774
+ require(
775
+ np.all(np.abs(x[active][:, :, ~self.mask_] - reference) <= tolerance),
776
+ "changed-constant-feature",
777
+ "A query changes a training-constant dropped feature",
778
+ )
779
+ regime = np.asarray(regime_ids, dtype=str)
780
+ require(regime.shape == (len(x),), "regime", "Query regime IDs must match grid rows")
781
+ if self.ablation == "shared-regime":
782
+ regime = np.repeat("pooled", len(x))
783
+ unseen = sorted(set(regime[active]) - set(self.regimes_))
784
+ require(
785
+ not unseen,
786
+ "unseen-regime",
787
+ "Unseen input regime refuses the fitted transport; use a separately named pooled reference",
788
+ unseen=unseen,
789
+ )
790
+ identification = self.fit_result_.diagnostics["identification"]
791
+ interpretation_complete = bool(
792
+ identification["identified"]
793
+ and identification["bootstrap_status"] == "complete"
794
+ and identification["profile_status"] == "complete"
795
+ and identification.get("bootstrap_requested") == 200
796
+ and identification.get("bootstrap_successful") == 200
797
+ and all(identification.get("profile_by_regime", {}).get(r) == "complete" for r in self.regimes_)
798
+ )
799
+ if require_identified:
800
+ require(
801
+ interpretation_complete,
802
+ "weak-identification",
803
+ "Physical transport interpretation is refused or still lacks its bootstrap/profile diagnostics",
804
+ reasons=identification["reasons"],
805
+ bootstrap_status=identification["bootstrap_status"],
806
+ profile_status=identification["profile_status"],
807
+ )
808
+ r = np.array([self.regimes_.index(value) for value in regime[active]])
809
+ scaled = (x[active][:, :, self.mask_] - self.mean_[self.mask_]) / self.scale_[self.mask_]
810
+ u = np.einsum("nlp,nl->np", scaled, self.kernels_[r], optimize=True)
811
+ grid = self.theta_[0] + u @ self.theta_[1:]
812
+ query_support = h[:, active].copy()
813
+ if self.ablation == "point-support":
814
+ for row in query_support:
815
+ indices = np.flatnonzero(row)
816
+ centre = np.sum(indices * row[indices])
817
+ chosen = indices[np.argmin(np.abs(indices - centre))]
818
+ row[:] = 0
819
+ row[chosen] = 1
820
+ predictions = query_support @ grid
821
+ require(np.isfinite(predictions).all(), "nonfinite-prediction", "Transport prediction is nonfinite")
822
+ negative = int(np.sum(predictions < 0))
823
+ interpretation = (
824
+ "identified-diagnostic"
825
+ if interpretation_complete
826
+ else "unverified-pending-bootstrap-profile"
827
+ if identification["identified"]
828
+ else "refused"
829
+ )
830
+ return NumericalResult(
831
+ predictions,
832
+ dict(
833
+ identification=deepcopy(identification),
834
+ prediction_state="converged-predictive-fit",
835
+ physical_interpretation=interpretation,
836
+ physical_output_state="negative-flow-refusal" if negative else "nonnegative-on-this-query",
837
+ recovered_plant_transport_claim=False,
838
+ negative_prediction_count=negative,
839
+ availability_policy=policy,
840
+ support_sha256=_digest(h),
841
+ observation_ids=ids(observation_ids, len(h)),
842
+ metadata=self.metadata_,
843
+ ),
844
+ source_ids or self.metadata_["source_ids"],
845
+ status="available" if identification["identified"] and not negative else "partial",
846
+ )
847
+
848
+ def to_dict(self):
849
+ require(
850
+ hasattr(self, "fit_result_"), "not-fitted", "Cannot serialize an unfitted or failed estimator"
851
+ )
852
+ return json_safe(
853
+ dict(
854
+ schema_version="1.0.0",
855
+ package_version="0.1.0",
856
+ estimator="SupportTransportRegressor",
857
+ parameters=self.get_params(),
858
+ theta=self.theta_,
859
+ kernels=self.kernels_,
860
+ regimes=self.regimes_,
861
+ mean=self.mean_,
862
+ scale=self.scale_,
863
+ mask=self.mask_,
864
+ lag_bins=self.lag_bins_,
865
+ n_features=self.n_features_,
866
+ n_outputs=self.n_outputs_,
867
+ metadata=self.metadata_,
868
+ fit_diagnostics=self.fit_result_.diagnostics,
869
+ )
870
+ )
871
+
872
+ @classmethod
873
+ def from_dict(cls, state):
874
+ require(isinstance(state, dict), "state-type", "Fitted state must be a mapping")
875
+ required = {
876
+ "schema_version",
877
+ "package_version",
878
+ "estimator",
879
+ "parameters",
880
+ "theta",
881
+ "kernels",
882
+ "regimes",
883
+ "mean",
884
+ "scale",
885
+ "mask",
886
+ "lag_bins",
887
+ "n_features",
888
+ "n_outputs",
889
+ "metadata",
890
+ "fit_diagnostics",
891
+ }
892
+ require(
893
+ required <= set(state),
894
+ "state-fields",
895
+ "Fitted state is missing required fields",
896
+ missing=sorted(required - set(state)),
897
+ )
898
+ require(
899
+ state.get("schema_version") == "1.0.0"
900
+ and state.get("package_version") == "0.1.0"
901
+ and state.get("estimator") == "SupportTransportRegressor",
902
+ "state-version",
903
+ "Unsupported fitted-state contract",
904
+ )
905
+ require(
906
+ isinstance(state["parameters"], dict)
907
+ and set(state["parameters"])
908
+ == {"ridge", "balance_weight", "smoothness", "seed", "max_iter", "kernel_max_iter", "ablation"},
909
+ "state-parameters",
910
+ "Restored parameter names do not match the estimator contract",
911
+ )
912
+ require(
913
+ isinstance(state["mask"], list) and all(isinstance(value, bool) for value in state["mask"]),
914
+ "state-mask",
915
+ "Restored feature mask must contain actual booleans",
916
+ )
917
+ model = cls(**state["parameters"])
918
+ model.theta_ = array(state["theta"], "theta", 2)
919
+ model.kernels_ = array(state["kernels"], "kernels", 2)
920
+ require(
921
+ isinstance(state["regimes"], list)
922
+ and len(state["regimes"]) > 0
923
+ and all(isinstance(r, str) and r.strip() and r != "None" for r in state["regimes"])
924
+ and len(set(state["regimes"])) == len(state["regimes"]),
925
+ "state-regimes",
926
+ "Restored regime identities must be unique nonempty strings",
927
+ )
928
+ model.regimes_ = list(state["regimes"])
929
+ model.mean_ = array(state["mean"], "mean", 1)
930
+ model.scale_ = array(state["scale"], "scale", 1)
931
+ model.mask_ = np.asarray(state["mask"], dtype=bool)
932
+ model.lag_bins_, model.n_features_, model.n_outputs_ = (
933
+ state["lag_bins"],
934
+ state["n_features"],
935
+ state["n_outputs"],
936
+ )
937
+ require(
938
+ model.kernels_.shape == (len(model.regimes_), model.lag_bins_)
939
+ and np.all(model.kernels_ >= -1e-10)
940
+ and np.allclose(model.kernels_.sum(axis=1), 1, atol=1e-8),
941
+ "state-kernel",
942
+ "Restored kernels violate simplex or shape",
943
+ )
944
+ require(
945
+ model.mask_.shape == model.mean_.shape == model.scale_.shape == (model.n_features_,)
946
+ and np.all(model.scale_[model.mask_] > 0)
947
+ and model.theta_.shape == (int(model.mask_.sum()) + 1, model.n_outputs_),
948
+ "state-shape",
949
+ "Restored response or feature transforms are incompatible",
950
+ )
951
+ model.metadata_ = deepcopy(state["metadata"])
952
+ metadata_fields = {
953
+ "feature_names",
954
+ "feature_units",
955
+ "output_names",
956
+ "output_units",
957
+ "effective_balance_weight",
958
+ "source_ids",
959
+ }
960
+ require(
961
+ isinstance(model.metadata_, dict) and metadata_fields <= set(model.metadata_),
962
+ "state-metadata",
963
+ "Fitted state lacks ordered quantity or provenance metadata",
964
+ )
965
+ require(
966
+ all(
967
+ isinstance(model.metadata_[key], list)
968
+ for key in ("feature_names", "feature_units", "output_names", "output_units", "source_ids")
969
+ )
970
+ and all(
971
+ isinstance(name, str) and name.strip()
972
+ for name in model.metadata_["feature_names"] + model.metadata_["output_names"]
973
+ )
974
+ and len(set(model.metadata_["feature_names"])) == model.n_features_
975
+ and len(set(model.metadata_["output_names"])) == model.n_outputs_
976
+ and len(model.metadata_["feature_names"])
977
+ == len(model.metadata_["feature_units"])
978
+ == model.n_features_
979
+ and len(model.metadata_["output_names"])
980
+ == len(model.metadata_["output_units"])
981
+ == model.n_outputs_
982
+ and all(
983
+ _known_unit(u) for u in model.metadata_["feature_units"] + model.metadata_["output_units"]
984
+ ),
985
+ "state-metadata",
986
+ "Restored names and units do not match numerical axes",
987
+ )
988
+ model._profile_constraint = model.metadata_.get("mean_lag_profile_constraint")
989
+ model._effective_balance = model.metadata_["effective_balance_weight"]
990
+ diagnostics = deepcopy(state["fit_diagnostics"])
991
+ require(
992
+ isinstance(diagnostics, dict)
993
+ and isinstance(diagnostics.get("identification"), dict)
994
+ and {"identified", "reasons", "bootstrap_status", "profile_status"}
995
+ <= set(diagnostics["identification"]),
996
+ "state-diagnostics",
997
+ "Restored state lacks identification and diagnostic completion states",
998
+ )
999
+ require(
1000
+ diagnostics.get("converged") is True,
1001
+ "state-convergence",
1002
+ "A restored state must carry convergence evidence",
1003
+ )
1004
+ model.fit_result_ = NumericalResult(
1005
+ None,
1006
+ diagnostics,
1007
+ model.metadata_["source_ids"],
1008
+ status="available" if diagnostics["identification"]["identified"] else "partial",
1009
+ )
1010
+ return model
1011
+
1012
+ def _check_diagnostic_inputs(self, X, Y, fit_kwargs):
1013
+ """Bind every post-fit refit to the original TRAIN data and physical problem."""
1014
+ x, y = array(X, "X", 3), array(Y, "Y", 2, finite=False)
1015
+ h = _support(fit_kwargs.get("support"), len(x))
1016
+ train = _indices(fit_kwargs.get("train_indices"), len(y), "train_indices")
1017
+ sigma = array(fit_kwargs.get("observation_sigma"), "observation_sigma", 2)
1018
+ require(
1019
+ len(h) == len(y) and sigma.shape == y.shape,
1020
+ "diagnostic-input",
1021
+ "Diagnostic observation shapes differ from the fitted physical problem",
1022
+ )
1023
+ active = np.flatnonzero(np.any(h[train] > 0, axis=0))
1024
+ names = ids(fit_kwargs.get("observation_ids"), len(y))
1025
+ require(
1026
+ [names[i] for i in train] == self.metadata_["training_observation_ids"]
1027
+ and _digest(h[train]) == self.metadata_["support_sha256"]
1028
+ and _digest(dict(x=x[active], y=y[train], sigma=sigma[train]))
1029
+ == self.metadata_["training_data_sha256"],
1030
+ "diagnostic-training-mismatch",
1031
+ "Diagnostic refits must use the exact frozen TRAIN identities, support and values",
1032
+ )
1033
+ regime = np.asarray(fit_kwargs.get("regime_ids"), dtype=str)
1034
+ require(regime.shape == (len(x),), "diagnostic-input", "Diagnostic regimes must match grid rows")
1035
+ if self.ablation == "shared-regime":
1036
+ regime = np.repeat("pooled", len(x))
1037
+ b = d = sb = None
1038
+ if self._effective_balance > 0:
1039
+ b = array(fit_kwargs.get("balance_matrix"), "balance_matrix", 2)
1040
+ d = array(fit_kwargs.get("balance_target"), "balance_target", 2)
1041
+ sb = array(fit_kwargs.get("balance_sigma"), "balance_sigma", 2)
1042
+ require(
1043
+ d.shape == sb.shape == (len(x), len(b)),
1044
+ "diagnostic-input",
1045
+ "Diagnostic balance rows and uncertainties differ",
1046
+ )
1047
+ d, sb = d[active], sb[active]
1048
+ policy = _availability(fit_kwargs.get("availability"), len(x), active)
1049
+ signature = _digest(dict(train_indices=train, regime=regime[active], b=b, d=d, sb=sb, policy=policy))
1050
+ require(
1051
+ signature == self.metadata_.get("diagnostic_context_sha256"),
1052
+ "diagnostic-context-mismatch",
1053
+ "Diagnostic refits must preserve frozen regimes, balances, availability and TRAIN membership",
1054
+ )
1055
+ require(
1056
+ list(fit_kwargs.get("feature_units", ())) == self.metadata_["feature_units"]
1057
+ and list(fit_kwargs.get("output_units", ())) == self.metadata_["output_units"],
1058
+ "diagnostic-units",
1059
+ "Diagnostic units differ from the fitted physical problem",
1060
+ )
1061
+ return x, y, h, train, sigma
1062
+
1063
+ def bootstrap(self, X, Y, *, groups, n_bootstrap=200, seed=11, **fit_kwargs):
1064
+ """Refit frozen parameters on source-support/episode blocks, never TEST."""
1065
+ require(hasattr(self, "fit_result_"), "not-fitted", "Bootstrap requires the selected converged fit")
1066
+ require(
1067
+ isinstance(n_bootstrap, int) and 2 <= n_bootstrap <= 200,
1068
+ "bootstrap-budget",
1069
+ "Request between two and 200 block refits",
1070
+ )
1071
+ X, y, h, train, sigma = self._check_diagnostic_inputs(X, Y, fit_kwargs)
1072
+ g = np.asarray(groups, dtype=str)
1073
+ require(g.shape == (len(y),), "bootstrap-groups", "Episode/support groups must match observations")
1074
+ unique = np.unique(g[train])
1075
+ require(
1076
+ len(unique) >= 2,
1077
+ "bootstrap-groups",
1078
+ "At least two independent declared training blocks are required",
1079
+ )
1080
+ original_groups = self.metadata_.get("training_groups")
1081
+ require(
1082
+ original_groups is None or np.array_equal(g[train], np.asarray(original_groups)),
1083
+ "diagnostic-groups",
1084
+ "Bootstrap groups differ from the fitted dependency groups",
1085
+ )
1086
+ rng = np.random.default_rng(seed)
1087
+ means = []
1088
+ predictions = []
1089
+ failures = []
1090
+ draw_digests = []
1091
+ for repetition in range(n_bootstrap):
1092
+ drawn = rng.choice(unique, len(unique), replace=True)
1093
+ rows = np.concatenate([train[g[train] == group] for group in drawn])
1094
+ arguments = dict(fit_kwargs)
1095
+ arguments.update(
1096
+ support=h[rows],
1097
+ observation_sigma=sigma[rows],
1098
+ train_indices=np.arange(len(rows)),
1099
+ validation_indices=(),
1100
+ dependency_groups=g[rows],
1101
+ observation_ids=[f"bootstrap-{repetition}-{i}" for i in range(len(rows))],
1102
+ )
1103
+ draw_digests.append(_digest(rows))
1104
+ try:
1105
+ fit = type(self)(**self.get_params()).fit(X, y[rows], **arguments)
1106
+ require(
1107
+ fit.regimes_ == self.regimes_,
1108
+ "bootstrap-regime",
1109
+ "A bootstrap draw omitted a required fitted regime",
1110
+ )
1111
+ means.append(fit.kernels_ @ np.arange(self.lag_bins_))
1112
+ predictions.append(
1113
+ fit.predict(
1114
+ X,
1115
+ support=h[train],
1116
+ regime_ids=fit_kwargs["regime_ids"],
1117
+ availability=fit_kwargs.get("availability"),
1118
+ ).value
1119
+ )
1120
+ except ScientificRefusal as exc:
1121
+ failures.append(dict(repetition=repetition, code=exc.code, message=str(exc)))
1122
+ require(
1123
+ len(means) >= 2, "bootstrap-refusal", "Fewer than two bootstrap fits converged", failures=failures
1124
+ )
1125
+ mean_interval = np.quantile(means, [0.025, 0.975], axis=0)
1126
+ width = mean_interval[1] - mean_interval[0]
1127
+ weak = bool(np.any(width > (self.lag_bins_ - 1) / 2)) if self.lag_bins_ > 1 else False
1128
+ identification = self.fit_result_.diagnostics["identification"]
1129
+ identification["bootstrap_requested"] = n_bootstrap
1130
+ identification["bootstrap_successful"] = len(means)
1131
+ identification["bootstrap_status"] = (
1132
+ "complete"
1133
+ if n_bootstrap == 200 and len(means) == 200
1134
+ else "exploratory-budget"
1135
+ if n_bootstrap < 200
1136
+ else "partial-refits"
1137
+ )
1138
+ identification["bootstrap_mean_lag_interval_95"] = mean_interval
1139
+ if weak:
1140
+ identification["identified"] = False
1141
+ if "bootstrap-mean-lag-ambiguity" not in identification["reasons"]:
1142
+ identification["reasons"].append("bootstrap-mean-lag-ambiguity")
1143
+ self.fit_result_.status = "partial"
1144
+ return NumericalResult(
1145
+ dict(
1146
+ kernel_mean_lag_interval_95=mean_interval,
1147
+ prediction_mean=np.mean(predictions, axis=0),
1148
+ prediction_std=np.std(predictions, axis=0, ddof=1),
1149
+ ),
1150
+ dict(
1151
+ requested=n_bootstrap,
1152
+ successful=len(means),
1153
+ failures=failures,
1154
+ seed=seed,
1155
+ blocks=unique,
1156
+ draw_sha256=draw_digests,
1157
+ mean_lag_samples=np.asarray(means),
1158
+ weak_identification=weak,
1159
+ frozen_parameters=self.get_params(),
1160
+ uncertainty_scope="training-block diagnostic; no universal coverage theorem",
1161
+ ),
1162
+ self.metadata_["source_ids"],
1163
+ status="available" if n_bootstrap == 200 and len(means) == 200 else "partial",
1164
+ )
1165
+
1166
+ def profile_mean_lag(self, X, Y, *, regime, grid=None, **fit_kwargs):
1167
+ """Constrained training objective profile, never a likelihood interval."""
1168
+ require(hasattr(self, "fit_result_"), "not-fitted", "Profile requires the selected converged fit")
1169
+ self._check_diagnostic_inputs(X, Y, fit_kwargs)
1170
+ require(
1171
+ str(regime) in self.regimes_, "unseen-regime", "Only a fitted available regime can be profiled"
1172
+ )
1173
+ points = np.linspace(0, self.lag_bins_ - 1, 13) if grid is None else array(grid, "grid", 1)
1174
+ if self.lag_bins_ == 1:
1175
+ points = np.array([0.0])
1176
+ require(
1177
+ len(points) == (1 if self.lag_bins_ == 1 else 13)
1178
+ and np.all((points >= 0) & (points <= self.lag_bins_ - 1))
1179
+ and np.allclose(points, np.linspace(0, self.lag_bins_ - 1, len(points)), rtol=0, atol=1e-12)
1180
+ and (self.lag_bins_ == 1 or len(np.unique(points)) == 13),
1181
+ "profile-grid",
1182
+ "The predeclared profile has 13 admissible mean-lag points",
1183
+ )
1184
+ rows = []
1185
+ r = self.regimes_.index(str(regime))
1186
+ for mean in points:
1187
+ model = type(self)(**self.get_params())
1188
+ model._profile_constraint = (r, float(mean)) if self.lag_bins_ > 1 else None
1189
+ try:
1190
+ model.fit(X, Y, **fit_kwargs)
1191
+ value = model.fit_result_.diagnostics["objective"]
1192
+ rows.append(
1193
+ dict(
1194
+ mean_lag_bins=float(mean),
1195
+ objective=value,
1196
+ objective_increase=value - self.fit_result_.diagnostics["objective"],
1197
+ status="converged",
1198
+ )
1199
+ )
1200
+ except ScientificRefusal as exc:
1201
+ rows.append(
1202
+ dict(
1203
+ mean_lag_bins=float(mean),
1204
+ objective=None,
1205
+ objective_increase=None,
1206
+ status="refused",
1207
+ refusal=exc.to_dict(),
1208
+ )
1209
+ )
1210
+ complete = all(row["status"] == "converged" for row in rows)
1211
+ identification = self.fit_result_.diagnostics["identification"]
1212
+ by_regime = identification.setdefault("profile_by_regime", {})
1213
+ by_regime[str(regime)] = "complete" if complete else "partial-refits"
1214
+ identification["profile_status"] = (
1215
+ "complete" if all(by_regime.get(r) == "complete" for r in self.regimes_) else "partial-refits"
1216
+ )
1217
+ return NumericalResult(
1218
+ rows,
1219
+ dict(
1220
+ regime=str(regime),
1221
+ frozen_parameters=self.get_params(),
1222
+ interpretation="training objective increase; not a likelihood confidence interval",
1223
+ ),
1224
+ self.metadata_["source_ids"],
1225
+ status="available" if complete else "partial",
1226
+ )