-
Notifications
You must be signed in to change notification settings - Fork 0
/
batchmut.html
666 lines (603 loc) · 35.1 KB
/
batchmut.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Codon-aware Mutation Designer</title>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; padding: 20px; max-width: 800px; margin: 0 auto; }
textarea { width: 100%; height: 200px; margin-bottom: 10px; }
button { padding: 10px; background-color: #4CAF50; color: white; border: none; cursor: pointer; margin-bottom: 20px; }
button:hover { background-color: #45a049; }
#output { margin-top: 10px; }
.sequence-box { font-family: monospace; overflow-x: auto; white-space: pre; background-color: #f0f0f0; padding: 10px; border: 1px solid #ccc; margin-bottom: 10px; }
.visual-alignment { font-family: monospace; white-space: pre; margin-bottom: 20px; }
.mutation { color: red; font-weight: bold; }
.flank { color: blue; }
select { margin-bottom: 10px; }
.advanced-settings {
display: none;
margin-top: 10px;
padding: 10px;
border: 1px solid #ccc;
background-color: #f9f9f9;
}
.advanced-settings label {
display: inline-block;
width: 150px;
margin-bottom: 5px;
}
.advanced-settings input {
width: 100px;
}
</style>
</head>
<body>
<h1>Codon-aware Mutation Designer</h1>
<textarea id="originalDNA" placeholder="Enter original DNA sequence (NOT in FASTA format)"></textarea>
<textarea id="mutatedAAFasta" placeholder="Enter one or more mutated amino acid sequences (in FASTA format)"></textarea>
<select id="codonUsageTable">
<option value="human" selected>Human</option>
<option value="wheat">Wheat</option>
<option value="rabbit">Rabbit</option>
<option value="ecoli">E. coli</option>
</select>
<button onclick="toggleAdvancedSettings()">Advanced Settings</button>
<div id="advancedSettings" class="advanced-settings" style="display: none;">
<h3>Alignment Parameters</h3>
<label for="gapOpen">Gap Open:</label>
<input type="number" id="gapOpen" value="-10.0" step="0.1"><br>
<label for="gapExtend">Gap Extend:</label>
<input type="number" id="gapExtend" value="-0.2" step="0.1"><br>
<label for="matchCost">Match Cost:</label>
<input type="number" id="matchCost" value="1.0" step="0.1"><br>
<label for="mismatchCost">Mismatch Cost:</label>
<input type="number" id="mismatchCost" value="-0.7" step="0.1"><br>
<label for="boundaryGapFactor">Boundary Gap Factor:</label>
<input type="number" id="boundaryGapFactor" value="10" step="1">
<h3>Codon Sampling Parameters</h3>
<label for="topP">Top-p (Nucleus Sampling):</label>
<input type="number" id="topP" value="0.7" min="0" max="1" step="0.1">
<div id="flankSettings">
<h3>Flank Treatment</h3>
<label for="leftFlankTreatment">Left Flank:</label>
<select id="leftFlankTreatment">
<option value="missing" selected>Treat as Missing</option>
<option value="deletion">Treat as Deletion</option>
</select>
<br>
<label for="rightFlankTreatment">Right Flank:</label>
<select id="rightFlankTreatment">
<option value="missing" selected>Treat as Missing</option>
<option value="deletion">Treat as Deletion</option>
</select>
</div>
</div>
<button onclick="processBatchMutations()">Process Batch</button>
<div id="output"></div>
<!-- Add this section after the h1 and before the textareas -->
<div id="explanation" style="background-color: #f0f0f0; padding: 15px; margin-bottom: 20px; border-radius: 5px;">
<h3>About This Tool</h3>
<p>This helps you to design DNA sequences based on desired amino acid changes while respecting species-specific codon usage frequencies.</p>
<h4>Typical use: You want to make a few mutations in an existing construct</h4>
<ul>
<li>Paste in the original (unmutated) DNA sequence, including the flanks you'll use for eg. Gibson assembly. Don't worry about the reading frame.</li>
<li>Paste in the .fasta file containing one or more mutated amino acid sequences (that are derived from the above sequence).</li>
<li>Choose how to treat the left and right flanks in the advanced settings: either as "missing" (reconstructed from original DNA) or as "deletions" (removed from the sequence).</li>
<li>Click to process, and carefully inspect the alignments to check that they make sense. The alignments will only show the longest translatable AA sequence from the original DNA.</li>
<li>Download the fasta file containing the mutated DNA sequences. Check these carefully!</li>
</ul>
<h4>How This Tool Works</h4>
<p>This tool processes DNA mutations based on amino acid sequences. Here's how it handles different scenarios:</p>
<ul>
<li><strong>Internal Indels:</strong> Insertions and deletions within the aligned region are directly applied to the DNA sequence. For insertions, new codons are sampled based on the codon usage table. For deletions, the corresponding codons are removed.</li>
<li><strong>Substitutions:</strong> When an amino acid differs between the original and mutated sequences, a new codon is sampled for the mutated amino acid and replaces the original codon.</li>
<li><strong>Overhangs and Truncations:</strong>
<ul>
<li>If the query (mutated) sequence is shorter than the reference at either end, this is treated according to your flank settings: either as "missing" (reconstructed from original DNA) or as "deletions" (removed from the sequence).</li>
<li>If the query sequence is longer than the reference at either end, this is treated as an insertion. New codons are sampled for these overhanging amino acids.</li>
</ul>
</li>
<li><strong>Flanking Regions:</strong> DNA sequences outside the aligned region (before the first or after the last AA in the longest alignable reading frame) are preserved from the original sequence.</li>
</ul>
<h4>Alignment Coloring</h4>
<p>In the visual alignment output:</p>
<ul>
<li><span style="color: blue;">Blue</span> text indicates alignment flanks that are treated as "missing" and reconstructed from the original DNA.</li>
<li><span style="color: red;">Red</span> text shows actual edits: insertions, deletions, or substitutions in the aligned region, as well as flanks treated as deletions.</li>
</ul>
<h4>Codon Sampling</h4>
<p>Species-specific codon usage frequencies are respected, and rare codons are excluded, whilst not being completely deterministic, using an approach called "top-p" or "nucleus sampling". This method selects from a dynamic set of most likely codons whose cumulative probability mass exceeds a threshold p. This balances between always choosing the most common codon and sampling purely based on frequencies.</p>
</div>
<script>
const geneticCodeJSON = {
"geneticCode": {
"TTT": "F", "TTC": "F", "TTA": "L", "TTG": "L",
"CTT": "L", "CTC": "L", "CTA": "L", "CTG": "L",
"ATT": "I", "ATC": "I", "ATA": "I", "ATG": "M",
"GTT": "V", "GTC": "V", "GTA": "V", "GTG": "V",
"TCT": "S", "TCC": "S", "TCA": "S", "TCG": "S",
"CCT": "P", "CCC": "P", "CCA": "P", "CCG": "P",
"ACT": "T", "ACC": "T", "ACA": "T", "ACG": "T",
"GCT": "A", "GCC": "A", "GCA": "A", "GCG": "A",
"TAT": "Y", "TAC": "Y", "TAA": "*", "TAG": "*",
"CAT": "H", "CAC": "H", "CAA": "Q", "CAG": "Q",
"AAT": "N", "AAC": "N", "AAA": "K", "AAG": "K",
"GAT": "D", "GAC": "D", "GAA": "E", "GAG": "E",
"TGT": "C", "TGC": "C", "TGA": "*", "TGG": "W",
"CGT": "R", "CGC": "R", "CGA": "R", "CGG": "R",
"AGT": "S", "AGC": "S", "AGA": "R", "AGG": "R",
"GGT": "G", "GGC": "G", "GGA": "G", "GGG": "G"
},
"wheat": {
"A": {"GCT": 0.2047, "GCC": 0.3507, "GCA": 0.1896, "GCG": 0.2550},
"R": {"CGT": 0.0988, "CGC": 0.2427, "CGA": 0.0711, "CGG": 0.1858, "AGA": 0.1541, "AGG": 0.2476},
"N": {"AAT": 0.4244, "AAC": 0.5756},
"D": {"GAT": 0.4457, "GAC": 0.5543},
"C": {"TGT": 0.3143, "TGC": 0.6857},
"Q": {"CAA": 0.3525, "CAG": 0.6475},
"E": {"GAA": 0.3417, "GAG": 0.6583},
"G": {"GGT": 0.1893, "GGC": 0.4003, "GGA": 0.1856, "GGG": 0.2248},
"H": {"CAT": 0.4368, "CAC": 0.5632},
"I": {"ATT": 0.3109, "ATC": 0.4770, "ATA": 0.2121},
"L": {"TTA": 0.0594, "TTG": 0.1483, "CTT": 0.1621, "CTC": 0.2939, "CTA": 0.0783, "CTG": 0.2579},
"K": {"AAA": 0.3118, "AAG": 0.6882},
"M": {"ATG": 1.0000},
"F": {"TTT": 0.3464, "TTC": 0.6536},
"P": {"CCT": 0.2241, "CCC": 0.2412, "CCA": 0.2378, "CCG": 0.2969},
"S": {"TCT": 0.1574, "TCC": 0.2227, "TCA": 0.1536, "TCG": 0.1419, "AGT": 0.1099, "AGC": 0.2145},
"T": {"ACT": 0.2055, "ACC": 0.3302, "ACA": 0.2405, "ACG": 0.2238},
"W": {"TGG": 1.0000},
"Y": {"TAT": 0.3663, "TAC": 0.6337},
"V": {"GTT": 0.2216, "GTC": 0.3066, "GTA": 0.0971, "GTG": 0.3746},
"*": {"TAA": 0.2063, "TAG": 0.3092, "TGA": 0.4845}
},
"rabbit": {
"A": {"GCT": 0.2386, "GCC": 0.4214, "GCA": 0.2041, "GCG": 0.1359},
"R": {"CGT": 0.0700, "CGC": 0.1991, "CGA": 0.0990, "CGG": 0.2094, "AGA": 0.2051, "AGG": 0.2174},
"N": {"AAT": 0.4350, "AAC": 0.5650},
"D": {"GAT": 0.4172, "GAC": 0.5828},
"C": {"TGT": 0.4309, "TGC": 0.5691},
"Q": {"CAA": 0.2448, "CAG": 0.7552},
"E": {"GAA": 0.4056, "GAG": 0.5944},
"G": {"GGT": 0.1437, "GGC": 0.3613, "GGA": 0.2394, "GGG": 0.2556},
"H": {"CAT": 0.3617, "CAC": 0.6383},
"I": {"ATT": 0.3387, "ATC": 0.4979, "ATA": 0.1634},
"L": {"TTA": 0.0704, "TTG": 0.1241, "CTT": 0.1180, "CTC": 0.2039, "CTA": 0.0588, "CTG": 0.4248},
"K": {"AAA": 0.4176, "AAG": 0.5824},
"M": {"ATG": 1.0000},
"F": {"TTT": 0.4271, "TTC": 0.5729},
"P": {"CCT": 0.2635, "CCC": 0.3446, "CCA": 0.2419, "CCG": 0.1500},
"S": {"TCT": 0.1714, "TCC": 0.2302, "TCA": 0.1311, "TCG": 0.0715, "AGT": 0.1416, "AGC": 0.2542},
"T": {"ACT": 0.2282, "ACC": 0.3623, "ACA": 0.2583, "ACG": 0.1512},
"W": {"TGG": 1.0000},
"Y": {"TAT": 0.3924, "TAC": 0.6076},
"V": {"GTT": 0.1668, "GTC": 0.2480, "GTA": 0.1015, "GTG": 0.4838},
"*": {"TAA": 0.2536, "TAG": 0.2360, "TGA": 0.5105}
},
"human": {
"A": {"GCT": 0.2627, "GCC": 0.3976, "GCA": 0.2301, "GCG": 0.1096},
"R": {"CGT": 0.0792, "CGC": 0.1823, "CGA": 0.1068, "CGG": 0.2010, "AGA": 0.2172, "AGG": 0.2135},
"N": {"AAT": 0.4816, "AAC": 0.5184},
"D": {"GAT": 0.4705, "GAC": 0.5295},
"C": {"TGT": 0.4655, "TGC": 0.5345},
"Q": {"CAA": 0.2702, "CAG": 0.7298},
"E": {"GAA": 0.4316, "GAG": 0.5684},
"G": {"GGT": 0.1616, "GGC": 0.3365, "GGA": 0.2527, "GGG": 0.2492},
"H": {"CAT": 0.4258, "CAC": 0.5742},
"I": {"ATT": 0.3684, "ATC": 0.4543, "ATA": 0.1773},
"L": {"TTA": 0.0797, "TTG": 0.1306, "CTT": 0.1351, "CTC": 0.1918, "CTA": 0.0722, "CTG": 0.3907},
"K": {"AAA": 0.4448, "AAG": 0.5552},
"M": {"ATG": 1.0000},
"F": {"TTT": 0.4694, "TTC": 0.5306},
"P": {"CCT": 0.2857, "CCC": 0.3214, "CCA": 0.2760, "CCG": 0.1168},
"S": {"TCT": 0.1879, "TCC": 0.2129, "TCA": 0.1546, "TCG": 0.0546, "AGT": 0.1519, "AGC": 0.2381},
"T": {"ACT": 0.2542, "ACC": 0.3464, "ACA": 0.2880, "ACG": 0.1114},
"W": {"TGG": 1.0000},
"Y": {"TAT": 0.4531, "TAC": 0.5469},
"V": {"GTT": 0.1857, "GTC": 0.2352, "GTA": 0.1210, "GTG": 0.4581},
"*": {"TAA": 0.2840, "TAG": 0.2235, "TGA": 0.4925}
},
"ecoli": {
"A": {"GCT": 0.1655, "GCC": 0.2710, "GCA": 0.2225, "GCG": 0.3409},
"R": {"CGT": 0.3654, "CGC": 0.3755, "CGA": 0.0670, "CGG": 0.1115, "AGA": 0.0494, "AGG": 0.0312},
"N": {"AAT": 0.4616, "AAC": 0.5384},
"D": {"GAT": 0.6281, "GAC": 0.3719},
"C": {"TGT": 0.4556, "TGC": 0.5444},
"Q": {"CAA": 0.3281, "CAG": 0.6719},
"E": {"GAA": 0.6768, "GAG": 0.3232},
"G": {"GGT": 0.3346, "GGC": 0.3835, "GGA": 0.1227, "GGG": 0.1592},
"H": {"CAT": 0.5755, "CAC": 0.4245},
"I": {"ATT": 0.5038, "ATC": 0.4081, "ATA": 0.0881},
"L": {"TTA": 0.1292, "TTG": 0.1232, "CTT": 0.1110, "CTC": 0.1023, "CTA": 0.0359, "CTG": 0.4983},
"K": {"AAA": 0.7528, "AAG": 0.2472},
"M": {"ATG": 1.0000},
"F": {"TTT": 0.5807, "TTC": 0.4193},
"P": {"CCT": 0.1670, "CCC": 0.1291, "CCA": 0.1898, "CCG": 0.5141},
"S": {"TCT": 0.1450, "TCC": 0.1519, "TCA": 0.1334, "TCG": 0.1462, "AGT": 0.1590, "AGC": 0.2645},
"T": {"ACT": 0.1640, "ACC": 0.4171, "ACA": 0.1510, "ACG": 0.2680},
"W": {"TGG": 1.0000},
"Y": {"TAT": 0.5717, "TAC": 0.4283},
"V": {"GTT": 0.2621, "GTC": 0.2124, "GTA": 0.1549, "GTG": 0.3705},
"*": {"TAA": 0.6154, "TAG": 0.1923, "TGA": 0.1923}
}
};
const geneticCode = geneticCodeJSON.geneticCode;
function getCurrentCodonUsage() {
const codonUsageTable = document.getElementById('codonUsageTable');
return geneticCodeJSON[codonUsageTable.value] || geneticCodeJSON["human"];
}
// Correct affine alignment function
function affineNWAlign(s1, s2, gapOpen = -10.0, gapExtend = -0.2, matchCost = 1.0, mismatchCost = -0.7, boundaryGapFactor = 10) {
const s1arr = s1.split('');
const s1len = s1arr.length;
const s2arr = s2.split('');
const s2len = s2arr.length;
const M = Array(s1len + 1).fill().map(() => Array(s2len + 1).fill(0));
const IX = Array(s1len + 1).fill().map(() => Array(s2len + 1).fill(0));
const IY = Array(s1len + 1).fill().map(() => Array(s2len + 1).fill(0));
for (let i = 0; i <= s1len; i++) {
IX[i][0] = gapOpen + gapExtend * i;
IY[i][0] = -Infinity;
M[i][0] = gapOpen + gapExtend * i;
}
for (let j = 0; j <= s2len; j++) {
IX[0][j] = -Infinity;
IY[0][j] = gapOpen + gapExtend * j;
M[0][j] = gapOpen + gapExtend * j;
}
const traceM = Array(s1len + 1).fill().map(() => Array(s2len + 1).fill(0));
const traceIX = Array(s1len + 1).fill().map(() => Array(s2len + 1).fill(0));
const traceIY = Array(s1len + 1).fill().map(() => Array(s2len + 1).fill(0));
traceM[0].fill(3);
traceIX[0].fill(3);
traceIY[0].fill(3);
for (let i = 1; i <= s1len; i++) {
traceM[i][0] = 2;
traceIX[i][0] = 2;
traceIY[i][0] = 2;
}
for (let i = 1; i <= s1len; i++) {
for (let j = 1; j <= s2len; j++) {
const diagCost = s1arr[i - 1] === s2arr[j - 1] ? matchCost : mismatchCost;
const diagM = M[i - 1][j - 1] + diagCost;
const IX2M = IX[i - 1][j - 1] + diagCost;
const IY2M = IY[i - 1][j - 1] + diagCost;
[M[i][j], traceM[i][j]] = findMax([diagM, IX2M, IY2M]);
// Reduce gap extension cost at X boundary (end of s1)
const boundaryGapExtendX = (i === s1len) ? gapExtend / boundaryGapFactor : gapExtend;
// Reduce gap extension cost at Y boundary (end of s2)
const boundaryGapExtendY = (j === s2len) ? gapExtend / boundaryGapFactor : gapExtend;
const M2IX = M[i - 1][j] + gapOpen;
const IXextend = IX[i - 1][j] + boundaryGapExtendY;
[IX[i][j], traceIX[i][j]] = findMax([M2IX, IXextend]);
const M2IY = M[i][j - 1] + gapOpen;
const IYextend = IY[i][j - 1] + boundaryGapExtendX;
[IY[i][j], traceIY[i][j]] = findMax([M2IY, -Infinity, IYextend]);
}
}
const revArr1 = [];
const revArr2 = [];
const mats = [traceM, traceIX, traceIY];
let xI = s1len;
let yI = s2len;
let mI = findMax([M[xI][yI], IX[xI][yI], IY[xI][yI]])[1];
while (xI > 0 && yI > 0) {
const nextMI = mats[mI - 1][xI][yI];
if (mI === 1) {
revArr1.push(s1arr[xI - 1]);
revArr2.push(s2arr[yI - 1]);
xI--;
yI--;
} else if (mI === 2) {
revArr1.push(s1arr[xI - 1]);
revArr2.push('-');
xI--;
} else if (mI === 3) {
revArr1.push('-');
revArr2.push(s2arr[yI - 1]);
yI--;
}
mI = nextMI;
}
while (xI > 0) {
revArr1.push(s1arr[xI - 1]);
revArr2.push('-');
xI--;
}
while (yI > 0) {
revArr1.push('-');
revArr2.push(s2arr[yI - 1]);
yI--;
}
return [revArr1.reverse().join(''), revArr2.reverse().join('')];
}
function findMax(arr) {
let maxVal = arr[0];
let maxIndex = 1;
for (let i = 1; i < arr.length; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
maxIndex = i + 1;
}
}
return [maxVal, maxIndex];
}
function translateDNA(dna, geneticCode) {
let protein = '';
for (let i = 0; i < dna.length; i += 3) {
const codon = dna.slice(i, i + 3);
protein += geneticCode[codon] || 'X';
}
return protein;
}
function reverseComplement(dna) {
const complement = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'};
return dna.split('').reverse().map(base => complement[base]).join('');
}
function sampleCodon(aa, codonUsage, p = 0.7) {
const codons = Object.keys(codonUsage[aa]);
const frequencies = Object.values(codonUsage[aa]);
const totalFreq = frequencies.reduce((a, b) => a + b, 0);
const normalizedFreqs = frequencies.map(f => f / totalFreq);
// Sort codons by descending probability
const sortedIndices = normalizedFreqs.map((_, i) => i)
.sort((a, b) => normalizedFreqs[b] - normalizedFreqs[a]);
let cumSum = 0;
const nucleusIndices = [];
for (const i of sortedIndices) {
cumSum += normalizedFreqs[i];
nucleusIndices.push(i);
if (cumSum >= p) break;
}
// Renormalize probabilities within the nucleus
const nucleusTotal = nucleusIndices.reduce((sum, i) => sum + normalizedFreqs[i], 0);
const nucleusProbs = nucleusIndices.map(i => normalizedFreqs[i] / nucleusTotal);
// Sample from the nucleus
const r = Math.random();
let cumulativeProb = 0;
for (let i = 0; i < nucleusIndices.length; i++) {
cumulativeProb += nucleusProbs[i];
if (r <= cumulativeProb) {
return codons[nucleusIndices[i]];
}
}
// Fallback (should rarely happen)
return codons[nucleusIndices[nucleusIndices.length - 1]];
}
function parseFasta(fastaText) {
const sequences = [];
const lines = fastaText.split('\n');
let currentSeq = '';
let currentName = '';
for (const line of lines) {
if (line.startsWith('>')) {
if (currentSeq) {
sequences.push({ name: currentName, sequence: currentSeq });
}
currentName = line.slice(1).trim();
currentSeq = '';
} else {
currentSeq += line.trim();
}
}
if (currentSeq) {
sequences.push({ name: currentName, sequence: currentSeq });
}
return sequences;
}
function findLongestORF(sequence) {
const stopCodons = ['TAA', 'TAG', 'TGA'];
let longestORF = '';
let longestORFStart = 0;
let longestORFEnd = 0;
for (let frame = 0; frame < 3; frame++) {
let currentORF = '';
let start = frame;
for (let i = frame; i < sequence.length - 2; i += 3) {
const codon = sequence.slice(i, i + 3);
if (stopCodons.includes(codon)) {
if (currentORF.length > longestORF.length) {
longestORF = currentORF;
longestORFStart = start;
longestORFEnd = i;
}
currentORF = '';
start = i + 3;
} else {
currentORF += codon;
}
}
if (currentORF.length > longestORF.length) {
longestORF = currentORF;
longestORFStart = start;
longestORFEnd = sequence.length;
}
}
return { orf: longestORF, start: longestORFStart, end: longestORFEnd };
}
function toggleAdvancedSettings() {
const advancedSettings = document.getElementById('advancedSettings');
advancedSettings.style.display = advancedSettings.style.display === 'none' ? 'block' : 'none';
}
function getAlignmentParameters() {
return {
gapOpen: parseFloat(document.getElementById('gapOpen').value),
gapExtend: parseFloat(document.getElementById('gapExtend').value),
matchCost: parseFloat(document.getElementById('matchCost').value),
mismatchCost: parseFloat(document.getElementById('mismatchCost').value),
boundaryGapFactor: parseFloat(document.getElementById('boundaryGapFactor').value),
topP: parseFloat(document.getElementById('topP').value)
};
}
function getFlankTreatment() {
return {
left: document.getElementById('leftFlankTreatment').value,
right: document.getElementById('rightFlankTreatment').value
};
}
function processSingleMutation(originalDNA, mutatedAA) {
let bestAlignment = null;
let bestFrame = 0;
let bestStrand = '+';
let bestORF = null;
let codonUsage = getCurrentCodonUsage();
const alignParams = getAlignmentParameters();
const flankTreatment = getFlankTreatment();
// Check both strands
for (const strand of ['+', '-']) {
const dna = strand === '+' ? originalDNA : reverseComplement(originalDNA);
const { orf, start, end } = findLongestORF(dna);
const orfAA = translateDNA(orf, geneticCode);
const [alignedOrig, alignedMutated] = affineNWAlign(orfAA, mutatedAA,
alignParams.gapOpen, alignParams.gapExtend, alignParams.matchCost,
alignParams.mismatchCost, alignParams.boundaryGapFactor);
const score = alignedOrig.split('').reduce((score, char, index) =>
score + (char === alignedMutated[index] ? 1 : 0), 0);
if (!bestAlignment || score > bestAlignment.score) {
bestAlignment = {score, alignedOrig, alignedMutated};
bestFrame = start % 3;
bestStrand = strand;
bestORF = { orf, start, end };
}
}
// Process mutations, including indels, while preserving flanks
let workingDNA = bestStrand === '+' ? originalDNA : reverseComplement(originalDNA);
let mutations = [];
let dnaIndex = bestORF.start;
let alignmentIndex = 0;
// Preserve left flank
let leftFlank = workingDNA.slice(0, bestORF.start);
let rightFlank = workingDNA.slice(bestORF.end);
// Find start and end of non-gap region in mutated sequence
let mutatedStart = 0;
let mutatedEnd = bestAlignment.alignedMutated.length - 1;
if (flankTreatment.left === 'missing') {
for (let i = 0; i < bestAlignment.alignedMutated.length; i++) {
if (bestAlignment.alignedMutated[i] !== '-') {
mutatedStart = i;
break;
}
}
}
if (flankTreatment.right === 'missing') {
for (let i = bestAlignment.alignedMutated.length - 1; i >= 0; i--) {
if (bestAlignment.alignedMutated[i] !== '-') {
mutatedEnd = i;
break;
}
}
}
// Adjust DNA index for left truncation
dnaIndex += mutatedStart * 3;
let dnaEndIndex = dnaIndex + (bestAlignment.alignedOrig.length - mutatedEnd - 1) * 3;
while (alignmentIndex < bestAlignment.alignedMutated.length) {
if ((flankTreatment.left === 'missing' && alignmentIndex < mutatedStart) ||
(flankTreatment.right === 'missing' && alignmentIndex > mutatedEnd)) {
// Skip truncated regions
alignmentIndex++;
continue;
}
if (bestAlignment.alignedOrig[alignmentIndex] === '-' && bestAlignment.alignedMutated[alignmentIndex] !== '-') {
// Insertion
const insertedAA = bestAlignment.alignedMutated[alignmentIndex];
const insertedCodon = sampleCodon(insertedAA, codonUsage, alignParams.topP);
workingDNA = workingDNA.slice(0, dnaIndex) + insertedCodon + workingDNA.slice(dnaIndex);
mutations.push({
type: 'insertion',
position: Math.floor(dnaIndex / 3) + 1,
inserted: insertedAA,
insertedCodon: insertedCodon
});
dnaIndex += 3;
} else if (bestAlignment.alignedOrig[alignmentIndex] !== '-' && bestAlignment.alignedMutated[alignmentIndex] === '-') {
// Deletion
workingDNA = workingDNA.slice(0, dnaIndex) + workingDNA.slice(dnaIndex + 3);
mutations.push({
type: 'deletion',
position: Math.floor(dnaIndex / 3) + 1,
deleted: bestAlignment.alignedOrig[alignmentIndex]
});
} else if (bestAlignment.alignedOrig[alignmentIndex] !== bestAlignment.alignedMutated[alignmentIndex]) {
// Substitution
const newAA = bestAlignment.alignedMutated[alignmentIndex];
const newCodon = sampleCodon(newAA, codonUsage, alignParams.topP);
workingDNA = workingDNA.slice(0, dnaIndex) + newCodon + workingDNA.slice(dnaIndex + 3);
mutations.push({
type: 'substitution',
position: Math.floor(dnaIndex / 3) + 1,
original: bestAlignment.alignedOrig[alignmentIndex],
mutated: newAA,
mutatedCodon: newCodon
});
dnaIndex += 3;
} else {
// No change
dnaIndex += 3;
}
alignmentIndex++;
}
// Adjust the right flank
rightFlank = workingDNA.slice(dnaEndIndex);
// Preserve flanks
let mutatedDNA = leftFlank + workingDNA.slice(bestORF.start, dnaEndIndex) + rightFlank;
if (bestStrand === '-') {
mutatedDNA = reverseComplement(mutatedDNA);
}
// Visual alignment output
let visualOutput = ``;
visualOutput += `Original: `;
let mutatedOutput = `Mutated: `;
for (let i = 0; i < bestAlignment.alignedOrig.length; i++) {
if ((flankTreatment.left === 'missing' && i < mutatedStart) ||
(flankTreatment.right === 'missing' && i > mutatedEnd)) {
// Color alignment missing flanks blue
visualOutput += `<span class="flank">${bestAlignment.alignedOrig[i]}</span>`;
mutatedOutput += `<span class="flank">${bestAlignment.alignedMutated[i]}</span>`;
} else if (bestAlignment.alignedOrig[i] !== bestAlignment.alignedMutated[i]) {
// Color internal mismatches and indels red
visualOutput += `<span class="mutation">${bestAlignment.alignedOrig[i]}</span>`;
mutatedOutput += `<span class="mutation">${bestAlignment.alignedMutated[i]}</span>`;
} else {
visualOutput += bestAlignment.alignedOrig[i];
mutatedOutput += bestAlignment.alignedMutated[i];
}
}
visualOutput += `\n${mutatedOutput}\n`;
let output = `<div class="visual-alignment">${visualOutput}</div>`;
return { output, mutatedDNA };
}
function processBatchMutations() {
const originalDNA = document.getElementById('originalDNA').value.toUpperCase();
const mutatedAAFasta = document.getElementById('mutatedAAFasta').value;
const mutatedAASequences = parseFasta(mutatedAAFasta);
let output = '';
let mutatedDNAFasta = '';
// Add download button for mutated DNA FASTA
output += `<h3>Download Mutated DNA Sequences:</h3>
<button onclick="downloadMutatedDNA()">Download FASTA</button>
<h3>Alignments:</h3>`;
for (const mutatedAA of mutatedAASequences) {
const result = processSingleMutation(originalDNA, mutatedAA.sequence);
output += `<h3>${mutatedAA.name}</h3>`;
output += result.output;
mutatedDNAFasta += `>${mutatedAA.name}\n${result.mutatedDNA}\n`;
}
document.getElementById('output').innerHTML = output;
// Store mutated DNA FASTA in a global variable for download
window.mutatedDNAFasta = mutatedDNAFasta;
}
function downloadMutatedDNA() {
const blob = new Blob([window.mutatedDNAFasta], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'mutated_dna_sequences.fasta';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
</script>
</body>
</html>