drvec 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.
drvec/params.py ADDED
@@ -0,0 +1,311 @@
1
+ """The specification, the parameter vector and its two row orders.
2
+
3
+ THE TWO ROW ORDERS (the BUG-17 family of the C, REVIEW_2026-09-23 §5.1). Every
4
+ matrix of the VEC coordinates -- the rows of Lambda, the rows AND columns of
5
+ F_k, Theta_k and Sigma (Q) -- is in the INTERNAL order [Y1 ; Y2], so Q[0][0] = 1
6
+ is the variance of the first Y1 series. The data, the names, the mean, B2, w and
7
+ the residuals are in the .inp order [Y2 ; Y1] = [nabla Y2 ; W]. `RowOrder` is the
8
+ one place that maps between them (drvec.c:2841 inp2lam, 2850 lam2inp); it
9
+ depends on r.
10
+
11
+ THE VECTOR (par_blocks 881, calc_nparametrs 923; walked by vec_shootx 4439-4583):
12
+
13
+ mean case 1: none; case 2: E[W] (r); case 3: E[nabla Y2] (s) then E[W] (r)
14
+ Lambda M x r, ROW-major, internal rows
15
+ F_k k = 1..p-1, M x M row-major, internal (diagonal under diag_ar)
16
+ Theta_k k = 1..q, in the class's pattern, internal
17
+ Q Q[i][i] for i = 2..M, then Q[i][j], i = 2..M, j < i (Q[1][1] = 1)
18
+ B2 s x r, COLUMN-major, .inp order of the Y2 block
19
+
20
+ Lambda and B2 run in opposite orders, as in the C. One walker, here, is used by
21
+ every other module: the C has seven hand walks of this vector, and two of them
22
+ disagreeing is how BUG-30 and BUG-32 happened.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ from dataclasses import dataclass, replace
27
+
28
+ # the moving-average classes, as zero patterns on Theta (internal order)
29
+ MA_CLASSES = ("free", "diag", "marow", "matri")
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Spec:
34
+ M: int
35
+ p: int
36
+ q: int
37
+ r: int
38
+ case: int = 2
39
+ ma: str = "free" # free (the default since 2026-09-23), diag, marow, matri
40
+ diag_ar: bool = False
41
+ diag_cov: bool = False
42
+ drift: tuple = None # case 3: drift[i] False holds E[nabla Y2_i] = 0 (-nodrift,
43
+ # -case pre); by series, .inp order; None = all free
44
+ trend: bool = False # -trend (case 4): a trend in W, restricted to beta
45
+ b2_hold: tuple = () # -fixb2row: ((row, value), ...), rows of B2 held, 0-based
46
+ xlink: tuple = () # -xlink: xlink.Link's (the inputs live in Data.xl)
47
+ xsys: tuple = () # -xsys: the input series (0-based, .inp order), embedded
48
+ # as strongly exogenous: alpha_X = 0, Gamma_k[X][j] = 0
49
+ gzero: tuple = () # -gzero: ((i, j), ...) 0-based, .inp order: Gamma_k[i][j] = 0
50
+ # for every k (no feedback in the short run)
51
+ alpha: tuple = () # -alpha FILE / -weakex i: A (M rows, .inp order, sa columns)
52
+ # of alpha = A psi; () = alpha free
53
+ weakex: int = 0 # -weakex i (1-based): A is the identity without column i
54
+ b2_fix: tuple = None # -fixb2 [v]: B2 held whole, s x r values (v, or static OLS)
55
+ fixb2_given: bool = False # -fixb2 v (an a-priori value) rather than -fixb2 alone
56
+
57
+ def __post_init__(self):
58
+ if self.ma not in MA_CLASSES:
59
+ raise ValueError(f"unknown MA class {self.ma!r}")
60
+ if self.case not in (1, 2, 3):
61
+ raise ValueError("case must be 1, 2 or 3")
62
+ if self.p < 1 or self.q < 0 or not (0 <= self.r < self.M):
63
+ raise ValueError("p >= 1, q >= 0 and 0 <= r < M")
64
+
65
+ def but(self, **kw):
66
+ return replace(self, **kw)
67
+
68
+ def mu_free(self, i):
69
+ """y2mu_free (drvec.c:796): series i (0-based) carries a free drift."""
70
+ if self.case != 3:
71
+ return False
72
+ return self.drift is None or i >= len(self.drift) or bool(self.drift[i])
73
+
74
+ def b2_held(self, i):
75
+ """The value row i of B2 is held at (-fixb2row; -fixb2: its first
76
+ column's), or None when the row is estimated."""
77
+ if self.b2_fix is not None:
78
+ return self.b2_fix[i][0] if self.r > 0 else None
79
+ for row, v in self.b2_hold:
80
+ if row == i:
81
+ return v
82
+ return None
83
+
84
+ def b2_value(self, i, j):
85
+ """The held value of B2[i][j] (b2_held(i) is not None)."""
86
+ if self.b2_fix is not None:
87
+ return self.b2_fix[i][j]
88
+ return self.b2_held(i)
89
+
90
+ def b2_nheld(self):
91
+ return sum(1 for i in range(self.s) if self.b2_held(i) is not None)
92
+
93
+ @property
94
+ def s(self):
95
+ return self.M - self.r
96
+
97
+ @property
98
+ def nf(self):
99
+ return self.p - 1 if self.p > 1 else 0
100
+
101
+ def theta_class(self):
102
+ """ma_class_now (drvec.c:4818). The structured classes are written on the
103
+ r/s partition and collapse at r = 0 (marow_on needs r > 0)."""
104
+ if self.q == 0:
105
+ return "q0"
106
+ if self.ma == "marow":
107
+ return "marow" if self.r > 0 else "free"
108
+ return self.ma
109
+
110
+ def is_input(self, a):
111
+ """xs_is_int (drvec.c:846): internal row a is an -xsys input."""
112
+ return bool(self.xsys) and RowOrder(self.M, self.r).lam2inp(a) in self.xsys
113
+
114
+ def gz_held(self, a, b):
115
+ """gz_held_int (drvec.c): internal entry (a, b) is held by -gzero."""
116
+ if not self.gzero:
117
+ return False
118
+ ro = RowOrder(self.M, self.r)
119
+ return (ro.lam2inp(a), ro.lam2inp(b)) in self.gzero
120
+
121
+ def f_free(self, i, j):
122
+ """Entry (i, j), internal order, of each F_k is a parameter (drvec.c's f_free)."""
123
+ if self.diag_ar:
124
+ return i == j
125
+ return i == j or (not self.is_input(i) and not self.gz_held(i, j))
126
+
127
+ @property
128
+ def alpha_sa(self):
129
+ """The columns of A in alpha = A psi (-xsys, -alpha, -weakex at r >= 1),
130
+ or 0 (alpha free)."""
131
+ if self.r < 1:
132
+ return 0
133
+ if self.xsys:
134
+ return self.M - len(self.xsys)
135
+ if self.alpha:
136
+ return len(self.alpha[0])
137
+ return 0
138
+
139
+ def alpha_A(self):
140
+ """A (M x sa, .inp rows): -alpha's or -weakex's, or for -xsys the
141
+ identity without the inputs' columns."""
142
+ if self.alpha and not self.xsys:
143
+ return [list(row) for row in self.alpha]
144
+ sa = self.alpha_sa
145
+ A = [[0.0] * sa for _ in range(self.M)]
146
+ c = 0
147
+ for i in range(self.M):
148
+ if i not in self.xsys:
149
+ A[i][c] = 1.0
150
+ c += 1
151
+ return A
152
+
153
+ def f_nfree(self):
154
+ M = self.M
155
+ return sum(self.f_free(i, j) for i in range(M) for j in range(M))
156
+
157
+ def nsig(self):
158
+ M = self.M
159
+ return (M if self.diag_cov else M * (M + 1) // 2) - 1
160
+
161
+ def blocks(self):
162
+ """(nmean, nlam, nmid, ntail): par_blocks."""
163
+ M, r, s = self.M, self.r, self.s
164
+ nmean = (r if self.case == 2 else
165
+ (sum(self.mu_free(i) for i in range(s)) + r if self.case == 3 else 0))
166
+ nmean += r if self.trend else 0
167
+ nlam = (self.alpha_sa or M) * r
168
+ nmid = self.nf * self.f_nfree() + theta_len(self.theta_class(), self.q, M, r) + self.nsig()
169
+ from .xlink import npar as xl_npar
170
+ return nmean, nlam, nmid, (s - self.b2_nheld()) * r + xl_npar(self.xlink)
171
+
172
+ def npar(self):
173
+ return sum(self.blocks())
174
+
175
+ def head_tail(self):
176
+ """search_blocks (4838): head = mean, Lambda, F; tail = Q, B2."""
177
+ nmean, nlam, nmid, ntail = self.blocks()
178
+ return nmean + nlam + self.nf * self.f_nfree(), self.nsig() + ntail
179
+
180
+
181
+ def theta_len(cls, q, M, r):
182
+ s = M - r
183
+ return {"q0": 0, "diag": q * M, "marow": q * r * M,
184
+ "matri": q * (M * M - s * r), "free": q * M * M}[cls]
185
+
186
+
187
+ def theta_unpack(x, off, cls, q, M, r):
188
+ """theta_unpack (4862): q M x M matrices, zeros where the class has none."""
189
+ Th = [[[0.0] * M for _ in range(M)] for _ in range(q)]
190
+ idx = off
191
+ for k in range(q):
192
+ T = Th[k]
193
+ if cls == "diag":
194
+ for i in range(M):
195
+ T[i][i] = x[idx]; idx += 1
196
+ elif cls in ("marow", "matri"):
197
+ for i in range(r):
198
+ for j in range(M):
199
+ T[i][j] = x[idx]; idx += 1
200
+ if cls == "matri":
201
+ for i in range(r, M):
202
+ for j in range(r, M):
203
+ T[i][j] = x[idx]; idx += 1
204
+ elif cls == "free":
205
+ for i in range(M):
206
+ for j in range(M):
207
+ T[i][j] = x[idx]; idx += 1
208
+ return Th, idx
209
+
210
+
211
+ def theta_pack(Th, cls, q, M, r):
212
+ out = []
213
+ for k in range(q):
214
+ T = Th[k]
215
+ if cls == "diag":
216
+ out += [T[i][i] for i in range(M)]
217
+ elif cls in ("marow", "matri"):
218
+ out += [T[i][j] for i in range(r) for j in range(M)]
219
+ if cls == "matri":
220
+ out += [T[i][j] for i in range(r, M) for j in range(r, M)]
221
+ elif cls == "free":
222
+ out += [T[i][j] for i in range(M) for j in range(M)]
223
+ return out
224
+
225
+
226
+ def embed_ma(xs, spec_src, spec_dst):
227
+ """embed_ma (4900): the optimum of a poorer MA class as a point of the
228
+ richer one. Same head and tail, Theta completed with zeros."""
229
+ M, r = spec_dst.M, spec_dst.r
230
+ head, tail = spec_dst.head_tail()
231
+ cs, qs = spec_src.theta_class(), spec_src.q
232
+ cd, qd = spec_dst.theta_class(), spec_dst.q
233
+ ls, ld = theta_len(cs, qs, M, r), theta_len(cd, qd, M, r)
234
+ qm = min(qs, qd)
235
+ Th = [[[0.0] * M for _ in range(M)] for _ in range(qd)]
236
+ if qs > 0:
237
+ Tu, _ = theta_unpack(xs, head, cs, qm, M, r)
238
+ for k in range(qm):
239
+ Th[k] = Tu[k]
240
+ xd = list(xs[:head]) + theta_pack(Th, cd, qd, M, r) + list(xs[head + ls: head + ls + tail])
241
+ assert len(xd) == head + ld + tail
242
+ return xd
243
+
244
+
245
+ class RowOrder:
246
+ """inp2lam / lam2inp for (M, r), 0-based."""
247
+
248
+ def __init__(self, M, r):
249
+ self.M, self.r, self.s = M, r, M - r
250
+
251
+ def inp2lam(self, i):
252
+ return self.r + i if i < self.s else i - self.s
253
+
254
+ def lam2inp(self, a):
255
+ return self.s + a if a < self.r else a - self.r
256
+
257
+
258
+ def slot_labels(spec, names, innames=None):
259
+ """One label per slot of x, in the vector's order, with the C's wording
260
+ (report_fit 8340-8550): what the reader sees, in the .inp's names.
261
+
262
+ Returns a list of (label, kind, sign): `sign = -1` for Lambda, which is
263
+ reported as alpha = -Lambda."""
264
+ M, r, s, q = spec.M, spec.r, spec.s, spec.q
265
+ ro = RowOrder(M, r)
266
+ nm = lambda a: names[ro.lam2inp(a)] # noqa: E731 (internal row -> name)
267
+ out = []
268
+ if spec.case == 2:
269
+ out += [(f"E[ec{j + 1}]", "mean", 1) for j in range(r)]
270
+ elif spec.case == 3:
271
+ out += [(f"E[D.{names[i]}]", "mean", 1) for i in range(s) if spec.mu_free(i)]
272
+ out += [(f"E[ec{j + 1}]", "mean", 1) for j in range(r)]
273
+ if spec.trend:
274
+ out += [(f"trend[ec{j + 1}]", "trend", 1) for j in range(r)]
275
+ if spec.alpha_sa:
276
+ out += [(f"psi[{a + 1} <- ec{j + 1}]", "psi", 1)
277
+ for a in range(spec.alpha_sa) for j in range(r)]
278
+ else:
279
+ for a in range(M):
280
+ for j in range(r):
281
+ out.append((f"D.{nm(a)} <- ec{j + 1}", "alpha", -1))
282
+ for k in range(spec.nf):
283
+ for a in range(M):
284
+ for b in range(M):
285
+ if spec.f_free(a, b):
286
+ out.append((f"D.{nm(a)} <- D.{nm(b)}(-{k + 1})", "gamma", 1))
287
+ cls = spec.theta_class()
288
+ pattern = []
289
+ for k in range(q):
290
+ if cls == "diag":
291
+ pattern += [(k, a, a) for a in range(M)]
292
+ elif cls in ("marow", "matri"):
293
+ pattern += [(k, a, b) for a in range(r) for b in range(M)]
294
+ if cls == "matri":
295
+ pattern += [(k, a, b) for a in range(r, M) for b in range(r, M)]
296
+ elif cls == "free":
297
+ pattern += [(k, a, b) for a in range(M) for b in range(M)]
298
+ for k, a, b in pattern:
299
+ out.append((f"D.{nm(a)} <- A.{nm(b)}(-{k + 1})", "theta", 1))
300
+ out += [(f"var {nm(a)}", "q", 1) for a in range(1, M)]
301
+ if not spec.diag_cov:
302
+ out += [(f"cov {nm(a)}, {nm(b)}", "q", 1) for a in range(1, M) for b in range(a)]
303
+ for j in range(r):
304
+ for i in range(s):
305
+ if spec.b2_held(i) is None:
306
+ out.append((f"{names[i]} in ec{j + 1}", "beta", 1))
307
+ if spec.xlink:
308
+ from .xlink import labels
309
+ out += labels(spec.xlink, names, innames or [f"x{k + 1}" for k in range(8)])
310
+ assert len(out) == spec.npar()
311
+ return out