2 * chimeraslayercommand.cpp
5 * Created by westcott on 3/31/10.
6 * Copyright 2010 Schloss Lab. All rights reserved.
10 #include "chimeraslayercommand.h"
11 #include "deconvolutecommand.h"
12 #include "referencedb.h"
13 #include "sequenceparser.h"
14 #include "counttable.h"
16 //**********************************************************************************************************************
17 vector<string> ChimeraSlayerCommand::setParameters(){
19 CommandParameter ptemplate("reference", "InputTypes", "", "", "none", "none", "none","",false,true,true); parameters.push_back(ptemplate);
20 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none","chimera-accnos",false,true,true); parameters.push_back(pfasta);
21 CommandParameter pname("name", "InputTypes", "", "", "NameCount", "none", "none","",false,false,true); parameters.push_back(pname);
22 CommandParameter pcount("count", "InputTypes", "", "", "NameCount-CountGroup", "none", "none","",false,false,true); parameters.push_back(pcount);
23 CommandParameter pgroup("group", "InputTypes", "", "", "CountGroup", "none", "none","",false,false,true); parameters.push_back(pgroup);
24 CommandParameter pwindow("window", "Number", "", "50", "", "", "","",false,false); parameters.push_back(pwindow);
25 CommandParameter pksize("ksize", "Number", "", "7", "", "", "","",false,false); parameters.push_back(pksize);
26 CommandParameter pmatch("match", "Number", "", "5.0", "", "", "","",false,false); parameters.push_back(pmatch);
27 CommandParameter pmismatch("mismatch", "Number", "", "-4.0", "", "", "","",false,false); parameters.push_back(pmismatch);
28 CommandParameter pminsim("minsim", "Number", "", "90", "", "", "","",false,false); parameters.push_back(pminsim);
29 CommandParameter pmincov("mincov", "Number", "", "70", "", "", "","",false,false); parameters.push_back(pmincov);
30 CommandParameter pminsnp("minsnp", "Number", "", "10", "", "", "","",false,false); parameters.push_back(pminsnp);
31 CommandParameter pminbs("minbs", "Number", "", "90", "", "", "","",false,false); parameters.push_back(pminbs);
32 CommandParameter psearch("search", "Multiple", "kmer-blast", "blast", "", "", "","",false,false); parameters.push_back(psearch);
33 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "","",false,false,true); parameters.push_back(pprocessors);
35 CommandParameter prealign("realign", "Boolean", "", "T", "", "", "","",false,false); parameters.push_back(prealign);
36 CommandParameter ptrim("trim", "Boolean", "", "F", "", "", "","fasta",false,false); parameters.push_back(ptrim);
37 CommandParameter psplit("split", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(psplit);
38 CommandParameter pnumwanted("numwanted", "Number", "", "15", "", "", "","",false,false); parameters.push_back(pnumwanted);
39 CommandParameter piters("iters", "Number", "", "1000", "", "", "","",false,false); parameters.push_back(piters);
40 CommandParameter pdivergence("divergence", "Number", "", "1.007", "", "", "","",false,false); parameters.push_back(pdivergence);
41 CommandParameter pdups("dereplicate", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(pdups);
42 CommandParameter pparents("parents", "Number", "", "3", "", "", "","",false,false); parameters.push_back(pparents);
43 CommandParameter pincrement("increment", "Number", "", "5", "", "", "","",false,false); parameters.push_back(pincrement);
44 CommandParameter pblastlocation("blastlocation", "String", "", "", "", "", "","",false,false); parameters.push_back(pblastlocation);
45 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
46 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
47 CommandParameter psave("save", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(psave);
49 vector<string> myArray;
50 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
54 m->errorOut(e, "ChimeraSlayerCommand", "setParameters");
58 //**********************************************************************************************************************
59 string ChimeraSlayerCommand::getHelpString(){
61 string helpString = "";
62 helpString += "The chimera.slayer command reads a fastafile and referencefile and outputs potentially chimeric sequences.\n";
63 helpString += "This command was modeled after the chimeraSlayer written by the Broad Institute.\n";
64 helpString += "The chimera.slayer command parameters are fasta, name, group, template, processors, dereplicate, trim, ksize, window, match, mismatch, divergence. minsim, mincov, minbs, minsnp, parents, search, iters, increment, numwanted, blastlocation and realign.\n";
65 helpString += "The fasta parameter allows you to enter the fasta file containing your potentially chimeric sequences, and is required, unless you have a valid current fasta file. \n";
66 helpString += "The name parameter allows you to provide a name file, if you are using reference=self. \n";
67 helpString += "The group parameter allows you to provide a group file. The group file can be used with a namesfile and reference=self. When checking sequences, only sequences from the same group as the query sequence will be used as the reference. \n";
68 helpString += "The count parameter allows you to provide a count file. The count file reference=self. If your count file contains group information, when checking sequences, only sequences from the same group as the query sequence will be used as the reference. \n";
69 helpString += "You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amazon.fasta \n";
70 helpString += "The reference parameter allows you to enter a reference file containing known non-chimeric sequences, and is required. You may also set template=self, in this case the abundant sequences will be used as potential parents. \n";
71 helpString += "The processors parameter allows you to specify how many processors you would like to use. The default is 1. \n";
73 helpString += "When using MPI, the processors parameter is set to the number of MPI processes running. \n";
75 helpString += "If the dereplicate parameter is false, then if one group finds the seqeunce to be chimeric, then all groups find it to be chimeric, default=f.\n";
76 helpString += "The trim parameter allows you to output a new fasta file containing your sequences with the chimeric ones trimmed to include only their longest piece, default=F. \n";
77 helpString += "The split parameter allows you to check both pieces of non-chimeric sequence for chimeras, thus looking for trimeras and quadmeras. default=F. \n";
78 helpString += "The window parameter allows you to specify the window size for searching for chimeras, default=50. \n";
79 helpString += "The increment parameter allows you to specify how far you move each window while finding chimeric sequences, default=5.\n";
80 helpString += "The numwanted parameter allows you to specify how many sequences you would each query sequence compared with, default=15.\n";
81 helpString += "The ksize parameter allows you to input kmersize, default is 7, used if search is kmer. \n";
82 helpString += "The match parameter allows you to reward matched bases in blast search, default is 5. \n";
83 helpString += "The parents parameter allows you to select the number of potential parents to investigate from the numwanted best matches after rating them, default is 3. \n";
84 helpString += "The mismatch parameter allows you to penalize mismatched bases in blast search, default is -4. \n";
85 helpString += "The divergence parameter allows you to set a cutoff for chimera determination, default is 1.007. \n";
86 helpString += "The iters parameter allows you to specify the number of bootstrap iters to do with the chimeraslayer method, default=1000.\n";
87 helpString += "The minsim parameter allows you to specify a minimum similarity with the parent fragments, default=90. \n";
88 helpString += "The mincov parameter allows you to specify minimum coverage by closest matches found in template. Default is 70, meaning 70%. \n";
89 helpString += "The minbs parameter allows you to specify minimum bootstrap support for calling a sequence chimeric. Default is 90, meaning 90%. \n";
90 helpString += "The minsnp parameter allows you to specify percent of SNPs to sample on each side of breakpoint for computing bootstrap support (default: 10) \n";
91 helpString += "The search parameter allows you to specify search method for finding the closest parent. Choices are blast, and kmer, default blast. \n";
92 helpString += "The realign parameter allows you to realign the query to the potential parents. Choices are true or false, default true. \n";
93 helpString += "The blastlocation parameter allows you to specify the location of your blast executable. By default mothur will look in ./blast/bin relative to mothur's executable. \n";
94 helpString += "If the save parameter is set to true the reference sequences will be saved in memory, to clear them later you can use the clear.memory command. Default=f.";
95 helpString += "The chimera.slayer command should be in the following format: \n";
96 helpString += "chimera.slayer(fasta=yourFastaFile, reference=yourTemplate, search=yourSearch) \n";
97 helpString += "Example: chimera.slayer(fasta=AD.align, reference=core_set_aligned.imputed.fasta, search=kmer) \n";
98 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";
101 catch(exception& e) {
102 m->errorOut(e, "ChimeraSlayerCommand", "getHelpString");
106 //**********************************************************************************************************************
107 string ChimeraSlayerCommand::getOutputPattern(string type) {
111 if (type == "chimera") { pattern = "[filename],slayer.chimeras"; }
112 else if (type == "accnos") { pattern = "[filename],slayer.accnos"; }
113 else if (type == "fasta") { pattern = "[filename],slayer.fasta"; }
114 else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true; }
118 catch(exception& e) {
119 m->errorOut(e, "ChimeraSlayerCommand", "getOutputPattern");
123 //**********************************************************************************************************************
124 ChimeraSlayerCommand::ChimeraSlayerCommand(){
126 abort = true; calledHelp = true;
128 vector<string> tempOutNames;
129 outputTypes["chimera"] = tempOutNames;
130 outputTypes["accnos"] = tempOutNames;
131 outputTypes["fasta"] = tempOutNames;
133 catch(exception& e) {
134 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
138 //***************************************************************************************************************
139 ChimeraSlayerCommand::ChimeraSlayerCommand(string option) {
141 abort = false; calledHelp = false;
142 ReferenceDB* rdb = ReferenceDB::getInstance();
146 //allow user to run help
147 if(option == "help") { help(); abort = true; calledHelp = true; }
148 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
151 vector<string> myArray = setParameters();
153 OptionParser parser(option);
154 map<string,string> parameters = parser.getParameters();
156 ValidParameters validParameter("chimera.slayer");
157 map<string,string>::iterator it;
159 //check to make sure all parameters are valid for command
160 for (it = parameters.begin(); it != parameters.end(); it++) {
161 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
164 vector<string> tempOutNames;
165 outputTypes["chimera"] = tempOutNames;
166 outputTypes["accnos"] = tempOutNames;
167 outputTypes["fasta"] = tempOutNames;
169 //if the user changes the input directory command factory will send this info to us in the output parameter
170 string inputDir = validParameter.validFile(parameters, "inputdir", false);
171 if (inputDir == "not found"){ inputDir = ""; }
173 //check for required parameters
174 fastafile = validParameter.validFile(parameters, "fasta", false);
175 if (fastafile == "not found") {
176 //if there is a current fasta file, use it
177 string filename = m->getFastaFile();
178 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
179 else { m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
181 m->splitAtDash(fastafile, fastaFileNames);
183 //go through files and make sure they are good, if not, then disregard them
184 for (int i = 0; i < fastaFileNames.size(); i++) {
187 if (fastaFileNames[i] == "current") {
188 fastaFileNames[i] = m->getFastaFile();
189 if (fastaFileNames[i] != "") { m->mothurOut("Using " + fastaFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
191 m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true;
192 //erase from file list
193 fastaFileNames.erase(fastaFileNames.begin()+i);
200 if (inputDir != "") {
201 string path = m->hasPath(fastaFileNames[i]);
202 //if the user has not given a path then, add inputdir. else leave path alone.
203 if (path == "") { fastaFileNames[i] = inputDir + fastaFileNames[i]; }
209 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
211 //if you can't open it, try default location
212 if (ableToOpen == 1) {
213 if (m->getDefaultPath() != "") { //default path is set
214 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
215 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
217 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
219 fastaFileNames[i] = tryPath;
223 if (ableToOpen == 1) {
224 if (m->getOutputDir() != "") { //default path is set
225 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
226 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
228 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
230 fastaFileNames[i] = tryPath;
236 if (ableToOpen == 1) {
237 m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
238 //erase from file list
239 fastaFileNames.erase(fastaFileNames.begin()+i);
242 m->setFastaFile(fastaFileNames[i]);
247 //make sure there is at least one valid file left
248 if (fastaFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid files."); m->mothurOutEndLine(); abort = true; }
252 //check for required parameters
253 namefile = validParameter.validFile(parameters, "name", false);
254 if (namefile == "not found") { namefile = ""; }
256 m->splitAtDash(namefile, nameFileNames);
258 //go through files and make sure they are good, if not, then disregard them
259 for (int i = 0; i < nameFileNames.size(); i++) {
262 if (nameFileNames[i] == "current") {
263 nameFileNames[i] = m->getNameFile();
264 if (nameFileNames[i] != "") { m->mothurOut("Using " + nameFileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
266 m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true;
267 //erase from file list
268 nameFileNames.erase(nameFileNames.begin()+i);
275 if (inputDir != "") {
276 string path = m->hasPath(nameFileNames[i]);
277 //if the user has not given a path then, add inputdir. else leave path alone.
278 if (path == "") { nameFileNames[i] = inputDir + nameFileNames[i]; }
284 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
286 //if you can't open it, try default location
287 if (ableToOpen == 1) {
288 if (m->getDefaultPath() != "") { //default path is set
289 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
290 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
292 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
294 nameFileNames[i] = tryPath;
298 if (ableToOpen == 1) {
299 if (m->getOutputDir() != "") { //default path is set
300 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
301 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
303 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
305 nameFileNames[i] = tryPath;
311 if (ableToOpen == 1) {
312 m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
313 //erase from file list
314 nameFileNames.erase(nameFileNames.begin()+i);
317 m->setNameFile(nameFileNames[i]);
323 if (nameFileNames.size() != 0) { hasName = true; }
325 //check for required parameters
326 vector<string> countfileNames;
327 countfile = validParameter.validFile(parameters, "count", false);
328 if (countfile == "not found") {
331 m->splitAtDash(countfile, countfileNames);
333 //go through files and make sure they are good, if not, then disregard them
334 for (int i = 0; i < countfileNames.size(); i++) {
337 if (countfileNames[i] == "current") {
338 countfileNames[i] = m->getCountTableFile();
339 if (nameFileNames[i] != "") { m->mothurOut("Using " + countfileNames[i] + " as input file for the count parameter where you had given current."); m->mothurOutEndLine(); }
341 m->mothurOut("You have no current count file, ignoring current."); m->mothurOutEndLine(); ignore=true;
342 //erase from file list
343 countfileNames.erase(countfileNames.begin()+i);
350 if (inputDir != "") {
351 string path = m->hasPath(countfileNames[i]);
352 //if the user has not given a path then, add inputdir. else leave path alone.
353 if (path == "") { countfileNames[i] = inputDir + countfileNames[i]; }
359 ableToOpen = m->openInputFile(countfileNames[i], in, "noerror");
361 //if you can't open it, try default location
362 if (ableToOpen == 1) {
363 if (m->getDefaultPath() != "") { //default path is set
364 string tryPath = m->getDefaultPath() + m->getSimpleName(countfileNames[i]);
365 m->mothurOut("Unable to open " + countfileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
367 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
369 countfileNames[i] = tryPath;
373 if (ableToOpen == 1) {
374 if (m->getOutputDir() != "") { //default path is set
375 string tryPath = m->getOutputDir() + m->getSimpleName(countfileNames[i]);
376 m->mothurOut("Unable to open " + countfileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
378 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
380 countfileNames[i] = tryPath;
386 if (ableToOpen == 1) {
387 m->mothurOut("Unable to open " + countfileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
388 //erase from file list
389 countfileNames.erase(countfileNames.begin()+i);
392 m->setCountTableFile(countfileNames[i]);
398 if (countfileNames.size() != 0) { hasCount = true; }
400 //make sure there is at least one valid file left
401 if (hasName && hasCount) { m->mothurOut("[ERROR]: You must enter ONLY ONE of the following: count or name."); m->mothurOutEndLine(); abort = true; }
403 if (!hasName && hasCount) { nameFileNames = countfileNames; }
405 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; }
407 bool hasGroup = true;
408 groupfile = validParameter.validFile(parameters, "group", false);
409 if (groupfile == "not found") { groupfile = ""; hasGroup = false; }
411 m->splitAtDash(groupfile, groupFileNames);
413 //go through files and make sure they are good, if not, then disregard them
414 for (int i = 0; i < groupFileNames.size(); i++) {
417 if (groupFileNames[i] == "current") {
418 groupFileNames[i] = m->getGroupFile();
419 if (groupFileNames[i] != "") { m->mothurOut("Using " + groupFileNames[i] + " as input file for the group parameter where you had given current."); m->mothurOutEndLine(); }
421 m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true;
422 //erase from file list
423 groupFileNames.erase(groupFileNames.begin()+i);
430 if (inputDir != "") {
431 string path = m->hasPath(groupFileNames[i]);
432 //if the user has not given a path then, add inputdir. else leave path alone.
433 if (path == "") { groupFileNames[i] = inputDir + groupFileNames[i]; }
439 ableToOpen = m->openInputFile(groupFileNames[i], in, "noerror");
441 //if you can't open it, try default location
442 if (ableToOpen == 1) {
443 if (m->getDefaultPath() != "") { //default path is set
444 string tryPath = m->getDefaultPath() + m->getSimpleName(groupFileNames[i]);
445 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
447 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
449 groupFileNames[i] = tryPath;
453 if (ableToOpen == 1) {
454 if (m->getOutputDir() != "") { //default path is set
455 string tryPath = m->getOutputDir() + m->getSimpleName(groupFileNames[i]);
456 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
458 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
460 groupFileNames[i] = tryPath;
466 if (ableToOpen == 1) {
467 m->mothurOut("Unable to open " + groupFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
468 //erase from file list
469 groupFileNames.erase(groupFileNames.begin()+i);
472 m->setGroupFile(groupFileNames[i]);
477 //make sure there is at least one valid file left
478 if (groupFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid group files."); m->mothurOutEndLine(); abort = true; }
481 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; }
483 if (hasGroup && hasCount) { m->mothurOut("[ERROR]: You must enter ONLY ONE of the following: count or group."); m->mothurOutEndLine(); abort = true; }
484 //if the user changes the output directory command factory will send this info to us in the output parameter
485 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
487 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
488 m->setProcessors(temp);
489 m->mothurConvert(temp, processors);
491 temp = validParameter.validFile(parameters, "save", false); if (temp == "not found"){ temp = "f"; }
492 save = m->isTrue(temp);
494 if (save) { //clear out old references
499 it = parameters.find("reference");
500 //user has given a template file
501 if(it != parameters.end()){
502 if (it->second == "self") {
503 templatefile = "self";
505 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save.");
506 m->mothurOutEndLine();
511 path = m->hasPath(it->second);
512 //if the user has not given a path then, add inputdir. else leave path alone.
513 if (path == "") { parameters["reference"] = inputDir + it->second; }
515 templatefile = validParameter.validFile(parameters, "reference", true);
516 if (templatefile == "not open") { abort = true; }
517 else if (templatefile == "not found") { //check for saved reference sequences
518 if (rdb->referenceSeqs.size() != 0) {
519 templatefile = "saved";
521 m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required.");
522 m->mothurOutEndLine();
525 }else { if (save) { rdb->setSavedReference(templatefile); } }
527 }else if (hasName) { templatefile = "self";
529 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save.");
530 m->mothurOutEndLine();
533 }else if (hasCount) { templatefile = "self";
535 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save.");
536 m->mothurOutEndLine();
541 if (rdb->referenceSeqs.size() != 0) {
542 templatefile = "saved";
544 m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required.");
545 m->mothurOutEndLine();
546 templatefile = ""; abort = true;
552 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found") { temp = "7"; }
553 m->mothurConvert(temp, ksize);
555 temp = validParameter.validFile(parameters, "window", false); if (temp == "not found") { temp = "50"; }
556 m->mothurConvert(temp, window);
558 temp = validParameter.validFile(parameters, "match", false); if (temp == "not found") { temp = "5"; }
559 m->mothurConvert(temp, match);
561 temp = validParameter.validFile(parameters, "mismatch", false); if (temp == "not found") { temp = "-4"; }
562 m->mothurConvert(temp, mismatch);
564 temp = validParameter.validFile(parameters, "divergence", false); if (temp == "not found") { temp = "1.007"; }
565 m->mothurConvert(temp, divR);
567 temp = validParameter.validFile(parameters, "minsim", false); if (temp == "not found") { temp = "90"; }
568 m->mothurConvert(temp, minSimilarity);
570 temp = validParameter.validFile(parameters, "mincov", false); if (temp == "not found") { temp = "70"; }
571 m->mothurConvert(temp, minCoverage);
573 temp = validParameter.validFile(parameters, "minbs", false); if (temp == "not found") { temp = "90"; }
574 m->mothurConvert(temp, minBS);
576 temp = validParameter.validFile(parameters, "minsnp", false); if (temp == "not found") { temp = "10"; }
577 m->mothurConvert(temp, minSNP);
579 temp = validParameter.validFile(parameters, "parents", false); if (temp == "not found") { temp = "3"; }
580 m->mothurConvert(temp, parents);
582 temp = validParameter.validFile(parameters, "realign", false); if (temp == "not found") { temp = "t"; }
583 realign = m->isTrue(temp);
585 temp = validParameter.validFile(parameters, "trim", false); if (temp == "not found") { temp = "f"; }
586 trim = m->isTrue(temp);
588 temp = validParameter.validFile(parameters, "split", false); if (temp == "not found") { temp = "f"; }
589 trimera = m->isTrue(temp);
591 search = validParameter.validFile(parameters, "search", false); if (search == "not found") { search = "blast"; }
593 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "1000"; }
594 m->mothurConvert(temp, iters);
596 temp = validParameter.validFile(parameters, "increment", false); if (temp == "not found") { temp = "5"; }
597 m->mothurConvert(temp, increment);
599 temp = validParameter.validFile(parameters, "numwanted", false); if (temp == "not found") { temp = "15"; }
600 m->mothurConvert(temp, numwanted);
602 temp = validParameter.validFile(parameters, "dereplicate", false);
603 if (temp == "not found") {
604 if (groupfile != "") { temp = "false"; }
605 else { temp = "true"; }
607 dups = m->isTrue(temp);
609 blastlocation = validParameter.validFile(parameters, "blastlocation", false);
610 if (blastlocation == "not found") { blastlocation = ""; }
612 //add / to name if needed
613 string lastChar = blastlocation.substr(blastlocation.length()-1);
614 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
615 if (lastChar != "/") { blastlocation += "/"; }
617 if (lastChar != "\\") { blastlocation += "\\"; }
619 blastlocation = m->getFullPathName(blastlocation);
620 string formatdbCommand = "";
621 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
622 formatdbCommand = blastlocation + "formatdb";
624 formatdbCommand = blastlocation + "formatdb.exe";
627 //test to make sure formatdb exists
629 formatdbCommand = m->getFullPathName(formatdbCommand);
630 int ableToOpen = m->openInputFile(formatdbCommand, in, "no error"); in.close();
631 if(ableToOpen == 1) { m->mothurOut("[ERROR]: " + formatdbCommand + " file does not exist. mothur requires formatdb.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
633 string blastCommand = "";
634 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
635 blastCommand = blastlocation + "megablast";
637 blastCommand = blastlocation + "megablast.exe";
639 //test to make sure formatdb exists
641 blastCommand = m->getFullPathName(blastCommand);
642 ableToOpen = m->openInputFile(blastCommand, in2, "no error"); in2.close();
643 if(ableToOpen == 1) { m->mothurOut("[ERROR]: " + blastCommand + " file does not exist. mothur requires blastall.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
646 if ((search != "blast") && (search != "kmer")) { m->mothurOut(search + " is not a valid search."); m->mothurOutEndLine(); abort = true; }
648 if ((hasName || hasCount) && (templatefile != "self")) { m->mothurOut("You have provided a namefile or countfile and the reference parameter is not set to self. I am not sure what reference you are trying to use, aborting."); m->mothurOutEndLine(); abort=true; }
649 if (hasGroup && (templatefile != "self")) { m->mothurOut("You have provided a group file and the reference parameter is not set to self. I am not sure what reference you are trying to use, aborting."); m->mothurOutEndLine(); abort=true; }
651 //until we resolve the issue 10-18-11
652 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
658 catch(exception& e) {
659 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
663 //***************************************************************************************************************
665 int ChimeraSlayerCommand::execute(){
667 if (abort == true) { if (calledHelp) { return 0; } return 2; }
669 for (int s = 0; s < fastaFileNames.size(); s++) {
671 m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
673 int start = time(NULL);
674 if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]); }//if user entered a file with a path then preserve it
675 map<string, string> variables;
676 variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]));
677 string outputFileName = getOutputFileName("chimera", variables);
678 string accnosFileName = getOutputFileName("accnos", variables);
679 string trimFastaFileName = getOutputFileName("fasta", variables);
682 ofstream out, out1, out2;
683 m->openOutputFile(outputFileName, out); out.close();
684 m->openOutputFile(accnosFileName, out1); out1.close();
685 if (trim) { m->openOutputFile(trimFastaFileName, out2); out2.close(); }
686 outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
687 outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
688 if (trim) { outputNames.push_back(trimFastaFileName); outputTypes["fasta"].push_back(trimFastaFileName); }
690 //maps a filename to priority map.
691 //if no groupfile this is fastafileNames[s] -> prioirity
692 //if groupfile then this is each groups seqs -> priority
693 map<string, map<string, int> > fileToPriority;
694 map<string, map<string, int> >::iterator itFile;
695 map<string, string> fileGroup;
696 fileToPriority[fastaFileNames[s]] = priority; //default
697 fileGroup[fastaFileNames[s]] = "noGroup";
698 map<string, string> uniqueNames;
699 int totalChimeras = 0;
702 if (templatefile == "self") {
704 SequenceCountParser* parser = NULL;
705 setUpForSelfReference(parser, fileGroup, fileToPriority, s);
706 if (parser != NULL) { uniqueNames = parser->getAllSeqsMap(); delete parser; }
708 SequenceParser* parser = NULL;
709 setUpForSelfReference(parser, fileGroup, fileToPriority, s);
710 if (parser != NULL) { uniqueNames = parser->getAllSeqsMap(); delete parser; }
714 if (m->control_pressed) { for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]); } return 0; }
716 if (fileToPriority.size() == 1) { //you running without a groupfile
717 itFile = fileToPriority.begin();
718 string thisFastaName = itFile->first;
719 map<string, int> thisPriority = itFile->second;
721 MPIExecute(thisFastaName, outputFileName, accnosFileName, trimFastaFileName, thisPriority);
724 vector<unsigned long long> positions;
725 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
726 positions = m->divideFile(thisFastaName, processors);
727 for (int i = 0; i < (positions.size()-1); i++) { lines.push_back(linePair(positions[i], positions[(i+1)])); }
729 if (processors == 1) { lines.push_back(linePair(0, 1000)); }
731 positions = m->setFilePosFasta(thisFastaName, numSeqs);
732 if (positions.size() < processors) { processors = positions.size(); }
734 //figure out how many sequences you have to process
735 int numSeqsPerProcessor = numSeqs / processors;
736 for (int i = 0; i < processors; i++) {
737 int startIndex = i * numSeqsPerProcessor;
738 if(i == (processors - 1)){ numSeqsPerProcessor = numSeqs - i * numSeqsPerProcessor; }
739 lines.push_back(linePair(positions[startIndex], numSeqsPerProcessor));
743 if(processors == 1){ numSeqs = driver(lines[0], outputFileName, thisFastaName, accnosFileName, trimFastaFileName, thisPriority); }
744 else{ numSeqs = createProcesses(outputFileName, thisFastaName, accnosFileName, trimFastaFileName, thisPriority); }
746 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; }
748 }else { //you have provided a groupfile
750 MPIExecuteGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup);
752 if (processors == 1) { numSeqs = driverGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup); }
753 else { numSeqs = createProcessesGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup); } //destroys fileToPriority
758 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
763 totalChimeras = deconvoluteResults(uniqueNames, outputFileName, accnosFileName, trimFastaFileName);
764 m->mothurOutEndLine(); m->mothurOut(toString(totalChimeras) + " chimera found."); m->mothurOutEndLine();
768 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
772 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
775 //set accnos file as new current accnosfile
777 itTypes = outputTypes.find("accnos");
778 if (itTypes != outputTypes.end()) {
779 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
783 itTypes = outputTypes.find("fasta");
784 if (itTypes != outputTypes.end()) {
785 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
789 m->mothurOutEndLine();
790 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
791 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
792 m->mothurOutEndLine();
797 catch(exception& e) {
798 m->errorOut(e, "ChimeraSlayerCommand", "execute");
802 //**********************************************************************************************************************
803 int ChimeraSlayerCommand::MPIExecuteGroups(string outputFileName, string accnosFileName, string trimFastaFileName, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup){
810 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
811 MPI_Comm_size(MPI_COMM_WORLD, &processors);
813 //put filenames in a vector, then pass each process a starting and ending point in the vector
814 //all processes already have the fileToPriority and fileGroup, they just need to know which files to process
815 map<string, map<string, int> >::iterator itFile;
816 vector<string> filenames;
817 for(itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) { filenames.push_back(itFile->first); }
819 int numGroupsPerProcessor = filenames.size() / processors;
820 int startIndex = pid * numGroupsPerProcessor;
821 int endIndex = (pid+1) * numGroupsPerProcessor;
822 if(pid == (processors - 1)){ endIndex = filenames.size(); }
824 vector<unsigned long long> MPIPos;
827 MPI_File outMPIAccnos;
828 MPI_File outMPIFasta;
830 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
831 int inMode=MPI_MODE_RDONLY;
833 char outFilename[1024];
834 strcpy(outFilename, outputFileName.c_str());
836 char outAccnosFilename[1024];
837 strcpy(outAccnosFilename, accnosFileName.c_str());
839 char outFastaFilename[1024];
840 strcpy(outFastaFilename, trimFastaFileName.c_str());
842 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
843 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
844 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
846 if (m->control_pressed) { MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
849 if (pid == 0) { //you are the root process
850 m->mothurOutEndLine();
851 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
852 m->mothurOutEndLine();
854 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
857 int length = outTemp.length();
858 char* buf2 = new char[length];
859 memcpy(buf2, outTemp.c_str(), length);
861 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
864 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
866 for (int i = startIndex; i < endIndex; i++) {
868 int start = time(NULL);
870 string thisFastaName = filenames[i];
871 map<string, int> thisPriority = fileToPriority[thisFastaName];
873 char inFileName[1024];
874 strcpy(inFileName, thisFastaName.c_str());
876 MPI_File_open(MPI_COMM_SELF, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
878 MPIPos = m->setFilePosFasta(thisFastaName, num); //fills MPIPos, returns numSeqs
880 cout << endl << "Checking sequences from group: " << fileGroup[thisFastaName] << "." << endl;
882 driverMPI(0, num, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, thisFastaName, thisPriority, true);
885 MPI_File_close(&inMPI);
886 m->mothurRemove(thisFastaName);
888 cout << endl << "It took " << toString(time(NULL) - start) << " secs to check " + toString(num) + " sequences from group " << fileGroup[thisFastaName] << "." << endl;
892 for(int i = 1; i < processors; i++) {
894 MPI_Recv(&temp, 1, MPI_INT, i, 2001, MPI_COMM_WORLD, &status);
897 }else{ MPI_Send(&numSeqs, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD); }
899 MPI_File_close(&outMPI);
900 MPI_File_close(&outMPIAccnos);
901 if (trim) { MPI_File_close(&outMPIFasta); }
903 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
907 }catch(exception& e) {
908 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecuteGroups");
912 //**********************************************************************************************************************
913 int ChimeraSlayerCommand::MPIExecute(string inputFile, string outputFileName, string accnosFileName, string trimFastaFileName, map<string, int>& priority){
917 int pid, numSeqsPerProcessor;
919 vector<unsigned long long> MPIPos;
922 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
923 MPI_Comm_size(MPI_COMM_WORLD, &processors);
927 MPI_File outMPIAccnos;
928 MPI_File outMPIFasta;
930 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
931 int inMode=MPI_MODE_RDONLY;
933 char outFilename[1024];
934 strcpy(outFilename, outputFileName.c_str());
936 char outAccnosFilename[1024];
937 strcpy(outAccnosFilename, accnosFileName.c_str());
939 char outFastaFilename[1024];
940 strcpy(outFastaFilename, trimFastaFileName.c_str());
942 char inFileName[1024];
943 strcpy(inFileName, inputFile.c_str());
945 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
946 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
947 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
948 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
950 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
952 if (pid == 0) { //you are the root process
953 m->mothurOutEndLine();
954 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
955 m->mothurOutEndLine();
957 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
960 int length = outTemp.length();
961 char* buf2 = new char[length];
962 memcpy(buf2, outTemp.c_str(), length);
964 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
967 MPIPos = m->setFilePosFasta(inputFile, numSeqs); //fills MPIPos, returns numSeqs
969 if (templatefile != "self") { //if template=self we can only use 1 processor
970 //send file positions to all processes
971 for(int i = 1; i < processors; i++) {
972 MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
973 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
976 //figure out how many sequences you have to align
977 numSeqsPerProcessor = numSeqs / processors;
978 int startIndex = pid * numSeqsPerProcessor;
979 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
981 if (templatefile == "self") { //if template=self we can only use 1 processor
983 numSeqsPerProcessor = numSeqs;
987 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, inputFile, priority, false);
989 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
991 }else{ //you are a child process
992 if (templatefile != "self") { //if template=self we can only use 1 processor
993 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
994 MPIPos.resize(numSeqs+1);
995 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
997 //figure out how many sequences you have to align
998 numSeqsPerProcessor = numSeqs / processors;
999 int startIndex = pid * numSeqsPerProcessor;
1000 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
1003 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, inputFile, priority, false);
1005 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); return 0; }
1011 MPI_File_close(&inMPI);
1012 MPI_File_close(&outMPI);
1013 MPI_File_close(&outMPIAccnos);
1014 if (trim) { MPI_File_close(&outMPIFasta); }
1015 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
1021 catch(exception& e) {
1022 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecute");
1026 //**********************************************************************************************************************
1027 int ChimeraSlayerCommand::deconvoluteResults(map<string, string>& uniqueNames, string outputFileName, string accnosFileName, string trimFileName){
1029 map<string, string>::iterator itUnique;
1032 if (trimera) { //add in more potential uniqueNames
1033 map<string, string> newUniqueNames = uniqueNames;
1034 for (map<string, string>::iterator it = uniqueNames.begin(); it != uniqueNames.end(); it++) {
1035 newUniqueNames[(it->first)+"_LEFT"] = (it->first)+"_LEFT";
1036 newUniqueNames[(it->first)+"_RIGHT"] = (it->first)+"_RIGHT";
1038 uniqueNames = newUniqueNames;
1039 newUniqueNames.clear();
1044 m->openInputFile(accnosFileName, in2, "no error");
1047 m->openOutputFile(accnosFileName+".temp", out2);
1049 string name; name = "";
1050 set<string> chimerasInFile;
1051 set<string>::iterator itChimeras;
1053 while (!in2.eof()) {
1054 if (m->control_pressed) { in2.close(); out2.close(); m->mothurRemove(outputFileName); m->mothurRemove((accnosFileName+".temp")); return 0; }
1056 in2 >> name; m->gobble(in2);
1059 itUnique = uniqueNames.find(name);
1061 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1063 itChimeras = chimerasInFile.find((itUnique->second));
1065 if (itChimeras == chimerasInFile.end()) {
1066 out2 << itUnique->second << endl;
1067 chimerasInFile.insert((itUnique->second));
1075 m->mothurRemove(accnosFileName);
1076 rename((accnosFileName+".temp").c_str(), accnosFileName.c_str());
1081 m->openInputFile(outputFileName, in);
1084 m->openOutputFile(outputFileName+".temp", out); out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
1086 string rest, parent1, parent2, line;
1087 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
1088 set<string>::iterator itNames;
1090 //assumptions - in file each read will always look like...
1093 F11Fcsw_63104 F11Fcsw_33372 F11Fcsw_37007 0.89441 80.4469 0.2 1.03727 93.2961 52.2 no 0-241 243-369
1098 line = m->getline(in); m->gobble(in);
1099 out << line << endl;
1102 //for the chimera file, we want to make sure if any group finds a sequence to be chimeric then all groups do,
1103 //so if this is a report that did not find it to be chimeric, but it appears in the accnos file,
1104 //then ignore this report and continue until we find the report that found it to be chimeric
1108 if (m->control_pressed) { in.close(); out.close(); m->mothurRemove((outputFileName+".temp")); return 0; }
1110 in >> name; m->gobble(in);
1111 in >> parent1; m->gobble(in);
1113 if (name == "Name") { //name = "Name" because we append the header line each time we add results from the groups
1114 line = m->getline(in); m->gobble(in);
1116 if (parent1 == "no") {
1118 itUnique = uniqueNames.find(name);
1120 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1122 //is this sequence really not chimeric??
1123 itChimeras = chimerasInFile.find(itUnique->second);
1125 if (itChimeras == chimerasInFile.end()) {
1126 //is this sequence not already in the file
1127 itNames = namesInFile.find((itUnique->second));
1129 if (itNames == namesInFile.end()) { out << itUnique->second << '\t' << "no" << endl; namesInFile.insert(itUnique->second); }
1132 }else { //read the rest of the line
1133 double DivQLAQRB,PerIDQLAQRB,BootStrapA,DivQLBQRA,PerIDQLBQRA,BootStrapB;
1134 string flag, range1, range2;
1136 in >> parent2 >> DivQLAQRB >> PerIDQLAQRB >> BootStrapA >> DivQLBQRA >> PerIDQLBQRA >> BootStrapB >> flag >> range1 >> range2; m->gobble(in);
1139 itUnique = uniqueNames.find(name);
1141 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1143 name = itUnique->second;
1144 //is this name already in the file
1145 itNames = namesInFile.find((name));
1147 if (itNames == namesInFile.end()) { //no not in file
1148 if (flag == "no") { //are you really a no??
1149 //is this sequence really not chimeric??
1150 itChimeras = chimerasInFile.find(name);
1152 //then you really are a no so print, otherwise skip
1153 if (itChimeras == chimerasInFile.end()) { print = true; }
1155 }else{ print = true; }
1160 out << name << '\t';
1162 namesInFile.insert(name);
1164 //output parent1's name
1165 itUnique = uniqueNames.find(parent1);
1166 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent1 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1167 else { out << itUnique->second << '\t'; }
1169 //output parent2's name
1170 itUnique = uniqueNames.find(parent2);
1171 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent2 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1172 else { out << itUnique->second << '\t'; }
1174 out << DivQLAQRB << '\t' << PerIDQLAQRB << '\t' << BootStrapA << '\t' << DivQLBQRA << '\t' << PerIDQLBQRA << '\t' << BootStrapB << '\t' << flag << '\t' << range1 << '\t' << range2 << endl;
1182 m->mothurRemove(outputFileName);
1183 rename((outputFileName+".temp").c_str(), outputFileName.c_str());
1188 m->openInputFile(trimFileName, in3);
1191 m->openOutputFile(trimFileName+".temp", out3);
1193 namesInFile.clear();
1195 while (!in3.eof()) {
1196 if (m->control_pressed) { in3.close(); out3.close(); m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); m->mothurRemove((trimFileName+".temp")); return 0; }
1198 Sequence seq(in3); m->gobble(in3);
1200 if (seq.getName() != "") {
1202 itUnique = uniqueNames.find(seq.getName());
1204 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ seq.getName() + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1206 itNames = namesInFile.find((itUnique->second));
1208 if (itNames == namesInFile.end()) {
1209 seq.printSequence(out3);
1217 m->mothurRemove(trimFileName);
1218 rename((trimFileName+".temp").c_str(), trimFileName.c_str());
1223 catch(exception& e) {
1224 m->errorOut(e, "ChimeraSlayerCommand", "deconvoluteResults");
1228 //**********************************************************************************************************************
1229 int ChimeraSlayerCommand::setUpForSelfReference(SequenceParser*& parser, map<string, string>& fileGroup, map<string, map<string, int> >& fileToPriority, int s){
1232 fileToPriority.clear();
1234 string nameFile = "";
1235 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
1236 nameFile = nameFileNames[s];
1237 }else { nameFile = getNamesFile(fastaFileNames[s]); }
1239 //you provided a groupfile
1240 string groupFile = "";
1241 if (groupFileNames.size() != 0) { groupFile = groupFileNames[s]; }
1243 if (groupFile == "") {
1244 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
1246 //sort fastafile by abundance, returns new sorted fastafile name
1247 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush();
1248 priority = sortFastaFile(fastaFileNames[s], nameFile);
1249 m->mothurOut("Done."); m->mothurOutEndLine();
1251 fileToPriority[fastaFileNames[s]] = priority;
1252 fileGroup[fastaFileNames[s]] = "noGroup";
1254 //Parse sequences by group
1255 parser = new SequenceParser(groupFile, fastaFileNames[s], nameFile);
1256 vector<string> groups = parser->getNamesOfGroups();
1258 for (int i = 0; i < groups.size(); i++) {
1259 vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
1260 map<string, string> thisGroupsMap = parser->getNameMap(groups[i]);
1261 string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
1262 priority = sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile);
1263 fileToPriority[newFastaFile] = priority;
1264 fileGroup[newFastaFile] = groups[i];
1271 catch(exception& e) {
1272 m->errorOut(e, "ChimeraSlayerCommand", "setUpForSelfReference");
1276 //**********************************************************************************************************************
1277 int ChimeraSlayerCommand::setUpForSelfReference(SequenceCountParser*& parser, map<string, string>& fileGroup, map<string, map<string, int> >& fileToPriority, int s){
1280 fileToPriority.clear();
1282 string nameFile = "";
1283 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
1284 nameFile = nameFileNames[s];
1285 }else { m->control_pressed = true; return 0; }
1288 if (!ct.testGroups(nameFile)) {
1289 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
1291 //sort fastafile by abundance, returns new sorted fastafile name
1292 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush();
1293 priority = sortFastaFile(fastaFileNames[s], nameFile);
1294 m->mothurOut("Done."); m->mothurOutEndLine();
1296 fileToPriority[fastaFileNames[s]] = priority;
1297 fileGroup[fastaFileNames[s]] = "noGroup";
1299 //Parse sequences by group
1300 parser = new SequenceCountParser(nameFile, fastaFileNames[s]);
1301 vector<string> groups = parser->getNamesOfGroups();
1303 for (int i = 0; i < groups.size(); i++) {
1304 vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
1305 map<string, int> thisGroupsMap = parser->getCountTable(groups[i]);
1306 string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
1307 sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile);
1308 fileToPriority[newFastaFile] = thisGroupsMap;
1309 fileGroup[newFastaFile] = groups[i];
1316 catch(exception& e) {
1317 m->errorOut(e, "ChimeraSlayerCommand", "setUpForSelfReference");
1321 //**********************************************************************************************************************
1322 string ChimeraSlayerCommand::getNamesFile(string& inputFile){
1324 string nameFile = "";
1326 m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
1328 //use unique.seqs to create new name and fastafile
1329 string inputString = "fasta=" + inputFile;
1330 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
1331 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine();
1332 m->mothurCalling = true;
1334 Command* uniqueCommand = new DeconvoluteCommand(inputString);
1335 uniqueCommand->execute();
1337 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
1339 delete uniqueCommand;
1340 m->mothurCalling = false;
1341 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
1343 nameFile = filenames["name"][0];
1344 inputFile = filenames["fasta"][0];
1348 catch(exception& e) {
1349 m->errorOut(e, "ChimeraSlayerCommand", "getNamesFile");
1353 //**********************************************************************************************************************
1355 int ChimeraSlayerCommand::driverGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup){
1359 for (map<string, map<string, int> >::iterator itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) {
1361 if (m->control_pressed) { return 0; }
1363 int start = time(NULL);
1364 string thisFastaName = itFile->first;
1365 map<string, int> thisPriority = itFile->second;
1366 string thisoutputFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.chimera";
1367 string thisaccnosFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.accnos";
1368 string thistrimFastaFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.fasta";
1370 m->mothurOutEndLine(); m->mothurOut("Checking sequences from group: " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine();
1373 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1375 vector<unsigned long long> positions = m->divideFile(thisFastaName, proc);
1376 lines.push_back(linePair(positions[0], positions[1]));
1378 lines.push_back(linePair(0, 1000));
1380 int numSeqs = driver(lines[0], thisoutputFileName, thisFastaName, thisaccnosFileName, thistrimFastaFileName, thisPriority);
1383 m->appendFiles(thisoutputFileName, outputFName); m->mothurRemove(thisoutputFileName);
1384 m->appendFiles(thisaccnosFileName, accnos); m->mothurRemove(thisaccnosFileName);
1385 if (trim) { m->appendFiles(thistrimFastaFileName, fasta); m->mothurRemove(thistrimFastaFileName); }
1386 m->mothurRemove(thisFastaName);
1388 totalSeqs += numSeqs;
1390 m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences from group " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine();
1395 catch(exception& e) {
1396 m->errorOut(e, "ChimeraSlayerCommand", "driverGroups");
1400 /**************************************************************************************************/
1401 int ChimeraSlayerCommand::createProcessesGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup) {
1407 if (fileToPriority.size() < processors) { processors = fileToPriority.size(); }
1409 int groupsPerProcessor = fileToPriority.size() / processors;
1410 int remainder = fileToPriority.size() % processors;
1412 vector< map<string, map<string, int> > > breakUp;
1414 for (int i = 0; i < processors; i++) {
1415 map<string, map<string, int> > thisFileToPriority;
1416 map<string, map<string, int> >::iterator itFile;
1418 int enough = groupsPerProcessor;
1419 if (i == 0) { enough = groupsPerProcessor + remainder; }
1421 for (itFile = fileToPriority.begin(); itFile != fileToPriority.end();) {
1422 thisFileToPriority[itFile->first] = itFile->second;
1423 fileToPriority.erase(itFile++);
1425 if (count == enough) { break; }
1427 breakUp.push_back(thisFileToPriority);
1430 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1431 //loop through and create all the processes you want
1432 while (process != processors) {
1436 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
1438 }else if (pid == 0){
1439 num = driverGroups(outputFName + toString(getpid()) + ".temp", accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", breakUp[process], fileGroup);
1441 //pass numSeqs to parent
1443 string tempFile = outputFName + toString(getpid()) + ".num.temp";
1444 m->openOutputFile(tempFile, out);
1449 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
1450 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1455 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup);
1457 //force parent to wait until all the processes are done
1458 for (int i=0;i<processors;i++) {
1459 int temp = processIDS[i];
1463 for (int i = 0; i < processIDS.size(); i++) {
1465 string tempFile = outputFName + toString(processIDS[i]) + ".num.temp";
1466 m->openInputFile(tempFile, in);
1467 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
1468 in.close(); m->mothurRemove(tempFile);
1472 //////////////////////////////////////////////////////////////////////////////////////////////////////
1473 //Windows version shared memory, so be careful when passing variables through the slayerData struct.
1474 //Above fork() will clone, so memory is separate, but that's not the case with windows,
1475 //////////////////////////////////////////////////////////////////////////////////////////////////////
1477 vector<slayerData*> pDataArray;
1478 DWORD dwThreadIdArray[processors-1];
1479 HANDLE hThreadArray[processors-1];
1481 //Create processor worker threads.
1482 for(int i=1; i<processors; i++ ){
1483 string extension = toString(i) + ".temp";
1484 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);
1485 pDataArray.push_back(tempslayer);
1486 processIDS.push_back(i);
1488 //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
1489 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1490 hThreadArray[i-1] = CreateThread(NULL, 0, MySlayerGroupThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);
1493 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup);
1495 //Wait until all threads have terminated.
1496 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
1498 //Close all thread handles and free memory allocations.
1499 for(int i=0; i < pDataArray.size(); i++){
1500 if (pDataArray[i]->count != pDataArray[i]->end) {
1501 m->mothurOut("[ERROR]: process " + toString(i) + " only processed " + toString(pDataArray[i]->count) + " of " + toString(pDataArray[i]->end) + " sequences assigned to it, quitting. \n"); m->control_pressed = true;
1503 num += pDataArray[i]->count;
1504 CloseHandle(hThreadArray[i]);
1505 delete pDataArray[i];
1509 //append output files
1510 for(int i=0;i<processIDS.size();i++){
1511 m->appendFiles((outputFName + toString(processIDS[i]) + ".temp"), outputFName);
1512 m->mothurRemove((outputFName + toString(processIDS[i]) + ".temp"));
1514 m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1515 m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1518 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
1519 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
1526 catch(exception& e) {
1527 m->errorOut(e, "ChimeraSlayerCommand", "createProcessesGroups");
1531 //**********************************************************************************************************************
1533 int ChimeraSlayerCommand::driver(linePair filePos, string outputFName, string filename, string accnos, string fasta, map<string, int>& priority){
1537 if (templatefile != "self") { //you want to run slayer with a reference template
1538 chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1540 chimera = new ChimeraSlayer(filename, templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1543 if (m->control_pressed) { delete chimera; return 0; }
1545 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1546 templateSeqsLength = chimera->getLength();
1549 m->openOutputFile(outputFName, out);
1552 m->openOutputFile(accnos, out2);
1555 if (trim) { m->openOutputFile(fasta, out3); }
1558 m->openInputFile(filename, inFASTA);
1560 inFASTA.seekg(filePos.start);
1562 if (filePos.start == 0) { chimera->printHeader(out); }
1569 if (m->control_pressed) { delete chimera; out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1; }
1571 Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
1572 string candidateAligned = candidateSeq->getAligned();
1574 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1575 if (candidateSeq->getAligned().length() != templateSeqsLength) {
1576 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1579 chimera->getChimeras(candidateSeq);
1581 if (m->control_pressed) { delete chimera; delete candidateSeq; return 1; }
1583 //if you are not chimeric, then check each half
1584 data_results wholeResults = chimera->getResults();
1586 //determine if we need to split
1587 bool isChimeric = false;
1589 if (wholeResults.flag == "yes") {
1590 string chimeraFlag = "no";
1591 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1593 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1596 if (chimeraFlag == "yes") {
1597 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1601 if ((!isChimeric) && trimera) {
1603 //split sequence in half by bases
1604 string leftQuery, rightQuery;
1605 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1606 divideInHalf(tempSeq, leftQuery, rightQuery);
1608 //run chimeraSlayer on each piece
1609 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1610 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1613 chimera->getChimeras(left);
1614 data_results leftResults = chimera->getResults();
1616 chimera->getChimeras(right);
1617 data_results rightResults = chimera->getResults();
1619 //if either piece is chimeric then report
1620 Sequence trimmed = chimera->print(out, out2, leftResults, rightResults);
1621 if (trim) { trimmed.printSequence(out3); }
1623 delete left; delete right;
1625 }else { //already chimeric
1627 Sequence trimmed = chimera->print(out, out2);
1628 if (trim) { trimmed.printSequence(out3); }
1636 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1637 unsigned long long pos = inFASTA.tellg();
1638 if ((pos == -1) || (pos >= filePos.end)) { break; }
1640 if (inFASTA.eof()) { break; }
1643 delete candidateSeq;
1645 if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
1648 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
1650 int numNoParents = chimera->getNumNoParents();
1651 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(); }
1655 if (trim) { out3.close(); }
1663 catch(exception& e) {
1664 m->errorOut(e, "ChimeraSlayerCommand", "driver");
1668 //**********************************************************************************************************************
1670 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){
1674 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1677 if (templatefile != "self") { //you want to run slayer with a reference template
1678 chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());
1680 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);
1683 if (m->control_pressed) { delete chimera; return 0; }
1685 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1686 templateSeqsLength = chimera->getLength();
1688 for(int i=0;i<num;i++){
1690 if (m->control_pressed) { delete chimera; return 1; }
1692 //read next sequence
1693 int length = MPIPos[start+i+1] - MPIPos[start+i];
1695 char* buf4 = new char[length];
1696 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
1698 string tempBuf = buf4;
1699 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
1700 istringstream iss (tempBuf,istringstream::in);
1704 Sequence* candidateSeq = new Sequence(iss); m->gobble(iss);
1705 string candidateAligned = candidateSeq->getAligned();
1707 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1709 if (candidateSeq->getAligned().length() != templateSeqsLength) {
1710 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1714 chimera->getChimeras(candidateSeq);
1716 if (m->control_pressed) { delete chimera; delete candidateSeq; return 1; }
1718 //if you are not chimeric, then check each half
1719 data_results wholeResults = chimera->getResults();
1721 //determine if we need to split
1722 bool isChimeric = false;
1724 if (wholeResults.flag == "yes") {
1725 string chimeraFlag = "no";
1726 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1728 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1731 if (chimeraFlag == "yes") {
1732 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1736 if ((!isChimeric) && trimera) {
1737 //split sequence in half by bases
1738 string leftQuery, rightQuery;
1739 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1740 divideInHalf(tempSeq, leftQuery, rightQuery);
1742 //run chimeraSlayer on each piece
1743 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1744 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1747 chimera->getChimeras(left);
1748 data_results leftResults = chimera->getResults();
1750 chimera->getChimeras(right);
1751 data_results rightResults = chimera->getResults();
1753 //if either piece is chimeric then report
1754 Sequence trimmed = chimera->print(outMPI, outAccMPI, leftResults, rightResults);
1756 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1758 //write to accnos file
1759 int length = outputString.length();
1760 char* buf2 = new char[length];
1761 memcpy(buf2, outputString.c_str(), length);
1763 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1767 delete left; delete right;
1771 Sequence trimmed = chimera->print(outMPI, outAccMPI);
1774 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1776 //write to accnos file
1777 int length = outputString.length();
1778 char* buf2 = new char[length];
1779 memcpy(buf2, outputString.c_str(), length);
1781 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1788 delete candidateSeq;
1791 if((i+1) % 100 == 0){ cout << "Processing sequence: " << (i+1) << endl; m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n"); }
1794 if(num % 100 != 0){ cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n"); }
1796 int numNoParents = chimera->getNumNoParents();
1797 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; }
1802 catch(exception& e) {
1803 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
1809 /**************************************************************************************************/
1811 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta, map<string, int>& thisPriority) {
1817 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1818 //loop through and create all the processes you want
1819 while (process != processors) {
1823 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
1825 }else if (pid == 0){
1826 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", thisPriority);
1828 //pass numSeqs to parent
1830 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
1831 m->openOutputFile(tempFile, out);
1836 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
1837 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1842 //force parent to wait until all the processes are done
1843 for (int i=0;i<processors;i++) {
1844 int temp = processIDS[i];
1848 for (int i = 0; i < processIDS.size(); i++) {
1850 string tempFile = outputFileName + toString(processIDS[i]) + ".num.temp";
1851 m->openInputFile(tempFile, in);
1852 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
1853 in.close(); m->mothurRemove(tempFile);
1857 //////////////////////////////////////////////////////////////////////////////////////////////////////
1858 //Windows version shared memory, so be careful when passing variables through the slayerData struct.
1859 //Above fork() will clone, so memory is separate, but that's not the case with windows,
1860 //////////////////////////////////////////////////////////////////////////////////////////////////////
1862 vector<slayerData*> pDataArray;
1863 DWORD dwThreadIdArray[processors];
1864 HANDLE hThreadArray[processors];
1866 //Create processor worker threads.
1867 for( int i=0; i<processors; i++ ){
1868 string extension = toString(i) + ".temp";
1869 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);
1870 pDataArray.push_back(tempslayer);
1871 processIDS.push_back(i);
1873 //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
1874 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1875 hThreadArray[i] = CreateThread(NULL, 0, MySlayerThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);
1878 //Wait until all threads have terminated.
1879 WaitForMultipleObjects(processors, hThreadArray, TRUE, INFINITE);
1881 //Close all thread handles and free memory allocations.
1882 for(int i=0; i < pDataArray.size(); i++){
1883 num += pDataArray[i]->count;
1884 CloseHandle(hThreadArray[i]);
1885 delete pDataArray[i];
1889 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
1890 rename((accnos + toString(processIDS[0]) + ".temp").c_str(), accnos.c_str());
1891 if (trim) { rename((fasta + toString(processIDS[0]) + ".temp").c_str(), fasta.c_str()); }
1893 //append output files
1894 for(int i=1;i<processIDS.size();i++){
1895 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
1896 m->mothurRemove((outputFileName + toString(processIDS[i]) + ".temp"));
1898 m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1899 m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1902 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
1903 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
1910 catch(exception& e) {
1911 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
1916 /**************************************************************************************************/
1918 int ChimeraSlayerCommand::divideInHalf(Sequence querySeq, string& leftQuery, string& rightQuery) {
1921 string queryUnAligned = querySeq.getUnaligned();
1922 int numBases = int(queryUnAligned.length() * 0.5);
1924 string queryAligned = querySeq.getAligned();
1925 leftQuery = querySeq.getAligned();
1926 rightQuery = querySeq.getAligned();
1930 for (int i = 0; i < queryAligned.length(); i++) {
1932 if (isalpha(queryAligned[i])) {
1937 if (baseCount >= numBases) { leftSpot = i; break; } //first half
1940 //blank out right side
1941 for (int i = leftSpot; i < leftQuery.length(); i++) { leftQuery[i] = '.'; }
1943 //blank out left side
1944 for (int i = 0; i < leftSpot; i++) { rightQuery[i] = '.'; }
1949 catch(exception& e) {
1950 m->errorOut(e, "ChimeraSlayerCommand", "divideInHalf");
1954 /**************************************************************************************************/
1955 map<string, int> ChimeraSlayerCommand::sortFastaFile(string fastaFile, string nameFile) {
1957 map<string, int> nameAbund;
1959 //read through fastafile and store info
1960 map<string, string> seqs;
1962 m->openInputFile(fastaFile, in);
1966 if (m->control_pressed) { in.close(); return nameAbund; }
1968 Sequence seq(in); m->gobble(in);
1969 seqs[seq.getName()] = seq.getAligned();
1974 //read namefile or countfile
1975 vector<seqPriorityNode> nameMapCount;
1979 ct.readTable(nameFile);
1981 for(map<string, string>::iterator it = seqs.begin(); it != seqs.end(); it++) {
1982 int num = ct.getNumSeqs(it->first);
1983 if (num == 0) { error = 1; }
1985 seqPriorityNode temp(num, it->second, it->first);
1986 nameMapCount.push_back(temp);
1989 }else { error = m->readNames(nameFile, nameMapCount, seqs); }
1991 if (m->control_pressed) { return nameAbund; }
1993 if (error == 1) { m->control_pressed = true; return nameAbund; }
1994 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; }
1996 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
1998 string newFasta = fastaFile + ".temp";
2000 m->openOutputFile(newFasta, out);
2002 //print new file in order of
2003 for (int i = 0; i < nameMapCount.size(); i++) {
2004 out << ">" << nameMapCount[i].name << endl << nameMapCount[i].seq << endl;
2005 nameAbund[nameMapCount[i].name] = nameMapCount[i].numIdentical;
2009 rename(newFasta.c_str(), fastaFile.c_str());
2014 catch(exception& e) {
2015 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2019 /**************************************************************************************************/
2020 map<string, int> ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, string>& nameMap, string newFile) {
2022 map<string, int> nameAbund;
2023 vector<seqPriorityNode> nameVector;
2025 //read through fastafile and store info
2026 map<string, string> seqs;
2028 for (int i = 0; i < thisseqs.size(); i++) {
2030 if (m->control_pressed) { return nameAbund; }
2032 map<string, string>::iterator itNameMap = nameMap.find(thisseqs[i].getName());
2034 if (itNameMap == nameMap.end()){
2035 m->control_pressed = true;
2036 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your namesfile, please correct."); m->mothurOutEndLine();
2038 int num = m->getNumNames(itNameMap->second);
2040 seqPriorityNode temp(num, thisseqs[i].getAligned(), thisseqs[i].getName());
2041 nameVector.push_back(temp);
2045 //sort by num represented
2046 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
2048 if (m->control_pressed) { return nameAbund; }
2050 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; }
2053 m->openOutputFile(newFile, out);
2055 //print new file in order of
2056 for (int i = 0; i < nameVector.size(); i++) {
2057 out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
2058 nameAbund[nameVector[i].name] = nameVector[i].numIdentical;
2065 catch(exception& e) {
2066 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2070 /**************************************************************************************************/
2071 int ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, int>& countMap, string newFile) {
2073 vector<seqPriorityNode> nameVector;
2075 //read through fastafile and store info
2076 map<string, string> seqs;
2078 for (int i = 0; i < thisseqs.size(); i++) {
2080 if (m->control_pressed) { return 0; }
2082 map<string, int>::iterator itCountMap = countMap.find(thisseqs[i].getName());
2084 if (itCountMap == countMap.end()){
2085 m->control_pressed = true;
2086 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your count file, please correct."); m->mothurOutEndLine();
2088 seqPriorityNode temp(itCountMap->second, thisseqs[i].getAligned(), thisseqs[i].getName());
2089 nameVector.push_back(temp);
2093 //sort by num represented
2094 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
2096 if (m->control_pressed) { return 0; }
2098 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; }
2101 m->openOutputFile(newFile, out);
2103 //print new file in order of
2104 for (int i = 0; i < nameVector.size(); i++) {
2105 out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
2112 catch(exception& e) {
2113 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2117 /**************************************************************************************************/