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") { temp = "false"; }
607 dups = m->isTrue(temp);
609 blastlocation = validParameter.validFile(parameters, "blastlocation", false);
610 if (blastlocation == "not found") { blastlocation = ""; }
612 //add / to name if needed
613 string lastChar = blastlocation.substr(blastlocation.length()-1);
614 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
615 if (lastChar != "/") { blastlocation += "/"; }
617 if (lastChar != "\\") { blastlocation += "\\"; }
619 blastlocation = m->getFullPathName(blastlocation);
620 string formatdbCommand = "";
621 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
622 formatdbCommand = blastlocation + "formatdb";
624 formatdbCommand = blastlocation + "formatdb.exe";
627 //test to make sure formatdb exists
629 formatdbCommand = m->getFullPathName(formatdbCommand);
630 int ableToOpen = m->openInputFile(formatdbCommand, in, "no error"); in.close();
631 if(ableToOpen == 1) { m->mothurOut("[ERROR]: " + formatdbCommand + " file does not exist. mothur requires formatdb.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
633 string blastCommand = "";
634 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
635 blastCommand = blastlocation + "megablast";
637 blastCommand = blastlocation + "megablast.exe";
639 //test to make sure formatdb exists
641 blastCommand = m->getFullPathName(blastCommand);
642 ableToOpen = m->openInputFile(blastCommand, in2, "no error"); in2.close();
643 if(ableToOpen == 1) { m->mothurOut("[ERROR]: " + blastCommand + " file does not exist. mothur requires blastall.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
646 if ((search != "blast") && (search != "kmer")) { m->mothurOut(search + " is not a valid search."); m->mothurOutEndLine(); abort = true; }
648 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; }
649 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; }
651 //until we resolve the issue 10-18-11
652 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
658 catch(exception& e) {
659 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
663 //***************************************************************************************************************
665 int ChimeraSlayerCommand::execute(){
667 if (abort == true) { if (calledHelp) { return 0; } return 2; }
669 for (int s = 0; s < fastaFileNames.size(); s++) {
671 m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
673 int start = time(NULL);
674 if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]); }//if user entered a file with a path then preserve it
675 map<string, string> variables;
676 variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]));
677 string outputFileName = getOutputFileName("chimera", variables);
678 string accnosFileName = getOutputFileName("accnos", variables);
679 string trimFastaFileName = getOutputFileName("fasta", variables);
680 string newCountFile = "";
683 ofstream out, out1, out2;
684 m->openOutputFile(outputFileName, out); out.close();
685 m->openOutputFile(accnosFileName, out1); out1.close();
686 if (trim) { m->openOutputFile(trimFastaFileName, out2); out2.close(); }
687 outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
688 outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
689 if (trim) { outputNames.push_back(trimFastaFileName); outputTypes["fasta"].push_back(trimFastaFileName); }
691 //maps a filename to priority map.
692 //if no groupfile this is fastafileNames[s] -> prioirity
693 //if groupfile then this is each groups seqs -> priority
694 map<string, map<string, int> > fileToPriority;
695 map<string, map<string, int> >::iterator itFile;
696 map<string, string> fileGroup;
697 fileToPriority[fastaFileNames[s]] = priority; //default
698 fileGroup[fastaFileNames[s]] = "noGroup";
699 map<string, string> uniqueNames;
700 int totalChimeras = 0;
703 if (templatefile == "self") {
705 SequenceCountParser* parser = NULL;
706 setUpForSelfReference(parser, fileGroup, fileToPriority, s);
707 if (parser != NULL) { uniqueNames = parser->getAllSeqsMap(); delete parser; }
709 SequenceParser* parser = NULL;
710 setUpForSelfReference(parser, fileGroup, fileToPriority, s);
711 if (parser != NULL) { uniqueNames = parser->getAllSeqsMap(); delete parser; }
715 if (m->control_pressed) { for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]); } return 0; }
717 if (fileToPriority.size() == 1) { //you running without a groupfile
718 itFile = fileToPriority.begin();
719 string thisFastaName = itFile->first;
720 map<string, int> thisPriority = itFile->second;
722 MPIExecute(thisFastaName, outputFileName, accnosFileName, trimFastaFileName, thisPriority);
725 vector<unsigned long long> positions;
726 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
727 positions = m->divideFile(thisFastaName, processors);
728 for (int i = 0; i < (positions.size()-1); i++) { lines.push_back(linePair(positions[i], positions[(i+1)])); }
730 if (processors == 1) { lines.push_back(linePair(0, 1000)); }
732 positions = m->setFilePosFasta(thisFastaName, numSeqs);
733 if (positions.size() < processors) { processors = positions.size(); }
735 //figure out how many sequences you have to process
736 int numSeqsPerProcessor = numSeqs / processors;
737 for (int i = 0; i < processors; i++) {
738 int startIndex = i * numSeqsPerProcessor;
739 if(i == (processors - 1)){ numSeqsPerProcessor = numSeqs - i * numSeqsPerProcessor; }
740 lines.push_back(linePair(positions[startIndex], numSeqsPerProcessor));
744 if(processors == 1){ numSeqs = driver(lines[0], outputFileName, thisFastaName, accnosFileName, trimFastaFileName, thisPriority); }
745 else{ numSeqs = createProcesses(outputFileName, thisFastaName, accnosFileName, trimFastaFileName, thisPriority); }
747 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; }
749 }else { //you have provided a groupfile
750 string countFile = "";
752 countFile = nameFileNames[s];
753 variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(nameFileNames[s]));
754 newCountFile = getOutputFileName("count", variables);
757 MPIExecuteGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup, newCountFile, countFile);
759 if (processors == 1) {
760 numSeqs = driverGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup, newCountFile);
761 if (hasCount && dups) {
762 CountTable c; c.readTable(nameFileNames[s], true);
763 if (!m->isBlank(newCountFile)) {
765 m->openInputFile(newCountFile, in2);
769 in2 >> name >> group; m->gobble(in2);
770 c.setAbund(name, group, 0);
774 m->mothurRemove(newCountFile);
775 c.printTable(newCountFile);
779 else { numSeqs = createProcessesGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup, newCountFile, countFile); } //destroys fileToPriority
784 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
789 totalChimeras = deconvoluteResults(uniqueNames, outputFileName, accnosFileName, trimFastaFileName);
790 m->mothurOutEndLine(); m->mothurOut(toString(totalChimeras) + " chimera found."); m->mothurOutEndLine();
793 set<string> doNotRemove;
794 CountTable c; c.readTable(newCountFile, true);
795 vector<string> namesInTable = c.getNamesOfSeqs();
796 for (int i = 0; i < namesInTable.size(); i++) {
797 int temp = c.getNumSeqs(namesInTable[i]);
798 if (temp == 0) { c.remove(namesInTable[i]); }
799 else { doNotRemove.insert((namesInTable[i])); }
801 //remove names we want to keep from accnos file.
802 set<string> accnosNames = m->readAccnos(accnosFileName);
804 m->openOutputFile(accnosFileName, out2);
805 for (set<string>::iterator it = accnosNames.begin(); it != accnosNames.end(); it++) {
806 if (doNotRemove.count(*it) == 0) { out2 << (*it) << endl; }
809 c.printTable(newCountFile);
810 outputNames.push_back(newCountFile); outputTypes["count"].push_back(newCountFile);
816 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
820 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
823 //set accnos file as new current accnosfile
825 itTypes = outputTypes.find("accnos");
826 if (itTypes != outputTypes.end()) {
827 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
831 itTypes = outputTypes.find("fasta");
832 if (itTypes != outputTypes.end()) {
833 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
837 itTypes = outputTypes.find("count");
838 if (itTypes != outputTypes.end()) {
839 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setCountTableFile(current); }
842 m->mothurOutEndLine();
843 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
844 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
845 m->mothurOutEndLine();
850 catch(exception& e) {
851 m->errorOut(e, "ChimeraSlayerCommand", "execute");
855 //**********************************************************************************************************************
856 int ChimeraSlayerCommand::MPIExecuteGroups(string outputFileName, string accnosFileName, string trimFastaFileName, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup, string countlist, string countfile){
863 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
864 MPI_Comm_size(MPI_COMM_WORLD, &processors);
866 //put filenames in a vector, then pass each process a starting and ending point in the vector
867 //all processes already have the fileToPriority and fileGroup, they just need to know which files to process
868 map<string, map<string, int> >::iterator itFile;
869 vector<string> filenames;
870 for(itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) { filenames.push_back(itFile->first); }
872 int numGroupsPerProcessor = filenames.size() / processors;
873 int startIndex = pid * numGroupsPerProcessor;
874 int endIndex = (pid+1) * numGroupsPerProcessor;
875 if(pid == (processors - 1)){ endIndex = filenames.size(); }
877 vector<unsigned long long> MPIPos;
880 MPI_File outMPIAccnos;
881 MPI_File outMPIFasta;
882 MPI_File outMPICount;
884 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
885 int inMode=MPI_MODE_RDONLY;
887 char outFilename[1024];
888 strcpy(outFilename, outputFileName.c_str());
890 char outAccnosFilename[1024];
891 strcpy(outAccnosFilename, accnosFileName.c_str());
893 char outFastaFilename[1024];
894 strcpy(outFastaFilename, trimFastaFileName.c_str());
896 char outCountFilename[1024];
897 strcpy(outCountFilename, countlist.c_str());
899 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
900 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
901 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
902 if (hasCount && dups) { MPI_File_open(MPI_COMM_WORLD, outCountFilename, outMode, MPI_INFO_NULL, &outMPICount); }
904 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; }
907 if (pid == 0) { //you are the root process
908 m->mothurOutEndLine();
909 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
910 m->mothurOutEndLine();
912 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
915 int length = outTemp.length();
916 char* buf2 = new char[length];
917 memcpy(buf2, outTemp.c_str(), length);
919 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
922 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
924 for (int i = startIndex; i < endIndex; i++) {
926 int start = time(NULL);
928 string thisFastaName = filenames[i];
929 map<string, int> thisPriority = fileToPriority[thisFastaName];
931 char inFileName[1024];
932 strcpy(inFileName, thisFastaName.c_str());
934 MPI_File_open(MPI_COMM_SELF, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
936 MPIPos = m->setFilePosFasta(thisFastaName, num); //fills MPIPos, returns numSeqs
938 cout << endl << "Checking sequences from group: " << fileGroup[thisFastaName] << "." << endl;
941 driverMPI(0, num, inMPI, outMPI, outMPIAccnos, outMPIFasta, cnames, MPIPos, thisFastaName, thisPriority, true);
944 MPI_File_close(&inMPI);
945 m->mothurRemove(thisFastaName);
948 if (cnames.size() != 0) {
950 for (set<string>::iterator it = cnames.begin(); it != cnames.end(); it++) {
951 string outputString = (*it) + "\t" + fileGroup[thisFastaName] + "\n";
952 int length = outputString.length();
953 char* buf2 = new char[length];
954 memcpy(buf2, outputString.c_str(), length);
955 MPI_File_write_shared(outMPICount, buf2, length, MPI_CHAR, &status);
959 map<string, map<string, string> >::iterator itGroupNameMap = group2NameMap.find(fileGroup[thisFastaName]);
960 if (itGroupNameMap != group2NameMap.end()) {
961 map<string, string> thisnamemap = itGroupNameMap->second;
962 map<string, string>::iterator itN;
963 for (set<string>::iterator it = cnames.begin(); it != cnames.end(); it++) {
964 itN = thisnamemap.find(*it);
965 if (itN != thisnamemap.end()) {
966 vector<string> tempNames; m->splitAtComma(itN->second, tempNames);
967 for (int j = 0; j < tempNames.size(); j++) { //write to accnos file
968 string outputString = tempNames[j] + "\n";
969 int length = outputString.length();
970 char* buf2 = new char[length];
971 memcpy(buf2, outputString.c_str(), length);
973 MPI_File_write_shared(outMPIAccnos, buf2, length, MPI_CHAR, &status);
977 }else { m->mothurOut("[ERROR]: parsing cannot find " + *it + ".\n"); m->control_pressed = true; }
979 }else { m->mothurOut("[ERROR]: parsing cannot find " + fileGroup[thisFastaName] + ".\n"); m->control_pressed = true; }
985 cout << endl << "It took " << toString(time(NULL) - start) << " secs to check " + toString(num) + " sequences from group " << fileGroup[thisFastaName] << "." << endl;
989 for(int i = 1; i < processors; i++) {
991 MPI_Recv(&temp, 1, MPI_INT, i, 2001, MPI_COMM_WORLD, &status);
994 }else{ MPI_Send(&numSeqs, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD); }
996 MPI_File_close(&outMPI);
997 MPI_File_close(&outMPIAccnos);
998 if (trim) { MPI_File_close(&outMPIFasta); }
999 if (hasCount && dups) { MPI_File_close(&outMPICount); }
1001 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
1005 }catch(exception& e) {
1006 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecuteGroups");
1010 //**********************************************************************************************************************
1011 int ChimeraSlayerCommand::MPIExecute(string inputFile, string outputFileName, string accnosFileName, string trimFastaFileName, map<string, int>& priority){
1015 int pid, numSeqsPerProcessor;
1017 vector<unsigned long long> MPIPos;
1020 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1021 MPI_Comm_size(MPI_COMM_WORLD, &processors);
1025 MPI_File outMPIAccnos;
1026 MPI_File outMPIFasta;
1028 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
1029 int inMode=MPI_MODE_RDONLY;
1031 char outFilename[1024];
1032 strcpy(outFilename, outputFileName.c_str());
1034 char outAccnosFilename[1024];
1035 strcpy(outAccnosFilename, accnosFileName.c_str());
1037 char outFastaFilename[1024];
1038 strcpy(outFastaFilename, trimFastaFileName.c_str());
1040 char inFileName[1024];
1041 strcpy(inFileName, inputFile.c_str());
1043 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
1044 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
1045 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
1046 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
1048 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
1050 if (pid == 0) { //you are the root process
1051 m->mothurOutEndLine();
1052 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
1053 m->mothurOutEndLine();
1055 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
1058 int length = outTemp.length();
1059 char* buf2 = new char[length];
1060 memcpy(buf2, outTemp.c_str(), length);
1062 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
1065 MPIPos = m->setFilePosFasta(inputFile, numSeqs); //fills MPIPos, returns numSeqs
1067 if (templatefile != "self") { //if template=self we can only use 1 processor
1068 //send file positions to all processes
1069 for(int i = 1; i < processors; i++) {
1070 MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
1071 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
1074 //figure out how many sequences you have to align
1075 numSeqsPerProcessor = numSeqs / processors;
1076 int startIndex = pid * numSeqsPerProcessor;
1077 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
1079 if (templatefile == "self") { //if template=self we can only use 1 processor
1081 numSeqsPerProcessor = numSeqs;
1086 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, cnames, MPIPos, inputFile, priority, false);
1088 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
1090 }else{ //you are a child process
1091 if (templatefile != "self") { //if template=self we can only use 1 processor
1092 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
1093 MPIPos.resize(numSeqs+1);
1094 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
1096 //figure out how many sequences you have to align
1097 numSeqsPerProcessor = numSeqs / processors;
1098 int startIndex = pid * numSeqsPerProcessor;
1099 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
1103 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, cnames, MPIPos, inputFile, priority, false);
1105 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
1111 MPI_File_close(&inMPI);
1112 MPI_File_close(&outMPI);
1113 MPI_File_close(&outMPIAccnos);
1114 if (trim) { MPI_File_close(&outMPIFasta); }
1115 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
1121 catch(exception& e) {
1122 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecute");
1126 //**********************************************************************************************************************
1127 int ChimeraSlayerCommand::deconvoluteResults(map<string, string>& uniqueNames, string outputFileName, string accnosFileName, string trimFileName){
1129 map<string, string>::iterator itUnique;
1132 if (trimera) { //add in more potential uniqueNames
1133 map<string, string> newUniqueNames = uniqueNames;
1134 for (map<string, string>::iterator it = uniqueNames.begin(); it != uniqueNames.end(); it++) {
1135 newUniqueNames[(it->first)+"_LEFT"] = (it->first)+"_LEFT";
1136 newUniqueNames[(it->first)+"_RIGHT"] = (it->first)+"_RIGHT";
1138 uniqueNames = newUniqueNames;
1139 newUniqueNames.clear();
1144 m->openInputFile(accnosFileName, in2, "no error");
1147 m->openOutputFile(accnosFileName+".temp", out2);
1149 string name; name = "";
1150 set<string> chimerasInFile;
1151 set<string>::iterator itChimeras;
1153 while (!in2.eof()) {
1154 if (m->control_pressed) { in2.close(); out2.close(); m->mothurRemove(outputFileName); m->mothurRemove((accnosFileName+".temp")); return 0; }
1156 in2 >> name; m->gobble(in2);
1159 itUnique = uniqueNames.find(name);
1161 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1163 itChimeras = chimerasInFile.find((itUnique->second));
1165 if (itChimeras == chimerasInFile.end()) {
1166 out2 << itUnique->second << endl;
1167 chimerasInFile.insert((itUnique->second));
1175 m->mothurRemove(accnosFileName);
1176 rename((accnosFileName+".temp").c_str(), accnosFileName.c_str());
1181 m->openInputFile(outputFileName, in);
1184 m->openOutputFile(outputFileName+".temp", out); out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
1186 string rest, parent1, parent2, line;
1187 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
1188 set<string>::iterator itNames;
1190 //assumptions - in file each read will always look like...
1193 F11Fcsw_63104 F11Fcsw_33372 F11Fcsw_37007 0.89441 80.4469 0.2 1.03727 93.2961 52.2 no 0-241 243-369
1198 line = m->getline(in); m->gobble(in);
1199 out << line << endl;
1202 //for the chimera file, we want to make sure if any group finds a sequence to be chimeric then all groups do,
1203 //so if this is a report that did not find it to be chimeric, but it appears in the accnos file,
1204 //then ignore this report and continue until we find the report that found it to be chimeric
1208 if (m->control_pressed) { in.close(); out.close(); m->mothurRemove((outputFileName+".temp")); return 0; }
1210 in >> name; m->gobble(in);
1211 in >> parent1; m->gobble(in);
1213 if (name == "Name") { //name = "Name" because we append the header line each time we add results from the groups
1214 line = m->getline(in); m->gobble(in);
1216 if (parent1 == "no") {
1218 itUnique = uniqueNames.find(name);
1220 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1222 //is this sequence really not chimeric??
1223 itChimeras = chimerasInFile.find(itUnique->second);
1225 if (itChimeras == chimerasInFile.end()) {
1226 //is this sequence not already in the file
1227 itNames = namesInFile.find((itUnique->second));
1229 if (itNames == namesInFile.end()) { out << itUnique->second << '\t' << "no" << endl; namesInFile.insert(itUnique->second); }
1232 }else { //read the rest of the line
1233 double DivQLAQRB,PerIDQLAQRB,BootStrapA,DivQLBQRA,PerIDQLBQRA,BootStrapB;
1234 string flag, range1, range2;
1236 in >> parent2 >> DivQLAQRB >> PerIDQLAQRB >> BootStrapA >> DivQLBQRA >> PerIDQLBQRA >> BootStrapB >> flag >> range1 >> range2; m->gobble(in);
1239 itUnique = uniqueNames.find(name);
1241 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1243 name = itUnique->second;
1244 //is this name already in the file
1245 itNames = namesInFile.find((name));
1247 if (itNames == namesInFile.end()) { //no not in file
1248 if (flag == "no") { //are you really a no??
1249 //is this sequence really not chimeric??
1250 itChimeras = chimerasInFile.find(name);
1252 //then you really are a no so print, otherwise skip
1253 if (itChimeras == chimerasInFile.end()) { print = true; }
1255 }else{ print = true; }
1260 out << name << '\t';
1262 namesInFile.insert(name);
1264 //output parent1's name
1265 itUnique = uniqueNames.find(parent1);
1266 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent1 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1267 else { out << itUnique->second << '\t'; }
1269 //output parent2's name
1270 itUnique = uniqueNames.find(parent2);
1271 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent2 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1272 else { out << itUnique->second << '\t'; }
1274 out << DivQLAQRB << '\t' << PerIDQLAQRB << '\t' << BootStrapA << '\t' << DivQLBQRA << '\t' << PerIDQLBQRA << '\t' << BootStrapB << '\t' << flag << '\t' << range1 << '\t' << range2 << endl;
1282 m->mothurRemove(outputFileName);
1283 rename((outputFileName+".temp").c_str(), outputFileName.c_str());
1288 m->openInputFile(trimFileName, in3);
1291 m->openOutputFile(trimFileName+".temp", out3);
1293 namesInFile.clear();
1295 while (!in3.eof()) {
1296 if (m->control_pressed) { in3.close(); out3.close(); m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); m->mothurRemove((trimFileName+".temp")); return 0; }
1298 Sequence seq(in3); m->gobble(in3);
1300 if (seq.getName() != "") {
1302 itUnique = uniqueNames.find(seq.getName());
1304 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ seq.getName() + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1306 itNames = namesInFile.find((itUnique->second));
1308 if (itNames == namesInFile.end()) {
1309 seq.printSequence(out3);
1317 m->mothurRemove(trimFileName);
1318 rename((trimFileName+".temp").c_str(), trimFileName.c_str());
1323 catch(exception& e) {
1324 m->errorOut(e, "ChimeraSlayerCommand", "deconvoluteResults");
1328 //**********************************************************************************************************************
1329 int ChimeraSlayerCommand::setUpForSelfReference(SequenceParser*& parser, map<string, string>& fileGroup, map<string, map<string, int> >& fileToPriority, int s){
1332 fileToPriority.clear();
1334 string nameFile = "";
1335 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
1336 nameFile = nameFileNames[s];
1337 }else { nameFile = getNamesFile(fastaFileNames[s]); }
1339 //you provided a groupfile
1340 string groupFile = "";
1341 if (groupFileNames.size() != 0) { groupFile = groupFileNames[s]; }
1343 if (groupFile == "") {
1344 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
1346 //sort fastafile by abundance, returns new sorted fastafile name
1347 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush();
1348 priority = sortFastaFile(fastaFileNames[s], nameFile);
1349 m->mothurOut("Done."); m->mothurOutEndLine();
1351 fileToPriority[fastaFileNames[s]] = priority;
1352 fileGroup[fastaFileNames[s]] = "noGroup";
1354 //Parse sequences by group
1355 parser = new SequenceParser(groupFile, fastaFileNames[s], nameFile);
1356 vector<string> groups = parser->getNamesOfGroups();
1358 for (int i = 0; i < groups.size(); i++) {
1359 vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
1360 map<string, string> thisGroupsMap = parser->getNameMap(groups[i]);
1361 group2NameMap[groups[i]] = thisGroupsMap;
1362 string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
1363 priority = sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile);
1364 fileToPriority[newFastaFile] = priority;
1365 fileGroup[newFastaFile] = groups[i];
1372 catch(exception& e) {
1373 m->errorOut(e, "ChimeraSlayerCommand", "setUpForSelfReference");
1377 //**********************************************************************************************************************
1378 int ChimeraSlayerCommand::setUpForSelfReference(SequenceCountParser*& parser, map<string, string>& fileGroup, map<string, map<string, int> >& fileToPriority, int s){
1381 fileToPriority.clear();
1383 string nameFile = "";
1384 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
1385 nameFile = nameFileNames[s];
1386 }else { m->control_pressed = true; return 0; }
1389 if (!ct.testGroups(nameFile)) {
1390 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
1392 //sort fastafile by abundance, returns new sorted fastafile name
1393 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush();
1394 priority = sortFastaFile(fastaFileNames[s], nameFile);
1395 m->mothurOut("Done."); m->mothurOutEndLine();
1397 fileToPriority[fastaFileNames[s]] = priority;
1398 fileGroup[fastaFileNames[s]] = "noGroup";
1400 //Parse sequences by group
1401 parser = new SequenceCountParser(nameFile, fastaFileNames[s]);
1402 vector<string> groups = parser->getNamesOfGroups();
1404 for (int i = 0; i < groups.size(); i++) {
1405 vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
1406 map<string, int> thisGroupsMap = parser->getCountTable(groups[i]);
1407 string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
1408 sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile);
1409 fileToPriority[newFastaFile] = thisGroupsMap;
1410 fileGroup[newFastaFile] = groups[i];
1417 catch(exception& e) {
1418 m->errorOut(e, "ChimeraSlayerCommand", "setUpForSelfReference");
1422 //**********************************************************************************************************************
1423 string ChimeraSlayerCommand::getNamesFile(string& inputFile){
1425 string nameFile = "";
1427 m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
1429 //use unique.seqs to create new name and fastafile
1430 string inputString = "fasta=" + inputFile;
1431 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
1432 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine();
1433 m->mothurCalling = true;
1435 Command* uniqueCommand = new DeconvoluteCommand(inputString);
1436 uniqueCommand->execute();
1438 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
1440 delete uniqueCommand;
1441 m->mothurCalling = false;
1442 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
1444 nameFile = filenames["name"][0];
1445 inputFile = filenames["fasta"][0];
1449 catch(exception& e) {
1450 m->errorOut(e, "ChimeraSlayerCommand", "getNamesFile");
1454 //**********************************************************************************************************************
1456 int ChimeraSlayerCommand::driverGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup, string countlist){
1459 ofstream outCountList;
1461 if (hasCount && dups) { m->openOutputFile(countlist, outCountList); }
1463 for (map<string, map<string, int> >::iterator itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) {
1465 if (m->control_pressed) { return 0; }
1467 int start = time(NULL);
1468 string thisFastaName = itFile->first;
1469 map<string, int> thisPriority = itFile->second;
1470 string thisoutputFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.chimera";
1471 string thisaccnosFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.accnos";
1472 string thistrimFastaFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.fasta";
1474 m->mothurOutEndLine(); m->mothurOut("Checking sequences from group: " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine();
1477 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1479 vector<unsigned long long> positions = m->divideFile(thisFastaName, proc);
1480 lines.push_back(linePair(positions[0], positions[1]));
1482 lines.push_back(linePair(0, 1000));
1484 int numSeqs = driver(lines[0], thisoutputFileName, thisFastaName, thisaccnosFileName, thistrimFastaFileName, thisPriority);
1486 //if we provided a count file with group info and set dereplicate=t, then we want to create a *.pick.count_table
1487 //This table will zero out group counts for seqs determined to be chimeric by that group.
1489 if (!m->isBlank(thisaccnosFileName)) {
1491 m->openInputFile(thisaccnosFileName, in);
1495 in >> name; m->gobble(in);
1496 outCountList << name << '\t' << fileGroup[thisFastaName] << endl;
1500 map<string, map<string, string> >::iterator itGroupNameMap = group2NameMap.find(fileGroup[thisFastaName]);
1501 if (itGroupNameMap != group2NameMap.end()) {
1502 map<string, string> thisnamemap = itGroupNameMap->second;
1503 map<string, string>::iterator itN;
1505 m->openOutputFile(thisaccnosFileName+".temp", out);
1507 in >> name; m->gobble(in);
1508 itN = thisnamemap.find(name);
1509 if (itN != thisnamemap.end()) {
1510 vector<string> tempNames; m->splitAtComma(itN->second, tempNames);
1511 for (int j = 0; j < tempNames.size(); j++) { out << tempNames[j] << endl; }
1513 }else { m->mothurOut("[ERROR]: parsing cannot find " + name + ".\n"); m->control_pressed = true; }
1517 m->renameFile(thisaccnosFileName+".temp", thisaccnosFileName);
1518 }else { m->mothurOut("[ERROR]: parsing cannot find " + fileGroup[thisFastaName] + ".\n"); m->control_pressed = true; }
1525 m->appendFiles(thisoutputFileName, outputFName); m->mothurRemove(thisoutputFileName);
1526 m->appendFiles(thisaccnosFileName, accnos); m->mothurRemove(thisaccnosFileName);
1527 if (trim) { m->appendFiles(thistrimFastaFileName, fasta); m->mothurRemove(thistrimFastaFileName); }
1528 m->mothurRemove(thisFastaName);
1530 totalSeqs += numSeqs;
1532 m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences from group " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine();
1535 if (hasCount && dups) { outCountList.close(); }
1539 catch(exception& e) {
1540 m->errorOut(e, "ChimeraSlayerCommand", "driverGroups");
1544 /**************************************************************************************************/
1545 int ChimeraSlayerCommand::createProcessesGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup, string countlist, string countFile) {
1551 if (fileToPriority.size() < processors) { processors = fileToPriority.size(); }
1553 CountTable newCount;
1554 if (hasCount && dups) { newCount.readTable(countFile, true); }
1556 int groupsPerProcessor = fileToPriority.size() / processors;
1557 int remainder = fileToPriority.size() % processors;
1559 vector< map<string, map<string, int> > > breakUp;
1561 for (int i = 0; i < processors; i++) {
1562 map<string, map<string, int> > thisFileToPriority;
1563 map<string, map<string, int> >::iterator itFile;
1565 int enough = groupsPerProcessor;
1566 if (i == 0) { enough = groupsPerProcessor + remainder; }
1568 for (itFile = fileToPriority.begin(); itFile != fileToPriority.end();) {
1569 thisFileToPriority[itFile->first] = itFile->second;
1570 fileToPriority.erase(itFile++);
1572 if (count == enough) { break; }
1574 breakUp.push_back(thisFileToPriority);
1577 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1578 //loop through and create all the processes you want
1579 while (process != processors) {
1583 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
1585 }else if (pid == 0){
1586 num = driverGroups(outputFName + toString(getpid()) + ".temp", accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", breakUp[process], fileGroup, accnos + toString(getpid()) + ".byCount");
1588 //pass numSeqs to parent
1590 string tempFile = outputFName + toString(getpid()) + ".num.temp";
1591 m->openOutputFile(tempFile, out);
1596 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
1597 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1602 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup, accnos + ".byCount");
1604 //force parent to wait until all the processes are done
1605 for (int i=0;i<processors;i++) {
1606 int temp = processIDS[i];
1610 for (int i = 0; i < processIDS.size(); i++) {
1612 string tempFile = outputFName + toString(processIDS[i]) + ".num.temp";
1613 m->openInputFile(tempFile, in);
1614 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
1615 in.close(); m->mothurRemove(tempFile);
1619 //////////////////////////////////////////////////////////////////////////////////////////////////////
1620 //Windows version shared memory, so be careful when passing variables through the slayerData struct.
1621 //Above fork() will clone, so memory is separate, but that's not the case with windows,
1622 //////////////////////////////////////////////////////////////////////////////////////////////////////
1624 vector<slayerData*> pDataArray;
1625 DWORD dwThreadIdArray[processors-1];
1626 HANDLE hThreadArray[processors-1];
1628 //Create processor worker threads.
1629 for(int i=1; i<processors; i++ ){
1630 string extension = toString(i) + ".temp";
1631 slayerData* tempslayer = new slayerData(group2NameMap, hasCount, dups, (accnos + toString(i) +".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);
1632 pDataArray.push_back(tempslayer);
1633 processIDS.push_back(i);
1635 //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
1636 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1637 hThreadArray[i-1] = CreateThread(NULL, 0, MySlayerGroupThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);
1640 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup, accnos + ".byCount");
1642 //Wait until all threads have terminated.
1643 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
1645 //Close all thread handles and free memory allocations.
1646 for(int i=0; i < pDataArray.size(); i++){
1647 if (pDataArray[i]->fileToPriority.size() != pDataArray[i]->end) {
1648 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;
1650 num += pDataArray[i]->count;
1651 CloseHandle(hThreadArray[i]);
1652 delete pDataArray[i];
1656 if (hasCount && dups) {
1657 if (!m->isBlank(accnos + ".byCount")) {
1659 m->openInputFile(accnos + ".byCount", in2);
1662 while (!in2.eof()) {
1663 in2 >> name >> group; m->gobble(in2);
1664 newCount.setAbund(name, group, 0);
1668 m->mothurRemove(accnos + ".byCount");
1672 //append output files
1673 for(int i=0;i<processIDS.size();i++){
1674 m->appendFiles((outputFName + toString(processIDS[i]) + ".temp"), outputFName);
1675 m->mothurRemove((outputFName + toString(processIDS[i]) + ".temp"));
1677 m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1678 m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1681 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
1682 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
1685 if (hasCount && dups) {
1686 if (!m->isBlank(accnos + toString(processIDS[i]) + ".byCount")) {
1688 m->openInputFile(accnos + toString(processIDS[i]) + ".byCount", in2);
1691 while (!in2.eof()) {
1692 in2 >> name >> group; m->gobble(in2);
1693 newCount.setAbund(name, group, 0);
1697 m->mothurRemove(accnos + toString(processIDS[i]) + ".byCount");
1702 //print new *.pick.count_table
1703 if (hasCount && dups) { newCount.printTable(countlist); }
1707 catch(exception& e) {
1708 m->errorOut(e, "ChimeraSlayerCommand", "createProcessesGroups");
1712 //**********************************************************************************************************************
1714 int ChimeraSlayerCommand::driver(linePair filePos, string outputFName, string filename, string accnos, string fasta, map<string, int>& priority){
1718 if (templatefile != "self") { //you want to run slayer with a reference template
1719 chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1721 chimera = new ChimeraSlayer(filename, templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1724 if (m->control_pressed) { delete chimera; return 0; }
1726 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1727 templateSeqsLength = chimera->getLength();
1730 m->openOutputFile(outputFName, out);
1733 m->openOutputFile(accnos, out2);
1736 if (trim) { m->openOutputFile(fasta, out3); }
1739 m->openInputFile(filename, inFASTA);
1741 inFASTA.seekg(filePos.start);
1743 if (filePos.start == 0) { chimera->printHeader(out); }
1750 if (m->control_pressed) { delete chimera; out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1; }
1752 Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
1753 string candidateAligned = candidateSeq->getAligned();
1755 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1756 if (candidateSeq->getAligned().length() != templateSeqsLength) {
1757 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1760 chimera->getChimeras(candidateSeq);
1762 if (m->control_pressed) { delete chimera; delete candidateSeq; return 1; }
1764 //if you are not chimeric, then check each half
1765 data_results wholeResults = chimera->getResults();
1767 //determine if we need to split
1768 bool isChimeric = false;
1770 if (wholeResults.flag == "yes") {
1771 string chimeraFlag = "no";
1772 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1774 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1777 if (chimeraFlag == "yes") {
1778 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1782 if ((!isChimeric) && trimera) {
1784 //split sequence in half by bases
1785 string leftQuery, rightQuery;
1786 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1787 divideInHalf(tempSeq, leftQuery, rightQuery);
1789 //run chimeraSlayer on each piece
1790 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1791 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1794 chimera->getChimeras(left);
1795 data_results leftResults = chimera->getResults();
1797 chimera->getChimeras(right);
1798 data_results rightResults = chimera->getResults();
1800 //if either piece is chimeric then report
1801 Sequence trimmed = chimera->print(out, out2, leftResults, rightResults);
1802 if (trim) { trimmed.printSequence(out3); }
1804 delete left; delete right;
1806 }else { //already chimeric
1808 Sequence trimmed = chimera->print(out, out2);
1809 if (trim) { trimmed.printSequence(out3); }
1817 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1818 unsigned long long pos = inFASTA.tellg();
1819 if ((pos == -1) || (pos >= filePos.end)) { break; }
1821 if (inFASTA.eof()) { break; }
1824 delete candidateSeq;
1826 if((count) % 100 == 0){ m->mothurOutJustToScreen("Processing sequence: " + toString(count) + "\n"); }
1829 if((count) % 100 != 0){ m->mothurOutJustToScreen("Processing sequence: " + toString(count)+ "\n"); }
1831 int numNoParents = chimera->getNumNoParents();
1832 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(); }
1836 if (trim) { out3.close(); }
1844 catch(exception& e) {
1845 m->errorOut(e, "ChimeraSlayerCommand", "driver");
1849 //**********************************************************************************************************************
1851 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){
1855 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1858 if (templatefile != "self") { //you want to run slayer with a reference template
1859 chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1861 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);
1864 if (m->control_pressed) { delete chimera; return 0; }
1866 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1867 templateSeqsLength = chimera->getLength();
1869 for(int i=0;i<num;i++){
1871 if (m->control_pressed) { delete chimera; return 1; }
1873 //read next sequence
1874 int length = MPIPos[start+i+1] - MPIPos[start+i];
1876 char* buf4 = new char[length];
1877 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
1879 string tempBuf = buf4;
1880 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
1881 istringstream iss (tempBuf,istringstream::in);
1885 Sequence* candidateSeq = new Sequence(iss); m->gobble(iss);
1886 string candidateAligned = candidateSeq->getAligned();
1888 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1890 if (candidateSeq->getAligned().length() != templateSeqsLength) {
1891 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1895 chimera->getChimeras(candidateSeq);
1897 if (m->control_pressed) { delete chimera; delete candidateSeq; return 1; }
1899 //if you are not chimeric, then check each half
1900 data_results wholeResults = chimera->getResults();
1902 //determine if we need to split
1903 bool isChimeric = false;
1905 if (wholeResults.flag == "yes") {
1906 string chimeraFlag = "no";
1907 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1909 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1912 if (chimeraFlag == "yes") {
1913 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1917 if ((!isChimeric) && trimera) {
1918 //split sequence in half by bases
1919 string leftQuery, rightQuery;
1920 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1921 divideInHalf(tempSeq, leftQuery, rightQuery);
1923 //run chimeraSlayer on each piece
1924 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1925 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1928 chimera->getChimeras(left);
1929 data_results leftResults = chimera->getResults();
1931 chimera->getChimeras(right);
1932 data_results rightResults = chimera->getResults();
1934 //if either piece is chimeric then report
1936 Sequence trimmed = chimera->print(outMPI, outAccMPI, leftResults, rightResults, flag);
1937 if (flag) { cnames.insert(candidateSeq->getName()); }
1940 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1942 //write to accnos file
1943 int length = outputString.length();
1944 char* buf2 = new char[length];
1945 memcpy(buf2, outputString.c_str(), length);
1947 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1951 delete left; delete right;
1955 Sequence trimmed = chimera->print(outMPI, outAccMPI);
1956 cnames.insert(candidateSeq->getName());
1959 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1961 //write to accnos file
1962 int length = outputString.length();
1963 char* buf2 = new char[length];
1964 memcpy(buf2, outputString.c_str(), length);
1966 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1973 delete candidateSeq;
1976 if((i+1) % 100 == 0){ cout << "Processing sequence: " << (i+1) << endl; }
1979 if(num % 100 != 0){ cout << "Processing sequence: " << num << endl; }
1981 int numNoParents = chimera->getNumNoParents();
1982 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; }
1987 catch(exception& e) {
1988 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
1994 /**************************************************************************************************/
1996 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta, map<string, int>& thisPriority) {
2002 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
2003 //loop through and create all the processes you want
2004 while (process != processors) {
2008 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
2010 }else if (pid == 0){
2011 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", thisPriority);
2013 //pass numSeqs to parent
2015 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
2016 m->openOutputFile(tempFile, out);
2021 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
2022 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
2027 //force parent to wait until all the processes are done
2028 for (int i=0;i<processors;i++) {
2029 int temp = processIDS[i];
2033 for (int i = 0; i < processIDS.size(); i++) {
2035 string tempFile = outputFileName + toString(processIDS[i]) + ".num.temp";
2036 m->openInputFile(tempFile, in);
2037 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
2038 in.close(); m->mothurRemove(tempFile);
2042 //////////////////////////////////////////////////////////////////////////////////////////////////////
2043 //Windows version shared memory, so be careful when passing variables through the slayerData struct.
2044 //Above fork() will clone, so memory is separate, but that's not the case with windows,
2045 //////////////////////////////////////////////////////////////////////////////////////////////////////
2047 vector<slayerData*> pDataArray;
2048 DWORD dwThreadIdArray[processors];
2049 HANDLE hThreadArray[processors];
2051 //Create processor worker threads.
2052 for( int i=0; i<processors; i++ ){
2053 string extension = toString(i) + ".temp";
2054 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);
2055 pDataArray.push_back(tempslayer);
2056 processIDS.push_back(i);
2058 //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
2059 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
2060 hThreadArray[i] = CreateThread(NULL, 0, MySlayerThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);
2063 //Wait until all threads have terminated.
2064 WaitForMultipleObjects(processors, hThreadArray, TRUE, INFINITE);
2066 //Close all thread handles and free memory allocations.
2067 for(int i=0; i < pDataArray.size(); i++){
2068 num += pDataArray[i]->count;
2069 CloseHandle(hThreadArray[i]);
2070 delete pDataArray[i];
2074 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
2075 rename((accnos + toString(processIDS[0]) + ".temp").c_str(), accnos.c_str());
2076 if (trim) { rename((fasta + toString(processIDS[0]) + ".temp").c_str(), fasta.c_str()); }
2078 //append output files
2079 for(int i=1;i<processIDS.size();i++){
2080 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
2081 m->mothurRemove((outputFileName + toString(processIDS[i]) + ".temp"));
2083 m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
2084 m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
2087 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
2088 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
2095 catch(exception& e) {
2096 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
2101 /**************************************************************************************************/
2103 int ChimeraSlayerCommand::divideInHalf(Sequence querySeq, string& leftQuery, string& rightQuery) {
2106 string queryUnAligned = querySeq.getUnaligned();
2107 int numBases = int(queryUnAligned.length() * 0.5);
2109 string queryAligned = querySeq.getAligned();
2110 leftQuery = querySeq.getAligned();
2111 rightQuery = querySeq.getAligned();
2115 for (int i = 0; i < queryAligned.length(); i++) {
2117 if (isalpha(queryAligned[i])) {
2122 if (baseCount >= numBases) { leftSpot = i; break; } //first half
2125 //blank out right side
2126 for (int i = leftSpot; i < leftQuery.length(); i++) { leftQuery[i] = '.'; }
2128 //blank out left side
2129 for (int i = 0; i < leftSpot; i++) { rightQuery[i] = '.'; }
2134 catch(exception& e) {
2135 m->errorOut(e, "ChimeraSlayerCommand", "divideInHalf");
2139 /**************************************************************************************************/
2140 map<string, int> ChimeraSlayerCommand::sortFastaFile(string fastaFile, string nameFile) {
2142 map<string, int> nameAbund;
2144 //read through fastafile and store info
2145 map<string, string> seqs;
2147 m->openInputFile(fastaFile, in);
2151 if (m->control_pressed) { in.close(); return nameAbund; }
2153 Sequence seq(in); m->gobble(in);
2154 seqs[seq.getName()] = seq.getAligned();
2159 //read namefile or countfile
2160 vector<seqPriorityNode> nameMapCount;
2164 ct.readTable(nameFile, true);
2166 for(map<string, string>::iterator it = seqs.begin(); it != seqs.end(); it++) {
2167 int num = ct.getNumSeqs(it->first);
2168 if (num == 0) { error = 1; }
2170 seqPriorityNode temp(num, it->second, it->first);
2171 nameMapCount.push_back(temp);
2174 }else { error = m->readNames(nameFile, nameMapCount, seqs); }
2176 if (m->control_pressed) { return nameAbund; }
2178 if (error == 1) { m->control_pressed = true; return nameAbund; }
2179 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; }
2181 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
2183 string newFasta = fastaFile + ".temp";
2185 m->openOutputFile(newFasta, out);
2187 //print new file in order of
2188 for (int i = 0; i < nameMapCount.size(); i++) {
2189 out << ">" << nameMapCount[i].name << endl << nameMapCount[i].seq << endl;
2190 nameAbund[nameMapCount[i].name] = nameMapCount[i].numIdentical;
2194 rename(newFasta.c_str(), fastaFile.c_str());
2199 catch(exception& e) {
2200 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2204 /**************************************************************************************************/
2205 map<string, int> ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, string>& nameMap, string newFile) {
2207 map<string, int> nameAbund;
2208 vector<seqPriorityNode> nameVector;
2210 //read through fastafile and store info
2211 map<string, string> seqs;
2213 for (int i = 0; i < thisseqs.size(); i++) {
2215 if (m->control_pressed) { return nameAbund; }
2217 map<string, string>::iterator itNameMap = nameMap.find(thisseqs[i].getName());
2219 if (itNameMap == nameMap.end()){
2220 m->control_pressed = true;
2221 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your namesfile, please correct."); m->mothurOutEndLine();
2223 int num = m->getNumNames(itNameMap->second);
2225 seqPriorityNode temp(num, thisseqs[i].getAligned(), thisseqs[i].getName());
2226 nameVector.push_back(temp);
2230 //sort by num represented
2231 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
2233 if (m->control_pressed) { return nameAbund; }
2235 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; }
2238 m->openOutputFile(newFile, out);
2240 //print new file in order of
2241 for (int i = 0; i < nameVector.size(); i++) {
2242 out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
2243 nameAbund[nameVector[i].name] = nameVector[i].numIdentical;
2250 catch(exception& e) {
2251 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2255 /**************************************************************************************************/
2256 int ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, int>& countMap, string newFile) {
2258 vector<seqPriorityNode> nameVector;
2260 //read through fastafile and store info
2261 map<string, string> seqs;
2263 for (int i = 0; i < thisseqs.size(); i++) {
2265 if (m->control_pressed) { return 0; }
2267 map<string, int>::iterator itCountMap = countMap.find(thisseqs[i].getName());
2269 if (itCountMap == countMap.end()){
2270 m->control_pressed = true;
2271 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your count file, please correct."); m->mothurOutEndLine();
2273 seqPriorityNode temp(itCountMap->second, thisseqs[i].getAligned(), thisseqs[i].getName());
2274 nameVector.push_back(temp);
2278 //sort by num represented
2279 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
2281 if (m->control_pressed) { return 0; }
2283 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; }
2286 m->openOutputFile(newFile, out);
2288 //print new file in order of
2289 for (int i = 0; i < nameVector.size(); i++) {
2290 out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
2297 catch(exception& e) {
2298 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2302 /**************************************************************************************************/