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 m->mothurOutEndLine();
841 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
842 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
843 m->mothurOutEndLine();
848 catch(exception& e) {
849 m->errorOut(e, "ChimeraSlayerCommand", "execute");
853 //**********************************************************************************************************************
854 int ChimeraSlayerCommand::MPIExecuteGroups(string outputFileName, string accnosFileName, string trimFastaFileName, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup, string countlist, string countfile){
861 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
862 MPI_Comm_size(MPI_COMM_WORLD, &processors);
864 //put filenames in a vector, then pass each process a starting and ending point in the vector
865 //all processes already have the fileToPriority and fileGroup, they just need to know which files to process
866 map<string, map<string, int> >::iterator itFile;
867 vector<string> filenames;
868 for(itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) { filenames.push_back(itFile->first); }
870 int numGroupsPerProcessor = filenames.size() / processors;
871 int startIndex = pid * numGroupsPerProcessor;
872 int endIndex = (pid+1) * numGroupsPerProcessor;
873 if(pid == (processors - 1)){ endIndex = filenames.size(); }
875 vector<unsigned long long> MPIPos;
878 MPI_File outMPIAccnos;
879 MPI_File outMPIFasta;
880 MPI_File outMPICount;
882 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
883 int inMode=MPI_MODE_RDONLY;
885 char outFilename[1024];
886 strcpy(outFilename, outputFileName.c_str());
888 char outAccnosFilename[1024];
889 strcpy(outAccnosFilename, accnosFileName.c_str());
891 char outFastaFilename[1024];
892 strcpy(outFastaFilename, trimFastaFileName.c_str());
894 char outCountFilename[1024];
895 strcpy(outCountFilename, countlist.c_str());
897 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
898 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
899 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
900 if (hasCount && dups) { MPI_File_open(MPI_COMM_WORLD, outCountFilename, outMode, MPI_INFO_NULL, &outMPICount); }
902 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; }
905 if (pid == 0) { //you are the root process
906 m->mothurOutEndLine();
907 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
908 m->mothurOutEndLine();
910 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
913 int length = outTemp.length();
914 char* buf2 = new char[length];
915 memcpy(buf2, outTemp.c_str(), length);
917 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
920 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
922 for (int i = startIndex; i < endIndex; i++) {
924 int start = time(NULL);
926 string thisFastaName = filenames[i];
927 map<string, int> thisPriority = fileToPriority[thisFastaName];
929 char inFileName[1024];
930 strcpy(inFileName, thisFastaName.c_str());
932 MPI_File_open(MPI_COMM_SELF, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
934 MPIPos = m->setFilePosFasta(thisFastaName, num); //fills MPIPos, returns numSeqs
936 cout << endl << "Checking sequences from group: " << fileGroup[thisFastaName] << "." << endl;
939 driverMPI(0, num, inMPI, outMPI, outMPIAccnos, outMPIFasta, cnames, MPIPos, thisFastaName, thisPriority, true);
942 MPI_File_close(&inMPI);
943 m->mothurRemove(thisFastaName);
946 if (cnames.size() != 0) {
948 for (set<string>::iterator it = cnames.begin(); it != cnames.end(); it++) {
949 string outputString = (*it) + "\t" + fileGroup[thisFastaName] + "\n";
950 int length = outputString.length();
951 char* buf2 = new char[length];
952 memcpy(buf2, outputString.c_str(), length);
953 MPI_File_write_shared(outMPICount, buf2, length, MPI_CHAR, &status);
957 map<string, map<string, string> >::iterator itGroupNameMap = group2NameMap.find(fileGroup[thisFastaName]);
958 if (itGroupNameMap != group2NameMap.end()) {
959 map<string, string> thisnamemap = itGroupNameMap->second;
960 map<string, string>::iterator itN;
961 for (set<string>::iterator it = cnames.begin(); it != cnames.end(); it++) {
962 itN = thisnamemap.find(*it);
963 if (itN != thisnamemap.end()) {
964 vector<string> tempNames; m->splitAtComma(itN->second, tempNames);
965 for (int j = 0; j < tempNames.size(); j++) { //write to accnos file
966 string outputString = tempNames[j] + "\n";
967 int length = outputString.length();
968 char* buf2 = new char[length];
969 memcpy(buf2, outputString.c_str(), length);
971 MPI_File_write_shared(outMPIAccnos, buf2, length, MPI_CHAR, &status);
975 }else { m->mothurOut("[ERROR]: parsing cannot find " + *it + ".\n"); m->control_pressed = true; }
977 }else { m->mothurOut("[ERROR]: parsing cannot find " + fileGroup[thisFastaName] + ".\n"); m->control_pressed = true; }
983 cout << endl << "It took " << toString(time(NULL) - start) << " secs to check " + toString(num) + " sequences from group " << fileGroup[thisFastaName] << "." << endl;
987 for(int i = 1; i < processors; i++) {
989 MPI_Recv(&temp, 1, MPI_INT, i, 2001, MPI_COMM_WORLD, &status);
992 }else{ MPI_Send(&numSeqs, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD); }
994 MPI_File_close(&outMPI);
995 MPI_File_close(&outMPIAccnos);
996 if (trim) { MPI_File_close(&outMPIFasta); }
997 if (hasCount && dups) { MPI_File_close(&outMPICount); }
999 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
1003 }catch(exception& e) {
1004 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecuteGroups");
1008 //**********************************************************************************************************************
1009 int ChimeraSlayerCommand::MPIExecute(string inputFile, string outputFileName, string accnosFileName, string trimFastaFileName, map<string, int>& priority){
1013 int pid, numSeqsPerProcessor;
1015 vector<unsigned long long> MPIPos;
1018 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1019 MPI_Comm_size(MPI_COMM_WORLD, &processors);
1023 MPI_File outMPIAccnos;
1024 MPI_File outMPIFasta;
1026 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
1027 int inMode=MPI_MODE_RDONLY;
1029 char outFilename[1024];
1030 strcpy(outFilename, outputFileName.c_str());
1032 char outAccnosFilename[1024];
1033 strcpy(outAccnosFilename, accnosFileName.c_str());
1035 char outFastaFilename[1024];
1036 strcpy(outFastaFilename, trimFastaFileName.c_str());
1038 char inFileName[1024];
1039 strcpy(inFileName, inputFile.c_str());
1041 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
1042 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
1043 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
1044 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
1046 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
1048 if (pid == 0) { //you are the root process
1049 m->mothurOutEndLine();
1050 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
1051 m->mothurOutEndLine();
1053 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
1056 int length = outTemp.length();
1057 char* buf2 = new char[length];
1058 memcpy(buf2, outTemp.c_str(), length);
1060 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
1063 MPIPos = m->setFilePosFasta(inputFile, numSeqs); //fills MPIPos, returns numSeqs
1065 if (templatefile != "self") { //if template=self we can only use 1 processor
1066 //send file positions to all processes
1067 for(int i = 1; i < processors; i++) {
1068 MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
1069 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
1072 //figure out how many sequences you have to align
1073 numSeqsPerProcessor = numSeqs / processors;
1074 int startIndex = pid * numSeqsPerProcessor;
1075 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
1077 if (templatefile == "self") { //if template=self we can only use 1 processor
1079 numSeqsPerProcessor = numSeqs;
1084 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, cnames, MPIPos, inputFile, priority, false);
1086 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
1088 }else{ //you are a child process
1089 if (templatefile != "self") { //if template=self we can only use 1 processor
1090 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
1091 MPIPos.resize(numSeqs+1);
1092 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
1094 //figure out how many sequences you have to align
1095 numSeqsPerProcessor = numSeqs / processors;
1096 int startIndex = pid * numSeqsPerProcessor;
1097 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
1101 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, cnames, MPIPos, inputFile, priority, false);
1103 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
1109 MPI_File_close(&inMPI);
1110 MPI_File_close(&outMPI);
1111 MPI_File_close(&outMPIAccnos);
1112 if (trim) { MPI_File_close(&outMPIFasta); }
1113 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
1119 catch(exception& e) {
1120 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecute");
1124 //**********************************************************************************************************************
1125 int ChimeraSlayerCommand::deconvoluteResults(map<string, string>& uniqueNames, string outputFileName, string accnosFileName, string trimFileName){
1127 map<string, string>::iterator itUnique;
1130 if (trimera) { //add in more potential uniqueNames
1131 map<string, string> newUniqueNames = uniqueNames;
1132 for (map<string, string>::iterator it = uniqueNames.begin(); it != uniqueNames.end(); it++) {
1133 newUniqueNames[(it->first)+"_LEFT"] = (it->first)+"_LEFT";
1134 newUniqueNames[(it->first)+"_RIGHT"] = (it->first)+"_RIGHT";
1136 uniqueNames = newUniqueNames;
1137 newUniqueNames.clear();
1142 m->openInputFile(accnosFileName, in2, "no error");
1145 m->openOutputFile(accnosFileName+".temp", out2);
1147 string name; name = "";
1148 set<string> chimerasInFile;
1149 set<string>::iterator itChimeras;
1151 while (!in2.eof()) {
1152 if (m->control_pressed) { in2.close(); out2.close(); m->mothurRemove(outputFileName); m->mothurRemove((accnosFileName+".temp")); return 0; }
1154 in2 >> name; m->gobble(in2);
1157 itUnique = uniqueNames.find(name);
1159 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1161 itChimeras = chimerasInFile.find((itUnique->second));
1163 if (itChimeras == chimerasInFile.end()) {
1164 out2 << itUnique->second << endl;
1165 chimerasInFile.insert((itUnique->second));
1173 m->mothurRemove(accnosFileName);
1174 rename((accnosFileName+".temp").c_str(), accnosFileName.c_str());
1179 m->openInputFile(outputFileName, in);
1182 m->openOutputFile(outputFileName+".temp", out); out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
1184 string rest, parent1, parent2, line;
1185 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
1186 set<string>::iterator itNames;
1188 //assumptions - in file each read will always look like...
1191 F11Fcsw_63104 F11Fcsw_33372 F11Fcsw_37007 0.89441 80.4469 0.2 1.03727 93.2961 52.2 no 0-241 243-369
1196 line = m->getline(in); m->gobble(in);
1197 out << line << endl;
1200 //for the chimera file, we want to make sure if any group finds a sequence to be chimeric then all groups do,
1201 //so if this is a report that did not find it to be chimeric, but it appears in the accnos file,
1202 //then ignore this report and continue until we find the report that found it to be chimeric
1206 if (m->control_pressed) { in.close(); out.close(); m->mothurRemove((outputFileName+".temp")); return 0; }
1208 in >> name; m->gobble(in);
1209 in >> parent1; m->gobble(in);
1211 if (name == "Name") { //name = "Name" because we append the header line each time we add results from the groups
1212 line = m->getline(in); m->gobble(in);
1214 if (parent1 == "no") {
1216 itUnique = uniqueNames.find(name);
1218 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1220 //is this sequence really not chimeric??
1221 itChimeras = chimerasInFile.find(itUnique->second);
1223 if (itChimeras == chimerasInFile.end()) {
1224 //is this sequence not already in the file
1225 itNames = namesInFile.find((itUnique->second));
1227 if (itNames == namesInFile.end()) { out << itUnique->second << '\t' << "no" << endl; namesInFile.insert(itUnique->second); }
1230 }else { //read the rest of the line
1231 double DivQLAQRB,PerIDQLAQRB,BootStrapA,DivQLBQRA,PerIDQLBQRA,BootStrapB;
1232 string flag, range1, range2;
1234 in >> parent2 >> DivQLAQRB >> PerIDQLAQRB >> BootStrapA >> DivQLBQRA >> PerIDQLBQRA >> BootStrapB >> flag >> range1 >> range2; m->gobble(in);
1237 itUnique = uniqueNames.find(name);
1239 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1241 name = itUnique->second;
1242 //is this name already in the file
1243 itNames = namesInFile.find((name));
1245 if (itNames == namesInFile.end()) { //no not in file
1246 if (flag == "no") { //are you really a no??
1247 //is this sequence really not chimeric??
1248 itChimeras = chimerasInFile.find(name);
1250 //then you really are a no so print, otherwise skip
1251 if (itChimeras == chimerasInFile.end()) { print = true; }
1253 }else{ print = true; }
1258 out << name << '\t';
1260 namesInFile.insert(name);
1262 //output parent1's name
1263 itUnique = uniqueNames.find(parent1);
1264 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent1 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1265 else { out << itUnique->second << '\t'; }
1267 //output parent2's name
1268 itUnique = uniqueNames.find(parent2);
1269 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent2 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1270 else { out << itUnique->second << '\t'; }
1272 out << DivQLAQRB << '\t' << PerIDQLAQRB << '\t' << BootStrapA << '\t' << DivQLBQRA << '\t' << PerIDQLBQRA << '\t' << BootStrapB << '\t' << flag << '\t' << range1 << '\t' << range2 << endl;
1280 m->mothurRemove(outputFileName);
1281 rename((outputFileName+".temp").c_str(), outputFileName.c_str());
1286 m->openInputFile(trimFileName, in3);
1289 m->openOutputFile(trimFileName+".temp", out3);
1291 namesInFile.clear();
1293 while (!in3.eof()) {
1294 if (m->control_pressed) { in3.close(); out3.close(); m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); m->mothurRemove((trimFileName+".temp")); return 0; }
1296 Sequence seq(in3); m->gobble(in3);
1298 if (seq.getName() != "") {
1300 itUnique = uniqueNames.find(seq.getName());
1302 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ seq.getName() + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1304 itNames = namesInFile.find((itUnique->second));
1306 if (itNames == namesInFile.end()) {
1307 seq.printSequence(out3);
1315 m->mothurRemove(trimFileName);
1316 rename((trimFileName+".temp").c_str(), trimFileName.c_str());
1321 catch(exception& e) {
1322 m->errorOut(e, "ChimeraSlayerCommand", "deconvoluteResults");
1326 //**********************************************************************************************************************
1327 int ChimeraSlayerCommand::setUpForSelfReference(SequenceParser*& parser, map<string, string>& fileGroup, map<string, map<string, int> >& fileToPriority, int s){
1330 fileToPriority.clear();
1332 string nameFile = "";
1333 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
1334 nameFile = nameFileNames[s];
1335 }else { nameFile = getNamesFile(fastaFileNames[s]); }
1337 //you provided a groupfile
1338 string groupFile = "";
1339 if (groupFileNames.size() != 0) { groupFile = groupFileNames[s]; }
1341 if (groupFile == "") {
1342 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
1344 //sort fastafile by abundance, returns new sorted fastafile name
1345 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush();
1346 priority = sortFastaFile(fastaFileNames[s], nameFile);
1347 m->mothurOut("Done."); m->mothurOutEndLine();
1349 fileToPriority[fastaFileNames[s]] = priority;
1350 fileGroup[fastaFileNames[s]] = "noGroup";
1352 //Parse sequences by group
1353 parser = new SequenceParser(groupFile, fastaFileNames[s], nameFile);
1354 vector<string> groups = parser->getNamesOfGroups();
1356 for (int i = 0; i < groups.size(); i++) {
1357 vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
1358 map<string, string> thisGroupsMap = parser->getNameMap(groups[i]);
1359 group2NameMap[groups[i]] = thisGroupsMap;
1360 string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
1361 priority = sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile);
1362 fileToPriority[newFastaFile] = priority;
1363 fileGroup[newFastaFile] = groups[i];
1370 catch(exception& e) {
1371 m->errorOut(e, "ChimeraSlayerCommand", "setUpForSelfReference");
1375 //**********************************************************************************************************************
1376 int ChimeraSlayerCommand::setUpForSelfReference(SequenceCountParser*& parser, map<string, string>& fileGroup, map<string, map<string, int> >& fileToPriority, int s){
1379 fileToPriority.clear();
1381 string nameFile = "";
1382 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
1383 nameFile = nameFileNames[s];
1384 }else { m->control_pressed = true; return 0; }
1387 if (!ct.testGroups(nameFile)) {
1388 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
1390 //sort fastafile by abundance, returns new sorted fastafile name
1391 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush();
1392 priority = sortFastaFile(fastaFileNames[s], nameFile);
1393 m->mothurOut("Done."); m->mothurOutEndLine();
1395 fileToPriority[fastaFileNames[s]] = priority;
1396 fileGroup[fastaFileNames[s]] = "noGroup";
1398 //Parse sequences by group
1399 parser = new SequenceCountParser(nameFile, fastaFileNames[s]);
1400 vector<string> groups = parser->getNamesOfGroups();
1402 for (int i = 0; i < groups.size(); i++) {
1403 vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
1404 map<string, int> thisGroupsMap = parser->getCountTable(groups[i]);
1405 string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
1406 sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile);
1407 fileToPriority[newFastaFile] = thisGroupsMap;
1408 fileGroup[newFastaFile] = groups[i];
1415 catch(exception& e) {
1416 m->errorOut(e, "ChimeraSlayerCommand", "setUpForSelfReference");
1420 //**********************************************************************************************************************
1421 string ChimeraSlayerCommand::getNamesFile(string& inputFile){
1423 string nameFile = "";
1425 m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
1427 //use unique.seqs to create new name and fastafile
1428 string inputString = "fasta=" + inputFile;
1429 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
1430 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine();
1431 m->mothurCalling = true;
1433 Command* uniqueCommand = new DeconvoluteCommand(inputString);
1434 uniqueCommand->execute();
1436 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
1438 delete uniqueCommand;
1439 m->mothurCalling = false;
1440 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
1442 nameFile = filenames["name"][0];
1443 inputFile = filenames["fasta"][0];
1447 catch(exception& e) {
1448 m->errorOut(e, "ChimeraSlayerCommand", "getNamesFile");
1452 //**********************************************************************************************************************
1454 int ChimeraSlayerCommand::driverGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup, string countlist){
1457 ofstream outCountList;
1459 if (hasCount && dups) { m->openOutputFile(countlist, outCountList); }
1461 for (map<string, map<string, int> >::iterator itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) {
1463 if (m->control_pressed) { return 0; }
1465 int start = time(NULL);
1466 string thisFastaName = itFile->first;
1467 map<string, int> thisPriority = itFile->second;
1468 string thisoutputFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.chimera";
1469 string thisaccnosFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.accnos";
1470 string thistrimFastaFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.fasta";
1472 m->mothurOutEndLine(); m->mothurOut("Checking sequences from group: " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine();
1475 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1477 vector<unsigned long long> positions = m->divideFile(thisFastaName, proc);
1478 lines.push_back(linePair(positions[0], positions[1]));
1480 lines.push_back(linePair(0, 1000));
1482 int numSeqs = driver(lines[0], thisoutputFileName, thisFastaName, thisaccnosFileName, thistrimFastaFileName, thisPriority);
1484 //if we provided a count file with group info and set dereplicate=t, then we want to create a *.pick.count_table
1485 //This table will zero out group counts for seqs determined to be chimeric by that group.
1487 if (!m->isBlank(thisaccnosFileName)) {
1489 m->openInputFile(thisaccnosFileName, in);
1493 in >> name; m->gobble(in);
1494 outCountList << name << '\t' << fileGroup[thisFastaName] << endl;
1498 map<string, map<string, string> >::iterator itGroupNameMap = group2NameMap.find(fileGroup[thisFastaName]);
1499 if (itGroupNameMap != group2NameMap.end()) {
1500 map<string, string> thisnamemap = itGroupNameMap->second;
1501 map<string, string>::iterator itN;
1503 m->openOutputFile(thisaccnosFileName+".temp", out);
1505 in >> name; m->gobble(in);
1506 itN = thisnamemap.find(name);
1507 if (itN != thisnamemap.end()) {
1508 vector<string> tempNames; m->splitAtComma(itN->second, tempNames);
1509 for (int j = 0; j < tempNames.size(); j++) { out << tempNames[j] << endl; }
1511 }else { m->mothurOut("[ERROR]: parsing cannot find " + name + ".\n"); m->control_pressed = true; }
1515 m->renameFile(thisaccnosFileName+".temp", thisaccnosFileName);
1516 }else { m->mothurOut("[ERROR]: parsing cannot find " + fileGroup[thisFastaName] + ".\n"); m->control_pressed = true; }
1523 m->appendFiles(thisoutputFileName, outputFName); m->mothurRemove(thisoutputFileName);
1524 m->appendFiles(thisaccnosFileName, accnos); m->mothurRemove(thisaccnosFileName);
1525 if (trim) { m->appendFiles(thistrimFastaFileName, fasta); m->mothurRemove(thistrimFastaFileName); }
1526 m->mothurRemove(thisFastaName);
1528 totalSeqs += numSeqs;
1530 m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences from group " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine();
1533 if (hasCount && dups) { outCountList.close(); }
1537 catch(exception& e) {
1538 m->errorOut(e, "ChimeraSlayerCommand", "driverGroups");
1542 /**************************************************************************************************/
1543 int ChimeraSlayerCommand::createProcessesGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup, string countlist, string countFile) {
1549 if (fileToPriority.size() < processors) { processors = fileToPriority.size(); }
1551 CountTable newCount;
1552 if (hasCount && dups) { newCount.readTable(countFile); }
1554 int groupsPerProcessor = fileToPriority.size() / processors;
1555 int remainder = fileToPriority.size() % processors;
1557 vector< map<string, map<string, int> > > breakUp;
1559 for (int i = 0; i < processors; i++) {
1560 map<string, map<string, int> > thisFileToPriority;
1561 map<string, map<string, int> >::iterator itFile;
1563 int enough = groupsPerProcessor;
1564 if (i == 0) { enough = groupsPerProcessor + remainder; }
1566 for (itFile = fileToPriority.begin(); itFile != fileToPriority.end();) {
1567 thisFileToPriority[itFile->first] = itFile->second;
1568 fileToPriority.erase(itFile++);
1570 if (count == enough) { break; }
1572 breakUp.push_back(thisFileToPriority);
1575 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1576 //loop through and create all the processes you want
1577 while (process != processors) {
1581 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
1583 }else if (pid == 0){
1584 num = driverGroups(outputFName + toString(getpid()) + ".temp", accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", breakUp[process], fileGroup, accnos + toString(getpid()) + ".byCount");
1586 //pass numSeqs to parent
1588 string tempFile = outputFName + toString(getpid()) + ".num.temp";
1589 m->openOutputFile(tempFile, out);
1594 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
1595 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1600 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup, accnos + ".byCount");
1602 //force parent to wait until all the processes are done
1603 for (int i=0;i<processors;i++) {
1604 int temp = processIDS[i];
1608 for (int i = 0; i < processIDS.size(); i++) {
1610 string tempFile = outputFName + toString(processIDS[i]) + ".num.temp";
1611 m->openInputFile(tempFile, in);
1612 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
1613 in.close(); m->mothurRemove(tempFile);
1617 //////////////////////////////////////////////////////////////////////////////////////////////////////
1618 //Windows version shared memory, so be careful when passing variables through the slayerData struct.
1619 //Above fork() will clone, so memory is separate, but that's not the case with windows,
1620 //////////////////////////////////////////////////////////////////////////////////////////////////////
1622 vector<slayerData*> pDataArray;
1623 DWORD dwThreadIdArray[processors-1];
1624 HANDLE hThreadArray[processors-1];
1626 //Create processor worker threads.
1627 for(int i=1; i<processors; i++ ){
1628 string extension = toString(i) + ".temp";
1629 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);
1630 pDataArray.push_back(tempslayer);
1631 processIDS.push_back(i);
1633 //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
1634 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1635 hThreadArray[i-1] = CreateThread(NULL, 0, MySlayerGroupThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);
1638 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup, accnos + ".byCount");
1640 //Wait until all threads have terminated.
1641 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
1643 //Close all thread handles and free memory allocations.
1644 for(int i=0; i < pDataArray.size(); i++){
1645 if (pDataArray[i]->fileToPriority.size() != pDataArray[i]->end) {
1646 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;
1648 num += pDataArray[i]->count;
1649 CloseHandle(hThreadArray[i]);
1650 delete pDataArray[i];
1654 if (hasCount && dups) {
1655 if (!m->isBlank(accnos + ".byCount")) {
1657 m->openInputFile(accnos + ".byCount", in2);
1660 while (!in2.eof()) {
1661 in2 >> name >> group; m->gobble(in2);
1662 newCount.setAbund(name, group, 0);
1666 m->mothurRemove(accnos + ".byCount");
1670 //append output files
1671 for(int i=0;i<processIDS.size();i++){
1672 m->appendFiles((outputFName + toString(processIDS[i]) + ".temp"), outputFName);
1673 m->mothurRemove((outputFName + toString(processIDS[i]) + ".temp"));
1675 m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1676 m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1679 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
1680 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
1683 if (hasCount && dups) {
1684 if (!m->isBlank(accnos + toString(processIDS[i]) + ".byCount")) {
1686 m->openInputFile(accnos + toString(processIDS[i]) + ".byCount", in2);
1689 while (!in2.eof()) {
1690 in2 >> name >> group; m->gobble(in2);
1691 newCount.setAbund(name, group, 0);
1695 m->mothurRemove(accnos + toString(processIDS[i]) + ".byCount");
1700 //print new *.pick.count_table
1701 if (hasCount && dups) { newCount.printTable(countlist); }
1705 catch(exception& e) {
1706 m->errorOut(e, "ChimeraSlayerCommand", "createProcessesGroups");
1710 //**********************************************************************************************************************
1712 int ChimeraSlayerCommand::driver(linePair filePos, string outputFName, string filename, string accnos, string fasta, map<string, int>& priority){
1716 if (templatefile != "self") { //you want to run slayer with a reference template
1717 chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1719 chimera = new ChimeraSlayer(filename, templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1722 if (m->control_pressed) { delete chimera; return 0; }
1724 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1725 templateSeqsLength = chimera->getLength();
1728 m->openOutputFile(outputFName, out);
1731 m->openOutputFile(accnos, out2);
1734 if (trim) { m->openOutputFile(fasta, out3); }
1737 m->openInputFile(filename, inFASTA);
1739 inFASTA.seekg(filePos.start);
1741 if (filePos.start == 0) { chimera->printHeader(out); }
1748 if (m->control_pressed) { delete chimera; out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1; }
1750 Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
1751 string candidateAligned = candidateSeq->getAligned();
1753 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1754 if (candidateSeq->getAligned().length() != templateSeqsLength) {
1755 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1758 chimera->getChimeras(candidateSeq);
1760 if (m->control_pressed) { delete chimera; delete candidateSeq; return 1; }
1762 //if you are not chimeric, then check each half
1763 data_results wholeResults = chimera->getResults();
1765 //determine if we need to split
1766 bool isChimeric = false;
1768 if (wholeResults.flag == "yes") {
1769 string chimeraFlag = "no";
1770 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1772 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1775 if (chimeraFlag == "yes") {
1776 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1780 if ((!isChimeric) && trimera) {
1782 //split sequence in half by bases
1783 string leftQuery, rightQuery;
1784 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1785 divideInHalf(tempSeq, leftQuery, rightQuery);
1787 //run chimeraSlayer on each piece
1788 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1789 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1792 chimera->getChimeras(left);
1793 data_results leftResults = chimera->getResults();
1795 chimera->getChimeras(right);
1796 data_results rightResults = chimera->getResults();
1798 //if either piece is chimeric then report
1799 Sequence trimmed = chimera->print(out, out2, leftResults, rightResults);
1800 if (trim) { trimmed.printSequence(out3); }
1802 delete left; delete right;
1804 }else { //already chimeric
1806 Sequence trimmed = chimera->print(out, out2);
1807 if (trim) { trimmed.printSequence(out3); }
1815 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1816 unsigned long long pos = inFASTA.tellg();
1817 if ((pos == -1) || (pos >= filePos.end)) { break; }
1819 if (inFASTA.eof()) { break; }
1822 delete candidateSeq;
1824 if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
1827 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
1829 int numNoParents = chimera->getNumNoParents();
1830 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(); }
1834 if (trim) { out3.close(); }
1842 catch(exception& e) {
1843 m->errorOut(e, "ChimeraSlayerCommand", "driver");
1847 //**********************************************************************************************************************
1849 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){
1853 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1856 if (templatefile != "self") { //you want to run slayer with a reference template
1857 chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1859 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);
1862 if (m->control_pressed) { delete chimera; return 0; }
1864 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1865 templateSeqsLength = chimera->getLength();
1867 for(int i=0;i<num;i++){
1869 if (m->control_pressed) { delete chimera; return 1; }
1871 //read next sequence
1872 int length = MPIPos[start+i+1] - MPIPos[start+i];
1874 char* buf4 = new char[length];
1875 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
1877 string tempBuf = buf4;
1878 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
1879 istringstream iss (tempBuf,istringstream::in);
1883 Sequence* candidateSeq = new Sequence(iss); m->gobble(iss);
1884 string candidateAligned = candidateSeq->getAligned();
1886 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1888 if (candidateSeq->getAligned().length() != templateSeqsLength) {
1889 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1893 chimera->getChimeras(candidateSeq);
1895 if (m->control_pressed) { delete chimera; delete candidateSeq; return 1; }
1897 //if you are not chimeric, then check each half
1898 data_results wholeResults = chimera->getResults();
1900 //determine if we need to split
1901 bool isChimeric = false;
1903 if (wholeResults.flag == "yes") {
1904 string chimeraFlag = "no";
1905 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1907 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1910 if (chimeraFlag == "yes") {
1911 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1915 if ((!isChimeric) && trimera) {
1916 //split sequence in half by bases
1917 string leftQuery, rightQuery;
1918 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1919 divideInHalf(tempSeq, leftQuery, rightQuery);
1921 //run chimeraSlayer on each piece
1922 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1923 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1926 chimera->getChimeras(left);
1927 data_results leftResults = chimera->getResults();
1929 chimera->getChimeras(right);
1930 data_results rightResults = chimera->getResults();
1932 //if either piece is chimeric then report
1934 Sequence trimmed = chimera->print(outMPI, outAccMPI, leftResults, rightResults, flag);
1935 if (flag) { cnames.insert(candidateSeq->getName()); }
1938 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1940 //write to accnos file
1941 int length = outputString.length();
1942 char* buf2 = new char[length];
1943 memcpy(buf2, outputString.c_str(), length);
1945 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1949 delete left; delete right;
1953 Sequence trimmed = chimera->print(outMPI, outAccMPI);
1954 cnames.insert(candidateSeq->getName());
1957 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1959 //write to accnos file
1960 int length = outputString.length();
1961 char* buf2 = new char[length];
1962 memcpy(buf2, outputString.c_str(), length);
1964 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1971 delete candidateSeq;
1974 if((i+1) % 100 == 0){ cout << "Processing sequence: " << (i+1) << endl; m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n"); }
1977 if(num % 100 != 0){ cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n"); }
1979 int numNoParents = chimera->getNumNoParents();
1980 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; }
1985 catch(exception& e) {
1986 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
1992 /**************************************************************************************************/
1994 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta, map<string, int>& thisPriority) {
2000 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
2001 //loop through and create all the processes you want
2002 while (process != processors) {
2006 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
2008 }else if (pid == 0){
2009 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", thisPriority);
2011 //pass numSeqs to parent
2013 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
2014 m->openOutputFile(tempFile, out);
2019 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
2020 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
2025 //force parent to wait until all the processes are done
2026 for (int i=0;i<processors;i++) {
2027 int temp = processIDS[i];
2031 for (int i = 0; i < processIDS.size(); i++) {
2033 string tempFile = outputFileName + toString(processIDS[i]) + ".num.temp";
2034 m->openInputFile(tempFile, in);
2035 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
2036 in.close(); m->mothurRemove(tempFile);
2040 //////////////////////////////////////////////////////////////////////////////////////////////////////
2041 //Windows version shared memory, so be careful when passing variables through the slayerData struct.
2042 //Above fork() will clone, so memory is separate, but that's not the case with windows,
2043 //////////////////////////////////////////////////////////////////////////////////////////////////////
2045 vector<slayerData*> pDataArray;
2046 DWORD dwThreadIdArray[processors];
2047 HANDLE hThreadArray[processors];
2049 //Create processor worker threads.
2050 for( int i=0; i<processors; i++ ){
2051 string extension = toString(i) + ".temp";
2052 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);
2053 pDataArray.push_back(tempslayer);
2054 processIDS.push_back(i);
2056 //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
2057 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
2058 hThreadArray[i] = CreateThread(NULL, 0, MySlayerThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);
2061 //Wait until all threads have terminated.
2062 WaitForMultipleObjects(processors, hThreadArray, TRUE, INFINITE);
2064 //Close all thread handles and free memory allocations.
2065 for(int i=0; i < pDataArray.size(); i++){
2066 num += pDataArray[i]->count;
2067 CloseHandle(hThreadArray[i]);
2068 delete pDataArray[i];
2072 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
2073 rename((accnos + toString(processIDS[0]) + ".temp").c_str(), accnos.c_str());
2074 if (trim) { rename((fasta + toString(processIDS[0]) + ".temp").c_str(), fasta.c_str()); }
2076 //append output files
2077 for(int i=1;i<processIDS.size();i++){
2078 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
2079 m->mothurRemove((outputFileName + toString(processIDS[i]) + ".temp"));
2081 m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
2082 m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
2085 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
2086 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
2093 catch(exception& e) {
2094 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
2099 /**************************************************************************************************/
2101 int ChimeraSlayerCommand::divideInHalf(Sequence querySeq, string& leftQuery, string& rightQuery) {
2104 string queryUnAligned = querySeq.getUnaligned();
2105 int numBases = int(queryUnAligned.length() * 0.5);
2107 string queryAligned = querySeq.getAligned();
2108 leftQuery = querySeq.getAligned();
2109 rightQuery = querySeq.getAligned();
2113 for (int i = 0; i < queryAligned.length(); i++) {
2115 if (isalpha(queryAligned[i])) {
2120 if (baseCount >= numBases) { leftSpot = i; break; } //first half
2123 //blank out right side
2124 for (int i = leftSpot; i < leftQuery.length(); i++) { leftQuery[i] = '.'; }
2126 //blank out left side
2127 for (int i = 0; i < leftSpot; i++) { rightQuery[i] = '.'; }
2132 catch(exception& e) {
2133 m->errorOut(e, "ChimeraSlayerCommand", "divideInHalf");
2137 /**************************************************************************************************/
2138 map<string, int> ChimeraSlayerCommand::sortFastaFile(string fastaFile, string nameFile) {
2140 map<string, int> nameAbund;
2142 //read through fastafile and store info
2143 map<string, string> seqs;
2145 m->openInputFile(fastaFile, in);
2149 if (m->control_pressed) { in.close(); return nameAbund; }
2151 Sequence seq(in); m->gobble(in);
2152 seqs[seq.getName()] = seq.getAligned();
2157 //read namefile or countfile
2158 vector<seqPriorityNode> nameMapCount;
2162 ct.readTable(nameFile);
2164 for(map<string, string>::iterator it = seqs.begin(); it != seqs.end(); it++) {
2165 int num = ct.getNumSeqs(it->first);
2166 if (num == 0) { error = 1; }
2168 seqPriorityNode temp(num, it->second, it->first);
2169 nameMapCount.push_back(temp);
2172 }else { error = m->readNames(nameFile, nameMapCount, seqs); }
2174 if (m->control_pressed) { return nameAbund; }
2176 if (error == 1) { m->control_pressed = true; return nameAbund; }
2177 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; }
2179 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
2181 string newFasta = fastaFile + ".temp";
2183 m->openOutputFile(newFasta, out);
2185 //print new file in order of
2186 for (int i = 0; i < nameMapCount.size(); i++) {
2187 out << ">" << nameMapCount[i].name << endl << nameMapCount[i].seq << endl;
2188 nameAbund[nameMapCount[i].name] = nameMapCount[i].numIdentical;
2192 rename(newFasta.c_str(), fastaFile.c_str());
2197 catch(exception& e) {
2198 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2202 /**************************************************************************************************/
2203 map<string, int> ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, string>& nameMap, string newFile) {
2205 map<string, int> nameAbund;
2206 vector<seqPriorityNode> nameVector;
2208 //read through fastafile and store info
2209 map<string, string> seqs;
2211 for (int i = 0; i < thisseqs.size(); i++) {
2213 if (m->control_pressed) { return nameAbund; }
2215 map<string, string>::iterator itNameMap = nameMap.find(thisseqs[i].getName());
2217 if (itNameMap == nameMap.end()){
2218 m->control_pressed = true;
2219 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your namesfile, please correct."); m->mothurOutEndLine();
2221 int num = m->getNumNames(itNameMap->second);
2223 seqPriorityNode temp(num, thisseqs[i].getAligned(), thisseqs[i].getName());
2224 nameVector.push_back(temp);
2228 //sort by num represented
2229 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
2231 if (m->control_pressed) { return nameAbund; }
2233 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; }
2236 m->openOutputFile(newFile, out);
2238 //print new file in order of
2239 for (int i = 0; i < nameVector.size(); i++) {
2240 out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
2241 nameAbund[nameVector[i].name] = nameVector[i].numIdentical;
2248 catch(exception& e) {
2249 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2253 /**************************************************************************************************/
2254 int ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, int>& countMap, string newFile) {
2256 vector<seqPriorityNode> nameVector;
2258 //read through fastafile and store info
2259 map<string, string> seqs;
2261 for (int i = 0; i < thisseqs.size(); i++) {
2263 if (m->control_pressed) { return 0; }
2265 map<string, int>::iterator itCountMap = countMap.find(thisseqs[i].getName());
2267 if (itCountMap == countMap.end()){
2268 m->control_pressed = true;
2269 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your count file, please correct."); m->mothurOutEndLine();
2271 seqPriorityNode temp(itCountMap->second, thisseqs[i].getAligned(), thisseqs[i].getName());
2272 nameVector.push_back(temp);
2276 //sort by num represented
2277 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
2279 if (m->control_pressed) { return 0; }
2281 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; }
2284 m->openOutputFile(newFile, out);
2286 //print new file in order of
2287 for (int i = 0; i < nameVector.size(); i++) {
2288 out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
2295 catch(exception& e) {
2296 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2300 /**************************************************************************************************/