bireactive 0.3.1 → 0.3.2

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.
Files changed (89) hide show
  1. package/README.md +14 -7
  2. package/dist/core/_counts.js +5 -12
  3. package/dist/core/cell.d.ts +3 -3
  4. package/dist/core/cell.js +6 -7
  5. package/dist/core/derived-geometry.js +4 -7
  6. package/dist/core/index.d.ts +3 -1
  7. package/dist/core/index.js +3 -1
  8. package/dist/core/lenses/aggregates.d.ts +42 -52
  9. package/dist/core/lenses/aggregates.js +225 -116
  10. package/dist/core/lenses/geometry.d.ts +22 -4
  11. package/dist/core/lenses/geometry.js +59 -27
  12. package/dist/core/lenses/index.d.ts +5 -6
  13. package/dist/core/lenses/index.js +5 -6
  14. package/dist/core/lenses/memory.js +4 -17
  15. package/dist/core/lenses/numerical.d.ts +100 -0
  16. package/dist/core/lenses/{typed-factor.js → numerical.js} +136 -34
  17. package/dist/core/lenses/point-cloud.d.ts +67 -0
  18. package/dist/core/lenses/{closed-form-policies.js → point-cloud.js} +218 -81
  19. package/dist/core/lenses/snap.d.ts +1 -1
  20. package/dist/core/lenses/snap.js +3 -10
  21. package/dist/core/lenses/text.d.ts +40 -0
  22. package/dist/core/lenses/text.js +202 -0
  23. package/dist/core/lifecycle.js +3 -6
  24. package/dist/core/linalg.js +5 -11
  25. package/dist/core/optic.js +10 -15
  26. package/dist/core/optics.js +4 -8
  27. package/dist/core/store.d.ts +1 -2
  28. package/dist/core/store.js +7 -15
  29. package/dist/core/traits.d.ts +4 -7
  30. package/dist/core/traits.js +8 -12
  31. package/dist/core/values/anchor.js +0 -4
  32. package/dist/core/values/arr.d.ts +110 -0
  33. package/dist/core/values/arr.js +336 -0
  34. package/dist/core/values/audio.d.ts +8 -9
  35. package/dist/core/values/audio.js +7 -23
  36. package/dist/core/values/bool.d.ts +11 -11
  37. package/dist/core/values/bool.js +12 -22
  38. package/dist/core/values/box.d.ts +15 -20
  39. package/dist/core/values/box.js +20 -33
  40. package/dist/core/values/canvas.d.ts +18 -25
  41. package/dist/core/values/canvas.js +17 -48
  42. package/dist/core/values/color.d.ts +5 -7
  43. package/dist/core/values/color.js +5 -11
  44. package/dist/core/values/field.d.ts +6 -7
  45. package/dist/core/values/field.js +10 -35
  46. package/dist/core/values/flags.d.ts +1 -2
  47. package/dist/core/values/flags.js +1 -17
  48. package/dist/core/values/gpu.d.ts +6 -10
  49. package/dist/core/values/gpu.js +8 -22
  50. package/dist/core/values/matrix.d.ts +2 -4
  51. package/dist/core/values/matrix.js +2 -12
  52. package/dist/core/values/num.d.ts +19 -28
  53. package/dist/core/values/num.js +23 -41
  54. package/dist/core/values/pose.d.ts +2 -4
  55. package/dist/core/values/pose.js +3 -12
  56. package/dist/core/values/range.d.ts +18 -26
  57. package/dist/core/values/range.js +22 -39
  58. package/dist/core/values/reg/ambiguity.d.ts +8 -0
  59. package/dist/core/values/reg/ambiguity.js +131 -0
  60. package/dist/core/values/reg/engine.d.ts +91 -0
  61. package/dist/core/values/reg/engine.js +373 -0
  62. package/dist/core/values/reg/nfa.d.ts +42 -0
  63. package/dist/core/values/reg/nfa.js +391 -0
  64. package/dist/core/values/reg/regex.d.ts +7 -0
  65. package/dist/core/values/reg/regex.js +318 -0
  66. package/dist/core/values/reg/types.d.ts +60 -0
  67. package/dist/core/values/reg/types.js +3 -0
  68. package/dist/core/values/reg.d.ts +250 -0
  69. package/dist/core/values/reg.js +649 -0
  70. package/dist/core/values/str.d.ts +16 -60
  71. package/dist/core/values/str.js +133 -315
  72. package/dist/core/values/template.js +1 -24
  73. package/dist/core/values/transform.d.ts +3 -5
  74. package/dist/core/values/transform.js +3 -12
  75. package/dist/core/values/tri.d.ts +9 -10
  76. package/dist/core/values/tri.js +9 -15
  77. package/dist/core/values/vec.d.ts +9 -24
  78. package/dist/core/values/vec.js +9 -64
  79. package/dist/index.d.ts +0 -11
  80. package/dist/index.js +1 -11
  81. package/package.json +6 -7
  82. package/dist/coll.d.ts +0 -74
  83. package/dist/coll.js +0 -210
  84. package/dist/core/lenses/closed-form-policies.d.ts +0 -57
  85. package/dist/core/lenses/decompositions.d.ts +0 -14
  86. package/dist/core/lenses/decompositions.js +0 -224
  87. package/dist/core/lenses/domain-aggregates.d.ts +0 -42
  88. package/dist/core/lenses/domain-aggregates.js +0 -245
  89. package/dist/core/lenses/typed-factor.d.ts +0 -40
@@ -1,245 +0,0 @@
1
- // domain-aggregates.ts — closed-form lenses beyond point clouds.
2
- //
3
- // The group-action patterns from `closed-form-policies.ts`, applied to:
4
- // (1) Generic Linear/Metric-trait aggregates — `mean`, `spread`,
5
- // `palette` work for colors, poses, ranges, boxes for free.
6
- // (2) Bezier gestalt handles ({start, end, startTangent, endTangent}).
7
- // (3) Time-series ({mean, slope}) over (i, value) samples.
8
- // All exact, idempotent, cross-channel invariant by construction.
9
- import { Num, reader, SKIP, Vec, } from "../index.js";
10
- import { remember } from "./memory.js";
11
- // Generic Linear-trait aggregates.
12
- //
13
- // Ergonomic entry points that infer the value class from the first input
14
- // (`mean(colors)` works for any `linear` class). Same engine, no new
15
- // infrastructure.
16
- /** Equal-weight mean (writable of `inputs[0]`'s class); writes distribute
17
- * the delta evenly. Class inferred from the first input; needs `linear`. */
18
- // biome-ignore lint/suspicious/noExplicitAny: variance escape
19
- export function mean(inputs) {
20
- if (inputs.length === 0)
21
- throw new Error("mean: need ≥ 1 input");
22
- // biome-ignore lint/suspicious/noExplicitAny: dynamic class lookup
23
- const Cls = inputs[0].constructor;
24
- // biome-ignore lint/suspicious/noExplicitAny: dynamic trait lookup
25
- const lin = Cls.traits?.linear;
26
- if (!lin)
27
- throw new Error(`mean: ${Cls.name ?? "?"} has no traits.linear`);
28
- const n = inputs.length;
29
- const inv = 1 / n;
30
- // biome-ignore lint/suspicious/noExplicitAny: variance escape on Cls.lens
31
- return Cls.lens(inputs,
32
- // biome-ignore lint/suspicious/noExplicitAny: variance escape
33
- (vals) => {
34
- let acc = vals[0];
35
- for (let i = 1; i < n; i++)
36
- acc = lin.add(acc, vals[i]);
37
- return lin.scale(acc, inv);
38
- },
39
- // biome-ignore lint/suspicious/noExplicitAny: variance escape
40
- (target, vals) => {
41
- let cur = vals[0];
42
- for (let i = 1; i < n; i++)
43
- cur = lin.add(cur, vals[i]);
44
- cur = lin.scale(cur, inv);
45
- const delta = lin.sub(target, cur);
46
- const out = new Array(n);
47
- for (let i = 0; i < n; i++)
48
- out[i] = lin.add(vals[i], delta);
49
- return out;
50
- });
51
- }
52
- // Weighted blend (the mix simplex).
53
- //
54
- // `mix` is `mean` with the uniform-weight assumption lifted: the read
55
- // is the normalized weighted sum `Σ wᵢ·aᵢ`, the write is the minimum-norm
56
- // delta `daᵢ = wᵢ·δ / Σwⱼ²` (the pseudoinverse of `wᵀ·da = δ`), so a
57
- // zero-weight branch is left untouched. Weights are read-only controls —
58
- // the bwd never writes them, keeping the blend fixed while the delta flows
59
- // into the branches.
60
- //
61
- // The control lives on the K-simplex: a one-hot vertex is `select`
62
- // (the live branch absorbs everything), a `(1−t, t)` edge is `crossfade`,
63
- // uniform weights recover `mean`. Reactive weights are dynamically
64
- // tracked (read via `.value` inside fwd), so flipping a Bool or sliding a
65
- // Num re-reads with no extra wiring.
66
- /** Weighted blend of K branches over any `Linear` type. See module note. */
67
- // biome-ignore lint/suspicious/noExplicitAny: variance escape
68
- export function mix(weights, branches) {
69
- const K = branches.length;
70
- if (K < 1)
71
- throw new Error("mix: need ≥ 1 branch");
72
- if (weights.length !== K)
73
- throw new Error("mix: weights/branches length mismatch");
74
- // biome-ignore lint/suspicious/noExplicitAny: dynamic class lookup
75
- const Cls = branches[0].constructor;
76
- // biome-ignore lint/suspicious/noExplicitAny: dynamic trait lookup
77
- const lin = Cls.traits?.linear;
78
- if (!lin)
79
- throw new Error(`mix: ${Cls.name ?? "?"} has no traits.linear`);
80
- const wf = weights.map(w => reader(w));
81
- // Normalized weights + Σw². Degenerate (all-zero) weights fall back to
82
- // uniform so the read stays defined.
83
- const readW = () => {
84
- const raw = wf.map(f => f());
85
- let sum = 0;
86
- for (const x of raw)
87
- sum += x;
88
- const w = Math.abs(sum) > 1e-12 ? raw.map(x => x / sum) : raw.map(() => 1 / K);
89
- let sumSq = 0;
90
- for (const x of w)
91
- sumSq += x * x;
92
- return { w, sumSq };
93
- };
94
- // biome-ignore lint/suspicious/noExplicitAny: variance escape on Cls.lens
95
- const combine = (vals, w) => {
96
- let acc = lin.scale(vals[0], w[0]);
97
- for (let i = 1; i < K; i++)
98
- acc = lin.add(acc, lin.scale(vals[i], w[i]));
99
- return acc;
100
- };
101
- // biome-ignore lint/suspicious/noExplicitAny: variance escape on Cls.lens
102
- return Cls.lens(branches,
103
- // biome-ignore lint/suspicious/noExplicitAny: variance escape
104
- (vals) => combine(vals, readW().w),
105
- // biome-ignore lint/suspicious/noExplicitAny: variance escape
106
- (target, vals) => {
107
- const { w, sumSq } = readW();
108
- const delta = lin.sub(target, combine(vals, w));
109
- if (sumSq < 1e-12)
110
- return vals.map(() => SKIP);
111
- const inv = 1 / sumSq;
112
- return vals.map((v, i) => w[i] === 0 ? SKIP : lin.add(v, lin.scale(delta, w[i] * inv)));
113
- });
114
- }
115
- /** Two-branch router (mix simplex *vertex*): reads the live branch, writes
116
- * flow entirely to it, the other is left put. Flipping `cond` snaps the
117
- * output to the other branch's stored value. */
118
- // biome-ignore lint/suspicious/noExplicitAny: variance escape
119
- export function select(cond, whenFalse, whenTrue) {
120
- return mix([Num.derive(() => (cond.value ? 0 : 1)), Num.derive(() => (cond.value ? 1 : 0))], [whenFalse, whenTrue]);
121
- }
122
- /** Two-branch crossfade (mix simplex *edge*): `lerp(a, b, t)`. Writing
123
- * keeps `t` fixed and splits the delta by influence. */
124
- // biome-ignore lint/suspicious/noExplicitAny: variance escape
125
- export function crossfade(t, a, b) {
126
- return mix([Num.derive(() => 1 - t.value), Num.derive(() => t.value)], [a, b]);
127
- }
128
- /** Mean radial distance from the centroid; write scales the cluster's
129
- * deviations so the new mean matches the target. Trait-driven via
130
- * `Linear` + `Metric`, so it works for any class declaring both (Vec,
131
- * Color, Pose, Box, Range, custom).
132
- *
133
- * Complement carries per-input deviations normalized by the current mean
134
- * radius, so `spread = T` places each input at `centroid + normDev_i * T`
135
- * and a collapse (spread → 0) reinflates the original SHAPE. Centroid is
136
- * recomputed every read/write, so an intervening mean translate is not
137
- * stale. */
138
- export function spread(inputs) {
139
- const K = inputs.length;
140
- if (K < 1)
141
- throw new Error("spread: need ≥ 1 input");
142
- // biome-ignore lint/suspicious/noExplicitAny: dynamic class lookup
143
- const Cls = inputs[0].constructor;
144
- const lin = Cls.traits?.linear;
145
- const met = Cls.traits?.metric;
146
- if (!lin || !met) {
147
- throw new Error(`spread: ${Cls.name ?? "?"} needs Linear + Metric`);
148
- }
149
- const inv = 1 / K;
150
- const centroid = (vals) => {
151
- let acc = vals[0];
152
- for (let i = 1; i < K; i++)
153
- acc = lin.add(acc, vals[i]);
154
- return lin.scale(acc, inv);
155
- };
156
- const meanSpread = (vals, ctr) => {
157
- let total = 0;
158
- for (let i = 0; i < K; i++)
159
- total += met(vals[i], ctr);
160
- return total * inv;
161
- };
162
- // Mean metric-distance from the centroid is a magnitude `remember`:
163
- // writing it scales the cluster's deviations about the centroid, and a
164
- // collapse (spread → 0) reinflates the remembered shape.
165
- return remember(inputs, {
166
- anchor: (vals) => centroid(vals),
167
- feature: (vals, ctr) => meanSpread(vals, ctr),
168
- });
169
- }
170
- /** Mean/spread decomposition: K values → {mean, spread}, i.e. centroid +
171
- * uniform scale about it. `mean` ∘ `spread`; works for any
172
- * Linear + Metric class (palettes, point clouds, poses, …). */
173
- export function meanSpread(colors) {
174
- return {
175
- mean: mean(colors),
176
- spread: spread(colors),
177
- };
178
- }
179
- export function bezierGestalt(p0, p1, p2, p3) {
180
- const start = Vec.lens([p0, p1], (vals) => vals[0], (target, vals) => {
181
- const dx = target.x - vals[0].x;
182
- const dy = target.y - vals[0].y;
183
- return [target, { x: vals[1].x + dx, y: vals[1].y + dy }];
184
- });
185
- const end = Vec.lens([p2, p3], (vals) => vals[1], (target, vals) => {
186
- const dx = target.x - vals[1].x;
187
- const dy = target.y - vals[1].y;
188
- return [{ x: vals[0].x + dx, y: vals[0].y + dy }, target];
189
- });
190
- const startTangent = Vec.lens([p0, p1], (vals) => ({ x: vals[1].x - vals[0].x, y: vals[1].y - vals[0].y }), (target, vals) => [SKIP, { x: vals[0].x + target.x, y: vals[0].y + target.y }]);
191
- const endTangent = Vec.lens([p2, p3], (vals) => ({ x: vals[1].x - vals[0].x, y: vals[1].y - vals[0].y }), (target, vals) => [{ x: vals[1].x - target.x, y: vals[1].y - target.y }, SKIP]);
192
- return { start, end, startTangent, endTangent };
193
- }
194
- // Time-series aggregates.
195
- //
196
- // Scalar values indexed by position → {mean, slope}:
197
- // mean := average; writes shift all values by the delta.
198
- // slope := least-squares slope of (i, value_i); writes tilt about mean.
199
- // mean and slope are invariant under each other (a y-shift preserves
200
- // slope; tilting about the mean preserves the mean).
201
- /** Time-series scalar aggregate over Num values as (i, value_i) samples. */
202
- export function timeSeries(values) {
203
- const N = values.length;
204
- if (N < 2)
205
- throw new Error("timeSeries: need ≥ 2 values");
206
- const mean = Num.lens(values, (vals) => {
207
- let s = 0;
208
- for (let i = 0; i < N; i++)
209
- s += vals[i];
210
- return s / N;
211
- }, (target, vals) => {
212
- let s = 0;
213
- for (let i = 0; i < N; i++)
214
- s += vals[i];
215
- const cur = s / N;
216
- const delta = target - cur;
217
- return vals.map(v => v + delta);
218
- });
219
- // Least-squares slope = Σ (i − idxMean)(v − mean) / Σ (i − idxMean)²,
220
- // idxMean = (N−1)/2 constant. Write tilts about the mean:
221
- // value_i = mean + (i − idxMean)·s.
222
- const idxMean = (N - 1) / 2;
223
- let denomSlope = 0;
224
- for (let i = 0; i < N; i++) {
225
- const di = i - idxMean;
226
- denomSlope += di * di;
227
- }
228
- const slope = Num.lens(values, (vals) => {
229
- let valMean = 0;
230
- for (let i = 0; i < N; i++)
231
- valMean += vals[i];
232
- valMean /= N;
233
- let num = 0;
234
- for (let i = 0; i < N; i++)
235
- num += (i - idxMean) * (vals[i] - valMean);
236
- return num / denomSlope;
237
- }, (target, vals) => {
238
- let valMean = 0;
239
- for (let i = 0; i < N; i++)
240
- valMean += vals[i];
241
- valMean /= N;
242
- return vals.map((_, i) => valMean + (i - idxMean) * target);
243
- });
244
- return { mean, slope };
245
- }
@@ -1,40 +0,0 @@
1
- import type { Cell, Inner, Read, Traits, Writable } from "../index.js";
2
- /** Input cell: writable cell whose value class declares the `pack`
3
- * trait. Vec, Num, Pose, Box, Color, Range all satisfy this. */
4
- export type PackedInput<T = any> = Writable<Read<T> & Traits<T, "pack">>;
5
- /** Output specification: a target class + a fwd from typed inputs to
6
- * the value the class wraps. Optional analytical Jacobian skips FD. */
7
- export interface OutputSpec<C extends new (...args: never[]) => Cell<any>> {
8
- Cls: C;
9
- fwd: (inputs: ReadonlyArray<any>) => Inner<InstanceType<C>>;
10
- /** Optional analytical Jacobian. Returns dim(Cls) rows, each of
11
- * length `sum(input pack dims)`. If supplied for ALL outputs, FD
12
- * is skipped entirely → faster AND exact (no eps drift). */
13
- jacobian?: (inputs: ReadonlyArray<any>) => readonly (readonly number[])[];
14
- }
15
- /** Result type: writable cell per output key, typed by the spec's Cls. */
16
- export type FactorResult<O extends Record<string, OutputSpec<any>>> = {
17
- [K in keyof O]: Writable<InstanceType<O[K]["Cls"]>>;
18
- };
19
- export interface FactorOpts {
20
- /** Per-input mobility weights. 0 = pinned. Defaults to 1 for all. */
21
- inputWeights?: readonly number[];
22
- /** Levenberg-Marquardt damping. Default 1e-6. */
23
- damping?: number;
24
- /** Finite-difference epsilon. Default 1e-5. */
25
- eps?: number;
26
- /** Auto-iterate the bwd until the written channel's reading is
27
- * within `tol` of target (or `maxIters` exhausted). Cheap when
28
- * forwards are linear (1 iter); needed for non-linear forwards
29
- * to land exactly without user-side loops. Default `false`. */
30
- converge?: boolean;
31
- /** Max iters when `converge: true`. Default 10. */
32
- maxIters?: number;
33
- /** Convergence tolerance (per-channel L2). Default 1e-4. */
34
- tol?: number;
35
- }
36
- export declare function factor<O extends Record<string, OutputSpec<any>>>(inputs: readonly PackedInput[], outputs: O, opts?: FactorOpts): FactorResult<O>;
37
- export declare function factorTuple<T extends readonly OutputSpec<any>[]>(inputs: readonly PackedInput[], outputs: readonly [...T], opts?: FactorOpts): {
38
- [K in keyof T]: Writable<InstanceType<T[K]["Cls"]>>;
39
- };
40
- export declare function bundle<T, O extends Record<string, OutputSpec<any>>>(source: Writable<Read<T> & Traits<T, "pack">>, views: O, opts?: FactorOpts): FactorResult<O>;