1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
|
package tax;
import java.io.File;
import java.io.PrintStream;
import java.util.LinkedHashMap;
import java.util.Locale;
import fileIO.ByteFile;
import fileIO.ByteStreamWriter;
import fileIO.FileFormat;
import fileIO.ReadWrite;
import fileIO.TextStreamWriter;
import shared.Parse;
import shared.Parser;
import shared.PreParser;
import shared.Shared;
import shared.Timer;
import shared.Tools;
import stream.FastaReadInputStream;
/**
* Constructs a directory and file tree of sequences
* corresponding to a taxonomic tree.
*
* @author Brian Bushnell
* @date December 12, 2017
*
*/
public class ExplodeTree {
/*--------------------------------------------------------------*/
/*---------------- Initialization ----------------*/
/*--------------------------------------------------------------*/
/**
* Code entrance from the command line.
* @param args Command line arguments
*/
public static void main(String[] args){
Timer t=new Timer();
ExplodeTree x=new ExplodeTree(args);
x.process(t);
//Close the print stream if it was redirected
Shared.closeStream(x.outstream);
}
/**
* Constructor.
* @param args Command line arguments
*/
public ExplodeTree(String[] args){
{//Preparse block for help, config files, and outstream
PreParser pp=new PreParser(args, getClass(), false);
args=pp.args;
outstream=pp.outstream;
}
//Set shared static variables
ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
ReadWrite.MAX_ZIP_THREADS=Shared.threads();
//Create a parser object
Parser parser=new Parser();
//Parse each argument
for(int i=0; i<args.length; i++){
String arg=args[i];
//Break arguments into their constituent parts, in the form of "a=b"
String[] split=arg.split("=");
String a=split[0].toLowerCase();
String b=split.length>1 ? split[1] : null;
if(a.equals("verbose")){
verbose=Parse.parseBoolean(b);
}else if(a.equals("out") || a.equals("path") || a.equals("outpath")){
outPath=b;
}else if(a.equals("prefix")){
prefix=b;
}else if(a.equals("results") || a.equals("result")){
resultsFile=b;
}else if(a.equals("makedirectories") || a.equals("mkdirs") || a.equals("mkdir")){
makeDirectories=Parse.parseBoolean(b);
}else if(a.equals("tree") || a.equals("taxtree")){
taxTreeFile=b;
}else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
//do nothing
}else{
outstream.println("Unknown parameter "+args[i]);
assert(false) : "Unknown parameter "+args[i];
// throw new RuntimeException("Unknown parameter "+args[i]);
}
}
if(prefix==null){prefix="";}
if("auto".equalsIgnoreCase(taxTreeFile)){taxTreeFile=TaxTree.defaultTreeFile();}
{//Process parser fields
Parser.processQuality();
maxReads=parser.maxReads;
overwrite=parser.overwrite;
in1=parser.in1;
extin=parser.extin;
}
if(outPath==null || outPath.trim().length()==0){outPath="";}
else{
outPath=outPath.trim().replace('\\', '/').replaceAll("/+", "/");
if(!outPath.endsWith("/")){outPath=outPath+"/";}
}
assert(FastaReadInputStream.settingsOK());
//Ensure there is an input file
if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
//Adjust the number of threads for input file reading
if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
ByteFile.FORCE_MODE_BF2=true;
}
//Ensure output files can be written
if(!Tools.testOutputFiles(overwrite, false, false, resultsFile)){
outstream.println(resultsFile);
throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+resultsFile+"\n");
}
//Ensure input files can be read
if(!Tools.testInputFiles(false, true, in1)){
throw new RuntimeException("\nCan't read some input files.\n");
}
//Ensure that no file was specified multiple times
if(!Tools.testForDuplicateFiles(true, in1, resultsFile)){
throw new RuntimeException("\nSome file names were specified multiple times.\n");
}
//Create input FileFormat objects
ffin1=FileFormat.testInput(in1, FileFormat.FASTA, extin, true, true);
tree=TaxTree.loadTaxTree(taxTreeFile, outstream, true, false);
}
/*--------------------------------------------------------------*/
/*---------------- Outer Methods ----------------*/
/*--------------------------------------------------------------*/
public void makeDirectoryTree(String root, boolean writeNames){
for(TaxNode node : tree.nodes){
if(node!=null){
String dir=tree.toDir(node, root);
File df=new File(dir);
if(!df.exists()){df.mkdirs();}
if(writeNames){
try {
String fname=node.simpleName()+".name";
File nf=new File(fname);
if(!nf.exists()){
ReadWrite.writeString(node.name, dir+fname);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
/** Create read streams and process all data */
public void process(Timer t){
Timer t2=new Timer();
if(makeDirectories){
makeDirectoryTree(outPath, true);
t2.stop("Finished making directories. ");
t2.start();
}
processInner();
t2.stop();
t2.stop("Finished writing data. ");
//Do anything necessary after processing
if(resultsFile!=null){
TextStreamWriter tsw=new TextStreamWriter(resultsFile, overwrite, false, false);
tsw.start();
for(TaxNode tn : nodes.keySet()){
Long data=nodes.get(tn);
if(data==null){data=0L;}
tsw.println(tn.id+"\t"+data+"\t"+tn.levelStringExtended(false)+"\t"+tn.name);
}
errorState|=tsw.poisonAndWait();
}
//Report timing and results
{
t.stop();
//Calculate units per nanosecond
double rpnano=readsProcessed/(double)(t.elapsed);
double lpnano=linesProcessed/(double)(t.elapsed);
double bpnano=basesProcessed/(double)(t.elapsed);
//Add "k" and "m" for large numbers
String rpstring=Tools.padKM(readsProcessed, 8);
String lpstring=Tools.padKM(linesProcessed, 8);
String bpstring=Tools.padKM(basesProcessed, 8);
String li="Lines In: \t"+linesProcessed+" lines";
String lo="Lines Out: \t"+linesOut+" lines";
while(lo.length()<li.length()){lo=lo+" ";}
String ri="Reads In: \t"+readsProcessed+" reads";
String ro="Reads Out: \t"+readsOut+" reads";
while(ro.length()<ri.length()){ro=ro+" ";}
outstream.println(ri+"\t"+basesProcessed+" bases");
outstream.println(ro+"\t"+basesOut+" bases");
outstream.println(li);
outstream.println(lo);
outstream.println();
outstream.println("Time: \t"+t);
outstream.println("Reads Processed: "+rpstring+" \t"+String.format(Locale.ROOT, "%.2fk reads/sec", rpnano*1000000));
outstream.println("Lines Processed: "+lpstring+" \t"+String.format(Locale.ROOT, "%.2fk reads/sec", lpnano*1000000));
outstream.println("Bases Processed: "+bpstring+" \t"+String.format(Locale.ROOT, "%.2fm bases/sec", bpnano*1000));
}
//Throw an exception of there was an error in a thread
if(errorState){
throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
}
}
/*--------------------------------------------------------------*/
/*---------------- Inner Methods ----------------*/
/*--------------------------------------------------------------*/
/** Iterate through the reads */
void processInner(){
ByteFile bf=ByteFile.makeByteFile(ffin1);
TaxNode currentNode=null;
long currentSize=0;
ByteStreamWriter bsw=null;
for(byte[] line=bf.nextLine(); line!=null; line=bf.nextLine()){
linesProcessed++;
if(line.length>0){
final boolean header=(line[0]=='>');
if(header){
if(maxReads>0 && readsProcessed>=maxReads){break;}
readsProcessed++;
if(currentNode!=null){nodes.put(currentNode, nodes.get(currentNode)+currentSize);}
final TaxNode tn=tree.parseNodeFromHeader(new String(line, 1, line.length-1), false);
if(tn==null || tn!=currentNode){
if(bsw!=null){errorState=bsw.poisonAndWait()|errorState; bsw=null;}
}
if(tn!=null && tn!=currentNode){
String dir=tree.toDir(tn, outPath);
final boolean found=nodes.containsKey(tn);
if(!found){nodes.put(tn, 0L);}
FileFormat ff=FileFormat.testOutput(dir+prefix+tn.id+".fa.gz", FileFormat.FASTA, null, true, overwrite && !found, found, false);
bsw=new ByteStreamWriter(ff);
bsw.start();
}
currentNode=tn;
currentSize=0;
if(bsw!=null){readsOut++;}
}else{
basesProcessed+=line.length;
currentSize+=line.length;
}
if(bsw!=null){
linesOut++;
if(!header){basesOut+=line.length;}
bsw.println(line);
}
}
}
if(bsw!=null){
errorState=bsw.poisonAndWait()|errorState; bsw=null;
if(currentNode!=null){nodes.put(currentNode, nodes.get(currentNode)+currentSize);}
}
bf.close();
}
/*--------------------------------------------------------------*/
/*---------------- Fields ----------------*/
/*--------------------------------------------------------------*/
/** Primary input file path */
private String in1=null;
/** Primary output file path */
private String outPath=null;
private String prefix;
/** Override input file extension */
private String extin=null;
/** For listing what is present in the output */
public String resultsFile=null;
public String taxTreeFile=null;
public boolean makeDirectories=true;
public LinkedHashMap<TaxNode, Long> nodes=new LinkedHashMap<TaxNode, Long>();
/*--------------------------------------------------------------*/
/** Number of reads processed */
protected long readsProcessed=0;
/** Number of lines processed */
protected long linesProcessed=0;
/** Number of bases processed */
protected long basesProcessed=0;
/** Number of reads out */
public long readsOut=0;
/** Number of lines out */
public long linesOut=0;
/** Number of bases out */
public long basesOut=0;
/** Quit after processing this many input reads; -1 means no limit */
private long maxReads=-1;
/*--------------------------------------------------------------*/
/*---------------- Final Fields ----------------*/
/*--------------------------------------------------------------*/
/** Primary input file */
private final FileFormat ffin1;
private final TaxTree tree;
/*--------------------------------------------------------------*/
/*---------------- Common Fields ----------------*/
/*--------------------------------------------------------------*/
/** Print status messages to this output stream */
private PrintStream outstream=System.err;
/** Print verbose messages */
public static boolean verbose=false;
/** True if an error was encountered */
public boolean errorState=false;
/** Overwrite existing output files */
private boolean overwrite=true;
}
|