2 * chimeraslayercommand.cpp
5 * Created by westcott on 3/31/10.
6 * Copyright 2010 Schloss Lab. All rights reserved.
10 #include "chimeraslayercommand.h"
11 #include "deconvolutecommand.h"
12 #include "referencedb.h"
13 #include "sequenceparser.h"
14 #include "counttable.h"
16 //**********************************************************************************************************************
17 vector<string> ChimeraSlayerCommand::setParameters(){
19 CommandParameter ptemplate("reference", "InputTypes", "", "", "none", "none", "none","",false,true,true); parameters.push_back(ptemplate);
20 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none","chimera-accnos",false,true,true); parameters.push_back(pfasta);
21 CommandParameter pname("name", "InputTypes", "", "", "NameCount", "none", "none","",false,false,true); parameters.push_back(pname);
22 CommandParameter pcount("count", "InputTypes", "", "", "NameCount-CountGroup", "none", "none","",false,false,true); parameters.push_back(pcount);
23 CommandParameter pgroup("group", "InputTypes", "", "", "CountGroup", "none", "none","",false,false,true); parameters.push_back(pgroup);
24 CommandParameter pwindow("window", "Number", "", "50", "", "", "","",false,false); parameters.push_back(pwindow);
25 CommandParameter pksize("ksize", "Number", "", "7", "", "", "","",false,false); parameters.push_back(pksize);
26 CommandParameter pmatch("match", "Number", "", "5.0", "", "", "","",false,false); parameters.push_back(pmatch);
27 CommandParameter pmismatch("mismatch", "Number", "", "-4.0", "", "", "","",false,false); parameters.push_back(pmismatch);
28 CommandParameter pminsim("minsim", "Number", "", "90", "", "", "","",false,false); parameters.push_back(pminsim);
29 CommandParameter pmincov("mincov", "Number", "", "70", "", "", "","",false,false); parameters.push_back(pmincov);
30 CommandParameter pminsnp("minsnp", "Number", "", "10", "", "", "","",false,false); parameters.push_back(pminsnp);
31 CommandParameter pminbs("minbs", "Number", "", "90", "", "", "","",false,false); parameters.push_back(pminbs);
32 CommandParameter psearch("search", "Multiple", "kmer-blast", "blast", "", "", "","",false,false); parameters.push_back(psearch);
33 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "","",false,false,true); parameters.push_back(pprocessors);
35 CommandParameter prealign("realign", "Boolean", "", "T", "", "", "","",false,false); parameters.push_back(prealign);
36 CommandParameter ptrim("trim", "Boolean", "", "F", "", "", "","fasta",false,false); parameters.push_back(ptrim);
37 CommandParameter psplit("split", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(psplit);
38 CommandParameter pnumwanted("numwanted", "Number", "", "15", "", "", "","",false,false); parameters.push_back(pnumwanted);
39 CommandParameter piters("iters", "Number", "", "1000", "", "", "","",false,false); parameters.push_back(piters);
40 CommandParameter pdivergence("divergence", "Number", "", "1.007", "", "", "","",false,false); parameters.push_back(pdivergence);
41 CommandParameter pdups("dereplicate", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(pdups);
42 CommandParameter pparents("parents", "Number", "", "3", "", "", "","",false,false); parameters.push_back(pparents);
43 CommandParameter pincrement("increment", "Number", "", "5", "", "", "","",false,false); parameters.push_back(pincrement);
44 CommandParameter pblastlocation("blastlocation", "String", "", "", "", "", "","",false,false); parameters.push_back(pblastlocation);
45 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
46 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
47 CommandParameter psave("save", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(psave);
49 vector<string> myArray;
50 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
54 m->errorOut(e, "ChimeraSlayerCommand", "setParameters");
58 //**********************************************************************************************************************
59 string ChimeraSlayerCommand::getHelpString(){
61 string helpString = "";
62 helpString += "The chimera.slayer command reads a fastafile and referencefile and outputs potentially chimeric sequences.\n";
63 helpString += "This command was modeled after the chimeraSlayer written by the Broad Institute.\n";
64 helpString += "The chimera.slayer command parameters are fasta, name, group, template, processors, dereplicate, trim, ksize, window, match, mismatch, divergence. minsim, mincov, minbs, minsnp, parents, search, iters, increment, numwanted, blastlocation and realign.\n";
65 helpString += "The fasta parameter allows you to enter the fasta file containing your potentially chimeric sequences, and is required, unless you have a valid current fasta file. \n";
66 helpString += "The name parameter allows you to provide a name file, if you are using reference=self. \n";
67 helpString += "The group parameter allows you to provide a group file. The group file can be used with a namesfile and reference=self. When checking sequences, only sequences from the same group as the query sequence will be used as the reference. \n";
68 helpString += "The count parameter allows you to provide a count file. The count file reference=self. If your count file contains group information, when checking sequences, only sequences from the same group as the query sequence will be used as the reference. When you use a count file with group info and dereplicate=T, mothur will create a *.pick.count_table file containing seqeunces after chimeras are removed. \n";
69 helpString += "You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amazon.fasta \n";
70 helpString += "The reference parameter allows you to enter a reference file containing known non-chimeric sequences, and is required. You may also set template=self, in this case the abundant sequences will be used as potential parents. \n";
71 helpString += "The processors parameter allows you to specify how many processors you would like to use. The default is 1. \n";
73 helpString += "When using MPI, the processors parameter is set to the number of MPI processes running. \n";
75 helpString += "If the dereplicate parameter is false, then if one group finds the seqeunce to be chimeric, then all groups find it to be chimeric, default=f.\n";
76 helpString += "The trim parameter allows you to output a new fasta file containing your sequences with the chimeric ones trimmed to include only their longest piece, default=F. \n";
77 helpString += "The split parameter allows you to check both pieces of non-chimeric sequence for chimeras, thus looking for trimeras and quadmeras. default=F. \n";
78 helpString += "The window parameter allows you to specify the window size for searching for chimeras, default=50. \n";
79 helpString += "The increment parameter allows you to specify how far you move each window while finding chimeric sequences, default=5.\n";
80 helpString += "The numwanted parameter allows you to specify how many sequences you would each query sequence compared with, default=15.\n";
81 helpString += "The ksize parameter allows you to input kmersize, default is 7, used if search is kmer. \n";
82 helpString += "The match parameter allows you to reward matched bases in blast search, default is 5. \n";
83 helpString += "The parents parameter allows you to select the number of potential parents to investigate from the numwanted best matches after rating them, default is 3. \n";
84 helpString += "The mismatch parameter allows you to penalize mismatched bases in blast search, default is -4. \n";
85 helpString += "The divergence parameter allows you to set a cutoff for chimera determination, default is 1.007. \n";
86 helpString += "The iters parameter allows you to specify the number of bootstrap iters to do with the chimeraslayer method, default=1000.\n";
87 helpString += "The minsim parameter allows you to specify a minimum similarity with the parent fragments, default=90. \n";
88 helpString += "The mincov parameter allows you to specify minimum coverage by closest matches found in template. Default is 70, meaning 70%. \n";
89 helpString += "The minbs parameter allows you to specify minimum bootstrap support for calling a sequence chimeric. Default is 90, meaning 90%. \n";
90 helpString += "The minsnp parameter allows you to specify percent of SNPs to sample on each side of breakpoint for computing bootstrap support (default: 10) \n";
91 helpString += "The search parameter allows you to specify search method for finding the closest parent. Choices are blast, and kmer, default blast. \n";
92 helpString += "The realign parameter allows you to realign the query to the potential parents. Choices are true or false, default true. \n";
93 helpString += "The blastlocation parameter allows you to specify the location of your blast executable. By default mothur will look in ./blast/bin relative to mothur's executable. \n";
94 helpString += "If the save parameter is set to true the reference sequences will be saved in memory, to clear them later you can use the clear.memory command. Default=f.";
95 helpString += "The chimera.slayer command should be in the following format: \n";
96 helpString += "chimera.slayer(fasta=yourFastaFile, reference=yourTemplate, search=yourSearch) \n";
97 helpString += "Example: chimera.slayer(fasta=AD.align, reference=core_set_aligned.imputed.fasta, search=kmer) \n";
98 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";
101 catch(exception& e) {
102 m->errorOut(e, "ChimeraSlayerCommand", "getHelpString");
106 //**********************************************************************************************************************
107 string ChimeraSlayerCommand::getOutputPattern(string type) {
111 if (type == "chimera") { pattern = "[filename],slayer.chimeras"; }
112 else if (type == "accnos") { pattern = "[filename],slayer.accnos"; }
113 else if (type == "fasta") { pattern = "[filename],slayer.fasta"; }
114 else if (type == "count") { pattern = "[filename],slayer.pick.count_table"; }
115 else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true; }
119 catch(exception& e) {
120 m->errorOut(e, "ChimeraSlayerCommand", "getOutputPattern");
124 //**********************************************************************************************************************
125 ChimeraSlayerCommand::ChimeraSlayerCommand(){
127 abort = true; calledHelp = true;
129 vector<string> tempOutNames;
130 outputTypes["chimera"] = tempOutNames;
131 outputTypes["accnos"] = tempOutNames;
132 outputTypes["fasta"] = tempOutNames;
133 outputTypes["count"] = tempOutNames;
135 catch(exception& e) {
136 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
140 //***************************************************************************************************************
141 ChimeraSlayerCommand::ChimeraSlayerCommand(string option) {
143 abort = false; calledHelp = false;
144 ReferenceDB* rdb = ReferenceDB::getInstance();
148 //allow user to run help
149 if(option == "help") { help(); abort = true; calledHelp = true; }
150 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
153 vector<string> myArray = setParameters();
155 OptionParser parser(option);
156 map<string,string> parameters = parser.getParameters();
158 ValidParameters validParameter("chimera.slayer");
159 map<string,string>::iterator it;
161 //check to make sure all parameters are valid for command
162 for (it = parameters.begin(); it != parameters.end(); it++) {
163 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
166 vector<string> tempOutNames;
167 outputTypes["chimera"] = tempOutNames;
168 outputTypes["accnos"] = tempOutNames;
169 outputTypes["fasta"] = tempOutNames;
170 outputTypes["count"] = tempOutNames;
172 //if the user changes the input directory command factory will send this info to us in the output parameter
173 string inputDir = validParameter.validFile(parameters, "inputdir", false);
174 if (inputDir == "not found"){ inputDir = ""; }
176 //check for required parameters
177 fastafile = validParameter.validFile(parameters, "fasta", false);
178 if (fastafile == "not found") {
179 //if there is a current fasta file, use it
180 string filename = m->getFastaFile();
181 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
182 else { m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
184 m->splitAtDash(fastafile, fastaFileNames);
186 //go through files and make sure they are good, if not, then disregard them
187 for (int i = 0; i < fastaFileNames.size(); i++) {
190 if (fastaFileNames[i] == "current") {
191 fastaFileNames[i] = m->getFastaFile();
192 if (fastaFileNames[i] != "") { m->mothurOut("Using " + fastaFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
194 m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true;
195 //erase from file list
196 fastaFileNames.erase(fastaFileNames.begin()+i);
203 if (inputDir != "") {
204 string path = m->hasPath(fastaFileNames[i]);
205 //if the user has not given a path then, add inputdir. else leave path alone.
206 if (path == "") { fastaFileNames[i] = inputDir + fastaFileNames[i]; }
212 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
214 //if you can't open it, try default location
215 if (ableToOpen == 1) {
216 if (m->getDefaultPath() != "") { //default path is set
217 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
218 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
220 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
222 fastaFileNames[i] = tryPath;
226 if (ableToOpen == 1) {
227 if (m->getOutputDir() != "") { //default path is set
228 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
229 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
231 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
233 fastaFileNames[i] = tryPath;
239 if (ableToOpen == 1) {
240 m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
241 //erase from file list
242 fastaFileNames.erase(fastaFileNames.begin()+i);
245 m->setFastaFile(fastaFileNames[i]);
250 //make sure there is at least one valid file left
251 if (fastaFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid files."); m->mothurOutEndLine(); abort = true; }
255 //check for required parameters
256 namefile = validParameter.validFile(parameters, "name", false);
257 if (namefile == "not found") { namefile = ""; }
259 m->splitAtDash(namefile, nameFileNames);
261 //go through files and make sure they are good, if not, then disregard them
262 for (int i = 0; i < nameFileNames.size(); i++) {
265 if (nameFileNames[i] == "current") {
266 nameFileNames[i] = m->getNameFile();
267 if (nameFileNames[i] != "") { m->mothurOut("Using " + nameFileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
269 m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true;
270 //erase from file list
271 nameFileNames.erase(nameFileNames.begin()+i);
278 if (inputDir != "") {
279 string path = m->hasPath(nameFileNames[i]);
280 //if the user has not given a path then, add inputdir. else leave path alone.
281 if (path == "") { nameFileNames[i] = inputDir + nameFileNames[i]; }
287 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
289 //if you can't open it, try default location
290 if (ableToOpen == 1) {
291 if (m->getDefaultPath() != "") { //default path is set
292 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
293 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
295 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
297 nameFileNames[i] = tryPath;
301 if (ableToOpen == 1) {
302 if (m->getOutputDir() != "") { //default path is set
303 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
304 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
306 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
308 nameFileNames[i] = tryPath;
314 if (ableToOpen == 1) {
315 m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
316 //erase from file list
317 nameFileNames.erase(nameFileNames.begin()+i);
320 m->setNameFile(nameFileNames[i]);
326 if (nameFileNames.size() != 0) { hasName = true; }
328 //check for required parameters
329 vector<string> countfileNames;
330 countfile = validParameter.validFile(parameters, "count", false);
331 if (countfile == "not found") {
334 m->splitAtDash(countfile, countfileNames);
336 //go through files and make sure they are good, if not, then disregard them
337 for (int i = 0; i < countfileNames.size(); i++) {
340 if (countfileNames[i] == "current") {
341 countfileNames[i] = m->getCountTableFile();
342 if (nameFileNames[i] != "") { m->mothurOut("Using " + countfileNames[i] + " as input file for the count parameter where you had given current."); m->mothurOutEndLine(); }
344 m->mothurOut("You have no current count file, ignoring current."); m->mothurOutEndLine(); ignore=true;
345 //erase from file list
346 countfileNames.erase(countfileNames.begin()+i);
353 if (inputDir != "") {
354 string path = m->hasPath(countfileNames[i]);
355 //if the user has not given a path then, add inputdir. else leave path alone.
356 if (path == "") { countfileNames[i] = inputDir + countfileNames[i]; }
362 ableToOpen = m->openInputFile(countfileNames[i], in, "noerror");
364 //if you can't open it, try default location
365 if (ableToOpen == 1) {
366 if (m->getDefaultPath() != "") { //default path is set
367 string tryPath = m->getDefaultPath() + m->getSimpleName(countfileNames[i]);
368 m->mothurOut("Unable to open " + countfileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
370 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
372 countfileNames[i] = tryPath;
376 if (ableToOpen == 1) {
377 if (m->getOutputDir() != "") { //default path is set
378 string tryPath = m->getOutputDir() + m->getSimpleName(countfileNames[i]);
379 m->mothurOut("Unable to open " + countfileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
381 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
383 countfileNames[i] = tryPath;
389 if (ableToOpen == 1) {
390 m->mothurOut("Unable to open " + countfileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
391 //erase from file list
392 countfileNames.erase(countfileNames.begin()+i);
395 m->setCountTableFile(countfileNames[i]);
401 if (countfileNames.size() != 0) { hasCount = true; }
403 //make sure there is at least one valid file left
404 if (hasName && hasCount) { m->mothurOut("[ERROR]: You must enter ONLY ONE of the following: count or name."); m->mothurOutEndLine(); abort = true; }
406 if (!hasName && hasCount) { nameFileNames = countfileNames; }
408 if ((hasCount || hasName) && (nameFileNames.size() != fastaFileNames.size())) { m->mothurOut("[ERROR]: The number of name or count files does not match the number of fastafiles, please correct."); m->mothurOutEndLine(); abort=true; }
410 bool hasGroup = true;
411 groupfile = validParameter.validFile(parameters, "group", false);
412 if (groupfile == "not found") { groupfile = ""; hasGroup = false; }
414 m->splitAtDash(groupfile, groupFileNames);
416 //go through files and make sure they are good, if not, then disregard them
417 for (int i = 0; i < groupFileNames.size(); i++) {
420 if (groupFileNames[i] == "current") {
421 groupFileNames[i] = m->getGroupFile();
422 if (groupFileNames[i] != "") { m->mothurOut("Using " + groupFileNames[i] + " as input file for the group parameter where you had given current."); m->mothurOutEndLine(); }
424 m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true;
425 //erase from file list
426 groupFileNames.erase(groupFileNames.begin()+i);
433 if (inputDir != "") {
434 string path = m->hasPath(groupFileNames[i]);
435 //if the user has not given a path then, add inputdir. else leave path alone.
436 if (path == "") { groupFileNames[i] = inputDir + groupFileNames[i]; }
442 ableToOpen = m->openInputFile(groupFileNames[i], in, "noerror");
444 //if you can't open it, try default location
445 if (ableToOpen == 1) {
446 if (m->getDefaultPath() != "") { //default path is set
447 string tryPath = m->getDefaultPath() + m->getSimpleName(groupFileNames[i]);
448 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
450 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
452 groupFileNames[i] = tryPath;
456 if (ableToOpen == 1) {
457 if (m->getOutputDir() != "") { //default path is set
458 string tryPath = m->getOutputDir() + m->getSimpleName(groupFileNames[i]);
459 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
461 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
463 groupFileNames[i] = tryPath;
469 if (ableToOpen == 1) {
470 m->mothurOut("Unable to open " + groupFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
471 //erase from file list
472 groupFileNames.erase(groupFileNames.begin()+i);
475 m->setGroupFile(groupFileNames[i]);
480 //make sure there is at least one valid file left
481 if (groupFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid group files."); m->mothurOutEndLine(); abort = true; }
484 if (hasGroup && (groupFileNames.size() != fastaFileNames.size())) { m->mothurOut("[ERROR]: The number of groupfiles does not match the number of fastafiles, please correct."); m->mothurOutEndLine(); abort=true; }
486 if (hasGroup && hasCount) { m->mothurOut("[ERROR]: You must enter ONLY ONE of the following: count or group."); m->mothurOutEndLine(); abort = true; }
487 //if the user changes the output directory command factory will send this info to us in the output parameter
488 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
490 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
491 m->setProcessors(temp);
492 m->mothurConvert(temp, processors);
494 temp = validParameter.validFile(parameters, "save", false); if (temp == "not found"){ temp = "f"; }
495 save = m->isTrue(temp);
497 if (save) { //clear out old references
502 it = parameters.find("reference");
503 //user has given a template file
504 if(it != parameters.end()){
505 if (it->second == "self") {
506 templatefile = "self";
508 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save.");
509 m->mothurOutEndLine();
514 path = m->hasPath(it->second);
515 //if the user has not given a path then, add inputdir. else leave path alone.
516 if (path == "") { parameters["reference"] = inputDir + it->second; }
518 templatefile = validParameter.validFile(parameters, "reference", true);
519 if (templatefile == "not open") { abort = true; }
520 else if (templatefile == "not found") { //check for saved reference sequences
521 if (rdb->referenceSeqs.size() != 0) {
522 templatefile = "saved";
524 m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required.");
525 m->mothurOutEndLine();
528 }else { if (save) { rdb->setSavedReference(templatefile); } }
530 }else if (hasName) { templatefile = "self";
532 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save.");
533 m->mothurOutEndLine();
536 }else if (hasCount) { templatefile = "self";
538 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save.");
539 m->mothurOutEndLine();
544 if (rdb->referenceSeqs.size() != 0) {
545 templatefile = "saved";
547 m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required.");
548 m->mothurOutEndLine();
549 templatefile = ""; abort = true;
555 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found") { temp = "7"; }
556 m->mothurConvert(temp, ksize);
558 temp = validParameter.validFile(parameters, "window", false); if (temp == "not found") { temp = "50"; }
559 m->mothurConvert(temp, window);
561 temp = validParameter.validFile(parameters, "match", false); if (temp == "not found") { temp = "5"; }
562 m->mothurConvert(temp, match);
564 temp = validParameter.validFile(parameters, "mismatch", false); if (temp == "not found") { temp = "-4"; }
565 m->mothurConvert(temp, mismatch);
567 temp = validParameter.validFile(parameters, "divergence", false); if (temp == "not found") { temp = "1.007"; }
568 m->mothurConvert(temp, divR);
570 temp = validParameter.validFile(parameters, "minsim", false); if (temp == "not found") { temp = "90"; }
571 m->mothurConvert(temp, minSimilarity);
573 temp = validParameter.validFile(parameters, "mincov", false); if (temp == "not found") { temp = "70"; }
574 m->mothurConvert(temp, minCoverage);
576 temp = validParameter.validFile(parameters, "minbs", false); if (temp == "not found") { temp = "90"; }
577 m->mothurConvert(temp, minBS);
579 temp = validParameter.validFile(parameters, "minsnp", false); if (temp == "not found") { temp = "10"; }
580 m->mothurConvert(temp, minSNP);
582 temp = validParameter.validFile(parameters, "parents", false); if (temp == "not found") { temp = "3"; }
583 m->mothurConvert(temp, parents);
585 temp = validParameter.validFile(parameters, "realign", false); if (temp == "not found") { temp = "t"; }
586 realign = m->isTrue(temp);
588 temp = validParameter.validFile(parameters, "trim", false); if (temp == "not found") { temp = "f"; }
589 trim = m->isTrue(temp);
591 temp = validParameter.validFile(parameters, "split", false); if (temp == "not found") { temp = "f"; }
592 trimera = m->isTrue(temp);
594 search = validParameter.validFile(parameters, "search", false); if (search == "not found") { search = "blast"; }
596 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "1000"; }
597 m->mothurConvert(temp, iters);
599 temp = validParameter.validFile(parameters, "increment", false); if (temp == "not found") { temp = "5"; }
600 m->mothurConvert(temp, increment);
602 temp = validParameter.validFile(parameters, "numwanted", false); if (temp == "not found") { temp = "15"; }
603 m->mothurConvert(temp, numwanted);
605 temp = validParameter.validFile(parameters, "dereplicate", false);
606 if (temp == "not found") {
607 if (groupfile != "") { temp = "false"; }
608 else { temp = "true"; }
610 dups = m->isTrue(temp);
612 blastlocation = validParameter.validFile(parameters, "blastlocation", false);
613 if (blastlocation == "not found") { blastlocation = ""; }
615 //add / to name if needed
616 string lastChar = blastlocation.substr(blastlocation.length()-1);
617 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
618 if (lastChar != "/") { blastlocation += "/"; }
620 if (lastChar != "\\") { blastlocation += "\\"; }
622 blastlocation = m->getFullPathName(blastlocation);
623 string formatdbCommand = "";
624 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
625 formatdbCommand = blastlocation + "formatdb";
627 formatdbCommand = blastlocation + "formatdb.exe";
630 //test to make sure formatdb exists
632 formatdbCommand = m->getFullPathName(formatdbCommand);
633 int ableToOpen = m->openInputFile(formatdbCommand, in, "no error"); in.close();
634 if(ableToOpen == 1) { m->mothurOut("[ERROR]: " + formatdbCommand + " file does not exist. mothur requires formatdb.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
636 string blastCommand = "";
637 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
638 blastCommand = blastlocation + "megablast";
640 blastCommand = blastlocation + "megablast.exe";
642 //test to make sure formatdb exists
644 blastCommand = m->getFullPathName(blastCommand);
645 ableToOpen = m->openInputFile(blastCommand, in2, "no error"); in2.close();
646 if(ableToOpen == 1) { m->mothurOut("[ERROR]: " + blastCommand + " file does not exist. mothur requires blastall.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
649 if ((search != "blast") && (search != "kmer")) { m->mothurOut(search + " is not a valid search."); m->mothurOutEndLine(); abort = true; }
651 if ((hasName || hasCount) && (templatefile != "self")) { m->mothurOut("You have provided a namefile or countfile and the reference parameter is not set to self. I am not sure what reference you are trying to use, aborting."); m->mothurOutEndLine(); abort=true; }
652 if (hasGroup && (templatefile != "self")) { m->mothurOut("You have provided a group file and the reference parameter is not set to self. I am not sure what reference you are trying to use, aborting."); m->mothurOutEndLine(); abort=true; }
654 //until we resolve the issue 10-18-11
655 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
661 catch(exception& e) {
662 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
666 //***************************************************************************************************************
668 int ChimeraSlayerCommand::execute(){
670 if (abort == true) { if (calledHelp) { return 0; } return 2; }
672 for (int s = 0; s < fastaFileNames.size(); s++) {
674 m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
676 int start = time(NULL);
677 if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]); }//if user entered a file with a path then preserve it
678 map<string, string> variables;
679 variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]));
680 string outputFileName = getOutputFileName("chimera", variables);
681 string accnosFileName = getOutputFileName("accnos", variables);
682 string trimFastaFileName = getOutputFileName("fasta", variables);
683 string newCountFile = "";
686 ofstream out, out1, out2;
687 m->openOutputFile(outputFileName, out); out.close();
688 m->openOutputFile(accnosFileName, out1); out1.close();
689 if (trim) { m->openOutputFile(trimFastaFileName, out2); out2.close(); }
690 outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
691 outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
692 if (trim) { outputNames.push_back(trimFastaFileName); outputTypes["fasta"].push_back(trimFastaFileName); }
694 //maps a filename to priority map.
695 //if no groupfile this is fastafileNames[s] -> prioirity
696 //if groupfile then this is each groups seqs -> priority
697 map<string, map<string, int> > fileToPriority;
698 map<string, map<string, int> >::iterator itFile;
699 map<string, string> fileGroup;
700 fileToPriority[fastaFileNames[s]] = priority; //default
701 fileGroup[fastaFileNames[s]] = "noGroup";
702 map<string, string> uniqueNames;
703 int totalChimeras = 0;
706 if (templatefile == "self") {
708 SequenceCountParser* parser = NULL;
709 setUpForSelfReference(parser, fileGroup, fileToPriority, s);
710 if (parser != NULL) { uniqueNames = parser->getAllSeqsMap(); delete parser; }
712 SequenceParser* parser = NULL;
713 setUpForSelfReference(parser, fileGroup, fileToPriority, s);
714 if (parser != NULL) { uniqueNames = parser->getAllSeqsMap(); delete parser; }
718 if (m->control_pressed) { for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]); } return 0; }
720 if (fileToPriority.size() == 1) { //you running without a groupfile
721 itFile = fileToPriority.begin();
722 string thisFastaName = itFile->first;
723 map<string, int> thisPriority = itFile->second;
725 MPIExecute(thisFastaName, outputFileName, accnosFileName, trimFastaFileName, thisPriority);
728 vector<unsigned long long> positions;
729 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
730 positions = m->divideFile(thisFastaName, processors);
731 for (int i = 0; i < (positions.size()-1); i++) { lines.push_back(linePair(positions[i], positions[(i+1)])); }
733 if (processors == 1) { lines.push_back(linePair(0, 1000)); }
735 positions = m->setFilePosFasta(thisFastaName, numSeqs);
736 if (positions.size() < processors) { processors = positions.size(); }
738 //figure out how many sequences you have to process
739 int numSeqsPerProcessor = numSeqs / processors;
740 for (int i = 0; i < processors; i++) {
741 int startIndex = i * numSeqsPerProcessor;
742 if(i == (processors - 1)){ numSeqsPerProcessor = numSeqs - i * numSeqsPerProcessor; }
743 lines.push_back(linePair(positions[startIndex], numSeqsPerProcessor));
747 if(processors == 1){ numSeqs = driver(lines[0], outputFileName, thisFastaName, accnosFileName, trimFastaFileName, thisPriority); }
748 else{ numSeqs = createProcesses(outputFileName, thisFastaName, accnosFileName, trimFastaFileName, thisPriority); }
750 if (m->control_pressed) { outputTypes.clear(); if (trim) { m->mothurRemove(trimFastaFileName); } m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]); } return 0; }
752 }else { //you have provided a groupfile
753 string countFile = "";
755 countFile = nameFileNames[s];
756 variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(nameFileNames[s]));
757 newCountFile = getOutputFileName("count", variables);
760 MPIExecuteGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup, newCountFile, countFile);
762 if (processors == 1) {
763 numSeqs = driverGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup, newCountFile);
764 if (hasCount && dups) {
765 CountTable c; c.readTable(nameFileNames[s]);
766 if (!m->isBlank(newCountFile)) {
768 m->openInputFile(newCountFile, in2);
772 in2 >> name >> group; m->gobble(in2);
773 c.setAbund(name, group, 0);
777 m->mothurRemove(newCountFile);
778 c.printTable(newCountFile);
782 else { numSeqs = createProcessesGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup, newCountFile, countFile); } //destroys fileToPriority
787 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
792 totalChimeras = deconvoluteResults(uniqueNames, outputFileName, accnosFileName, trimFastaFileName);
793 m->mothurOutEndLine(); m->mothurOut(toString(totalChimeras) + " chimera found."); m->mothurOutEndLine();
796 set<string> doNotRemove;
797 CountTable c; c.readTable(newCountFile);
798 vector<string> namesInTable = c.getNamesOfSeqs();
799 for (int i = 0; i < namesInTable.size(); i++) {
800 int temp = c.getNumSeqs(namesInTable[i]);
801 if (temp == 0) { c.remove(namesInTable[i]); }
802 else { doNotRemove.insert((namesInTable[i])); }
804 //remove names we want to keep from accnos file.
805 set<string> accnosNames = m->readAccnos(accnosFileName);
807 m->openOutputFile(accnosFileName, out2);
808 for (set<string>::iterator it = accnosNames.begin(); it != accnosNames.end(); it++) {
809 if (doNotRemove.count(*it) == 0) { out2 << (*it) << endl; }
812 c.printTable(newCountFile);
813 outputNames.push_back(newCountFile); outputTypes["count"].push_back(newCountFile);
819 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
823 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
826 //set accnos file as new current accnosfile
828 itTypes = outputTypes.find("accnos");
829 if (itTypes != outputTypes.end()) {
830 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
834 itTypes = outputTypes.find("fasta");
835 if (itTypes != outputTypes.end()) {
836 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
840 itTypes = outputTypes.find("count");
841 if (itTypes != outputTypes.end()) {
842 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setCountTableFile(current); }
845 m->mothurOutEndLine();
846 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
847 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
848 m->mothurOutEndLine();
853 catch(exception& e) {
854 m->errorOut(e, "ChimeraSlayerCommand", "execute");
858 //**********************************************************************************************************************
859 int ChimeraSlayerCommand::MPIExecuteGroups(string outputFileName, string accnosFileName, string trimFastaFileName, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup, string countlist, string countfile){
866 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
867 MPI_Comm_size(MPI_COMM_WORLD, &processors);
869 //put filenames in a vector, then pass each process a starting and ending point in the vector
870 //all processes already have the fileToPriority and fileGroup, they just need to know which files to process
871 map<string, map<string, int> >::iterator itFile;
872 vector<string> filenames;
873 for(itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) { filenames.push_back(itFile->first); }
875 int numGroupsPerProcessor = filenames.size() / processors;
876 int startIndex = pid * numGroupsPerProcessor;
877 int endIndex = (pid+1) * numGroupsPerProcessor;
878 if(pid == (processors - 1)){ endIndex = filenames.size(); }
880 vector<unsigned long long> MPIPos;
883 MPI_File outMPIAccnos;
884 MPI_File outMPIFasta;
885 MPI_File outMPICount;
887 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
888 int inMode=MPI_MODE_RDONLY;
890 char outFilename[1024];
891 strcpy(outFilename, outputFileName.c_str());
893 char outAccnosFilename[1024];
894 strcpy(outAccnosFilename, accnosFileName.c_str());
896 char outFastaFilename[1024];
897 strcpy(outFastaFilename, trimFastaFileName.c_str());
899 char outCountFilename[1024];
900 strcpy(outCountFilename, countlist.c_str());
902 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
903 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
904 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
905 if (hasCount && dups) { MPI_File_open(MPI_COMM_WORLD, outCountFilename, outMode, MPI_INFO_NULL, &outMPICount); }
907 if (m->control_pressed) { MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); if (hasCount && dups) { MPI_File_close(&outMPICount); } return 0; }
910 if (pid == 0) { //you are the root process
911 m->mothurOutEndLine();
912 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
913 m->mothurOutEndLine();
915 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
918 int length = outTemp.length();
919 char* buf2 = new char[length];
920 memcpy(buf2, outTemp.c_str(), length);
922 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
925 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
927 for (int i = startIndex; i < endIndex; i++) {
929 int start = time(NULL);
931 string thisFastaName = filenames[i];
932 map<string, int> thisPriority = fileToPriority[thisFastaName];
934 char inFileName[1024];
935 strcpy(inFileName, thisFastaName.c_str());
937 MPI_File_open(MPI_COMM_SELF, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
939 MPIPos = m->setFilePosFasta(thisFastaName, num); //fills MPIPos, returns numSeqs
941 cout << endl << "Checking sequences from group: " << fileGroup[thisFastaName] << "." << endl;
944 driverMPI(0, num, inMPI, outMPI, outMPIAccnos, outMPIFasta, cnames, MPIPos, thisFastaName, thisPriority, true);
947 MPI_File_close(&inMPI);
948 m->mothurRemove(thisFastaName);
951 if (cnames.size() != 0) {
953 for (set<string>::iterator it = cnames.begin(); it != cnames.end(); it++) {
954 string outputString = (*it) + "\t" + fileGroup[thisFastaName] + "\n";
955 int length = outputString.length();
956 char* buf2 = new char[length];
957 memcpy(buf2, outputString.c_str(), length);
958 MPI_File_write_shared(outMPICount, buf2, length, MPI_CHAR, &status);
962 map<string, map<string, string> >::iterator itGroupNameMap = group2NameMap.find(fileGroup[thisFastaName]);
963 if (itGroupNameMap != group2NameMap.end()) {
964 map<string, string> thisnamemap = itGroupNameMap->second;
965 map<string, string>::iterator itN;
966 for (set<string>::iterator it = cnames.begin(); it != cnames.end(); it++) {
967 itN = thisnamemap.find(*it);
968 if (itN != thisnamemap.end()) {
969 vector<string> tempNames; m->splitAtComma(itN->second, tempNames);
970 for (int j = 0; j < tempNames.size(); j++) { //write to accnos file
971 string outputString = tempNames[j] + "\n";
972 int length = outputString.length();
973 char* buf2 = new char[length];
974 memcpy(buf2, outputString.c_str(), length);
976 MPI_File_write_shared(outMPIAccnos, buf2, length, MPI_CHAR, &status);
980 }else { m->mothurOut("[ERROR]: parsing cannot find " + *it + ".\n"); m->control_pressed = true; }
982 }else { m->mothurOut("[ERROR]: parsing cannot find " + fileGroup[thisFastaName] + ".\n"); m->control_pressed = true; }
988 cout << endl << "It took " << toString(time(NULL) - start) << " secs to check " + toString(num) + " sequences from group " << fileGroup[thisFastaName] << "." << endl;
992 for(int i = 1; i < processors; i++) {
994 MPI_Recv(&temp, 1, MPI_INT, i, 2001, MPI_COMM_WORLD, &status);
997 }else{ MPI_Send(&numSeqs, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD); }
999 MPI_File_close(&outMPI);
1000 MPI_File_close(&outMPIAccnos);
1001 if (trim) { MPI_File_close(&outMPIFasta); }
1002 if (hasCount && dups) { MPI_File_close(&outMPICount); }
1004 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
1008 }catch(exception& e) {
1009 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecuteGroups");
1013 //**********************************************************************************************************************
1014 int ChimeraSlayerCommand::MPIExecute(string inputFile, string outputFileName, string accnosFileName, string trimFastaFileName, map<string, int>& priority){
1018 int pid, numSeqsPerProcessor;
1020 vector<unsigned long long> MPIPos;
1023 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1024 MPI_Comm_size(MPI_COMM_WORLD, &processors);
1028 MPI_File outMPIAccnos;
1029 MPI_File outMPIFasta;
1031 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
1032 int inMode=MPI_MODE_RDONLY;
1034 char outFilename[1024];
1035 strcpy(outFilename, outputFileName.c_str());
1037 char outAccnosFilename[1024];
1038 strcpy(outAccnosFilename, accnosFileName.c_str());
1040 char outFastaFilename[1024];
1041 strcpy(outFastaFilename, trimFastaFileName.c_str());
1043 char inFileName[1024];
1044 strcpy(inFileName, inputFile.c_str());
1046 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
1047 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
1048 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
1049 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
1051 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
1053 if (pid == 0) { //you are the root process
1054 m->mothurOutEndLine();
1055 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
1056 m->mothurOutEndLine();
1058 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
1061 int length = outTemp.length();
1062 char* buf2 = new char[length];
1063 memcpy(buf2, outTemp.c_str(), length);
1065 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
1068 MPIPos = m->setFilePosFasta(inputFile, numSeqs); //fills MPIPos, returns numSeqs
1070 if (templatefile != "self") { //if template=self we can only use 1 processor
1071 //send file positions to all processes
1072 for(int i = 1; i < processors; i++) {
1073 MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
1074 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
1077 //figure out how many sequences you have to align
1078 numSeqsPerProcessor = numSeqs / processors;
1079 int startIndex = pid * numSeqsPerProcessor;
1080 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
1082 if (templatefile == "self") { //if template=self we can only use 1 processor
1084 numSeqsPerProcessor = numSeqs;
1089 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, cnames, MPIPos, inputFile, priority, false);
1091 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
1093 }else{ //you are a child process
1094 if (templatefile != "self") { //if template=self we can only use 1 processor
1095 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
1096 MPIPos.resize(numSeqs+1);
1097 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
1099 //figure out how many sequences you have to align
1100 numSeqsPerProcessor = numSeqs / processors;
1101 int startIndex = pid * numSeqsPerProcessor;
1102 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
1106 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, cnames, MPIPos, inputFile, priority, false);
1108 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
1114 MPI_File_close(&inMPI);
1115 MPI_File_close(&outMPI);
1116 MPI_File_close(&outMPIAccnos);
1117 if (trim) { MPI_File_close(&outMPIFasta); }
1118 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
1124 catch(exception& e) {
1125 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecute");
1129 //**********************************************************************************************************************
1130 int ChimeraSlayerCommand::deconvoluteResults(map<string, string>& uniqueNames, string outputFileName, string accnosFileName, string trimFileName){
1132 map<string, string>::iterator itUnique;
1135 if (trimera) { //add in more potential uniqueNames
1136 map<string, string> newUniqueNames = uniqueNames;
1137 for (map<string, string>::iterator it = uniqueNames.begin(); it != uniqueNames.end(); it++) {
1138 newUniqueNames[(it->first)+"_LEFT"] = (it->first)+"_LEFT";
1139 newUniqueNames[(it->first)+"_RIGHT"] = (it->first)+"_RIGHT";
1141 uniqueNames = newUniqueNames;
1142 newUniqueNames.clear();
1147 m->openInputFile(accnosFileName, in2, "no error");
1150 m->openOutputFile(accnosFileName+".temp", out2);
1152 string name; name = "";
1153 set<string> chimerasInFile;
1154 set<string>::iterator itChimeras;
1156 while (!in2.eof()) {
1157 if (m->control_pressed) { in2.close(); out2.close(); m->mothurRemove(outputFileName); m->mothurRemove((accnosFileName+".temp")); return 0; }
1159 in2 >> name; m->gobble(in2);
1162 itUnique = uniqueNames.find(name);
1164 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1166 itChimeras = chimerasInFile.find((itUnique->second));
1168 if (itChimeras == chimerasInFile.end()) {
1169 out2 << itUnique->second << endl;
1170 chimerasInFile.insert((itUnique->second));
1178 m->mothurRemove(accnosFileName);
1179 rename((accnosFileName+".temp").c_str(), accnosFileName.c_str());
1184 m->openInputFile(outputFileName, in);
1187 m->openOutputFile(outputFileName+".temp", out); out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
1189 string rest, parent1, parent2, line;
1190 set<string> namesInFile; //this is so if a sequence is found to be chimera in several samples we dont write it to the results file more than once
1191 set<string>::iterator itNames;
1193 //assumptions - in file each read will always look like...
1196 F11Fcsw_63104 F11Fcsw_33372 F11Fcsw_37007 0.89441 80.4469 0.2 1.03727 93.2961 52.2 no 0-241 243-369
1201 line = m->getline(in); m->gobble(in);
1202 out << line << endl;
1205 //for the chimera file, we want to make sure if any group finds a sequence to be chimeric then all groups do,
1206 //so if this is a report that did not find it to be chimeric, but it appears in the accnos file,
1207 //then ignore this report and continue until we find the report that found it to be chimeric
1211 if (m->control_pressed) { in.close(); out.close(); m->mothurRemove((outputFileName+".temp")); return 0; }
1213 in >> name; m->gobble(in);
1214 in >> parent1; m->gobble(in);
1216 if (name == "Name") { //name = "Name" because we append the header line each time we add results from the groups
1217 line = m->getline(in); m->gobble(in);
1219 if (parent1 == "no") {
1221 itUnique = uniqueNames.find(name);
1223 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1225 //is this sequence really not chimeric??
1226 itChimeras = chimerasInFile.find(itUnique->second);
1228 if (itChimeras == chimerasInFile.end()) {
1229 //is this sequence not already in the file
1230 itNames = namesInFile.find((itUnique->second));
1232 if (itNames == namesInFile.end()) { out << itUnique->second << '\t' << "no" << endl; namesInFile.insert(itUnique->second); }
1235 }else { //read the rest of the line
1236 double DivQLAQRB,PerIDQLAQRB,BootStrapA,DivQLBQRA,PerIDQLBQRA,BootStrapB;
1237 string flag, range1, range2;
1239 in >> parent2 >> DivQLAQRB >> PerIDQLAQRB >> BootStrapA >> DivQLBQRA >> PerIDQLBQRA >> BootStrapB >> flag >> range1 >> range2; m->gobble(in);
1242 itUnique = uniqueNames.find(name);
1244 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1246 name = itUnique->second;
1247 //is this name already in the file
1248 itNames = namesInFile.find((name));
1250 if (itNames == namesInFile.end()) { //no not in file
1251 if (flag == "no") { //are you really a no??
1252 //is this sequence really not chimeric??
1253 itChimeras = chimerasInFile.find(name);
1255 //then you really are a no so print, otherwise skip
1256 if (itChimeras == chimerasInFile.end()) { print = true; }
1258 }else{ print = true; }
1263 out << name << '\t';
1265 namesInFile.insert(name);
1267 //output parent1's name
1268 itUnique = uniqueNames.find(parent1);
1269 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent1 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1270 else { out << itUnique->second << '\t'; }
1272 //output parent2's name
1273 itUnique = uniqueNames.find(parent2);
1274 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent2 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1275 else { out << itUnique->second << '\t'; }
1277 out << DivQLAQRB << '\t' << PerIDQLAQRB << '\t' << BootStrapA << '\t' << DivQLBQRA << '\t' << PerIDQLBQRA << '\t' << BootStrapB << '\t' << flag << '\t' << range1 << '\t' << range2 << endl;
1285 m->mothurRemove(outputFileName);
1286 rename((outputFileName+".temp").c_str(), outputFileName.c_str());
1291 m->openInputFile(trimFileName, in3);
1294 m->openOutputFile(trimFileName+".temp", out3);
1296 namesInFile.clear();
1298 while (!in3.eof()) {
1299 if (m->control_pressed) { in3.close(); out3.close(); m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); m->mothurRemove((trimFileName+".temp")); return 0; }
1301 Sequence seq(in3); m->gobble(in3);
1303 if (seq.getName() != "") {
1305 itUnique = uniqueNames.find(seq.getName());
1307 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ seq.getName() + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1309 itNames = namesInFile.find((itUnique->second));
1311 if (itNames == namesInFile.end()) {
1312 seq.printSequence(out3);
1320 m->mothurRemove(trimFileName);
1321 rename((trimFileName+".temp").c_str(), trimFileName.c_str());
1326 catch(exception& e) {
1327 m->errorOut(e, "ChimeraSlayerCommand", "deconvoluteResults");
1331 //**********************************************************************************************************************
1332 int ChimeraSlayerCommand::setUpForSelfReference(SequenceParser*& parser, map<string, string>& fileGroup, map<string, map<string, int> >& fileToPriority, int s){
1335 fileToPriority.clear();
1337 string nameFile = "";
1338 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
1339 nameFile = nameFileNames[s];
1340 }else { nameFile = getNamesFile(fastaFileNames[s]); }
1342 //you provided a groupfile
1343 string groupFile = "";
1344 if (groupFileNames.size() != 0) { groupFile = groupFileNames[s]; }
1346 if (groupFile == "") {
1347 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
1349 //sort fastafile by abundance, returns new sorted fastafile name
1350 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush();
1351 priority = sortFastaFile(fastaFileNames[s], nameFile);
1352 m->mothurOut("Done."); m->mothurOutEndLine();
1354 fileToPriority[fastaFileNames[s]] = priority;
1355 fileGroup[fastaFileNames[s]] = "noGroup";
1357 //Parse sequences by group
1358 parser = new SequenceParser(groupFile, fastaFileNames[s], nameFile);
1359 vector<string> groups = parser->getNamesOfGroups();
1361 for (int i = 0; i < groups.size(); i++) {
1362 vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
1363 map<string, string> thisGroupsMap = parser->getNameMap(groups[i]);
1364 group2NameMap[groups[i]] = thisGroupsMap;
1365 string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
1366 priority = sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile);
1367 fileToPriority[newFastaFile] = priority;
1368 fileGroup[newFastaFile] = groups[i];
1375 catch(exception& e) {
1376 m->errorOut(e, "ChimeraSlayerCommand", "setUpForSelfReference");
1380 //**********************************************************************************************************************
1381 int ChimeraSlayerCommand::setUpForSelfReference(SequenceCountParser*& parser, map<string, string>& fileGroup, map<string, map<string, int> >& fileToPriority, int s){
1384 fileToPriority.clear();
1386 string nameFile = "";
1387 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
1388 nameFile = nameFileNames[s];
1389 }else { m->control_pressed = true; return 0; }
1392 if (!ct.testGroups(nameFile)) {
1393 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
1395 //sort fastafile by abundance, returns new sorted fastafile name
1396 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush();
1397 priority = sortFastaFile(fastaFileNames[s], nameFile);
1398 m->mothurOut("Done."); m->mothurOutEndLine();
1400 fileToPriority[fastaFileNames[s]] = priority;
1401 fileGroup[fastaFileNames[s]] = "noGroup";
1403 //Parse sequences by group
1404 parser = new SequenceCountParser(nameFile, fastaFileNames[s]);
1405 vector<string> groups = parser->getNamesOfGroups();
1407 for (int i = 0; i < groups.size(); i++) {
1408 vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
1409 map<string, int> thisGroupsMap = parser->getCountTable(groups[i]);
1410 string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
1411 sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile);
1412 fileToPriority[newFastaFile] = thisGroupsMap;
1413 fileGroup[newFastaFile] = groups[i];
1420 catch(exception& e) {
1421 m->errorOut(e, "ChimeraSlayerCommand", "setUpForSelfReference");
1425 //**********************************************************************************************************************
1426 string ChimeraSlayerCommand::getNamesFile(string& inputFile){
1428 string nameFile = "";
1430 m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
1432 //use unique.seqs to create new name and fastafile
1433 string inputString = "fasta=" + inputFile;
1434 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
1435 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine();
1436 m->mothurCalling = true;
1438 Command* uniqueCommand = new DeconvoluteCommand(inputString);
1439 uniqueCommand->execute();
1441 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
1443 delete uniqueCommand;
1444 m->mothurCalling = false;
1445 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
1447 nameFile = filenames["name"][0];
1448 inputFile = filenames["fasta"][0];
1452 catch(exception& e) {
1453 m->errorOut(e, "ChimeraSlayerCommand", "getNamesFile");
1457 //**********************************************************************************************************************
1459 int ChimeraSlayerCommand::driverGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup, string countlist){
1462 ofstream outCountList;
1464 if (hasCount && dups) { m->openOutputFile(countlist, outCountList); }
1466 for (map<string, map<string, int> >::iterator itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) {
1468 if (m->control_pressed) { return 0; }
1470 int start = time(NULL);
1471 string thisFastaName = itFile->first;
1472 map<string, int> thisPriority = itFile->second;
1473 string thisoutputFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.chimera";
1474 string thisaccnosFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.accnos";
1475 string thistrimFastaFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.fasta";
1477 m->mothurOutEndLine(); m->mothurOut("Checking sequences from group: " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine();
1480 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1482 vector<unsigned long long> positions = m->divideFile(thisFastaName, proc);
1483 lines.push_back(linePair(positions[0], positions[1]));
1485 lines.push_back(linePair(0, 1000));
1487 int numSeqs = driver(lines[0], thisoutputFileName, thisFastaName, thisaccnosFileName, thistrimFastaFileName, thisPriority);
1489 //if we provided a count file with group info and set dereplicate=t, then we want to create a *.pick.count_table
1490 //This table will zero out group counts for seqs determined to be chimeric by that group.
1492 if (!m->isBlank(thisaccnosFileName)) {
1494 m->openInputFile(thisaccnosFileName, in);
1498 in >> name; m->gobble(in);
1499 outCountList << name << '\t' << fileGroup[thisFastaName] << endl;
1503 map<string, map<string, string> >::iterator itGroupNameMap = group2NameMap.find(fileGroup[thisFastaName]);
1504 if (itGroupNameMap != group2NameMap.end()) {
1505 map<string, string> thisnamemap = itGroupNameMap->second;
1506 map<string, string>::iterator itN;
1508 m->openOutputFile(thisaccnosFileName+".temp", out);
1510 in >> name; m->gobble(in);
1511 itN = thisnamemap.find(name);
1512 if (itN != thisnamemap.end()) {
1513 vector<string> tempNames; m->splitAtComma(itN->second, tempNames);
1514 for (int j = 0; j < tempNames.size(); j++) { out << tempNames[j] << endl; }
1516 }else { m->mothurOut("[ERROR]: parsing cannot find " + name + ".\n"); m->control_pressed = true; }
1520 m->renameFile(thisaccnosFileName+".temp", thisaccnosFileName);
1521 }else { m->mothurOut("[ERROR]: parsing cannot find " + fileGroup[thisFastaName] + ".\n"); m->control_pressed = true; }
1528 m->appendFiles(thisoutputFileName, outputFName); m->mothurRemove(thisoutputFileName);
1529 m->appendFiles(thisaccnosFileName, accnos); m->mothurRemove(thisaccnosFileName);
1530 if (trim) { m->appendFiles(thistrimFastaFileName, fasta); m->mothurRemove(thistrimFastaFileName); }
1531 m->mothurRemove(thisFastaName);
1533 totalSeqs += numSeqs;
1535 m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences from group " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine();
1538 if (hasCount && dups) { outCountList.close(); }
1542 catch(exception& e) {
1543 m->errorOut(e, "ChimeraSlayerCommand", "driverGroups");
1547 /**************************************************************************************************/
1548 int ChimeraSlayerCommand::createProcessesGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup, string countlist, string countFile) {
1554 if (fileToPriority.size() < processors) { processors = fileToPriority.size(); }
1556 CountTable newCount;
1557 if (hasCount && dups) { newCount.readTable(countFile); }
1559 int groupsPerProcessor = fileToPriority.size() / processors;
1560 int remainder = fileToPriority.size() % processors;
1562 vector< map<string, map<string, int> > > breakUp;
1564 for (int i = 0; i < processors; i++) {
1565 map<string, map<string, int> > thisFileToPriority;
1566 map<string, map<string, int> >::iterator itFile;
1568 int enough = groupsPerProcessor;
1569 if (i == 0) { enough = groupsPerProcessor + remainder; }
1571 for (itFile = fileToPriority.begin(); itFile != fileToPriority.end();) {
1572 thisFileToPriority[itFile->first] = itFile->second;
1573 fileToPriority.erase(itFile++);
1575 if (count == enough) { break; }
1577 breakUp.push_back(thisFileToPriority);
1580 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1581 //loop through and create all the processes you want
1582 while (process != processors) {
1586 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
1588 }else if (pid == 0){
1589 num = driverGroups(outputFName + toString(getpid()) + ".temp", accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", breakUp[process], fileGroup, accnos + toString(getpid()) + ".byCount");
1591 //pass numSeqs to parent
1593 string tempFile = outputFName + toString(getpid()) + ".num.temp";
1594 m->openOutputFile(tempFile, out);
1599 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
1600 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1605 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup, accnos + ".byCount");
1607 //force parent to wait until all the processes are done
1608 for (int i=0;i<processors;i++) {
1609 int temp = processIDS[i];
1613 for (int i = 0; i < processIDS.size(); i++) {
1615 string tempFile = outputFName + toString(processIDS[i]) + ".num.temp";
1616 m->openInputFile(tempFile, in);
1617 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
1618 in.close(); m->mothurRemove(tempFile);
1622 //////////////////////////////////////////////////////////////////////////////////////////////////////
1623 //Windows version shared memory, so be careful when passing variables through the slayerData struct.
1624 //Above fork() will clone, so memory is separate, but that's not the case with windows,
1625 //////////////////////////////////////////////////////////////////////////////////////////////////////
1627 vector<slayerData*> pDataArray;
1628 DWORD dwThreadIdArray[processors-1];
1629 HANDLE hThreadArray[processors-1];
1631 //Create processor worker threads.
1632 for(int i=1; i<processors; i++ ){
1633 string extension = toString(i) + ".temp";
1634 slayerData* tempslayer = new slayerData(group2NameMap, hasCount, dups, (accnos + extension+".byCount"), (outputFName + extension), (fasta + extension), (accnos + extension), templatefile, search, blastlocation, trimera, trim, realign, m, breakUp[i], fileGroup, ksize, match, mismatch, window, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, divR, priority, i);
1635 pDataArray.push_back(tempslayer);
1636 processIDS.push_back(i);
1638 //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
1639 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1640 hThreadArray[i-1] = CreateThread(NULL, 0, MySlayerGroupThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);
1643 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup, accnos + ".byCount");
1645 //Wait until all threads have terminated.
1646 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
1648 //Close all thread handles and free memory allocations.
1649 for(int i=0; i < pDataArray.size(); i++){
1650 if (pDataArray[i]->fileToPriority.size() != pDataArray[i]->end) {
1651 m->mothurOut("[ERROR]: process " + toString(i) + " only processed " + toString(pDataArray[i]->end) + " of " + toString(pDataArray[i]->fileToPriority.size()) + " groups assigned to it, quitting. \n"); m->control_pressed = true;
1653 num += pDataArray[i]->count;
1654 CloseHandle(hThreadArray[i]);
1655 delete pDataArray[i];
1659 if (hasCount && dups) {
1660 if (!m->isBlank(accnos + ".byCount")) {
1662 m->openInputFile(accnos + ".byCount", in2);
1665 while (!in2.eof()) {
1666 in2 >> name >> group; m->gobble(in2);
1667 newCount.setAbund(name, group, 0);
1671 m->mothurRemove(accnos + ".byCount");
1675 //append output files
1676 for(int i=0;i<processIDS.size();i++){
1677 m->appendFiles((outputFName + toString(processIDS[i]) + ".temp"), outputFName);
1678 m->mothurRemove((outputFName + toString(processIDS[i]) + ".temp"));
1680 m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1681 m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1684 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
1685 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
1688 if (hasCount && dups) {
1689 if (!m->isBlank(accnos + toString(processIDS[i]) + ".byCount")) {
1691 m->openInputFile(accnos + toString(processIDS[i]) + ".byCount", in2);
1694 while (!in2.eof()) {
1695 in2 >> name >> group; m->gobble(in2);
1696 newCount.setAbund(name, group, 0);
1700 m->mothurRemove(accnos + toString(processIDS[i]) + ".byCount");
1705 //print new *.pick.count_table
1706 if (hasCount && dups) { newCount.printTable(countlist); }
1710 catch(exception& e) {
1711 m->errorOut(e, "ChimeraSlayerCommand", "createProcessesGroups");
1715 //**********************************************************************************************************************
1717 int ChimeraSlayerCommand::driver(linePair filePos, string outputFName, string filename, string accnos, string fasta, map<string, int>& priority){
1721 if (templatefile != "self") { //you want to run slayer with a reference template
1722 chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1724 chimera = new ChimeraSlayer(filename, templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1727 if (m->control_pressed) { delete chimera; return 0; }
1729 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1730 templateSeqsLength = chimera->getLength();
1733 m->openOutputFile(outputFName, out);
1736 m->openOutputFile(accnos, out2);
1739 if (trim) { m->openOutputFile(fasta, out3); }
1742 m->openInputFile(filename, inFASTA);
1744 inFASTA.seekg(filePos.start);
1746 if (filePos.start == 0) { chimera->printHeader(out); }
1753 if (m->control_pressed) { delete chimera; out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1; }
1755 Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
1756 string candidateAligned = candidateSeq->getAligned();
1758 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1759 if (candidateSeq->getAligned().length() != templateSeqsLength) {
1760 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1763 chimera->getChimeras(candidateSeq);
1765 if (m->control_pressed) { delete chimera; delete candidateSeq; return 1; }
1767 //if you are not chimeric, then check each half
1768 data_results wholeResults = chimera->getResults();
1770 //determine if we need to split
1771 bool isChimeric = false;
1773 if (wholeResults.flag == "yes") {
1774 string chimeraFlag = "no";
1775 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1777 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1780 if (chimeraFlag == "yes") {
1781 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1785 if ((!isChimeric) && trimera) {
1787 //split sequence in half by bases
1788 string leftQuery, rightQuery;
1789 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1790 divideInHalf(tempSeq, leftQuery, rightQuery);
1792 //run chimeraSlayer on each piece
1793 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1794 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1797 chimera->getChimeras(left);
1798 data_results leftResults = chimera->getResults();
1800 chimera->getChimeras(right);
1801 data_results rightResults = chimera->getResults();
1803 //if either piece is chimeric then report
1804 Sequence trimmed = chimera->print(out, out2, leftResults, rightResults);
1805 if (trim) { trimmed.printSequence(out3); }
1807 delete left; delete right;
1809 }else { //already chimeric
1811 Sequence trimmed = chimera->print(out, out2);
1812 if (trim) { trimmed.printSequence(out3); }
1820 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1821 unsigned long long pos = inFASTA.tellg();
1822 if ((pos == -1) || (pos >= filePos.end)) { break; }
1824 if (inFASTA.eof()) { break; }
1827 delete candidateSeq;
1829 if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
1832 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
1834 int numNoParents = chimera->getNumNoParents();
1835 if (numNoParents == count) { m->mothurOut("[WARNING]: megablast returned 0 potential parents for all your sequences. This could be due to formatdb.exe not being setup properly, please check formatdb.log for errors."); m->mothurOutEndLine(); }
1839 if (trim) { out3.close(); }
1847 catch(exception& e) {
1848 m->errorOut(e, "ChimeraSlayerCommand", "driver");
1852 //**********************************************************************************************************************
1854 int ChimeraSlayerCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, MPI_File& outAccMPI, MPI_File& outFastaMPI, set<string>& cnames, vector<unsigned long long>& MPIPos, string filename, map<string, int>& priority, bool byGroup){
1858 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1861 if (templatefile != "self") { //you want to run slayer with a reference template
1862 chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1864 chimera = new ChimeraSlayer(filename, templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand(), byGroup);
1867 if (m->control_pressed) { delete chimera; return 0; }
1869 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1870 templateSeqsLength = chimera->getLength();
1872 for(int i=0;i<num;i++){
1874 if (m->control_pressed) { delete chimera; return 1; }
1876 //read next sequence
1877 int length = MPIPos[start+i+1] - MPIPos[start+i];
1879 char* buf4 = new char[length];
1880 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
1882 string tempBuf = buf4;
1883 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
1884 istringstream iss (tempBuf,istringstream::in);
1888 Sequence* candidateSeq = new Sequence(iss); m->gobble(iss);
1889 string candidateAligned = candidateSeq->getAligned();
1891 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1893 if (candidateSeq->getAligned().length() != templateSeqsLength) {
1894 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1898 chimera->getChimeras(candidateSeq);
1900 if (m->control_pressed) { delete chimera; delete candidateSeq; return 1; }
1902 //if you are not chimeric, then check each half
1903 data_results wholeResults = chimera->getResults();
1905 //determine if we need to split
1906 bool isChimeric = false;
1908 if (wholeResults.flag == "yes") {
1909 string chimeraFlag = "no";
1910 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1912 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1915 if (chimeraFlag == "yes") {
1916 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1920 if ((!isChimeric) && trimera) {
1921 //split sequence in half by bases
1922 string leftQuery, rightQuery;
1923 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1924 divideInHalf(tempSeq, leftQuery, rightQuery);
1926 //run chimeraSlayer on each piece
1927 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1928 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1931 chimera->getChimeras(left);
1932 data_results leftResults = chimera->getResults();
1934 chimera->getChimeras(right);
1935 data_results rightResults = chimera->getResults();
1937 //if either piece is chimeric then report
1939 Sequence trimmed = chimera->print(outMPI, outAccMPI, leftResults, rightResults, flag);
1940 if (flag) { cnames.insert(candidateSeq->getName()); }
1943 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1945 //write to accnos file
1946 int length = outputString.length();
1947 char* buf2 = new char[length];
1948 memcpy(buf2, outputString.c_str(), length);
1950 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1954 delete left; delete right;
1958 Sequence trimmed = chimera->print(outMPI, outAccMPI);
1959 cnames.insert(candidateSeq->getName());
1962 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1964 //write to accnos file
1965 int length = outputString.length();
1966 char* buf2 = new char[length];
1967 memcpy(buf2, outputString.c_str(), length);
1969 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1976 delete candidateSeq;
1979 if((i+1) % 100 == 0){ cout << "Processing sequence: " << (i+1) << endl; m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n"); }
1982 if(num % 100 != 0){ cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n"); }
1984 int numNoParents = chimera->getNumNoParents();
1985 if (numNoParents == num) { cout << "[WARNING]: megablast returned 0 potential parents for all your sequences. This could be due to formatdb.exe not being setup properly, please check formatdb.log for errors." << endl; }
1990 catch(exception& e) {
1991 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
1997 /**************************************************************************************************/
1999 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta, map<string, int>& thisPriority) {
2005 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
2006 //loop through and create all the processes you want
2007 while (process != processors) {
2011 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
2013 }else if (pid == 0){
2014 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", thisPriority);
2016 //pass numSeqs to parent
2018 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
2019 m->openOutputFile(tempFile, out);
2024 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
2025 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
2030 //force parent to wait until all the processes are done
2031 for (int i=0;i<processors;i++) {
2032 int temp = processIDS[i];
2036 for (int i = 0; i < processIDS.size(); i++) {
2038 string tempFile = outputFileName + toString(processIDS[i]) + ".num.temp";
2039 m->openInputFile(tempFile, in);
2040 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
2041 in.close(); m->mothurRemove(tempFile);
2045 //////////////////////////////////////////////////////////////////////////////////////////////////////
2046 //Windows version shared memory, so be careful when passing variables through the slayerData struct.
2047 //Above fork() will clone, so memory is separate, but that's not the case with windows,
2048 //////////////////////////////////////////////////////////////////////////////////////////////////////
2050 vector<slayerData*> pDataArray;
2051 DWORD dwThreadIdArray[processors];
2052 HANDLE hThreadArray[processors];
2054 //Create processor worker threads.
2055 for( int i=0; i<processors; i++ ){
2056 string extension = toString(i) + ".temp";
2057 slayerData* tempslayer = new slayerData((outputFileName + extension), (fasta + extension), (accnos + extension), filename, templatefile, search, blastlocation, trimera, trim, realign, m, lines[i].start, lines[i].end, ksize, match, mismatch, window, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, divR, priority, i);
2058 pDataArray.push_back(tempslayer);
2059 processIDS.push_back(i);
2061 //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
2062 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
2063 hThreadArray[i] = CreateThread(NULL, 0, MySlayerThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);
2066 //Wait until all threads have terminated.
2067 WaitForMultipleObjects(processors, hThreadArray, TRUE, INFINITE);
2069 //Close all thread handles and free memory allocations.
2070 for(int i=0; i < pDataArray.size(); i++){
2071 num += pDataArray[i]->count;
2072 CloseHandle(hThreadArray[i]);
2073 delete pDataArray[i];
2077 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
2078 rename((accnos + toString(processIDS[0]) + ".temp").c_str(), accnos.c_str());
2079 if (trim) { rename((fasta + toString(processIDS[0]) + ".temp").c_str(), fasta.c_str()); }
2081 //append output files
2082 for(int i=1;i<processIDS.size();i++){
2083 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
2084 m->mothurRemove((outputFileName + toString(processIDS[i]) + ".temp"));
2086 m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
2087 m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
2090 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
2091 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
2098 catch(exception& e) {
2099 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
2104 /**************************************************************************************************/
2106 int ChimeraSlayerCommand::divideInHalf(Sequence querySeq, string& leftQuery, string& rightQuery) {
2109 string queryUnAligned = querySeq.getUnaligned();
2110 int numBases = int(queryUnAligned.length() * 0.5);
2112 string queryAligned = querySeq.getAligned();
2113 leftQuery = querySeq.getAligned();
2114 rightQuery = querySeq.getAligned();
2118 for (int i = 0; i < queryAligned.length(); i++) {
2120 if (isalpha(queryAligned[i])) {
2125 if (baseCount >= numBases) { leftSpot = i; break; } //first half
2128 //blank out right side
2129 for (int i = leftSpot; i < leftQuery.length(); i++) { leftQuery[i] = '.'; }
2131 //blank out left side
2132 for (int i = 0; i < leftSpot; i++) { rightQuery[i] = '.'; }
2137 catch(exception& e) {
2138 m->errorOut(e, "ChimeraSlayerCommand", "divideInHalf");
2142 /**************************************************************************************************/
2143 map<string, int> ChimeraSlayerCommand::sortFastaFile(string fastaFile, string nameFile) {
2145 map<string, int> nameAbund;
2147 //read through fastafile and store info
2148 map<string, string> seqs;
2150 m->openInputFile(fastaFile, in);
2154 if (m->control_pressed) { in.close(); return nameAbund; }
2156 Sequence seq(in); m->gobble(in);
2157 seqs[seq.getName()] = seq.getAligned();
2162 //read namefile or countfile
2163 vector<seqPriorityNode> nameMapCount;
2167 ct.readTable(nameFile);
2169 for(map<string, string>::iterator it = seqs.begin(); it != seqs.end(); it++) {
2170 int num = ct.getNumSeqs(it->first);
2171 if (num == 0) { error = 1; }
2173 seqPriorityNode temp(num, it->second, it->first);
2174 nameMapCount.push_back(temp);
2177 }else { error = m->readNames(nameFile, nameMapCount, seqs); }
2179 if (m->control_pressed) { return nameAbund; }
2181 if (error == 1) { m->control_pressed = true; return nameAbund; }
2182 if (seqs.size() != nameMapCount.size()) { m->mothurOut( "The number of sequences in your fastafile does not match the number of sequences in your namefile, aborting."); m->mothurOutEndLine(); m->control_pressed = true; return nameAbund; }
2184 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
2186 string newFasta = fastaFile + ".temp";
2188 m->openOutputFile(newFasta, out);
2190 //print new file in order of
2191 for (int i = 0; i < nameMapCount.size(); i++) {
2192 out << ">" << nameMapCount[i].name << endl << nameMapCount[i].seq << endl;
2193 nameAbund[nameMapCount[i].name] = nameMapCount[i].numIdentical;
2197 rename(newFasta.c_str(), fastaFile.c_str());
2202 catch(exception& e) {
2203 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2207 /**************************************************************************************************/
2208 map<string, int> ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, string>& nameMap, string newFile) {
2210 map<string, int> nameAbund;
2211 vector<seqPriorityNode> nameVector;
2213 //read through fastafile and store info
2214 map<string, string> seqs;
2216 for (int i = 0; i < thisseqs.size(); i++) {
2218 if (m->control_pressed) { return nameAbund; }
2220 map<string, string>::iterator itNameMap = nameMap.find(thisseqs[i].getName());
2222 if (itNameMap == nameMap.end()){
2223 m->control_pressed = true;
2224 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your namesfile, please correct."); m->mothurOutEndLine();
2226 int num = m->getNumNames(itNameMap->second);
2228 seqPriorityNode temp(num, thisseqs[i].getAligned(), thisseqs[i].getName());
2229 nameVector.push_back(temp);
2233 //sort by num represented
2234 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
2236 if (m->control_pressed) { return nameAbund; }
2238 if (thisseqs.size() != nameVector.size()) { m->mothurOut( "The number of sequences in your fastafile does not match the number of sequences in your namefile, aborting."); m->mothurOutEndLine(); m->control_pressed = true; return nameAbund; }
2241 m->openOutputFile(newFile, out);
2243 //print new file in order of
2244 for (int i = 0; i < nameVector.size(); i++) {
2245 out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
2246 nameAbund[nameVector[i].name] = nameVector[i].numIdentical;
2253 catch(exception& e) {
2254 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2258 /**************************************************************************************************/
2259 int ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, int>& countMap, string newFile) {
2261 vector<seqPriorityNode> nameVector;
2263 //read through fastafile and store info
2264 map<string, string> seqs;
2266 for (int i = 0; i < thisseqs.size(); i++) {
2268 if (m->control_pressed) { return 0; }
2270 map<string, int>::iterator itCountMap = countMap.find(thisseqs[i].getName());
2272 if (itCountMap == countMap.end()){
2273 m->control_pressed = true;
2274 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your count file, please correct."); m->mothurOutEndLine();
2276 seqPriorityNode temp(itCountMap->second, thisseqs[i].getAligned(), thisseqs[i].getName());
2277 nameVector.push_back(temp);
2281 //sort by num represented
2282 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
2284 if (m->control_pressed) { return 0; }
2286 if (thisseqs.size() != nameVector.size()) { m->mothurOut( "The number of sequences in your fastafile does not match the number of sequences in your count file, aborting."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
2289 m->openOutputFile(newFile, out);
2291 //print new file in order of
2292 for (int i = 0; i < nameVector.size(); i++) {
2293 out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
2300 catch(exception& e) {
2301 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2305 /**************************************************************************************************/