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