pi-mega-compact 0.20.0 → 0.20.1
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.
- package/dist/config/vector-cortex.js +12 -0
- package/dist/config.js +1 -1
- package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +1 -0
- package/dist/extensions/dashboard-server/routes-vector-cortex-residual.js +51 -0
- package/dist/extensions/dashboard-server/routes-vector-cortex.js +1 -0
- package/dist/extensions/dashboard-server/routes.js +1 -1
- package/dist/extensions/dashboard-server/server.js +3 -1
- package/dist/src/config/vector-cortex.js +12 -0
- package/dist/src/config.js +1 -1
- package/dist/src/vector-cortex/residual/codec.js +224 -0
- package/dist/src/vector-cortex/residual/dct.js +158 -0
- package/dist/src/vector-cortex/residual/fixture-payload.js +77 -0
- package/dist/src/vector-cortex/residual/gf256.js +182 -0
- package/dist/src/vector-cortex/residual/parity.js +245 -0
- package/dist/src/vector-cortex/residual/quantize.js +200 -0
- package/dist/src/vector-cortex/residual/stream.js +124 -0
- package/dist/src/vector-cortex/residual/types.js +55 -0
- package/dist/vector-cortex/residual/codec.js +224 -0
- package/dist/vector-cortex/residual/dct.js +158 -0
- package/dist/vector-cortex/residual/fixture-payload.js +77 -0
- package/dist/vector-cortex/residual/gf256.js +182 -0
- package/dist/vector-cortex/residual/parity.js +245 -0
- package/dist/vector-cortex/residual/quantize.js +200 -0
- package/dist/vector-cortex/residual/stream.js +124 -0
- package/dist/vector-cortex/residual/types.js +55 -0
- package/extensions/dashboard-server/api-contracts/vector-cortex.ts +29 -0
- package/extensions/dashboard-server/routes-rag-settings-helpers.ts +6 -0
- package/extensions/dashboard-server/routes-vector-cortex-residual.ts +60 -0
- package/extensions/dashboard-server/routes-vector-cortex.ts +1 -0
- package/extensions/dashboard-server/routes.ts +1 -0
- package/extensions/dashboard-server/server.ts +2 -0
- package/package.json +1 -1
- package/src/config/vector-cortex.ts +13 -0
- package/src/config.ts +1 -0
- package/src/vector-cortex/residual/codec.ts +292 -0
- package/src/vector-cortex/residual/dct.ts +166 -0
- package/src/vector-cortex/residual/fixture-payload.ts +90 -0
- package/src/vector-cortex/residual/gf256.ts +196 -0
- package/src/vector-cortex/residual/parity.ts +283 -0
- package/src/vector-cortex/residual/quantize.ts +230 -0
- package/src/vector-cortex/residual/stream.ts +135 -0
- package/src/vector-cortex/residual/types.ts +236 -0
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* vector-cortex/residual/dct.ts — orthonormal DCT-II basis V1 (VC4B).
|
|
3
|
+
*
|
|
4
|
+
* Basis V1 is the orthonormal DCT-II matrix generated ANALYTICALLY and never
|
|
5
|
+
* learned or stored (RESIDUAL_CODEC §byte scope):
|
|
6
|
+
*
|
|
7
|
+
* alpha(0) = sqrt(1/n), alpha(k>0) = sqrt(2/n)
|
|
8
|
+
* C[k][i] = alpha(k) * cos(pi * (2i + 1) * k / (2n))
|
|
9
|
+
*
|
|
10
|
+
* Forward coefficients are the dot product with each basis row (the orthonormal
|
|
11
|
+
* least-squares solve); the inverse is the transpose applied to the coefficient
|
|
12
|
+
* vector. Byte mapping is `x = (byte - 127.5) / 127.5`; the inverse maps back
|
|
13
|
+
* with round-to-nearest-even and clamps to 0..255.
|
|
14
|
+
*
|
|
15
|
+
* The full 4096x4096 matrix is ~134 MB of float64, so it is NEVER materialized.
|
|
16
|
+
* Instead the cosine argument `pi*(2i+1)*k/(2n)` is reduced modulo `2n` against
|
|
17
|
+
* a precomputed half-period table of length `2n` — this is EXACTLY the same set
|
|
18
|
+
* of cosine values the matrix would hold (cos is sampled only at the `2n`
|
|
19
|
+
* distinct arguments `pi*j/(2n)`, j = 0..2n-1), so the transform is bit-stable
|
|
20
|
+
* and table-generation is O(n) rather than O(n^2).
|
|
21
|
+
*
|
|
22
|
+
* Pure numeric transform: no storage, no console, no network (PREVENT-PI-004 /
|
|
23
|
+
* PREVENT-011).
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { RESIDUAL_BLOCK_SIZE } from "./types.js";
|
|
27
|
+
|
|
28
|
+
/** Byte-to-signal mapping midpoint / half-range (RESIDUAL_CODEC §transform). */
|
|
29
|
+
const BYTE_MIDPOINT = 127.5;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Cosine table cache keyed by block length. `table[j] = cos(pi * j / (2n))` for
|
|
33
|
+
* j = 0..2n-1; every DCT argument `pi*(2i+1)*k/(2n)` reduces to one of these
|
|
34
|
+
* entries (with a sign) because cos has period `2*pi` = index period `4n`.
|
|
35
|
+
*/
|
|
36
|
+
const cosTables = new Map<number, Float64Array>();
|
|
37
|
+
|
|
38
|
+
/** Build (or fetch) the `4n`-entry cosine table for block length `n`. */
|
|
39
|
+
function cosTable(n: number): Float64Array {
|
|
40
|
+
const cached = cosTables.get(n);
|
|
41
|
+
if (cached) return cached;
|
|
42
|
+
const period = 4 * n;
|
|
43
|
+
const table = new Float64Array(period);
|
|
44
|
+
for (let j = 0; j < period; j++) {
|
|
45
|
+
table[j] = Math.cos((Math.PI * j) / (2 * n));
|
|
46
|
+
}
|
|
47
|
+
cosTables.set(n, table);
|
|
48
|
+
return table;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Orthonormal DCT-II row scale: alpha(0)=sqrt(1/n), else sqrt(2/n). */
|
|
52
|
+
export function alpha(k: number, n: number): number {
|
|
53
|
+
return k === 0 ? Math.sqrt(1 / n) : Math.sqrt(2 / n);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Map a padded byte block to the signal domain: `x = (byte - 127.5) / 127.5`.
|
|
58
|
+
* The input must be exactly `n` bytes (the caller zero-pads the final block).
|
|
59
|
+
*/
|
|
60
|
+
export function bytesToSignal(block: Uint8Array): Float64Array {
|
|
61
|
+
const out = new Float64Array(block.length);
|
|
62
|
+
for (let i = 0; i < block.length; i++) {
|
|
63
|
+
out[i] = (block[i]! - BYTE_MIDPOINT) / BYTE_MIDPOINT;
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Map a reconstructed signal back to bytes: invert the affine map, round to
|
|
70
|
+
* nearest with ties-to-even, and clamp to 0..255 (RESIDUAL_CODEC §transform).
|
|
71
|
+
*/
|
|
72
|
+
export function signalToBytes(signal: Float64Array): Uint8Array {
|
|
73
|
+
const out = new Uint8Array(signal.length);
|
|
74
|
+
for (let i = 0; i < signal.length; i++) {
|
|
75
|
+
const v = signal[i]! * BYTE_MIDPOINT + BYTE_MIDPOINT;
|
|
76
|
+
const r = roundHalfToEven(v);
|
|
77
|
+
out[i] = r < 0 ? 0 : r > 255 ? 255 : r;
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Round to nearest, ties to even (banker's rounding). `Math.round` rounds ties
|
|
84
|
+
* toward +Infinity, which is NOT the rule RESIDUAL_CODEC mandates.
|
|
85
|
+
*/
|
|
86
|
+
export function roundHalfToEven(v: number): number {
|
|
87
|
+
const floor = Math.floor(v);
|
|
88
|
+
const diff = v - floor;
|
|
89
|
+
if (diff > 0.5) return floor + 1;
|
|
90
|
+
if (diff < 0.5) return floor;
|
|
91
|
+
// Exact tie: pick the even neighbour.
|
|
92
|
+
return floor % 2 === 0 ? floor : floor + 1;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Forward orthonormal DCT-II over one block of length `n` (default 4096).
|
|
97
|
+
* `coefficients[k] = alpha(k) * sum_i x[i] * cos(pi*(2i+1)*k/(2n))`, emitted in
|
|
98
|
+
* ascending frequency order `k = 0..n-1` (the exact RESIDUAL_CODEC coefficient
|
|
99
|
+
* order).
|
|
100
|
+
*/
|
|
101
|
+
export function forwardDct(signal: Float64Array): Float64Array {
|
|
102
|
+
const n = signal.length;
|
|
103
|
+
const table = cosTable(n);
|
|
104
|
+
const period = 4 * n;
|
|
105
|
+
const out = new Float64Array(n);
|
|
106
|
+
for (let k = 0; k < n; k++) {
|
|
107
|
+
let sum = 0;
|
|
108
|
+
// Argument index advances by 2k each step, starting at k (i=0 gives
|
|
109
|
+
// (2*0+1)*k = k). Reduce modulo the 4n-entry period.
|
|
110
|
+
let idx = k % period;
|
|
111
|
+
const step = (2 * k) % period;
|
|
112
|
+
for (let i = 0; i < n; i++) {
|
|
113
|
+
sum += signal[i]! * table[idx]!;
|
|
114
|
+
idx += step;
|
|
115
|
+
if (idx >= period) idx -= period;
|
|
116
|
+
}
|
|
117
|
+
out[k] = alpha(k, n) * sum;
|
|
118
|
+
}
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Inverse orthonormal DCT (the transpose of the forward matrix):
|
|
124
|
+
* `x[i] = sum_k alpha(k) * c[k] * cos(pi*(2i+1)*k/(2n))`.
|
|
125
|
+
*/
|
|
126
|
+
export function inverseDct(coefficients: Float64Array): Float64Array {
|
|
127
|
+
const n = coefficients.length;
|
|
128
|
+
const table = cosTable(n);
|
|
129
|
+
const period = 4 * n;
|
|
130
|
+
// Pre-scale each coefficient by its row alpha so the inner loop is a plain
|
|
131
|
+
// dot product (identical arithmetic to scaling inside the loop for k, and it
|
|
132
|
+
// keeps the per-i accumulation order stable).
|
|
133
|
+
const scaled = new Float64Array(n);
|
|
134
|
+
for (let k = 0; k < n; k++) scaled[k] = alpha(k, n) * coefficients[k]!;
|
|
135
|
+
const out = new Float64Array(n);
|
|
136
|
+
for (let i = 0; i < n; i++) {
|
|
137
|
+
let sum = 0;
|
|
138
|
+
const step = (2 * i + 1) % period;
|
|
139
|
+
let idx = 0;
|
|
140
|
+
for (let k = 0; k < n; k++) {
|
|
141
|
+
sum += scaled[k]! * table[idx]!;
|
|
142
|
+
idx += step;
|
|
143
|
+
if (idx >= period) idx -= period;
|
|
144
|
+
}
|
|
145
|
+
out[i] = sum;
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Split a payload into fixed 4096-byte blocks, zero-padding ONLY the final
|
|
152
|
+
* block. The original length is retained by the caller (the header) so the
|
|
153
|
+
* padding is dropped on decode.
|
|
154
|
+
*/
|
|
155
|
+
export function splitBlocks(
|
|
156
|
+
payload: Uint8Array,
|
|
157
|
+
blockSize: number = RESIDUAL_BLOCK_SIZE,
|
|
158
|
+
): Uint8Array[] {
|
|
159
|
+
const blocks: Uint8Array[] = [];
|
|
160
|
+
for (let off = 0; off < payload.length; off += blockSize) {
|
|
161
|
+
const block = new Uint8Array(blockSize);
|
|
162
|
+
block.set(payload.subarray(off, Math.min(off + blockSize, payload.length)));
|
|
163
|
+
blocks.push(block);
|
|
164
|
+
}
|
|
165
|
+
return blocks;
|
|
166
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* vector-cortex/residual/fixture-payload.ts — deterministic payload
|
|
3
|
+
* materialization for the VC4B conformance corpus.
|
|
4
|
+
*
|
|
5
|
+
* The residual fixtures describe their payloads GENERATIVELY (`kind` + `length`
|
|
6
|
+
* + `seed`) rather than embedding megabytes of base64, so this module is the
|
|
7
|
+
* single normative generator both the fixture producer and the acceptance test
|
|
8
|
+
* agree on. Every generator is pure and deterministic — the same descriptor
|
|
9
|
+
* always yields byte-identical output, which is what makes the committed
|
|
10
|
+
* fixtures meaningful.
|
|
11
|
+
*
|
|
12
|
+
* Pure byte generation: no storage, no console, no network (PREVENT-PI-004 /
|
|
13
|
+
* PREVENT-011).
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** A generative payload descriptor as carried by a residual fixture. */
|
|
17
|
+
export interface PayloadDescriptor {
|
|
18
|
+
readonly kind: string;
|
|
19
|
+
readonly length?: number;
|
|
20
|
+
readonly seed?: number;
|
|
21
|
+
readonly value?: number;
|
|
22
|
+
readonly outlierOffset?: number;
|
|
23
|
+
readonly bytesBase64?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Linear congruential generator (numerical-recipes constants), deterministic. */
|
|
27
|
+
function lcgBytes(length: number, seed: number): Uint8Array {
|
|
28
|
+
const out = new Uint8Array(length);
|
|
29
|
+
let state = seed >>> 0;
|
|
30
|
+
for (let i = 0; i < length; i++) {
|
|
31
|
+
state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
|
|
32
|
+
out[i] = (state >>> 24) & 0xff;
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Materialize a fixture payload descriptor into exact bytes.
|
|
39
|
+
*
|
|
40
|
+
* empty zero bytes
|
|
41
|
+
* zeros `length` 0x00 bytes
|
|
42
|
+
* constant `length` copies of `value`
|
|
43
|
+
* sequence `i % 256`
|
|
44
|
+
* lcg deterministic pseudorandom stream from `seed`
|
|
45
|
+
* text repeating printable ASCII (valid UTF-8)
|
|
46
|
+
* invalid-utf8 a stream containing lone continuation/overlong bytes
|
|
47
|
+
* dc-outlier all 0xff except one 0x00 at `outlierOffset` (forces the exact
|
|
48
|
+
* correction stream: a DC-dominant block whose coarse scale
|
|
49
|
+
* cannot reproduce the outlier's neighbourhood)
|
|
50
|
+
* alternating 0x00/0xff alternation (maximum Nyquist energy)
|
|
51
|
+
*/
|
|
52
|
+
export function materializePayload(d: PayloadDescriptor): Uint8Array {
|
|
53
|
+
const length = d.length ?? 0;
|
|
54
|
+
switch (d.kind) {
|
|
55
|
+
case "empty":
|
|
56
|
+
return new Uint8Array(0);
|
|
57
|
+
case "zeros":
|
|
58
|
+
return new Uint8Array(length);
|
|
59
|
+
case "constant":
|
|
60
|
+
return new Uint8Array(length).fill((d.value ?? 0) & 0xff);
|
|
61
|
+
case "sequence":
|
|
62
|
+
return Uint8Array.from({ length }, (_v, i) => i % 256);
|
|
63
|
+
case "lcg":
|
|
64
|
+
return lcgBytes(length, d.seed ?? 1);
|
|
65
|
+
case "text": {
|
|
66
|
+
const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 ";
|
|
67
|
+
return Uint8Array.from({ length }, (_v, i) =>
|
|
68
|
+
alphabet.charCodeAt(i % alphabet.length),
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
case "invalid-utf8": {
|
|
72
|
+
// Deliberately invalid: lone 0x80 continuation, 0xff (never valid), and
|
|
73
|
+
// the overlong 0xc0 0xaf encoding of "/". Never normalized by the codec.
|
|
74
|
+
const pattern = [0xff, 0x80, 0xc0, 0xaf, 0x00, 0xfe];
|
|
75
|
+
return Uint8Array.from({ length }, (_v, i) => pattern[i % pattern.length]!);
|
|
76
|
+
}
|
|
77
|
+
case "dc-outlier": {
|
|
78
|
+
const out = new Uint8Array(length).fill(255);
|
|
79
|
+
const at = d.outlierOffset ?? 0;
|
|
80
|
+
if (at < length) out[at] = 0;
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
case "alternating":
|
|
84
|
+
return Uint8Array.from({ length }, (_v, i) => (i % 2 === 0 ? 0 : 255));
|
|
85
|
+
case "literal":
|
|
86
|
+
return new Uint8Array(Buffer.from(d.bytesBase64 ?? "", "base64"));
|
|
87
|
+
default:
|
|
88
|
+
throw new Error(`unknown residual payload kind: ${d.kind}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* vector-cortex/residual/gf256.ts — GF(2^8) field arithmetic and matrix algebra
|
|
3
|
+
* for the VC4B Reed–Solomon erasure parity.
|
|
4
|
+
*
|
|
5
|
+
* Field: GF(2^8) with primitive polynomial `0x11d`, elements represented as
|
|
6
|
+
* polynomial-basis bytes (RESIDUAL_CODEC §erasure parity). Log/antilog tables
|
|
7
|
+
* are built once from generator 2 and drive constant-time multiply/divide.
|
|
8
|
+
*
|
|
9
|
+
* Matrix inversion and recovery use DETERMINISTIC left-to-right pivot search and
|
|
10
|
+
* GF Gaussian elimination — no randomness, no iteration-order dependence, so
|
|
11
|
+
* every implementation reaches byte-identical results.
|
|
12
|
+
*
|
|
13
|
+
* Pure arithmetic: no storage, no console, no network (PREVENT-PI-004 /
|
|
14
|
+
* PREVENT-011).
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { GF_PRIMITIVE_POLYNOMIAL } from "./types.js";
|
|
18
|
+
|
|
19
|
+
const FIELD_SIZE = 256;
|
|
20
|
+
|
|
21
|
+
/** `EXP[i] = 2^i` in GF(2^8) (doubled length so multiply needs no modulo). */
|
|
22
|
+
const EXP = new Uint8Array(FIELD_SIZE * 2);
|
|
23
|
+
/** `LOG[x] = i` such that `2^i = x`; `LOG[0]` is unused (0 has no logarithm). */
|
|
24
|
+
const LOG = new Uint8Array(FIELD_SIZE);
|
|
25
|
+
|
|
26
|
+
(function buildTables(): void {
|
|
27
|
+
let x = 1;
|
|
28
|
+
for (let i = 0; i < FIELD_SIZE - 1; i++) {
|
|
29
|
+
EXP[i] = x;
|
|
30
|
+
LOG[x] = i;
|
|
31
|
+
x <<= 1;
|
|
32
|
+
if (x & 0x100) x ^= GF_PRIMITIVE_POLYNOMIAL;
|
|
33
|
+
}
|
|
34
|
+
// Mirror the cycle so `EXP[a + b]` is valid for a,b <= 254 without a modulo.
|
|
35
|
+
for (let i = FIELD_SIZE - 1; i < EXP.length; i++) {
|
|
36
|
+
EXP[i] = EXP[i - (FIELD_SIZE - 1)]!;
|
|
37
|
+
}
|
|
38
|
+
})();
|
|
39
|
+
|
|
40
|
+
/** GF(2^8) addition (and subtraction) is XOR. */
|
|
41
|
+
export function gfAdd(a: number, b: number): number {
|
|
42
|
+
return (a ^ b) & 0xff;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** GF(2^8) multiplication via log/antilog tables. */
|
|
46
|
+
export function gfMul(a: number, b: number): number {
|
|
47
|
+
if (a === 0 || b === 0) return 0;
|
|
48
|
+
return EXP[LOG[a]! + LOG[b]!]!;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** GF(2^8) division; dividing by zero is a programming error and throws. */
|
|
52
|
+
export function gfDiv(a: number, b: number): number {
|
|
53
|
+
if (b === 0) throw new RangeError("gf256: division by zero");
|
|
54
|
+
if (a === 0) return 0;
|
|
55
|
+
return EXP[LOG[a]! + (FIELD_SIZE - 1) - LOG[b]!]!;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Multiplicative inverse of a non-zero field element. */
|
|
59
|
+
export function gfInv(a: number): number {
|
|
60
|
+
if (a === 0) throw new RangeError("gf256: zero has no inverse");
|
|
61
|
+
return EXP[FIELD_SIZE - 1 - LOG[a]!]!;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** `base^exponent` in GF(2^8) (exponent is a non-negative integer). */
|
|
65
|
+
export function gfPow(base: number, exponent: number): number {
|
|
66
|
+
if (exponent === 0) return 1;
|
|
67
|
+
if (base === 0) return 0;
|
|
68
|
+
return EXP[(LOG[base]! * exponent) % (FIELD_SIZE - 1)]!;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** A dense row-major GF(2^8) matrix. */
|
|
72
|
+
export interface GfMatrix {
|
|
73
|
+
readonly rows: number;
|
|
74
|
+
readonly cols: number;
|
|
75
|
+
readonly data: Uint8Array;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Allocate a zero matrix. */
|
|
79
|
+
export function gfMatrix(rows: number, cols: number): GfMatrix {
|
|
80
|
+
return { rows, cols, data: new Uint8Array(rows * cols) };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Read `m[r][c]`. */
|
|
84
|
+
export function gfAt(m: GfMatrix, r: number, c: number): number {
|
|
85
|
+
return m.data[r * m.cols + c]!;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Write `m[r][c] = v`. */
|
|
89
|
+
export function gfSet(m: GfMatrix, r: number, c: number, v: number): void {
|
|
90
|
+
m.data[r * m.cols + c] = v;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Build the `rows x cols` Vandermonde matrix `V[r][c] = alpha_r^c` with the
|
|
95
|
+
* distinct evaluation points `alpha_r = r + 1` (RESIDUAL_CODEC: rows r=0..8,
|
|
96
|
+
* columns c=0..5).
|
|
97
|
+
*/
|
|
98
|
+
export function vandermonde(rows: number, cols: number): GfMatrix {
|
|
99
|
+
const m = gfMatrix(rows, cols);
|
|
100
|
+
for (let r = 0; r < rows; r++) {
|
|
101
|
+
for (let c = 0; c < cols; c++) {
|
|
102
|
+
gfSet(m, r, c, gfPow((r + 1) & 0xff, c));
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return m;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Matrix product `a x b` over GF(2^8). */
|
|
109
|
+
export function gfMatMul(a: GfMatrix, b: GfMatrix): GfMatrix {
|
|
110
|
+
const out = gfMatrix(a.rows, b.cols);
|
|
111
|
+
for (let r = 0; r < a.rows; r++) {
|
|
112
|
+
for (let c = 0; c < b.cols; c++) {
|
|
113
|
+
let acc = 0;
|
|
114
|
+
for (let i = 0; i < a.cols; i++) {
|
|
115
|
+
acc ^= gfMul(gfAt(a, r, i), gfAt(b, i, c));
|
|
116
|
+
}
|
|
117
|
+
gfSet(out, r, c, acc);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Extract the contiguous row range `[start, start+count)` of a matrix. */
|
|
124
|
+
export function gfSubRows(m: GfMatrix, start: number, count: number): GfMatrix {
|
|
125
|
+
const out = gfMatrix(count, m.cols);
|
|
126
|
+
out.data.set(m.data.subarray(start * m.cols, (start + count) * m.cols));
|
|
127
|
+
return out;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Gather the given row indices (in order) into a new matrix. */
|
|
131
|
+
export function gfPickRows(m: GfMatrix, indices: readonly number[]): GfMatrix {
|
|
132
|
+
const out = gfMatrix(indices.length, m.cols);
|
|
133
|
+
indices.forEach((src, dest) => {
|
|
134
|
+
out.data.set(m.data.subarray(src * m.cols, (src + 1) * m.cols), dest * m.cols);
|
|
135
|
+
});
|
|
136
|
+
return out;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Invert a square GF(2^8) matrix by Gauss–Jordan elimination with a
|
|
141
|
+
* DETERMINISTIC left-to-right pivot search (the first row at or below the
|
|
142
|
+
* current column with a non-zero entry). Returns null when the matrix is
|
|
143
|
+
* singular.
|
|
144
|
+
*/
|
|
145
|
+
export function gfInvert(m: GfMatrix): GfMatrix | null {
|
|
146
|
+
if (m.rows !== m.cols) return null;
|
|
147
|
+
const n = m.rows;
|
|
148
|
+
const work = gfMatrix(n, n);
|
|
149
|
+
work.data.set(m.data);
|
|
150
|
+
const inv = gfMatrix(n, n);
|
|
151
|
+
for (let i = 0; i < n; i++) gfSet(inv, i, i, 1);
|
|
152
|
+
|
|
153
|
+
const swapRows = (mat: GfMatrix, a: number, b: number): void => {
|
|
154
|
+
if (a === b) return;
|
|
155
|
+
for (let c = 0; c < mat.cols; c++) {
|
|
156
|
+
const t = gfAt(mat, a, c);
|
|
157
|
+
gfSet(mat, a, c, gfAt(mat, b, c));
|
|
158
|
+
gfSet(mat, b, c, t);
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
for (let col = 0; col < n; col++) {
|
|
163
|
+
// Deterministic pivot: the lowest-index row >= col with a non-zero entry.
|
|
164
|
+
let pivot = -1;
|
|
165
|
+
for (let r = col; r < n; r++) {
|
|
166
|
+
if (gfAt(work, r, col) !== 0) {
|
|
167
|
+
pivot = r;
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (pivot === -1) return null; // singular
|
|
172
|
+
swapRows(work, col, pivot);
|
|
173
|
+
swapRows(inv, col, pivot);
|
|
174
|
+
|
|
175
|
+
// Normalize the pivot row.
|
|
176
|
+
const pivotValue = gfAt(work, col, col);
|
|
177
|
+
if (pivotValue !== 1) {
|
|
178
|
+
const scale = gfInv(pivotValue);
|
|
179
|
+
for (let c = 0; c < n; c++) {
|
|
180
|
+
gfSet(work, col, c, gfMul(gfAt(work, col, c), scale));
|
|
181
|
+
gfSet(inv, col, c, gfMul(gfAt(inv, col, c), scale));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
// Eliminate the column from every other row.
|
|
185
|
+
for (let r = 0; r < n; r++) {
|
|
186
|
+
if (r === col) continue;
|
|
187
|
+
const factor = gfAt(work, r, col);
|
|
188
|
+
if (factor === 0) continue;
|
|
189
|
+
for (let c = 0; c < n; c++) {
|
|
190
|
+
gfSet(work, r, c, gfAdd(gfAt(work, r, c), gfMul(factor, gfAt(work, col, c))));
|
|
191
|
+
gfSet(inv, r, c, gfAdd(gfAt(inv, r, c), gfMul(factor, gfAt(inv, col, c))));
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return inv;
|
|
196
|
+
}
|