Repository navigation
Expand file tree
/
Copy pathmsa_engine_optimized.cpp
More file actions
1859 lines (1576 loc) · 74 KB
/
Copy pathmsa_engine_optimized.cpp
File metadata and controls
1859 lines (1576 loc) · 74 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
#include <emscripten/bind.h>
#include <emscripten/val.h>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <memory>
#include <sstream>
#include <cmath>
#include <fstream>
extern "C" {
#include "pdfgen.h"
}
#include "font_manager.h"
#include "alignment_pdf.h"
using namespace emscripten;
// Verbose engine tracing. Off in normal builds so the browser console stays
// usable; rebuild with -DSLOP_DEBUG to turn it back on. Genuine errors and
// warnings are printed unconditionally and do not use this macro.
#ifdef SLOP_DEBUG
#define SLOP_LOG(...) printf(__VA_ARGS__)
#else
#define SLOP_LOG(...) ((void)0)
#endif
class MSAEngine {
private:
// Store sequences as contiguous strings for better memory locality
std::vector<std::string> sequences;
std::vector<std::string> sequence_names;
// Store pre-translated amino acid sequences
std::vector<std::string> amino_acid_sequences;
bool amino_acid_translations_valid = false;
// Selection stored as ranges, not individual cells
int selection_start_row = -1;
int selection_start_col = -1;
int selection_end_row = -1;
int selection_end_col = -1;
// Cache for frequent operations
mutable int cached_max_length = -1;
mutable std::vector<char> consensus_cache;
mutable bool consensus_dirty = true;
// Static color maps
static const std::unordered_map<char, uint32_t> nucleotide_colors;
static const std::unordered_map<char, uint32_t> amino_acid_colors;
// Genetic code tables
static const std::unordered_map<std::string, std::unordered_map<std::string, char>> genetic_codes;
// Scoring parameters (customizable)
int gap_open_penalty = -10;
int gap_extend_penalty = -1;
int match_score = 2;
int mismatch_penalty = -1;
// Codon mode parameters
bool codon_mode_enabled = false;
int codon_phase = 0; // 0, 1, or 2 (representing phase 1, 2, 3)
std::string genetic_code_name = "standard";
bool is_dna_sequences = false;
public:
MSAEngine() {
sequences.reserve(1000); // Pre-allocate for large datasets
sequence_names.reserve(1000);
}
// Methods to set scoring parameters
void setGapOpenPenalty(int penalty) { gap_open_penalty = penalty; }
void setGapExtendPenalty(int penalty) { gap_extend_penalty = penalty; }
void setMatchScore(int score) { match_score = score; }
void setMismatchPenalty(int penalty) { mismatch_penalty = penalty; }
// Methods to get current scoring parameters
int getGapOpenPenalty() { return gap_open_penalty; }
int getGapExtendPenalty() { return gap_extend_penalty; }
int getMatchScore() { return match_score; }
int getMismatchPenalty() { return mismatch_penalty; }
// Codon mode methods
void setCodonMode(bool enabled) { codon_mode_enabled = enabled; }
bool getCodonMode() { return codon_mode_enabled; }
void setCodonPhase(int phase) {
if (phase >= 1 && phase <= 3) {
codon_phase = phase - 1; // Store as 0-based
}
}
int getCodonPhase() { return codon_phase + 1; } // Return as 1-based
void setGeneticCode(const std::string& code) { genetic_code_name = code; }
std::string getGeneticCode() { return genetic_code_name; }
bool isDNA() { return is_dna_sequences; }
// Check if sequences are DNA (only ACGT and gaps)
void checkIfDNA() {
is_dna_sequences = true;
for (const auto& seq : sequences) {
for (char c : seq) {
if (c != 'A' && c != 'C' && c != 'G' && c != 'T' && c != '-' && c != 'N') {
is_dna_sequences = false;
return;
}
}
}
}
// Translate a codon to amino acid using the current genetic code
char translateCodon(const std::string& codon) {
if (codon.length() != 3) return 'X';
// Handle complete gap codon first
if (codon == "---") return '-';
// Handle incomplete codons (containing gaps) - return '?' for uncertain translation
if (codon.find('-') != std::string::npos) return '?';
// Get the appropriate genetic code table
auto code_it = genetic_codes.find(genetic_code_name);
if (code_it == genetic_codes.end()) {
code_it = genetic_codes.find("standard");
}
auto aa_it = code_it->second.find(codon);
if (aa_it != code_it->second.end()) {
return aa_it->second;
}
return 'X'; // Unknown codon
}
// Get amino acid character for a position in codon mode
char getAminoAcidAt(int seq_idx, int pos) {
if (!codon_mode_enabled || seq_idx >= sequences.size()) {
return ' ';
}
// Simple approach: treat pos as the start of the codon
// JavaScript should only call this for codon start positions
if (pos < 0 || pos + 2 >= sequences[seq_idx].length()) {
return ' ';
}
std::string codon = sequences[seq_idx].substr(pos, 3);
return translateCodon(codon);
}
// Get three-letter amino acid code
std::string getThreeLetterCode(char aa) {
static std::unordered_map<char, std::string> three_letter = {
{'A', "Ala"}, {'C', "Cys"}, {'D', "Asp"}, {'E', "Glu"},
{'F', "Phe"}, {'G', "Gly"}, {'H', "His"}, {'I', "Ile"},
{'K', "Lys"}, {'L', "Leu"}, {'M', "Met"}, {'N', "Asn"},
{'P', "Pro"}, {'Q', "Gln"}, {'R', "Arg"}, {'S', "Ser"},
{'T', "Thr"}, {'V', "Val"}, {'W', "Trp"}, {'Y', "Tyr"},
{'*', "STP"}, {'-', "---"}, {'X', "???"}, {'?', "???"}
};
auto it = three_letter.find(aa);
if (it != three_letter.end()) {
return it->second;
}
return "???";
}
// Translate a single sequence to amino acids
// Returns translated sequence with amino acids at codon start positions, spaces elsewhere
std::string translateSequence(int seqIdx) {
if (seqIdx < 0 || seqIdx >= sequences.size()) {
return "";
}
const std::string& seq = sequences[seqIdx];
int seqLen = seq.length();
std::string translated(seqLen, ' '); // Initialize with spaces
// Translate each codon
for (int i = codon_phase; i + 2 < seqLen; i += 3) {
std::string codon = seq.substr(i, 3);
char aa = translateCodon(codon);
translated[i] = aa; // Store amino acid at codon start position
}
return translated;
}
// Translate a region of a sequence (from startCol onwards)
void translateSequenceRegion(int seqIdx, int startCol) {
if (seqIdx < 0 || seqIdx >= sequences.size() || seqIdx >= amino_acid_sequences.size()) {
return;
}
const std::string& seq = sequences[seqIdx];
int seqLen = seq.length();
std::string& translated = amino_acid_sequences[seqIdx];
// Ensure translated sequence is the right size
if (translated.length() != seqLen) {
translated.resize(seqLen, ' ');
}
// Find the first codon start position at or after startCol
int firstCodonStart = startCol;
if (codon_phase > 0) {
int offset = (startCol - codon_phase);
if (offset < 0) {
firstCodonStart = codon_phase;
} else {
int remainder = offset % 3;
firstCodonStart = startCol + (remainder == 0 ? 0 : (3 - remainder));
}
} else {
int remainder = startCol % 3;
firstCodonStart = startCol + (remainder == 0 ? 0 : (3 - remainder));
}
// Clear affected positions first (set to space)
for (int i = startCol; i < seqLen; i++) {
translated[i] = ' ';
}
// Translate from first codon start onwards
for (int i = firstCodonStart; i + 2 < seqLen; i += 3) {
std::string codon = seq.substr(i, 3);
char aa = translateCodon(codon);
translated[i] = aa; // Store amino acid at codon start position
}
}
// Translate all sequences completely
void translateAllSequences() {
SLOP_LOG("translateAllSequences called, sequences.size=%zu, codon_phase=%d\n", sequences.size(), codon_phase);
amino_acid_sequences.clear();
amino_acid_sequences.resize(sequences.size());
for (size_t i = 0; i < sequences.size(); i++) {
amino_acid_sequences[i] = translateSequence(i);
if (i == 0) {
SLOP_LOG("Translated seq 0: '%s'\n", amino_acid_sequences[i].substr(0, 30).c_str());
}
}
amino_acid_translations_valid = true;
SLOP_LOG("Translation complete, valid=%d\n", amino_acid_translations_valid);
}
// Translate a range of sequences
void translateSequenceRange(int startSeq, int endSeq) {
if (amino_acid_sequences.size() != sequences.size()) {
amino_acid_sequences.resize(sequences.size());
}
startSeq = std::max(0, startSeq);
endSeq = std::min(endSeq, (int)sequences.size());
for (int i = startSeq; i < endSeq; i++) {
amino_acid_sequences[i] = translateSequence(i);
}
amino_acid_translations_valid = true;
}
// Invalidate translations (call when sequences are edited outside codon mode)
void invalidateTranslations() {
amino_acid_translations_valid = false;
}
// Get amino acid color for a codon at position
uint32_t getCodonColor(int seq_idx, int pos) {
if (!codon_mode_enabled || seq_idx >= sequences.size() || pos < 0) {
// Return regular nucleotide color when not in codon mode
char c = getCharAt(seq_idx, pos);
auto color_it = nucleotide_colors.find(c);
if (color_it != nucleotide_colors.end()) {
return color_it->second;
}
return 0xF0F0F0FF; // Default gray
}
// Calculate codon position
int codon_start = ((pos - codon_phase) / 3) * 3 + codon_phase;
if (codon_start < 0 || codon_start + 2 >= sequences[seq_idx].length()) {
return 0xF0F0F0FF; // Gray for incomplete codons
}
std::string codon = sequences[seq_idx].substr(codon_start, 3);
char aa = translateCodon(codon);
auto color_it = amino_acid_colors.find(aa);
if (color_it != amino_acid_colors.end()) {
return color_it->second;
}
return 0xCCCCCCFF; // Default gray
}
void loadFASTA(const std::string& fasta_content) {
sequences.clear();
sequence_names.clear();
sequences.reserve(1000);
sequence_names.reserve(1000);
std::string current_seq;
current_seq.reserve(10000); // Pre-allocate for long sequences
std::string current_name;
size_t pos = 0;
size_t content_len = fasta_content.length();
while (pos < content_len) {
size_t line_end = fasta_content.find('\n', pos);
if (line_end == std::string::npos) line_end = content_len;
if (pos < line_end) { // Non-empty line
if (fasta_content[pos] == '>') {
if (!current_seq.empty()) {
sequences.emplace_back(std::move(current_seq));
sequence_names.emplace_back(std::move(current_name));
current_seq.clear();
current_seq.reserve(10000);
}
current_name = fasta_content.substr(pos + 1, line_end - pos - 1);
} else {
// Append sequence data directly
for (size_t i = pos; i < line_end; i++) {
char c = fasta_content[i];
if (c != ' ' && c != '\t' && c != '\r') {
current_seq += toupper(c);
}
}
}
}
pos = line_end + 1;
}
if (!current_seq.empty()) {
sequences.emplace_back(std::move(current_seq));
sequence_names.emplace_back(std::move(current_name));
}
// Reset caches
cached_max_length = -1;
consensus_dirty = true;
// Invalidate amino acid translations
invalidateTranslations();
// Check if sequences are DNA
checkIfDNA();
}
void loadPHYLIP(const std::string& phylip_content) {
sequences.clear();
sequence_names.clear();
std::istringstream input(phylip_content);
std::string line;
// Read header line
if (!std::getline(input, line)) return;
// Parse header - should be two numbers: num_sequences and seq_length
std::istringstream header(line);
int num_sequences = 0, seq_length = 0;
header >> num_sequences >> seq_length;
if (num_sequences <= 0 || seq_length <= 0) return;
sequences.reserve(num_sequences);
sequence_names.reserve(num_sequences);
// Initialize sequences
for (int i = 0; i < num_sequences; i++) {
sequences.push_back("");
sequences[i].reserve(seq_length);
}
// Try to detect if it's interleaved or sequential
std::vector<std::string> lines;
while (std::getline(input, line)) {
// Skip empty lines and whitespace
if (line.find_first_not_of(" \t\r\n") != std::string::npos) {
lines.push_back(line);
}
}
if (lines.empty()) return;
// Check if it's interleaved or sequential
bool is_interleaved = false;
// For sequential format, we expect num_sequences blocks of continuous sequence
// For interleaved, we expect names to repeat
// First pass: read the first block (names and initial sequences)
int current_seq = 0;
size_t line_idx = 0;
// Read first block with names
while (current_seq < num_sequences && line_idx < lines.size()) {
const std::string& current_line = lines[line_idx++];
// PHYLIP format: first 10 characters are the name (padded with spaces)
// Some variants allow longer names or use tabs
std::string name;
std::string seq_data;
// Handle both strict (10-char) and relaxed PHYLIP formats
size_t name_end = current_line.find_first_of(" \t");
if (name_end == std::string::npos || name_end > 10) {
// Strict format: take first 10 chars as name
name = current_line.substr(0, std::min((size_t)10, current_line.length()));
if (current_line.length() > 10) {
seq_data = current_line.substr(10);
}
} else {
// Relaxed format: name ends at first whitespace
name = current_line.substr(0, name_end);
seq_data = current_line.substr(name_end);
}
// Trim whitespace from name
name.erase(name.find_last_not_of(" \t") + 1);
if (name.empty()) name = "Seq" + std::to_string(current_seq + 1);
sequence_names.push_back(name);
// Process sequence data
for (char c : seq_data) {
if (c != ' ' && c != '\t' && c != '\r' && c != '\n' && c >= 0) {
sequences[current_seq] += toupper(c);
}
}
current_seq++;
}
// Now determine if remaining lines are interleaved or sequential
if (line_idx < lines.size()) {
// Check if the pattern suggests interleaved (cycling through sequences)
// or sequential (all data for one sequence before moving to next)
// Simple heuristic: if we've read significant sequence data already,
// and there are many lines left, it's probably interleaved
size_t avg_seq_len = 0;
for (const auto& seq : sequences) {
avg_seq_len += seq.length();
}
avg_seq_len /= num_sequences;
is_interleaved = (avg_seq_len < seq_length / 2) &&
(lines.size() - line_idx) > num_sequences;
}
// Continue reading based on format
if (is_interleaved) {
// Interleaved format: cycle through sequences
while (line_idx < lines.size()) {
for (int seq_idx = 0; seq_idx < num_sequences && line_idx < lines.size(); seq_idx++) {
const std::string& current_line = lines[line_idx++];
// In interleaved continuation, lines usually don't have names
// Just sequence data
for (char c : current_line) {
if (c != ' ' && c != '\t' && c != '\r' && c != '\n' && c >= 0) {
sequences[seq_idx] += toupper(c);
}
}
}
}
} else {
// Sequential format: continue reading remaining sequences
current_seq = 0;
// Find where we are in sequential reading
while (current_seq < num_sequences && sequences[current_seq].length() >= seq_length) {
current_seq++;
}
// Continue with remaining sequences
while (current_seq < num_sequences && line_idx < lines.size()) {
const std::string& current_line = lines[line_idx++];
// Add to current sequence
for (char c : current_line) {
if (c != ' ' && c != '\t' && c != '\r' && c != '\n' && c >= 0) {
sequences[current_seq] += toupper(c);
}
}
// Move to next sequence if current is complete
if (sequences[current_seq].length() >= seq_length) {
current_seq++;
}
}
}
// Ensure all sequences have the same length (pad with gaps if needed)
size_t max_len = 0;
for (const auto& seq : sequences) {
max_len = std::max(max_len, seq.length());
}
for (auto& seq : sequences) {
while (seq.length() < max_len) {
seq += '-';
}
}
// Reset caches
cached_max_length = -1;
consensus_dirty = true;
// Invalidate amino acid translations
invalidateTranslations();
// Check if sequences are DNA
checkIfDNA();
}
// Optimized getters that return raw data for batch processing
std::string getSequenceData(int seq_idx) {
if (seq_idx >= 0 && seq_idx < sequences.size()) {
return sequences[seq_idx];
}
return "";
}
// Get character at position - inline for speed
inline char getCharAt(int seq_idx, int pos_idx) {
if (seq_idx >= 0 && seq_idx < sequences.size() &&
pos_idx >= 0 && pos_idx < sequences[seq_idx].length()) {
return sequences[seq_idx][pos_idx];
}
return ' ';
}
// Wrapper for JavaScript that takes char code instead of char
uint32_t getColorForCharacter(int charCode) {
return getColorInt(static_cast<char>(charCode));
}
// Return color as integer for faster transfer
uint32_t getColorInt(char c) {
// Updated color scheme for nucleotides
static const std::unordered_map<char, uint32_t> nuc_colors = {
{'A', 0xFF0000}, // Red
{'T', 0x87CEEB}, // Light Blue (Sky Blue)
{'G', 0xFFD700}, // Yellow (Gold)
{'C', 0x00FF00}, // Green
{'U', 0x87CEEB}, // Light Blue (same as T)
{'-', 0xF0F0F0}, // Very light gray for gaps
{'N', 0xE0E0E0} // Light gray for ambiguous
};
// Check if this is a DNA sequence - only use nucleotide colors for DNA
if (is_dna_sequences) {
auto nuc_it = nuc_colors.find(c);
if (nuc_it != nuc_colors.end()) return nuc_it->second;
}
// For protein sequences or characters not in nucleotide set, use amino acid colors
auto aa_it = amino_acid_colors.find(c);
if (aa_it != amino_acid_colors.end()) {
// Remove the FF alpha suffix since getRenderData expects RGB only
return aa_it->second >> 8;
}
return 0x95A5A6; // Default gray
}
// Batch operations for rendering
val getRenderData(int startRow, int endRow, int startCol, int endCol, bool aminoAcidMode = false) {
val result = val::object();
val rows = val::array();
// Ensure valid bounds
startRow = std::max(0, startRow);
endRow = std::min(endRow, (int)sequences.size());
startCol = std::max(0, startCol);
endCol = std::max(0, endCol);
for (int r = startRow; r < endRow && r < sequences.size(); r++) {
val row = val::object();
const std::string& seq = sequences[r];
int seqLen = seq.length();
std::string visibleChars;
val colors = val::array();
// Use pre-translated amino acid sequences if in amino acid display mode
if (r == 0 && startCol == 0) {
SLOP_LOG("getRenderData: aminoAcidMode=%d, codon_mode=%d, valid=%d, size=%zu\n",
aminoAcidMode, codon_mode_enabled, amino_acid_translations_valid, amino_acid_sequences.size());
}
if (aminoAcidMode && codon_mode_enabled && amino_acid_translations_valid && r < amino_acid_sequences.size()) {
const std::string& aa_seq = amino_acid_sequences[r];
for (int c = startCol; c < endCol; c++) {
if (c < aa_seq.length()) {
char aa = aa_seq[c];
visibleChars += aa;
// Get color for amino acid (or space)
if (aa != ' ') {
colors.call<void>("push", getCodonColor(r, c));
} else {
colors.call<void>("push", 0);
}
} else {
visibleChars += ' ';
colors.call<void>("push", 0);
}
}
} else {
// Normal nucleotide or codon mode
for (int c = startCol; c < endCol; c++) {
if (c < seqLen) {
visibleChars += seq[c];
// Use codon color if in codon mode, otherwise regular nucleotide color
if (codon_mode_enabled) {
colors.call<void>("push", getCodonColor(r, c));
} else {
colors.call<void>("push", getColorInt(seq[c]));
}
} else {
// Pad with spaces if beyond sequence length
visibleChars += ' ';
colors.call<void>("push", getColorInt(' '));
}
}
}
row.set("chars", visibleChars);
row.set("colors", colors);
row.set("name", sequence_names[r]);
rows.call<void>("push", row);
}
result.set("rows", rows);
return result;
}
void startSelection(int row, int col) {
selection_start_row = row;
selection_start_col = col;
selection_end_row = row;
selection_end_col = col;
}
void updateSelection(int row, int col) {
selection_end_row = row;
selection_end_col = col;
}
void clearSelection() {
selection_start_row = -1;
selection_start_col = -1;
selection_end_row = -1;
selection_end_col = -1;
}
bool isSelected(int row, int col) {
if (selection_start_row < 0) return false;
int min_row = std::min(selection_start_row, selection_end_row);
int max_row = std::max(selection_start_row, selection_end_row);
int min_col = std::min(selection_start_col, selection_end_col);
int max_col = std::max(selection_start_col, selection_end_col);
return row >= min_row && row <= max_row && col >= min_col && col <= max_col;
}
// Optimized gap operations
void removeGapsFromSelection() {
if (selection_start_row < 0) return;
int min_row = std::min(selection_start_row, selection_end_row);
int max_row = std::max(selection_start_row, selection_end_row);
int min_col = std::min(selection_start_col, selection_end_col);
int max_col = std::max(selection_start_col, selection_end_col);
for (int row = min_row; row <= max_row && row < sequences.size(); row++) {
std::string& seq = sequences[row];
std::string new_seq;
new_seq.reserve(seq.length());
for (int i = 0; i < seq.length(); i++) {
if (i < min_col || i > max_col || seq[i] != '-') {
new_seq += seq[i];
}
}
seq = std::move(new_seq);
}
// Pad all sequences to the same length after removing gaps
padSequencesToMaxLength();
consensus_dirty = true;
// Invalidate cached max length since sequences may have changed length
cached_max_length = -1;
}
// Helper function to pad all sequences to the same length
void padSequencesToMaxLength() {
int max_len = 0;
for (const auto& seq : sequences) {
max_len = std::max(max_len, (int)seq.length());
}
// Pad shorter sequences with gaps
for (auto& seq : sequences) {
if (seq.length() < max_len) {
seq.append(max_len - seq.length(), '-');
}
}
}
void dragEdit(int delta_col) {
if (selection_start_row < 0 || delta_col == 0) return;
int min_row = std::min(selection_start_row, selection_end_row);
int max_row = std::max(selection_start_row, selection_end_row);
int min_col = std::min(selection_start_col, selection_end_col);
int max_col = std::max(selection_start_col, selection_end_col);
if (delta_col > 0) {
// Moving right - insert gaps to the left of selection
std::string gaps(delta_col, '-');
for (int row = min_row; row <= max_row && row < sequences.size(); row++) {
sequences[row].insert(min_col, gaps);
}
selection_start_col += delta_col;
selection_end_col += delta_col;
// Pad all other sequences to match the new maximum length
padSequencesToMaxLength();
} else if (delta_col < 0) {
// Moving left - remove gaps from the left of selection if they exist
int abs_delta = -delta_col;
int gaps_removed = 0;
// Check how many gaps we can actually remove
for (int row = min_row; row <= max_row && row < sequences.size(); row++) {
int gaps_available = 0;
for (int i = 1; i <= abs_delta && min_col - i >= 0; i++) {
if (sequences[row][min_col - i] == '-') {
gaps_available++;
} else {
break; // Stop if we hit a non-gap
}
}
gaps_removed = (row == min_row) ? gaps_available : std::min(gaps_removed, gaps_available);
}
// Remove the gaps
if (gaps_removed > 0) {
for (int row = min_row; row <= max_row && row < sequences.size(); row++) {
sequences[row].erase(min_col - gaps_removed, gaps_removed);
}
selection_start_col -= gaps_removed;
selection_end_col -= gaps_removed;
}
// Don't insert gaps on the right - just don't move if can't go left
}
consensus_dirty = true;
// Invalidate cached max length since sequences may have grown
cached_max_length = -1;
}
// Lazy consensus calculation
std::string getConsensusRange(int startCol, int endCol) {
int max_len = getMaxLength();
endCol = std::min(endCol, max_len);
std::string result;
result.reserve(endCol - startCol);
for (int pos = startCol; pos < endCol; pos++) {
std::unordered_map<char, int> counts;
int max_count = 0;
char max_char = '-';
for (const auto& seq : sequences) {
if (pos < seq.length() && seq[pos] != '-') {
int count = ++counts[seq[pos]];
if (count > max_count) {
max_count = count;
max_char = seq[pos];
}
}
}
result += max_char;
}
return result;
}
// Get amino acid consensus for codon mode
std::string getAminoAcidConsensusRange(int startCol, int endCol) {
if (!codon_mode_enabled) {
return getConsensusRange(startCol, endCol);
}
int max_len = getMaxLength();
endCol = std::min(endCol, max_len);
std::string result;
result.reserve(endCol - startCol);
const int phase = codon_phase - 1;
for (int pos = startCol; pos < endCol; pos++) {
// Always calculate amino acid consensus for every position
// The JavaScript will handle which positions to display
std::unordered_map<char, int> aa_counts;
int max_count = 0;
char max_aa = '-';
// For positions before phase, just add a gap
const int adjustedPos = pos - phase;
if (adjustedPos < 0) {
result += '-';
continue;
}
// Get the codon start position for this column
int codon_start = (adjustedPos / 3) * 3 + phase;
for (int seq_idx = 0; seq_idx < sequences.size(); seq_idx++) {
// Get the amino acid for the codon that contains this position
char aa = getAminoAcidAt(seq_idx, codon_start);
if (aa != ' ' && aa != '-') {
int count = ++aa_counts[aa];
if (count > max_count) {
max_count = count;
max_aa = aa;
}
}
}
result += max_aa;
}
return result;
}
float getConservation(int pos) {
if (sequences.empty() || pos < 0) return 0.0;
std::unordered_map<char, int> counts;
int total = 0;
for (const auto& seq : sequences) {
if (pos < seq.length() && seq[pos] != '-') {
counts[seq[pos]]++;
total++;
}
}
if (total == 0) return 0.0;
int max_count = 0;
for (const auto& pair : counts) {
max_count = std::max(max_count, pair.second);
}
return (float)max_count / total * 100.0;
}
int getSequenceCount() { return sequences.size(); }
int getMaxLength() {
if (cached_max_length < 0) {
cached_max_length = 0;
for (const auto& seq : sequences) {
cached_max_length = std::max(cached_max_length, (int)seq.length());
}
}
return cached_max_length;
}
std::string getSequenceName(int idx) {
return (idx >= 0 && idx < sequence_names.size()) ? sequence_names[idx] : "";
}
val getSelectionBounds() {
val bounds = val::object();
if (selection_start_row >= 0) {
bounds.set("minRow", std::min(selection_start_row, selection_end_row));
bounds.set("maxRow", std::max(selection_start_row, selection_end_row));
bounds.set("minCol", std::min(selection_start_col, selection_end_col));
bounds.set("maxCol", std::max(selection_start_col, selection_end_col));
} else {
bounds.set("minRow", -1);
}
return bounds;
}
// Calculate alignment score with affine gap penalties
int calculateScore() {
int score = 0;
// Simple scoring: penalize gaps, reward matches
for (const auto& seq : sequences) {
bool in_gap = false;
for (char c : seq) {
if (c == '-') {
score += in_gap ? gap_extend_penalty : gap_open_penalty;
in_gap = true;
} else {
in_gap = false;
}
}
}
// Add match/mismatch scoring for conservation
int max_len = getMaxLength();
for (int pos = 0; pos < max_len; pos++) {
std::unordered_map<char, int> counts;
int total = 0;
for (const auto& seq : sequences) {
if (pos < seq.length() && seq[pos] != '-') {
counts[seq[pos]]++;
total++;
}
}
if (total > 1) {
int max_count = 0;
for (const auto& pair : counts) {
max_count = std::max(max_count, pair.second);
}
// Reward conservation
score += (max_count - 1) * match_score;
score += (total - max_count) * mismatch_penalty;
}
}
return score;
}
// Reorder sequences
void moveSequence(int from_idx, int to_idx) {
if (from_idx < 0 || from_idx >= sequences.size() ||
to_idx < 0 || to_idx >= sequences.size() ||
from_idx == to_idx) return;
std::string seq = sequences[from_idx];
std::string name = sequence_names[from_idx];
if (from_idx < to_idx) {
// Moving down
for (int i = from_idx; i < to_idx; i++) {
sequences[i] = sequences[i + 1];
sequence_names[i] = sequence_names[i + 1];
}
} else {
// Moving up
for (int i = from_idx; i > to_idx; i--) {
sequences[i] = sequences[i - 1];
sequence_names[i] = sequence_names[i - 1];
}
}
sequences[to_idx] = seq;
sequence_names[to_idx] = name;
}
// Select entire row
void selectRow(int row) {
if (row >= 0 && row < sequences.size()) {
selection_start_row = row;
selection_end_row = row;
selection_start_col = 0;
selection_end_col = getMaxLength() - 1;
if (selection_end_col < 0) selection_end_col = 0;
}
}
// Select entire column
void selectColumn(int col) {
if (col >= 0 && col < getMaxLength()) {
selection_start_row = 0;
selection_end_row = sequences.size() - 1;
selection_start_col = col;
selection_end_col = col;
}
}
// ========== PDF EXPORT FUNCTIONALITY ==========
// Helper: Convert RGB color to PDF color (0.0 - 1.0 range)
struct PDFColor {
float r, g, b;
static PDFColor fromRGB(uint32_t color) {
PDFColor c;