]> git.donarmstrong.com Git - mothur.git/blob - makecontigscommand.h
added checks to make sure windows processes completed their tasks.
[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, done;
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         done=false;
149         }
150 };
151
152 /**************************************************************************************************/
153 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
154 #else
155 static DWORD WINAPI MyContigsThreadFunction(LPVOID lpParam){ 
156         contigsData* pDataArray;
157         pDataArray = (contigsData*)lpParam;
158         
159         try {
160         int longestBase = 1000;
161         Alignment* alignment;
162         if(pDataArray->align == "gotoh")                        {       alignment = new GotohOverlap(pDataArray->gapOpen, pDataArray->gapExtend, pDataArray->match, pDataArray->misMatch, longestBase);                 }
163                 else if(pDataArray->align == "needleman")       {       alignment = new NeedlemanOverlap(pDataArray->gapOpen, pDataArray->match, pDataArray->misMatch, longestBase);                            }
164         
165         pDataArray->count = 0;
166         string thisffastafile = pDataArray->files[0];
167         string thisfqualfile = pDataArray->files[1];
168         string thisrfastafile = pDataArray->files[2];
169         string thisrqualfile = pDataArray->files[3];
170         
171         if (pDataArray->m->debug) {  pDataArray->m->mothurOut("[DEBUG]: ffasta = " + thisffastafile + ".\n[DEBUG]: fqual = " + thisfqualfile + ".\n[DEBUG]: rfasta = " + thisrfastafile + ".\n[DEBUG]: rqual = " + thisrqualfile + ".\n"); }
172         
173                 if(pDataArray->allFiles){
174                         for (int i = 0; i < pDataArray->fastaFileNames.size(); i++) { //clears old file
175                                 for (int j = 0; j < pDataArray->fastaFileNames[i].size(); j++) { //clears old file
176                                         if (pDataArray->fastaFileNames[i][j] != "") {
177                                                 ofstream temp;
178                                                 pDataArray->m->openOutputFile(pDataArray->fastaFileNames[i][j], temp);                  temp.close();
179                         if (thisfqualfile != "") { pDataArray->m->openOutputFile(pDataArray->qualFileNames[i][j], temp);                        temp.close(); }
180                                         }
181                                 }
182                         }
183                 }
184         
185         ifstream inFFasta, inRFasta, inFQual, inRQual;
186         ofstream outFasta, outQual, outMisMatch, outScrapFasta, outScrapQual;
187         pDataArray->m->openInputFile(thisffastafile, inFFasta);
188         pDataArray->m->openInputFile(thisrfastafile, inRFasta);
189         if (thisfqualfile != "") {
190             pDataArray->m->openInputFile(thisfqualfile, inFQual);
191             pDataArray->m->openInputFile(thisrqualfile, inRQual);
192             pDataArray->m->openOutputFile(pDataArray->outputQual, outQual);
193             pDataArray->m->openOutputFile(pDataArray->outputScrapQual, outScrapQual);
194         }
195         pDataArray->m->openOutputFile(pDataArray->outputFasta, outFasta);
196         pDataArray->m->openOutputFile(pDataArray->outputMisMatches, outMisMatch);
197         pDataArray->m->openOutputFile(pDataArray->outputScrapFasta, outScrapFasta);
198         
199         outMisMatch << "Name\tLength\tMisMatches\n";
200         
201         TrimOligos trimOligos(pDataArray->pdiffs, pDataArray->bdiffs, 0, 0, pDataArray->primers, pDataArray->barcodes);
202         
203         while ((!inFFasta.eof()) && (!inRFasta.eof())) {
204             
205             if (pDataArray->m->control_pressed) { break; }
206             
207             int success = 1;
208             string trashCode = "";
209             int currentSeqsDiffs = 0;
210             
211             //read seqs and quality info
212             Sequence fSeq(inFFasta); pDataArray->m->gobble(inFFasta);
213             Sequence rSeq(inRFasta); pDataArray->m->gobble(inRFasta);
214             QualityScores* fQual = NULL; QualityScores* rQual = NULL;
215             if (thisfqualfile != "") {
216                 fQual = new QualityScores(inFQual); pDataArray->m->gobble(inFQual);
217                 rQual = new QualityScores(inRQual); pDataArray->m->gobble(inRQual);
218             }
219             
220             int barcodeIndex = 0;
221             int primerIndex = 0;
222             
223             if(pDataArray->barcodes.size() != 0){
224                 if (thisfqualfile != "") {
225                     success = trimOligos.stripBarcode(fSeq, rSeq, *fQual, *rQual, barcodeIndex);
226                 }else {
227                     success = trimOligos.stripBarcode(fSeq, rSeq, barcodeIndex);
228                 }
229                 if(success > pDataArray->bdiffs)                {       trashCode += 'b';       }
230                 else{ currentSeqsDiffs += success;  }
231             }
232             
233             if(pDataArray->primers.size() != 0){
234                 if (thisfqualfile != "") {
235                     success = trimOligos.stripForward(fSeq, rSeq, *fQual, *rQual, primerIndex);
236                 }else {
237                     success = trimOligos.stripForward(fSeq, rSeq, primerIndex);
238                 }
239                 if(success > pDataArray->pdiffs)                {       trashCode += 'f';       }
240                 else{ currentSeqsDiffs += success;  }
241             }
242             
243             if (currentSeqsDiffs > pDataArray->tdiffs)  {       trashCode += 't';   }
244             
245             //flip the reverse reads
246             rSeq.reverseComplement();
247             if (thisfqualfile != "") { rQual->flipQScores(); }
248            
249             //pairwise align
250             alignment->align(fSeq.getUnaligned(), rSeq.getUnaligned());
251             map<int, int> ABaseMap = alignment->getSeqAAlnBaseMap();
252             map<int, int> BBaseMap = alignment->getSeqBAlnBaseMap();
253             fSeq.setAligned(alignment->getSeqAAln());
254             rSeq.setAligned(alignment->getSeqBAln());
255             int length = fSeq.getAligned().length();
256             
257             //traverse alignments merging into one contiguous seq
258             string contig = "";
259             vector<int> contigScores; 
260             int numMismatches = 0;
261             string seq1 = fSeq.getAligned();
262             string seq2 = rSeq.getAligned();
263             vector<int> scores1, scores2;
264             if (thisfqualfile != "") {
265                 scores1 = fQual->getQualityScores();
266                 scores2 = rQual->getQualityScores();
267                 delete fQual; delete rQual;
268             }
269             
270             int overlapStart = fSeq.getStartPos();
271             int seq2Start = rSeq.getStartPos();
272             //bigger of the 2 starting positions is the location of the overlapping start
273             if (overlapStart < seq2Start) { //seq2 starts later so take from 0 to seq2Start from seq1
274                 overlapStart = seq2Start; 
275                 for (int i = 0; i < overlapStart; i++) {
276                     contig += seq1[i];
277                     if (thisfqualfile != "") { contigScores.push_back(scores1[ABaseMap[i]]); }
278                 }
279             }else { //seq1 starts later so take from 0 to overlapStart from seq2
280                 for (int i = 0; i < overlapStart; i++) {
281                     contig += seq2[i];
282                     if (thisfqualfile != "") { contigScores.push_back(scores2[BBaseMap[i]]); }
283                 }
284             }
285             
286             int seq1End = fSeq.getEndPos();
287             int seq2End = rSeq.getEndPos();
288             int overlapEnd = seq1End;
289             if (seq2End < overlapEnd) { overlapEnd = seq2End; }  //smallest end position is where overlapping ends
290             
291             for (int i = overlapStart; i < overlapEnd; i++) {
292                 if (seq1[i] == seq2[i]) { //match, add base and choose highest score
293                     contig += seq1[i];
294                     if (thisfqualfile != "") { 
295                         contigScores.push_back(scores1[ABaseMap[i]]);
296                         if (scores1[ABaseMap[i]] < scores2[BBaseMap[i]]) { contigScores[contigScores.size()-1] = scores2[BBaseMap[i]]; }
297                     }
298                 }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
299                     if (thisfqualfile != "") {
300                         if (scores2[BBaseMap[i]] < pDataArray->threshold) { } //
301                         else {
302                             contig += seq2[i];
303                             contigScores.push_back(scores2[BBaseMap[i]]);
304                         }
305                     }else { contig += seq2[i]; }
306                 }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
307                     if (thisfqualfile != "") {
308                         if (scores1[ABaseMap[i]] < pDataArray->threshold) { } //
309                         else {
310                             contig += seq1[i];
311                             contigScores.push_back(scores1[ABaseMap[i]]);
312                         }
313                     }else { contig += seq1[i]; }
314                 }else if (((seq1[i] != '-') && (seq1[i] != '.')) && ((seq2[i] != '-') && (seq2[i] != '.'))) { //both bases choose one with better quality
315                     if (thisfqualfile != "") {
316                         char c = seq1[i];
317                         contigScores.push_back(scores1[ABaseMap[i]]);
318                         if (scores1[ABaseMap[i]] < scores2[BBaseMap[i]]) { contigScores[contigScores.size()-1] = scores2[BBaseMap[i]]; c = seq2[i]; }
319                         contig += c;
320                         numMismatches++;
321                     }else { numMismatches++; }
322                 }else { //should never get here
323                     pDataArray->m->mothurOut("[ERROR]: case I didn't think of seq1 = " + toString(seq1[i]) + " and seq2 = " + toString(seq2[i]) + "\n");
324                 }
325             }
326             
327             if (seq1End < seq2End) { //seq1 ends before seq2 so take from overlap to length from seq2
328                 for (int i = overlapEnd; i < length; i++) {
329                     contig += seq2[i];
330                     if (thisfqualfile != "") { contigScores.push_back(scores2[BBaseMap[i]]); }
331                 }
332             }else { //seq2 ends before seq1 so take from overlap to length from seq1
333                 for (int i = overlapEnd; i < length; i++) {
334                     contig += seq1[i];
335                     if (thisfqualfile != "") { contigScores.push_back(scores1[ABaseMap[i]]); }
336                 }
337                 
338             }
339
340             if(trashCode.length() == 0){
341                 bool ignore = false;
342                 if (pDataArray->createGroup) {
343                     if(pDataArray->barcodes.size() != 0){
344                         string thisGroup = pDataArray->barcodeNameVector[barcodeIndex];
345                         if (pDataArray->primers.size() != 0) { 
346                             if (pDataArray->primerNameVector[primerIndex] != "") { 
347                                 if(thisGroup != "") {
348                                     thisGroup += "." + pDataArray->primerNameVector[primerIndex]; 
349                                 }else {
350                                     thisGroup = pDataArray->primerNameVector[primerIndex]; 
351                                 }
352                             } 
353                         }
354                         
355                         if (pDataArray->m->debug) { pDataArray->m->mothurOut(", group= " + thisGroup + "\n"); }
356                         
357                         int pos = thisGroup.find("ignore");
358                         if (pos == string::npos) {
359                             pDataArray->groupMap[fSeq.getName()] = thisGroup; 
360                         
361                             map<string, int>::iterator it = pDataArray->groupCounts.find(thisGroup);
362                             if (it == pDataArray->groupCounts.end()) {  pDataArray->groupCounts[thisGroup] = 1; }
363                             else { pDataArray->groupCounts[it->first] ++; }
364                         }else { ignore = true; }
365                     }
366                 }
367                 
368                 if(pDataArray->allFiles && !ignore){
369                     ofstream output;
370                     pDataArray->m->openOutputFileAppend(pDataArray->fastaFileNames[barcodeIndex][primerIndex], output);
371                     output << ">" << fSeq.getName() << endl << contig << endl;
372                     output.close();
373                     
374                     if (thisfqualfile != "") {
375                         pDataArray->m->openOutputFileAppend(pDataArray->qualFileNames[barcodeIndex][primerIndex], output);
376                         output << ">" << fSeq.getName() << endl;
377                         for (int i = 0; i < contigScores.size(); i++) { output << contigScores[i] << ' '; }
378                         output << endl;
379                         output.close(); 
380                     }
381                 }
382                 
383                 //output
384                 outFasta << ">" << fSeq.getName() << endl << contig << endl;
385                 if (thisfqualfile != "") {
386                     outQual << ">" << fSeq.getName() << endl;
387                     for (int i = 0; i < contigScores.size(); i++) { outQual << contigScores[i] << ' '; }
388                     outQual << endl;
389                 }
390                 outMisMatch << fSeq.getName() << '\t' << contig.length() << '\t' << numMismatches << endl;
391             }else {
392                 //output
393                 outScrapFasta << ">" << fSeq.getName() << " | " << trashCode << endl << contig << endl;
394                 if (thisfqualfile != "") {
395                     outScrapQual << ">" << fSeq.getName() << " | " << trashCode << endl;
396                     for (int i = 0; i < contigScores.size(); i++) { outScrapQual << contigScores[i] << ' '; }
397                     outScrapQual << endl;
398                 }
399             }
400             pDataArray->count++;
401             
402                         //report progress
403                         if((pDataArray->count) % 1000 == 0){    pDataArray->m->mothurOut(toString(pDataArray->count)); pDataArray->m->mothurOutEndLine();               }
404                 }
405         
406                 //report progress
407                 if((pDataArray->count) % 1000 != 0){    pDataArray->m->mothurOut(toString(pDataArray->count)); pDataArray->m->mothurOutEndLine();               }
408         
409         inFFasta.close();
410         inRFasta.close();
411         outFasta.close();
412         outMisMatch.close();
413         outScrapFasta.close();
414         if (thisfqualfile != "") {
415             inFQual.close();
416             inRQual.close();
417             outQual.close();
418             outScrapQual.close();
419         }
420         delete alignment;
421         
422         pDataArray->done = true;
423         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); } }
424         
425         return 0;
426                 
427         }
428         catch(exception& e) {
429                 pDataArray->m->errorOut(e, "AlignCommand", "MyContigsThreadFunction");
430                 exit(1);
431         }
432
433 #endif
434
435
436 #endif