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"
15 //**********************************************************************************************************************
16 vector<string> ChimeraSlayerCommand::setParameters(){
18 CommandParameter ptemplate("reference", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(ptemplate);
19 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
20 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
21 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pgroup);
22 CommandParameter pwindow("window", "Number", "", "50", "", "", "",false,false); parameters.push_back(pwindow);
23 CommandParameter pksize("ksize", "Number", "", "7", "", "", "",false,false); parameters.push_back(pksize);
24 CommandParameter pmatch("match", "Number", "", "5.0", "", "", "",false,false); parameters.push_back(pmatch);
25 CommandParameter pmismatch("mismatch", "Number", "", "-4.0", "", "", "",false,false); parameters.push_back(pmismatch);
26 CommandParameter pminsim("minsim", "Number", "", "90", "", "", "",false,false); parameters.push_back(pminsim);
27 CommandParameter pmincov("mincov", "Number", "", "70", "", "", "",false,false); parameters.push_back(pmincov);
28 CommandParameter pminsnp("minsnp", "Number", "", "10", "", "", "",false,false); parameters.push_back(pminsnp);
29 CommandParameter pminbs("minbs", "Number", "", "90", "", "", "",false,false); parameters.push_back(pminbs);
30 CommandParameter psearch("search", "Multiple", "kmer-blast", "blast", "", "", "",false,false); parameters.push_back(psearch);
31 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
32 CommandParameter prealign("realign", "Boolean", "", "T", "", "", "",false,false); parameters.push_back(prealign);
33 CommandParameter ptrim("trim", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(ptrim);
34 CommandParameter psplit("split", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(psplit);
35 CommandParameter pnumwanted("numwanted", "Number", "", "15", "", "", "",false,false); parameters.push_back(pnumwanted);
36 CommandParameter piters("iters", "Number", "", "1000", "", "", "",false,false); parameters.push_back(piters);
37 CommandParameter pdivergence("divergence", "Number", "", "1.007", "", "", "",false,false); parameters.push_back(pdivergence);
38 CommandParameter pparents("parents", "Number", "", "3", "", "", "",false,false); parameters.push_back(pparents);
39 CommandParameter pincrement("increment", "Number", "", "5", "", "", "",false,false); parameters.push_back(pincrement);
40 CommandParameter pblastlocation("blastlocation", "String", "", "", "", "", "",false,false); parameters.push_back(pblastlocation);
41 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
42 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
43 CommandParameter psave("save", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(psave);
45 vector<string> myArray;
46 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
50 m->errorOut(e, "ChimeraSlayerCommand", "setParameters");
54 //**********************************************************************************************************************
55 string ChimeraSlayerCommand::getHelpString(){
57 string helpString = "";
58 helpString += "The chimera.slayer command reads a fastafile and referencefile and outputs potentially chimeric sequences.\n";
59 helpString += "This command was modeled after the chimeraSlayer written by the Broad Institute.\n";
60 helpString += "The chimera.slayer command parameters are fasta, name, template, processors, trim, ksize, window, match, mismatch, divergence. minsim, mincov, minbs, minsnp, parents, search, iters, increment, numwanted, blastlocation and realign.\n";
61 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";
62 helpString += "The name parameter allows you to provide a name file, if you are using reference=self. \n";
63 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";
64 helpString += "You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amazon.fasta \n";
65 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";
66 helpString += "The processors parameter allows you to specify how many processors you would like to use. The default is 1. \n";
68 helpString += "When using MPI, the processors parameter is set to the number of MPI processes running. \n";
70 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";
71 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";
72 helpString += "The window parameter allows you to specify the window size for searching for chimeras, default=50. \n";
73 helpString += "The increment parameter allows you to specify how far you move each window while finding chimeric sequences, default=5.\n";
74 helpString += "The numwanted parameter allows you to specify how many sequences you would each query sequence compared with, default=15.\n";
75 helpString += "The ksize parameter allows you to input kmersize, default is 7, used if search is kmer. \n";
76 helpString += "The match parameter allows you to reward matched bases in blast search, default is 5. \n";
77 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";
78 helpString += "The mismatch parameter allows you to penalize mismatched bases in blast search, default is -4. \n";
79 helpString += "The divergence parameter allows you to set a cutoff for chimera determination, default is 1.007. \n";
80 helpString += "The iters parameter allows you to specify the number of bootstrap iters to do with the chimeraslayer method, default=1000.\n";
81 helpString += "The minsim parameter allows you to specify a minimum similarity with the parent fragments, default=90. \n";
82 helpString += "The mincov parameter allows you to specify minimum coverage by closest matches found in template. Default is 70, meaning 70%. \n";
83 helpString += "The minbs parameter allows you to specify minimum bootstrap support for calling a sequence chimeric. Default is 90, meaning 90%. \n";
84 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";
85 helpString += "The search parameter allows you to specify search method for finding the closest parent. Choices are blast, and kmer, default blast. \n";
86 helpString += "The realign parameter allows you to realign the query to the potential parents. Choices are true or false, default true. \n";
87 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";
88 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.";
89 helpString += "The chimera.slayer command should be in the following format: \n";
90 helpString += "chimera.slayer(fasta=yourFastaFile, reference=yourTemplate, search=yourSearch) \n";
91 helpString += "Example: chimera.slayer(fasta=AD.align, reference=core_set_aligned.imputed.fasta, search=kmer) \n";
92 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";
96 m->errorOut(e, "ChimeraSlayerCommand", "getHelpString");
100 //**********************************************************************************************************************
101 string ChimeraSlayerCommand::getOutputFileNameTag(string type, string inputName=""){
103 string outputFileName = "";
104 map<string, vector<string> >::iterator it;
106 //is this a type this command creates
107 it = outputTypes.find(type);
108 if (it == outputTypes.end()) { m->mothurOut("[ERROR]: this command doesn't create a " + type + " output file.\n"); }
110 if (type == "chimera") { outputFileName = "slayer.chimeras"; }
111 else if (type == "accnos") { outputFileName = "slayer.accnos"; }
112 else if (type == "fasta") { outputFileName = "slayer.fasta"; }
113 else { m->mothurOut("[ERROR]: No definition for type " + type + " output file tag.\n"); m->control_pressed = true; }
115 return outputFileName;
117 catch(exception& e) {
118 m->errorOut(e, "ChimeraSlayerCommand", "getOutputFileNameTag");
122 //**********************************************************************************************************************
123 ChimeraSlayerCommand::ChimeraSlayerCommand(){
125 abort = true; calledHelp = true;
127 vector<string> tempOutNames;
128 outputTypes["chimera"] = tempOutNames;
129 outputTypes["accnos"] = tempOutNames;
130 outputTypes["fasta"] = tempOutNames;
132 catch(exception& e) {
133 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
137 //***************************************************************************************************************
138 ChimeraSlayerCommand::ChimeraSlayerCommand(string option) {
140 abort = false; calledHelp = false;
141 ReferenceDB* rdb = ReferenceDB::getInstance();
143 //allow user to run help
144 if(option == "help") { help(); abort = true; calledHelp = true; }
145 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
148 vector<string> myArray = setParameters();
150 OptionParser parser(option);
151 map<string,string> parameters = parser.getParameters();
153 ValidParameters validParameter("chimera.slayer");
154 map<string,string>::iterator it;
156 //check to make sure all parameters are valid for command
157 for (it = parameters.begin(); it != parameters.end(); it++) {
158 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
161 vector<string> tempOutNames;
162 outputTypes["chimera"] = tempOutNames;
163 outputTypes["accnos"] = tempOutNames;
164 outputTypes["fasta"] = tempOutNames;
166 //if the user changes the input directory command factory will send this info to us in the output parameter
167 string inputDir = validParameter.validFile(parameters, "inputdir", false);
168 if (inputDir == "not found"){ inputDir = ""; }
170 //check for required parameters
171 fastafile = validParameter.validFile(parameters, "fasta", false);
172 if (fastafile == "not found") {
173 //if there is a current fasta file, use it
174 string filename = m->getFastaFile();
175 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
176 else { m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
178 m->splitAtDash(fastafile, fastaFileNames);
180 //go through files and make sure they are good, if not, then disregard them
181 for (int i = 0; i < fastaFileNames.size(); i++) {
184 if (fastaFileNames[i] == "current") {
185 fastaFileNames[i] = m->getFastaFile();
186 if (fastaFileNames[i] != "") { m->mothurOut("Using " + fastaFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
188 m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true;
189 //erase from file list
190 fastaFileNames.erase(fastaFileNames.begin()+i);
197 if (inputDir != "") {
198 string path = m->hasPath(fastaFileNames[i]);
199 //if the user has not given a path then, add inputdir. else leave path alone.
200 if (path == "") { fastaFileNames[i] = inputDir + fastaFileNames[i]; }
206 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
208 //if you can't open it, try default location
209 if (ableToOpen == 1) {
210 if (m->getDefaultPath() != "") { //default path is set
211 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
212 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
214 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
216 fastaFileNames[i] = tryPath;
220 if (ableToOpen == 1) {
221 if (m->getOutputDir() != "") { //default path is set
222 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
223 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
225 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
227 fastaFileNames[i] = tryPath;
233 if (ableToOpen == 1) {
234 m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
235 //erase from file list
236 fastaFileNames.erase(fastaFileNames.begin()+i);
239 m->setFastaFile(fastaFileNames[i]);
244 //make sure there is at least one valid file left
245 if (fastaFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid files."); m->mothurOutEndLine(); abort = true; }
249 //check for required parameters
251 namefile = validParameter.validFile(parameters, "name", false);
252 if (namefile == "not found") { namefile = ""; hasName = false; }
254 m->splitAtDash(namefile, nameFileNames);
256 //go through files and make sure they are good, if not, then disregard them
257 for (int i = 0; i < nameFileNames.size(); i++) {
260 if (nameFileNames[i] == "current") {
261 nameFileNames[i] = m->getNameFile();
262 if (nameFileNames[i] != "") { m->mothurOut("Using " + nameFileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
264 m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true;
265 //erase from file list
266 nameFileNames.erase(nameFileNames.begin()+i);
273 if (inputDir != "") {
274 string path = m->hasPath(nameFileNames[i]);
275 //if the user has not given a path then, add inputdir. else leave path alone.
276 if (path == "") { nameFileNames[i] = inputDir + nameFileNames[i]; }
282 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
284 //if you can't open it, try default location
285 if (ableToOpen == 1) {
286 if (m->getDefaultPath() != "") { //default path is set
287 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
288 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
290 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
292 nameFileNames[i] = tryPath;
296 if (ableToOpen == 1) {
297 if (m->getOutputDir() != "") { //default path is set
298 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
299 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
301 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
303 nameFileNames[i] = tryPath;
309 if (ableToOpen == 1) {
310 m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
311 //erase from file list
312 nameFileNames.erase(nameFileNames.begin()+i);
315 m->setNameFile(nameFileNames[i]);
320 //make sure there is at least one valid file left
321 if (nameFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid name files."); m->mothurOutEndLine(); abort = true; }
324 if (hasName && (nameFileNames.size() != fastaFileNames.size())) { m->mothurOut("[ERROR]: The number of namefiles does not match the number of fastafiles, please correct."); m->mothurOutEndLine(); abort=true; }
326 bool hasGroup = true;
327 groupfile = validParameter.validFile(parameters, "group", false);
328 if (groupfile == "not found") { groupfile = ""; hasGroup = false; }
330 m->splitAtDash(groupfile, groupFileNames);
332 //go through files and make sure they are good, if not, then disregard them
333 for (int i = 0; i < groupFileNames.size(); i++) {
336 if (groupFileNames[i] == "current") {
337 groupFileNames[i] = m->getGroupFile();
338 if (groupFileNames[i] != "") { m->mothurOut("Using " + groupFileNames[i] + " as input file for the group parameter where you had given current."); m->mothurOutEndLine(); }
340 m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true;
341 //erase from file list
342 groupFileNames.erase(groupFileNames.begin()+i);
349 if (inputDir != "") {
350 string path = m->hasPath(groupFileNames[i]);
351 //if the user has not given a path then, add inputdir. else leave path alone.
352 if (path == "") { groupFileNames[i] = inputDir + groupFileNames[i]; }
358 ableToOpen = m->openInputFile(groupFileNames[i], in, "noerror");
360 //if you can't open it, try default location
361 if (ableToOpen == 1) {
362 if (m->getDefaultPath() != "") { //default path is set
363 string tryPath = m->getDefaultPath() + m->getSimpleName(groupFileNames[i]);
364 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
366 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
368 groupFileNames[i] = tryPath;
372 if (ableToOpen == 1) {
373 if (m->getOutputDir() != "") { //default path is set
374 string tryPath = m->getOutputDir() + m->getSimpleName(groupFileNames[i]);
375 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
377 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
379 groupFileNames[i] = tryPath;
385 if (ableToOpen == 1) {
386 m->mothurOut("Unable to open " + groupFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
387 //erase from file list
388 groupFileNames.erase(groupFileNames.begin()+i);
391 m->setGroupFile(groupFileNames[i]);
396 //make sure there is at least one valid file left
397 if (groupFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid group files."); m->mothurOutEndLine(); abort = true; }
400 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; }
403 //if the user changes the output directory command factory will send this info to us in the output parameter
404 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
406 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
407 m->setProcessors(temp);
408 m->mothurConvert(temp, processors);
410 temp = validParameter.validFile(parameters, "save", false); if (temp == "not found"){ temp = "f"; }
411 save = m->isTrue(temp);
413 if (save) { //clear out old references
418 it = parameters.find("reference");
419 //user has given a template file
420 if(it != parameters.end()){
421 if (it->second == "self") {
422 templatefile = "self";
424 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save.");
425 m->mothurOutEndLine();
430 path = m->hasPath(it->second);
431 //if the user has not given a path then, add inputdir. else leave path alone.
432 if (path == "") { parameters["reference"] = inputDir + it->second; }
434 templatefile = validParameter.validFile(parameters, "reference", true);
435 if (templatefile == "not open") { abort = true; }
436 else if (templatefile == "not found") { //check for saved reference sequences
437 if (rdb->referenceSeqs.size() != 0) {
438 templatefile = "saved";
440 m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required.");
441 m->mothurOutEndLine();
444 }else { if (save) { rdb->setSavedReference(templatefile); } }
446 }else if (hasName) { templatefile = "self";
448 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save.");
449 m->mothurOutEndLine();
454 if (rdb->referenceSeqs.size() != 0) {
455 templatefile = "saved";
457 m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required.");
458 m->mothurOutEndLine();
459 templatefile = ""; abort = true;
465 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found") { temp = "7"; }
466 m->mothurConvert(temp, ksize);
468 temp = validParameter.validFile(parameters, "window", false); if (temp == "not found") { temp = "50"; }
469 m->mothurConvert(temp, window);
471 temp = validParameter.validFile(parameters, "match", false); if (temp == "not found") { temp = "5"; }
472 m->mothurConvert(temp, match);
474 temp = validParameter.validFile(parameters, "mismatch", false); if (temp == "not found") { temp = "-4"; }
475 m->mothurConvert(temp, mismatch);
477 temp = validParameter.validFile(parameters, "divergence", false); if (temp == "not found") { temp = "1.007"; }
478 m->mothurConvert(temp, divR);
480 temp = validParameter.validFile(parameters, "minsim", false); if (temp == "not found") { temp = "90"; }
481 m->mothurConvert(temp, minSimilarity);
483 temp = validParameter.validFile(parameters, "mincov", false); if (temp == "not found") { temp = "70"; }
484 m->mothurConvert(temp, minCoverage);
486 temp = validParameter.validFile(parameters, "minbs", false); if (temp == "not found") { temp = "90"; }
487 m->mothurConvert(temp, minBS);
489 temp = validParameter.validFile(parameters, "minsnp", false); if (temp == "not found") { temp = "10"; }
490 m->mothurConvert(temp, minSNP);
492 temp = validParameter.validFile(parameters, "parents", false); if (temp == "not found") { temp = "3"; }
493 m->mothurConvert(temp, parents);
495 temp = validParameter.validFile(parameters, "realign", false); if (temp == "not found") { temp = "t"; }
496 realign = m->isTrue(temp);
498 temp = validParameter.validFile(parameters, "trim", false); if (temp == "not found") { temp = "f"; }
499 trim = m->isTrue(temp);
501 temp = validParameter.validFile(parameters, "split", false); if (temp == "not found") { temp = "f"; }
502 trimera = m->isTrue(temp);
504 search = validParameter.validFile(parameters, "search", false); if (search == "not found") { search = "blast"; }
506 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "1000"; }
507 m->mothurConvert(temp, iters);
509 temp = validParameter.validFile(parameters, "increment", false); if (temp == "not found") { temp = "5"; }
510 m->mothurConvert(temp, increment);
512 temp = validParameter.validFile(parameters, "numwanted", false); if (temp == "not found") { temp = "15"; }
513 m->mothurConvert(temp, numwanted);
515 blastlocation = validParameter.validFile(parameters, "blastlocation", false);
516 if (blastlocation == "not found") { blastlocation = ""; }
518 //add / to name if needed
519 string lastChar = blastlocation.substr(blastlocation.length()-1);
520 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
521 if (lastChar != "/") { blastlocation += "/"; }
523 if (lastChar != "\\") { blastlocation += "\\"; }
525 blastlocation = m->getFullPathName(blastlocation);
526 string formatdbCommand = "";
527 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
528 formatdbCommand = blastlocation + "formatdb";
530 formatdbCommand = blastlocation + "formatdb.exe";
533 //test to make sure formatdb exists
535 formatdbCommand = m->getFullPathName(formatdbCommand);
536 int ableToOpen = m->openInputFile(formatdbCommand, in, "no error"); in.close();
537 if(ableToOpen == 1) { m->mothurOut("[ERROR]: " + formatdbCommand + " file does not exist. mothur requires formatdb.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
539 string blastCommand = "";
540 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
541 blastCommand = blastlocation + "megablast";
543 blastCommand = blastlocation + "megablast.exe";
545 //test to make sure formatdb exists
547 blastCommand = m->getFullPathName(blastCommand);
548 ableToOpen = m->openInputFile(blastCommand, in2, "no error"); in2.close();
549 if(ableToOpen == 1) { m->mothurOut("[ERROR]: " + blastCommand + " file does not exist. mothur requires blastall.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
552 if ((search != "blast") && (search != "kmer")) { m->mothurOut(search + " is not a valid search."); m->mothurOutEndLine(); abort = true; }
554 if (hasName && (templatefile != "self")) { m->mothurOut("You have provided a namefile 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; }
555 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; }
557 //until we resolve the issue 10-18-11
558 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
564 catch(exception& e) {
565 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
569 //***************************************************************************************************************
571 int ChimeraSlayerCommand::execute(){
573 if (abort == true) { if (calledHelp) { return 0; } return 2; }
575 for (int s = 0; s < fastaFileNames.size(); s++) {
577 m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
579 int start = time(NULL);
580 if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]); }//if user entered a file with a path then preserve it
581 string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + getOutputFileNameTag("chimera");
582 string accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + getOutputFileNameTag("accnos");
583 string trimFastaFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + getOutputFileNameTag("fasta");
586 ofstream out, out1, out2;
587 m->openOutputFile(outputFileName, out); out.close();
588 m->openOutputFile(accnosFileName, out1); out1.close();
589 if (trim) { m->openOutputFile(trimFastaFileName, out2); out2.close(); }
590 outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
591 outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
592 if (trim) { outputNames.push_back(trimFastaFileName); outputTypes["fasta"].push_back(trimFastaFileName); }
594 //maps a filename to priority map.
595 //if no groupfile this is fastafileNames[s] -> prioirity
596 //if groupfile then this is each groups seqs -> priority
597 map<string, map<string, int> > fileToPriority;
598 map<string, map<string, int> >::iterator itFile;
599 map<string, string> fileGroup;
600 fileToPriority[fastaFileNames[s]] = priority; //default
601 fileGroup[fastaFileNames[s]] = "noGroup";
602 SequenceParser* parser = NULL;
603 int totalChimeras = 0;
606 if (templatefile == "self") { setUpForSelfReference(parser, fileGroup, fileToPriority, s); }
608 if (m->control_pressed) { if (parser != NULL) { delete parser; } for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]); } return 0; }
610 if (fileToPriority.size() == 1) { //you running without a groupfile
611 itFile = fileToPriority.begin();
612 string thisFastaName = itFile->first;
613 map<string, int> thisPriority = itFile->second;
615 MPIExecute(thisFastaName, outputFileName, accnosFileName, trimFastaFileName, thisPriority);
618 vector<unsigned long long> positions;
619 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
620 positions = m->divideFile(thisFastaName, processors);
621 for (int i = 0; i < (positions.size()-1); i++) { lines.push_back(linePair(positions[i], positions[(i+1)])); }
623 if (processors == 1) { lines.push_back(linePair(0, 1000)); }
625 positions = m->setFilePosFasta(thisFastaName, numSeqs);
626 if (positions.size() < processors) { processors = positions.size(); }
628 //figure out how many sequences you have to process
629 int numSeqsPerProcessor = numSeqs / processors;
630 for (int i = 0; i < processors; i++) {
631 int startIndex = i * numSeqsPerProcessor;
632 if(i == (processors - 1)){ numSeqsPerProcessor = numSeqs - i * numSeqsPerProcessor; }
633 lines.push_back(linePair(positions[startIndex], numSeqsPerProcessor));
637 if(processors == 1){ numSeqs = driver(lines[0], outputFileName, thisFastaName, accnosFileName, trimFastaFileName, thisPriority); }
638 else{ numSeqs = createProcesses(outputFileName, thisFastaName, accnosFileName, trimFastaFileName, thisPriority); }
640 if (m->control_pressed) { if (parser != NULL) { delete parser; } 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; }
642 }else { //you have provided a groupfile
644 MPIExecuteGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup);
646 if (processors == 1) { numSeqs = driverGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup); }
647 else { numSeqs = createProcessesGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup); } //destroys fileToPriority
652 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
657 totalChimeras = deconvoluteResults(parser, outputFileName, accnosFileName, trimFastaFileName);
658 m->mothurOutEndLine(); m->mothurOut(toString(totalChimeras) + " chimera found."); m->mothurOutEndLine();
661 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
665 if (parser != NULL) { delete parser; }
667 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
670 //set accnos file as new current accnosfile
672 itTypes = outputTypes.find("accnos");
673 if (itTypes != outputTypes.end()) {
674 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
678 itTypes = outputTypes.find("fasta");
679 if (itTypes != outputTypes.end()) {
680 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
684 m->mothurOutEndLine();
685 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
686 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
687 m->mothurOutEndLine();
692 catch(exception& e) {
693 m->errorOut(e, "ChimeraSlayerCommand", "execute");
697 //**********************************************************************************************************************
698 int ChimeraSlayerCommand::MPIExecuteGroups(string outputFileName, string accnosFileName, string trimFastaFileName, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup){
705 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
706 MPI_Comm_size(MPI_COMM_WORLD, &processors);
708 //put filenames in a vector, then pass each process a starting and ending point in the vector
709 //all processes already have the fileToPriority and fileGroup, they just need to know which files to process
710 map<string, map<string, int> >::iterator itFile;
711 vector<string> filenames;
712 for(itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) { filenames.push_back(itFile->first); }
714 int numGroupsPerProcessor = filenames.size() / processors;
715 int startIndex = pid * numGroupsPerProcessor;
716 int endIndex = (pid+1) * numGroupsPerProcessor;
717 if(pid == (processors - 1)){ endIndex = filenames.size(); }
719 vector<unsigned long long> MPIPos;
722 MPI_File outMPIAccnos;
723 MPI_File outMPIFasta;
725 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
726 int inMode=MPI_MODE_RDONLY;
728 char outFilename[1024];
729 strcpy(outFilename, outputFileName.c_str());
731 char outAccnosFilename[1024];
732 strcpy(outAccnosFilename, accnosFileName.c_str());
734 char outFastaFilename[1024];
735 strcpy(outFastaFilename, trimFastaFileName.c_str());
737 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
738 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
739 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
741 if (m->control_pressed) { MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
744 if (pid == 0) { //you are the root process
745 m->mothurOutEndLine();
746 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
747 m->mothurOutEndLine();
749 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
752 int length = outTemp.length();
753 char* buf2 = new char[length];
754 memcpy(buf2, outTemp.c_str(), length);
756 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
759 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
761 for (int i = startIndex; i < endIndex; i++) {
763 int start = time(NULL);
765 string thisFastaName = filenames[i];
766 map<string, int> thisPriority = fileToPriority[thisFastaName];
768 char inFileName[1024];
769 strcpy(inFileName, thisFastaName.c_str());
771 MPI_File_open(MPI_COMM_SELF, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
773 MPIPos = m->setFilePosFasta(thisFastaName, num); //fills MPIPos, returns numSeqs
775 cout << endl << "Checking sequences from group: " << fileGroup[thisFastaName] << "." << endl;
777 driverMPI(0, num, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, thisFastaName, thisPriority, true);
780 MPI_File_close(&inMPI);
781 m->mothurRemove(thisFastaName);
783 cout << endl << "It took " << toString(time(NULL) - start) << " secs to check " + toString(num) + " sequences from group " << fileGroup[thisFastaName] << "." << endl;
787 for(int i = 1; i < processors; i++) {
789 MPI_Recv(&temp, 1, MPI_INT, i, 2001, MPI_COMM_WORLD, &status);
792 }else{ MPI_Send(&numSeqs, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD); }
794 MPI_File_close(&outMPI);
795 MPI_File_close(&outMPIAccnos);
796 if (trim) { MPI_File_close(&outMPIFasta); }
798 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
802 }catch(exception& e) {
803 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecuteGroups");
807 //**********************************************************************************************************************
808 int ChimeraSlayerCommand::MPIExecute(string inputFile, string outputFileName, string accnosFileName, string trimFastaFileName, map<string, int>& priority){
812 int pid, numSeqsPerProcessor;
814 vector<unsigned long long> MPIPos;
817 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
818 MPI_Comm_size(MPI_COMM_WORLD, &processors);
822 MPI_File outMPIAccnos;
823 MPI_File outMPIFasta;
825 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
826 int inMode=MPI_MODE_RDONLY;
828 char outFilename[1024];
829 strcpy(outFilename, outputFileName.c_str());
831 char outAccnosFilename[1024];
832 strcpy(outAccnosFilename, accnosFileName.c_str());
834 char outFastaFilename[1024];
835 strcpy(outFastaFilename, trimFastaFileName.c_str());
837 char inFileName[1024];
838 strcpy(inFileName, inputFile.c_str());
840 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
841 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
842 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
843 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
845 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
847 if (pid == 0) { //you are the root process
848 m->mothurOutEndLine();
849 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
850 m->mothurOutEndLine();
852 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
855 int length = outTemp.length();
856 char* buf2 = new char[length];
857 memcpy(buf2, outTemp.c_str(), length);
859 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
862 MPIPos = m->setFilePosFasta(inputFile, numSeqs); //fills MPIPos, returns numSeqs
864 if (templatefile != "self") { //if template=self we can only use 1 processor
865 //send file positions to all processes
866 for(int i = 1; i < processors; i++) {
867 MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
868 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
871 //figure out how many sequences you have to align
872 numSeqsPerProcessor = numSeqs / processors;
873 int startIndex = pid * numSeqsPerProcessor;
874 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
876 if (templatefile == "self") { //if template=self we can only use 1 processor
878 numSeqsPerProcessor = numSeqs;
882 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, inputFile, priority, false);
884 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
886 }else{ //you are a child process
887 if (templatefile != "self") { //if template=self we can only use 1 processor
888 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
889 MPIPos.resize(numSeqs+1);
890 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
892 //figure out how many sequences you have to align
893 numSeqsPerProcessor = numSeqs / processors;
894 int startIndex = pid * numSeqsPerProcessor;
895 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
898 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, inputFile, priority, false);
900 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
906 MPI_File_close(&inMPI);
907 MPI_File_close(&outMPI);
908 MPI_File_close(&outMPIAccnos);
909 if (trim) { MPI_File_close(&outMPIFasta); }
910 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
916 catch(exception& e) {
917 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecute");
921 //**********************************************************************************************************************
922 int ChimeraSlayerCommand::deconvoluteResults(SequenceParser* parser, string outputFileName, string accnosFileName, string trimFileName){
924 map<string, string> uniqueNames = parser->getAllSeqsMap();
925 map<string, string>::iterator itUnique;
928 if (trimera) { //add in more potential uniqueNames
929 map<string, string> newUniqueNames = uniqueNames;
930 for (map<string, string>::iterator it = uniqueNames.begin(); it != uniqueNames.end(); it++) {
931 newUniqueNames[(it->first)+"_LEFT"] = (it->first)+"_LEFT";
932 newUniqueNames[(it->first)+"_RIGHT"] = (it->first)+"_RIGHT";
934 uniqueNames = newUniqueNames;
935 newUniqueNames.clear();
940 m->openInputFile(accnosFileName, in2, "no error");
943 m->openOutputFile(accnosFileName+".temp", out2);
945 string name; name = "";
946 set<string> chimerasInFile;
947 set<string>::iterator itChimeras;
950 if (m->control_pressed) { in2.close(); out2.close(); m->mothurRemove(outputFileName); m->mothurRemove((accnosFileName+".temp")); return 0; }
952 in2 >> name; m->gobble(in2);
955 itUnique = uniqueNames.find(name);
957 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
959 itChimeras = chimerasInFile.find((itUnique->second));
961 if (itChimeras == chimerasInFile.end()) {
962 out2 << itUnique->second << endl;
963 chimerasInFile.insert((itUnique->second));
971 m->mothurRemove(accnosFileName);
972 rename((accnosFileName+".temp").c_str(), accnosFileName.c_str());
977 m->openInputFile(outputFileName, in);
980 m->openOutputFile(outputFileName+".temp", out); out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
982 string rest, parent1, parent2, line;
983 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
984 set<string>::iterator itNames;
986 //assumptions - in file each read will always look like...
989 F11Fcsw_63104 F11Fcsw_33372 F11Fcsw_37007 0.89441 80.4469 0.2 1.03727 93.2961 52.2 no 0-241 243-369
994 line = m->getline(in); m->gobble(in);
998 //for the chimera file, we want to make sure if any group finds a sequence to be chimeric then all groups do,
999 //so if this is a report that did not find it to be chimeric, but it appears in the accnos file,
1000 //then ignore this report and continue until we find the report that found it to be chimeric
1004 if (m->control_pressed) { in.close(); out.close(); m->mothurRemove((outputFileName+".temp")); return 0; }
1006 in >> name; m->gobble(in);
1007 in >> parent1; m->gobble(in);
1009 if (name == "Name") { //name = "Name" because we append the header line each time we add results from the groups
1010 line = m->getline(in); m->gobble(in);
1012 if (parent1 == "no") {
1014 itUnique = uniqueNames.find(name);
1016 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1018 //is this sequence really not chimeric??
1019 itChimeras = chimerasInFile.find(itUnique->second);
1021 if (itChimeras == chimerasInFile.end()) {
1022 //is this sequence not already in the file
1023 itNames = namesInFile.find((itUnique->second));
1025 if (itNames == namesInFile.end()) { out << itUnique->second << '\t' << "no" << endl; namesInFile.insert(itUnique->second); }
1028 }else { //read the rest of the line
1029 double DivQLAQRB,PerIDQLAQRB,BootStrapA,DivQLBQRA,PerIDQLBQRA,BootStrapB;
1030 string flag, range1, range2;
1032 in >> parent2 >> DivQLAQRB >> PerIDQLAQRB >> BootStrapA >> DivQLBQRA >> PerIDQLBQRA >> BootStrapB >> flag >> range1 >> range2; m->gobble(in);
1035 itUnique = uniqueNames.find(name);
1037 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1039 name = itUnique->second;
1040 //is this name already in the file
1041 itNames = namesInFile.find((name));
1043 if (itNames == namesInFile.end()) { //no not in file
1044 if (flag == "no") { //are you really a no??
1045 //is this sequence really not chimeric??
1046 itChimeras = chimerasInFile.find(name);
1048 //then you really are a no so print, otherwise skip
1049 if (itChimeras == chimerasInFile.end()) { print = true; }
1051 }else{ print = true; }
1056 out << name << '\t';
1058 namesInFile.insert(name);
1060 //output parent1's name
1061 itUnique = uniqueNames.find(parent1);
1062 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent1 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1063 else { out << itUnique->second << '\t'; }
1065 //output parent2's name
1066 itUnique = uniqueNames.find(parent2);
1067 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent2 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1068 else { out << itUnique->second << '\t'; }
1070 out << DivQLAQRB << '\t' << PerIDQLAQRB << '\t' << BootStrapA << '\t' << DivQLBQRA << '\t' << PerIDQLBQRA << '\t' << BootStrapB << '\t' << flag << '\t' << range1 << '\t' << range2 << endl;
1078 m->mothurRemove(outputFileName);
1079 rename((outputFileName+".temp").c_str(), outputFileName.c_str());
1084 m->openInputFile(trimFileName, in3);
1087 m->openOutputFile(trimFileName+".temp", out3);
1089 namesInFile.clear();
1091 while (!in3.eof()) {
1092 if (m->control_pressed) { in3.close(); out3.close(); m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); m->mothurRemove((trimFileName+".temp")); return 0; }
1094 Sequence seq(in3); m->gobble(in3);
1096 if (seq.getName() != "") {
1098 itUnique = uniqueNames.find(seq.getName());
1100 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ seq.getName() + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1102 itNames = namesInFile.find((itUnique->second));
1104 if (itNames == namesInFile.end()) {
1105 seq.printSequence(out3);
1113 m->mothurRemove(trimFileName);
1114 rename((trimFileName+".temp").c_str(), trimFileName.c_str());
1119 catch(exception& e) {
1120 m->errorOut(e, "ChimeraSlayerCommand", "deconvoluteResults");
1124 //**********************************************************************************************************************
1125 int ChimeraSlayerCommand::setUpForSelfReference(SequenceParser*& parser, map<string, string>& fileGroup, map<string, map<string, int> >& fileToPriority, int s){
1128 fileToPriority.clear();
1130 string nameFile = "";
1131 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
1132 nameFile = nameFileNames[s];
1133 }else { nameFile = getNamesFile(fastaFileNames[s]); }
1135 //you provided a groupfile
1136 string groupFile = "";
1137 if (groupFileNames.size() != 0) { groupFile = groupFileNames[s]; }
1139 if (groupFile == "") {
1140 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
1142 //sort fastafile by abundance, returns new sorted fastafile name
1143 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush();
1144 priority = sortFastaFile(fastaFileNames[s], nameFile);
1145 m->mothurOut("Done."); m->mothurOutEndLine();
1147 fileToPriority[fastaFileNames[s]] = priority;
1148 fileGroup[fastaFileNames[s]] = "noGroup";
1150 //Parse sequences by group
1151 parser = new SequenceParser(groupFile, fastaFileNames[s], nameFile);
1152 vector<string> groups = parser->getNamesOfGroups();
1154 for (int i = 0; i < groups.size(); i++) {
1155 vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
1156 map<string, string> thisGroupsMap = parser->getNameMap(groups[i]);
1157 string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
1158 priority = sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile);
1159 fileToPriority[newFastaFile] = priority;
1160 fileGroup[newFastaFile] = groups[i];
1167 catch(exception& e) {
1168 m->errorOut(e, "ChimeraSlayerCommand", "setUpForSelfReference");
1173 //**********************************************************************************************************************
1174 string ChimeraSlayerCommand::getNamesFile(string& inputFile){
1176 string nameFile = "";
1178 m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
1180 //use unique.seqs to create new name and fastafile
1181 string inputString = "fasta=" + inputFile;
1182 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
1183 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine();
1184 m->mothurCalling = true;
1186 Command* uniqueCommand = new DeconvoluteCommand(inputString);
1187 uniqueCommand->execute();
1189 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
1191 delete uniqueCommand;
1192 m->mothurCalling = false;
1193 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
1195 nameFile = filenames["name"][0];
1196 inputFile = filenames["fasta"][0];
1200 catch(exception& e) {
1201 m->errorOut(e, "ChimeraSlayerCommand", "getNamesFile");
1205 //**********************************************************************************************************************
1207 int ChimeraSlayerCommand::driverGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup){
1211 for (map<string, map<string, int> >::iterator itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) {
1213 if (m->control_pressed) { return 0; }
1215 int start = time(NULL);
1216 string thisFastaName = itFile->first;
1217 map<string, int> thisPriority = itFile->second;
1218 string thisoutputFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.chimera";
1219 string thisaccnosFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.accnos";
1220 string thistrimFastaFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.fasta";
1222 m->mothurOutEndLine(); m->mothurOut("Checking sequences from group: " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine();
1225 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1227 vector<unsigned long long> positions = m->divideFile(thisFastaName, proc);
1228 lines.push_back(linePair(positions[0], positions[1]));
1230 lines.push_back(linePair(0, 1000));
1232 int numSeqs = driver(lines[0], thisoutputFileName, thisFastaName, thisaccnosFileName, thistrimFastaFileName, thisPriority);
1235 m->appendFiles(thisoutputFileName, outputFName); m->mothurRemove(thisoutputFileName);
1236 m->appendFiles(thisaccnosFileName, accnos); m->mothurRemove(thisaccnosFileName);
1237 if (trim) { m->appendFiles(thistrimFastaFileName, fasta); m->mothurRemove(thistrimFastaFileName); }
1238 m->mothurRemove(thisFastaName);
1240 totalSeqs += numSeqs;
1242 m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences from group " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine();
1247 catch(exception& e) {
1248 m->errorOut(e, "ChimeraSlayerCommand", "driverGroups");
1252 /**************************************************************************************************/
1253 int ChimeraSlayerCommand::createProcessesGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup) {
1259 if (fileToPriority.size() < processors) { processors = fileToPriority.size(); }
1261 int groupsPerProcessor = fileToPriority.size() / processors;
1262 int remainder = fileToPriority.size() % processors;
1264 vector< map<string, map<string, int> > > breakUp;
1266 for (int i = 0; i < processors; i++) {
1267 map<string, map<string, int> > thisFileToPriority;
1268 map<string, map<string, int> >::iterator itFile;
1270 int enough = groupsPerProcessor;
1271 if (i == 0) { enough = groupsPerProcessor + remainder; }
1273 for (itFile = fileToPriority.begin(); itFile != fileToPriority.end();) {
1274 thisFileToPriority[itFile->first] = itFile->second;
1275 fileToPriority.erase(itFile++);
1277 if (count == enough) { break; }
1279 breakUp.push_back(thisFileToPriority);
1282 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1283 //loop through and create all the processes you want
1284 while (process != processors) {
1288 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
1290 }else if (pid == 0){
1291 num = driverGroups(outputFName + toString(getpid()) + ".temp", accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", breakUp[process], fileGroup);
1293 //pass numSeqs to parent
1295 string tempFile = outputFName + toString(getpid()) + ".num.temp";
1296 m->openOutputFile(tempFile, out);
1301 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
1302 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1307 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup);
1309 //force parent to wait until all the processes are done
1310 for (int i=0;i<processors;i++) {
1311 int temp = processIDS[i];
1315 for (int i = 0; i < processIDS.size(); i++) {
1317 string tempFile = outputFName + toString(processIDS[i]) + ".num.temp";
1318 m->openInputFile(tempFile, in);
1319 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
1320 in.close(); m->mothurRemove(tempFile);
1324 //////////////////////////////////////////////////////////////////////////////////////////////////////
1325 //Windows version shared memory, so be careful when passing variables through the slayerData struct.
1326 //Above fork() will clone, so memory is separate, but that's not the case with windows,
1327 //////////////////////////////////////////////////////////////////////////////////////////////////////
1329 vector<slayerData*> pDataArray;
1330 DWORD dwThreadIdArray[processors-1];
1331 HANDLE hThreadArray[processors-1];
1333 //Create processor worker threads.
1334 for(int i=1; i<processors; i++ ){
1335 string extension = toString(i) + ".temp";
1336 slayerData* tempslayer = new slayerData((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);
1337 pDataArray.push_back(tempslayer);
1338 processIDS.push_back(i);
1340 //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
1341 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1342 hThreadArray[i-1] = CreateThread(NULL, 0, MySlayerGroupThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);
1345 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup);
1347 //Wait until all threads have terminated.
1348 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
1350 //Close all thread handles and free memory allocations.
1351 for(int i=0; i < pDataArray.size(); i++){
1352 num += pDataArray[i]->count;
1353 CloseHandle(hThreadArray[i]);
1354 delete pDataArray[i];
1358 //append output files
1359 for(int i=0;i<processIDS.size();i++){
1360 m->appendFiles((outputFName + toString(processIDS[i]) + ".temp"), outputFName);
1361 m->mothurRemove((outputFName + toString(processIDS[i]) + ".temp"));
1363 m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1364 m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1367 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
1368 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
1375 catch(exception& e) {
1376 m->errorOut(e, "ChimeraSlayerCommand", "createProcessesGroups");
1380 //**********************************************************************************************************************
1382 int ChimeraSlayerCommand::driver(linePair filePos, string outputFName, string filename, string accnos, string fasta, map<string, int>& priority){
1386 if (templatefile != "self") { //you want to run slayer with a reference template
1387 chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1389 chimera = new ChimeraSlayer(filename, templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1392 if (m->control_pressed) { delete chimera; return 0; }
1394 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1395 templateSeqsLength = chimera->getLength();
1398 m->openOutputFile(outputFName, out);
1401 m->openOutputFile(accnos, out2);
1404 if (trim) { m->openOutputFile(fasta, out3); }
1407 m->openInputFile(filename, inFASTA);
1409 inFASTA.seekg(filePos.start);
1411 if (filePos.start == 0) { chimera->printHeader(out); }
1418 if (m->control_pressed) { delete chimera; out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1; }
1420 Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
1421 string candidateAligned = candidateSeq->getAligned();
1423 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1424 if (candidateSeq->getAligned().length() != templateSeqsLength) {
1425 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1428 chimera->getChimeras(candidateSeq);
1430 if (m->control_pressed) { delete chimera; delete candidateSeq; return 1; }
1432 //if you are not chimeric, then check each half
1433 data_results wholeResults = chimera->getResults();
1435 //determine if we need to split
1436 bool isChimeric = false;
1438 if (wholeResults.flag == "yes") {
1439 string chimeraFlag = "no";
1440 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1442 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1445 if (chimeraFlag == "yes") {
1446 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1450 if ((!isChimeric) && trimera) {
1452 //split sequence in half by bases
1453 string leftQuery, rightQuery;
1454 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1455 divideInHalf(tempSeq, leftQuery, rightQuery);
1457 //run chimeraSlayer on each piece
1458 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1459 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1462 chimera->getChimeras(left);
1463 data_results leftResults = chimera->getResults();
1465 chimera->getChimeras(right);
1466 data_results rightResults = chimera->getResults();
1468 //if either piece is chimeric then report
1469 Sequence trimmed = chimera->print(out, out2, leftResults, rightResults);
1470 if (trim) { trimmed.printSequence(out3); }
1472 delete left; delete right;
1474 }else { //already chimeric
1476 Sequence trimmed = chimera->print(out, out2);
1477 if (trim) { trimmed.printSequence(out3); }
1485 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1486 unsigned long long pos = inFASTA.tellg();
1487 if ((pos == -1) || (pos >= filePos.end)) { break; }
1489 if (inFASTA.eof()) { break; }
1492 delete candidateSeq;
1494 if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
1497 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
1499 int numNoParents = chimera->getNumNoParents();
1500 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(); }
1504 if (trim) { out3.close(); }
1512 catch(exception& e) {
1513 m->errorOut(e, "ChimeraSlayerCommand", "driver");
1517 //**********************************************************************************************************************
1519 int ChimeraSlayerCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, MPI_File& outAccMPI, MPI_File& outFastaMPI, vector<unsigned long long>& MPIPos, string filename, map<string, int>& priority, bool byGroup){
1523 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1526 if (templatefile != "self") { //you want to run slayer with a reference template
1527 chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1529 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);
1532 if (m->control_pressed) { delete chimera; return 0; }
1534 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1535 templateSeqsLength = chimera->getLength();
1537 for(int i=0;i<num;i++){
1539 if (m->control_pressed) { delete chimera; return 1; }
1541 //read next sequence
1542 int length = MPIPos[start+i+1] - MPIPos[start+i];
1544 char* buf4 = new char[length];
1545 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
1547 string tempBuf = buf4;
1548 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
1549 istringstream iss (tempBuf,istringstream::in);
1553 Sequence* candidateSeq = new Sequence(iss); m->gobble(iss);
1554 string candidateAligned = candidateSeq->getAligned();
1556 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1558 if (candidateSeq->getAligned().length() != templateSeqsLength) {
1559 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1563 chimera->getChimeras(candidateSeq);
1565 if (m->control_pressed) { delete chimera; delete candidateSeq; return 1; }
1567 //if you are not chimeric, then check each half
1568 data_results wholeResults = chimera->getResults();
1570 //determine if we need to split
1571 bool isChimeric = false;
1573 if (wholeResults.flag == "yes") {
1574 string chimeraFlag = "no";
1575 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1577 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1580 if (chimeraFlag == "yes") {
1581 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1585 if ((!isChimeric) && trimera) {
1586 //split sequence in half by bases
1587 string leftQuery, rightQuery;
1588 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1589 divideInHalf(tempSeq, leftQuery, rightQuery);
1591 //run chimeraSlayer on each piece
1592 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1593 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1596 chimera->getChimeras(left);
1597 data_results leftResults = chimera->getResults();
1599 chimera->getChimeras(right);
1600 data_results rightResults = chimera->getResults();
1602 //if either piece is chimeric then report
1603 Sequence trimmed = chimera->print(outMPI, outAccMPI, leftResults, rightResults);
1605 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1607 //write to accnos file
1608 int length = outputString.length();
1609 char* buf2 = new char[length];
1610 memcpy(buf2, outputString.c_str(), length);
1612 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1616 delete left; delete right;
1620 Sequence trimmed = chimera->print(outMPI, outAccMPI);
1623 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1625 //write to accnos file
1626 int length = outputString.length();
1627 char* buf2 = new char[length];
1628 memcpy(buf2, outputString.c_str(), length);
1630 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1637 delete candidateSeq;
1640 if((i+1) % 100 == 0){ cout << "Processing sequence: " << (i+1) << endl; m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n"); }
1643 if(num % 100 != 0){ cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n"); }
1645 int numNoParents = chimera->getNumNoParents();
1646 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; }
1651 catch(exception& e) {
1652 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
1658 /**************************************************************************************************/
1660 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta, map<string, int>& thisPriority) {
1666 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1667 //loop through and create all the processes you want
1668 while (process != processors) {
1672 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
1674 }else if (pid == 0){
1675 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", thisPriority);
1677 //pass numSeqs to parent
1679 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
1680 m->openOutputFile(tempFile, out);
1685 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
1686 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1691 //force parent to wait until all the processes are done
1692 for (int i=0;i<processors;i++) {
1693 int temp = processIDS[i];
1697 for (int i = 0; i < processIDS.size(); i++) {
1699 string tempFile = outputFileName + toString(processIDS[i]) + ".num.temp";
1700 m->openInputFile(tempFile, in);
1701 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
1702 in.close(); m->mothurRemove(tempFile);
1706 //////////////////////////////////////////////////////////////////////////////////////////////////////
1707 //Windows version shared memory, so be careful when passing variables through the slayerData struct.
1708 //Above fork() will clone, so memory is separate, but that's not the case with windows,
1709 //////////////////////////////////////////////////////////////////////////////////////////////////////
1711 vector<slayerData*> pDataArray;
1712 DWORD dwThreadIdArray[processors];
1713 HANDLE hThreadArray[processors];
1715 //Create processor worker threads.
1716 for( int i=0; i<processors; i++ ){
1717 string extension = toString(i) + ".temp";
1718 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);
1719 pDataArray.push_back(tempslayer);
1720 processIDS.push_back(i);
1722 //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
1723 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1724 hThreadArray[i] = CreateThread(NULL, 0, MySlayerThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);
1727 //Wait until all threads have terminated.
1728 WaitForMultipleObjects(processors, hThreadArray, TRUE, INFINITE);
1730 //Close all thread handles and free memory allocations.
1731 for(int i=0; i < pDataArray.size(); i++){
1732 num += pDataArray[i]->count;
1733 CloseHandle(hThreadArray[i]);
1734 delete pDataArray[i];
1738 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
1739 rename((accnos + toString(processIDS[0]) + ".temp").c_str(), accnos.c_str());
1740 if (trim) { rename((fasta + toString(processIDS[0]) + ".temp").c_str(), fasta.c_str()); }
1742 //append output files
1743 for(int i=1;i<processIDS.size();i++){
1744 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
1745 m->mothurRemove((outputFileName + toString(processIDS[i]) + ".temp"));
1747 m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1748 m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1751 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
1752 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
1759 catch(exception& e) {
1760 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
1765 /**************************************************************************************************/
1767 int ChimeraSlayerCommand::divideInHalf(Sequence querySeq, string& leftQuery, string& rightQuery) {
1770 string queryUnAligned = querySeq.getUnaligned();
1771 int numBases = int(queryUnAligned.length() * 0.5);
1773 string queryAligned = querySeq.getAligned();
1774 leftQuery = querySeq.getAligned();
1775 rightQuery = querySeq.getAligned();
1779 for (int i = 0; i < queryAligned.length(); i++) {
1781 if (isalpha(queryAligned[i])) {
1786 if (baseCount >= numBases) { leftSpot = i; break; } //first half
1789 //blank out right side
1790 for (int i = leftSpot; i < leftQuery.length(); i++) { leftQuery[i] = '.'; }
1792 //blank out left side
1793 for (int i = 0; i < leftSpot; i++) { rightQuery[i] = '.'; }
1798 catch(exception& e) {
1799 m->errorOut(e, "ChimeraSlayerCommand", "divideInHalf");
1803 /**************************************************************************************************/
1804 map<string, int> ChimeraSlayerCommand::sortFastaFile(string fastaFile, string nameFile) {
1806 map<string, int> nameAbund;
1808 //read through fastafile and store info
1809 map<string, string> seqs;
1811 m->openInputFile(fastaFile, in);
1815 if (m->control_pressed) { in.close(); return nameAbund; }
1817 Sequence seq(in); m->gobble(in);
1818 seqs[seq.getName()] = seq.getAligned();
1824 vector<seqPriorityNode> nameMapCount;
1825 int error = m->readNames(nameFile, nameMapCount, seqs);
1827 if (m->control_pressed) { return nameAbund; }
1829 if (error == 1) { m->control_pressed = true; return nameAbund; }
1830 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; }
1832 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
1834 string newFasta = fastaFile + ".temp";
1836 m->openOutputFile(newFasta, out);
1838 //print new file in order of
1839 for (int i = 0; i < nameMapCount.size(); i++) {
1840 out << ">" << nameMapCount[i].name << endl << nameMapCount[i].seq << endl;
1841 nameAbund[nameMapCount[i].name] = nameMapCount[i].numIdentical;
1845 rename(newFasta.c_str(), fastaFile.c_str());
1850 catch(exception& e) {
1851 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
1855 /**************************************************************************************************/
1856 map<string, int> ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, string>& nameMap, string newFile) {
1858 map<string, int> nameAbund;
1859 vector<seqPriorityNode> nameVector;
1861 //read through fastafile and store info
1862 map<string, string> seqs;
1864 for (int i = 0; i < thisseqs.size(); i++) {
1866 if (m->control_pressed) { return nameAbund; }
1868 map<string, string>::iterator itNameMap = nameMap.find(thisseqs[i].getName());
1870 if (itNameMap == nameMap.end()){
1871 m->control_pressed = true;
1872 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your namesfile, please correct."); m->mothurOutEndLine();
1874 int num = m->getNumNames(itNameMap->second);
1876 seqPriorityNode temp(num, thisseqs[i].getAligned(), thisseqs[i].getName());
1877 nameVector.push_back(temp);
1881 //sort by num represented
1882 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
1884 if (m->control_pressed) { return nameAbund; }
1886 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; }
1889 m->openOutputFile(newFile, out);
1891 //print new file in order of
1892 for (int i = 0; i < nameVector.size(); i++) {
1893 out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
1894 nameAbund[nameVector[i].name] = nameVector[i].numIdentical;
1901 catch(exception& e) {
1902 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
1906 /**************************************************************************************************/