-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.cpp
4364 lines (4186 loc) · 150 KB
/
common.cpp
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 "common.h"
#include <assert.h>
#include <limits.h>
#include <algorithm>
#include <math.h>
#include <string>
#include <cstdio>
#include <sstream>
#include <numeric>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#ifndef NO_OPENMP
#include<omp.h>
#define WITH_OPENMP " (+OpenMP)"
#else
#define WITH_OPENMP ""
#define omp_set_num_threads(T) (T = T)
#define omp_get_thread_num() 0
#endif
int min(int x, int y) {
return (x>y ? y : x);
}
int max(int x, int y) {
return (x>y ? x : y);
}
template <typename T>
vector<unsigned int> sort_indexes(const vector<T> &v) {
// 初始化索引向量
vector<unsigned int> idx(v.size());
//使用iota对向量赋0~?的连续值
iota(idx.begin(), idx.end(), 0);
// 通过比较v的值对索引idx进行排序
sort(idx.begin(), idx.end(),
[&v](unsigned int i1, unsigned int i2) {return v[i1] < v[i2]; });
return idx;
}
//int aa2idx[] = { 0, 2, 4, 3, 6, 13,7, 8, 9,20,11,10,12, 2,20,14,
//5, 1,15,16,20,19,17,20,18, 6 };
// idx for A B C D E F G H I J K L M N O P
// Q R S T U V W X Y Z
// so aa2idx[ X - 'A'] => idx_of_X, eg aa2idx['A' - 'A'] => 0,
// and aa2idx['M'-'A'] => 12
int aa2idx_ACGT[] = { 0, -1, 1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3 };
// index for A B C D E F G H I J K L M N O P Q R S T
// so aa2idx_ACGT[ X - 'A'] => idx_of_X
// eg aa2idx_ACGT['A' - 'A'] => 0, aa2idx_ACGT['T' - 'A'] => 3.
// kmer weight 1 2 3 4 5 6 7 8 9 10
unsigned int NAAN_array[15] = { 1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144,
1048576, 4194304, 16777216, 67108864, 268435456 };
// 11 12 13 14 15
// node for sort
struct node
{
unsigned int data;
unsigned int index_in_genome;
unsigned int index_in_sequence;
};
int comp(const void *a, const void *b) { // ascending order for struct
return (*(struct node *)a).data> (*(struct node *)b).data ? 1 : -1;
}
struct TempFile
{
FILE *file;
char buf[512];
TempFile(const char *dir = NULL) {
int len = dir ? strlen(dir) : 0;
assert(len < 400);
buf[0] = 0;
if (len) {
strcat(buf, dir);
if (buf[len - 1] != '/' && buf[len - 1] != '\\') {
buf[len] = '/';
len += 1;
}
}
strcat(buf, "cdhit.temp.");
len += 11;
sprintf(buf + len, "%p", this);
file = fopen(buf, "w+");
}
~TempFile() {
if (file) {
fclose(file);
remove(buf);
}
}
};
struct TempFiles
{
NVector<TempFile*> files;
~TempFiles() { Clear(); }
void Clear() {
int i;
#pragma omp critical
{
for (i = 0; i<files.size; i++) if (files[i]) delete files[i];
files.Clear();
}
}
};
const char *temp_dir = "";
TempFiles temp_files;
FILE* OpenTempFile(const char *dir = NULL)
{
TempFile *file = new TempFile(dir);
#pragma omp critical
{
temp_files.files.Append(file);
}
return file->file;
}
static void CleanUpTempFiles()
{
if (temp_files.files.Size()) printf("Clean up temporary files ...\n");
temp_files.Clear();
}
void bomb_error(const char *message)
{
fprintf(stderr, "\nFatal Error:\n%s\nProgram halted !!\n\n", message);
temp_files.Clear();
exit(1);
} // END void bomb_error
string getTime() {
time_t timep;
time(&timep);
char tmp[64];
strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S", localtime(&timep));
return tmp;
}
// sort methods
// insert sorting and return the original index
// 插入排序法
vector<unsigned int> insertSort(vector<unsigned int> &num) {
vector<unsigned int> index_original(num.size());
#pragma omp parallel for schedule( dynamic, 1 )
for (unsigned int i = 1; i < num.size(); ++i) {
index_original[i] = i;
}
for (unsigned int i = 1; i < num.size(); ++i) {
for (unsigned int j = i; j > 0; --j) {
if (num[j] < num[j - 1]) {
unsigned int temp = num[j];
num[j] = num[j - 1];
num[j - 1] = temp;
index_original[j] = j - 1;
index_original[j - 1] = j;
}
}
}
return index_original;
}
void Merge(vector<unsigned int> & A, unsigned int left, unsigned int mid, unsigned int right)// 合并两个已排好序的数组A[left...mid]和A[mid+1...right]
{
int len = right - left + 1;
int *temp = new int[len]; // 辅助空间O(n)
int index = 0;
int i = left; // 前一数组的起始元素
int j = mid + 1; // 后一数组的起始元素
while (i <= mid && j <= right)
{
temp[index++] = A[i] <= A[j] ? A[i++] : A[j++]; // 带等号保证归并排序的稳定性
}
while (i <= mid)
{
temp[index++] = A[i++];
}
while (j <= right)
{
temp[index++] = A[j++];
}
for (int k = 0; k < len; k++)
{
A[left++] = temp[k];
}
delete temp;
}
void MergeAndIndex(vector<unsigned int> & A, unsigned int left, unsigned int mid, unsigned int right, vector<unsigned int> & idx) {
int len = right - left + 1;
int *temp = new int[len]; // 辅助空间O(n)
int *temp_index = new int[len]; // 辅助空间O(n)
int index = 0;
int i = left; // 前一数组的起始元素
int j = mid + 1; // 后一数组的起始元素
while (i <= mid && j <= right)
{
if (A[i] <= A[j]) {
temp[index] = A[i];
temp_index[index++] = idx[i++];
}
else {
temp[index] = A[j];
temp_index[index++] = idx[j++];
}
//temp[index] = A[i] <= A[j] ? A[i++] : A[j++]; // 带等号保证归并排序的稳定性
//temp_index[index++] = A[i] <= A[j] ? idx[i++] : idx[j++];
}
while (i <= mid)
{
temp[index] = A[i];
temp_index[index++] = idx[i++];
}
while (j <= right)
{
temp[index] = A[j];
temp_index[index++] = idx[j++];
}
for (int k = 0; k < len; k++)
{
A[left] = temp[k];
idx[left++] = temp_index[k];
}
delete temp;
delete temp_index;
}
void MergeAndIndex_with_matrix_point(unsigned int * A, unsigned int left, unsigned int mid, unsigned int right, unsigned int * idx) {
unsigned int len = right - left + 1;
unsigned int *temp = new unsigned int[len]; // 辅助空间O(n)
unsigned int *temp_index = new unsigned int[len]; // 辅助空间O(n)
unsigned int index = 0;
unsigned int i = left; // 前一数组的起始元素
unsigned int j = mid + 1; // 后一数组的起始元素
while (i <= mid && j <= right)
{
if (A[i] <= A[j]) {
temp[index] = A[i];
temp_index[index++] = idx[i++];
}
else {
temp[index] = A[j];
temp_index[index++] = idx[j++];
}
//temp[index] = A[i] <= A[j] ? A[i++] : A[j++]; // 带等号保证归并排序的稳定性
//temp_index[index++] = A[i] <= A[j] ? idx[i++] : idx[j++];
}
while (i <= mid)
{
temp[index] = A[i];
temp_index[index++] = idx[i++];
}
while (j <= right)
{
temp[index] = A[j];
temp_index[index++] = idx[j++];
}
for (unsigned int k = 0; k < len; k++)
{
A[left] = temp[k];
idx[left++] = temp_index[k];
}
delete temp;
delete temp_index;
}
void MergeSortRecursion(vector<unsigned int> & A, unsigned int left, unsigned int right) // 递归实现的归并排序(自顶向下)
{
if (left == right) // 当待排序的序列长度为1时,递归开始回溯,进行merge操作
return;
unsigned int mid = (left + right) / 2;
MergeSortRecursion(A, left, mid);
MergeSortRecursion(A, mid + 1, right);
Merge(A, left, mid, right);
}
void MergeSortRecursionAndIndex(vector<unsigned int> & A, unsigned int left, unsigned int right, vector<unsigned int> & index) // 递归实现的归并排序(自顶向下)
{
if (left == right) // 当待排序的序列长度为1时,递归开始回溯,进行merge操作
return;
unsigned int mid = (left + right) / 2;
MergeSortRecursionAndIndex(A, left, mid, index);
MergeSortRecursionAndIndex(A, mid + 1, right, index);
MergeAndIndex(A, left, mid, right, index);
}
// sort matrix
void MergeSortRecursionAndIndex_with_matrix_point(unsigned int * A, unsigned int left, unsigned int right, unsigned int * index) // 递归实现的归并排序(自顶向下)
{
if (left == right) // 当待排序的序列长度为1时,递归开始回溯,进行merge操作
return;
unsigned int mid = (left + right) / 2;
MergeSortRecursionAndIndex_with_matrix_point(A, left, mid, index);
MergeSortRecursionAndIndex_with_matrix_point(A, mid + 1, right, index);
MergeAndIndex_with_matrix_point(A, left, mid, right, index);
}
void MergeSortIterationAndIndex_with_matrix_point(unsigned int * A, unsigned int len, unsigned int * index) {
long long int left, mid, right;
for (long long int i = 1; i < len; i *= 2) {
printf("i = %lld, len = %u\n", i, len);
left = 0;
while (left + i < len) {
mid = left + i - 1;
right = mid + i < len ? mid + i : len - 1;
MergeAndIndex_with_matrix_point(A, left, mid, right, index);
left = right + 1;
}
}
}
void MergeSortIteration(vector<unsigned int> & A, unsigned int len) // 非递归(迭代)实现的归并排序(自底向上)
{
unsigned int left, mid, right;// 子数组索引,前一个为A[left...mid],后一个子数组为A[mid+1...right]
for (unsigned int i = 1; i < len; i *= 2) // 子数组的大小i初始为1,每轮翻倍
{
left = 0;
while (left + i < len) // 后一个子数组存在(需要归并)
{
mid = left + i - 1;
right = mid + i < len ? mid + i : len - 1;// 后一个子数组大小可能不够
Merge(A, left, mid, right);
left = right + 1; // 前一个子数组索引向后移动
}
}
}
int print_usage() {
cout << "*****************************************************************************" << endl;
cout << "=============== Usage example(build genome library): ================" << endl;
cout << "./smsAlign -build -i genome.fa -o genome_lib.txt" << endl << endl;
cout << "-----build required:" << endl;
cout << "-i input genome fasta file (e.g. -i genome.fa)." << endl;
cout << "-o output library file (e.g. -o genome_lib.txt)." << endl;
cout << " \n----build optional:" << endl;
cout << "-k k-mer length (default: 11)." << endl;
cout << "\n=============== Uasge example(locate sequence position): ===============" << endl;
cout << "./smsAlign -locate -i sequence.fasta -lib genomeLib.txt -o seqPos.txt" << endl;
cout << "-----locate required:" << endl;
cout << "-i input sequence file (e.g. -i sequence.fa)." << endl;
cout << "-lib genome library file (e.g. -genome_lib.txt)." << endl;
cout << "-o output file (e.g. -o seqPos.txt)." << endl;
cout << "\n----locate optional:" << endl;
cout << "-T the threads number (default: your computer has)." << endl;
cout << "\n================ Uasge example(align sequences): ===============" << endl;
cout << "./smsAlign -align -i sequence.fa -pos seqPos.txt -j genome.fa -o aligned.txt" << endl << endl;
cout << "-----Align required:" << endl;
cout << "-i input sequence file (e.g. -i sequence.fa)." << endl;
cout << "-j genome sequence file (e.g. -j genome.fa)." << endl;
cout << "-pos sequence position file (e.g. -pos seqPos.txt)." << endl;
cout << "\n----Align optional:" << endl;
//cout << "-k k-mer length (default: 11)." << endl;
cout << "-T the threads number (default: your computer has)." << endl;
//cout << "-sam SAM format output e.g. -sam samOut.txt (default: no sam output)." << endl;
cout << "-ms match score in the sequence alignment (default: 2)." << endl;
cout << "-ss substitution (mismatch) score in the sequence alignment (default: -2)." << endl;
cout << "-gs gap score in the sequence alignment (default: -2)." << endl;
cout << "-h print this usage (or --help)." << endl;
return 0;
}
int print_usage_genome_library_build() {
cout << "====================================================" << endl;
cout << "Uasge example:" << endl;
cout << "./smsAlign -build -i genome.fa -o genome_lib.txt" << endl << endl;
cout << "-----build required:" << endl;
cout << "-i genome sequence file (e.g. -i genome.fa)." << endl;
cout << "-o output library file (e.g. -o genome_lib.txt)." << endl;
cout << " \n----build optional:" << endl;
cout << "-k k-mer length (default: 15)." << endl;
//cout << "Usage: ./smsAlignGenomeLibBuild genome_file output_file_name -k number of kmer (default 11), -T CPU number (default 10)" << endl;
return 0;
}
int print_usage_sequence_position_locate() {
cout << "====================================================" << endl;
cout << "Usage example:" << endl;
cout << "./smsAlign -locate -i sequence.fasta -lib genomeLib.txt -o seqPos.txt" << endl;
cout << "-----Locate required:" << endl;
cout << "-i input sequence file (e.g. -i sequence.fa)." << endl;
cout << "-lib genome library file (e.g. -genome_lib.txt)." << endl;
cout << "-o output file (e.g. -o seqPos.txt)." << endl;
cout << "\n----Locate optional:" << endl;
cout << "-T the threads number (default: your computer has)." << endl;
return 0;
}
int print_usage_sequence_banded_alignment() {
cout << "====================================================" << endl;
cout << "Usage example:" << endl;
cout << "smsMap --seq sequence.fa --pos pos.txt --genome genome.fa -out aligned.txt" << endl << endl;
cout << "-----Align required:" << endl;
cout << "--seq input sequence file." << endl;
cout << "--genome genome sequence file." << endl;
cout << "--pos sequence position file." << endl;
cout << "--out output aligned file." << endl;
//cout << "\n----Align optional:" << endl;
//cout << "-k k-mer length (default: 11)." << endl;
//cout << "-T the threads number (default: your computer has)." << endl;
cout << "-h print this usage (or --help)." << endl;
//cout << "-sam SAM format output e.g. -sam samOut.txt (default: no sam output)." << endl;
//cout << "-ms match score in the sequence alignment (default: 2)." << endl;
//cout << "-ss substitution (mismatch) score in the sequence alignment (default: -2)." << endl;
//cout << "-gs gap score in the sequence alignment (default: -2)." << endl;
//cout << "-h print this usage (or --help)." << endl;
return 0;
}
bool Options::SetOptions(int argc, const char *argv[])
{
int i, n;
char date[100];
strcpy(date, __DATE__);
n = strlen(date);
for (i = 1; i < n; i++) {
if (date[i - 1] == ' ' && date[i] == ' ')
date[i] = '0';
}
printf("================================================================\n");
printf("Program: , V" VERSION WITH_OPENMP ", %s, " __TIME__ "\n", date);
printf("Your command:");
//n = 9;
for (i = 0; i<argc; i++) {
printf(" %s", argv[i]);
}
printf("\n\n");
time_t tm = time(NULL);
printf("Started: %s", ctime(&tm));
printf("================================================================\n");
printf(" Output \n");
printf("----------------------------------------------------------------\n");
for (i = 1; i + 1<argc; i += 2) {
//printf("\n argv[%d]= %s", i, argv[i]);
//printf("\n argv[%d]= %s", i + 1, argv[i + 1]);
bool dddd = SetOption(argv[i], argv[i + 1]);
if (dddd == 0) return false;
}
if (i < argc) return false;
atexit(CleanUpTempFiles);
return true;
}
bool Options::SetOption(const char *flag, const char *value)
{
bool ffff = SetOptionCommon(flag, value);
return ffff;
}
void Options::SetKmerlength(int aaa) {
kmer_length = aaa;
}
void Options::SetMaxBandedWidth(int ww) {
max_banded_width = ww;
}
bool Options::SetOptionCommon(const char *flag, const char *value)
{
int intval = atoi(value);
if (strcmp(flag, "--seq") == 0) input = value;
else if (strcmp(flag, "--genome") == 0) genome = value;
else if (strcmp(flag, "-lib") == 0) genomeLibFile = value; //genome library file
else if (strcmp(flag, "--pos") == 0) sequencePosFile = value; //genome library file
else if (strcmp(flag, "--out") == 0) output = value;
else if (strcmp(flag, "-m") == 0) model = value;
else if (strcmp(flag, "-M") == 0) max_memory = atol(value) * 1000000;
else if (strcmp(flag, "-k") == 0) kmer_length = intval;
//else if (strcmp(flag, "-b") == 0) banded_width = intval;
else if (strcmp(flag, "-p") == 0) print = intval;
//else if (strcmp(flag, "-tmp") == 0) temp_dir = value;
else if (strcmp(flag, "-min") == 0) min_length = intval;
else if (strcmp(flag, "-ms") == 0) match_score = intval;
else if (strcmp(flag, "-ss") == 0) mismatch_score = intval;
else if (strcmp(flag, "-gs") == 0) gap_score = intval;
else if (strcmp(flag, "-h") == 0 || strcmp(flag, "--help") == 0) {
print_usage();
exit(1);
}
else if (strcmp(flag, "-T") == 0) {
#ifndef NO_OPENMP
int cpu = omp_get_num_procs();
threads = intval;
if (threads > cpu) {
threads = cpu;
printf("Warning: total number of CPUs in your system is %i\n", cpu);
}
if (threads == 0) {
threads = cpu;
printf("total number of CPUs in your system is %i\n", cpu);
}
if (threads != intval) printf("Actual number of CPUs to be used: %i\n\n", threads);
#else
printf("Option -T is ignored: multi-threading with OpenMP is NOT enabled!\n");
#endif
}
else return false;
return true;
}
void Options::Validate()
{
if (model.compare("edlib") != 0 && model.compare("banded") != 0)
bomb_error("Invalid alignment model (-m setting) detected!!!");
if (kmer_length < 1 || kmer_length > 20) bomb_error("Invalid k-mer length, k should be 1 < k < 20");
if (banded_width < 1) bomb_error("Invalid band width");
if (min_length < 1) bomb_error("Invalid minimum length");
#ifndef NO_OPENMP
int cpu = omp_get_num_procs();
threads = cpu;
#else
printf("Option -T is ignored: multi-threading with OpenMP is NOT enabled!\n");
#endif
}
void Options::Print()
{
//printf("query_file = %i\n", input);
printf("min_length = %i\n", min_length);
printf("kmer_length = %i\n", kmer_length);
printf("threads = %i\n", threads);
printf("match_score = %i\n", match_score);
printf("mismatch_score = %i\n", mismatch_score);
printf("gap_score = %i\n", gap_score);
printf("print = %i\n", print);
}
void Sequence::Clear()
{
if (data) delete[] data;
/* do not set size to zero here, it is need for writing output */
bufsize = 0;
data = NULL;
}
Sequence::Sequence()
{
memset(this, 0, sizeof(Sequence));
plus = -1;
position_in_sequence = 0;
position_in_genome = 0;
position_in_genome_minus = 0;
nMatch = 0;
nSubsitute = 0;
nDelete = 0;
nInsert = 0;
}
Sequence::Sequence(const Sequence & other)
{
int i;
//printf( "new: %p %p\n", this, & other );
memcpy(this, &other, sizeof(Sequence));
if (other.data) {
size = bufsize = other.size;
data = new char[size + 1];
//printf( "data: %p %p\n", data, other.data );
data[size] = 0;
memcpy(data, other.data, size);
//for (i=0; i<size; i++) data[i] = other.data[i];
}
if (other.identifier) {
int len = strlen(other.identifier);
identifier = new char[len + 1];
memcpy(identifier, other.identifier, len);
identifier[len] = 0;
}
}
Sequence::~Sequence()
{
//printf( "delete: %p\n", this );
if (data) delete[] data;
if (identifier) delete[] identifier;
}
void Sequence::operator=(const char *s)
{
size = 0; // avoid copying;
Resize(strlen(s));
strcpy(data, s);
}
void Sequence::operator+=(const char *s)
{
int i, m = size, n = strlen(s);
Reserve(m + n);
memcpy(data + m, s, n);
}
void Sequence::Resize(int n)
{
int i, m = size < n ? size : n;
size = n;
if (size != bufsize) {
char *old = data;
bufsize = size;
data = new char[bufsize + 1];
if (data == NULL) bomb_error("Memory");
if (old) {
memcpy(data, old, m);
delete[]old;
}
if (size) data[size] = 0;
}
}
void Sequence::Reserve(int n)
{
int i, m = size < n ? size : n;
size = n;
if (size > bufsize) {
char *old = data;
bufsize = size + size / 5 + 1;
data = new char[bufsize + 1];
if (data == NULL) bomb_error("Memory");
if (old) {
memcpy(data, old, m);
delete[]old;
}
}
if (size) data[size] = 0;
}
void Sequence::Set_aligned_information(string a1, string a2, string midd, int nmattch, int nsubsitute, int ninsert, int deleten, int aligned_base_n, double sim) {
aligned1 = new char[a1.size() + 1];
aligned1[a1.size()] = 0;
memcpy(aligned1, a1.c_str(), a1.size());
aligned2 = new char[a2.size() + 1];
aligned2[a2.size()] = 0;
memcpy(aligned2, a2.c_str(), a2.size());
middle = new char[midd.size() + 1];
middle[midd.size()] = 0;
memcpy(middle, midd.c_str(), midd.size());
nMatch = nmattch;
nSubsitute = nsubsitute;
nDelete = deleten;
nInsert = ninsert;
identify = sim;
nAlignedBase = aligned_base_n;
}
void Sequence::Set_sequence_locate(short direction, unsigned int pos_in_seq, unsigned int pos_in_gen, unsigned int pos_in_gen_minus) {
plus = direction;
position_in_sequence = pos_in_seq;
if (direction == 1) {//plus direction
position_in_genome = pos_in_gen;
}
else if (direction == 0) {
position_in_genome_minus = pos_in_gen_minus;
}
else {
position_in_genome = -1;
}
}
/*
void Sequence::ConvertBases()
{
int i, indexBase;
//cout << *data << endl;
for (i = 0; i < size; i++) {
indexBase = aa2idx_ACGT[data[i] - 'A'];
data[i] = indexBase * weight;
//int a = toascii(data[i]);
//printf("haha=%d, toascii = %d\n", data[i], a);
//cout<<data[i];
}
}
*/
void Sequence::Swap(Sequence & other)
{
Sequence tmp;
memcpy(&tmp, this, sizeof(Sequence));
memcpy(this, &other, sizeof(Sequence));
memcpy(&other, &tmp, sizeof(Sequence));
memset(&tmp, 0, sizeof(Sequence));
}
int Sequence::Format()
{
int i, j = 0, m = 0;
while (size && isspace(data[size - 1])) size--;
if (size && data[size - 1] == '*') size--;
if (size) data[size] = 0;
for (i = 0; i<size; i++) {
char ch = data[i];
m += !(isalpha(ch) | isspace(ch));
}
if (m) return m;
for (i = 0; i<size; i++) {
char ch = data[i];
if (isalpha(ch)) data[j++] = toupper(ch);
}
data[j] = 0;
size = j;
return 0;
}
void Sequence::SwapIn()
{
if (data) return;
if (swap == NULL) bomb_error("Can not swap in sequence");
Resize(size);
fseek(swap, offset, SEEK_SET);
if (fread(data, 1, size, swap) == 0) bomb_error("Can not swap in sequence");
data[size] = 0;
}
void Sequence::SwapOut()
{
if (swap && data) {
delete[] data;
bufsize = 0;
data = NULL;
}
}
void SequenceDB::Read(const char *file, const Options & options)
{
Sequence one;
Sequence dummy;
Sequence des;
Sequence *last = NULL;
FILE *swap = NULL;
FILE *fin = fopen(file, "r");
char *buffer = NULL;
char *res = NULL;
size_t swap_size = 0;
int option_l = options.min_length;
if (fin == NULL) bomb_error("Failed to open the sequence file");
Clear();
dummy.swap = swap;
buffer = new char[MAX_LINE_SIZE + 1];
while (!feof(fin) || one.size) { /* do not break when the last sequence is not handled */
buffer[0] = '>';
if ((res = fgets(buffer, MAX_LINE_SIZE, fin)) == NULL && one.size == 0)
break;
if (buffer[0] == '+') {
int len = strlen(buffer);
int len2 = len;
while (len2 && buffer[len2 - 1] != '\n') {
if ((res = fgets(buffer, MAX_LINE_SIZE, fin)) == NULL) break;
len2 = strlen(buffer);
len += len2;
}
one.des_length2 = len;
dummy.des_length2 = len;
fseek(fin, one.size, SEEK_CUR);
}
else if (buffer[0] == '>' || buffer[0] == '@' || (res == NULL && one.size)) {
if (one.size) { // write previous record
one.dat_length = dummy.dat_length = one.size;
if (one.identifier == NULL || one.Format()) {
printf("Warning: from file \"%s\",\n", file);
printf("Discarding invalid sequence or sequence without header and description!\n\n");
if (one.identifier) printf("%s\n", one.identifier);
printf("%s\n", one.data);
one.size = 0;
}
one.index = dummy.index = sequences.size();
if (one.size > 0) {
if (swap) {
swap_size += one.size;
// so that size of file < MAX_BIN_SWAP about 2GB
if (swap_size >= MAX_BIN_SWAP) {
dummy.swap = swap = OpenTempFile(temp_dir);
swap_size = one.size;
}
dummy.size = one.size;
dummy.offset = ftell(swap);
dummy.des_length = one.des_length;
dummy.plus = -1;
sequences.Append(new Sequence(dummy));
//one.ConvertBases();
fwrite(one.data, 1, one.size, swap);
}
else {
//printf( "==================\n" );
sequences.Append(new Sequence(one));
//printf( "------------------\n" );
//if( sequences.size() > 10 ) break;
}
//if( sequences.size() >= 10000 ) break;
}
}
one.size = 0;
one.des_length2 = 0;
int len = strlen(buffer);
int len2 = len;
des.size = 0;
des += buffer;
while (len2 && buffer[len2 - 1] != '\n') {
if ((res = fgets(buffer, MAX_LINE_SIZE, fin)) == NULL) break;
des += buffer;
len2 = strlen(buffer);
len += len2;
}
size_t offset = ftell(fin);
one.des_begin = dummy.des_begin = offset - len;
one.des_length = dummy.des_length = len;
int i = 0;
if (des.data[i] == '>' || des.data[i] == '@' || des.data[i] == '+')
i += 1;
if (des.data[i] == ' ' || des.data[i] == '\t')
i += 1;
//if (options.des_len && options.des_len < des.size) des.size = options.des_len;
while (i < des.size && !isspace(des.data[i]))
i += 1;
des.data[i] = 0;
one.identifier = dummy.identifier = des.data;
}
else {
one += buffer;
}
}
#if 0
int i, n = 0;
for (i = 0; i<sequences.size(); i++) n += sequences[i].bufsize + 4;
cout << n << "\t" << sequences.capacity() * sizeof(Sequence) << endl;
int i;
scanf("%i", &i);
#endif
one.identifier = dummy.identifier = NULL;
delete[] buffer;
fclose(fin);
}
void SequenceDB::SequenceStatistic(Options & options)
{
int i, j, k, len;
int N = sequences.size();
total_letter = 0; // total bases
total_desc = 0; // total letters of sequence headers
max_len = 0;
mean_len = 0.0;
min_len = (size_t)-1;
for (i = 0; i<N; i++) {
Sequence *seq = sequences[i];
len = seq->size;
mean_len += seq->size;
total_letter += len;
if (len > max_len)
max_len = len;
if (len < min_len)
min_len = len;
if (seq->swap == NULL)
// seq->ConvertBases();
if (seq->identifier)
total_desc += strlen(seq->identifier);
}
mean_len = mean_len / N;
cout << " Total number: " << N << endl;
cout << " Longest: " << max_len << endl;
cout << " Shortest: " << min_len << endl;
cout << " Mean length: " << mean_len << endl;
cout << " Total bases: " << total_letter << endl;
cout << endl;
// END change all the NR_seq to iseq
//len_n50 = (max_len + min_len) / 2; // will be properly set, if sort is true;
}// END sort_seqs_divide_segs
void SequenceDB::SequencePositionWriteToFile(Options & options) {
string time_now = getTime();
ofstream outfile;
const char* filename = options.output.data();
outfile.open(filename, ios::out);
//outfile2.open(options.output, ios::app);
if (!outfile.is_open())
bomb_error("Open sequence positiony output file failure, exit!");
//for (int aaa = 0; aaa < location_num; aaa++) {
outfile << "Build date: " << time_now << endl;
outfile << "Word length: " << options.kmer_length << endl;
outfile << "Sequence num: " << sequences.size() << endl;
outfile << "Max. length: " << max_len << endl;
outfile << "Min. length: " << min_len << endl;
outfile << "Ave. length: " << mean_len << endl;
outfile << "SeqIndex\tPlus\tPosInSeq\tPosInGen" << endl;
for (int i = 0; i < sequences.size(); i++) {
outfile << i << "\t";
outfile << sequences[i]->plus << "\t";
//if (i > 100) {
// continue;
//}
//printf("%d-th in sequence: %d, in genome: %d\n", i, sequences[i]->position_in_sequence, sequences[i]->position_in_genome);
if (sequences[i]->plus == 1) {
outfile << sequences[i]->position_in_sequence << "\t";
outfile << sequences[i]->position_in_genome;
}
else if (sequences[i]->plus == 0) {
outfile << sequences[i]->position_in_sequence << "\t";
outfile << sequences[i]->position_in_genome_minus;
}
else {
outfile << "-1" << "\t";
outfile << "-1";
}
outfile << endl;
}
outfile.close();
}
void SequenceDB::ReadSequencePositionFile(Options & options) {
const char* filename = options.sequencePosFile.data();
ifstream libfile(filename);
string line, kmer, w1, w2;
int index, plus, genome_id, positionInSequence, positionInGenome, kmer_length;
if (!libfile.is_open())
bomb_error("Open genome library output file failure, exit!");
// ignore the first four lines
//getline(libfile, line);// data
//getline(libfile, line);// word length
//istringstream iss(line);
//iss >> w1 >> w2 >> kmer_length;
//getline(libfile, line);// sequence num
//getline(libfile, line);// Max length
//getline(libfile, line);// Min length
//getline(libfile, line);// Average length
//getline(libfile, line);// title
while (getline(libfile, line)) {
istringstream iss(line);
iss >> index >> genome_id >> plus >> positionInSequence >> positionInGenome;
if (plus == 1) {
sequences[index]->plus = 1;
sequences[index]->tar_id = genome_id;
sequences[index]->position_in_sequence = positionInSequence;
sequences[index]->position_in_genome = positionInGenome;
}
else if (plus == 0) {
sequences[index]->plus = 0;
sequences[index]->tar_id = genome_id;
sequences[index]->position_in_sequence = positionInSequence;
sequences[index]->position_in_genome_minus = positionInGenome;
}
else if (plus == -1) {
sequences[index]->plus = -1;
sequences[index]->tar_id = genome_id;
sequences[index]->position_in_sequence = -1;
sequences[index]->position_in_genome = -1;
}
else {
printf("\nInvalid position detected in the %d-th sequence!\n", index);
bomb_error("Invalid position detected in the sequence position file, exit!");
}
}
}
void SequenceDB::WriteAlignedToFile(Options & options) {
ofstream outfile2;
string direction = "";
string seq1_whole_aligned = "";
string middle_whole_aligned = "";
string seq2_whole_aligned = "";
int leftPosition = 0, rightPosition = 0;
const char* filename = options.output.data();
outfile2.open(filename, ios::out);
//outfile2.open(options.output, ios::app);
if (!outfile2.is_open())
bomb_error("Open output file failure");
for (int i = 0; i < sequences.size(); i++) {
if (sequences[i]->nMatch <= 0) {
continue;
}
if (sequences[i]->plus) {
direction = "Plus";
}
else {
direction = "Minus";
}
outfile2 << "Query: " << sequences[i]->identifier << endl;
outfile2 << "Length: " << sequences[i]->size << endl;
outfile2 << "nMatch: " << sequences[i]->nMatch << endl;
outfile2 << "nSubsitute: " << sequences[i]->nSubsitute << endl;
outfile2 << "nDelete: " << sequences[i]->nDelete << endl;
outfile2 << "nInsert: " << sequences[i]->nInsert << endl;
outfile2 << "Identify: " << sequences[i]->identify << endl;
outfile2 << "Strand: Plus/" << direction << endl;