Debian Codegraph @

current/tax/TaxSize.java

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