forked from jsh58/NGmerge
-
Notifications
You must be signed in to change notification settings - Fork 6
/
NGmerge.c
1249 lines (1129 loc) · 36.7 KB
/
NGmerge.c
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
/*
John M. Gaspar (jsh58@wildcats.unh.edu)
April 2015 (updated 2016, 2017)
Analyzing paired-end reads for overlaps. Two modes:
- 'stitch': producing a single, merged read for reads
with sufficient overlaps
- 'adapter-removal': removing adapters (3' overhangs
of stitched alignment) from individual reads
Version 0.3
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <getopt.h>
#include <zlib.h>
#include <omp.h>
#include "NGmerge.h"
/* void printVersion()
* Print version and copyright.
*/
void printVersion(void) {
fprintf(stderr, "NGmerge, version %s\n", VERSION);
fprintf(stderr, "Copyright (C) 2017 John M. Gaspar (jsh58@wildcats.unh.edu)\n");
exit(-1);
}
/* void usage()
* Prints usage information.
*/
void usage(int exitval) {
fprintf(stderr, "Usage: NGmerge {-%c <file> -%c <file>", FIRST, SECOND);
fprintf(stderr, " -%c <file>} [optional arguments]\n", OUTFILE);
fprintf(stderr, "Required arguments:\n");
fprintf(stderr, " -%c <file> Input FASTQ file with reads from forward direction\n", FIRST);
fprintf(stderr, " -%c <file> Input FASTQ file with reads from reverse direction\n", SECOND);
fprintf(stderr, " -%c <file> Output FASTQ file(s):\n", OUTFILE);
fprintf(stderr, " - in 'stitch' mode (def.), the file of merged reads\n");
fprintf(stderr, " - in 'adapter-removal' mode (-%c), the output files\n", ADAPTOPT);
fprintf(stderr, " will be <file>%s and <file>%s\n", ONEEXT, TWOEXT);
fprintf(stderr, "Alignment parameters:\n");
fprintf(stderr, " -%c <int> Minimum overlap of the paired-end reads (def. %d)\n", OVERLAP, DEFOVER);
fprintf(stderr, " -%c <float> Mismatches to allow in the overlapped region\n", MISMATCH);
fprintf(stderr, " (a fraction of the overlap length; def. %.2f)\n", DEFMISM);
fprintf(stderr, " -%c Use 'adapter-removal' mode (also sets -%c option)\n", ADAPTOPT, DOVEOPT);
fprintf(stderr, " -%c Option to check for dovetailing (with 3' overhangs)\n", DOVEOPT);
fprintf(stderr, " -%c <int> Minimum overlap of dovetailed alignments (def. %d)\n", DOVEOVER, DEFDOVE);
fprintf(stderr, " -%c Option to produce shortest stitched read\n", MAXOPT);
fprintf(stderr, "I/O options:\n");
fprintf(stderr, " -%c <file> Log file for stitching results of each read pair\n", LOGFILE);
fprintf(stderr, " -%c <file> FASTQ files for reads that failed stitching\n", UNFILE);
fprintf(stderr, " (output as <file>%s and <file>%s)\n", ONEEXT, TWOEXT);
fprintf(stderr, " -%c <file> Log file for dovetailed reads (adapter sequences)\n", DOVEFILE);
fprintf(stderr, " -%c <file> Log file for formatted alignments of merged reads\n", ALNFILE);
fprintf(stderr, " -%c/-%c Option to gzip (-%c) or not (-%c) FASTQ output(s)\n", GZOPT, UNGZOPT, GZOPT, UNGZOPT);
fprintf(stderr, " -%c Option to produce interleaved FASTQ output(s)\n", INTEROPT);
fprintf(stderr, " -%c <file> Use given error profile for merged qual scores\n", QUALFILE);
fprintf(stderr, " -%c Use 'fastq-join' method for merged qual scores\n", FJOINOPT);
fprintf(stderr, " -%c <int> FASTQ quality offset (def. %d)\n", QUALITY, OFFSET);
fprintf(stderr, " -%c <int> Maximum input quality score (0-based; def. %d)\n", SETQUAL, MAXQUAL);
fprintf(stderr, " -%c <int> Number of threads to use (def. %d)\n", THREADS, DEFTHR);
fprintf(stderr, " -%c Option to print status updates/counts to stderr\n", VERBOSE);
exit(exitval);
}
/* int error()
* Prints an error message.
*/
int error(char* msg, enum errCode err) {
fprintf(stderr, "Error! %s%s\n", msg, errMsg[err]);
return -1;
}
/* void* memalloc()
* Allocates a heap block.
*/
void* memalloc(int size) {
void* ans = malloc(size);
if (ans == NULL)
exit(error("", ERRMEM));
return ans;
}
/* float getFloat(char*)
* Converts the given char* to a float.
*/
float getFloat(char* in) {
char* endptr;
float ans = strtof(in, &endptr);
if (*endptr != '\0')
exit(error(in, ERRFLOAT));
return ans;
}
/* int getInt(char*)
* Converts the given char* to an int.
*/
int getInt(char* in) {
char* endptr;
int ans = (int) strtol(in, &endptr, 10);
if (*endptr != '\0')
exit(error(in, ERRINT));
return ans;
}
/* char rc(char)
* Returns the complement of the given base.
*/
char rc(char in) {
char out;
if (in == 'A') out = 'T';
else if (in == 'T') out = 'A';
else if (in == 'C') out = 'G';
else if (in == 'G') out = 'C';
else if (in == 'N') out = 'N';
else {
char msg[4] = "' '";
msg[1] = in;
exit(error(msg, ERRUNK));
}
return out;
}
/* char* getLine()
* Reads the next line from a file.
*/
char* getLine(char* line, int size, File in, bool gz) {
if (gz)
return gzgets(in.gzf, line, size);
else
return fgets(line, size, in.f);
}
/* void checkHeaders()
* Ensure headers match (up to first space character);
* create consensus header.
*/
void checkHeaders(char* head1, char* head2, char* header) {
bool ok = false; // match boolean
int j;
for (j = 0; head1[j] != '\n' && head1[j] != '\0'; j++) {
if (head1[j] != head2[j]) {
if (ok)
break;
for ( ; head1[j] != '\n' && head1[j] != '\0'
&& head1[j] != ' '; j++) ;
head1[j] = '\0'; // trim head1 for err msg
exit(error(head1, ERRHEAD));
} else if (head1[j] == ' ')
ok = true; // headers match
header[j] = head1[j];
}
if (header[j - 1] == ' ')
header[j - 1] = '\0'; // removing trailing space
else
header[j] = '\0';
}
/* void checkQual()
* Check given quality string for offset errors.
*/
void checkQual(char* qual, int len, int offset,
int maxQual) {
for (int i = 0; i < len; i++)
// error if qual < 0 or qual > maxQual
if (qual[i] < offset || qual[i] > offset + maxQual) {
char* msg = (char*) memalloc(MAX_SIZE);
sprintf(msg, "(range [0, %d], offset %d) '%c'",
maxQual, offset, qual[i]);
exit(error(msg, ERROFFSET));
}
}
/* void processSeq()
* Process the given sequence; save length;
* for 2nd read, save reversed seq/qual.
*/
void processSeq(char** read, int* len, bool i,
int j, int offset, int maxQual) {
// remove new-line character and save length
int k;
for (k = 0; read[j][k] != '\n' && read[j][k] != '\0'; k++) ;
read[j][k] = '\0';
if (j == SEQ)
*len = k; // save read length
else if (k != *len)
exit(error("", ERRQUAL)); // seq/qual length mismatch
// for 2nd read (i == true), save revComp(seq) or rev(qual)
if (i) {
int dest = j + EXTRA; // save to 'extra' field of read2
int m = 0;
if (j == SEQ) {
dest++; // increment b/c of fastq 'plus' line
for (k--; k > -1; k--)
read[dest][m++] = rc(read[j][k]);
} else
for (k--; k > -1; k--)
read[dest][m++] = read[j][k];
read[dest][m] = '\0';
} else if (j == SEQ)
// check 1st read's sequence for non-ACGTN chars
for (int m = 0; m < k; m++)
rc(read[j][m]);
// check quality scores
if (j == QUAL)
checkQual(read[j], k, offset, maxQual);
}
/* bool loadReads()
* Load a pair of reads. Check formatting, determine
* consensus header. Return false on EOF.
*/
bool loadReads(File in1, File in2, char** read1, char** read2,
char* header, int* len1, int* len2, int offset,
int maxQual, bool gz1, bool gz2) {
// load both reads from input files (LOCK)
bool flag = false; // boolean for EOF
#pragma omp critical
for (int i = 0; i < 2; i++) {
File in = in1;
char** read = read1;
bool gz = gz1;
if (i) {
in = in2;
read = read2;
gz = gz2;
}
// load read (4 lines)
for (int j = 0; j < FASTQ; j++)
if (getLine(read[j], MAX_SIZE, in, gz) == NULL) {
if (j == 0) {
if (i == 0) {
flag = true; // EOF
break;
} else {
int k = 0;
for ( ; read1[HEAD][k] != '\n' && read1[HEAD][k] != '\0'
&& read1[HEAD][k] != ' '; k++) ;
read1[HEAD][k] = '\0'; // trim header for err msg
exit(error(read1[HEAD], ERRHEAD));
}
} else
exit(error("", ERRSEQ));
}
if (flag)
break;
} // (UNLOCK)
if (flag)
return false; // EOF
// check fastq formatting
if (read1[HEAD][0] != BEGIN || read1[PLUS][0] != PLUSCHAR
|| read2[HEAD][0] != BEGIN || read2[PLUS][0] != PLUSCHAR)
exit(error("", ERRFASTQ));
// process sequence/quality lines
processSeq(read1, len1, false, SEQ, offset, maxQual);
processSeq(read1, len1, false, QUAL, offset, maxQual);
processSeq(read2, len2, true, SEQ, offset, maxQual);
processSeq(read2, len2, true, QUAL, offset, maxQual);
// check headers
checkHeaders(read1[HEAD], read2[HEAD], header);
return true;
}
/* float compare()
* Compare two sequences. Return the fraction mismatch.
*/
float compare(char* seq1, char* seq2, int length,
float mismatch, int overlap) {
int mis = 0; // number of mismatches
int len = length; // length of overlap, not counting Ns
float allow = len * mismatch;
for (int i = 0; i < length; i++) {
// do not count Ns
if (seq1[i] == 'N' || seq2[i] == 'N') {
if (--len < overlap || mis > len * mismatch)
return NOTMATCH;
allow = len * mismatch;
} else if (seq1[i] != seq2[i] && ++mis > allow)
return NOTMATCH;
}
return (float) mis / len;
}
/* int findPos()
* Find optimal overlapping position.
* Currently, quality scores are not considered
* (e.g. decreased penalty for a low-quality mismatch).
*/
int findPos (char* seq1, char* seq2, char* qual1,
char* qual2, int len1, int len2, int overlap,
bool dovetail, int doveOverlap, float mismatch,
bool maxLen, float* best) {
// check for regular (non-dovetailed) alignments
int pos = len1 - overlap + 1; // position of match
int i = len1 - overlap;
for ( ; i > -1 && len1 - i <= len2; i--) {
// align sequences
float res = compare(seq1 + i, seq2, len1 - i,
mismatch, overlap);
// compare result
if (res < *best || (res == *best && !maxLen)) {
*best = res;
pos = i;
}
if (res == 0.0f && maxLen)
return pos; // shortcut for exact match
}
// check for dovetailing
if (dovetail) {
// if no regular alignment, reset i
if (i == len1 - overlap)
i = (len1 > len2 ? len1 - len2 - 1 : -1);
// continue decrementing i
for ( ; ; i--) {
float res = NOTMATCH;
if (i >= 0) {
// read1 is longer, with 3' overhang
if (len2 < doveOverlap)
break;
res = compare(seq1 + i, seq2, len2,
mismatch, doveOverlap);
} else if (len1 < len2 + i) {
// read2 has 3' overhang, read1 determines overlap
if (len1 < doveOverlap)
break;
res = compare(seq1, seq2 - i, len1,
mismatch, doveOverlap);
} else {
// read2 has 3' overhang and determines overlap
if (len2 + i < doveOverlap)
break;
res = compare(seq1, seq2 - i, len2 + i,
mismatch, doveOverlap);
}
// compare result
if (res < *best || (res == *best && !maxLen)) {
*best = res;
pos = i;
}
if (res == 0.0f && maxLen)
return pos; // shortcut for exact match
}
}
return pos;
}
/* void printDove()
* Log 3' overhangs of dovetailed reads.
*/
void printDove(File dove, char* header, char** read1,
char** read2, int len1, int len2, int pos,
omp_lock_t* lock) {
if (len1 > len2 + pos || pos < 0) {
omp_set_lock(lock);
fprintf(dove.f, "%s\t%s\t%s\n", header + 1,
len1 > len2 + pos ? read1[SEQ] + len2 + pos : "-",
pos < 0 ? read2[SEQ] + len2 + pos : "-");
omp_unset_lock(lock);
}
}
/* void printGZNoAdapt()
* Print the reads minus adapters (gzip output).
*/
void printGZNoAdapt(gzFile out1, gzFile out2,
char** read1, char** read2, int end1, int end2) {
// print fwd read
gzprintf(out1, "%s", read1[HEAD]);
for (int i = 0; i < end1; i++)
gzputc(out1, read1[SEQ][i]);
gzprintf(out1, "\n%s", read1[PLUS]);
for (int i = 0; i < end1; i++)
gzputc(out1, read1[QUAL][i]);
gzputc(out1, '\n');
// print rev read
gzprintf(out2, "%s", read2[HEAD]);
for (int i = 0; i < end2; i++)
gzputc(out2, read2[SEQ][i]);
gzprintf(out2, "\n%s", read2[PLUS]);
for (int i = 0; i < end2; i++)
gzputc(out2, read2[QUAL][i]);
gzputc(out2, '\n');
}
/* void printNoAdapt()
* Print the reads minus adapters.
*/
void printNoAdapt(FILE* out1, FILE* out2, char** read1,
char** read2, int end1, int end2) {
// print fwd read
fprintf(out1, "%s", read1[HEAD]);
for (int i = 0; i < end1; i++)
fputc(read1[SEQ][i], out1);
fprintf(out1, "\n%s", read1[PLUS]);
for (int i = 0; i < end1; i++)
fputc(read1[QUAL][i], out1);
fputc('\n', out1);
// print rev read
fprintf(out2, "%s", read2[HEAD]);
for (int i = 0; i < end2; i++)
fputc(read2[SEQ][i], out2);
fprintf(out2, "\n%s", read2[PLUS]);
for (int i = 0; i < end2; i++)
fputc(read2[QUAL][i], out2);
fputc('\n', out2);
}
/* bool printResAdapt()
* Control printing of reads minus adapters.
* Return 1 if adapter found, else 0.
*/
bool printResAdapt(File out1, File out2, File dove,
bool doveOpt, char* header, char** read1, char** read2,
int len1, int len2, int pos, float best, bool gz,
omp_lock_t* lock) {
bool adapter = false;
int end1 = len1;
int end2 = len2;
// if found, identify locations of adapters
if (len1 > len2 + pos || pos < 0) {
adapter = true;
if (len1 > len2 + pos)
end1 = len2 + pos;
if (pos < 0)
end2 += pos;
if (doveOpt)
printDove(dove, header, read1, read2,
len1, len2, pos, lock + DOVE);
}
// print output
omp_set_lock(lock + OUT);
if (gz)
printGZNoAdapt(out1.gzf, out2.gzf, read1, read2,
end1, end2);
else
printNoAdapt(out1.f, out2.f, read1, read2,
end1, end2);
omp_unset_lock(lock + OUT);
return adapter;
}
/* void printAln2()
* Printing details of stitch mismatches.
*/
void printAln2(File aln, char* header, char** read1,
char** read2, int len1, int len2, int pos) {
int i = pos;
int j = 0;
if (pos < 0) {
j = -pos;
i = 0;
}
while (i < len1 && j < len2) {
if (read1[SEQ][i] == 'N' || read2[SEQ + EXTRA + 1][j] == 'N'
|| read1[SEQ][i] != read2[SEQ + EXTRA + 1][j])
fprintf(aln.f, "%s\t%d\t%c\t%c\t%c\t%c\n",
header + 1, i, read1[SEQ][i], read1[QUAL][i],
read2[SEQ + EXTRA + 1][j], read2[QUAL + EXTRA][j]);
i++;
j++;
}
}
/* void printAln()
* Print nicely formatted alignment of stitched reads.
*/
void printAln(File aln, char* header, char** read1,
char** read2, int len1, int len2, int pos) {
fprintf(aln.f, "%s\n", header + 1);
// print sequence alignment
fprintf(aln.f, "seq_R1: ");
for (int i = 0; i > pos; i--)
fputc(' ', aln.f);
fprintf(aln.f, "%s\n", read1[SEQ]);
// print '|' for matches, ':' for Ns
fprintf(aln.f, " ");
int i;
for (i = 0; i < abs(pos); i++)
fputc(' ', aln.f);
int j = 0;
if (pos < 0) {
j = -pos;
i = 0;
}
while (i < len1 && j < len2) {
fputc((read1[SEQ][i] == 'N' || read2[SEQ + EXTRA + 1][j] == 'N') ?
':' : (read1[SEQ][i] == read2[SEQ + EXTRA + 1][j] ?
'|' : ' '), aln.f);
i++;
j++;
}
fputc('\n', aln.f);
fprintf(aln.f, "seq_R2: ");
for (int i = 0; i < pos; i++)
fputc(' ', aln.f);
fprintf(aln.f, "%s\n\n", read2[SEQ + EXTRA + 1]);
// print quality scores
fprintf(aln.f, "qual_R1: ");
for (int i = 0; i > pos; i--)
fputc(' ', aln.f);
fprintf(aln.f, "%s\n", read1[QUAL]);
fprintf(aln.f, "qual_R2: ");
for (int i = 0; i < pos; i++)
fputc(' ', aln.f);
fprintf(aln.f, "%s\n\n", read2[QUAL + EXTRA]);
}
/* void createSeq()
* Create stitched sequence (into seq1, qual1).
* Use empirical error profiles for quality scores,
* or 'fastq-join' method.
*/
void createSeq(char* seq1, char* seq2, char* qual1,
char* qual2, int len1, int len2, int pos,
int offset, char** match, char** mism, bool fjoin) {
int len = len2 + pos; // length of stitched sequence
for (int i = 0; i < len; i++) {
if (i - pos < 0) {
// 1st read only: continue
continue;
} else if (i >= len1) {
// 2nd read only: copy seq and qual
seq1[i] = seq2[i-pos];
qual1[i] = qual2[i-pos];
} else if (seq2[i-pos] == 'N') {
// 2nd read 'N': continue
continue;
} else if (seq1[i] == 'N') {
// 1st read 'N': copy seq and qual
seq1[i] = seq2[i-pos];
qual1[i] = qual2[i-pos];
} else if (seq1[i] != seq2[i-pos]) {
// mismatch:
// - base matches higher quality score or equal
// quality score that is closer to 5' end
// - quality score calculated as diff (fastq-join
// method) or copied from mism array
if (qual1[i] < qual2[i-pos] ||
(qual1[i] == qual2[i-pos] && i >= len / 2.0) )
seq1[i] = seq2[i-pos];
if (fjoin)
qual1[i] = abs(qual2[i-pos] - qual1[i]) + offset;
else
qual1[i] = mism[ (int) qual1[i] - offset ]
[ (int) qual2[i-pos] - offset ] + offset;
} else {
// match:
// - quality score calculated as max (fastq-join
// method) or copied from match array
if (fjoin) {
if (qual1[i] < qual2[i-pos])
qual1[i] = qual2[i-pos];
} else
qual1[i] = match[ (int) qual1[i] - offset ]
[ (int) qual2[i-pos] - offset ] + offset;
}
}
seq1[len] = '\0';
qual1[len] = '\0';
}
/* void printRes()
* Print stitched read.
*/
void printRes(File out, File log, bool logOpt, File dove,
bool doveOpt, File aln, int alnOpt, char* header,
char** read1, char** read2, int len1, int len2,
int pos, float best, int offset, bool gz, bool fjoin,
char** match, char** mism, omp_lock_t* lock) {
// log result
if (logOpt) {
omp_set_lock(lock + LOG);
fprintf(log.f, "%s\t%d\t%d\t", header + 1,
pos < 0 ? (len2+pos < len1 ? len2+pos : len1) :
(len1-pos < len2 ? len1-pos : len2), len2 + pos);
best ? fprintf(log.f, "%.3f", best) : fprintf(log.f, "0");
fprintf(log.f, "\n");
omp_unset_lock(lock + LOG);
}
if (doveOpt)
printDove(dove, header, read1, read2, len1, len2,
pos, lock + DOVE);
// print formatted alignments
if (alnOpt == 1) {
omp_set_lock(lock + ALN);
printAln(aln, header, read1, read2, len1, len2, pos);
// create stitched sequence
createSeq(read1[SEQ], read2[SEQ + EXTRA + 1],
read1[QUAL], read2[QUAL + EXTRA], len1, len2,
pos, offset, match, mism, fjoin);
// print merged seq to alignment output
fprintf(aln.f, "merged\nseq: ");
for (int i = 0; i > pos; i--)
fputc(' ', aln.f);
fprintf(aln.f, "%s\n", read1[SEQ]);
fprintf(aln.f, "qual: ");
for (int i = 0; i > pos; i--)
fputc(' ', aln.f);
fprintf(aln.f, "%s\n\n\n", read1[QUAL]);
omp_unset_lock(lock + ALN);
} else {
// print stitch differences
if (alnOpt == 2) {
omp_set_lock(lock + ALN);
printAln2(aln, header, read1, read2, len1, len2, pos);
omp_unset_lock(lock + ALN);
}
// create stitched sequence
createSeq(read1[SEQ], read2[SEQ + EXTRA + 1],
read1[QUAL], read2[QUAL + EXTRA], len1, len2,
pos, offset, match, mism, fjoin);
}
// print stitched sequence
omp_set_lock(lock + OUT);
if (gz)
gzprintf(out.gzf, "%s\n%s\n+\n%s\n", header,
read1[SEQ], read1[QUAL]);
else
fprintf(out.f, "%s\n%s\n+\n%s\n", header,
read1[SEQ], read1[QUAL]);
omp_unset_lock(lock + OUT);
}
/* void printFail()
* Print stitch failure reads.
*/
void printFail(File un1, File un2, bool unOpt,
File log, bool logOpt, char* header, char** read1,
char** read2, bool gz, omp_lock_t* outLock,
omp_lock_t* logLock) {
if (logOpt) {
omp_set_lock(logLock);
fprintf(log.f, "%s\t%s\n", header + 1, NA);
omp_unset_lock(logLock);
}
if (unOpt) {
omp_set_lock(outLock);
if (gz) {
gzprintf(un1.gzf, "%s%s\n%s%s\n", read1[HEAD],
read1[SEQ], read1[PLUS], read1[QUAL]);
gzprintf(un2.gzf, "%s%s\n%s%s\n", read2[HEAD],
read2[SEQ], read2[PLUS], read2[QUAL]);
} else {
fprintf(un1.f, "%s%s\n%s%s\n", read1[HEAD],
read1[SEQ], read1[PLUS], read1[QUAL]);
fprintf(un2.f, "%s%s\n%s%s\n", read2[HEAD],
read2[SEQ], read2[PLUS], read2[QUAL]);
}
omp_unset_lock(outLock);
}
}
/* int readFile()
* Analyzes the reads in a set of input files.
* Controls writing to the output file(s).
* Multithreaded.
*/
int readFile(File in1, File in2, File out, File out2,
File un1, File un2, bool unOpt, File log,
bool logOpt, int overlap, bool dovetail, int doveOverlap,
File dove, bool doveOpt, File aln, int alnOpt,
bool adaptOpt, float mismatch, bool maxLen,
int* stitch, int offset, int maxQual,
bool gz1, bool gz2, bool gzOut, bool fjoin,
char** match, char** mism, int threads) {
// initialize omp locks -- out, un, log, dove, aln
omp_lock_t lock[OMP_LOCKS];
for (int i = 0; i < OMP_LOCKS; i++)
omp_init_lock(&lock[i]);
// process files in parallel
int count = 0, stitchRed = 0;
#pragma omp parallel num_threads(threads) reduction(+: count, stitchRed)
{
// allocate memory for both reads
char** read1 = (char**) memalloc(FASTQ * sizeof(char*));
char** read2 = (char**) memalloc((FASTQ + EXTRA) * sizeof(char*));
for (int i = 0; i < FASTQ + EXTRA; i++) {
if (i < FASTQ)
read1[i] = (char*) memalloc(MAX_SIZE);
// for 2nd read, save extra fields for revComp(seq) and rev(qual)
read2[i] = (char*) memalloc(MAX_SIZE);
}
char* header = (char*) memalloc(MAX_SIZE); // consensus header
// process reads
int len1 = 0, len2 = 0; // lengths of reads
while (loadReads(in1, in2, read1, read2, header,
&len1, &len2, offset, maxQual, gz1, gz2)) {
// find optimal overlap
float best = 1.0f;
int pos = findPos(read1[SEQ], read2[SEQ + EXTRA + 1],
read1[QUAL], read2[QUAL + EXTRA], len1, len2, overlap,
dovetail, doveOverlap, mismatch, maxLen, &best);
// print result
if (pos == len1 - overlap + 1) {
// stitch failure
if (adaptOpt)
printFail(out, out2, 1, log, 0, header, read1,
read2, gzOut, lock + OUT, lock + LOG);
else
printFail(un1, un2, unOpt, log, logOpt, header,
read1, read2, gzOut, lock + UN, lock + LOG);
} else {
// stitch success
if (adaptOpt) {
stitchRed += printResAdapt(out, out2, dove, doveOpt,
header, read1, read2, len1, len2, pos, best,
gzOut, lock);
} else {
printRes(out, log, logOpt, dove, doveOpt, aln, alnOpt,
header, read1, read2, len1, len2, pos, best, offset,
gzOut, fjoin, match, mism, lock);
stitchRed++;
}
}
count++;
}
// free memory
free(header);
for (int i = 0; i < FASTQ + EXTRA; i++) {
if (i < FASTQ)
free(read1[i]);
free(read2[i]);
}
free(read1);
free(read2);
} // END parallel
// destroy omp locks
for (int i = 0; i < 5; i++)
omp_destroy_lock(&lock[i]);
*stitch = stitchRed;
return count;
}
/* void openWrite()
* Open a file for writing (stdout if file is '-').
*/
void openWrite(char* outFile, File* out, bool gz) {
if (outFile[0] == '-' && strlen(outFile) > 1)
exit(error(outFile, ERRNAME));
if (gz) {
if (!strcmp(outFile + strlen(outFile) - strlen(GZEXT), GZEXT)
|| !strcmp(outFile, "/dev/null"))
out->gzf = gzopen(outFile, "w");
else if (!strcmp(outFile, "-"))
out->gzf = gzdopen(fileno(stdout), "wb");
else {
// add ".gz" to outFile
char* outFile2 = memalloc(strlen(outFile)
+ strlen(GZEXT) + 1);
strcpy(outFile2, outFile);
strcat(outFile2, GZEXT);
out->gzf = gzopen(outFile2, "w");
free(outFile2);
}
if (out->gzf == NULL)
exit(error(outFile, ERROPENW));
} else {
out->f = (strcmp(outFile, "-") ?
fopen(outFile, "w") : stdout);
if (out->f == NULL)
exit(error(outFile, ERROPENW));
}
}
/* void openFiles()
* Opens output files for the program,
* adjusting file names/extensions as needed.
*/
void openFiles(char* outFile, File* out, File* out2,
char* unFile, File* un1, File* un2,
char* logFile, File* log,
char* doveFile, File* dove, bool dovetail,
char* alnFile, File* aln,
bool adaptOpt, bool gz, bool interOpt) {
if (adaptOpt) {
if (interOpt)
openWrite(outFile, out, gz);
else if (! strcmp(outFile, "-"))
exit(error("stdout + \"_1.fastq\"", ERROPENW));
else if (! strcmp(outFile, "/dev/null")) {
openWrite(outFile, out, gz);
openWrite(outFile, out2, gz);
} else {
// add "_1.fastq" and "_2.fastq" extensions
int add = strlen(ONEEXT) > strlen(TWOEXT) ?
strlen(ONEEXT) + 1 : strlen(TWOEXT) + 1;
char* outFile2 = memalloc(strlen(outFile) + add);
strcpy(outFile2, outFile);
strcat(outFile2, ONEEXT);
openWrite(outFile2, out, gz);
strcpy(outFile2, outFile);
strcat(outFile2, TWOEXT);
openWrite(outFile2, out2, gz);
free(outFile2);
}
} else {
openWrite(outFile, out, gz);
// open optional files
if (unFile != NULL) {
if (interOpt)
openWrite(unFile, un1, gz);
else if (! strcmp(unFile, "-"))
exit(error("stdout + \"_1.fastq\"", ERROPENW));
else {
// add "_1.fastq" and "_2.fastq" extensions
int add = strlen(ONEEXT) > strlen(TWOEXT) ?
strlen(ONEEXT) + 1 : strlen(TWOEXT) + 1;
char* unFile2 = memalloc(strlen(unFile) + add);
strcpy(unFile2, unFile);
strcat(unFile2, ONEEXT);
openWrite(unFile2, un1, gz);
strcpy(unFile2, unFile);
strcat(unFile2, TWOEXT);
openWrite(unFile2, un2, gz);
free(unFile2);
}
}
if (logFile != NULL) {
openWrite(logFile, log, false);
fprintf(log->f, "Read\tOverlapLen\tStitchedLen\tMismatch\n");
}
if (alnFile != NULL)
openWrite(alnFile, aln, false);
}
if (dovetail && doveFile != NULL) {
openWrite(doveFile, dove, false);
fprintf(dove->f, "Read\tAdapter_R1\tAdapter_R2\n");
}
}
/* bool openRead()
* Open a file for reading (stdin if file is '-').
* Return true if gzip compressed.
*/
bool openRead(char* inFile, File* in) {
// open file or stdin
bool stdinBool = (strcmp(inFile, "-") ? false : true);
FILE* dummy = (stdinBool ? stdin : fopen(inFile, "r"));
if (dummy == NULL)
exit(error(inFile, ERROPEN));
// check for gzip compression: magic number 0x1F, 0x8B
bool gzip = true;
int save = 0; // first char to pushback (for stdin)
int i, j;
for (i = 0; i < 2; i++) {
j = fgetc(dummy);
if (j == EOF)
exit(error(inFile, ERROPEN));
if ( (i && (unsigned char) j != 0x8B)
|| (! i && (unsigned char) j != 0x1F) ) {
gzip = false;
break;
}
if (! i)
save = j;
}
// for stdin, push back chars
if (stdinBool) {
if (gzip)
exit(error("", ERRGZIP));
if (ungetc(j, dummy) == EOF)
exit(error("", ERRUNGET));
if (i && ungetc(save, dummy) == EOF)
exit(error("", ERRUNGET));
}
// open file
if (gzip) {
if (fclose(dummy))
exit(error("", ERRCLOSE));
in->gzf = gzopen(inFile, "r");
if (in->gzf == NULL)
exit(error(inFile, ERROPEN));
} else {
if (! stdinBool)
rewind(dummy);
in->f = dummy;
}
return gzip;
}
/* void loadQual()
* Load quality score profiles from file.
*/
void loadQual(char* qualFile, int maxQual,
char*** match, char*** mism) {
File qual;
bool gz = openRead(qualFile, &qual);
char* line = memalloc(MAX_SIZE);
char** arr = NULL; // array to save to
int i = 0, matIdx = 0, misIdx = 0; // array indices
while (getLine(line, MAX_SIZE, qual, gz) != NULL) {
if (line[0] == '#' || line[0] == '\n') {
// determine target array
i = 0;
if (! strcmp(line + 1, "match\n"))
arr = *match;
else if (! strcmp(line + 1, "mismatch\n"))
arr = *mism;
} else if (arr == NULL) {
continue;
} else {
// remove trailing '\n'
int j;
for (j = 0; line[j] != '\n' && line[j] != '\0'; j++) ;
line[j] = '\0';
// save values to array
char* tok = strtok(line, CSV);
for (j = 0; j < maxQual + 1; j++) {
if (tok == NULL) {
char* msg = (char*) memalloc(MAX_SIZE);
sprintf(msg, "(range [0, %d]) %s",
maxQual, qualFile);
exit(error(msg, ERRRANGE));
}
arr[i][j] = getInt(tok);
tok = strtok(NULL, CSV);
}
i++;
if ( (arr == *match && ++matIdx > maxQual)
|| (arr == *mism && ++misIdx > maxQual) )
arr = NULL;
}
}
// make sure all values were loaded
if (matIdx < maxQual + 1 || misIdx < maxQual + 1) {
char* msg = (char*) memalloc(MAX_SIZE);
sprintf(msg, "(range [0, %d]) %s", maxQual, qualFile);
exit(error(msg, ERRRANGE));
}
if ( (gz && gzclose(qual.gzf) != Z_OK) ||
(! gz && fclose(qual.f) ) )