Debian Codegraph @

current/tax/ExplodeTree.java

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