]> git.donarmstrong.com Git - mothur.git/blob - makecontigscommand.h
added primer.design command. fixed bug with linux unifrac subsampling, metastats...
[mothur.git] / makecontigscommand.h
1 #ifndef Mothur_makecontigscommand_h
2 #define Mothur_makecontigscommand_h
3
4 //
5 //  makecontigscommand.h
6 //  Mothur
7 //
8 //  Created by Sarah Westcott on 5/15/12.
9 //  Copyright (c) 2012 Schloss Lab. All rights reserved.
10 //
11
12 #include "command.hpp"
13 #include "sequence.hpp"
14 #include "qualityscores.h"
15 #include "alignment.hpp"
16 #include "gotohoverlap.hpp"
17 #include "needlemanoverlap.hpp"
18 #include "blastalign.hpp"
19 #include "noalign.hpp"
20 #include "trimoligos.h"
21
22 struct fastqRead {
23         vector<int> scores;
24         string name;
25         string sequence;
26         
27         fastqRead() { name = ""; sequence = ""; scores.clear(); };
28         fastqRead(string n, string s, vector<int> sc) : name(n), sequence(s), scores(sc) {};
29         ~fastqRead() {};
30 };
31
32 struct pairFastqRead {
33         fastqRead forward;
34     fastqRead reverse;
35         
36         pairFastqRead() {};
37         pairFastqRead(fastqRead f, fastqRead r) : forward(f), reverse(r){};
38         ~pairFastqRead() {};
39 };
40 /**************************************************************************************************/
41
42 class MakeContigsCommand : public Command {
43 public:
44     MakeContigsCommand(string);
45     MakeContigsCommand();
46     ~MakeContigsCommand(){}
47     
48     vector<string> setParameters();
49     string getCommandName()                     { return "make.contigs";                        }
50     string getCommandCategory()         { return "Sequence Processing";         } 
51     //commmand category choices: Sequence Processing, OTU-Based Approaches, Hypothesis Testing, Phylotype Analysis, General, Clustering and Hidden
52     
53         string getHelpString(); 
54     string getOutputPattern(string);    
55     string getCitation() { return "http://www.mothur.org/wiki/Make.contigs"; }
56     string getDescription()             { return "description"; }
57     
58     int execute(); 
59     void help() { m->mothurOut(getHelpString()); }      
60     
61 private:
62     bool abort, allFiles, createGroup;
63     string outputDir, ffastqfile, rfastqfile, align, oligosfile, rfastafile, ffastafile, rqualfile, fqualfile, file, format;
64         float match, misMatch, gapOpen, gapExtend;
65         int processors, longestBase, threshold, tdiffs, bdiffs, pdiffs, ldiffs, sdiffs;
66     vector<string> outputNames;
67     
68     map<int, oligosPair> barcodes;
69         map<int, oligosPair> primers;
70     vector<string>  linker;
71     vector<string>  spacer;
72         vector<string> primerNameVector;        
73         vector<string> barcodeNameVector;
74         vector<char> convertTable;
75     
76         map<string, int> groupCounts; 
77     map<string, string> groupMap;
78     
79     vector<int> convertQual(string);
80     fastqRead readFastq(ifstream&, bool&);
81     vector< vector< vector<string> > > preProcessData(unsigned long int&);
82     vector< vector<string> > readFileNames(string);
83     vector< vector<string> > readFastqFiles(unsigned long int&, string, string);
84     vector< vector<string> > readFastaFiles(unsigned long int&, string, string);
85     bool checkReads(fastqRead&, fastqRead&, string, string);
86     int createProcesses(vector< vector<string> >, string, string, string, string, string, vector<vector<string> >, vector<vector<string> >);
87     int driver(vector<string>, string, string, string, string, string, vector<vector<string> >, vector<vector<string> >);
88     bool getOligos(vector<vector<string> >&, vector< vector<string> >&, string);
89     string reverseOligo(string);
90     vector<pairFastqRead> getReads(bool ignoref, bool ignorer, fastqRead forward, fastqRead reverse, map<string, fastqRead>& uniques);
91 };
92
93 /**************************************************************************************************/
94
95 /**************************************************************************************************/
96 //custom data structure for threads to use.
97 // This is passed by void pointer so it can be any data type
98 // that can be passed using a single void pointer (LPVOID).
99 struct contigsData {
100         string outputFasta; 
101         string outputQual; 
102     string outputScrapFasta; 
103         string outputScrapQual;
104         string outputMisMatches;
105         string align;
106     vector<string> files;
107     vector<vector<string> > fastaFileNames;
108     vector<vector<string> > qualFileNames;
109         MothurOut* m;
110         float match, misMatch, gapOpen, gapExtend;
111         int count, threshold, threadID, pdiffs, bdiffs, tdiffs;
112     bool allFiles, createGroup;
113     map<string, int> groupCounts; 
114     map<string, string> groupMap;
115     vector<string> primerNameVector;    
116         vector<string> barcodeNameVector;
117     map<int, oligosPair> barcodes;
118         map<int, oligosPair> primers;
119         
120         contigsData(){}
121         contigsData(vector<string> f, string of, string oq, string osf, string osq, string om, string al, MothurOut* mout, float ma, float misMa, float gapO, float gapE, int thr, map<int, oligosPair> br, map<int, oligosPair> pr, vector<vector<string> > ffn, vector<vector<string> > qfn, vector<string>bnv, vector<string> pnv, int pdf, int bdf, int tdf, bool cg, bool all, int tid) {
122         files = f;
123                 outputFasta = of;
124         outputQual = oq;
125         outputMisMatches = om;
126         m = mout;
127                 match = ma; 
128                 misMatch = misMa;
129                 gapOpen = gapO; 
130                 gapExtend = gapE; 
131         threshold = thr;
132                 align = al;
133                 count = 0;
134         outputScrapFasta = osf;
135         outputScrapQual = osq;
136         fastaFileNames = ffn;
137         qualFileNames = qfn;
138         barcodes = br;
139         primers = pr;
140         barcodeNameVector = bnv;
141         primerNameVector = pnv;
142         pdiffs = pdf;
143         bdiffs = bdf;
144         tdiffs = tdf;
145         allFiles = all;
146         createGroup = cg;
147                 threadID = tid;
148         }
149 };
150
151 /**************************************************************************************************/
152 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
153 #else
154 static DWORD WINAPI MyContigsThreadFunction(LPVOID lpParam){ 
155         contigsData* pDataArray;
156         pDataArray = (contigsData*)lpParam;
157         
158         try {
159         int longestBase = 1000;
160         Alignment* alignment;
161         if(pDataArray->align == "gotoh")                        {       alignment = new GotohOverlap(pDataArray->gapOpen, pDataArray->gapExtend, pDataArray->match, pDataArray->misMatch, longestBase);                 }
162                 else if(pDataArray->align == "needleman")       {       alignment = new NeedlemanOverlap(pDataArray->gapOpen, pDataArray->match, pDataArray->misMatch, longestBase);                            }
163         
164         int num = 0;
165         string thisffastafile = pDataArray->files[0];
166         string thisfqualfile = pDataArray->files[1];
167         string thisrfastafile = pDataArray->files[2];
168         string thisrqualfile = pDataArray->files[3];
169         
170         if (pDataArray->m->debug) {  pDataArray->m->mothurOut("[DEBUG]: ffasta = " + thisffastafile + ".\n[DEBUG]: fqual = " + thisfqualfile + ".\n[DEBUG]: rfasta = " + thisrfastafile + ".\n[DEBUG]: rqual = " + thisrqualfile + ".\n"); }
171         
172                 if(pDataArray->allFiles){
173                         for (int i = 0; i < pDataArray->fastaFileNames.size(); i++) { //clears old file
174                                 for (int j = 0; j < pDataArray->fastaFileNames[i].size(); j++) { //clears old file
175                                         if (pDataArray->fastaFileNames[i][j] != "") {
176                                                 ofstream temp;
177                                                 pDataArray->m->openOutputFile(pDataArray->fastaFileNames[i][j], temp);                  temp.close();
178                         if (thisfqualfile != "") { pDataArray->m->openOutputFile(pDataArray->qualFileNames[i][j], temp);                        temp.close(); }
179                                         }
180                                 }
181                         }
182                 }
183         
184         ifstream inFFasta, inRFasta, inFQual, inRQual;
185         ofstream outFasta, outQual, outMisMatch, outScrapFasta, outScrapQual;
186         pDataArray->m->openInputFile(thisffastafile, inFFasta);
187         pDataArray->m->openInputFile(thisrfastafile, inRFasta);
188         if (thisfqualfile != "") {
189             pDataArray->m->openInputFile(thisfqualfile, inFQual);
190             pDataArray->m->openInputFile(thisrqualfile, inRQual);
191             pDataArray->m->openOutputFile(pDataArray->outputQual, outQual);
192             pDataArray->m->openOutputFile(pDataArray->outputScrapQual, outScrapQual);
193         }
194         pDataArray->m->openOutputFile(pDataArray->outputFasta, outFasta);
195         pDataArray->m->openOutputFile(pDataArray->outputMisMatches, outMisMatch);
196         pDataArray->m->openOutputFile(pDataArray->outputScrapFasta, outScrapFasta);
197         
198         outMisMatch << "Name\tLength\tMisMatches\n";
199         
200         TrimOligos trimOligos(pDataArray->pdiffs, pDataArray->bdiffs, 0, 0, pDataArray->primers, pDataArray->barcodes);
201         
202         while ((!inFFasta.eof()) && (!inRFasta.eof())) {
203             
204             if (pDataArray->m->control_pressed) { break; }
205             
206             int success = 1;
207             string trashCode = "";
208             int currentSeqsDiffs = 0;
209             
210             //read seqs and quality info
211             Sequence fSeq(inFFasta); pDataArray->m->gobble(inFFasta);
212             Sequence rSeq(inRFasta); pDataArray->m->gobble(inRFasta);
213             QualityScores* fQual = NULL; QualityScores* rQual = NULL;
214             if (thisfqualfile != "") {
215                 fQual = new QualityScores(inFQual); pDataArray->m->gobble(inFQual);
216                 rQual = new QualityScores(inRQual); pDataArray->m->gobble(inRQual);
217             }
218             
219             int barcodeIndex = 0;
220             int primerIndex = 0;
221             
222             if(pDataArray->barcodes.size() != 0){
223                 if (thisfqualfile != "") {
224                     success = trimOligos.stripBarcode(fSeq, rSeq, *fQual, *rQual, barcodeIndex);
225                 }else {
226                     success = trimOligos.stripBarcode(fSeq, rSeq, barcodeIndex);
227                 }
228                 if(success > pDataArray->bdiffs)                {       trashCode += 'b';       }
229                 else{ currentSeqsDiffs += success;  }
230             }
231             
232             if(pDataArray->primers.size() != 0){
233                 if (thisfqualfile != "") {
234                     success = trimOligos.stripForward(fSeq, rSeq, *fQual, *rQual, primerIndex);
235                 }else {
236                     success = trimOligos.stripForward(fSeq, rSeq, primerIndex);
237                 }
238                 if(success > pDataArray->pdiffs)                {       trashCode += 'f';       }
239                 else{ currentSeqsDiffs += success;  }
240             }
241             
242             if (currentSeqsDiffs > pDataArray->tdiffs)  {       trashCode += 't';   }
243             
244             //flip the reverse reads
245             rSeq.reverseComplement();
246             if (thisfqualfile != "") { rQual->flipQScores(); }
247            
248             //pairwise align
249             alignment->align(fSeq.getUnaligned(), rSeq.getUnaligned());
250             map<int, int> ABaseMap = alignment->getSeqAAlnBaseMap();
251             map<int, int> BBaseMap = alignment->getSeqBAlnBaseMap();
252             fSeq.setAligned(alignment->getSeqAAln());
253             rSeq.setAligned(alignment->getSeqBAln());
254             int length = fSeq.getAligned().length();
255             
256             //traverse alignments merging into one contiguous seq
257             string contig = "";
258             vector<int> contigScores; 
259             int numMismatches = 0;
260             string seq1 = fSeq.getAligned();
261             string seq2 = rSeq.getAligned();
262             vector<int> scores1, scores2;
263             if (thisfqualfile != "") {
264                 scores1 = fQual->getQualityScores();
265                 scores2 = rQual->getQualityScores();
266                 delete fQual; delete rQual;
267             }
268             
269             int overlapStart = fSeq.getStartPos();
270             int seq2Start = rSeq.getStartPos();
271             //bigger of the 2 starting positions is the location of the overlapping start
272             if (overlapStart < seq2Start) { //seq2 starts later so take from 0 to seq2Start from seq1
273                 overlapStart = seq2Start; 
274                 for (int i = 0; i < overlapStart; i++) {
275                     contig += seq1[i];
276                     if (thisfqualfile != "") { contigScores.push_back(scores1[ABaseMap[i]]); }
277                 }
278             }else { //seq1 starts later so take from 0 to overlapStart from seq2
279                 for (int i = 0; i < overlapStart; i++) {
280                     contig += seq2[i];
281                     if (thisfqualfile != "") { contigScores.push_back(scores2[BBaseMap[i]]); }
282                 }
283             }
284             
285             int seq1End = fSeq.getEndPos();
286             int seq2End = rSeq.getEndPos();
287             int overlapEnd = seq1End;
288             if (seq2End < overlapEnd) { overlapEnd = seq2End; }  //smallest end position is where overlapping ends
289             
290             for (int i = overlapStart; i < overlapEnd; i++) {
291                 if (seq1[i] == seq2[i]) { //match, add base and choose highest score
292                     contig += seq1[i];
293                     if (thisfqualfile != "") { 
294                         contigScores.push_back(scores1[ABaseMap[i]]);
295                         if (scores1[ABaseMap[i]] < scores2[BBaseMap[i]]) { contigScores[contigScores.size()-1] = scores2[BBaseMap[i]]; }
296                     }
297                 }else if (((seq1[i] == '.') || (seq1[i] == '-')) && ((seq2[i] != '-') && (seq2[i] != '.'))) { //seq1 is a gap and seq2 is a base, choose seq2, unless quality score for base is below threshold. In that case eliminate base
298                     if (thisfqualfile != "") {
299                         if (scores2[BBaseMap[i]] < pDataArray->threshold) { } //
300                         else {
301                             contig += seq2[i];
302                             contigScores.push_back(scores2[BBaseMap[i]]);
303                         }
304                     }else { contig += seq2[i]; }
305                 }else if (((seq2[i] == '.') || (seq2[i] == '-')) && ((seq1[i] != '-') && (seq1[i] != '.'))) { //seq2 is a gap and seq1 is a base, choose seq1, unless quality score for base is below threshold. In that case eliminate base
306                     if (thisfqualfile != "") {
307                         if (scores1[ABaseMap[i]] < pDataArray->threshold) { } //
308                         else {
309                             contig += seq1[i];
310                             contigScores.push_back(scores1[ABaseMap[i]]);
311                         }
312                     }else { contig += seq1[i]; }
313                 }else if (((seq1[i] != '-') && (seq1[i] != '.')) && ((seq2[i] != '-') && (seq2[i] != '.'))) { //both bases choose one with better quality
314                     if (thisfqualfile != "") {
315                         char c = seq1[i];
316                         contigScores.push_back(scores1[ABaseMap[i]]);
317                         if (scores1[ABaseMap[i]] < scores2[BBaseMap[i]]) { contigScores[contigScores.size()-1] = scores2[BBaseMap[i]]; c = seq2[i]; }
318                         contig += c;
319                         numMismatches++;
320                     }else { numMismatches++; }
321                 }else { //should never get here
322                     pDataArray->m->mothurOut("[ERROR]: case I didn't think of seq1 = " + toString(seq1[i]) + " and seq2 = " + toString(seq2[i]) + "\n");
323                 }
324             }
325             
326             if (seq1End < seq2End) { //seq1 ends before seq2 so take from overlap to length from seq2
327                 for (int i = overlapEnd; i < length; i++) {
328                     contig += seq2[i];
329                     if (thisfqualfile != "") { contigScores.push_back(scores2[BBaseMap[i]]); }
330                 }
331             }else { //seq2 ends before seq1 so take from overlap to length from seq1
332                 for (int i = overlapEnd; i < length; i++) {
333                     contig += seq1[i];
334                     if (thisfqualfile != "") { contigScores.push_back(scores1[ABaseMap[i]]); }
335                 }
336                 
337             }
338
339             if(trashCode.length() == 0){
340                 bool ignore = false;
341                 if (pDataArray->createGroup) {
342                     if(pDataArray->barcodes.size() != 0){
343                         string thisGroup = pDataArray->barcodeNameVector[barcodeIndex];
344                         if (pDataArray->primers.size() != 0) { 
345                             if (pDataArray->primerNameVector[primerIndex] != "") { 
346                                 if(thisGroup != "") {
347                                     thisGroup += "." + pDataArray->primerNameVector[primerIndex]; 
348                                 }else {
349                                     thisGroup = pDataArray->primerNameVector[primerIndex]; 
350                                 }
351                             } 
352                         }
353                         
354                         if (pDataArray->m->debug) { pDataArray->m->mothurOut(", group= " + thisGroup + "\n"); }
355                         
356                         int pos = thisGroup.find("ignore");
357                         if (pos == string::npos) {
358                             pDataArray->groupMap[fSeq.getName()] = thisGroup; 
359                         
360                             map<string, int>::iterator it = pDataArray->groupCounts.find(thisGroup);
361                             if (it == pDataArray->groupCounts.end()) {  pDataArray->groupCounts[thisGroup] = 1; }
362                             else { pDataArray->groupCounts[it->first] ++; }
363                         }else { ignore = true; }
364                     }
365                 }
366                 
367                 if(pDataArray->allFiles && !ignore){
368                     ofstream output;
369                     pDataArray->m->openOutputFileAppend(pDataArray->fastaFileNames[barcodeIndex][primerIndex], output);
370                     output << ">" << fSeq.getName() << endl << contig << endl;
371                     output.close();
372                     
373                     if (thisfqualfile != "") {
374                         pDataArray->m->openOutputFileAppend(pDataArray->qualFileNames[barcodeIndex][primerIndex], output);
375                         output << ">" << fSeq.getName() << endl;
376                         for (int i = 0; i < contigScores.size(); i++) { output << contigScores[i] << ' '; }
377                         output << endl;
378                         output.close(); 
379                     }
380                 }
381                 
382                 //output
383                 outFasta << ">" << fSeq.getName() << endl << contig << endl;
384                 if (thisfqualfile != "") {
385                     outQual << ">" << fSeq.getName() << endl;
386                     for (int i = 0; i < contigScores.size(); i++) { outQual << contigScores[i] << ' '; }
387                     outQual << endl;
388                 }
389                 outMisMatch << fSeq.getName() << '\t' << contig.length() << '\t' << numMismatches << endl;
390             }else {
391                 //output
392                 outScrapFasta << ">" << fSeq.getName() << " | " << trashCode << endl << contig << endl;
393                 if (thisfqualfile != "") {
394                     outScrapQual << ">" << fSeq.getName() << " | " << trashCode << endl;
395                     for (int i = 0; i < contigScores.size(); i++) { outScrapQual << contigScores[i] << ' '; }
396                     outScrapQual << endl;
397                 }
398             }
399             num++;
400             
401                         //report progress
402                         if((num) % 1000 == 0){  pDataArray->m->mothurOut(toString(num)); pDataArray->m->mothurOutEndLine();             }
403                 }
404         
405                 //report progress
406                 if((num) % 1000 != 0){  pDataArray->m->mothurOut(toString(num)); pDataArray->m->mothurOutEndLine();             }
407         
408         inFFasta.close();
409         inRFasta.close();
410         outFasta.close();
411         outMisMatch.close();
412         outScrapFasta.close();
413         if (thisfqualfile != "") {
414             inFQual.close();
415             inRQual.close();
416             outQual.close();
417             outScrapQual.close();
418         }
419         delete alignment;
420         
421         if (pDataArray->m->control_pressed) {  pDataArray->m->mothurRemove(pDataArray->outputFasta);  pDataArray->m->mothurRemove(pDataArray->outputMisMatches);  pDataArray->m->mothurRemove(pDataArray->outputScrapFasta);  if (thisfqualfile != "") { pDataArray->m->mothurRemove(pDataArray->outputQual); pDataArray->m->mothurRemove(pDataArray->outputScrapQual); } }
422         
423         return 0;
424                 
425         }
426         catch(exception& e) {
427                 pDataArray->m->errorOut(e, "AlignCommand", "MyContigsThreadFunction");
428                 exit(1);
429         }
430
431 #endif
432
433
434 #endif