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 ChimeraSlayerCommand::ChimeraSlayerCommand(){
103 abort = true; calledHelp = true;
105 vector<string> tempOutNames;
106 outputTypes["chimera"] = tempOutNames;
107 outputTypes["accnos"] = tempOutNames;
108 outputTypes["fasta"] = tempOutNames;
110 catch(exception& e) {
111 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
115 //***************************************************************************************************************
116 ChimeraSlayerCommand::ChimeraSlayerCommand(string option) {
118 abort = false; calledHelp = false;
119 ReferenceDB* rdb = ReferenceDB::getInstance();
121 //allow user to run help
122 if(option == "help") { help(); abort = true; calledHelp = true; }
123 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
126 vector<string> myArray = setParameters();
128 OptionParser parser(option);
129 map<string,string> parameters = parser.getParameters();
131 ValidParameters validParameter("chimera.slayer");
132 map<string,string>::iterator it;
134 //check to make sure all parameters are valid for command
135 for (it = parameters.begin(); it != parameters.end(); it++) {
136 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
139 vector<string> tempOutNames;
140 outputTypes["chimera"] = tempOutNames;
141 outputTypes["accnos"] = tempOutNames;
142 outputTypes["fasta"] = tempOutNames;
144 //if the user changes the input directory command factory will send this info to us in the output parameter
145 string inputDir = validParameter.validFile(parameters, "inputdir", false);
146 if (inputDir == "not found"){ inputDir = ""; }
148 //check for required parameters
149 fastafile = validParameter.validFile(parameters, "fasta", false);
150 if (fastafile == "not found") {
151 //if there is a current fasta file, use it
152 string filename = m->getFastaFile();
153 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
154 else { m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
156 m->splitAtDash(fastafile, fastaFileNames);
158 //go through files and make sure they are good, if not, then disregard them
159 for (int i = 0; i < fastaFileNames.size(); i++) {
162 if (fastaFileNames[i] == "current") {
163 fastaFileNames[i] = m->getFastaFile();
164 if (fastaFileNames[i] != "") { m->mothurOut("Using " + fastaFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
166 m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true;
167 //erase from file list
168 fastaFileNames.erase(fastaFileNames.begin()+i);
175 if (inputDir != "") {
176 string path = m->hasPath(fastaFileNames[i]);
177 //if the user has not given a path then, add inputdir. else leave path alone.
178 if (path == "") { fastaFileNames[i] = inputDir + fastaFileNames[i]; }
184 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
186 //if you can't open it, try default location
187 if (ableToOpen == 1) {
188 if (m->getDefaultPath() != "") { //default path is set
189 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
190 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
192 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
194 fastaFileNames[i] = tryPath;
198 if (ableToOpen == 1) {
199 if (m->getOutputDir() != "") { //default path is set
200 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
201 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
203 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
205 fastaFileNames[i] = tryPath;
211 if (ableToOpen == 1) {
212 m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
213 //erase from file list
214 fastaFileNames.erase(fastaFileNames.begin()+i);
217 m->setFastaFile(fastaFileNames[i]);
222 //make sure there is at least one valid file left
223 if (fastaFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid files."); m->mothurOutEndLine(); abort = true; }
227 //check for required parameters
229 namefile = validParameter.validFile(parameters, "name", false);
230 if (namefile == "not found") { namefile = ""; hasName = false; }
232 m->splitAtDash(namefile, nameFileNames);
234 //go through files and make sure they are good, if not, then disregard them
235 for (int i = 0; i < nameFileNames.size(); i++) {
238 if (nameFileNames[i] == "current") {
239 nameFileNames[i] = m->getNameFile();
240 if (nameFileNames[i] != "") { m->mothurOut("Using " + nameFileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
242 m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true;
243 //erase from file list
244 nameFileNames.erase(nameFileNames.begin()+i);
251 if (inputDir != "") {
252 string path = m->hasPath(nameFileNames[i]);
253 //if the user has not given a path then, add inputdir. else leave path alone.
254 if (path == "") { nameFileNames[i] = inputDir + nameFileNames[i]; }
260 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
262 //if you can't open it, try default location
263 if (ableToOpen == 1) {
264 if (m->getDefaultPath() != "") { //default path is set
265 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
266 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
268 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
270 nameFileNames[i] = tryPath;
274 if (ableToOpen == 1) {
275 if (m->getOutputDir() != "") { //default path is set
276 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
277 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
279 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
281 nameFileNames[i] = tryPath;
287 if (ableToOpen == 1) {
288 m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
289 //erase from file list
290 nameFileNames.erase(nameFileNames.begin()+i);
293 m->setNameFile(nameFileNames[i]);
298 //make sure there is at least one valid file left
299 if (nameFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid name files."); m->mothurOutEndLine(); abort = true; }
302 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; }
304 bool hasGroup = true;
305 groupfile = validParameter.validFile(parameters, "group", false);
306 if (groupfile == "not found") { groupfile = ""; hasGroup = false; }
308 m->splitAtDash(groupfile, groupFileNames);
310 //go through files and make sure they are good, if not, then disregard them
311 for (int i = 0; i < groupFileNames.size(); i++) {
314 if (groupFileNames[i] == "current") {
315 groupFileNames[i] = m->getGroupFile();
316 if (groupFileNames[i] != "") { m->mothurOut("Using " + groupFileNames[i] + " as input file for the group parameter where you had given current."); m->mothurOutEndLine(); }
318 m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true;
319 //erase from file list
320 groupFileNames.erase(groupFileNames.begin()+i);
327 if (inputDir != "") {
328 string path = m->hasPath(groupFileNames[i]);
329 //if the user has not given a path then, add inputdir. else leave path alone.
330 if (path == "") { groupFileNames[i] = inputDir + groupFileNames[i]; }
336 ableToOpen = m->openInputFile(groupFileNames[i], in, "noerror");
338 //if you can't open it, try default location
339 if (ableToOpen == 1) {
340 if (m->getDefaultPath() != "") { //default path is set
341 string tryPath = m->getDefaultPath() + m->getSimpleName(groupFileNames[i]);
342 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
344 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
346 groupFileNames[i] = tryPath;
350 if (ableToOpen == 1) {
351 if (m->getOutputDir() != "") { //default path is set
352 string tryPath = m->getOutputDir() + m->getSimpleName(groupFileNames[i]);
353 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
355 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
357 groupFileNames[i] = tryPath;
363 if (ableToOpen == 1) {
364 m->mothurOut("Unable to open " + groupFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
365 //erase from file list
366 groupFileNames.erase(groupFileNames.begin()+i);
369 m->setGroupFile(groupFileNames[i]);
374 //make sure there is at least one valid file left
375 if (groupFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid group files."); m->mothurOutEndLine(); abort = true; }
378 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; }
381 //if the user changes the output directory command factory will send this info to us in the output parameter
382 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
384 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
385 m->setProcessors(temp);
386 m->mothurConvert(temp, processors);
388 temp = validParameter.validFile(parameters, "save", false); if (temp == "not found"){ temp = "f"; }
389 save = m->isTrue(temp);
391 if (save) { //clear out old references
396 it = parameters.find("reference");
397 //user has given a template file
398 if(it != parameters.end()){
399 if (it->second == "self") {
400 templatefile = "self";
402 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save.");
403 m->mothurOutEndLine();
408 path = m->hasPath(it->second);
409 //if the user has not given a path then, add inputdir. else leave path alone.
410 if (path == "") { parameters["reference"] = inputDir + it->second; }
412 templatefile = validParameter.validFile(parameters, "reference", true);
413 if (templatefile == "not open") { abort = true; }
414 else if (templatefile == "not found") { //check for saved reference sequences
415 if (rdb->referenceSeqs.size() != 0) {
416 templatefile = "saved";
418 m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required.");
419 m->mothurOutEndLine();
422 }else { if (save) { rdb->setSavedReference(templatefile); } }
424 }else if (hasName) { templatefile = "self";
426 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save.");
427 m->mothurOutEndLine();
432 if (rdb->referenceSeqs.size() != 0) {
433 templatefile = "saved";
435 m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required.");
436 m->mothurOutEndLine();
437 templatefile = ""; abort = true;
443 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found") { temp = "7"; }
444 m->mothurConvert(temp, ksize);
446 temp = validParameter.validFile(parameters, "window", false); if (temp == "not found") { temp = "50"; }
447 m->mothurConvert(temp, window);
449 temp = validParameter.validFile(parameters, "match", false); if (temp == "not found") { temp = "5"; }
450 m->mothurConvert(temp, match);
452 temp = validParameter.validFile(parameters, "mismatch", false); if (temp == "not found") { temp = "-4"; }
453 m->mothurConvert(temp, mismatch);
455 temp = validParameter.validFile(parameters, "divergence", false); if (temp == "not found") { temp = "1.007"; }
456 m->mothurConvert(temp, divR);
458 temp = validParameter.validFile(parameters, "minsim", false); if (temp == "not found") { temp = "90"; }
459 m->mothurConvert(temp, minSimilarity);
461 temp = validParameter.validFile(parameters, "mincov", false); if (temp == "not found") { temp = "70"; }
462 m->mothurConvert(temp, minCoverage);
464 temp = validParameter.validFile(parameters, "minbs", false); if (temp == "not found") { temp = "90"; }
465 m->mothurConvert(temp, minBS);
467 temp = validParameter.validFile(parameters, "minsnp", false); if (temp == "not found") { temp = "10"; }
468 m->mothurConvert(temp, minSNP);
470 temp = validParameter.validFile(parameters, "parents", false); if (temp == "not found") { temp = "3"; }
471 m->mothurConvert(temp, parents);
473 temp = validParameter.validFile(parameters, "realign", false); if (temp == "not found") { temp = "t"; }
474 realign = m->isTrue(temp);
476 temp = validParameter.validFile(parameters, "trim", false); if (temp == "not found") { temp = "f"; }
477 trim = m->isTrue(temp);
479 temp = validParameter.validFile(parameters, "split", false); if (temp == "not found") { temp = "f"; }
480 trimera = m->isTrue(temp);
482 search = validParameter.validFile(parameters, "search", false); if (search == "not found") { search = "blast"; }
484 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "1000"; }
485 m->mothurConvert(temp, iters);
487 temp = validParameter.validFile(parameters, "increment", false); if (temp == "not found") { temp = "5"; }
488 m->mothurConvert(temp, increment);
490 temp = validParameter.validFile(parameters, "numwanted", false); if (temp == "not found") { temp = "15"; }
491 m->mothurConvert(temp, numwanted);
493 blastlocation = validParameter.validFile(parameters, "blastlocation", false);
494 if (blastlocation == "not found") { blastlocation = ""; }
496 //add / to name if needed
497 string lastChar = blastlocation.substr(blastlocation.length()-1);
498 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
499 if (lastChar != "/") { blastlocation += "/"; }
501 if (lastChar != "\\") { blastlocation += "\\"; }
503 blastlocation = m->getFullPathName(blastlocation);
504 string formatdbCommand = "";
505 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
506 formatdbCommand = blastlocation + "formatdb";
508 formatdbCommand = blastlocation + "formatdb.exe";
511 //test to make sure formatdb exists
513 formatdbCommand = m->getFullPathName(formatdbCommand);
514 int ableToOpen = m->openInputFile(formatdbCommand, in, "no error"); in.close();
515 if(ableToOpen == 1) { m->mothurOut("[ERROR]: " + formatdbCommand + " file does not exist. mothur requires formatdb.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
517 string blastCommand = "";
518 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
519 blastCommand = blastlocation + "megablast";
521 blastCommand = blastlocation + "megablast.exe";
523 //test to make sure formatdb exists
525 blastCommand = m->getFullPathName(blastCommand);
526 ableToOpen = m->openInputFile(blastCommand, in2, "no error"); in2.close();
527 if(ableToOpen == 1) { m->mothurOut("[ERROR]: " + blastCommand + " file does not exist. mothur requires blastall.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
530 if ((search != "blast") && (search != "kmer")) { m->mothurOut(search + " is not a valid search."); m->mothurOutEndLine(); abort = true; }
532 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; }
533 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; }
535 //until we resolve the issue 10-18-11
536 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
542 catch(exception& e) {
543 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
547 //***************************************************************************************************************
549 int ChimeraSlayerCommand::execute(){
551 if (abort == true) { if (calledHelp) { return 0; } return 2; }
553 for (int s = 0; s < fastaFileNames.size(); s++) {
555 m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
557 int start = time(NULL);
558 if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]); }//if user entered a file with a path then preserve it
559 string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimera";
560 string accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.accnos";
561 string trimFastaFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.fasta";
564 ofstream out, out1, out2;
565 m->openOutputFile(outputFileName, out); out.close();
566 m->openOutputFile(accnosFileName, out1); out1.close();
567 if (trim) { m->openOutputFile(trimFastaFileName, out2); out2.close(); }
568 outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
569 outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
570 if (trim) { outputNames.push_back(trimFastaFileName); outputTypes["fasta"].push_back(trimFastaFileName); }
572 //maps a filename to priority map.
573 //if no groupfile this is fastafileNames[s] -> prioirity
574 //if groupfile then this is each groups seqs -> priority
575 map<string, map<string, int> > fileToPriority;
576 map<string, map<string, int> >::iterator itFile;
577 map<string, string> fileGroup;
578 fileToPriority[fastaFileNames[s]] = priority; //default
579 fileGroup[fastaFileNames[s]] = "noGroup";
580 SequenceParser* parser = NULL;
581 int totalChimeras = 0;
584 if (templatefile == "self") { setUpForSelfReference(parser, fileGroup, fileToPriority, s); }
586 if (m->control_pressed) { if (parser != NULL) { delete parser; } for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]); } return 0; }
588 if (fileToPriority.size() == 1) { //you running without a groupfile
589 itFile = fileToPriority.begin();
590 string thisFastaName = itFile->first;
591 map<string, int> thisPriority = itFile->second;
593 MPIExecute(thisFastaName, outputFileName, accnosFileName, trimFastaFileName, thisPriority);
596 vector<unsigned long long> positions;
597 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
598 positions = m->divideFile(thisFastaName, processors);
599 for (int i = 0; i < (positions.size()-1); i++) { lines.push_back(linePair(positions[i], positions[(i+1)])); }
601 if (processors == 1) { lines.push_back(linePair(0, 1000)); }
603 positions = m->setFilePosFasta(thisFastaName, numSeqs);
605 //figure out how many sequences you have to process
606 int numSeqsPerProcessor = numSeqs / processors;
607 for (int i = 0; i < processors; i++) {
608 int startIndex = i * numSeqsPerProcessor;
609 if(i == (processors - 1)){ numSeqsPerProcessor = numSeqs - i * numSeqsPerProcessor; }
610 lines.push_back(linePair(positions[startIndex], numSeqsPerProcessor));
614 if(processors == 1){ numSeqs = driver(lines[0], outputFileName, thisFastaName, accnosFileName, trimFastaFileName, thisPriority); }
615 else{ numSeqs = createProcesses(outputFileName, thisFastaName, accnosFileName, trimFastaFileName, thisPriority); }
617 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; }
619 }else { //you have provided a groupfile
621 MPIExecuteGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup);
623 if (processors == 1) { numSeqs = driverGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup); }
624 else { numSeqs = createProcessesGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup); } //destroys fileToPriority
629 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
634 totalChimeras = deconvoluteResults(parser, outputFileName, accnosFileName, trimFastaFileName);
637 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
641 if (parser != NULL) { delete parser; }
643 m->mothurOutEndLine(); m->mothurOut(toString(totalChimeras) + " chimera found."); m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
646 //set accnos file as new current accnosfile
648 itTypes = outputTypes.find("accnos");
649 if (itTypes != outputTypes.end()) {
650 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
654 itTypes = outputTypes.find("fasta");
655 if (itTypes != outputTypes.end()) {
656 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
660 m->mothurOutEndLine();
661 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
662 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
663 m->mothurOutEndLine();
668 catch(exception& e) {
669 m->errorOut(e, "ChimeraSlayerCommand", "execute");
673 //**********************************************************************************************************************
674 int ChimeraSlayerCommand::MPIExecuteGroups(string outputFileName, string accnosFileName, string trimFastaFileName, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup){
681 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
682 MPI_Comm_size(MPI_COMM_WORLD, &processors);
684 //put filenames in a vector, then pass each process a starting and ending point in the vector
685 //all processes already have the fileToPriority and fileGroup, they just need to know which files to process
686 map<string, map<string, int> >::iterator itFile;
687 vector<string> filenames;
688 for(itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) { filenames.push_back(itFile->first); }
690 int numGroupsPerProcessor = filenames.size() / processors;
691 int startIndex = pid * numGroupsPerProcessor;
692 int endIndex = (pid+1) * numGroupsPerProcessor;
693 if(pid == (processors - 1)){ endIndex = filenames.size(); }
695 vector<unsigned long long> MPIPos;
698 MPI_File outMPIAccnos;
699 MPI_File outMPIFasta;
701 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
702 int inMode=MPI_MODE_RDONLY;
704 char outFilename[1024];
705 strcpy(outFilename, outputFileName.c_str());
707 char outAccnosFilename[1024];
708 strcpy(outAccnosFilename, accnosFileName.c_str());
710 char outFastaFilename[1024];
711 strcpy(outFastaFilename, trimFastaFileName.c_str());
713 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
714 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
715 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
717 if (m->control_pressed) { MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
720 if (pid == 0) { //you are the root process
721 m->mothurOutEndLine();
722 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
723 m->mothurOutEndLine();
725 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
728 int length = outTemp.length();
729 char* buf2 = new char[length];
730 memcpy(buf2, outTemp.c_str(), length);
732 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
735 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
737 for (int i = startIndex; i < endIndex; i++) {
739 int start = time(NULL);
741 string thisFastaName = filenames[i];
742 map<string, int> thisPriority = fileToPriority[thisFastaName];
744 char inFileName[1024];
745 strcpy(inFileName, thisFastaName.c_str());
747 MPI_File_open(MPI_COMM_SELF, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
749 MPIPos = m->setFilePosFasta(thisFastaName, num); //fills MPIPos, returns numSeqs
751 cout << endl << "Checking sequences from group: " << fileGroup[thisFastaName] << "." << endl;
753 driverMPI(0, num, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, thisFastaName, thisPriority, true);
756 MPI_File_close(&inMPI);
757 m->mothurRemove(thisFastaName);
759 cout << endl << "It took " << toString(time(NULL) - start) << " secs to check " + toString(num) + " sequences from group " << fileGroup[thisFastaName] << "." << endl;
763 for(int i = 1; i < processors; i++) {
765 MPI_Recv(&temp, 1, MPI_INT, i, 2001, MPI_COMM_WORLD, &status);
768 }else{ MPI_Send(&numSeqs, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD); }
770 MPI_File_close(&outMPI);
771 MPI_File_close(&outMPIAccnos);
772 if (trim) { MPI_File_close(&outMPIFasta); }
774 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
778 }catch(exception& e) {
779 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecuteGroups");
783 //**********************************************************************************************************************
784 int ChimeraSlayerCommand::MPIExecute(string inputFile, string outputFileName, string accnosFileName, string trimFastaFileName, map<string, int>& priority){
788 int pid, numSeqsPerProcessor;
790 vector<unsigned long long> MPIPos;
793 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
794 MPI_Comm_size(MPI_COMM_WORLD, &processors);
798 MPI_File outMPIAccnos;
799 MPI_File outMPIFasta;
801 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
802 int inMode=MPI_MODE_RDONLY;
804 char outFilename[1024];
805 strcpy(outFilename, outputFileName.c_str());
807 char outAccnosFilename[1024];
808 strcpy(outAccnosFilename, accnosFileName.c_str());
810 char outFastaFilename[1024];
811 strcpy(outFastaFilename, trimFastaFileName.c_str());
813 char inFileName[1024];
814 strcpy(inFileName, inputFile.c_str());
816 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
817 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
818 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
819 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
821 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
823 if (pid == 0) { //you are the root process
824 m->mothurOutEndLine();
825 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
826 m->mothurOutEndLine();
828 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
831 int length = outTemp.length();
832 char* buf2 = new char[length];
833 memcpy(buf2, outTemp.c_str(), length);
835 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
838 MPIPos = m->setFilePosFasta(inputFile, numSeqs); //fills MPIPos, returns numSeqs
840 if (templatefile != "self") { //if template=self we can only use 1 processor
841 //send file positions to all processes
842 for(int i = 1; i < processors; i++) {
843 MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
844 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
847 //figure out how many sequences you have to align
848 numSeqsPerProcessor = numSeqs / processors;
849 int startIndex = pid * numSeqsPerProcessor;
850 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
852 if (templatefile == "self") { //if template=self we can only use 1 processor
854 numSeqsPerProcessor = numSeqs;
858 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, inputFile, priority, false);
860 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
862 }else{ //you are a child process
863 if (templatefile != "self") { //if template=self we can only use 1 processor
864 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
865 MPIPos.resize(numSeqs+1);
866 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
868 //figure out how many sequences you have to align
869 numSeqsPerProcessor = numSeqs / processors;
870 int startIndex = pid * numSeqsPerProcessor;
871 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
874 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, inputFile, priority, false);
876 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
882 MPI_File_close(&inMPI);
883 MPI_File_close(&outMPI);
884 MPI_File_close(&outMPIAccnos);
885 if (trim) { MPI_File_close(&outMPIFasta); }
886 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
892 catch(exception& e) {
893 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecute");
897 //**********************************************************************************************************************
898 int ChimeraSlayerCommand::deconvoluteResults(SequenceParser* parser, string outputFileName, string accnosFileName, string trimFileName){
900 map<string, string> uniqueNames = parser->getAllSeqsMap();
901 map<string, string>::iterator itUnique;
906 m->openInputFile(accnosFileName, in2, "no error");
909 m->openOutputFile(accnosFileName+".temp", out2);
911 string name; name = "";
912 set<string> chimerasInFile;
913 set<string>::iterator itChimeras;
916 if (m->control_pressed) { in2.close(); out2.close(); m->mothurRemove(outputFileName); m->mothurRemove((accnosFileName+".temp")); return 0; }
918 in2 >> name; m->gobble(in2);
921 itUnique = uniqueNames.find(name);
923 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
925 itChimeras = chimerasInFile.find((itUnique->second));
927 if (itChimeras == chimerasInFile.end()) {
928 out2 << itUnique->second << endl;
929 chimerasInFile.insert((itUnique->second));
937 m->mothurRemove(accnosFileName);
938 rename((accnosFileName+".temp").c_str(), accnosFileName.c_str());
943 m->openInputFile(outputFileName, in);
946 m->openOutputFile(outputFileName+".temp", out); out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
948 string rest, parent1, parent2, line;
949 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
950 set<string>::iterator itNames;
952 //assumptions - in file each read will always look like...
955 F11Fcsw_63104 F11Fcsw_33372 F11Fcsw_37007 0.89441 80.4469 0.2 1.03727 93.2961 52.2 no 0-241 243-369
960 line = m->getline(in); m->gobble(in);
964 //for the chimera file, we want to make sure if any group finds a sequence to be chimeric then all groups do,
965 //so if this is a report that did not find it to be chimeric, but it appears in the accnos file,
966 //then ignore this report and continue until we find the report that found it to be chimeric
970 if (m->control_pressed) { in.close(); out.close(); m->mothurRemove((outputFileName+".temp")); return 0; }
972 in >> name; m->gobble(in);
973 in >> parent1; m->gobble(in);
975 if (name == "Name") { //name = "Name" because we append the header line each time we add results from the groups
976 line = m->getline(in); m->gobble(in);
978 if (parent1 == "no") {
980 itUnique = uniqueNames.find(name);
982 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
984 //is this sequence really not chimeric??
985 itChimeras = chimerasInFile.find(itUnique->second);
987 if (itChimeras == chimerasInFile.end()) {
988 //is this sequence not already in the file
989 itNames = namesInFile.find((itUnique->second));
991 if (itNames == namesInFile.end()) { out << itUnique->second << '\t' << "no" << endl; namesInFile.insert(itUnique->second); }
994 }else { //read the rest of the line
995 double DivQLAQRB,PerIDQLAQRB,BootStrapA,DivQLBQRA,PerIDQLBQRA,BootStrapB;
996 string flag, range1, range2;
998 in >> parent2 >> DivQLAQRB >> PerIDQLAQRB >> BootStrapA >> DivQLBQRA >> PerIDQLBQRA >> BootStrapB >> flag >> range1 >> range2; m->gobble(in);
1001 itUnique = uniqueNames.find(name);
1003 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1005 name = itUnique->second;
1006 //is this name already in the file
1007 itNames = namesInFile.find((name));
1009 if (itNames == namesInFile.end()) { //no not in file
1010 if (flag == "no") { //are you really a no??
1011 //is this sequence really not chimeric??
1012 itChimeras = chimerasInFile.find(name);
1014 //then you really are a no so print, otherwise skip
1015 if (itChimeras == chimerasInFile.end()) { print = true; }
1017 }else{ print = true; }
1022 out << name << '\t';
1024 namesInFile.insert(name);
1026 //output parent1's name
1027 itUnique = uniqueNames.find(parent1);
1028 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent1 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1029 else { out << itUnique->second << '\t'; }
1031 //output parent2's name
1032 itUnique = uniqueNames.find(parent2);
1033 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent2 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1034 else { out << itUnique->second << '\t'; }
1036 out << DivQLAQRB << '\t' << PerIDQLAQRB << '\t' << BootStrapA << '\t' << DivQLBQRA << '\t' << PerIDQLBQRA << '\t' << BootStrapB << '\t' << flag << '\t' << range1 << '\t' << range2 << endl;
1044 m->mothurRemove(outputFileName);
1045 rename((outputFileName+".temp").c_str(), outputFileName.c_str());
1050 m->openInputFile(trimFileName, in3);
1053 m->openOutputFile(trimFileName+".temp", out3);
1055 namesInFile.clear();
1057 while (!in3.eof()) {
1058 if (m->control_pressed) { in3.close(); out3.close(); m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); m->mothurRemove((trimFileName+".temp")); return 0; }
1060 Sequence seq(in3); m->gobble(in3);
1062 if (seq.getName() != "") {
1064 itUnique = uniqueNames.find(seq.getName());
1066 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ seq.getName() + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1068 itNames = namesInFile.find((itUnique->second));
1070 if (itNames == namesInFile.end()) {
1071 seq.printSequence(out3);
1079 m->mothurRemove(trimFileName);
1080 rename((trimFileName+".temp").c_str(), trimFileName.c_str());
1085 catch(exception& e) {
1086 m->errorOut(e, "ChimeraSlayerCommand", "deconvoluteResults");
1090 //**********************************************************************************************************************
1091 int ChimeraSlayerCommand::setUpForSelfReference(SequenceParser*& parser, map<string, string>& fileGroup, map<string, map<string, int> >& fileToPriority, int s){
1094 fileToPriority.clear();
1096 string nameFile = "";
1097 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
1098 nameFile = nameFileNames[s];
1099 }else { nameFile = getNamesFile(fastaFileNames[s]); }
1101 //you provided a groupfile
1102 string groupFile = "";
1103 if (groupFileNames.size() != 0) { groupFile = groupFileNames[s]; }
1105 if (groupFile == "") {
1106 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
1108 //sort fastafile by abundance, returns new sorted fastafile name
1109 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush();
1110 priority = sortFastaFile(fastaFileNames[s], nameFile);
1111 m->mothurOut("Done."); m->mothurOutEndLine();
1113 fileToPriority[fastaFileNames[s]] = priority;
1114 fileGroup[fastaFileNames[s]] = "noGroup";
1116 //Parse sequences by group
1117 parser = new SequenceParser(groupFile, fastaFileNames[s], nameFile);
1118 vector<string> groups = parser->getNamesOfGroups();
1120 for (int i = 0; i < groups.size(); i++) {
1121 vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
1122 map<string, string> thisGroupsMap = parser->getNameMap(groups[i]);
1123 string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
1124 priority = sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile);
1125 fileToPriority[newFastaFile] = priority;
1126 fileGroup[newFastaFile] = groups[i];
1133 catch(exception& e) {
1134 m->errorOut(e, "ChimeraSlayerCommand", "setUpForSelfReference");
1139 //**********************************************************************************************************************
1140 string ChimeraSlayerCommand::getNamesFile(string& inputFile){
1142 string nameFile = "";
1144 m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
1146 //use unique.seqs to create new name and fastafile
1147 string inputString = "fasta=" + inputFile;
1148 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
1149 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine();
1151 Command* uniqueCommand = new DeconvoluteCommand(inputString);
1152 uniqueCommand->execute();
1154 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
1156 delete uniqueCommand;
1158 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
1160 nameFile = filenames["name"][0];
1161 inputFile = filenames["fasta"][0];
1165 catch(exception& e) {
1166 m->errorOut(e, "ChimeraSlayerCommand", "getNamesFile");
1170 //**********************************************************************************************************************
1172 int ChimeraSlayerCommand::driverGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup){
1176 for (map<string, map<string, int> >::iterator itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) {
1178 if (m->control_pressed) { return 0; }
1180 int start = time(NULL);
1181 string thisFastaName = itFile->first;
1182 map<string, int> thisPriority = itFile->second;
1183 string thisoutputFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.chimera";
1184 string thisaccnosFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.accnos";
1185 string thistrimFastaFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.fasta";
1187 m->mothurOutEndLine(); m->mothurOut("Checking sequences from group: " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine();
1190 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1192 vector<unsigned long long> positions = m->divideFile(thisFastaName, proc);
1193 lines.push_back(linePair(positions[0], positions[1]));
1195 lines.push_back(linePair(0, 1000));
1197 int numSeqs = driver(lines[0], thisoutputFileName, thisFastaName, thisaccnosFileName, thistrimFastaFileName, thisPriority);
1200 m->appendFiles(thisoutputFileName, outputFName); m->mothurRemove(thisoutputFileName);
1201 m->appendFiles(thisaccnosFileName, accnos); m->mothurRemove(thisaccnosFileName);
1202 if (trim) { m->appendFiles(thistrimFastaFileName, fasta); m->mothurRemove(thistrimFastaFileName); }
1203 m->mothurRemove(thisFastaName);
1205 totalSeqs += numSeqs;
1207 m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences from group " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine();
1212 catch(exception& e) {
1213 m->errorOut(e, "ChimeraSlayerCommand", "driverGroups");
1217 /**************************************************************************************************/
1218 int ChimeraSlayerCommand::createProcessesGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup) {
1224 if (fileToPriority.size() < processors) { processors = fileToPriority.size(); }
1226 int groupsPerProcessor = fileToPriority.size() / processors;
1227 int remainder = fileToPriority.size() % processors;
1229 vector< map<string, map<string, int> > > breakUp;
1231 for (int i = 0; i < processors; i++) {
1232 map<string, map<string, int> > thisFileToPriority;
1233 map<string, map<string, int> >::iterator itFile;
1235 int enough = groupsPerProcessor;
1236 if (i == 0) { enough = groupsPerProcessor + remainder; }
1238 for (itFile = fileToPriority.begin(); itFile != fileToPriority.end();) {
1239 thisFileToPriority[itFile->first] = itFile->second;
1240 fileToPriority.erase(itFile++);
1242 if (count == enough) { break; }
1244 breakUp.push_back(thisFileToPriority);
1247 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1248 //loop through and create all the processes you want
1249 while (process != processors) {
1253 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
1255 }else if (pid == 0){
1256 num = driverGroups(outputFName + toString(getpid()) + ".temp", accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", breakUp[process], fileGroup);
1258 //pass numSeqs to parent
1260 string tempFile = outputFName + toString(getpid()) + ".num.temp";
1261 m->openOutputFile(tempFile, out);
1266 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
1267 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1272 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup);
1274 //force parent to wait until all the processes are done
1275 for (int i=0;i<processors;i++) {
1276 int temp = processIDS[i];
1280 for (int i = 0; i < processIDS.size(); i++) {
1282 string tempFile = outputFName + toString(processIDS[i]) + ".num.temp";
1283 m->openInputFile(tempFile, in);
1284 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
1285 in.close(); m->mothurRemove(tempFile);
1289 //////////////////////////////////////////////////////////////////////////////////////////////////////
1290 //Windows version shared memory, so be careful when passing variables through the slayerData struct.
1291 //Above fork() will clone, so memory is separate, but that's not the case with windows,
1292 //////////////////////////////////////////////////////////////////////////////////////////////////////
1294 vector<slayerData*> pDataArray;
1295 DWORD dwThreadIdArray[processors-1];
1296 HANDLE hThreadArray[processors-1];
1298 //Create processor worker threads.
1299 for(int i=1; i<processors; i++ ){
1300 string extension = toString(i) + ".temp";
1301 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);
1302 pDataArray.push_back(tempslayer);
1303 processIDS.push_back(i);
1305 //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
1306 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1307 hThreadArray[i-1] = CreateThread(NULL, 0, MySlayerGroupThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);
1310 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup);
1312 //Wait until all threads have terminated.
1313 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
1315 //Close all thread handles and free memory allocations.
1316 for(int i=0; i < pDataArray.size(); i++){
1317 num += pDataArray[i]->count;
1318 CloseHandle(hThreadArray[i]);
1319 delete pDataArray[i];
1323 //append output files
1324 for(int i=0;i<processIDS.size();i++){
1325 m->appendFiles((outputFName + toString(processIDS[i]) + ".temp"), outputFName);
1326 m->mothurRemove((outputFName + toString(processIDS[i]) + ".temp"));
1328 m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1329 m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1332 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
1333 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
1340 catch(exception& e) {
1341 m->errorOut(e, "ChimeraSlayerCommand", "createProcessesGroups");
1345 //**********************************************************************************************************************
1347 int ChimeraSlayerCommand::driver(linePair filePos, string outputFName, string filename, string accnos, string fasta, map<string, int>& priority){
1351 if (templatefile != "self") { //you want to run slayer with a reference template
1352 chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1354 chimera = new ChimeraSlayer(filename, templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1357 if (m->control_pressed) { delete chimera; return 0; }
1359 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1360 templateSeqsLength = chimera->getLength();
1363 m->openOutputFile(outputFName, out);
1366 m->openOutputFile(accnos, out2);
1369 if (trim) { m->openOutputFile(fasta, out3); }
1372 m->openInputFile(filename, inFASTA);
1374 inFASTA.seekg(filePos.start);
1376 if (filePos.start == 0) { chimera->printHeader(out); }
1383 if (m->control_pressed) { delete chimera; out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1; }
1385 Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
1386 string candidateAligned = candidateSeq->getAligned();
1388 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1389 if (candidateSeq->getAligned().length() != templateSeqsLength) {
1390 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1393 chimera->getChimeras(candidateSeq);
1395 if (m->control_pressed) { delete chimera; delete candidateSeq; return 1; }
1397 //if you are not chimeric, then check each half
1398 data_results wholeResults = chimera->getResults();
1400 //determine if we need to split
1401 bool isChimeric = false;
1403 if (wholeResults.flag == "yes") {
1404 string chimeraFlag = "no";
1405 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1407 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1410 if (chimeraFlag == "yes") {
1411 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1415 if ((!isChimeric) && trimera) {
1417 //split sequence in half by bases
1418 string leftQuery, rightQuery;
1419 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1420 divideInHalf(tempSeq, leftQuery, rightQuery);
1422 //run chimeraSlayer on each piece
1423 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1424 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1427 chimera->getChimeras(left);
1428 data_results leftResults = chimera->getResults();
1430 chimera->getChimeras(right);
1431 data_results rightResults = chimera->getResults();
1433 //if either piece is chimeric then report
1434 Sequence trimmed = chimera->print(out, out2, leftResults, rightResults);
1435 if (trim) { trimmed.printSequence(out3); }
1437 delete left; delete right;
1439 }else { //already chimeric
1441 Sequence trimmed = chimera->print(out, out2);
1442 if (trim) { trimmed.printSequence(out3); }
1450 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1451 unsigned long long pos = inFASTA.tellg();
1452 if ((pos == -1) || (pos >= filePos.end)) { break; }
1454 if (inFASTA.eof()) { break; }
1457 delete candidateSeq;
1459 if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
1462 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
1464 int numNoParents = chimera->getNumNoParents();
1465 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(); }
1469 if (trim) { out3.close(); }
1477 catch(exception& e) {
1478 m->errorOut(e, "ChimeraSlayerCommand", "driver");
1482 //**********************************************************************************************************************
1484 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){
1488 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1491 if (templatefile != "self") { //you want to run slayer with a reference template
1492 chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1494 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);
1497 if (m->control_pressed) { delete chimera; return 0; }
1499 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1500 templateSeqsLength = chimera->getLength();
1502 for(int i=0;i<num;i++){
1504 if (m->control_pressed) { delete chimera; return 1; }
1506 //read next sequence
1507 int length = MPIPos[start+i+1] - MPIPos[start+i];
1509 char* buf4 = new char[length];
1510 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
1512 string tempBuf = buf4;
1513 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
1514 istringstream iss (tempBuf,istringstream::in);
1518 Sequence* candidateSeq = new Sequence(iss); m->gobble(iss);
1519 string candidateAligned = candidateSeq->getAligned();
1521 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1523 if (candidateSeq->getAligned().length() != templateSeqsLength) {
1524 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1528 chimera->getChimeras(candidateSeq);
1530 if (m->control_pressed) { delete chimera; delete candidateSeq; return 1; }
1532 //if you are not chimeric, then check each half
1533 data_results wholeResults = chimera->getResults();
1535 //determine if we need to split
1536 bool isChimeric = false;
1538 if (wholeResults.flag == "yes") {
1539 string chimeraFlag = "no";
1540 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1542 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1545 if (chimeraFlag == "yes") {
1546 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1550 if ((!isChimeric) && trimera) {
1551 //split sequence in half by bases
1552 string leftQuery, rightQuery;
1553 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1554 divideInHalf(tempSeq, leftQuery, rightQuery);
1556 //run chimeraSlayer on each piece
1557 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1558 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1561 chimera->getChimeras(left);
1562 data_results leftResults = chimera->getResults();
1564 chimera->getChimeras(right);
1565 data_results rightResults = chimera->getResults();
1567 //if either piece is chimeric then report
1568 Sequence trimmed = chimera->print(outMPI, outAccMPI, leftResults, rightResults);
1570 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1572 //write to accnos file
1573 int length = outputString.length();
1574 char* buf2 = new char[length];
1575 memcpy(buf2, outputString.c_str(), length);
1577 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1581 delete left; delete right;
1585 Sequence trimmed = chimera->print(outMPI, outAccMPI);
1588 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1590 //write to accnos file
1591 int length = outputString.length();
1592 char* buf2 = new char[length];
1593 memcpy(buf2, outputString.c_str(), length);
1595 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1602 delete candidateSeq;
1605 if((i+1) % 100 == 0){ cout << "Processing sequence: " << (i+1) << endl; m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n"); }
1608 if(num % 100 != 0){ cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n"); }
1610 int numNoParents = chimera->getNumNoParents();
1611 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; }
1616 catch(exception& e) {
1617 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
1623 /**************************************************************************************************/
1625 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta, map<string, int>& thisPriority) {
1631 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1632 //loop through and create all the processes you want
1633 while (process != processors) {
1637 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
1639 }else if (pid == 0){
1640 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", thisPriority);
1642 //pass numSeqs to parent
1644 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
1645 m->openOutputFile(tempFile, out);
1650 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
1651 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1656 //force parent to wait until all the processes are done
1657 for (int i=0;i<processors;i++) {
1658 int temp = processIDS[i];
1662 for (int i = 0; i < processIDS.size(); i++) {
1664 string tempFile = outputFileName + toString(processIDS[i]) + ".num.temp";
1665 m->openInputFile(tempFile, in);
1666 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
1667 in.close(); m->mothurRemove(tempFile);
1671 //////////////////////////////////////////////////////////////////////////////////////////////////////
1672 //Windows version shared memory, so be careful when passing variables through the slayerData struct.
1673 //Above fork() will clone, so memory is separate, but that's not the case with windows,
1674 //////////////////////////////////////////////////////////////////////////////////////////////////////
1676 vector<slayerData*> pDataArray;
1677 DWORD dwThreadIdArray[processors];
1678 HANDLE hThreadArray[processors];
1680 //Create processor worker threads.
1681 for( int i=0; i<processors; i++ ){
1682 string extension = toString(i) + ".temp";
1683 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);
1684 pDataArray.push_back(tempslayer);
1685 processIDS.push_back(i);
1687 //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
1688 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1689 hThreadArray[i] = CreateThread(NULL, 0, MySlayerThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);
1692 //Wait until all threads have terminated.
1693 WaitForMultipleObjects(processors, hThreadArray, TRUE, INFINITE);
1695 //Close all thread handles and free memory allocations.
1696 for(int i=0; i < pDataArray.size(); i++){
1697 num += pDataArray[i]->count;
1698 CloseHandle(hThreadArray[i]);
1699 delete pDataArray[i];
1703 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
1704 rename((accnos + toString(processIDS[0]) + ".temp").c_str(), accnos.c_str());
1705 if (trim) { rename((fasta + toString(processIDS[0]) + ".temp").c_str(), fasta.c_str()); }
1707 //append output files
1708 for(int i=1;i<processIDS.size();i++){
1709 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
1710 m->mothurRemove((outputFileName + toString(processIDS[i]) + ".temp"));
1712 m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1713 m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1716 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
1717 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
1724 catch(exception& e) {
1725 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
1730 /**************************************************************************************************/
1732 int ChimeraSlayerCommand::divideInHalf(Sequence querySeq, string& leftQuery, string& rightQuery) {
1735 string queryUnAligned = querySeq.getUnaligned();
1736 int numBases = int(queryUnAligned.length() * 0.5);
1738 string queryAligned = querySeq.getAligned();
1739 leftQuery = querySeq.getAligned();
1740 rightQuery = querySeq.getAligned();
1744 for (int i = 0; i < queryAligned.length(); i++) {
1746 if (isalpha(queryAligned[i])) {
1751 if (baseCount >= numBases) { leftSpot = i; break; } //first half
1754 //blank out right side
1755 for (int i = leftSpot; i < leftQuery.length(); i++) { leftQuery[i] = '.'; }
1757 //blank out left side
1758 for (int i = 0; i < leftSpot; i++) { rightQuery[i] = '.'; }
1763 catch(exception& e) {
1764 m->errorOut(e, "ChimeraSlayerCommand", "divideInHalf");
1768 /**************************************************************************************************/
1769 map<string, int> ChimeraSlayerCommand::sortFastaFile(string fastaFile, string nameFile) {
1771 map<string, int> nameAbund;
1773 //read through fastafile and store info
1774 map<string, string> seqs;
1776 m->openInputFile(fastaFile, in);
1780 if (m->control_pressed) { in.close(); return nameAbund; }
1782 Sequence seq(in); m->gobble(in);
1783 seqs[seq.getName()] = seq.getAligned();
1789 vector<seqPriorityNode> nameMapCount;
1790 int error = m->readNames(nameFile, nameMapCount, seqs);
1792 if (m->control_pressed) { return nameAbund; }
1794 if (error == 1) { m->control_pressed = true; return nameAbund; }
1795 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; }
1797 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
1799 string newFasta = fastaFile + ".temp";
1801 m->openOutputFile(newFasta, out);
1803 //print new file in order of
1804 for (int i = 0; i < nameMapCount.size(); i++) {
1805 out << ">" << nameMapCount[i].name << endl << nameMapCount[i].seq << endl;
1806 nameAbund[nameMapCount[i].name] = nameMapCount[i].numIdentical;
1810 rename(newFasta.c_str(), fastaFile.c_str());
1815 catch(exception& e) {
1816 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
1820 /**************************************************************************************************/
1821 map<string, int> ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, string>& nameMap, string newFile) {
1823 map<string, int> nameAbund;
1824 vector<seqPriorityNode> nameVector;
1826 //read through fastafile and store info
1827 map<string, string> seqs;
1829 for (int i = 0; i < thisseqs.size(); i++) {
1831 if (m->control_pressed) { return nameAbund; }
1833 map<string, string>::iterator itNameMap = nameMap.find(thisseqs[i].getName());
1835 if (itNameMap == nameMap.end()){
1836 m->control_pressed = true;
1837 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your namesfile, please correct."); m->mothurOutEndLine();
1839 int num = m->getNumNames(itNameMap->second);
1841 seqPriorityNode temp(num, thisseqs[i].getAligned(), thisseqs[i].getName());
1842 nameVector.push_back(temp);
1846 //sort by num represented
1847 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
1849 if (m->control_pressed) { return nameAbund; }
1851 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; }
1854 m->openOutputFile(newFile, out);
1856 //print new file in order of
1857 for (int i = 0; i < nameVector.size(); i++) {
1858 out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
1859 nameAbund[nameVector[i].name] = nameVector[i].numIdentical;
1866 catch(exception& e) {
1867 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
1871 /**************************************************************************************************/