-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest.js
More file actions
3168 lines (3002 loc) · 106 KB
/
test.js
File metadata and controls
3168 lines (3002 loc) · 106 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
#!/usr/bin/env node
//
// Extracts the <script> block from index.html and runs unit tests
// against the pure-logic functions (no DOM required).
//
// Usage: node test.js
//
const fs = require("fs");
const path = require("path");
// --- Release footer must match package.json (commit-and-tag-version keeps them in sync) ---
const html = fs.readFileSync(path.join(__dirname, "index.html"), "utf-8");
const pkg = JSON.parse(
fs.readFileSync(path.join(__dirname, "package.json"), "utf-8"),
);
const footerMatch = html.match(/<span id="lambs-app-version">([^<]*)<\/span>/);
if (!footerMatch) {
console.error('index.html: missing <span id="lambs-app-version">...</span>');
process.exit(1);
}
const footerVersion = footerMatch[1].trim();
if (footerVersion !== pkg.version) {
console.error(
`Version mismatch: package.json "${pkg.version}" vs index.html footer "${footerVersion}". ` +
"Run npm run release (commit-and-tag-version) so both stay aligned.",
);
process.exit(1);
}
// --- Extract pure-logic JS from index.html (everything before DOM code) ---
const scriptMatch = html.match(/<script>([\s\S]*?)<\/script>/);
if (!scriptMatch) {
console.error("No <script> block found");
process.exit(1);
}
// Cut at the TAB SWITCHING section — everything before it is pure logic
// (DOM-touching basket functions get a mock document so they don't crash)
const CUTOFF =
"// ================================================================\n// TAB SWITCHING";
const pureJS = scriptMatch[1].split(CUTOFF)[0];
const wrappedJS = `
(function(exports) {
// Minimal DOM mock for basket functions that call renderBasket()
var document = { getElementById: function() {
return { textContent: '', innerHTML: '', disabled: false, style: {} };
}};
${pureJS}
exports.cleanSequence = cleanSequence;
exports.validateSequence = validateSequence;
exports.validateBasketNames = validateBasketNames;
exports.buildRuler = buildRuler;
exports.detectLiabilities = detectLiabilities;
exports.alignVGene = alignVGene;
exports.findClosestGermline = findClosestGermline;
exports.AA_PROPERTY = AA_PROPERTY;
exports.V_GENE_DB = V_GENE_DB;
exports.parseCSV = parseCSV;
exports.escapeHtml = escapeHtml;
exports.globalAlign = globalAlign;
exports.pairwiseIdentity = pairwiseIdentity;
exports.clusterSequences = clusterSequences;
exports.starMSA = starMSA;
exports.computeConservation = computeConservation;
exports.consensusSequenceForAnalysis = consensusSequenceForAnalysis;
exports.LIABILITY_ORDER_ACTIVE = LIABILITY_ORDER_ACTIVE;
exports.msaRawToMasterAligned = msaRawToMasterAligned;
exports.filterBasketByLiabilityFilters = filterBasketByLiabilityFilters;
exports.entryHasFilteredLiability = entryHasFilteredLiability;
exports.buildMsaLiabilityColorMap = buildMsaLiabilityColorMap;
exports.KD_HYDROPHOBICITY = KD_HYDROPHOBICITY;
exports.AGG_WINDOW = AGG_WINDOW;
exports.AGG_THRESHOLD = AGG_THRESHOLD;
exports.detectCDR3 = detectCDR3;
exports.calcMW = calcMW;
exports.calcNetCharge = calcNetCharge;
exports.calcPI = calcPI;
exports.calcGRAVY = calcGRAVY;
exports.computeSequenceProperties = computeSequenceProperties;
exports.calcPercentile = calcPercentile;
exports.alignConstantRegion = alignConstantRegion;
exports.findConstantRegion = findConstantRegion;
exports.CONST_REGION_DB = CONST_REGION_DB;
exports.EXAMPLE_CSV = EXAMPLE_CSV;
exports.csvChainColumnIndices = csvChainColumnIndices;
exports.alignJGene = alignJGene;
exports.findClosestJGene = findClosestJGene;
exports.J_GENE_DB = J_GENE_DB;
exports.buildGermlineAlignmentContext = buildGermlineAlignmentContext;
exports.buildMergedGermlineA2 = buildMergedGermlineA2;
})(this);
`;
const ctx = {};
new Function(wrappedJS).call(ctx);
const {
cleanSequence,
validateSequence,
validateBasketNames,
buildRuler,
detectLiabilities,
alignVGene,
findClosestGermline,
AA_PROPERTY,
V_GENE_DB,
parseCSV,
escapeHtml,
globalAlign,
pairwiseIdentity,
clusterSequences,
starMSA,
computeConservation,
consensusSequenceForAnalysis,
LIABILITY_ORDER_ACTIVE,
msaRawToMasterAligned,
filterBasketByLiabilityFilters,
entryHasFilteredLiability,
buildMsaLiabilityColorMap,
KD_HYDROPHOBICITY,
AGG_WINDOW,
AGG_THRESHOLD,
detectCDR3,
calcMW,
calcNetCharge,
calcPI,
calcGRAVY,
computeSequenceProperties,
calcPercentile,
alignConstantRegion,
findConstantRegion,
CONST_REGION_DB,
EXAMPLE_CSV,
csvChainColumnIndices,
alignJGene,
findClosestJGene,
J_GENE_DB,
buildGermlineAlignmentContext,
buildMergedGermlineA2,
} = ctx;
// --- Test harness ---
let passed = 0,
failed = 0;
function assert(condition, msg) {
if (condition) {
passed++;
} else {
failed++;
console.error(` FAIL: ${msg}`);
}
}
function assertApprox(actual, expected, tol, msg) {
assert(
Math.abs(actual - expected) <= tol,
`${msg} (got ${actual}, expected ~${expected})`,
);
}
function section(name) {
console.log(`\n--- ${name} ---`);
}
// ============================================================
// cleanSequence
// ============================================================
section("cleanSequence");
assert(cleanSequence("evqlves") === "EVQLVES", "converts to uppercase");
assert(cleanSequence("EVQ LVES") === "EVQLVES", "strips spaces");
assert(
cleanSequence(">header\nEVQL\nVES") === "EVQLVES",
"strips FASTA header",
);
assert(cleanSequence(" \n ") === "", "empty after stripping");
assert(cleanSequence("EVQLVES*") === "EVQLVES*", "retains stop codon *");
assert(
cleanSequence(">sp|P12345|MABS_HUMAN\nEVQLVES") === "EVQLVES",
"strips multi-word FASTA header",
);
// ============================================================
// validateSequence
// ============================================================
section("validateSequence");
assert(validateSequence("") === null, "empty string is valid (blank allowed)");
assert(
validateSequence(" ") === null,
"whitespace-only is valid (blank allowed)",
);
assert(validateSequence("EVQLVES") === null, "clean uppercase AA is valid");
assert(validateSequence("evqlves") === null, "lowercase AA is valid");
assert(
validateSequence("EVQ LVES") === null,
"spaces in sequence are valid (stripped)",
);
assert(validateSequence(">header\nEVQLVES") === null, "FASTA format is valid");
assert(validateSequence("EVQLVES*") === null, "trailing stop codon * is valid");
assert(
validateSequence("EVQ*LV*ES") === null,
"embedded stop codons are valid",
);
assert(
validateSequence("EVQ123LVES") !== null,
"digits in sequence are invalid",
);
assert(validateSequence("EVQ1LVES") !== null, "single digit is invalid");
assert(validateSequence("EVQ-LVES") !== null, "dash is invalid");
assert(validateSequence("EVQ_LVES") !== null, "underscore is invalid");
assert(validateSequence("EVQ!LVES") !== null, "exclamation mark is invalid");
assert(validateSequence("EVQ.LVES") !== null, "period is invalid");
// Error string should mention the offending character
const digitErr = validateSequence("EVQ1LVES");
assert(
digitErr && digitErr.includes("1"),
"digit error message mentions the bad char",
);
const symbolErr = validateSequence("EVQ-LV@ES");
assert(
symbolErr && symbolErr.includes("-") && symbolErr.includes("@"),
"symbol error lists all bad chars",
);
// Blank after stripping FASTA header is valid (VH-only mode etc.)
assert(
validateSequence(">header\n") === null,
"FASTA header with no sequence is valid (blank)",
);
// ============================================================
// validateBasketNames
// ============================================================
section("validateBasketNames");
assert(validateBasketNames([]) === null, "empty basket has no duplicate names");
assert(
validateBasketNames([{ id: 1, name: "mAb1", vh: "", vl: "" }]) === null,
"single entry has no duplicate names",
);
assert(
validateBasketNames([
{ id: 1, name: "mAb1", vh: "", vl: "" },
{ id: 2, name: "mAb2", vh: "", vl: "" },
{ id: 3, name: "mAb3", vh: "", vl: "" },
]) === null,
"all unique names passes",
);
assert(
validateBasketNames([
{ id: 1, name: "mAb1", vh: "", vl: "" },
{ id: 2, name: "mAb1", vh: "", vl: "" },
]) !== null,
"duplicate names returns error",
);
const dupeErr = validateBasketNames([
{ id: 1, name: "Alpha", vh: "", vl: "" },
{ id: 2, name: "Beta", vh: "", vl: "" },
{ id: 3, name: "Alpha", vh: "", vl: "" },
{ id: 4, name: "Beta", vh: "", vl: "" },
]);
assert(dupeErr !== null, "multiple duplicates returns error");
assert(dupeErr.includes("Alpha"), "error message names 'Alpha'");
assert(dupeErr.includes("Beta"), "error message names 'Beta'");
assert(
validateBasketNames([
{ id: 1, name: "mAb1", vh: "", vl: "" },
{ id: 2, name: "mAb1", vh: "", vl: "" },
{ id: 3, name: "mAb2", vh: "", vl: "" },
]) !== null,
"one duplicate among uniques is still an error",
);
// ============================================================
// buildRuler
// ============================================================
section("buildRuler");
const r25 = buildRuler(25).join("");
assert(r25[0] === "1", "position 1 at column 0");
assert(r25[8] === "1" && r25[9] === "0", "position 10 at columns 8-9");
assert(r25[18] === "2" && r25[19] === "0", "position 20 at columns 18-19");
assert(r25.length === 25, "ruler length matches input");
const r5 = buildRuler(5).join("");
assert(r5[0] === "1", "short ruler starts with 1");
assert(r5.length === 5, "short ruler correct length");
const r110 = buildRuler(110).join("");
assert(
r110[97] === "1" && r110[98] === "0" && r110[99] === "0",
"position 100 right-aligned to column 99",
);
// ============================================================
// detectLiabilities
// ============================================================
section("detectLiabilities");
// Unpaired cysteine (odd count)
assert(
detectLiabilities("ACDA")["Unp. Cys"]?.length === 1,
"single C = unpaired",
);
assert(!detectLiabilities("ACCA")["Unp. Cys"], "two C = paired, no flag");
// Methionine oxidation
assert(detectLiabilities("AMGA")["Met Ox"]?.includes(1), "M detected at pos 1");
assert(!detectLiabilities("AGGA")["Met Ox"], "no M = no met ox");
// N-linked glycosylation: N-X-S/T where X!=P
assert(
detectLiabilities("ANST")["Glycosyl"]?.length === 3,
"NAS motif flags 3 positions",
);
assert(
!detectLiabilities("ANPA")["Glycosyl"],
"NPS should not flag (but NPA has X=N, check...)",
);
// More specific: NPT should NOT flag because X=P
assert(!detectLiabilities("NPTA")["Glycosyl"], "NPT not flagged (X=P)");
// NAS should flag
const glyc = detectLiabilities("XNASY");
assert(glyc["Glycosyl"]?.includes(1), "glycosyl flags N");
assert(glyc["Glycosyl"]?.includes(2), "glycosyl flags A (middle)");
assert(glyc["Glycosyl"]?.includes(3), "glycosyl flags S (third)");
// Deamidation: NG, NS, NT, NN, NH — both residues flagged
const deamNG = detectLiabilities("ANGA")["Deamid"];
assert(
deamNG?.includes(1) && deamNG?.includes(2),
"NG deamidation flags both N and G",
);
const deamNS = detectLiabilities("ANSA")["Deamid"];
assert(
deamNS?.includes(1) && deamNS?.includes(2),
"NS deamidation flags both N and S",
);
const deamNT = detectLiabilities("ANTA")["Deamid"];
assert(
deamNT?.includes(1) && deamNT?.includes(2),
"NT deamidation flags both N and T",
);
const deamNN = detectLiabilities("ANNA")["Deamid"];
assert(
deamNN?.includes(1) && deamNN?.includes(2),
"NN deamidation flags both Ns",
);
const deamNH = detectLiabilities("ANHA")["Deamid"];
assert(
deamNH?.includes(1) && deamNH?.includes(2),
"NH deamidation flags both N and H",
);
assert(!detectLiabilities("ANDA")["Deamid"], "ND is NOT deamidation");
// Isomerization: DG, DS — both residues flagged
const isoDG = detectLiabilities("ADGA")["Isomer"];
assert(
isoDG?.includes(1) && isoDG?.includes(2),
"DG isomerization flags both D and G",
);
const isoDS = detectLiabilities("ADSA")["Isomer"];
assert(
isoDS?.includes(1) && isoDS?.includes(2),
"DS isomerization flags both D and S",
);
assert(!detectLiabilities("ADPA")["Isomer"], "DP is NOT isomerization");
// Acid-labile cleavage: DP — both residues flagged
const cleavDP = detectLiabilities("ADPA")["Cleavage"];
assert(
cleavDP?.includes(1) && cleavDP?.includes(2),
"DP cleavage flags both D and P",
);
assert(!detectLiabilities("ADGA")["Cleavage"], "DG is NOT cleavage");
// N-terminal Q
assert(
detectLiabilities("QAAA")["N-term Q"]?.[0] === 0,
"leading Q flagged at index 0",
);
assert(!detectLiabilities("AQAA")["N-term Q"], "Q not at N-term = no flag");
assert(!detectLiabilities("")["N-term Q"], "empty sequence = no N-term Q");
// Tryptophan oxidation
// assert(detectLiabilities("AWGA")["Trp Ox"]?.includes(1), "W detected");
// assert(!detectLiabilities("AGGA")["Trp Ox"], "no W = no trp ox");
// ============================================================
// Full VH/VL liability check
// ============================================================
section("detectLiabilities (full sequences)");
const VH =
"EVQLVESGGGLVQPGGSLRLSCAASGFTFSDYWMHWVRQAPGKGLEWVSRINSDGSSTSYADSVKGRFTISRDNAKNTLYLQMNSLRAEDTAVYYCTTDGWGFDYWGQGTLVTVSS";
const vhL = detectLiabilities(VH);
assert(!vhL["Unp. Cys"], "VH has even cysteine count (2)");
// assert(vhL["Met Ox"]?.length === 2, "VH has 2 methionines");
// assert(vhL["Trp Ox"]?.length === 5, "VH has 5 tryptophans");
assert(vhL["Deamid"]?.length > 0, "VH has deamidation sites");
assert(vhL["Isomer"]?.length > 0, "VH has isomerization sites");
assert(!vhL["Glycosyl"], "VH has no N-linked glycosylation");
const VL =
"DIQMTQSPSSLSASVGDRVTITCRASQSISSYLNWYQQKPGKAPKLLIYAASSLQSGVPSRFSGSGSGTDFTLTISSLQPEDFATYYCQQSYSTPLTFGGGTKVEIK";
const vlL = detectLiabilities(VL);
assert(vlL["Met Ox"]?.length === 1, "VL has 1 methionine");
// assert(vlL["Trp Ox"]?.length === 1, "VL has 1 tryptophan");
// ============================================================
// alignVGene (semi-global: germline fully consumed, query free suffix)
// ============================================================
section("alignVGene");
// Identical sequences — same as global alignment
const sg1 = alignVGene("ABCDEF", "ABCDEF");
assert(sg1.identity === 1.0, "identical sequences = 100% identity");
assert(sg1.aligned1 === "ABCDEF", "identical align1");
assert(sg1.aligned2 === "ABCDEF", "identical align2");
assert(sg1.matches === 6 && sg1.total === 6, "identical counts");
// Single mismatch
const sg2 = alignVGene("ABCDEF", "ABXDEF");
assert(
sg2.aligned1.replace(/-/g, "") === "ABCDEF",
"mismatch: query chars preserved",
);
assert(
sg2.aligned2.replace(/-/g, "") === "ABXDEF",
"mismatch: germline chars preserved",
);
assert(sg2.matches === 5, "mismatch: 5 matches");
// Query longer than germline (D/J suffix should be free)
const sg3 = alignVGene("ABCDEFGHIJ", "ABCDEF");
assert(sg3.identity === 1.0, "prefix match = 100% V-gene identity");
assert(
sg3.aligned1.replace(/-/g, "") === "ABCDEFGHIJ",
"long query: all query chars present",
);
const germChars = sg3.aligned2.replace(/-/g, "");
assert(germChars === "ABCDEF", "long query: all germline chars present");
const trailingGaps = sg3.aligned2.slice(-4);
assert(
trailingGaps === "----",
"long query: trailing gaps in germline for D/J suffix",
);
// Germline with insertion relative to query
const sg4 = alignVGene("ABDEF", "ABCDEF");
assert(
sg4.aligned1.replace(/-/g, "") === "ABDEF",
"insertion: query chars preserved",
);
assert(
sg4.aligned2.replace(/-/g, "") === "ABCDEF",
"insertion: germline chars preserved",
);
const gapCount = (sg4.aligned1.match(/-/g) || []).length;
assert(gapCount >= 1, "insertion: at least 1 gap in query");
// Empty sequences
const sg5 = alignVGene("", "");
assert(sg5.identity === 0, "empty sequences = 0 identity");
assert(sg5.aligned1 === "" && sg5.aligned2 === "", "empty aligned strings");
// One empty (query only, no germline)
const sg6 = alignVGene("ABC", "");
assert(sg6.aligned2 === "---", "empty germline: gaps in germline row");
// ============================================================
// findClosestGermline (with a test sequence injected)
// ============================================================
section("findClosestGermline (with test data)");
// Temporarily inject a test germline
V_GENE_DB.human.IGHV["TEST-GENE*01"] = VH.substring(0, 98);
const germTest = findClosestGermline(VH, "VH");
assert(germTest !== null, "finds match with test data");
assert(germTest.gene === "TEST-GENE*01", "correct gene name");
assert(germTest.species === "human", "correct species");
assert(germTest.identity > 0.8, "high identity for near-match");
delete V_GENE_DB.human.IGHV["TEST-GENE*01"];
// ============================================================
// AA_PROPERTY map
// ============================================================
section("AA_PROPERTY");
assert(AA_PROPERTY["A"] === "hydrophobic", "A is hydrophobic");
assert(
AA_PROPERTY["F"] === "aromatic",
"F is aromatic (overrides hydrophobic)",
);
assert(AA_PROPERTY["W"] === "aromatic", "W is aromatic");
assert(AA_PROPERTY["S"] === "polar", "S is polar");
assert(AA_PROPERTY["K"] === "positive", "K is positive");
assert(AA_PROPERTY["D"] === "negative", "D is negative");
assert(AA_PROPERTY["C"] === "special", "C is special");
assert(AA_PROPERTY["G"] === "special", "G is special");
assert(AA_PROPERTY["P"] === "special", "P is special");
// ============================================================
// escapeHtml
// ============================================================
section("escapeHtml");
assert(escapeHtml("a&b") === "a&b", "escapes ampersand");
assert(escapeHtml("<b>") === "<b>", "escapes angle brackets");
assert(escapeHtml('"hi"') === ""hi"", "escapes quotes");
assert(escapeHtml("plain") === "plain", "no-op for plain text");
// ============================================================
// parseCSV
// ============================================================
section("parseCSV");
const csv1 = parseCSV("a,b,c\n1,2,3\n4,5,6\n");
assert(csv1.length === 3, "parseCSV: 3 rows (header + 2 data)");
assert(csv1[0][0] === "a" && csv1[0][2] === "c", "parseCSV: header parsed");
assert(csv1[1][1] === "2", "parseCSV: data cell correct");
const csv2 = parseCSV('name,heavy\n"Seq, 1","ABC"\n');
assert(csv2[1][0] === "Seq, 1", "parseCSV: quoted field with comma");
assert(csv2[1][1] === "ABC", "parseCSV: quoted field value");
const csv3 = parseCSV("a,b\r\n1,2\r\n3,4\r\n");
assert(csv3.length === 3, "parseCSV: handles CRLF line endings");
assert(csv3[2][0] === "3", "parseCSV: CRLF data correct");
const csv4 = parseCSV('a\n"he said ""hi"""\n');
assert(csv4[1][0] === 'he said "hi"', "parseCSV: escaped double quotes");
const csvEmpty = parseCSV("");
assert(csvEmpty.length === 0, "parseCSV: empty string returns no rows");
// ============================================================
// CSV import: heavy and light column names
// ============================================================
section("CSV import: heavy and light columns");
function normHeaders(cells) {
return cells.map((h) => h.trim().toLowerCase());
}
let cci = csvChainColumnIndices(normHeaders(["Name", "Heavy", "Light"]));
assert(
cci.nameCol === 0 && cci.heavyCol === 1 && cci.lightCol === 2,
"csvChainColumnIndices: Name, Heavy, Light in default order",
);
cci = csvChainColumnIndices(normHeaders(["light", "Name", "heavy"]));
assert(
cci.lightCol === 0 && cci.nameCol === 1 && cci.heavyCol === 2,
"csvChainColumnIndices: any column order",
);
const exHdr = normHeaders(parseCSV(EXAMPLE_CSV)[0]);
cci = csvChainColumnIndices(exHdr);
assert(
cci.heavyCol >= 0 &&
cci.lightCol >= 0 &&
exHdr[cci.heavyCol] === "heavy" &&
exHdr[cci.lightCol] === "light",
"EXAMPLE_CSV first row must use literal column names heavy and light",
);
const miniCsv = parseCSV("name,heavy,light\nmAb1,QVQLVES,DIQLTQS\n");
cci = csvChainColumnIndices(normHeaders(miniCsv[0]));
const heavyFromCsv = cleanSequence(miniCsv[1][cci.heavyCol]);
const lightFromCsv = cleanSequence(miniCsv[1][cci.lightCol]);
assert(
heavyFromCsv === "QVQLVES" && lightFromCsv === "DIQLTQS",
"data cells map to heavy and light columns by name",
);
// ============================================================
// globalAlign (full Needleman-Wunsch)
// ============================================================
section("globalAlign");
const ga1 = globalAlign("ABCDEF", "ABCDEF");
assert(ga1.identity === 1.0, "globalAlign: identical = 100%");
assert(ga1.matches === 6 && ga1.total === 6, "globalAlign: identical counts");
const ga2 = globalAlign("ABCDEF", "ABXDEF");
assert(ga2.matches === 5, "globalAlign: single mismatch = 5 matches");
assert(
ga2.aligned1.replace(/-/g, "") === "ABCDEF",
"globalAlign: mismatch query preserved",
);
assert(
ga2.aligned2.replace(/-/g, "") === "ABXDEF",
"globalAlign: mismatch ref preserved",
);
const ga3 = globalAlign("ABCDEF", "ABCXYZDEF");
assert(
ga3.aligned1.replace(/-/g, "") === "ABCDEF",
"globalAlign: insertion query preserved",
);
assert(
ga3.aligned2.replace(/-/g, "") === "ABCXYZDEF",
"globalAlign: insertion ref preserved",
);
const ga4 = globalAlign("", "");
assert(ga4.identity === 0, "globalAlign: empty sequences = 0");
const ga5 = globalAlign("ABC", "");
assert(ga5.aligned1.replace(/-/g, "") === "ABC", "globalAlign: one empty seq1");
assert(ga5.aligned2 === "---", "globalAlign: one empty seq2 gaps");
const ga6 = globalAlign("ABCDEFGHIJ", "ABCDEF");
assert(ga6.matches === 6, "globalAlign: prefix match 6 matches");
assert(ga6.total === 10, "globalAlign: prefix match 10 total positions");
// ============================================================
// pairwiseIdentity
// ============================================================
section("pairwiseIdentity");
const pi1 = pairwiseIdentity(
{ vh: "ABCDEF", vl: "GHIJ" },
{ vh: "ABCDEF", vl: "GHIJ" },
);
assert(pi1 === 1.0, "pairwiseIdentity: identical pairs = 1.0");
const pi2 = pairwiseIdentity(
{ vh: "ABCDEF", vl: "GHIJ" },
{ vh: "XYZXYZ", vl: "WXWX" },
);
assert(pi2 < 0.5, "pairwiseIdentity: dissimilar pairs < 0.5");
const pi3 = pairwiseIdentity({ vh: "", vl: "" }, { vh: "ABC", vl: "DEF" });
assert(pi3 === 0, "pairwiseIdentity: empty entry = 0");
const pi4 = pairwiseIdentity(
{ vh: "ABCDEF", vl: "" },
{ vh: "ABCDEF", vl: "" },
);
assert(pi4 === 1.0, "pairwiseIdentity: VH-only identical = 1.0");
const piStrip1 = pairwiseIdentity(
{
vh:
"EVQLVESGGGLVQPGGSLRLSCAASGFTFSSYGMHWVRQAPGKGLEWVAVIWYDGSNKYYADSVKGRFTISRDNSKNTLYLQMNSLRAEDTAVYYCAR" +
CONST_REGION_DB.human.CH["IGHG1"].s,
vl: "",
},
{
vh: "EVQLVESGGGLVQPGGSLRLSCAASGFTFSSYGMHWVRQAPGKGLEWVAVIWYDGSNKYYADSVKGRFTISRDNSKNTLYLQMNSLRAEDTAVYYCAR",
vl: "",
},
);
assert(
piStrip1 === 1.0,
"pairwiseIdentity: VH+CH vs VH-only (same variable) = 1.0 after constant strip",
);
// ============================================================
// clusterSequences
// ============================================================
section("clusterSequences");
const clEntries = [
{ id: 1, name: "A", vh: "ABCDEF", vl: "GHIJ" },
{ id: 2, name: "B", vh: "ABCDEF", vl: "GHIJ" },
{ id: 3, name: "C", vh: "XYZXYZ", vl: "WXWX" },
];
const cl100 = clusterSequences(clEntries, 100);
assert(
cl100.length >= 2,
"cluster@100%: dissimilar seqs form separate clusters",
);
const cl10 = clusterSequences(clEntries, 10);
assert(
cl10.length >= 1,
"cluster@10%: very low threshold groups more sequences",
);
const clIdentical = clusterSequences(
[
{ id: 1, name: "A", vh: "ABCDEF", vl: "GHIJ" },
{ id: 2, name: "B", vh: "ABCDEF", vl: "GHIJ" },
{ id: 3, name: "C", vh: "ABCDEF", vl: "GHIJ" },
],
70,
);
assert(clIdentical.length === 1, "cluster: 3 identical seqs = 1 cluster");
assert(
clIdentical[0].members.length === 3,
"cluster: single cluster has all 3 members",
);
const clEmpty = clusterSequences([], 70);
assert(clEmpty.length === 0, "cluster: empty input = empty output");
const clSingle = clusterSequences(
[{ id: 1, name: "A", vh: "ABCDEF", vl: "GHIJ" }],
70,
);
assert(clSingle.length === 1, "cluster: single entry = 1 cluster");
assert(
clSingle[0].members.length === 1,
"cluster: single entry cluster size 1",
);
// Verify sorted by size (largest first)
const clSorted = clusterSequences(
[
{ id: 1, name: "A", vh: "ABCDEF", vl: "GHIJ" },
{ id: 2, name: "B", vh: "ABCDEF", vl: "GHIJ" },
{ id: 3, name: "C", vh: "XYZXYZ", vl: "WXWX" },
],
70,
);
assert(
clSorted[0].members.length >= clSorted[clSorted.length - 1].members.length,
"cluster: results sorted largest first",
);
// ============================================================
// MSA liability helpers
// ============================================================
section("MSA liability helpers");
assert(
LIABILITY_ORDER_ACTIVE.indexOf("Trp Ox") < 0,
"LIABILITY_ORDER_ACTIVE excludes Trp Ox",
);
const mapGapped = msaRawToMasterAligned("---MQ");
assert(
mapGapped[0] === 3 && mapGapped[1] === 4,
"msaRawToMasterAligned maps gap-free indices to MSA columns",
);
const colorMap = buildMsaLiabilityColorMap("---MQ", ["Met Ox"]);
assert(
typeof colorMap === "object" && colorMap !== null,
"buildMsaLiabilityColorMap returns an object",
);
assert(
Object.keys(colorMap).length > 0,
"buildMsaLiabilityColorMap finds Met Ox hit in ---MQ",
);
assert(
colorMap[3] && colorMap[3].indexOf("rgba(") >= 0,
"buildMsaLiabilityColorMap maps M at MSA col 3 to an rgba color",
);
assert(
Object.keys(buildMsaLiabilityColorMap("MQ", [])).length === 0,
"buildMsaLiabilityColorMap returns empty map when no highlights selected",
);
const qEntry = { id: 1, name: "Q", vh: "QAAAA", vl: "" };
assert(
entryHasFilteredLiability(qEntry, ["N-term Q"]),
"entryHasFilteredLiability detects N-term Q on VH",
);
assert(
!entryHasFilteredLiability(qEntry, ["Met Ox"]),
"entryHasFilteredLiability false when filter type absent",
);
const kept = filterBasketByLiabilityFilters(
[qEntry, { id: 2, name: "M", vh: "AAAAA", vl: "" }],
["N-term Q"],
);
assert(
kept.length === 1 && kept[0].id === 2,
"filterBasketByLiabilityFilters drops matching entries",
);
// ============================================================
// starMSA
// ============================================================
section("starMSA");
const msa0 = starMSA([]);
assert(msa0.length === 0, "starMSA: empty input");
const msa1 = starMSA(["ABCDEF"]);
assert(msa1.length === 1, "starMSA: single sequence");
assert(msa1[0] === "ABCDEF", "starMSA: single sequence unchanged");
const msa2 = starMSA(["ABCDEF", "ABCDEF"]);
assert(msa2.length === 2, "starMSA: two identical sequences");
assert(msa2[0] === msa2[1], "starMSA: identical sequences aligned identically");
const msa3 = starMSA(["ABCDEF", "ABCDEF", "ABCDEF"]);
assert(msa3.length === 3, "starMSA: three identical");
assert(
msa3[0] === msa3[1] && msa3[1] === msa3[2],
"starMSA: three identical all equal",
);
// All MSA outputs must have equal length
const msa4 = starMSA(["ABCDEF", "ABXDEF", "ABCEF"]);
assert(msa4.length === 3, "starMSA: three similar sequences");
const msaLen = msa4[0].length;
assert(
msa4[1].length === msaLen && msa4[2].length === msaLen,
"starMSA: all outputs same length",
);
// Original residues are preserved (no residue loss)
for (let i = 0; i < msa4.length; i++) {
const original = ["ABCDEF", "ABXDEF", "ABCEF"][i];
const stripped = msa4[i].replace(/-/g, "");
assert(
stripped === original,
"starMSA: residues preserved for seq " + (i + 1),
);
}
// Realistic antibody-like sequences
const msaAb = starMSA([
"EVQLVESGGGLVQPGGSLRLSCAAS",
"EVQLVESGGGLVQPGGSLRLSCAAS",
"EVQLVETGGGLVQPGGSLRLSCAAS",
]);
assert(msaAb.length === 3, "starMSA: antibody-like sequences");
assert(
msaAb[0].length === msaAb[1].length && msaAb[1].length === msaAb[2].length,
"starMSA: antibody-like equal length",
);
// ============================================================
// computeConservation
// ============================================================
section("computeConservation");
const cons0 = computeConservation([]);
assert(cons0.identity.length === 0, "conservation: empty input");
assert(cons0.consensus === "", "conservation: empty consensus");
const cons1 = computeConservation(["QQQ", "QET", "QQS"]);
assert(cons1.identity.length === 3, "conservation: 3 columns");
assert(cons1.identity[0] === 1.0, "conservation: col 1 = 100% (all Q)");
assert(
Math.abs(cons1.identity[1] - 2 / 3) < 0.01,
"conservation: col 2 = 66% (2 Q, 1 E)",
);
assert(
Math.abs(cons1.identity[2] - 1 / 3) < 0.01,
"conservation: col 3 = 33% (Q, T, S all different)",
);
assert(cons1.consensus[0] === "Q", "conservation: consensus pos 1 = Q");
assert(
cons1.consensus[1] === "Q",
"conservation: consensus pos 2 = Q (majority)",
);
// Consensus lowercase when no residue exceeds 50%
const cons2 = computeConservation(["AB", "CD", "EF", "GH"]);
assert(
cons2.consensus[0] === cons2.consensus[0].toLowerCase(),
"conservation: low-identity position = lowercase",
);
// Gaps are excluded from counting
const cons3 = computeConservation(["A-C", "A-C", "ABC"]);
assert(cons3.identity[0] === 1.0, "conservation: col 1 all A = 100%");
assert(
cons3.identity[1] === 1.0,
"conservation: col 2 gaps excluded, only B counted = 100%",
);
assert(cons3.identity[2] === 1.0, "conservation: col 3 all C = 100%");
// All gaps column
const cons4 = computeConservation(["A-", "A-"]);
assert(cons4.identity[1] === 0, "conservation: all-gap column = 0");
assert(cons4.consensus[1] === "-", "conservation: all-gap consensus = dash");
// Perfect conservation
const cons5 = computeConservation(["AAAA", "AAAA", "AAAA"]);
assert(
cons5.identity.every(function (v) {
return v === 1.0;
}),
"conservation: all identical = all 1.0",
);
assert(cons5.consensus === "AAAA", "conservation: all identical consensus");
// ============================================================
// consensusSequenceForAnalysis
// ============================================================
section("consensusSequenceForAnalysis");
assert(
consensusSequenceForAnalysis("A-bC") === "ABC",
"consensusForAnalysis: strips gaps and uppercases",
);
assert(consensusSequenceForAnalysis("") === "", "consensusForAnalysis: empty");
assert(
consensusSequenceForAnalysis("abc") === "ABC",
"consensusForAnalysis: lowercases to uppercase",
);
// ============================================================
// Integration: cluster + MSA + conservation pipeline
// ============================================================
section("integration: cluster-MSA-conservation pipeline");
const pipelineEntries = [
{
id: 1,
name: "mAb1",
vh: "EVQLVESGGGLVQPGGSLRLSCAASGFTFSDYWMHWVRQAPGKGLEWVSRINSDGSSTSYADSVKGRFTISRDNAKNTLYLQMNSLRAEDTAVYYCTTDGWGFDYWGQGTLVTVSS",
vl: "DIQMTQSPSSLSASVGDRVTITCRASQSISSYLNWYQQKPGKAPKLLIYAASSLQSGVPSRFSGSGSGTDFTLTISSLQPEDFATYYCQQSYSTPLTFGGGTKVEIK",
},
{
id: 2,
name: "mAb2",
vh: "EVQLVESGGGLVQPGGSLRLSCAASGFTFSDYWMHWVRQAPGKGLEWVSRINSDGSSTSYADSVKGRFTISRDNAKNTLYLQMNSLRAEDTAVYYCTTDGWGFDYWGQGTLVTVSS",
vl: "DIQMTQSPSSLSASVGDRVTITCRASQSISSYLNWYQQKPGKAPKLLIYAASSLQSGVPSRFSGSGSGTDFTLTISSLQPEDFATYYCQQSYSTPLTFGGGTKVEIK",
},
];
const pipeClusters = clusterSequences(pipelineEntries, 70);
assert(pipeClusters.length === 1, "pipeline: identical pair = 1 cluster");
assert(pipeClusters[0].members.length === 2, "pipeline: cluster has 2 members");
const pipeMSA = starMSA(
pipeClusters[0].members.map(function (m) {
return m.vh;
}),
);
assert(pipeMSA.length === 2, "pipeline: MSA produces 2 aligned seqs");
assert(
pipeMSA[0].length === pipeMSA[1].length,
"pipeline: MSA seqs equal length",
);
const pipeCons = computeConservation(pipeMSA);
assert(
pipeCons.identity.every(function (v) {
return v === 1.0;
}),
"pipeline: identical seqs = 100% conservation everywhere",
);
assert(
pipeCons.consensus === pipeMSA[0],
"pipeline: consensus matches aligned seq",
);
// ============================================================
// detectLiabilities — Agg Patch (Kyte-Doolittle sliding window)
// ============================================================
section("detectLiabilities (Agg Patch)");
// Verify constants
assert(AGG_WINDOW === 7, "AGG_WINDOW is 7");
assert(AGG_THRESHOLD === 1.6, "AGG_THRESHOLD is 1.6");
assert(KD_HYDROPHOBICITY["I"] === 4.5, "KD: Ile = 4.5");
assert(KD_HYDROPHOBICITY["R"] === -4.5, "KD: Arg = -4.5");
assert(KD_HYDROPHOBICITY["A"] === 1.8, "KD: Ala = 1.8");
// Pure hydrophobic 7-mer: mean 4.5 >> 1.6
const aggAllI = detectLiabilities("IIIIIII")["Agg Patch"];
assert(aggAllI && aggAllI.length === 7, "7 Ile = all 7 positions flagged");
assert(aggAllI[0] === 0 && aggAllI[6] === 6, "7 Ile spans positions 0-6");
// Pure charged 7-mer: mean -3.5, no patch
assert(!detectLiabilities("DDDDDDD")["Agg Patch"], "7 Asp = no agg patch");
// Sequence shorter than window: no patch possible
assert(
!detectLiabilities("IIIII")["Agg Patch"],
"5 Ile < window = no agg patch",
);
assert(
!detectLiabilities("IIIIII")["Agg Patch"],
"6 Ile < window = no agg patch",
);
// Below threshold: AAAAAAG → 6(1.8) + (-0.4) = 10.4, mean 1.486
assert(
!detectLiabilities("AAAAAAG")["Agg Patch"],
"AAAAAAG mean 1.49 = no patch",
);
// Above threshold: AAAAAAM → 6(1.8) + 1.9 = 12.7, mean 1.814
const aggAAM = detectLiabilities("AAAAAAM")["Agg Patch"];
assert(aggAAM && aggAAM.length === 7, "AAAAAAM mean 1.81 = all 7 flagged");
// Hydrophobic island in polar flanks: DDDIIIIIIIDDD (13 chars)
// Windows [0,6] and [6,12] straddle the boundary, only middle windows pass
const aggIsland = detectLiabilities("DDDIIIIIIIDDD")["Agg Patch"];
assert(aggIsland && aggIsland.length > 0, "Ile island is detected");
assert(!aggIsland.includes(0), "position 0 (D flank) not flagged");
assert(!aggIsland.includes(12), "position 12 (D flank) not flagged");
assert(aggIsland.includes(5), "middle of island is flagged");
assert(