-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1203 lines (1127 loc) · 34.5 KB
/
index.js
File metadata and controls
1203 lines (1127 loc) · 34.5 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
export const STANDARD_NAME = "ZeroLocus62";
export const BASE62 =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
export const SEP = ".";
export const LOCUS_SEP = "-";
export const ESCAPE = BASE62[0];
export const TYPE_ORDER = "ABCDEFG";
export const TYPE_TABLE = Object.freeze([
...Array.from({ length: 15 }, (_, index) => ["A", index + 1]),
...Array.from({ length: 14 }, (_, index) => ["B", index + 2]),
...Array.from({ length: 13 }, (_, index) => ["C", index + 3]),
...Array.from({ length: 12 }, (_, index) => ["D", index + 4]),
["E", 6],
["E", 7],
["E", 8],
["F", 4],
["G", 2],
]);
export const TYPE_CHARS = BASE62.slice(1, 1 + TYPE_TABLE.length);
export const MAX_SMALL_VALUE = 7;
export const DIRECT_ROW_CAPACITY = 58;
export const SMALL_PAIR_MARKER = BASE62[58];
export const SMALL_POSITIVE_MARKER = BASE62[59];
export const POSITIVE_SPARSE_MARKER = BASE62[60];
export const SIGNED_SPARSE_MARKER = BASE62[61];
export const BASE62_INDEX = Object.freeze(
Object.fromEntries(
Array.from(BASE62, (character, value) => [character, value]),
),
);
export const TYPE_INDEX = new Map(
TYPE_TABLE.map(([group, rank], index) => [`${group}${rank}`, index]),
);
export const TYPE_CHAR_INDEX = Object.freeze(
Object.fromEntries(
Array.from(TYPE_CHARS, (character, index) => [character, index]),
),
);
function toBigInt(value, name) {
if (typeof value === "bigint") {
return value;
}
if (typeof value === "number") {
if (!Number.isSafeInteger(value)) {
throw new RangeError(`${name} must be a safe integer`);
}
return BigInt(value);
}
if (typeof value === "string" && /^-?\d+$/.test(value)) {
return BigInt(value);
}
throw new TypeError(`${name} must be an integer`);
}
function toSafeInteger(value, name) {
const integer = toBigInt(value, name);
if (integer > BigInt(Number.MAX_SAFE_INTEGER)) {
throw new RangeError(`${name} exceeds supported safe integer range`);
}
if (integer < BigInt(Number.MIN_SAFE_INTEGER)) {
throw new RangeError(`${name} exceeds supported safe integer range`);
}
return Number(integer);
}
function toNonNegativeSafeInteger(value, name) {
const integer = toSafeInteger(value, name);
if (integer < 0) {
throw new RangeError(`${name} must be non-negative`);
}
return integer;
}
function zigZagEncode(value) {
return value >= 0 ? 2 * value : -2 * value - 1;
}
function zigZagDecode(value) {
return value % 2 === 0 ? value / 2 : -Math.floor(value / 2) - 1;
}
function coerceFactor(factor) {
if (factor instanceof Factor) {
return factor;
}
if (factor && typeof factor === "object") {
return new Factor(factor.group, factor.rank, factor.mask);
}
throw new TypeError("factor must be a Factor or factor-like object");
}
function normalizeSummands(summands, factors) {
if (!Array.isArray(summands)) {
throw new TypeError("summands must be an array");
}
return summands.map((row) => {
if (!Array.isArray(row) || row.length !== factors.length) {
throw new RangeError("summand row factor count mismatch");
}
return row.map((weights, index) => {
if (!Array.isArray(weights)) {
throw new RangeError("highest-weight entry must be an array");
}
if (weights.length !== factors[index].rank) {
throw new RangeError(
"highest-weight length must match the Dynkin rank",
);
}
return weights.map((coefficient) =>
toSafeInteger(coefficient, "highest-weight coefficient"),
);
});
});
}
function compareLexicographic(left, right) {
if (left < right) {
return -1;
}
if (left > right) {
return 1;
}
return 0;
}
export class Factor {
constructor(group, rank, mask) {
this.group = String(group);
this.rank = toNonNegativeSafeInteger(rank, "rank");
this.mask = toBigInt(mask, "mask");
Object.freeze(this);
}
markedNodes() {
const nodes = [];
for (let node = 0; node < this.rank; node += 1) {
if (((this.mask >> BigInt(node)) & 1n) === 1n) {
nodes.push(node + 1);
}
}
return nodes;
}
marked_nodes() {
return this.markedNodes();
}
}
export function isValidTypeRank(group, rank) {
return (
(group === "A" && rank >= 1) ||
(group === "B" && rank >= 2) ||
(group === "C" && rank >= 3) ||
(group === "D" && rank >= 4) ||
(group === "E" && (rank === 6 || rank === 7 || rank === 8)) ||
(group === "F" && rank === 4) ||
(group === "G" && rank === 2)
);
}
export function validateTypeRank(group, rank) {
if (!isValidTypeRank(group, rank)) {
throw new RangeError(`invalid Dynkin type/rank pair ${group}${rank}`);
}
}
function validateFactor(factor) {
validateTypeRank(factor.group, factor.rank);
if (!(1n <= factor.mask && factor.mask < 1n << BigInt(factor.rank))) {
throw new RangeError("mask out of range");
}
}
function maskWidth(rank) {
let width = 0;
let capacity = 1n;
const limit = (1n << BigInt(rank)) - 2n;
while (capacity <= limit) {
width += 1;
capacity *= 62n;
}
return width;
}
function encodeCharacters(value, width) {
const integerValue = toBigInt(value, "value");
if (width < 0) {
throw new RangeError("width must be non-negative");
}
if (width === 0) {
if (integerValue !== 0n) {
throw new RangeError("non-zero value does not fit in width 0");
}
return "";
}
if (!(0n <= integerValue && integerValue < 62n ** BigInt(width))) {
throw new RangeError("value does not fit in character width");
}
let remaining = integerValue;
const characters = Array.from({ length: width }, () => "0");
for (let index = width - 1; index >= 0; index -= 1) {
characters[index] = BASE62[Number(remaining % 62n)];
remaining /= 62n;
}
return characters.join("");
}
function decodeCharacters(text) {
let value = 0n;
for (const character of text) {
const charValue = BASE62_INDEX[character];
if (charValue === undefined) {
throw new RangeError(
`invalid Base62 character ${JSON.stringify(character)}`,
);
}
value = value * 62n + BigInt(charValue);
}
return value;
}
function encodeNatural(value) {
const integerValue = toBigInt(value, "natural");
if (integerValue <= 0n) {
throw new RangeError("natural must be positive");
}
let width = 1;
let capacity = 62n;
while (integerValue >= capacity) {
width += 1;
capacity *= 62n;
}
return encodeCharacters(integerValue, width);
}
function encodeFactor(factor) {
validateFactor(factor);
const width = maskWidth(factor.rank);
const index = TYPE_INDEX.get(`${factor.group}${factor.rank}`);
if (index !== undefined) {
return TYPE_CHARS[index] + encodeCharacters(factor.mask - 1n, width);
}
const rankCharacters = encodeNatural(factor.rank);
return (
ESCAPE +
factor.group +
encodeCharacters(rankCharacters.length, 1) +
rankCharacters +
encodeCharacters(factor.mask - 1n, width)
);
}
function decodeFactor(text, position) {
if (position >= text.length) {
throw new RangeError("unexpected end decoding factor");
}
let group;
let rank;
let nextPosition = position;
const leadCharacter = text[position];
if (leadCharacter === ESCAPE) {
if (position + 3 > text.length) {
throw new RangeError("factor escape truncated");
}
group = text[position + 1];
if (!TYPE_ORDER.includes(group)) {
throw new RangeError(`unknown Dynkin type ${JSON.stringify(group)}`);
}
const rankLength = Number(decodeCharacters(text[position + 2]));
if (rankLength <= 0) {
throw new RangeError("escaped rank length must be positive");
}
const start = position + 3;
const end = start + rankLength;
if (end > text.length) {
throw new RangeError("escaped rank truncated");
}
rank = toSafeInteger(decodeCharacters(text.slice(start, end)), "rank");
nextPosition = end;
} else {
const index = TYPE_CHAR_INDEX[leadCharacter];
if (index === undefined) {
throw new RangeError(
`unknown standard factor character ${JSON.stringify(leadCharacter)}`,
);
}
[group, rank] = TYPE_TABLE[index];
nextPosition = position + 1;
}
validateTypeRank(group, rank);
const end = nextPosition + maskWidth(rank);
if (end > text.length) {
throw new RangeError("mask truncated");
}
const mask =
end > nextPosition
? decodeCharacters(text.slice(nextPosition, end)) + 1n
: 1n;
if (!(1n <= mask && mask < 1n << BigInt(rank))) {
throw new RangeError("mask out of range");
}
return [new Factor(group, rank, mask), end];
}
function encodeDescriptor(value) {
const integer = toSafeInteger(value, "descriptor");
if (integer <= 0) {
throw new RangeError("descriptor must be positive");
}
if (integer <= 61) {
return BASE62[integer];
}
const characters = encodeNatural(integer);
if (characters.length > 61) {
throw new RangeError("descriptor length exceeds hard limit");
}
return ESCAPE + encodeCharacters(characters.length, 1) + characters;
}
function decodeDescriptor(text, position, name) {
if (position >= text.length) {
throw new RangeError(`unexpected end decoding ${name}`);
}
const lead = BASE62_INDEX[text[position]];
if (lead === undefined) {
throw new RangeError(
`invalid Base62 character in ${name} ${JSON.stringify(text[position])}`,
);
}
if (lead !== 0) {
return [lead, position + 1];
}
if (position + 2 > text.length) {
throw new RangeError(`${name} truncated`);
}
const width = Number(decodeCharacters(text[position + 1]));
if (width <= 0) {
throw new RangeError(`${name} length must be positive`);
}
const start = position + 2;
const end = start + width;
if (end > text.length) {
throw new RangeError(`${name} truncated`);
}
const value = toSafeInteger(decodeCharacters(text.slice(start, end)), name);
if (value <= 61) {
throw new RangeError(`escaped ${name} must be at least 62`);
}
return [value, end];
}
function statesWidth(states) {
let width = 0;
let capacity = 1n;
const required = toBigInt(states, "states");
while (capacity < required) {
width += 1;
capacity *= 62n;
}
return width;
}
function binomial(n, k) {
if (k < 0 || k > n) {
return 0n;
}
let choose = Math.min(k, n - k);
let value = 1n;
for (let index = 1; index <= choose; index += 1) {
value = (value * BigInt(n - choose + index)) / BigInt(index);
}
return value;
}
function rankSupport(totalDynkinRank, positions) {
let rank = 0n;
let previous = -1;
for (let index = 0; index < positions.length; index += 1) {
const position = positions[index];
for (let candidate = previous + 1; candidate < position; candidate += 1) {
rank += binomial(
totalDynkinRank - 1 - candidate,
positions.length - 1 - index,
);
}
previous = position;
}
return rank;
}
function unrankSupport(totalDynkinRank, count, rank) {
const positions = [];
let nextMin = 0;
let remainingRank = toBigInt(rank, "support rank");
for (let index = 0; index < count; index += 1) {
let found = false;
for (let position = nextMin; position < totalDynkinRank; position += 1) {
const block = binomial(totalDynkinRank - 1 - position, count - 1 - index);
if (remainingRank < block) {
positions.push(position);
nextMin = position + 1;
found = true;
break;
}
remainingRank -= block;
}
if (!found) {
throw new RangeError("support rank out of range");
}
}
if (remainingRank !== 0n) {
throw new RangeError("support rank out of range");
}
return positions;
}
function signedDigit(value) {
if (value === 0) {
throw new RangeError("signed sparse rows encode only non-zero values");
}
return zigZagEncode(value) - 1;
}
function decodeSignedDigit(value) {
return zigZagDecode(value + 1);
}
function directSmallLimit(totalDynkinRank, maxSmallValue = MAX_SMALL_VALUE) {
return Math.min(
maxSmallValue,
Math.floor(DIRECT_ROW_CAPACITY / totalDynkinRank),
);
}
function unpackDigits(value, base, count) {
let remaining = toBigInt(value, "packed value");
const digits = Array.from({ length: count }, () => 0);
for (let index = count - 1; index >= 0; index -= 1) {
digits[index] = Number(remaining % BigInt(base));
remaining /= BigInt(base);
}
if (remaining !== 0n) {
throw new RangeError("packed value exceeds range");
}
return digits;
}
function splitFlatRow(flatCoefficients, factors) {
const row = [];
let offset = 0;
for (const factor of factors) {
row.push(flatCoefficients.slice(offset, offset + factor.rank));
offset += factor.rank;
}
return row;
}
function rowValue(digits, base) {
let value = 0n;
for (const digit of digits) {
value = value * BigInt(base) + BigInt(digit);
}
return value;
}
function encodeSummand(row, totalDynkinRank) {
const flatCoefficients = row.flat();
const positions = [];
const values = [];
for (let index = 0; index < flatCoefficients.length; index += 1) {
if (flatCoefficients[index] !== 0) {
positions.push(index);
values.push(flatCoefficients[index]);
}
}
const supportSize = positions.length;
const smallLimit = directSmallLimit(totalDynkinRank);
const directPairOffset = totalDynkinRank * smallLimit;
const directPairCapacity =
directPairOffset + Number(binomial(totalDynkinRank, 2));
if (supportSize === 1 && values[0] >= 1 && values[0] <= smallLimit) {
return BASE62[(values[0] - 1) * totalDynkinRank + positions[0]];
}
if (
directPairCapacity <= DIRECT_ROW_CAPACITY &&
supportSize === 2 &&
values[0] === 1 &&
values[1] === 1
) {
return BASE62[
directPairOffset + Number(rankSupport(totalDynkinRank, positions))
];
}
if (supportSize === 2 && values[0] === 1 && values[1] === 1) {
return (
SMALL_PAIR_MARKER +
encodeCharacters(
rankSupport(totalDynkinRank, positions),
statesWidth(binomial(totalDynkinRank, 2)),
)
);
}
const signed = values.some((value) => value < 0);
if (
!signed &&
values.every((value) => value >= 1 && value <= MAX_SMALL_VALUE)
) {
let text = SMALL_POSITIVE_MARKER + encodeDescriptor(supportSize + 1);
if (supportSize === 0) {
return text;
}
text += encodeCharacters(
rankSupport(totalDynkinRank, positions),
statesWidth(binomial(totalDynkinRank, supportSize)),
);
text += encodeCharacters(
rowValue(
values.map((value) => value - 1),
MAX_SMALL_VALUE,
),
statesWidth(BigInt(MAX_SMALL_VALUE) ** BigInt(supportSize)),
);
return text;
}
const digits = signed
? values.map((value) => signedDigit(value))
: values.map((value) => value - 1);
let text =
(signed ? SIGNED_SPARSE_MARKER : POSITIVE_SPARSE_MARKER) +
encodeDescriptor(supportSize + 1);
if (supportSize === 0) {
return text;
}
text += encodeCharacters(
rankSupport(totalDynkinRank, positions),
statesWidth(binomial(totalDynkinRank, supportSize)),
);
const base = Math.max(2, Math.max(1, ...digits) + 1);
text += encodeDescriptor(base);
text += encodeCharacters(
rowValue(digits, base),
statesWidth(BigInt(base) ** BigInt(supportSize)),
);
return text;
}
function encodeRankBound(k) {
const value = toBigInt(k, "rank bound");
if (value < 0n) {
throw new RangeError("rank bound must be non-negative");
}
if (value === 0n) {
return BASE62[0];
}
let remaining = value;
const characters = [];
while (remaining > 0n) {
characters.push(BASE62[Number(remaining % 62n)]);
remaining /= 62n;
}
return characters.reverse().join("");
}
function decodeRankBound(text) {
if (!text) {
throw new RangeError("rank bound text must be non-empty");
}
if (text.length > 1 && BASE62_INDEX[text[0]] === 0) {
throw new RangeError("rank bound has leading zeros");
}
let value = 0n;
for (const character of text) {
const charValue = BASE62_INDEX[character];
if (charValue === undefined) {
throw new RangeError(
`invalid Base62 character in rank bound ${JSON.stringify(character)}`,
);
}
value = value * 62n + BigInt(charValue);
}
return toSafeInteger(value, "rank bound");
}
function encodeBundleText(summands, totalDynkinRank) {
return summands.map((row) => encodeSummand(row, totalDynkinRank)).join("");
}
function decodeBundleText(bundleText, factors, totalDynkinRank) {
const summands = [];
let position = 0;
const smallLimit = directSmallLimit(totalDynkinRank);
const directPairOffset = totalDynkinRank * smallLimit;
const directPairCapacity =
directPairOffset + Number(binomial(totalDynkinRank, 2));
while (position < bundleText.length) {
const lead = bundleText[position];
const leadValue = BASE62_INDEX[lead];
if (leadValue === undefined) {
throw new RangeError(
`invalid bundle row lead character ${JSON.stringify(lead)}`,
);
}
if (smallLimit > 0 && leadValue < directPairOffset) {
const flatCoefficients = Array.from({ length: totalDynkinRank }, () => 0);
flatCoefficients[leadValue % totalDynkinRank] =
Math.floor(leadValue / totalDynkinRank) + 1;
position += 1;
summands.push(splitFlatRow(flatCoefficients, factors));
continue;
}
if (
directPairCapacity <= DIRECT_ROW_CAPACITY &&
leadValue >= directPairOffset &&
leadValue < directPairCapacity
) {
const flatCoefficients = Array.from({ length: totalDynkinRank }, () => 0);
for (const supportPosition of unrankSupport(
totalDynkinRank,
2,
BigInt(leadValue - directPairOffset),
)) {
flatCoefficients[supportPosition] = 1;
}
position += 1;
summands.push(splitFlatRow(flatCoefficients, factors));
continue;
}
if (lead === SMALL_PAIR_MARKER) {
position += 1;
const supportEnd = position + statesWidth(binomial(totalDynkinRank, 2));
if (supportEnd > bundleText.length) {
throw new RangeError("pair support rank truncated");
}
const flatCoefficients = Array.from({ length: totalDynkinRank }, () => 0);
for (const supportPosition of unrankSupport(
totalDynkinRank,
2,
decodeCharacters(bundleText.slice(position, supportEnd)),
)) {
flatCoefficients[supportPosition] = 1;
}
position = supportEnd;
summands.push(splitFlatRow(flatCoefficients, factors));
continue;
}
if (lead === SMALL_POSITIVE_MARKER) {
position += 1;
let supportSizePlusOne;
[supportSizePlusOne, position] = decodeDescriptor(
bundleText,
position,
"support size",
);
const supportSize = supportSizePlusOne - 1;
if (supportSize < 0 || supportSize > totalDynkinRank) {
throw new RangeError("support size out of range");
}
const flatCoefficients = Array.from({ length: totalDynkinRank }, () => 0);
if (supportSize === 0) {
summands.push(splitFlatRow(flatCoefficients, factors));
continue;
}
const supportEnd =
position + statesWidth(binomial(totalDynkinRank, supportSize));
if (supportEnd > bundleText.length) {
throw new RangeError("support rank truncated");
}
const supportPositions = unrankSupport(
totalDynkinRank,
supportSize,
decodeCharacters(bundleText.slice(position, supportEnd)),
);
position = supportEnd;
const valueEnd =
position + statesWidth(BigInt(MAX_SMALL_VALUE) ** BigInt(supportSize));
if (valueEnd > bundleText.length) {
throw new RangeError("value payload truncated");
}
const values = unpackDigits(
decodeCharacters(bundleText.slice(position, valueEnd)),
MAX_SMALL_VALUE,
supportSize,
).map((digit) => digit + 1);
position = valueEnd;
for (let index = 0; index < supportPositions.length; index += 1) {
flatCoefficients[supportPositions[index]] = values[index];
}
summands.push(splitFlatRow(flatCoefficients, factors));
continue;
}
if (lead !== POSITIVE_SPARSE_MARKER && lead !== SIGNED_SPARSE_MARKER) {
throw new RangeError(
`invalid bundle row lead character ${JSON.stringify(lead)}`,
);
}
const signed = lead === SIGNED_SPARSE_MARKER;
position += 1;
let supportSizePlusOne;
[supportSizePlusOne, position] = decodeDescriptor(
bundleText,
position,
"support size",
);
const supportSize = supportSizePlusOne - 1;
if (supportSize < 0 || supportSize > totalDynkinRank) {
throw new RangeError("support size out of range");
}
const flatCoefficients = Array.from({ length: totalDynkinRank }, () => 0);
if (supportSize === 0) {
summands.push(splitFlatRow(flatCoefficients, factors));
continue;
}
const supportWidth = statesWidth(binomial(totalDynkinRank, supportSize));
const supportEnd = position + supportWidth;
if (supportEnd > bundleText.length) {
throw new RangeError("support rank truncated");
}
const supportRank = decodeCharacters(
bundleText.slice(position, supportEnd),
);
if (supportRank >= binomial(totalDynkinRank, supportSize)) {
throw new RangeError("support rank out of range");
}
position = supportEnd;
const supportPositions = unrankSupport(
totalDynkinRank,
supportSize,
supportRank,
);
let base;
[base, position] = decodeDescriptor(bundleText, position, "value base");
if (base < 2) {
throw new RangeError("value base must be at least 2");
}
const valueWidth = statesWidth(BigInt(base) ** BigInt(supportSize));
const valueEnd = position + valueWidth;
if (valueEnd > bundleText.length) {
throw new RangeError("value payload truncated");
}
const digits = unpackDigits(
decodeCharacters(bundleText.slice(position, valueEnd)),
base,
supportSize,
);
position = valueEnd;
const values = signed
? digits.map((digit) => decodeSignedDigit(digit))
: digits.map((digit) => digit + 1);
for (let index = 0; index < supportPositions.length; index += 1) {
flatCoefficients[supportPositions[index]] = values[index];
}
summands.push(splitFlatRow(flatCoefficients, factors));
}
return summands;
}
function reorder(order, factors, summands) {
return [
order.map((index) => factors[index]),
summands.map((row) => order.map((index) => row[index].slice())),
];
}
function serializeWeights(weights) {
return `[${weights.join(",")}]`;
}
function flatRow(row) {
return row.flat();
}
function compareIntegerArrays(left, right) {
const sharedLength = Math.min(left.length, right.length);
for (let index = 0; index < sharedLength; index += 1) {
if (left[index] < right[index]) {
return -1;
}
if (left[index] > right[index]) {
return 1;
}
}
return left.length - right.length;
}
function compareRowCertificates(left, right) {
const sharedLength = Math.min(left.length, right.length);
for (let index = 0; index < sharedLength; index += 1) {
const comparison = compareIntegerArrays(left[index], right[index]);
if (comparison !== 0) {
return comparison;
}
}
return left.length - right.length;
}
function compareCertificates(left, right) {
const sharedLength = Math.min(left.length, right.length);
for (let index = 0; index < sharedLength; index += 1) {
const comparison = compareRowCertificates(left[index], right[index]);
if (comparison !== 0) {
return comparison;
}
}
return left.length - right.length;
}
function equalFactorBlocks(factors) {
const factorCodes = factors.map((factor) => encodeFactor(factor));
const blocks = [];
let start = 0;
for (let stop = 1; stop <= factors.length; stop += 1) {
if (stop === factors.length || factorCodes[stop] !== factorCodes[start]) {
if (stop - start > 1) {
blocks.push(
Array.from({ length: stop - start }, (_, index) => start + index),
);
}
start = stop;
}
}
return blocks;
}
function singleSummandFactorOrder(factors, summand) {
const order = Array.from({ length: factors.length }, (_, index) => index);
for (const block of equalFactorBlocks(factors)) {
const sortedBlock = block.slice().sort((left, right) => {
const comparison = compareIntegerArrays(summand[left], summand[right]);
return comparison === 0 ? left - right : comparison;
});
for (let index = 0; index < block.length; index += 1) {
order[block[index]] = sortedBlock[index];
}
}
return order;
}
function factorBlocks(factors) {
const factorCodes = factors.map((factor) => encodeFactor(factor));
const blocks = [];
let start = 0;
for (let stop = 1; stop <= factors.length; stop += 1) {
if (stop === factors.length || factorCodes[stop] !== factorCodes[start]) {
blocks.push(
Array.from({ length: stop - start }, (_, index) => start + index),
);
start = stop;
}
}
return blocks;
}
function refineRowGroups(groups, rows, factorIndex) {
const refined = [];
for (const group of groups) {
const buckets = new Map();
for (const rowIndex of group) {
const value = rows[rowIndex][factorIndex];
const key = JSON.stringify(value);
if (!buckets.has(key)) {
buckets.set(key, { value, rowIndices: [] });
}
buckets.get(key).rowIndices.push(rowIndex);
}
for (const { rowIndices } of [...buckets.values()].sort((left, right) =>
compareIntegerArrays(left.value, right.value),
)) {
refined.push(rowIndices);
}
}
return refined;
}
function emptySuffixCertificate(groups) {
return groups.flatMap((group) => group.map(() => []));
}
function prependSuffixCertificate(
factorIndex,
suffixCertificate,
groups,
rows,
) {
const certificate = [];
let offset = 0;
for (const group of groups) {
const value = rows[group[0]][factorIndex];
for (const suffix of suffixCertificate.slice(
offset,
offset + group.length,
)) {
certificate.push(value.concat(suffix));
}
offset += group.length;
}
return certificate;
}
function columnSignature(index, summands, summandsF) {
const parts = [summands.map((row) => row[index])];
if (summandsF !== null) {
parts.push(summandsF.map((row) => row[index]));
}
return JSON.stringify(parts);
}
function canonicalFactorOrderDp(factors, summands, summandsF) {
const blocks = factorBlocks(factors);
const positionBlocks = Array.from({ length: factors.length });
for (const block of blocks) {
for (const position of block) {
positionBlocks[position] = block;
}
}
const initialGroups = [
Array.from({ length: summands.length }, (_, index) => index),
];
const initialGroupsF =
summandsF === null
? null
: [Array.from({ length: summandsF.length }, (_, index) => index)];
const memo = new Map();
const columnSignatures = Array.from({ length: factors.length }, (_, index) =>
columnSignature(index, summands, summandsF),
);
function bestSuffix(groups, groupsF, remaining) {
if (remaining.length === 0) {
const parts = [emptySuffixCertificate(groups)];
if (summandsF !== null) {
parts.push(emptySuffixCertificate(groupsF));
}
return [[], parts];
}
const key = JSON.stringify([groups, groupsF, remaining]);
const cached = memo.get(key);
if (cached !== undefined) {
return cached;
}
const depth = factors.length - remaining.length;
const block = positionBlocks[depth];
const candidates = remaining.filter((index) => block.includes(index));
const seenSignatures = new Set();
let bestOrder = null;
let bestCertificate = null;
for (const candidate of candidates) {
const signature = columnSignatures[candidate];
if (seenSignatures.has(signature)) {
continue;
}
seenSignatures.add(signature);
const nextRemaining = remaining.filter((index) => index !== candidate);
const nextGroups = refineRowGroups(groups, summands, candidate);
const nextGroupsF =
summandsF === null
? null
: refineRowGroups(groupsF, summandsF, candidate);
const [suffixOrder, suffixCertificate] = bestSuffix(
nextGroups,
nextGroupsF,
nextRemaining,
);
const currentCertificate = [
prependSuffixCertificate(
candidate,
suffixCertificate[0],
nextGroups,
summands,
),
];
if (summandsF !== null) {
currentCertificate.push(
prependSuffixCertificate(
candidate,
suffixCertificate[1],
nextGroupsF,
summandsF,
),
);
}
if (
bestCertificate === null ||
compareCertificates(currentCertificate, bestCertificate) < 0
) {
bestCertificate = currentCertificate;
bestOrder = [candidate, ...suffixOrder];
}
}
const result = [bestOrder, bestCertificate];
memo.set(key, result);
return result;