]> git.donarmstrong.com Git - mothur.git/blob - makecontigscommand.h
Merge remote-tracking branch 'origin/master'
[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;
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     
75         map<string, int> groupCounts; 
76     map<string, string> groupMap;
77     //map<string, int> combos;
78         //map<string, int> groupToIndex;
79     //vector<string> groupVector;
80     
81     fastqRead readFastq(ifstream&, bool&);
82     vector< vector<string> > readFastqFiles(int&);
83     bool checkReads(fastqRead&, fastqRead&);
84     int createProcesses(vector< vector<string> >, string, string, string, string, string, vector<vector<string> >, vector<vector<string> >);
85     int driver(vector<string>, string, string, string, string, string, vector<vector<string> >, vector<vector<string> >);
86     bool getOligos(vector<vector<string> >&, vector<vector<string> >&);
87     string reverseOligo(string);
88     vector<pairFastqRead> getReads(bool ignoref, bool ignorer, fastqRead forward, fastqRead reverse, map<string, fastqRead>& uniques);
89 };
90
91 /**************************************************************************************************/
92
93 /**************************************************************************************************/
94 //custom data structure for threads to use.
95 // This is passed by void pointer so it can be any data type
96 // that can be passed using a single void pointer (LPVOID).
97 struct contigsData {
98         string outputFasta; 
99         string outputQual; 
100     string outputScrapFasta; 
101         string outputScrapQual;
102         string outputMisMatches;
103         string align;
104     vector<string> files;
105     vector<vector<string> > fastaFileNames;
106     vector<vector<string> > qualFileNames;
107         MothurOut* m;
108         float match, misMatch, gapOpen, gapExtend;
109         int count, threshold, threadID, pdiffs, bdiffs, tdiffs;
110     bool allFiles, createGroup;
111     map<string, int> groupCounts; 
112     map<string, string> groupMap;
113     vector<string> primerNameVector;    
114         vector<string> barcodeNameVector;
115     map<int, oligosPair> barcodes;
116         map<int, oligosPair> primers;
117         
118         contigsData(){}
119         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) {
120         files = f;
121                 outputFasta = of;
122         outputQual = oq;
123         outputMisMatches = om;
124         m = mout;
125                 match = ma; 
126                 misMatch = misMa;
127                 gapOpen = gapO; 
128                 gapExtend = gapE; 
129         threshold = thr;
130                 align = al;
131                 count = 0;
132         outputScrapFasta = osf;
133         outputScrapQual = osq;
134         fastaFileNames = ffn;
135         qualFileNames = qfn;
136         barcodes = br;
137         primers = pr;
138         barcodeNameVector = bnv;
139         primerNameVector = pnv;
140         pdiffs = pdf;
141         bdiffs = bdf;
142         tdiffs = tdf;
143         allFiles = all;
144         createGroup = cg;
145                 threadID = tid;
146         }
147 };
148
149 /**************************************************************************************************/
150 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
151 #else
152 static DWORD WINAPI MyContigsThreadFunction(LPVOID lpParam){ 
153         contigsData* pDataArray;
154         pDataArray = (contigsData*)lpParam;
155         
156         try {
157         int longestBase = 1000;
158         Alignment* alignment;
159         if(pDataArray->align == "gotoh")                        {       alignment = new GotohOverlap(pDataArray->gapOpen, pDataArray->gapExtend, pDataArray->match, pDataArray->misMatch, longestBase);                 }
160                 else if(pDataArray->align == "needleman")       {       alignment = new NeedlemanOverlap(pDataArray->gapOpen, pDataArray->match, pDataArray->misMatch, longestBase);                            }
161         
162         int num = 0;
163         string thisffastafile = pDataArray->files[0];
164         string thisfqualfile = pDataArray->files[1];
165         string thisrfastafile = pDataArray->files[2];
166         string thisrqualfile = pDataArray->files[3];
167         
168         if (pDataArray->m->debug) {  pDataArray->m->mothurOut("[DEBUG]: ffasta = " + thisffastafile + ".\n[DEBUG]: fqual = " + thisfqualfile + ".\n[DEBUG]: rfasta = " + thisrfastafile + ".\n[DEBUG]: rqual = " + thisrqualfile + ".\n"); }
169         
170                 if(pDataArray->allFiles){
171                         for (int i = 0; i < pDataArray->fastaFileNames.size(); i++) { //clears old file
172                                 for (int j = 0; j < pDataArray->fastaFileNames[i].size(); j++) { //clears old file
173                                         if (pDataArray->fastaFileNames[i][j] != "") {
174                                                 ofstream temp;
175                                                 pDataArray->m->openOutputFile(pDataArray->fastaFileNames[i][j], temp);                  temp.close();
176                         pDataArray->m->openOutputFile(pDataArray->qualFileNames[i][j], temp);                   temp.close();
177                                         }
178                                 }
179                         }
180                 }
181         
182         ifstream inFFasta, inRFasta, inFQual, inRQual;
183         pDataArray->m->openInputFile(thisffastafile, inFFasta);
184         pDataArray->m->openInputFile(thisfqualfile, inFQual);
185         pDataArray->m->openInputFile(thisrfastafile, inRFasta);
186         pDataArray->m->openInputFile(thisrqualfile, inRQual);
187         
188         ofstream outFasta, outQual, outMisMatch, outScrapFasta, outScrapQual;
189         pDataArray->m->openOutputFile(pDataArray->outputFasta, outFasta);
190         pDataArray->m->openOutputFile(pDataArray->outputQual, outQual);
191         pDataArray->m->openOutputFile(pDataArray->outputMisMatches, outMisMatch);
192         pDataArray->m->openOutputFile(pDataArray->outputScrapFasta, outScrapFasta);
193         pDataArray->m->openOutputFile(pDataArray->outputScrapQual, outScrapQual);
194         outMisMatch << "Name\tLength\tMisMatches\n";
195         
196         TrimOligos trimOligos(pDataArray->pdiffs, pDataArray->bdiffs, 0, 0, pDataArray->primers, pDataArray->barcodes);
197         
198         while ((!inFQual.eof()) && (!inFFasta.eof()) && (!inRFasta.eof()) && (!inRQual.eof())) {
199             
200             if (pDataArray->m->control_pressed) { break; }
201             
202             int success = 1;
203             string trashCode = "";
204             int currentSeqsDiffs = 0;
205             
206             //read seqs and quality info
207             Sequence fSeq(inFFasta); pDataArray->m->gobble(inFFasta);
208             Sequence rSeq(inRFasta); pDataArray->m->gobble(inRFasta);
209             QualityScores fQual(inFQual); pDataArray->m->gobble(inFQual);
210             QualityScores rQual(inRQual); pDataArray->m->gobble(inRQual);
211             
212             int barcodeIndex = 0;
213             int primerIndex = 0;
214             
215             if(pDataArray->barcodes.size() != 0){
216                 success = trimOligos.stripBarcode(fSeq, rSeq, fQual, rQual, barcodeIndex);
217                 if(success > pDataArray->bdiffs)                {       trashCode += 'b';       }
218                 else{ currentSeqsDiffs += success;  }
219             }
220             
221             if(pDataArray->primers.size() != 0){
222                 success = trimOligos.stripForward(fSeq, rSeq, fQual, rQual, primerIndex);
223                 if(success > pDataArray->pdiffs)                {       trashCode += 'f';       }
224                 else{ currentSeqsDiffs += success;  }
225             }
226             
227             if (currentSeqsDiffs > pDataArray->tdiffs)  {       trashCode += 't';   }
228             
229             //flip the reverse reads
230             rSeq.reverseComplement();
231             rQual.flipQScores();
232            
233             //pairwise align
234             alignment->align(fSeq.getUnaligned(), rSeq.getUnaligned());
235             map<int, int> ABaseMap = alignment->getSeqAAlnBaseMap();
236             map<int, int> BBaseMap = alignment->getSeqBAlnBaseMap();
237             fSeq.setAligned(alignment->getSeqAAln());
238             rSeq.setAligned(alignment->getSeqBAln());
239             int length = fSeq.getAligned().length();
240             
241             //traverse alignments merging into one contiguous seq
242             string contig = "";
243             vector<int> contigScores; 
244             int numMismatches = 0;
245             string seq1 = fSeq.getAligned();
246             string seq2 = rSeq.getAligned();
247             vector<int> scores1 = fQual.getQualityScores();
248             vector<int> scores2 = rQual.getQualityScores();
249             
250             int overlapStart = fSeq.getStartPos();
251             int seq2Start = rSeq.getStartPos();
252             //bigger of the 2 starting positions is the location of the overlapping start
253             if (overlapStart < seq2Start) { //seq2 starts later so take from 0 to seq2Start from seq1
254                 overlapStart = seq2Start; 
255                 for (int i = 0; i < overlapStart; i++) {
256                     contig += seq1[i];
257                     contigScores.push_back(scores1[ABaseMap[i]]);
258                 }
259             }else { //seq1 starts later so take from 0 to overlapStart from seq2
260                 for (int i = 0; i < overlapStart; i++) {
261                     contig += seq2[i];
262                     contigScores.push_back(scores2[BBaseMap[i]]);
263                 }
264             }
265             
266             int seq1End = fSeq.getEndPos();
267             int seq2End = rSeq.getEndPos();
268             int overlapEnd = seq1End;
269             if (seq2End < overlapEnd) { overlapEnd = seq2End; }  //smallest end position is where overlapping ends
270             
271             for (int i = overlapStart; i < overlapEnd; i++) {
272                 if (seq1[i] == seq2[i]) { //match, add base and choose highest score
273                     contig += seq1[i];
274                     contigScores.push_back(scores1[ABaseMap[i]]);
275                     if (scores1[ABaseMap[i]] < scores2[BBaseMap[i]]) { contigScores[contigScores.size()-1] = scores2[BBaseMap[i]]; }
276                 }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
277                     if (scores2[BBaseMap[i]] < pDataArray->threshold) { } //
278                     else {
279                         contig += seq2[i];
280                         contigScores.push_back(scores2[BBaseMap[i]]);
281                     }
282                 }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
283                     if (scores1[ABaseMap[i]] < pDataArray->threshold) { } //
284                     else {
285                         contig += seq1[i];
286                         contigScores.push_back(scores1[ABaseMap[i]]);
287                     }
288                 }else if (((seq1[i] != '-') && (seq1[i] != '.')) && ((seq2[i] != '-') && (seq2[i] != '.'))) { //both bases choose one with better quality
289                     char c = seq1[i];
290                     contigScores.push_back(scores1[ABaseMap[i]]);
291                     if (scores1[ABaseMap[i]] < scores2[BBaseMap[i]]) { contigScores[contigScores.size()-1] = scores2[BBaseMap[i]]; c = seq2[i]; }
292                     contig += c;
293                     numMismatches++;
294                 }else { //should never get here
295                     pDataArray->m->mothurOut("[ERROR]: case I didn't think of seq1 = " + toString(seq1[i]) + " and seq2 = " + toString(seq2[i]) + "\n");
296                 }
297             }
298             
299             if (seq1End < seq2End) { //seq1 ends before seq2 so take from overlap to length from seq2
300                 for (int i = overlapEnd; i < length; i++) {
301                     contig += seq2[i];
302                     contigScores.push_back(scores2[BBaseMap[i]]);
303                 }
304             }else { //seq2 ends before seq1 so take from overlap to length from seq1
305                 for (int i = overlapEnd; i < length; i++) {
306                     contig += seq1[i];
307                     contigScores.push_back(scores1[ABaseMap[i]]);
308                 }
309                 
310             }
311
312             if(trashCode.length() == 0){
313                 if (pDataArray->createGroup) {
314                     if(pDataArray->barcodes.size() != 0){
315                         string thisGroup = pDataArray->barcodeNameVector[barcodeIndex];
316                         if (pDataArray->primers.size() != 0) { 
317                             if (pDataArray->primerNameVector[primerIndex] != "") { 
318                                 if(thisGroup != "") {
319                                     thisGroup += "." + pDataArray->primerNameVector[primerIndex]; 
320                                 }else {
321                                     thisGroup = pDataArray->primerNameVector[primerIndex]; 
322                                 }
323                             } 
324                         }
325                         
326                         if (pDataArray->m->debug) { pDataArray->m->mothurOut(", group= " + thisGroup + "\n"); }
327                         
328                         pDataArray->groupMap[fSeq.getName()] = thisGroup; 
329                         
330                         map<string, int>::iterator it = pDataArray->groupCounts.find(thisGroup);
331                         if (it == pDataArray->groupCounts.end()) {      pDataArray->groupCounts[thisGroup] = 1; }
332                         else { pDataArray->groupCounts[it->first] ++; }
333                         
334                     }
335                 }
336                 
337                 if(pDataArray->allFiles){
338                     ofstream output;
339                     pDataArray->m->openOutputFileAppend(pDataArray->fastaFileNames[barcodeIndex][primerIndex], output);
340                     output << ">" << fSeq.getName() << endl << contig << endl;
341                     output.close();
342                     
343                     pDataArray->m->openOutputFileAppend(pDataArray->qualFileNames[barcodeIndex][primerIndex], output);
344                     output << ">" << fSeq.getName() << endl;
345                     for (int i = 0; i < contigScores.size(); i++) { output << contigScores[i] << ' '; }
346                     output << endl;
347                     output.close();                                                     
348                 }
349                 
350                 //output
351                 outFasta << ">" << fSeq.getName() << endl << contig << endl;
352                 outQual << ">" << fSeq.getName() << endl;
353                 for (int i = 0; i < contigScores.size(); i++) { outQual << contigScores[i] << ' '; }
354                 outQual << endl;
355                 outMisMatch << fSeq.getName() << '\t' << contig.length() << '\t' << numMismatches << endl;
356             }else {
357                 //output
358                 outScrapFasta << ">" << fSeq.getName() << " | " << trashCode << endl << contig << endl;
359                 outScrapQual << ">" << fSeq.getName() << " | " << trashCode << endl;
360                 for (int i = 0; i < contigScores.size(); i++) { outScrapQual << contigScores[i] << ' '; }
361                 outScrapQual << endl;
362             }
363             num++;
364             
365                         //report progress
366                         if((num) % 1000 == 0){  pDataArray->m->mothurOut(toString(num)); pDataArray->m->mothurOutEndLine();             }
367                 }
368         
369                 //report progress
370                 if((num) % 1000 != 0){  pDataArray->m->mothurOut(toString(num)); pDataArray->m->mothurOutEndLine();             }
371         
372         inFFasta.close();
373         inFQual.close();
374         inRFasta.close();
375         inRQual.close();
376         outFasta.close();
377         outQual.close();
378         outMisMatch.close();
379         outScrapFasta.close();
380         outScrapQual.close();
381         delete alignment;
382         
383         if (pDataArray->m->control_pressed) { pDataArray->m->mothurRemove(pDataArray->outputQual); pDataArray->m->mothurRemove(pDataArray->outputFasta);  pDataArray->m->mothurRemove(pDataArray->outputMisMatches); pDataArray->m->mothurRemove(pDataArray->outputScrapQual); pDataArray->m->mothurRemove(pDataArray->outputScrapFasta);}
384         
385         return 0;
386                 
387         }
388         catch(exception& e) {
389                 pDataArray->m->errorOut(e, "AlignCommand", "MyContigsThreadFunction");
390                 exit(1);
391         }
392
393 #endif
394
395
396 #endif