-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtmp_uns_runtime_app.js
More file actions
4305 lines (4020 loc) · 171 KB
/
tmp_uns_runtime_app.js
File metadata and controls
4305 lines (4020 loc) · 171 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(() => {
const SCALE = 65536;
const KEYWORD_LOOKUP = buildCaseLookup(["let", "state", "const", "read", "lift1", "lift2", "D", "true", "false"]);
const RESERVED_LOOKUP = buildCaseLookup(["novel", "uvalue", "ustate", "scalar", "fn", "type"]);
const SPECIAL_IDENTIFIERS = new Set(['uvalue_of', 'frac']);
const DOC_EXPANDED_STORAGE_KEY = 'uns.docExplorer.expanded';
const DOC_SELECTED_STORAGE_KEY = 'uns.docExplorer.selected';
const INSPECTOR_TAB_STORAGE_KEY = 'uns.inspector.activeTab';
const DIAGNOSTIC_FILTER_STORAGE_KEY = 'uns.diagnostics.filter';
const MAX_DIAGNOSTIC_EVENTS = 150;
const SVG_NS = 'http://www.w3.org/2000/svg';
const HELPER_SPECS = {
uniform_state: { returnType: 'ustate', required: [], optional: [] },
psi_uniform: { returnType: 'ustate', required: [], optional: [] },
delta_state: { returnType: 'ustate', required: ['scalar'], optional: [] },
state: { returnType: 'ustate', required: ['uvalue'], optional: [] },
state_from_mask: { returnType: 'ustate', required: ['uvalue'], optional: [] },
state_range: { returnType: 'ustate', required: ['scalar', 'scalar'], optional: [] },
mask_range: { returnType: 'uvalue', required: ['scalar', 'scalar'], optional: [] },
mask_threshold: { returnType: 'uvalue', required: ['uvalue', 'uvalue'], optional: [] },
mask_lt: { returnType: 'uvalue', required: ['uvalue', 'uvalue'], optional: [] },
mask_gt: { returnType: 'uvalue', required: ['uvalue', 'uvalue'], optional: [] },
mask_eq: { returnType: 'uvalue', required: ['uvalue', 'uvalue'], optional: [] },
NORM: { returnType: 'uvalue', required: ['uvalue'], optional: [] },
MERGE: { returnType: 'uvalue', required: ['tuple'], optional: ['tuple'] },
MASK: { returnType: 'uvalue', required: ['uvalue', 'uvalue'], optional: [] },
PROJECT: { returnType: 'uvalue', required: ['uvalue', 'tuple'], optional: [] },
OVERLAP: { returnType: 'uvalue', required: ['uvalue', 'uvalue'], optional: [] },
DOT: { returnType: 'scalar', required: ['uvalue', 'uvalue'], optional: [] },
DIST_L1: { returnType: 'scalar', required: ['uvalue', 'uvalue'], optional: [] },
collection: { returnType: 'uvalue', required: [], optional: [], variadicType: 'uvalue' },
inject: { returnType: 'uvalue', required: ['scalarOrUValue', 'scalar'], optional: ['scalar'] },
CANCEL: { returnTuple: ['uvalue', 'uvalue'], required: ['uvalue', 'uvalue'], optional: [] },
CANCEL_JOINT: { returnType: 'uvalue', required: ['uvalue', 'uvalue'], optional: [] },
MIX: { returnType: 'uvalue', required: ['uvalue', 'uvalue', 'scalar'], optional: [] },
invokeDKeyword: { returnType: 'ustate', required: ['scalar', 'stateLike'], optional: [] },
meanU: { returnType: 'scalar', required: ['uvalue'], optional: ['stateLike'] },
sumU: { returnType: 'scalar', required: ['uvalue'], optional: ['stateLike'] },
integralU: { returnType: 'scalar', required: ['uvalue'], optional: ['stateLike'] },
varianceU: { returnType: 'scalar', required: ['uvalue'], optional: ['stateLike'] },
variance: { returnType: 'scalar', required: ['uvalue', 'stateLike'], optional: [] },
stddevU: { returnType: 'scalar', required: ['uvalue'], optional: ['stateLike'] },
stdU: { returnType: 'scalar', required: ['uvalue'], optional: ['stateLike'] },
densityU: { returnType: 'scalar', required: ['uvalue'], optional: ['stateLike'] },
integrate: { returnType: 'scalar', required: ['uvalue', 'stateLike'], optional: [] },
mean: { returnType: 'scalar', required: ['uvalue'], optional: [] },
smoothness: { returnType: 'scalar', required: ['uvalue'], optional: [] },
absU: { returnType: 'uvalue', required: ['uvalue'], optional: [] },
negU: { returnType: 'uvalue', required: ['uvalue'], optional: [] },
sqrtU: { returnType: 'uvalue', required: ['uvalue'], optional: [] },
normU: { returnType: 'uvalue', required: ['uvalue'], optional: [] },
addU: { returnType: 'uvalue', required: ['uvalue', 'uvalue'], optional: [] },
subU: { returnType: 'uvalue', required: ['uvalue', 'uvalue'], optional: [] },
mulU: { returnType: 'uvalue', required: ['uvalue', 'uvalue'], optional: [] },
divU: { returnType: 'uvalue', required: ['uvalue', 'uvalue'], optional: [] },
powU: { returnType: 'uvalue', required: ['uvalue', 'uvalue'], optional: [] },
printU: { returnType: 'void', required: ['uvalue'], optional: [] },
plotU: { returnType: 'void', required: ['uvalue'], optional: [] }
};
const EXPLICIT_HELPER_ALIASES = {
helperUniformState: 'uniform_state',
helperPsiUniform: 'psi_uniform',
helperDeltaState: 'delta_state',
helperState: 'state',
helperStateFromMask: 'state_from_mask',
helperStateRange: 'state_range',
helperMaskRange: 'mask_range',
helperMaskThreshold: 'mask_threshold',
helperMaskLessThan: 'mask_lt',
helperMaskGreaterThan: 'mask_gt',
helperMaskEqual: 'mask_eq',
helperNorm: 'NORM',
helperMerge: 'MERGE',
helperMaskSimplex: 'MASK',
helperProject: 'PROJECT',
helperOverlap: 'OVERLAP',
helperDot: 'DOT',
helperDistL1: 'DIST_L1',
helperCollection: 'collection',
helperInject: 'inject',
helperCancel: 'CANCEL',
helperCancelJoint: 'CANCEL_JOINT',
helperMix: 'MIX'
};
const HELPER_ALIAS_LOOKUP = buildHelperAliasLookup(Object.keys(HELPER_SPECS), EXPLICIT_HELPER_ALIASES);
const HELPER_ALIAS_TUPLE_SPREAD = new Map([
['helpermerge', { canonical: 'MERGE', tupleIndex: 0 }],
['helperproject', { canonical: 'PROJECT', tupleIndex: 1 }]
]);
const PRECEDENCE = { "+u": 1, "*u": 2, "*s": 2 };
const tupleType = (elements) => ({ kind: 'tuple', elements: Array.isArray(elements) ? [...elements] : [] });
const isTupleType = (value) => Boolean(value && typeof value === 'object' && value.kind === 'tuple');
function buildCaseLookup(words) {
const map = new Map();
words.forEach((word) => {
if (!word) return;
map.set(word.toLowerCase(), word);
});
return map;
}
function toPascalCase(value) {
if (!value) return '';
return value
.split(/[^A-Za-z0-9]+/)
.filter(Boolean)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
.join('');
}
function buildHelperAliasLookup(names, explicitAliases = {}) {
const map = new Map();
const register = (alias, canonical) => {
if (!alias || !canonical) return;
map.set(alias.toLowerCase(), canonical);
};
names.forEach((name) => {
register(name, name);
register(`helper${toPascalCase(name)}`, name);
register(`helper_${name}`, name);
register(`helper${name}`, name);
register(name.replace(/[^A-Za-z0-9]/g, ''), name);
});
Object.entries(explicitAliases).forEach(([alias, canonical]) => register(alias, canonical));
return map;
}
function canonicalHelperName(name) {
if (typeof name !== 'string') return null;
return HELPER_ALIAS_LOOKUP.get(name.toLowerCase()) ?? null;
}
function reshapeHelperArgs(canonicalName, rawName, args) {
if (!rawName) return args;
const config = HELPER_ALIAS_TUPLE_SPREAD.get(rawName.toLowerCase());
if (!config) return args;
if (config.canonical && config.canonical !== canonicalName) return args;
const index = Math.max(0, config.tupleIndex ?? 0);
if (index >= args.length) return args;
const prefix = args.slice(0, index);
const elements = args.slice(index);
if (!elements.length) return args;
const tupleLiteral = { type: 'TupleLiteral', elements };
return [...prefix, tupleLiteral];
}
const describeTypeName = (value) => {
if (typeof value === 'string') return value;
if (isTupleType(value)) {
const count = value.elements?.length;
const size = Number.isFinite(count) ? count : '?';
return `tuple(${size})`;
}
if (!value) return 'void';
return 'unknown';
};
const UNSOperators = (() => {
const EPS = 1e-12;
const SUM_TOLERANCE = 1e-9;
const toArray = (vector, label = 'vector') => {
if (Array.isArray(vector)) return vector.map(Number);
if (ArrayBuffer.isView(vector)) return Array.from(vector, Number);
throw new Error(`Expected array-like for ${label}`);
};
const ensureSameLength = (a, b, labelA = 'a', labelB = 'b') => {
if (a.length !== b.length) {
throw new Error(`${labelA} and ${labelB} must have equal length`);
}
};
const assertNonNegative = (vec, label) => {
if (vec.some(v => v < -EPS)) {
throw new Error(`${label} must be nonnegative`);
}
};
const sum = (vec) => vec.reduce((acc, v) => acc + v, 0);
const uniform = (dim) => {
if (dim <= 0) throw new Error('Dimension must be positive');
const value = 1 / dim;
return Array(dim).fill(value);
};
const clampAlpha = (alpha) => {
if (!Number.isFinite(alpha)) return 0;
return Math.min(1, Math.max(0, alpha));
};
const normalize = (vector) => {
const arr = toArray(vector, 'NORM input');
assertNonNegative(arr, 'NORM input');
const total = sum(arr);
if (total > EPS) {
return arr.map(v => v / total);
}
return uniform(arr.length);
};
const overlap = (u, v) => {
const a = toArray(u, 'OVERLAP u');
const b = toArray(v, 'OVERLAP v');
ensureSameLength(a, b, 'u', 'v');
return a.map((value, idx) => Math.min(value, b[idx]));
};
const subtract = (a, b) => a.map((value, idx) => {
const diff = value - b[idx];
return diff < 0 && Math.abs(diff) < 1e-14 ? 0 : Math.max(0, diff);
});
const addVectors = (vectors) => {
const dim = vectors[0].length;
const acc = Array(dim).fill(0);
vectors.forEach(vec => {
vec.forEach((value, idx) => {
acc[idx] += value;
});
});
return acc;
};
const renormResidual = (vec) => {
const total = sum(vec);
if (total > EPS) return vec.map(v => v / total);
return uniform(vec.length);
};
const mix = (u, v, alpha) => {
const a = toArray(u, 'MIX u');
const b = toArray(v, 'MIX v');
ensureSameLength(a, b, 'u', 'v');
assertNonNegative(a, 'MIX u');
assertNonNegative(b, 'MIX v');
const clamped = clampAlpha(alpha ?? 0);
return a.map((value, idx) => (clamped * value) + ((1 - clamped) * b[idx]));
};
const merge = (vectors, weights) => {
if (!Array.isArray(vectors) || vectors.length === 0) {
throw new Error('MERGE requires at least one vector');
}
const arrays = vectors.map((vec, idx) => toArray(vec, `MERGE input ${idx}`));
const dim = arrays[0].length;
arrays.forEach((arr, idx) => {
if (arr.length !== dim) throw new Error(`MERGE input ${idx} has mismatched dimension`);
assertNonNegative(arr, `MERGE input ${idx}`);
});
const normalizedWeights = (weights ?? []).map((w, idx) => {
if (w === undefined) return 1;
if (w < 0) throw new Error(`MERGE weight ${idx} must be nonnegative`);
return w;
});
const coeffs = arrays.map((_, idx) => normalizedWeights[idx] ?? 1);
if (coeffs.every(weight => weight <= EPS)) {
return uniform(dim);
}
const accumulator = Array(dim).fill(0);
arrays.forEach((arr, idx) => {
const weight = coeffs[idx];
arr.forEach((value, j) => {
accumulator[j] += weight * value;
});
});
return normalize(accumulator);
};
const split = (u, alphas) => {
const base = toArray(u, 'SPLIT input');
assertNonNegative(base, 'SPLIT input');
if (!Array.isArray(alphas) || alphas.length === 0) {
throw new Error('SPLIT requires coefficient array');
}
const totalAlpha = sum(alphas);
if (Math.abs(totalAlpha - 1) > SUM_TOLERANCE) {
throw new Error('SPLIT coefficients must sum to 1');
}
return alphas.map((alpha, idx) => {
if (alpha < -EPS) throw new Error(`SPLIT alpha ${idx} must be nonnegative`);
return base.map(value => alpha * value);
});
};
const cancel = (u, v) => {
const a = toArray(u, 'CANCEL u');
const b = toArray(v, 'CANCEL v');
ensureSameLength(a, b, 'u', 'v');
assertNonNegative(a, 'CANCEL u');
assertNonNegative(b, 'CANCEL v');
const w = overlap(a, b);
const uRaw = subtract(a, w);
const vRaw = subtract(b, w);
return [renormResidual(uRaw), renormResidual(vRaw)];
};
const cancelJoint = (u, v) => {
const a = toArray(u, 'CANCEL_JOINT u');
const b = toArray(v, 'CANCEL_JOINT v');
ensureSameLength(a, b, 'u', 'v');
const w = overlap(a, b);
const uRaw = subtract(a, w);
const vRaw = subtract(b, w);
const residual = addVectors([uRaw, vRaw]);
return renormResidual(residual);
};
const mask = (u, maskVector) => {
const base = toArray(u, 'MASK input');
const maskArr = toArray(maskVector, 'MASK mask');
ensureSameLength(base, maskArr, 'u', 'mask');
assertNonNegative(base, 'MASK input');
assertNonNegative(maskArr, 'MASK mask');
const attenuated = base.map((value, idx) => value * maskArr[idx]);
return normalize(attenuated);
};
const project = (u, subset) => {
const indices = new Set(subset ?? []);
const base = toArray(u, 'PROJECT input');
const maskVector = base.map((_, idx) => (indices.has(idx) ? 1 : 0));
return mask(base, maskVector);
};
const dot = (u, v) => {
const a = toArray(u, 'DOT u');
const b = toArray(v, 'DOT v');
ensureSameLength(a, b, 'u', 'v');
return Math.min(1, Math.max(0, a.reduce((acc, value, idx) => acc + value * b[idx], 0)));
};
const distL1 = (u, v) => {
const a = toArray(u, 'DIST_L1 u');
const b = toArray(v, 'DIST_L1 v');
ensureSameLength(a, b, 'u', 'v');
const total = a.reduce((acc, value, idx) => acc + Math.abs(value - b[idx]), 0);
return Math.min(1, Math.max(0, 0.5 * total));
};
const checkSimplex = (vec, label) => {
assertNonNegative(vec, label);
const total = sum(vec);
if (Math.abs(total - 1) > 5 * SUM_TOLERANCE) {
throw new Error(`${label} must sum to 1 (was ${total})`);
}
};
const approxEqualVec = (a, b) => {
if (a.length !== b.length) return false;
return a.every((value, idx) => Math.abs(value - b[idx]) <= 5 * SUM_TOLERANCE);
};
const runSelfTests = () => {
const report = [];
const record = (name, fn) => {
try {
fn();
report.push({ name, status: 'ok' });
} catch (err) {
report.push({ name, status: 'fail', message: err.message });
throw err;
}
};
record('NORM invariants', () => {
const u = [0.2, 0.3, 0.5];
const normalized = normalize(u);
checkSimplex(normalized, 'NORM(u)');
const zero = normalize([0, 0, 0, 0]);
checkSimplex(zero, 'NORM(0)');
});
record('MIX invariants', () => {
const u = [0.7, 0.3];
const v = [0.5, 0.5];
const mixed = mix(u, v, 0.4);
checkSimplex(mixed, 'mix result');
});
record('MERGE invariants', () => {
const u = [0.6, 0.2, 0.2];
const v = [0.1, 0.3, 0.6];
const merged = merge([u, v], [2, 1]);
checkSimplex(merged, 'MERGE result');
});
record('SPLIT coefficients', () => {
const base = [0.5, 0.5];
const parts = split(base, [0.25, 0.75]);
if (parts.length !== 2) throw new Error('SPLIT returned wrong count');
const sums = parts.map(sum);
if (Math.abs(sums[0] - 0.25) > SUM_TOLERANCE) throw new Error('First split sum incorrect');
if (Math.abs(sums[1] - 0.75) > SUM_TOLERANCE) throw new Error('Second split sum incorrect');
});
record('CANCEL symmetry', () => {
const u = [0.6, 0.4];
const v = [0.5, 0.5];
const [u1, v1] = cancel(u, v);
const [v2, u2] = cancel(v, u);
if (!approxEqualVec(u1, u2) || !approxEqualVec(v1, v2)) {
throw new Error('CANCEL residuals not symmetric');
}
checkSimplex(u1, 'CANCEL u residual');
checkSimplex(v1, 'CANCEL v residual');
});
record('CANCEL_JOINT invariants', () => {
const u = [0.3, 0.7];
const v = [0.8, 0.2];
const joint = cancelJoint(u, v);
checkSimplex(joint, 'CANCEL_JOINT result');
});
record('MASK and PROJECT', () => {
const u = [0.1, 0.4, 0.5];
const masked = mask(u, [1, 0.5, 0]);
checkSimplex(masked, 'MASK result');
const projected = project(u, [0, 2]);
checkSimplex(projected, 'PROJECT result');
if (projected[1] !== projected[1]) {
throw new Error('PROJECT produced NaN');
}
});
record('Metric bounds', () => {
const u = [0.9, 0.1];
const v = [0.2, 0.8];
const s = dot(u, v);
const d = distL1(u, v);
if (s < -SUM_TOLERANCE || s > 1 + SUM_TOLERANCE) throw new Error('DOT out of bounds');
if (d < -SUM_TOLERANCE || d > 1 + SUM_TOLERANCE) throw new Error('DIST_L1 out of bounds');
});
return report;
};
const api = {
EPSILON: EPS,
NORM: normalize,
MIX: mix,
MERGE: merge,
SPLIT: split,
CANCEL: cancel,
CANCEL_JOINT: cancelJoint,
MASK: mask,
PROJECT: project,
OVERLAP: overlap,
DOT: dot,
DIST_L1: distL1,
runSelfTests
};
const selfTestStatus = (() => {
try {
return { ok: true, report: runSelfTests() };
} catch (err) {
return { ok: false, error: err };
}
})();
if (typeof window !== 'undefined') {
window.UNSOperators = api;
window.UNSOperatorTestReport = selfTestStatus;
}
if (selfTestStatus.ok) {
console.info('UNS operator self-tests passed', selfTestStatus.report);
} else {
console.error('UNS operator self-tests failed', selfTestStatus.error);
}
return api;
})();
const SIMPLEX_OPERATOR_SPECS = [
{
key: 'NORM',
label: 'NORM — Normalize vector',
description: 'Rescales any nonnegative vector to the simplex (uniform fallback when the sum is zero).',
args: [
{ key: 'vector', label: 'Vector', type: 'vector', placeholder: '[0.25, 0.25, 0.5]' }
],
run: ({ vector }) => UNSOperators.NORM(vector)
},
{
key: 'MIX',
label: 'MIX — Convex mix',
description: 'Clamps α into [0,1] before computing αu + (1−α)v.',
args: [
{ key: 'u', label: 'Vector u', type: 'vector', placeholder: '[0.7, 0.3]' },
{ key: 'v', label: 'Vector v', type: 'vector', placeholder: '[0.5, 0.5]' },
{ key: 'alpha', label: 'α (0-1)', type: 'alpha', placeholder: '0.5' }
],
run: ({ u, v, alpha }) => UNSOperators.MIX(u, v, alpha)
},
{
key: 'MERGE',
label: 'MERGE — Weighted union',
description: 'Combines a family of vectors with optional weights, then normalizes.',
args: [
{ key: 'vectors', label: 'Vectors (JSON array of arrays)', type: 'vectors', placeholder: '[[0.6,0.4],[0.1,0.9]]' },
{ key: 'weights', label: 'Weights (optional)', type: 'numberArray', optional: true, placeholder: '[2, 1]' }
],
run: ({ vectors, weights }) => UNSOperators.MERGE(vectors, weights)
},
{
key: 'SPLIT',
label: 'SPLIT — Partition vector',
description: 'Creates subnormalized components α_j u (coefficients must sum to 1).',
args: [
{ key: 'vector', label: 'Vector', type: 'vector', placeholder: '[0.5, 0.3, 0.2]' },
{ key: 'coefficients', label: 'Coefficients (sum to 1)', type: 'numberArray', placeholder: '[0.25, 0.75]' }
],
run: ({ vector, coefficients }) => UNSOperators.SPLIT(vector, coefficients)
},
{
key: 'CANCEL',
label: 'CANCEL — Remove overlap',
description: 'Subtracts component-wise overlap, then normalizes each residual.',
args: [
{ key: 'u', label: 'Vector u', type: 'vector', placeholder: '[0.6, 0.4]' },
{ key: 'v', label: 'Vector v', type: 'vector', placeholder: '[0.5, 0.5]' }
],
run: ({ u, v }) => UNSOperators.CANCEL(u, v)
},
{
key: 'CANCEL_JOINT',
label: 'CANCEL_JOINT — Joint residual',
description: 'Returns one vector encoding both non-overlapping parts.',
args: [
{ key: 'u', label: 'Vector u', type: 'vector', placeholder: '[0.3, 0.7]' },
{ key: 'v', label: 'Vector v', type: 'vector', placeholder: '[0.8, 0.2]' }
],
run: ({ u, v }) => UNSOperators.CANCEL_JOINT(u, v)
},
{
key: 'MASK',
label: 'MASK — Apply weights',
description: 'Multiplies by a nonnegative mask and renormalizes.',
args: [
{ key: 'vector', label: 'Vector', type: 'vector', placeholder: '[0.2, 0.4, 0.4]' },
{ key: 'mask', label: 'Mask vector', type: 'vector', placeholder: '[1, 0.5, 0]' }
],
run: ({ vector, mask }) => UNSOperators.MASK(vector, mask)
},
{
key: 'PROJECT',
label: 'PROJECT — Pick indices',
description: 'Keeps only selected indices via MASK with a binary mask.',
args: [
{ key: 'vector', label: 'Vector', type: 'vector', placeholder: '[0.1, 0.2, 0.7]' },
{ key: 'subset', label: 'Indices (JSON array)', type: 'subset', placeholder: '[0, 2]' }
],
run: ({ vector, subset }) => UNSOperators.PROJECT(vector, subset)
},
{
key: 'OVERLAP',
label: 'OVERLAP — Component minima',
description: 'Returns min(u_i, v_i) without renormalization.',
args: [
{ key: 'u', label: 'Vector u', type: 'vector', placeholder: '[0.6, 0.4]' },
{ key: 'v', label: 'Vector v', type: 'vector', placeholder: '[0.5, 0.5]' }
],
run: ({ u, v }) => UNSOperators.OVERLAP(u, v)
},
{
key: 'DOT',
label: 'DOT — Similarity',
description: 'Computes ∑ u_i v_i (bounded inside [0,1]).',
args: [
{ key: 'u', label: 'Vector u', type: 'vector', placeholder: '[0.9, 0.1]' },
{ key: 'v', label: 'Vector v', type: 'vector', placeholder: '[0.2, 0.8]' }
],
run: ({ u, v }) => UNSOperators.DOT(u, v)
},
{
key: 'DIST_L1',
label: 'DIST_L1 — L1 distance',
description: 'Returns 0.5 · ∑ |u_i − v_i| (also bounded inside [0,1]).',
args: [
{ key: 'u', label: 'Vector u', type: 'vector', placeholder: '[0.9, 0.1]' },
{ key: 'v', label: 'Vector v', type: 'vector', placeholder: '[0.2, 0.8]' }
],
run: ({ u, v }) => UNSOperators.DIST_L1(u, v)
}
];
const SIMPLEX_OPERATOR_INDEX = Object.fromEntries(SIMPLEX_OPERATOR_SPECS.map(spec => [spec.key, spec]));
const sampleProgram = `// Sample UNS program demonstrating const, +u, *s, lifts, windowed states, read
let alpha = const(0.75)
let beta = const(0.25)
let probe = alpha +u (beta *s 2)
let signal = lift1(sqrt, probe)
let idx = lift1(index, const(0))
let windowMask = lift1(windowWeight_3_4, idx)
state psi = windowMask
let guard = lift2(divide, probe +u const(0.1), signal)
read(guard | psi)`;
const DEFAULT_MICROSTATES = 512;
const MAX_MICROSTATES = 32768;
const MICROSTATE_STORAGE_KEY = 'uns_microstate_count';
const DEFAULT_UNSE_FILENAME = 'program.unse';
let currentFileName = DEFAULT_UNSE_FILENAME;
const ui = {
source: document.getElementById('unsSource'),
output: document.getElementById('output'),
status: document.getElementById('status'),
ast: document.getElementById('astView'),
debug: document.getElementById('debugLog'),
valueTable: document.querySelector('#valueTable tbody'),
readTester: document.getElementById('readTester'),
readResult: document.getElementById('readResult'),
microstateInput: document.getElementById('microstateCount'),
highlightLayer: document.getElementById('highlightLayer'),
cursorStatus: document.getElementById('cursorStatus'),
layout: {
workspace: document.getElementById('workspaceLayout'),
resizer: document.getElementById('columnResizer')
},
examples: {
select: document.getElementById('exampleSelect'),
loadBtn: document.getElementById('loadExampleBtn')
},
inspectors: {
panel: document.getElementById('inspectorPanel'),
uvalueSelect: document.getElementById('inspectUValueSelect'),
uvalueBtn: document.getElementById('inspectUValueBtn'),
uvalueOutput: document.getElementById('inspectUValueOutput'),
stateSelect: document.getElementById('inspectUStateSelect'),
stateBtn: document.getElementById('inspectUStateBtn'),
stateOutput: document.getElementById('inspectUStateOutput'),
novelOutput: document.getElementById('novelInspector')
},
diagnostics: {
log: document.getElementById('diagnosticLog'),
empty: document.getElementById('diagnosticEmpty'),
filters: document.querySelectorAll('[data-diagnostic-filter]'),
clearBtn: document.getElementById('clearDiagnosticsBtn')
},
docs: {
tree: document.getElementById('docTree'),
search: document.getElementById('docSearch'),
detailTitle: document.getElementById('docDetailTitle'),
detailBody: document.getElementById('docDetailBody')
},
files: {
saveBtn: document.getElementById('saveBtn'),
loadBtn: document.getElementById('loadBtn'),
input: document.getElementById('unseFileInput')
},
simplex: {
panel: document.getElementById('simplexPanel'),
select: document.getElementById('simplexOperatorSelect'),
inputs: document.getElementById('simplexOperatorInputs'),
runBtn: document.getElementById('runSimplexOperatorBtn'),
result: document.getElementById('simplexOperatorResult'),
hint: document.getElementById('simplexOperatorHint')
}
};
const EXAMPLE_SCRIPTS = {
smoothness: {
label: 'Smoothness detection',
code: `// Detect how smooth a hybrid window + sine signal is
let idx = lift1(index, const(0))
let carrier = lift1(windowWeight_96_48, idx)
let signal = carrier +u lift1(sin, idx)
let roughness = smoothness(signal)
printU(signal)
plotU(signal)`
},
primeScan: {
label: 'Prime distribution analysis',
code: `// Compare global vs windowed prime densities
let idx = lift1(index, const(0))
let primes = lift1(isPrime, idx)
state psi = psi_uniform()
let global = meanU(primes, psi)
let firstBand = mask_range(0, 128)
let firstBandDensity = meanU(primes *u firstBand, psi)
read(primes | psi)`
},
dTransform: {
label: 'D-transform invariance',
code: `// Show readout invariance after shifting psi
let idx = lift1(index, const(0))
let wave = lift1(sin, idx)
state psi = psi_uniform()
state shifted = D(48, psi)
let baseline = read(wave | psi)
let shiftedRead = read(wave | shifted)`
},
injectedDiff: {
label: 'Injected diff pattern',
code: `// Assemble sparse differences and spike a microstate
let diff = assemble {
0: 0.2,
1: 0.1,
2: -0.2,
3: 0.1,
4: 0.1
}
let spike = inject(0.5, 32)
let combined = diff +u spike
plotU(combined)`
},
triangle: {
label: 'Triangle hypotenuse',
code: `// Compute sqrt(a^2 + b^2) per microstate
let idx = lift1(index, const(0))
let a = lift1(sin, idx)
let b = lift1(cos, idx)
let hypSquared = (a *u a) +u (b *u b)
let hyp = sqrtU(hypSquared)
plotU(hyp)`
},
novelDivision: {
label: 'Division-by-zero novel',
code: `// Surface a novel value produced by divide-by-zero
let zeros = collection(const(0))
let unstable = divU(const(1), zeros)
printU(unstable)`
}
};
const DOC_TREE_DATA = [
{
id: 'language',
title: 'Language Surface',
summary: 'Keywords, lifts, and reserved identifiers.',
children: [
{
id: 'language-core',
title: 'Core keywords',
summary: 'let, state, const, read, and boolean literals.',
content: `
<ul>
<li><code>let</code> introduces immutable bindings per microstate.</li>
<li><code>state</code> declares reusable <code>|psi|^2</code> distributions.</li>
<li><code>const</code> lifts scalars; <code>true</code>/<code>false</code> are predefined.</li>
<li><code>read(f | psi)</code> performs expectation-style aggregation.</li>
<li><code>lift1</code>/<code>lift2</code>/<code>D</code> expose helper entry points.</li>
</ul>
`
},
{
id: 'language-helpers',
title: 'Scalar helpers (lift1)',
summary: 'Utility functions for building signals.',
content: `
<p><code>index</code> returns the microstate index, <code>isPrime</code> marks prime indices, and <code>windowWeight_CENTER_WIDTH</code> (for example <code>windowWeight_3_4</code>) emits tapered windows.</p>
`
},
{
id: 'language-lifts',
title: 'Lift catalog',
summary: 'Built-in unary and binary lifts.',
content: `
<ul>
<li><strong>lift1</strong>: <code>sqrt</code>, <code>sin</code>, <code>cos</code>, <code>log</code>, <code>abs</code>, <code>conj</code>, and all scalar helpers.</li>
<li><strong>lift2</strong>: <code>divide</code>, <code>pow</code>, <code>blend</code>, <code>lt</code>, <code>gt</code>, <code>eq</code>, <code>ge</code>, <code>le</code>.</li>
<li><strong>Special</strong>: <code>frac(a, b)</code> expands to <code>lift2(divide, a, b)</code>.</li>
</ul>
`
},
{
id: 'language-reserved',
title: 'Reserved identifiers',
summary: 'Future-facing tokens.',
content: `
<p>The runtime reserves <code>novel</code>, <code>uvalue</code>, <code>ustate</code>, <code>scalar</code>, <code>fn</code>, and <code>type</code> for future extensions.</p>
`
}
]
},
{
id: 'collections',
title: 'Collections & Aggregates',
summary: 'State builders, collections, and readout helpers.',
children: [
{
id: 'collections-builders',
title: 'Collections and injections',
summary: 'Create sparse or dense signals.',
content: `
<p><code>assemble {i: value}</code>, <code>inject(value, index, M?)</code>, <code>collection(a0, a1, ...)</code>, and <code>uvalue_of({index: expr})</code> provide quick ways to seed signals before lifting.</p>
`
},
{
id: 'collections-states',
title: 'States and masks',
summary: 'Common |psi|^2 builders.',
content: `
<p><code>psi_uniform()</code>, <code>uniform_state()</code>, <code>state(uvalue)</code>, <code>delta_state(i)</code>, <code>state_range(start, end)</code>, and <code>mask_range(start, end)</code> cover most support shapes. <code>mask_threshold(f, t)</code> and comparison masks (<code>mask_lt</code>, <code>mask_gt</code>, <code>mask_eq</code>) refine regions.</p>
`
},
{
id: 'collections-aggregates',
title: 'Aggregates via read()',
summary: 'Expectation helpers.',
content: `
<p><code>read(f | psi)</code> plus helpers (<code>integrate</code>, <code>mean</code>, <code>variance</code>, <code>smoothness</code>) evaluate expectations without loops. <code>meanU</code>, <code>sumU</code>, <code>varianceU</code>, <code>stddevU</code>, and <code>smoothness</code> operate directly on UValues.</p>
`
},
{
id: 'collections-integrations',
title: 'Integrations and densities',
summary: 'Weighted statistics.',
content: `
<p><code>integrate(f, psi)</code> mirrors <code>read(f | psi)</code>; <code>mean(f)</code> defaults to <code>uniform_state()</code>. Combine <code>densityU</code>, <code>meanU</code>, and <code>varianceU</code> for weighted stats.</p>
`
},
{
id: 'collections-dtransform',
title: 'D-transform workflows',
summary: 'Symmetry exploration.',
content: `
<p><code>D(k, psi)</code> shifts amplitudes and preserves normalization, making it easy to compare <code>read</code> results before and after transforms.</p>
`
}
]
},
{
id: 'diagnostics',
title: 'Diagnostics & Debugging',
summary: 'printU, plotU, and inspector guidance.',
children: [
{
id: 'diagnostics-print',
title: 'printU streams',
summary: 'Emit per-microstate slices.',
content: `
<p><code>printU(value)</code> emits 128-sample slices of a UValue, preserving novel metadata so spikes are easy to trace.</p>
`
},
{
id: 'diagnostics-plot',
title: 'plotU visualizations',
summary: 'Inline magnitude charts.',
content: `
<p><code>plotU(value)</code> renders magnitudes for up to 512 samples. Pair with masks or helper states to visualize support.</p>
`
},
{
id: 'diagnostics-inspectors',
title: 'Inspector hub tips',
summary: 'Bindings, simplex, diagnostics.',
content: `
<p>The <strong>Bindings</strong> tab mirrors runtime bindings, <strong>Simplex Toolkit</strong> exposes helper operators, and <strong>Diagnostics</strong> aggregates <code>printU</code>/<code>plotU</code> events with copy-ready logs.</p>
`
}
]
},
{
id: 'simplex',
title: 'Simplex Operators',
summary: 'Helper operators that preserve the UNS simplex.',
children: [
{
id: 'simplex-overview',
title: 'Operator overview',
summary: 'Interactive helper descriptions.',
content: `
<ul>
<li><code>NORM(x)</code> rescales any nonnegative vector to the simplex (uniform fallback on zero).</li>
<li><code>MIX(u, v; alpha)</code> clamps <code>alpha</code> to [0,1] before mixing.</li>
<li><code>MERGE</code>/<code>SPLIT</code> convert between weighted families and standalone elements.</li>
<li><code>CANCEL</code>/<code>CANCEL_JOINT</code> remove shared support via <code>OVERLAP</code>.</li>
<li><code>MASK</code>/<code>PROJECT</code> restrict components and renormalize.</li>
<li><code>DOT</code> and <code>DIST_L1</code> remain in [0,1] and are read-only observables.</li>
</ul>
`
}
]
}
];
if (ui.examples.select) {
ui.examples.select.innerHTML = '';
let firstKey = '';
Object.entries(EXAMPLE_SCRIPTS).forEach(([key, script], index) => {
const opt = document.createElement('option');
opt.value = key;
opt.textContent = script.label;
ui.examples.select.appendChild(opt);
if (index === 0) firstKey = key;
});
if (firstKey) ui.examples.select.value = firstKey;
}
if (ui.examples.loadBtn) {
ui.examples.loadBtn.addEventListener('click', () => {
if (!ui.examples.select) return;
const selected = ui.examples.select.value;
const script = EXAMPLE_SCRIPTS[selected];
if (!script) return;
ui.source.value = script.code;
currentFileName = DEFAULT_UNSE_FILENAME;
updateHighlight();
});
}
if (ui.inspectors?.uvalueBtn) {
ui.inspectors.uvalueBtn.addEventListener('click', () => {
if (!currentVm) {
if (ui.inspectors.uvalueOutput) ui.inspectors.uvalueOutput.textContent = 'Run a program first.';
return;
}
const select = ui.inspectors.uvalueSelect;
if (!select || select.disabled || !select.value) {
if (ui.inspectors.uvalueOutput) ui.inspectors.uvalueOutput.textContent = 'No UValues available.';
return;
}
const binding = currentVm.env.get(select.value);
if (!binding || binding.kind !== 'uvalue') {
if (ui.inspectors.uvalueOutput) ui.inspectors.uvalueOutput.textContent = 'Binding is not a UValue.';
return;
}
if (ui.inspectors.uvalueOutput) ui.inspectors.uvalueOutput.textContent = formatUValueLines(currentVm, binding.ref);
});
}
if (ui.inspectors?.stateBtn) {
ui.inspectors.stateBtn.addEventListener('click', () => {
if (!currentVm) {
if (ui.inspectors.stateOutput) ui.inspectors.stateOutput.textContent = 'Run a program first.';
return;
}
const select = ui.inspectors.stateSelect;
if (!select || select.disabled || !select.value) {
if (ui.inspectors.stateOutput) ui.inspectors.stateOutput.textContent = 'No UStates available.';
return;
}
const binding = currentVm.env.get(select.value);
if (!binding || binding.kind !== 'ustate') {
if (ui.inspectors.stateOutput) ui.inspectors.stateOutput.textContent = 'Binding is not a UState.';
return;
}
if (ui.inspectors.stateOutput) ui.inspectors.stateOutput.textContent = formatUStateLines(currentVm, binding.ref);
});
}
setupCollapsibles();
setupSimplexToolkit();
setupResizer();
setupFileIo();
setupInspectorTabs();
setupDocExplorer();
diagnosticsController = createDiagnosticsController();
function setupCollapsibles() {
document.querySelectorAll('[data-collapsible]').forEach(section => {
const button = section.querySelector('.collapse-btn');
const body = section.querySelector('.panel-body');
if (!button || !body) return;
const setState = (expanded) => {
button.setAttribute('aria-expanded', String(expanded));
body.hidden = !expanded;
button.textContent = expanded ? 'Collapse' : 'Expand';
};
setState(button.getAttribute('aria-expanded') !== 'false');
button.addEventListener('click', () => {
const expanded = button.getAttribute('aria-expanded') === 'true';
setState(!expanded);
});
});
}
function setupSimplexToolkit() {
const panel = ui.simplex;
if (!panel?.select || !panel.inputs || !panel.runBtn || !panel.result) return;
if (!panel.select.options.length) {
SIMPLEX_OPERATOR_SPECS.forEach(spec => {
const option = document.createElement('option');
option.value = spec.key;
option.textContent = spec.label;
panel.select.appendChild(option);
});
}
if (!panel.select.value && SIMPLEX_OPERATOR_SPECS.length) {
panel.select.value = SIMPLEX_OPERATOR_SPECS[0].key;
}
let activeSpec = null;
let activeControls = {};
const renderInputs = () => {
activeControls = {};
panel.inputs.innerHTML = '';
activeSpec = SIMPLEX_OPERATOR_INDEX[panel.select.value] ?? null;
if (!activeSpec) return;
activeSpec.args.forEach(arg => {
const field = document.createElement('div');
field.className = 'simplex-field';
const label = document.createElement('label');