Debian Codegraph @

current/sort/MergeSorted.java

raw symbols SCIP
1 package sort;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.io.PrintStream;
6 import java.util.ArrayList;
7
8 import fileIO.ByteFile;
9 import fileIO.FileFormat;
10 import fileIO.ReadWrite;
11 import shared.KillSwitch;
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.FASTQ;
19 import stream.FastaReadInputStream;
20 import stream.SamLine;
21 import structures.ListNum;
22 import tax.AccessionToTaxid;
23 import tax.GiToTaxid;
24 import tax.TaxTree;
25 import tracker.ReadStats;
26 import var2.ScafMap;
27
28 /**
29 * Sorts reads by name, potentially from multiple input files.
30 *
31 * @author Brian Bushnell
32 * @date September 21, 2016
33 *
34 */
35 public class MergeSorted {
36
37 /*--------------------------------------------------------------*/
38 /*---------------- Initialization ----------------*/
39 /*--------------------------------------------------------------*/
40
41 /**
42 * Code entrance from the command line.
43 * @param args Command line arguments
44 */
45 public static void main(String[] args){
46 Timer t=new Timer();
47 final boolean oldFI=FASTQ.FORCE_INTERLEAVED, oldTI=FASTQ.TEST_INTERLEAVED;
48 MergeSorted x=new MergeSorted(args);
49 x.process(t);
50 FASTQ.FORCE_INTERLEAVED=oldFI;
51 FASTQ.TEST_INTERLEAVED=oldTI;
52
53 //Close the print stream if it was redirected
54 Shared.closeStream(x.outstream);
55 }
56
57 /**
58 * Constructor.
59 * @param args Command line arguments
60 */
61 public MergeSorted(String[] args){
62
63 {//Preparse block for help, config files, and outstream
64 PreParser pp=new PreParser(args, getClass(), false);
65 args=pp.args;
66 outstream=pp.outstream;
67 }
68
69 boolean setInterleaved=false; //Whether interleaved was explicitly set.
70
71 //Set shared static variables
72 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
73 ReadWrite.setZipThreads(Shared.threads());
74
75 //Create a parser object
76 Parser parser=new Parser();
77 boolean ascending=true;
78
79 //Parse each argument
80 for(int i=0; i<args.length; i++){
81 String arg=args[i];
82
83 //Break arguments into their constituent parts, in the form of "a=b"
84 String[] split=arg.split("=");
85 String a=split[0].toLowerCase();
86 String b=split.length>1 ? split[1] : null;
87
88 if(a.equals("verbose")){
89 verbose=Parse.parseBoolean(b);
90 }else if(a.equals("verbose2")){
91 assert(false) : "Verbose2 is disabled.";
92 // verbose2=Parse.parseBoolean(b);
93 }else if(a.equals("allowsubprocess")){
94 allowInputSubprocess=Parse.parseBoolean(b);
95 }else if(a.equals("delete")){
96 delete=Parse.parseBoolean(b);
97 }else if(a.equals("ascending")){
98 ascending=Parse.parseBoolean(b);
99 }else if(a.equals("descending")){
100 ascending=!Parse.parseBoolean(b);
101 }else if(a.equals("length")){
102 if(Parse.parseBoolean(b)){
103 comparator=ReadLengthComparator.comparator;
104 }
105 }else if(a.equals("name")){
106 if(Parse.parseBoolean(b)){
107 comparator=ReadComparatorName.comparator;
108 }
109 }else if(a.equals("quality")){
110 if(Parse.parseBoolean(b)){
111 comparator=ReadQualityComparator.comparator;
112 }
113 }else if(a.equals("position")){
114 if(Parse.parseBoolean(b)){
115 comparator=ReadComparatorPosition.comparator;
116 }
117 }else if(a.equals("list") || a.equals("names")){
118 comparator=new ReadComparatorList(b);
119 }else if(a.equals("random") || a.equals("shuffle")){
120 if(Parse.parseBoolean(b)){
121 comparator=ReadComparatorRandom.comparator;
122 }
123 }else if(a.equals("taxa")){
124 if(Parse.parseBoolean(b)){
125 comparator=ReadComparatorTaxa.comparator;
126 }
127 }else if(a.equals("topo") || a.equals("topological") || a.equals("alphabetic") || a.equals("sequence") || a.equals("lexographic")){
128 if(Parse.parseBoolean(b)){
129 comparator=ReadComparatorTopological.comparator;
130 }
131 }else if(a.equals("flowcell")){
132 if(Parse.parseBoolean(b)){
133 comparator=ReadComparatorFlowcell.comparator;
134 }
135 }else if(a.equalsIgnoreCase("clump") || a.equalsIgnoreCase("clumpify")){
136 if(Parse.parseBoolean(b)){
137 comparator=ReadComparatorClump.comparator;
138 }
139 }else if(a.equals("table") || a.equals("gi") || a.equals("gitable")){
140 if(b==null || "ignore".equalsIgnoreCase(b) || "skip".equalsIgnoreCase(b)){
141 giTableFile=null;
142 TaxTree.CRASH_IF_NO_GI_TABLE=false;
143 }else{giTableFile=b;}
144 }else if(a.equals("accession")){
145 accessionFile=b;
146 }else if(a.equals("tree") || a.equals("taxtree")){
147 taxTreeFile=b;
148 }else if(a.equals("in") || a.equals("in1")){
149 for(String s : b.split(",")){in1.add(s);}
150 }else if(a.equals("maxfiles") || a.equals("files")){
151 maxFiles=Integer.parseInt(b);
152 }else if(a.equals("parse_flag_goes_here")){
153 //Set a variable here
154 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
155 //do nothing
156 }else if(b==null && new File(arg).exists()){
157 in1.add(arg);
158 }else{
159 outstream.println("Unknown parameter "+args[i]);
160 assert(false) : "Unknown parameter "+args[i];
161 // throw new RuntimeException("Unknown parameter "+args[i]);
162 }
163 }
164 if("auto".equalsIgnoreCase(taxTreeFile)){taxTreeFile=TaxTree.defaultTreeFile();}
165 if("auto".equalsIgnoreCase(giTableFile)){giTableFile=TaxTree.defaultTableFile();}
166 if("auto".equalsIgnoreCase(accessionFile)){accessionFile=TaxTree.defaultAccessionFile();}
167
168 if(comparator==ReadComparatorTopological.comparator && genKmer){
169 comparator=ReadComparatorTopological5Bit.comparator;
170 }else{
171 genKmer=false;
172 }
173
174 comparator.setAscending(ascending);
175 SamLine.SET_FROM_OK=true;
176
177 if(comparator==ReadComparatorRandom.comparator){
178 ListNum.setDeterministicRandomSeed(-1);
179 ListNum.setDeterministicRandom(true);
180 }
181
182 {//Process parser fields
183 Parser.processQuality();
184
185 overwrite=ReadStats.overwrite=parser.overwrite;
186 append=ReadStats.append=parser.append;
187 setInterleaved=parser.setInterleaved;
188
189 out1=parser.out1;
190 out2=parser.out2;
191
192 extin=parser.extin;
193 extout=parser.extout;
194 }
195
196 //Do output file # replacement
197 if(out1!=null && out2==null && out1.indexOf('#')>-1){
198 out2=out1.replace("#", "2");
199 out1=out1.replace("#", "1");
200 }
201
202 assert(FastaReadInputStream.settingsOK());
203
204 //Ensure there is an input file
205 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
206
207 //Adjust the number of threads for input file reading
208 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
209 ByteFile.FORCE_MODE_BF2=true;
210 }
211
212 //Ensure out2 is not set without out1
213 if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
214
215 //Adjust interleaved settings based on number of output files
216 if(!setInterleaved){
217 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
218 }
219
220 //Ensure output files can be written
221 if(!Tools.testOutputFiles(overwrite, append, false, out1, out2)){
222 outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2);
223 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+"\n");
224 }
225
226 //Ensure input files can be read
227 if(!Tools.testInputFiles(false, true, in1.toArray(new String[0]))){
228 throw new RuntimeException("\nCan't read some input files.\n");
229 }
230
231 //Ensure that no file was specified multiple times
232 if(!Tools.testForDuplicateFiles(true, out1, out2)){
233 throw new RuntimeException("\nSome file names were specified multiple times.\n");
234 }
235
236 //Create output FileFormat objects
237 ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, append, false);
238 ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, append, false);
239
240 if(comparator==ReadComparatorPosition.comparator){
241 if(ReadComparatorPosition.scafMap==null){
242 ReadComparatorPosition.scafMap=ScafMap.loadSamHeader(in1.get(0));
243 }
244 }
245
246 if((comparator==ReadComparatorTaxa.comparator)){
247 if(giTableFile!=null){
248 outstream.println("Loading gi table.");
249 GiToTaxid.initialize(giTableFile);
250 }
251 if(accessionFile!=null){
252 outstream.println("Loading accession table.");
253 AccessionToTaxid.load(accessionFile);
254 }
255 if(taxTreeFile!=null){
256 ReadComparatorTaxa.tree=TaxTree.loadTaxTree(taxTreeFile, outstream, true, false);
257 assert(ReadComparatorTaxa.tree.nameMap()!=null);
258 }else{
259 throw new RuntimeException("No tree specified.");
260 }
261 }
262
263 {
264 FileFormat ffin=null;
265 if(in1!=null && in1.size()>0){
266 ffin=FileFormat.testInput(in1.get(0), null, false);
267 }
268 tempExt=Tools.getTempExt(ffin, ffout1, extout);
269 }
270 }
271
272 /*--------------------------------------------------------------*/
273 /*---------------- Outer Methods ----------------*/
274 /*--------------------------------------------------------------*/
275
276 /** Create read streams and process all data */
277 void process(Timer t){
278
279 //Reset counters
280 readsProcessed=0;
281 basesProcessed=0;
282
283 //Process the read stream
284 ArrayList<String> currentList=mergeRecursive(in1);
285 merge(currentList, ffout1, ffout2);
286
287 if(verbose){outstream.println("Finished; closing streams.");}
288
289 //Report timing and results
290 t.stop("Time: \t");
291
292 //Throw an exception of there was an error in a thread
293 if(errorState){
294 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
295 }
296 }
297
298 private ArrayList<String> mergeRecursive(final ArrayList<String> inList){
299 assert(maxFiles>1);
300 ArrayList<String> currentList=inList;
301 final int oldZL=ReadWrite.ZIPLEVEL;
302 while(currentList.size()>maxFiles){
303 ReadWrite.ZIPLEVEL=Tools.min(ReadWrite.ZIPLEVEL, 4);
304 final int size=currentList.size();
305 final int groups=(size+maxFiles-1)/maxFiles;
306 assert(groups>0 && groups<size);
307 ArrayList<ArrayList<String>> listList=new ArrayList<ArrayList<String>>();
308 ArrayList<String> outList=new ArrayList<String>();
309 for(int i=0; i<groups; i++){
310 listList.add(new ArrayList<String>());
311 }
312 for(int i=0; i<size; i++){
313 listList.get(i%groups).add(currentList.get(i));
314 }
315 for(ArrayList<String> subList : listList){
316 String temp=getTempFile();
317 FileFormat ff=FileFormat.testOutput(temp, FileFormat.FASTQ, null, true, false, false, false);
318 merge(subList, ff, null);
319 outList.add(temp);
320 }
321 currentList=outList;
322 }
323 ReadWrite.ZIPLEVEL=oldZL;
324 return currentList;
325 }
326
327 public String getTempFile(){
328 String temp;
329 File dir=new File(".");//(Shared.tmpdir()==null ? null : new File(Shared.tmpdir()));
330 if(dir!=null && !dir.exists()){dir.mkdirs();}
331 try {
332 temp=File.createTempFile("sort_temp_", tempExt, dir).toString();
333 } catch (IOException e) {
334 // TODO Auto-generated catch block
335 e.printStackTrace();
336 KillSwitch.kill(e.getMessage());
337 return null;
338 }
339 return temp;
340 }
341
342 public void merge(ArrayList<String> inList, FileFormat ff1, FileFormat ff2){
343 errorState|=SortByName.mergeAndDump(inList, /*null, */ff1, ff2, delete, useSharedHeader, allowInputSubprocess, outstream, SortByName.maxSizeObservedStatic());
344 }
345
346 /*--------------------------------------------------------------*/
347 /*---------------- Fields ----------------*/
348 /*--------------------------------------------------------------*/
349
350 /** Primary input file path */
351 private ArrayList<String> in1=new ArrayList<String>();
352
353 /** Primary output file path */
354 private String out1=null;
355 /** Secondary output file path */
356 private String out2=null;
357
358 /** Override input file extension */
359 private String extin=null;
360 /** Override output file extension */
361 private String extout=null;
362
363 private String giTableFile=null;;
364 private String taxTreeFile=null;
365 private String accessionFile=null;
366
367 /*--------------------------------------------------------------*/
368
369 // long maxLengthObserved=0;
370
371 /** Number of reads processed */
372 protected long readsProcessed=0;
373 /** Number of bases processed */
374 protected long basesProcessed=0;
375
376 private int maxFiles=16;
377
378 private boolean delete=true;
379
380 private boolean useSharedHeader=false;
381
382 private boolean allowInputSubprocess=true;
383
384 private String tempExt=null;
385
386 private boolean genKmer=true;
387
388 /*--------------------------------------------------------------*/
389 /*---------------- Final Fields ----------------*/
390 /*--------------------------------------------------------------*/
391
392 /** Primary output file */
393 private final FileFormat ffout1;
394 /** Secondary output file */
395 private final FileFormat ffout2;
396
397 private static ReadComparator comparator=ReadComparatorName.comparator;
398
399 /*--------------------------------------------------------------*/
400 /*---------------- Common Fields ----------------*/
401 /*--------------------------------------------------------------*/
402
403 /** Print status messages to this output stream */
404 private PrintStream outstream=System.err;
405 /** Print verbose messages */
406 public static boolean verbose=false;
407 /** Print verbose messages */
408 public static final boolean verbose2=false;
409 /** True if an error was encountered */
410 public boolean errorState=false;
411 /** Overwrite existing output files */
412 private boolean overwrite=true;
413 /** Append to existing output files */
414 private boolean append=false;
415
416 }