2 * chimeraslayercommand.cpp
5 * Created by westcott on 3/31/10.
6 * Copyright 2010 Schloss Lab. All rights reserved.
10 #include "chimeraslayercommand.h"
11 #include "deconvolutecommand.h"
12 #include "referencedb.h"
13 #include "sequenceparser.h"
14 #include "counttable.h"
16 //**********************************************************************************************************************
17 vector<string> ChimeraSlayerCommand::setParameters(){
19 CommandParameter ptemplate("reference", "InputTypes", "", "", "none", "none", "none","",false,true,true); parameters.push_back(ptemplate);
20 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none","chimera-accnos",false,true,true); parameters.push_back(pfasta);
21 CommandParameter pname("name", "InputTypes", "", "", "NameCount", "none", "none","",false,false,true); parameters.push_back(pname);
22 CommandParameter pcount("count", "InputTypes", "", "", "NameCount-CountGroup", "none", "none","",false,false,true); parameters.push_back(pcount);
23 CommandParameter pgroup("group", "InputTypes", "", "", "CountGroup", "none", "none","",false,false,true); parameters.push_back(pgroup);
24 CommandParameter pwindow("window", "Number", "", "50", "", "", "","",false,false); parameters.push_back(pwindow);
25 CommandParameter pksize("ksize", "Number", "", "7", "", "", "","",false,false); parameters.push_back(pksize);
26 CommandParameter pmatch("match", "Number", "", "5.0", "", "", "","",false,false); parameters.push_back(pmatch);
27 CommandParameter pmismatch("mismatch", "Number", "", "-4.0", "", "", "","",false,false); parameters.push_back(pmismatch);
28 CommandParameter pminsim("minsim", "Number", "", "90", "", "", "","",false,false); parameters.push_back(pminsim);
29 CommandParameter pmincov("mincov", "Number", "", "70", "", "", "","",false,false); parameters.push_back(pmincov);
30 CommandParameter pminsnp("minsnp", "Number", "", "10", "", "", "","",false,false); parameters.push_back(pminsnp);
31 CommandParameter pminbs("minbs", "Number", "", "90", "", "", "","",false,false); parameters.push_back(pminbs);
32 CommandParameter psearch("search", "Multiple", "kmer-blast", "blast", "", "", "","",false,false); parameters.push_back(psearch);
33 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "","",false,false,true); parameters.push_back(pprocessors);
34 CommandParameter prealign("realign", "Boolean", "", "T", "", "", "","",false,false); parameters.push_back(prealign);
35 CommandParameter ptrim("trim", "Boolean", "", "F", "", "", "","fasta",false,false); parameters.push_back(ptrim);
36 CommandParameter psplit("split", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(psplit);
37 CommandParameter pnumwanted("numwanted", "Number", "", "15", "", "", "","",false,false); parameters.push_back(pnumwanted);
38 CommandParameter piters("iters", "Number", "", "1000", "", "", "","",false,false); parameters.push_back(piters);
39 CommandParameter pdivergence("divergence", "Number", "", "1.007", "", "", "","",false,false); parameters.push_back(pdivergence);
40 CommandParameter pparents("parents", "Number", "", "3", "", "", "","",false,false); parameters.push_back(pparents);
41 CommandParameter pincrement("increment", "Number", "", "5", "", "", "","",false,false); parameters.push_back(pincrement);
42 CommandParameter pblastlocation("blastlocation", "String", "", "", "", "", "","",false,false); parameters.push_back(pblastlocation);
43 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
44 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
45 CommandParameter psave("save", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(psave);
47 vector<string> myArray;
48 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
52 m->errorOut(e, "ChimeraSlayerCommand", "setParameters");
56 //**********************************************************************************************************************
57 string ChimeraSlayerCommand::getHelpString(){
59 string helpString = "";
60 helpString += "The chimera.slayer command reads a fastafile and referencefile and outputs potentially chimeric sequences.\n";
61 helpString += "This command was modeled after the chimeraSlayer written by the Broad Institute.\n";
62 helpString += "The chimera.slayer command parameters are fasta, name, group, template, processors, trim, ksize, window, match, mismatch, divergence. minsim, mincov, minbs, minsnp, parents, search, iters, increment, numwanted, blastlocation and realign.\n";
63 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";
64 helpString += "The name parameter allows you to provide a name file, if you are using reference=self. \n";
65 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";
66 helpString += "The count parameter allows you to provide a count file. The count file reference=self. If your count file contains group information, when checking sequences, only sequences from the same group as the query sequence will be used as the reference. \n";
67 helpString += "You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amazon.fasta \n";
68 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";
69 helpString += "The processors parameter allows you to specify how many processors you would like to use. The default is 1. \n";
71 helpString += "When using MPI, the processors parameter is set to the number of MPI processes running. \n";
73 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";
74 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";
75 helpString += "The window parameter allows you to specify the window size for searching for chimeras, default=50. \n";
76 helpString += "The increment parameter allows you to specify how far you move each window while finding chimeric sequences, default=5.\n";
77 helpString += "The numwanted parameter allows you to specify how many sequences you would each query sequence compared with, default=15.\n";
78 helpString += "The ksize parameter allows you to input kmersize, default is 7, used if search is kmer. \n";
79 helpString += "The match parameter allows you to reward matched bases in blast search, default is 5. \n";
80 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";
81 helpString += "The mismatch parameter allows you to penalize mismatched bases in blast search, default is -4. \n";
82 helpString += "The divergence parameter allows you to set a cutoff for chimera determination, default is 1.007. \n";
83 helpString += "The iters parameter allows you to specify the number of bootstrap iters to do with the chimeraslayer method, default=1000.\n";
84 helpString += "The minsim parameter allows you to specify a minimum similarity with the parent fragments, default=90. \n";
85 helpString += "The mincov parameter allows you to specify minimum coverage by closest matches found in template. Default is 70, meaning 70%. \n";
86 helpString += "The minbs parameter allows you to specify minimum bootstrap support for calling a sequence chimeric. Default is 90, meaning 90%. \n";
87 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";
88 helpString += "The search parameter allows you to specify search method for finding the closest parent. Choices are blast, and kmer, default blast. \n";
89 helpString += "The realign parameter allows you to realign the query to the potential parents. Choices are true or false, default true. \n";
90 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";
91 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.";
92 helpString += "The chimera.slayer command should be in the following format: \n";
93 helpString += "chimera.slayer(fasta=yourFastaFile, reference=yourTemplate, search=yourSearch) \n";
94 helpString += "Example: chimera.slayer(fasta=AD.align, reference=core_set_aligned.imputed.fasta, search=kmer) \n";
95 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";
99 m->errorOut(e, "ChimeraSlayerCommand", "getHelpString");
103 //**********************************************************************************************************************
104 string ChimeraSlayerCommand::getOutputPattern(string type) {
108 if (type == "chimera") { pattern = "[filename],slayer.chimeras"; }
109 else if (type == "accnos") { pattern = "[filename],slayer.accnos"; }
110 else if (type == "fasta") { pattern = "[filename],slayer.fasta"; }
111 else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true; }
115 catch(exception& e) {
116 m->errorOut(e, "ChimeraSlayerCommand", "getOutputPattern");
120 //**********************************************************************************************************************
121 ChimeraSlayerCommand::ChimeraSlayerCommand(){
123 abort = true; calledHelp = true;
125 vector<string> tempOutNames;
126 outputTypes["chimera"] = tempOutNames;
127 outputTypes["accnos"] = tempOutNames;
128 outputTypes["fasta"] = tempOutNames;
130 catch(exception& e) {
131 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
135 //***************************************************************************************************************
136 ChimeraSlayerCommand::ChimeraSlayerCommand(string option) {
138 abort = false; calledHelp = false;
139 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
250 namefile = validParameter.validFile(parameters, "name", false);
251 if (namefile == "not found") { namefile = ""; }
253 m->splitAtDash(namefile, nameFileNames);
255 //go through files and make sure they are good, if not, then disregard them
256 for (int i = 0; i < nameFileNames.size(); i++) {
259 if (nameFileNames[i] == "current") {
260 nameFileNames[i] = m->getNameFile();
261 if (nameFileNames[i] != "") { m->mothurOut("Using " + nameFileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
263 m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true;
264 //erase from file list
265 nameFileNames.erase(nameFileNames.begin()+i);
272 if (inputDir != "") {
273 string path = m->hasPath(nameFileNames[i]);
274 //if the user has not given a path then, add inputdir. else leave path alone.
275 if (path == "") { nameFileNames[i] = inputDir + nameFileNames[i]; }
281 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
283 //if you can't open it, try default location
284 if (ableToOpen == 1) {
285 if (m->getDefaultPath() != "") { //default path is set
286 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
287 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
289 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
291 nameFileNames[i] = tryPath;
295 if (ableToOpen == 1) {
296 if (m->getOutputDir() != "") { //default path is set
297 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
298 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
300 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
302 nameFileNames[i] = tryPath;
308 if (ableToOpen == 1) {
309 m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
310 //erase from file list
311 nameFileNames.erase(nameFileNames.begin()+i);
314 m->setNameFile(nameFileNames[i]);
320 if (nameFileNames.size() != 0) { hasName = true; }
322 //check for required parameters
323 vector<string> countfileNames;
324 countfile = validParameter.validFile(parameters, "count", false);
325 if (countfile == "not found") {
328 m->splitAtDash(countfile, countfileNames);
330 //go through files and make sure they are good, if not, then disregard them
331 for (int i = 0; i < countfileNames.size(); i++) {
334 if (countfileNames[i] == "current") {
335 countfileNames[i] = m->getCountTableFile();
336 if (nameFileNames[i] != "") { m->mothurOut("Using " + countfileNames[i] + " as input file for the count parameter where you had given current."); m->mothurOutEndLine(); }
338 m->mothurOut("You have no current count file, ignoring current."); m->mothurOutEndLine(); ignore=true;
339 //erase from file list
340 countfileNames.erase(countfileNames.begin()+i);
347 if (inputDir != "") {
348 string path = m->hasPath(countfileNames[i]);
349 //if the user has not given a path then, add inputdir. else leave path alone.
350 if (path == "") { countfileNames[i] = inputDir + countfileNames[i]; }
356 ableToOpen = m->openInputFile(countfileNames[i], in, "noerror");
358 //if you can't open it, try default location
359 if (ableToOpen == 1) {
360 if (m->getDefaultPath() != "") { //default path is set
361 string tryPath = m->getDefaultPath() + m->getSimpleName(countfileNames[i]);
362 m->mothurOut("Unable to open " + countfileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
364 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
366 countfileNames[i] = tryPath;
370 if (ableToOpen == 1) {
371 if (m->getOutputDir() != "") { //default path is set
372 string tryPath = m->getOutputDir() + m->getSimpleName(countfileNames[i]);
373 m->mothurOut("Unable to open " + countfileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
375 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
377 countfileNames[i] = tryPath;
383 if (ableToOpen == 1) {
384 m->mothurOut("Unable to open " + countfileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
385 //erase from file list
386 countfileNames.erase(countfileNames.begin()+i);
389 m->setCountTableFile(countfileNames[i]);
395 if (countfileNames.size() != 0) { hasCount = true; }
397 //make sure there is at least one valid file left
398 if (hasName && hasCount) { m->mothurOut("[ERROR]: You must enter ONLY ONE of the following: count or name."); m->mothurOutEndLine(); abort = true; }
400 if (!hasName && hasCount) { nameFileNames = countfileNames; }
402 if ((hasCount || hasName) && (nameFileNames.size() != fastaFileNames.size())) { m->mothurOut("[ERROR]: The number of name or count files does not match the number of fastafiles, please correct."); m->mothurOutEndLine(); abort=true; }
404 bool hasGroup = true;
405 groupfile = validParameter.validFile(parameters, "group", false);
406 if (groupfile == "not found") { groupfile = ""; hasGroup = false; }
408 m->splitAtDash(groupfile, groupFileNames);
410 //go through files and make sure they are good, if not, then disregard them
411 for (int i = 0; i < groupFileNames.size(); i++) {
414 if (groupFileNames[i] == "current") {
415 groupFileNames[i] = m->getGroupFile();
416 if (groupFileNames[i] != "") { m->mothurOut("Using " + groupFileNames[i] + " as input file for the group parameter where you had given current."); m->mothurOutEndLine(); }
418 m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true;
419 //erase from file list
420 groupFileNames.erase(groupFileNames.begin()+i);
427 if (inputDir != "") {
428 string path = m->hasPath(groupFileNames[i]);
429 //if the user has not given a path then, add inputdir. else leave path alone.
430 if (path == "") { groupFileNames[i] = inputDir + groupFileNames[i]; }
436 ableToOpen = m->openInputFile(groupFileNames[i], in, "noerror");
438 //if you can't open it, try default location
439 if (ableToOpen == 1) {
440 if (m->getDefaultPath() != "") { //default path is set
441 string tryPath = m->getDefaultPath() + m->getSimpleName(groupFileNames[i]);
442 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
444 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
446 groupFileNames[i] = tryPath;
450 if (ableToOpen == 1) {
451 if (m->getOutputDir() != "") { //default path is set
452 string tryPath = m->getOutputDir() + m->getSimpleName(groupFileNames[i]);
453 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
455 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
457 groupFileNames[i] = tryPath;
463 if (ableToOpen == 1) {
464 m->mothurOut("Unable to open " + groupFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
465 //erase from file list
466 groupFileNames.erase(groupFileNames.begin()+i);
469 m->setGroupFile(groupFileNames[i]);
474 //make sure there is at least one valid file left
475 if (groupFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid group files."); m->mothurOutEndLine(); abort = true; }
478 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; }
480 if (hasGroup && hasCount) { m->mothurOut("[ERROR]: You must enter ONLY ONE of the following: count or group."); m->mothurOutEndLine(); abort = true; }
481 //if the user changes the output directory command factory will send this info to us in the output parameter
482 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
484 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
485 m->setProcessors(temp);
486 m->mothurConvert(temp, processors);
488 temp = validParameter.validFile(parameters, "save", false); if (temp == "not found"){ temp = "f"; }
489 save = m->isTrue(temp);
491 if (save) { //clear out old references
496 it = parameters.find("reference");
497 //user has given a template file
498 if(it != parameters.end()){
499 if (it->second == "self") {
500 templatefile = "self";
502 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save.");
503 m->mothurOutEndLine();
508 path = m->hasPath(it->second);
509 //if the user has not given a path then, add inputdir. else leave path alone.
510 if (path == "") { parameters["reference"] = inputDir + it->second; }
512 templatefile = validParameter.validFile(parameters, "reference", true);
513 if (templatefile == "not open") { abort = true; }
514 else if (templatefile == "not found") { //check for saved reference sequences
515 if (rdb->referenceSeqs.size() != 0) {
516 templatefile = "saved";
518 m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required.");
519 m->mothurOutEndLine();
522 }else { if (save) { rdb->setSavedReference(templatefile); } }
524 }else if (hasName) { templatefile = "self";
526 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save.");
527 m->mothurOutEndLine();
530 }else if (hasCount) { templatefile = "self";
532 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save.");
533 m->mothurOutEndLine();
538 if (rdb->referenceSeqs.size() != 0) {
539 templatefile = "saved";
541 m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required.");
542 m->mothurOutEndLine();
543 templatefile = ""; abort = true;
549 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found") { temp = "7"; }
550 m->mothurConvert(temp, ksize);
552 temp = validParameter.validFile(parameters, "window", false); if (temp == "not found") { temp = "50"; }
553 m->mothurConvert(temp, window);
555 temp = validParameter.validFile(parameters, "match", false); if (temp == "not found") { temp = "5"; }
556 m->mothurConvert(temp, match);
558 temp = validParameter.validFile(parameters, "mismatch", false); if (temp == "not found") { temp = "-4"; }
559 m->mothurConvert(temp, mismatch);
561 temp = validParameter.validFile(parameters, "divergence", false); if (temp == "not found") { temp = "1.007"; }
562 m->mothurConvert(temp, divR);
564 temp = validParameter.validFile(parameters, "minsim", false); if (temp == "not found") { temp = "90"; }
565 m->mothurConvert(temp, minSimilarity);
567 temp = validParameter.validFile(parameters, "mincov", false); if (temp == "not found") { temp = "70"; }
568 m->mothurConvert(temp, minCoverage);
570 temp = validParameter.validFile(parameters, "minbs", false); if (temp == "not found") { temp = "90"; }
571 m->mothurConvert(temp, minBS);
573 temp = validParameter.validFile(parameters, "minsnp", false); if (temp == "not found") { temp = "10"; }
574 m->mothurConvert(temp, minSNP);
576 temp = validParameter.validFile(parameters, "parents", false); if (temp == "not found") { temp = "3"; }
577 m->mothurConvert(temp, parents);
579 temp = validParameter.validFile(parameters, "realign", false); if (temp == "not found") { temp = "t"; }
580 realign = m->isTrue(temp);
582 temp = validParameter.validFile(parameters, "trim", false); if (temp == "not found") { temp = "f"; }
583 trim = m->isTrue(temp);
585 temp = validParameter.validFile(parameters, "split", false); if (temp == "not found") { temp = "f"; }
586 trimera = m->isTrue(temp);
588 search = validParameter.validFile(parameters, "search", false); if (search == "not found") { search = "blast"; }
590 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "1000"; }
591 m->mothurConvert(temp, iters);
593 temp = validParameter.validFile(parameters, "increment", false); if (temp == "not found") { temp = "5"; }
594 m->mothurConvert(temp, increment);
596 temp = validParameter.validFile(parameters, "numwanted", false); if (temp == "not found") { temp = "15"; }
597 m->mothurConvert(temp, numwanted);
599 blastlocation = validParameter.validFile(parameters, "blastlocation", false);
600 if (blastlocation == "not found") { blastlocation = ""; }
602 //add / to name if needed
603 string lastChar = blastlocation.substr(blastlocation.length()-1);
604 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
605 if (lastChar != "/") { blastlocation += "/"; }
607 if (lastChar != "\\") { blastlocation += "\\"; }
609 blastlocation = m->getFullPathName(blastlocation);
610 string formatdbCommand = "";
611 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
612 formatdbCommand = blastlocation + "formatdb";
614 formatdbCommand = blastlocation + "formatdb.exe";
617 //test to make sure formatdb exists
619 formatdbCommand = m->getFullPathName(formatdbCommand);
620 int ableToOpen = m->openInputFile(formatdbCommand, in, "no error"); in.close();
621 if(ableToOpen == 1) { m->mothurOut("[ERROR]: " + formatdbCommand + " file does not exist. mothur requires formatdb.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
623 string blastCommand = "";
624 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
625 blastCommand = blastlocation + "megablast";
627 blastCommand = blastlocation + "megablast.exe";
629 //test to make sure formatdb exists
631 blastCommand = m->getFullPathName(blastCommand);
632 ableToOpen = m->openInputFile(blastCommand, in2, "no error"); in2.close();
633 if(ableToOpen == 1) { m->mothurOut("[ERROR]: " + blastCommand + " file does not exist. mothur requires blastall.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
636 if ((search != "blast") && (search != "kmer")) { m->mothurOut(search + " is not a valid search."); m->mothurOutEndLine(); abort = true; }
638 if ((hasName || hasCount) && (templatefile != "self")) { m->mothurOut("You have provided a namefile or countfile and the reference parameter is not set to self. I am not sure what reference you are trying to use, aborting."); m->mothurOutEndLine(); abort=true; }
639 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; }
641 //until we resolve the issue 10-18-11
642 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
648 catch(exception& e) {
649 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
653 //***************************************************************************************************************
655 int ChimeraSlayerCommand::execute(){
657 if (abort == true) { if (calledHelp) { return 0; } return 2; }
659 for (int s = 0; s < fastaFileNames.size(); s++) {
661 m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
663 int start = time(NULL);
664 if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]); }//if user entered a file with a path then preserve it
665 map<string, string> variables;
666 variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]));
667 string outputFileName = getOutputFileName("chimera", variables);
668 string accnosFileName = getOutputFileName("accnos", variables);
669 string trimFastaFileName = getOutputFileName("fasta", variables);
672 ofstream out, out1, out2;
673 m->openOutputFile(outputFileName, out); out.close();
674 m->openOutputFile(accnosFileName, out1); out1.close();
675 if (trim) { m->openOutputFile(trimFastaFileName, out2); out2.close(); }
676 outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
677 outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
678 if (trim) { outputNames.push_back(trimFastaFileName); outputTypes["fasta"].push_back(trimFastaFileName); }
680 //maps a filename to priority map.
681 //if no groupfile this is fastafileNames[s] -> prioirity
682 //if groupfile then this is each groups seqs -> priority
683 map<string, map<string, int> > fileToPriority;
684 map<string, map<string, int> >::iterator itFile;
685 map<string, string> fileGroup;
686 fileToPriority[fastaFileNames[s]] = priority; //default
687 fileGroup[fastaFileNames[s]] = "noGroup";
688 map<string, string> uniqueNames;
689 int totalChimeras = 0;
692 if (templatefile == "self") {
694 SequenceCountParser* parser = NULL;
695 setUpForSelfReference(parser, fileGroup, fileToPriority, s);
696 if (parser != NULL) { uniqueNames = parser->getAllSeqsMap(); delete parser; }
698 SequenceParser* parser = NULL;
699 setUpForSelfReference(parser, fileGroup, fileToPriority, s);
700 if (parser != NULL) { uniqueNames = parser->getAllSeqsMap(); delete parser; }
704 if (m->control_pressed) { for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]); } return 0; }
706 if (fileToPriority.size() == 1) { //you running without a groupfile
707 itFile = fileToPriority.begin();
708 string thisFastaName = itFile->first;
709 map<string, int> thisPriority = itFile->second;
711 MPIExecute(thisFastaName, outputFileName, accnosFileName, trimFastaFileName, thisPriority);
714 vector<unsigned long long> positions;
715 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
716 positions = m->divideFile(thisFastaName, processors);
717 for (int i = 0; i < (positions.size()-1); i++) { lines.push_back(linePair(positions[i], positions[(i+1)])); }
719 if (processors == 1) { lines.push_back(linePair(0, 1000)); }
721 positions = m->setFilePosFasta(thisFastaName, numSeqs);
722 if (positions.size() < processors) { processors = positions.size(); }
724 //figure out how many sequences you have to process
725 int numSeqsPerProcessor = numSeqs / processors;
726 for (int i = 0; i < processors; i++) {
727 int startIndex = i * numSeqsPerProcessor;
728 if(i == (processors - 1)){ numSeqsPerProcessor = numSeqs - i * numSeqsPerProcessor; }
729 lines.push_back(linePair(positions[startIndex], numSeqsPerProcessor));
733 if(processors == 1){ numSeqs = driver(lines[0], outputFileName, thisFastaName, accnosFileName, trimFastaFileName, thisPriority); }
734 else{ numSeqs = createProcesses(outputFileName, thisFastaName, accnosFileName, trimFastaFileName, thisPriority); }
736 if (m->control_pressed) { outputTypes.clear(); if (trim) { m->mothurRemove(trimFastaFileName); } m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]); } return 0; }
738 }else { //you have provided a groupfile
740 MPIExecuteGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup);
742 if (processors == 1) { numSeqs = driverGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup); }
743 else { numSeqs = createProcessesGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup); } //destroys fileToPriority
748 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
752 totalChimeras = deconvoluteResults(uniqueNames, outputFileName, accnosFileName, trimFastaFileName);
753 m->mothurOutEndLine(); m->mothurOut(toString(totalChimeras) + " chimera found."); m->mothurOutEndLine();
756 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
760 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
763 //set accnos file as new current accnosfile
765 itTypes = outputTypes.find("accnos");
766 if (itTypes != outputTypes.end()) {
767 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
771 itTypes = outputTypes.find("fasta");
772 if (itTypes != outputTypes.end()) {
773 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
777 m->mothurOutEndLine();
778 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
779 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
780 m->mothurOutEndLine();
785 catch(exception& e) {
786 m->errorOut(e, "ChimeraSlayerCommand", "execute");
790 //**********************************************************************************************************************
791 int ChimeraSlayerCommand::MPIExecuteGroups(string outputFileName, string accnosFileName, string trimFastaFileName, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup){
798 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
799 MPI_Comm_size(MPI_COMM_WORLD, &processors);
801 //put filenames in a vector, then pass each process a starting and ending point in the vector
802 //all processes already have the fileToPriority and fileGroup, they just need to know which files to process
803 map<string, map<string, int> >::iterator itFile;
804 vector<string> filenames;
805 for(itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) { filenames.push_back(itFile->first); }
807 int numGroupsPerProcessor = filenames.size() / processors;
808 int startIndex = pid * numGroupsPerProcessor;
809 int endIndex = (pid+1) * numGroupsPerProcessor;
810 if(pid == (processors - 1)){ endIndex = filenames.size(); }
812 vector<unsigned long long> MPIPos;
815 MPI_File outMPIAccnos;
816 MPI_File outMPIFasta;
818 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
819 int inMode=MPI_MODE_RDONLY;
821 char outFilename[1024];
822 strcpy(outFilename, outputFileName.c_str());
824 char outAccnosFilename[1024];
825 strcpy(outAccnosFilename, accnosFileName.c_str());
827 char outFastaFilename[1024];
828 strcpy(outFastaFilename, trimFastaFileName.c_str());
830 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
831 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
832 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
834 if (m->control_pressed) { MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
837 if (pid == 0) { //you are the root process
838 m->mothurOutEndLine();
839 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
840 m->mothurOutEndLine();
842 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
845 int length = outTemp.length();
846 char* buf2 = new char[length];
847 memcpy(buf2, outTemp.c_str(), length);
849 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
852 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
854 for (int i = startIndex; i < endIndex; i++) {
856 int start = time(NULL);
858 string thisFastaName = filenames[i];
859 map<string, int> thisPriority = fileToPriority[thisFastaName];
861 char inFileName[1024];
862 strcpy(inFileName, thisFastaName.c_str());
864 MPI_File_open(MPI_COMM_SELF, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
866 MPIPos = m->setFilePosFasta(thisFastaName, num); //fills MPIPos, returns numSeqs
868 cout << endl << "Checking sequences from group: " << fileGroup[thisFastaName] << "." << endl;
870 driverMPI(0, num, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, thisFastaName, thisPriority, true);
873 MPI_File_close(&inMPI);
874 m->mothurRemove(thisFastaName);
876 cout << endl << "It took " << toString(time(NULL) - start) << " secs to check " + toString(num) + " sequences from group " << fileGroup[thisFastaName] << "." << endl;
880 for(int i = 1; i < processors; i++) {
882 MPI_Recv(&temp, 1, MPI_INT, i, 2001, MPI_COMM_WORLD, &status);
885 }else{ MPI_Send(&numSeqs, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD); }
887 MPI_File_close(&outMPI);
888 MPI_File_close(&outMPIAccnos);
889 if (trim) { MPI_File_close(&outMPIFasta); }
891 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
895 }catch(exception& e) {
896 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecuteGroups");
900 //**********************************************************************************************************************
901 int ChimeraSlayerCommand::MPIExecute(string inputFile, string outputFileName, string accnosFileName, string trimFastaFileName, map<string, int>& priority){
905 int pid, numSeqsPerProcessor;
907 vector<unsigned long long> MPIPos;
910 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
911 MPI_Comm_size(MPI_COMM_WORLD, &processors);
915 MPI_File outMPIAccnos;
916 MPI_File outMPIFasta;
918 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
919 int inMode=MPI_MODE_RDONLY;
921 char outFilename[1024];
922 strcpy(outFilename, outputFileName.c_str());
924 char outAccnosFilename[1024];
925 strcpy(outAccnosFilename, accnosFileName.c_str());
927 char outFastaFilename[1024];
928 strcpy(outFastaFilename, trimFastaFileName.c_str());
930 char inFileName[1024];
931 strcpy(inFileName, inputFile.c_str());
933 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
934 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
935 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
936 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
938 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
940 if (pid == 0) { //you are the root process
941 m->mothurOutEndLine();
942 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
943 m->mothurOutEndLine();
945 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
948 int length = outTemp.length();
949 char* buf2 = new char[length];
950 memcpy(buf2, outTemp.c_str(), length);
952 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
955 MPIPos = m->setFilePosFasta(inputFile, numSeqs); //fills MPIPos, returns numSeqs
957 if (templatefile != "self") { //if template=self we can only use 1 processor
958 //send file positions to all processes
959 for(int i = 1; i < processors; i++) {
960 MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
961 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
964 //figure out how many sequences you have to align
965 numSeqsPerProcessor = numSeqs / processors;
966 int startIndex = pid * numSeqsPerProcessor;
967 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
969 if (templatefile == "self") { //if template=self we can only use 1 processor
971 numSeqsPerProcessor = numSeqs;
975 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, inputFile, priority, false);
977 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
979 }else{ //you are a child process
980 if (templatefile != "self") { //if template=self we can only use 1 processor
981 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
982 MPIPos.resize(numSeqs+1);
983 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
985 //figure out how many sequences you have to align
986 numSeqsPerProcessor = numSeqs / processors;
987 int startIndex = pid * numSeqsPerProcessor;
988 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
991 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, inputFile, priority, false);
993 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
999 MPI_File_close(&inMPI);
1000 MPI_File_close(&outMPI);
1001 MPI_File_close(&outMPIAccnos);
1002 if (trim) { MPI_File_close(&outMPIFasta); }
1003 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
1009 catch(exception& e) {
1010 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecute");
1014 //**********************************************************************************************************************
1015 int ChimeraSlayerCommand::deconvoluteResults(map<string, string>& uniqueNames, string outputFileName, string accnosFileName, string trimFileName){
1017 map<string, string>::iterator itUnique;
1020 if (trimera) { //add in more potential uniqueNames
1021 map<string, string> newUniqueNames = uniqueNames;
1022 for (map<string, string>::iterator it = uniqueNames.begin(); it != uniqueNames.end(); it++) {
1023 newUniqueNames[(it->first)+"_LEFT"] = (it->first)+"_LEFT";
1024 newUniqueNames[(it->first)+"_RIGHT"] = (it->first)+"_RIGHT";
1026 uniqueNames = newUniqueNames;
1027 newUniqueNames.clear();
1032 m->openInputFile(accnosFileName, in2, "no error");
1035 m->openOutputFile(accnosFileName+".temp", out2);
1037 string name; name = "";
1038 set<string> chimerasInFile;
1039 set<string>::iterator itChimeras;
1041 while (!in2.eof()) {
1042 if (m->control_pressed) { in2.close(); out2.close(); m->mothurRemove(outputFileName); m->mothurRemove((accnosFileName+".temp")); return 0; }
1044 in2 >> name; m->gobble(in2);
1047 itUnique = uniqueNames.find(name);
1049 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1051 itChimeras = chimerasInFile.find((itUnique->second));
1053 if (itChimeras == chimerasInFile.end()) {
1054 out2 << itUnique->second << endl;
1055 chimerasInFile.insert((itUnique->second));
1063 m->mothurRemove(accnosFileName);
1064 rename((accnosFileName+".temp").c_str(), accnosFileName.c_str());
1069 m->openInputFile(outputFileName, in);
1072 m->openOutputFile(outputFileName+".temp", out); out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
1074 string rest, parent1, parent2, line;
1075 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
1076 set<string>::iterator itNames;
1078 //assumptions - in file each read will always look like...
1081 F11Fcsw_63104 F11Fcsw_33372 F11Fcsw_37007 0.89441 80.4469 0.2 1.03727 93.2961 52.2 no 0-241 243-369
1086 line = m->getline(in); m->gobble(in);
1087 out << line << endl;
1090 //for the chimera file, we want to make sure if any group finds a sequence to be chimeric then all groups do,
1091 //so if this is a report that did not find it to be chimeric, but it appears in the accnos file,
1092 //then ignore this report and continue until we find the report that found it to be chimeric
1096 if (m->control_pressed) { in.close(); out.close(); m->mothurRemove((outputFileName+".temp")); return 0; }
1098 in >> name; m->gobble(in);
1099 in >> parent1; m->gobble(in);
1101 if (name == "Name") { //name = "Name" because we append the header line each time we add results from the groups
1102 line = m->getline(in); m->gobble(in);
1104 if (parent1 == "no") {
1106 itUnique = uniqueNames.find(name);
1108 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1110 //is this sequence really not chimeric??
1111 itChimeras = chimerasInFile.find(itUnique->second);
1113 if (itChimeras == chimerasInFile.end()) {
1114 //is this sequence not already in the file
1115 itNames = namesInFile.find((itUnique->second));
1117 if (itNames == namesInFile.end()) { out << itUnique->second << '\t' << "no" << endl; namesInFile.insert(itUnique->second); }
1120 }else { //read the rest of the line
1121 double DivQLAQRB,PerIDQLAQRB,BootStrapA,DivQLBQRA,PerIDQLBQRA,BootStrapB;
1122 string flag, range1, range2;
1124 in >> parent2 >> DivQLAQRB >> PerIDQLAQRB >> BootStrapA >> DivQLBQRA >> PerIDQLBQRA >> BootStrapB >> flag >> range1 >> range2; m->gobble(in);
1127 itUnique = uniqueNames.find(name);
1129 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1131 name = itUnique->second;
1132 //is this name already in the file
1133 itNames = namesInFile.find((name));
1135 if (itNames == namesInFile.end()) { //no not in file
1136 if (flag == "no") { //are you really a no??
1137 //is this sequence really not chimeric??
1138 itChimeras = chimerasInFile.find(name);
1140 //then you really are a no so print, otherwise skip
1141 if (itChimeras == chimerasInFile.end()) { print = true; }
1143 }else{ print = true; }
1148 out << name << '\t';
1150 namesInFile.insert(name);
1152 //output parent1's name
1153 itUnique = uniqueNames.find(parent1);
1154 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent1 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1155 else { out << itUnique->second << '\t'; }
1157 //output parent2's name
1158 itUnique = uniqueNames.find(parent2);
1159 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent2 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1160 else { out << itUnique->second << '\t'; }
1162 out << DivQLAQRB << '\t' << PerIDQLAQRB << '\t' << BootStrapA << '\t' << DivQLBQRA << '\t' << PerIDQLBQRA << '\t' << BootStrapB << '\t' << flag << '\t' << range1 << '\t' << range2 << endl;
1170 m->mothurRemove(outputFileName);
1171 rename((outputFileName+".temp").c_str(), outputFileName.c_str());
1176 m->openInputFile(trimFileName, in3);
1179 m->openOutputFile(trimFileName+".temp", out3);
1181 namesInFile.clear();
1183 while (!in3.eof()) {
1184 if (m->control_pressed) { in3.close(); out3.close(); m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); m->mothurRemove((trimFileName+".temp")); return 0; }
1186 Sequence seq(in3); m->gobble(in3);
1188 if (seq.getName() != "") {
1190 itUnique = uniqueNames.find(seq.getName());
1192 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ seq.getName() + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1194 itNames = namesInFile.find((itUnique->second));
1196 if (itNames == namesInFile.end()) {
1197 seq.printSequence(out3);
1205 m->mothurRemove(trimFileName);
1206 rename((trimFileName+".temp").c_str(), trimFileName.c_str());
1211 catch(exception& e) {
1212 m->errorOut(e, "ChimeraSlayerCommand", "deconvoluteResults");
1216 //**********************************************************************************************************************
1217 int ChimeraSlayerCommand::setUpForSelfReference(SequenceParser*& parser, map<string, string>& fileGroup, map<string, map<string, int> >& fileToPriority, int s){
1220 fileToPriority.clear();
1222 string nameFile = "";
1223 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
1224 nameFile = nameFileNames[s];
1225 }else { nameFile = getNamesFile(fastaFileNames[s]); }
1227 //you provided a groupfile
1228 string groupFile = "";
1229 if (groupFileNames.size() != 0) { groupFile = groupFileNames[s]; }
1231 if (groupFile == "") {
1232 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
1234 //sort fastafile by abundance, returns new sorted fastafile name
1235 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush();
1236 priority = sortFastaFile(fastaFileNames[s], nameFile);
1237 m->mothurOut("Done."); m->mothurOutEndLine();
1239 fileToPriority[fastaFileNames[s]] = priority;
1240 fileGroup[fastaFileNames[s]] = "noGroup";
1242 //Parse sequences by group
1243 parser = new SequenceParser(groupFile, fastaFileNames[s], nameFile);
1244 vector<string> groups = parser->getNamesOfGroups();
1246 for (int i = 0; i < groups.size(); i++) {
1247 vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
1248 map<string, string> thisGroupsMap = parser->getNameMap(groups[i]);
1249 string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
1250 priority = sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile);
1251 fileToPriority[newFastaFile] = priority;
1252 fileGroup[newFastaFile] = groups[i];
1259 catch(exception& e) {
1260 m->errorOut(e, "ChimeraSlayerCommand", "setUpForSelfReference");
1264 //**********************************************************************************************************************
1265 int ChimeraSlayerCommand::setUpForSelfReference(SequenceCountParser*& parser, map<string, string>& fileGroup, map<string, map<string, int> >& fileToPriority, int s){
1268 fileToPriority.clear();
1270 string nameFile = "";
1271 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
1272 nameFile = nameFileNames[s];
1273 }else { m->control_pressed = true; return 0; }
1276 if (!ct.testGroups(nameFile)) {
1277 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
1279 //sort fastafile by abundance, returns new sorted fastafile name
1280 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush();
1281 priority = sortFastaFile(fastaFileNames[s], nameFile);
1282 m->mothurOut("Done."); m->mothurOutEndLine();
1284 fileToPriority[fastaFileNames[s]] = priority;
1285 fileGroup[fastaFileNames[s]] = "noGroup";
1287 //Parse sequences by group
1288 parser = new SequenceCountParser(nameFile, fastaFileNames[s]);
1289 vector<string> groups = parser->getNamesOfGroups();
1291 for (int i = 0; i < groups.size(); i++) {
1292 vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
1293 map<string, int> thisGroupsMap = parser->getCountTable(groups[i]);
1294 string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
1295 sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile);
1296 fileToPriority[newFastaFile] = thisGroupsMap;
1297 fileGroup[newFastaFile] = groups[i];
1304 catch(exception& e) {
1305 m->errorOut(e, "ChimeraSlayerCommand", "setUpForSelfReference");
1309 //**********************************************************************************************************************
1310 string ChimeraSlayerCommand::getNamesFile(string& inputFile){
1312 string nameFile = "";
1314 m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
1316 //use unique.seqs to create new name and fastafile
1317 string inputString = "fasta=" + inputFile;
1318 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
1319 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine();
1320 m->mothurCalling = true;
1322 Command* uniqueCommand = new DeconvoluteCommand(inputString);
1323 uniqueCommand->execute();
1325 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
1327 delete uniqueCommand;
1328 m->mothurCalling = false;
1329 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
1331 nameFile = filenames["name"][0];
1332 inputFile = filenames["fasta"][0];
1336 catch(exception& e) {
1337 m->errorOut(e, "ChimeraSlayerCommand", "getNamesFile");
1341 //**********************************************************************************************************************
1343 int ChimeraSlayerCommand::driverGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup){
1347 for (map<string, map<string, int> >::iterator itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) {
1349 if (m->control_pressed) { return 0; }
1351 int start = time(NULL);
1352 string thisFastaName = itFile->first;
1353 map<string, int> thisPriority = itFile->second;
1354 string thisoutputFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.chimera";
1355 string thisaccnosFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.accnos";
1356 string thistrimFastaFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.fasta";
1358 m->mothurOutEndLine(); m->mothurOut("Checking sequences from group: " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine();
1361 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1363 vector<unsigned long long> positions = m->divideFile(thisFastaName, proc);
1364 lines.push_back(linePair(positions[0], positions[1]));
1366 lines.push_back(linePair(0, 1000));
1368 int numSeqs = driver(lines[0], thisoutputFileName, thisFastaName, thisaccnosFileName, thistrimFastaFileName, thisPriority);
1371 m->appendFiles(thisoutputFileName, outputFName); m->mothurRemove(thisoutputFileName);
1372 m->appendFiles(thisaccnosFileName, accnos); m->mothurRemove(thisaccnosFileName);
1373 if (trim) { m->appendFiles(thistrimFastaFileName, fasta); m->mothurRemove(thistrimFastaFileName); }
1374 m->mothurRemove(thisFastaName);
1376 totalSeqs += numSeqs;
1378 m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences from group " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine();
1383 catch(exception& e) {
1384 m->errorOut(e, "ChimeraSlayerCommand", "driverGroups");
1388 /**************************************************************************************************/
1389 int ChimeraSlayerCommand::createProcessesGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup) {
1395 if (fileToPriority.size() < processors) { processors = fileToPriority.size(); }
1397 int groupsPerProcessor = fileToPriority.size() / processors;
1398 int remainder = fileToPriority.size() % processors;
1400 vector< map<string, map<string, int> > > breakUp;
1402 for (int i = 0; i < processors; i++) {
1403 map<string, map<string, int> > thisFileToPriority;
1404 map<string, map<string, int> >::iterator itFile;
1406 int enough = groupsPerProcessor;
1407 if (i == 0) { enough = groupsPerProcessor + remainder; }
1409 for (itFile = fileToPriority.begin(); itFile != fileToPriority.end();) {
1410 thisFileToPriority[itFile->first] = itFile->second;
1411 fileToPriority.erase(itFile++);
1413 if (count == enough) { break; }
1415 breakUp.push_back(thisFileToPriority);
1418 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1419 //loop through and create all the processes you want
1420 while (process != processors) {
1424 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
1426 }else if (pid == 0){
1427 num = driverGroups(outputFName + toString(getpid()) + ".temp", accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", breakUp[process], fileGroup);
1429 //pass numSeqs to parent
1431 string tempFile = outputFName + toString(getpid()) + ".num.temp";
1432 m->openOutputFile(tempFile, out);
1437 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
1438 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1443 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup);
1445 //force parent to wait until all the processes are done
1446 for (int i=0;i<processors;i++) {
1447 int temp = processIDS[i];
1451 for (int i = 0; i < processIDS.size(); i++) {
1453 string tempFile = outputFName + toString(processIDS[i]) + ".num.temp";
1454 m->openInputFile(tempFile, in);
1455 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
1456 in.close(); m->mothurRemove(tempFile);
1460 //////////////////////////////////////////////////////////////////////////////////////////////////////
1461 //Windows version shared memory, so be careful when passing variables through the slayerData struct.
1462 //Above fork() will clone, so memory is separate, but that's not the case with windows,
1463 //////////////////////////////////////////////////////////////////////////////////////////////////////
1465 vector<slayerData*> pDataArray;
1466 DWORD dwThreadIdArray[processors-1];
1467 HANDLE hThreadArray[processors-1];
1469 //Create processor worker threads.
1470 for(int i=1; i<processors; i++ ){
1471 string extension = toString(i) + ".temp";
1472 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);
1473 pDataArray.push_back(tempslayer);
1474 processIDS.push_back(i);
1476 //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
1477 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1478 hThreadArray[i-1] = CreateThread(NULL, 0, MySlayerGroupThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);
1481 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup);
1483 //Wait until all threads have terminated.
1484 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
1486 //Close all thread handles and free memory allocations.
1487 for(int i=0; i < pDataArray.size(); i++){
1488 num += pDataArray[i]->count;
1489 CloseHandle(hThreadArray[i]);
1490 delete pDataArray[i];
1494 //append output files
1495 for(int i=0;i<processIDS.size();i++){
1496 m->appendFiles((outputFName + toString(processIDS[i]) + ".temp"), outputFName);
1497 m->mothurRemove((outputFName + toString(processIDS[i]) + ".temp"));
1499 m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1500 m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1503 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
1504 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
1511 catch(exception& e) {
1512 m->errorOut(e, "ChimeraSlayerCommand", "createProcessesGroups");
1516 //**********************************************************************************************************************
1518 int ChimeraSlayerCommand::driver(linePair filePos, string outputFName, string filename, string accnos, string fasta, map<string, int>& priority){
1522 if (templatefile != "self") { //you want to run slayer with a reference template
1523 chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1525 chimera = new ChimeraSlayer(filename, templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1528 if (m->control_pressed) { delete chimera; return 0; }
1530 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1531 templateSeqsLength = chimera->getLength();
1534 m->openOutputFile(outputFName, out);
1537 m->openOutputFile(accnos, out2);
1540 if (trim) { m->openOutputFile(fasta, out3); }
1543 m->openInputFile(filename, inFASTA);
1545 inFASTA.seekg(filePos.start);
1547 if (filePos.start == 0) { chimera->printHeader(out); }
1554 if (m->control_pressed) { delete chimera; out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1; }
1556 Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
1557 string candidateAligned = candidateSeq->getAligned();
1559 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1560 if (candidateSeq->getAligned().length() != templateSeqsLength) {
1561 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1564 chimera->getChimeras(candidateSeq);
1566 if (m->control_pressed) { delete chimera; delete candidateSeq; return 1; }
1568 //if you are not chimeric, then check each half
1569 data_results wholeResults = chimera->getResults();
1571 //determine if we need to split
1572 bool isChimeric = false;
1574 if (wholeResults.flag == "yes") {
1575 string chimeraFlag = "no";
1576 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1578 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1581 if (chimeraFlag == "yes") {
1582 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1586 if ((!isChimeric) && trimera) {
1588 //split sequence in half by bases
1589 string leftQuery, rightQuery;
1590 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1591 divideInHalf(tempSeq, leftQuery, rightQuery);
1593 //run chimeraSlayer on each piece
1594 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1595 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1598 chimera->getChimeras(left);
1599 data_results leftResults = chimera->getResults();
1601 chimera->getChimeras(right);
1602 data_results rightResults = chimera->getResults();
1604 //if either piece is chimeric then report
1605 Sequence trimmed = chimera->print(out, out2, leftResults, rightResults);
1606 if (trim) { trimmed.printSequence(out3); }
1608 delete left; delete right;
1610 }else { //already chimeric
1612 Sequence trimmed = chimera->print(out, out2);
1613 if (trim) { trimmed.printSequence(out3); }
1621 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1622 unsigned long long pos = inFASTA.tellg();
1623 if ((pos == -1) || (pos >= filePos.end)) { break; }
1625 if (inFASTA.eof()) { break; }
1628 delete candidateSeq;
1630 if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
1633 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
1635 int numNoParents = chimera->getNumNoParents();
1636 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(); }
1640 if (trim) { out3.close(); }
1648 catch(exception& e) {
1649 m->errorOut(e, "ChimeraSlayerCommand", "driver");
1653 //**********************************************************************************************************************
1655 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){
1659 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1662 if (templatefile != "self") { //you want to run slayer with a reference template
1663 chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1665 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);
1668 if (m->control_pressed) { delete chimera; return 0; }
1670 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1671 templateSeqsLength = chimera->getLength();
1673 for(int i=0;i<num;i++){
1675 if (m->control_pressed) { delete chimera; return 1; }
1677 //read next sequence
1678 int length = MPIPos[start+i+1] - MPIPos[start+i];
1680 char* buf4 = new char[length];
1681 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
1683 string tempBuf = buf4;
1684 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
1685 istringstream iss (tempBuf,istringstream::in);
1689 Sequence* candidateSeq = new Sequence(iss); m->gobble(iss);
1690 string candidateAligned = candidateSeq->getAligned();
1692 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1694 if (candidateSeq->getAligned().length() != templateSeqsLength) {
1695 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1699 chimera->getChimeras(candidateSeq);
1701 if (m->control_pressed) { delete chimera; delete candidateSeq; return 1; }
1703 //if you are not chimeric, then check each half
1704 data_results wholeResults = chimera->getResults();
1706 //determine if we need to split
1707 bool isChimeric = false;
1709 if (wholeResults.flag == "yes") {
1710 string chimeraFlag = "no";
1711 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1713 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1716 if (chimeraFlag == "yes") {
1717 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1721 if ((!isChimeric) && trimera) {
1722 //split sequence in half by bases
1723 string leftQuery, rightQuery;
1724 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1725 divideInHalf(tempSeq, leftQuery, rightQuery);
1727 //run chimeraSlayer on each piece
1728 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1729 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1732 chimera->getChimeras(left);
1733 data_results leftResults = chimera->getResults();
1735 chimera->getChimeras(right);
1736 data_results rightResults = chimera->getResults();
1738 //if either piece is chimeric then report
1739 Sequence trimmed = chimera->print(outMPI, outAccMPI, leftResults, rightResults);
1741 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1743 //write to accnos file
1744 int length = outputString.length();
1745 char* buf2 = new char[length];
1746 memcpy(buf2, outputString.c_str(), length);
1748 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1752 delete left; delete right;
1756 Sequence trimmed = chimera->print(outMPI, outAccMPI);
1759 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1761 //write to accnos file
1762 int length = outputString.length();
1763 char* buf2 = new char[length];
1764 memcpy(buf2, outputString.c_str(), length);
1766 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1773 delete candidateSeq;
1776 if((i+1) % 100 == 0){ cout << "Processing sequence: " << (i+1) << endl; m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n"); }
1779 if(num % 100 != 0){ cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n"); }
1781 int numNoParents = chimera->getNumNoParents();
1782 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; }
1787 catch(exception& e) {
1788 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
1794 /**************************************************************************************************/
1796 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta, map<string, int>& thisPriority) {
1802 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1803 //loop through and create all the processes you want
1804 while (process != processors) {
1808 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
1810 }else if (pid == 0){
1811 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", thisPriority);
1813 //pass numSeqs to parent
1815 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
1816 m->openOutputFile(tempFile, out);
1821 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
1822 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1827 //force parent to wait until all the processes are done
1828 for (int i=0;i<processors;i++) {
1829 int temp = processIDS[i];
1833 for (int i = 0; i < processIDS.size(); i++) {
1835 string tempFile = outputFileName + toString(processIDS[i]) + ".num.temp";
1836 m->openInputFile(tempFile, in);
1837 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
1838 in.close(); m->mothurRemove(tempFile);
1842 //////////////////////////////////////////////////////////////////////////////////////////////////////
1843 //Windows version shared memory, so be careful when passing variables through the slayerData struct.
1844 //Above fork() will clone, so memory is separate, but that's not the case with windows,
1845 //////////////////////////////////////////////////////////////////////////////////////////////////////
1847 vector<slayerData*> pDataArray;
1848 DWORD dwThreadIdArray[processors];
1849 HANDLE hThreadArray[processors];
1851 //Create processor worker threads.
1852 for( int i=0; i<processors; i++ ){
1853 string extension = toString(i) + ".temp";
1854 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);
1855 pDataArray.push_back(tempslayer);
1856 processIDS.push_back(i);
1858 //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
1859 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1860 hThreadArray[i] = CreateThread(NULL, 0, MySlayerThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);
1863 //Wait until all threads have terminated.
1864 WaitForMultipleObjects(processors, hThreadArray, TRUE, INFINITE);
1866 //Close all thread handles and free memory allocations.
1867 for(int i=0; i < pDataArray.size(); i++){
1868 num += pDataArray[i]->count;
1869 CloseHandle(hThreadArray[i]);
1870 delete pDataArray[i];
1874 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
1875 rename((accnos + toString(processIDS[0]) + ".temp").c_str(), accnos.c_str());
1876 if (trim) { rename((fasta + toString(processIDS[0]) + ".temp").c_str(), fasta.c_str()); }
1878 //append output files
1879 for(int i=1;i<processIDS.size();i++){
1880 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
1881 m->mothurRemove((outputFileName + toString(processIDS[i]) + ".temp"));
1883 m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1884 m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1887 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
1888 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
1895 catch(exception& e) {
1896 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
1901 /**************************************************************************************************/
1903 int ChimeraSlayerCommand::divideInHalf(Sequence querySeq, string& leftQuery, string& rightQuery) {
1906 string queryUnAligned = querySeq.getUnaligned();
1907 int numBases = int(queryUnAligned.length() * 0.5);
1909 string queryAligned = querySeq.getAligned();
1910 leftQuery = querySeq.getAligned();
1911 rightQuery = querySeq.getAligned();
1915 for (int i = 0; i < queryAligned.length(); i++) {
1917 if (isalpha(queryAligned[i])) {
1922 if (baseCount >= numBases) { leftSpot = i; break; } //first half
1925 //blank out right side
1926 for (int i = leftSpot; i < leftQuery.length(); i++) { leftQuery[i] = '.'; }
1928 //blank out left side
1929 for (int i = 0; i < leftSpot; i++) { rightQuery[i] = '.'; }
1934 catch(exception& e) {
1935 m->errorOut(e, "ChimeraSlayerCommand", "divideInHalf");
1939 /**************************************************************************************************/
1940 map<string, int> ChimeraSlayerCommand::sortFastaFile(string fastaFile, string nameFile) {
1942 map<string, int> nameAbund;
1944 //read through fastafile and store info
1945 map<string, string> seqs;
1947 m->openInputFile(fastaFile, in);
1951 if (m->control_pressed) { in.close(); return nameAbund; }
1953 Sequence seq(in); m->gobble(in);
1954 seqs[seq.getName()] = seq.getAligned();
1959 //read namefile or countfile
1960 vector<seqPriorityNode> nameMapCount;
1964 ct.readTable(nameFile);
1966 for(map<string, string>::iterator it = seqs.begin(); it != seqs.end(); it++) {
1967 int num = ct.getNumSeqs(it->first);
1968 if (num == 0) { error = 1; }
1970 seqPriorityNode temp(num, it->second, it->first);
1971 nameMapCount.push_back(temp);
1974 }else { error = m->readNames(nameFile, nameMapCount, seqs); }
1976 if (m->control_pressed) { return nameAbund; }
1978 if (error == 1) { m->control_pressed = true; return nameAbund; }
1979 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; }
1981 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
1983 string newFasta = fastaFile + ".temp";
1985 m->openOutputFile(newFasta, out);
1987 //print new file in order of
1988 for (int i = 0; i < nameMapCount.size(); i++) {
1989 out << ">" << nameMapCount[i].name << endl << nameMapCount[i].seq << endl;
1990 nameAbund[nameMapCount[i].name] = nameMapCount[i].numIdentical;
1994 rename(newFasta.c_str(), fastaFile.c_str());
1999 catch(exception& e) {
2000 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2004 /**************************************************************************************************/
2005 map<string, int> ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, string>& nameMap, string newFile) {
2007 map<string, int> nameAbund;
2008 vector<seqPriorityNode> nameVector;
2010 //read through fastafile and store info
2011 map<string, string> seqs;
2013 for (int i = 0; i < thisseqs.size(); i++) {
2015 if (m->control_pressed) { return nameAbund; }
2017 map<string, string>::iterator itNameMap = nameMap.find(thisseqs[i].getName());
2019 if (itNameMap == nameMap.end()){
2020 m->control_pressed = true;
2021 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your namesfile, please correct."); m->mothurOutEndLine();
2023 int num = m->getNumNames(itNameMap->second);
2025 seqPriorityNode temp(num, thisseqs[i].getAligned(), thisseqs[i].getName());
2026 nameVector.push_back(temp);
2030 //sort by num represented
2031 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
2033 if (m->control_pressed) { return nameAbund; }
2035 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; }
2038 m->openOutputFile(newFile, out);
2040 //print new file in order of
2041 for (int i = 0; i < nameVector.size(); i++) {
2042 out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
2043 nameAbund[nameVector[i].name] = nameVector[i].numIdentical;
2050 catch(exception& e) {
2051 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2055 /**************************************************************************************************/
2056 int ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, int>& countMap, string newFile) {
2058 vector<seqPriorityNode> nameVector;
2060 //read through fastafile and store info
2061 map<string, string> seqs;
2063 for (int i = 0; i < thisseqs.size(); i++) {
2065 if (m->control_pressed) { return 0; }
2067 map<string, int>::iterator itCountMap = countMap.find(thisseqs[i].getName());
2069 if (itCountMap == countMap.end()){
2070 m->control_pressed = true;
2071 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your count file, please correct."); m->mothurOutEndLine();
2073 seqPriorityNode temp(itCountMap->second, thisseqs[i].getAligned(), thisseqs[i].getName());
2074 nameVector.push_back(temp);
2078 //sort by num represented
2079 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
2081 if (m->control_pressed) { return 0; }
2083 if (thisseqs.size() != nameVector.size()) { m->mothurOut( "The number of sequences in your fastafile does not match the number of sequences in your count file, aborting."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
2086 m->openOutputFile(newFile, out);
2088 //print new file in order of
2089 for (int i = 0; i < nameVector.size(); i++) {
2090 out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
2097 catch(exception& e) {
2098 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2102 /**************************************************************************************************/