Debian Codegraph @

current/jgi/FungalRelease.java

raw symbols SCIP
1 package jgi;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5
6 import fileIO.ByteFile;
7 import fileIO.ByteStreamWriter;
8 import fileIO.FileFormat;
9 import fileIO.ReadWrite;
10 import shared.KillSwitch;
11 import shared.MetadataWriter;
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 sort.ReadLengthComparator;
19 import stream.ConcurrentReadInputStream;
20 import stream.ConcurrentReadOutputStream;
21 import stream.FASTQ;
22 import stream.FastaReadInputStream;
23 import stream.Read;
24 import structures.ListNum;
25 import tracker.ReadStats;
26
27 /**
28 * Reformats a fungal assembly for release. Also creates contig and agp files.
29 *
30 * @author Brian Bushnell
31 * @date December 9, 2015
32 *
33 */
34 public class FungalRelease {
35
36 /*--------------------------------------------------------------*/
37 /*---------------- Initialization ----------------*/
38 /*--------------------------------------------------------------*/
39
40 /**
41 * Code entrance from the command line.
42 *
43 * @param args
44 * Command line arguments
45 */
46 public static void main(String[] args) {
47 Timer t = new Timer();
48 FungalRelease x = new FungalRelease(args);
49 x.process(t);
50
51 // Close the print stream if it was redirected
52 Shared.closeStream(x.outstream);
53 }
54
55 /**
56 * Constructor.
57 *
58 * @param args
59 * Command line arguments
60 */
61 public FungalRelease(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 FASTQ.FORCE_INTERLEAVED = FASTQ.TEST_INTERLEAVED = false;
70 Shared.FASTA_WRAP = 60;
71
72 // Set shared static variables
73 Shared.capBuffers(4);
74 ReadWrite.USE_PIGZ = ReadWrite.USE_UNPIGZ = true;
75 ReadWrite.setZipThreads(Shared.threads());
76
77 Read.TO_UPPER_CASE = true;
78
79 // Create a parser object
80 Parser parser = new Parser();
81
82 // Parse each argument
83 for (int i = 0; i < args.length; i++) {
84 String arg = args[i];
85
86 // Break arguments into their constituent parts, in the form of
87 // "a=b"
88 String[] split = arg.split("=");
89 String a = split[0].toLowerCase();
90 String b = split.length > 1 ? split[1] : null;
91
92 if (parser.parse(arg, a, b)) {// Parse standard flags in the parser
93 // do nothing
94 } else if (a.equals("verbose")) {
95 verbose = Parse.parseBoolean(b);
96 } else if (a.equals("mingapin")) {
97 minGapIn = (int) Parse.parseKMG(b);
98 } else if (a.equals("mingap") || a.equals("mingapout")) {
99 minGapOut = (int) Parse.parseKMG(b);
100 } else if (a.equals("minlen") || a.equals("minlength") || a.equals("minscaf")) {
101 minScaf = (int) Parse.parseKMG(b);
102 } else if (a.equals("mincontig")) {
103 minContig = (int) Parse.parseKMG(b);
104 } else if (a.equals("outc") || a.equals("contigs")) {
105 outC = b;
106 } else if (a.equals("qfoutc")) {
107 qfoutC = b;
108 } else if (a.equals("sortcontigs")) {
109 sortContigs = Parse.parseBoolean(b);
110 } else if (a.equals("sortcscaffolds")) {
111 sortScaffolds = Parse.parseBoolean(b);
112 } else if (a.equals("baniupac")) {
113 banIupac = Parse.parseBoolean(b);
114 } else if (a.equals("agp")) {
115 agpFile = b;
116 } else if (a.equals("legend")) {
117 legendFile = b;
118 } else if (a.equals("scafnum")) {
119 scafNum = Parse.parseKMG(b);
120 } else if (a.equals("renamescaffolds") || a.equals("rename")) {
121 renameScaffolds = Parse.parseBoolean(b);
122 } else if (a.equals("scafnum")) {
123 contigNum = Parse.parseKMG(b);
124 } else if (a.equals("renamecontigs")) {
125 renameContigs = Parse.parseBoolean(b);
126 } else if (a.equals("parse_flag_goes_here")) {
127 // Set a variable here
128 } else {
129 outstream.println("Unknown parameter " + args[i]);
130 assert (false) : "Unknown parameter " + args[i];
131 // throw new RuntimeException("Unknown parameter "+args[i]);
132 }
133 }
134
135 {// Process parser fields
136 Parser.processQuality();
137
138 maxReads = parser.maxReads;
139
140 overwrite = ReadStats.overwrite = parser.overwrite;
141 append = ReadStats.append = parser.append;
142
143 in1 = parser.in1;
144 qfin1 = parser.qfin1;
145
146 out1 = parser.out1;
147 qfout1 = parser.qfout1;
148
149 extin = parser.extin;
150 extout = parser.extout;
151 }
152
153 assert (FastaReadInputStream.settingsOK());
154
155 // Ensure there is an input file
156 if (in1 == null) {
157 throw new RuntimeException("Error - at least one input file is required.");
158 }
159
160 // Adjust the number of threads for input file reading
161 if (!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads() > 2) {
162 ByteFile.FORCE_MODE_BF2 = true;
163 }
164
165 // Ensure output files can be written
166 if (!Tools.testOutputFiles(overwrite, append, false, out1, outC)) {
167 outstream.println((out1 == null) + ", " + out1);
168 throw new RuntimeException("\n\noverwrite=" + overwrite + "; Can't write to output files " + out1 + "\n");
169 }
170
171 // Ensure input files can be read
172 if (!Tools.testInputFiles(false, true, in1)) {
173 throw new RuntimeException("\nCan't read some input files.\n");
174 }
175
176 // Ensure that no file was specified multiple times
177 if (!Tools.testForDuplicateFiles(true, in1, out1, outC)) {
178 throw new RuntimeException("\nSome file names were specified multiple times.\n");
179 }
180
181 // Create output FileFormat objects
182 ffout1 = FileFormat.testOutput(out1, FileFormat.FASTA, extout, true, overwrite, append, false);
183
184 // Create output FileFormat objects
185 ffoutC = FileFormat.testOutput(outC, FileFormat.FASTA, extout, true, overwrite, append, false);
186
187 // Create input FileFormat objects
188 ffin1 = FileFormat.testInput(in1, FileFormat.FASTA, extin, true, true);
189 }
190
191 /*--------------------------------------------------------------*/
192 /*---------------- Outer Methods ----------------*/
193 /*--------------------------------------------------------------*/
194
195 /** Create read streams and process all data */
196 void process(Timer t) {
197
198 // Create a read input stream
199 final ConcurrentReadInputStream cris;
200 {
201 cris = ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, null, qfin1, null);
202 cris.start(); // Start the stream
203 if (verbose) {
204 outstream.println("Started cris");
205 }
206 }
207
208 // Optionally create a read output stream
209 final ConcurrentReadOutputStream ros, rosc;
210 final int buff = 4;
211 if (ffout1 != null) {
212 ros = ConcurrentReadOutputStream.getStream(ffout1, null, qfout1, null, buff, null, false);
213 ros.start(); // Start the stream
214 } else {
215 ros = null;
216 }
217 if (ffoutC != null) {
218 rosc = ConcurrentReadOutputStream.getStream(ffoutC, null, qfoutC, null, 4, null, false);
219 rosc.start(); // Start the stream
220 } else {
221 rosc = null;
222 }
223
224 // Reset counters
225 readsProcessed = 0;
226 basesProcessed = 0;
227 readsOut = 0;
228 basesOut = 0;
229
230 // Process the read stream
231 processInner(cris, ros, rosc);
232
233 if (verbose) {
234 outstream.println("Finished; closing streams.");
235 }
236
237 // Write anything that was accumulated by ReadStats
238 errorState |= ReadStats.writeAll();
239 // Close the read streams
240 errorState |= ReadWrite.closeStreams(cris, ros, rosc);
241
242 // Report timing and results
243 t.stop();
244 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
245 MetadataWriter.write(null, readsProcessed, basesProcessed, readsOut, basesOut, false);
246
247 // Throw an exception of there was an error in a thread
248 if (errorState) {
249 throw new RuntimeException(
250 getClass().getName() + " terminated in an error state; the output may be corrupt.");
251 }
252 }
253
254 /** Iterate through the reads */
255 void processInner(final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros,
256 final ConcurrentReadOutputStream rosc) {
257
258 ArrayList<Read> scaffolds = getReads(cris);
259
260 final boolean makeLegend = (legendFile != null);
261 ByteStreamWriter bswLegend = (makeLegend ? new ByteStreamWriter(legendFile, overwrite, append, false) : null);
262 if (bswLegend != null) {
263 bswLegend.start();
264 }
265
266 if (ros != null) {
267 if (sortScaffolds) {
268 Shared.sort(scaffolds, ReadLengthComparator.comparator);
269 }
270 if (renameScaffolds) {
271 for (Read r : scaffolds) {
272 String old = r.id;
273 r.id = "scaffold_" + scafNum;
274 if (bswLegend != null) {
275 bswLegend.println(old + "\t" + r.id);
276 }
277 scafNum++;
278 }
279 }
280 ros.add(scaffolds, 0);
281 }
282 if (bswLegend != null) {
283 bswLegend.poisonAndWait();
284 }
285
286 final boolean makeAgp = (agpFile != null);
287 ByteStreamWriter bswAgp = (makeAgp ? new ByteStreamWriter(agpFile, overwrite, append, false) : null);
288 if (bswAgp != null) {
289 bswAgp.start();
290 }
291
292 if (rosc != null || makeAgp) {// Process contigs
293 ArrayList<Read> contigs = new ArrayList<Read>();
294 for (Read r : scaffolds) {
295 ArrayList<Read> temp = r.breakAtGaps(makeAgp, minContig);
296 if (bswAgp != null) {
297 bswAgp.print((byte[]) r.obj);
298 r.obj=null;
299 }
300 contigs.addAll(temp);
301 }
302 if (sortContigs) {
303 Shared.sort(contigs, ReadLengthComparator.comparator);
304 }
305 if (renameContigs) {
306 for (Read r : contigs) {
307 r.id = "contig_" + contigNum;
308 contigNum++;
309 }
310 }
311 if (rosc != null) {
312 rosc.add(contigs, 0);
313 }
314 }
315
316 if (bswAgp != null) {
317 bswAgp.poisonAndWait();
318 }
319
320 }
321
322 /** Iterate through the reads */
323 private ArrayList<Read> getReads(final ConcurrentReadInputStream cris) {
324
325 ArrayList<Read> all = new ArrayList<Read>(10000);
326
327 {
328 // Grab the first ListNum of reads
329 ListNum<Read> ln = cris.nextList();
330 // Grab the actual read list from the ListNum
331 ArrayList<Read> reads = (ln != null ? ln.list : null);
332
333 // Check to ensure pairing is as expected
334 if (reads != null && !reads.isEmpty()) {
335 Read r = reads.get(0);
336 assert ((ffin1 == null || ffin1.samOrBam()) || (r.mate != null) == cris.paired());
337 }
338
339 // As long as there is a nonempty read list...
340 while (ln != null && reads != null && reads.size() > 0) {// ln!=null
341 // prevents
342 // a
343 // compiler
344 // potential
345 // null
346 // access
347 // warning
348 if (verbose) {
349 outstream.println("Fetched " + reads.size() + " reads.");
350 }
351
352 // Loop through each read in the list
353 for (int idx = 0; idx < reads.size(); idx++) {
354 final Read r1 = reads.get(idx);
355 assert (r1.mate == null);
356
357 // Track the initial length for statistics
358 final int initialLength1 = r1.length();
359
360 // Increment counters
361 readsProcessed+=1;
362 basesProcessed+=initialLength1;
363
364 boolean keep = processRead(r1);
365 if (keep) {
366 all.add(r1);
367 readsOut+=1;
368 basesOut+=initialLength1;
369 }
370 }
371
372 // Notify the input stream that the list was used
373 cris.returnList(ln);
374 if (verbose) {
375 outstream.println("Returned a list.");
376 }
377
378 // Fetch a new list
379 ln = cris.nextList();
380 reads = (ln != null ? ln.list : null);
381 }
382
383 // Notify the input stream that the final list was used
384 if (ln != null) {
385 cris.returnList(ln.id, ln.list == null || ln.list.isEmpty());
386 }
387 }
388
389 return all;
390 }
391
392 /*--------------------------------------------------------------*/
393 /*---------------- Inner Methods ----------------*/
394 /*--------------------------------------------------------------*/
395
396 /**
397 * Process a single read pair.
398 *
399 * @param r1
400 * Read 1
401 * @return True if the reads should be kept, false if they should be
402 * discarded.
403 */
404 boolean processRead(final Read r1) {
405 //assert (!banIupac || !r1.containsNonACGTN()) : "Non-ACGTN base found in scaffold " + r1.id;
406 if(banIupac){
407 if(r1.containsNonACGTN()){
408 KillSwitch.exceptionKill(new RuntimeException("Non-ACGTN base found in scaffold " + r1.id));
409 }
410 }
411 r1.inflateGaps(minGapIn, minGapOut);
412 return r1.length() >= minScaf;
413 }
414
415 /*--------------------------------------------------------------*/
416 /*---------------- Fields ----------------*/
417 /*--------------------------------------------------------------*/
418
419 private int minGapIn = 1;
420 private int minGapOut = 10;
421 private int minScaf = 1;
422 private int minContig = 1;
423 private long scafNum = 1;
424 private long contigNum = 1;
425
426 private boolean sortScaffolds = true;
427 private boolean sortContigs = false;
428 private boolean banIupac = true;
429 private boolean renameScaffolds = true;
430 private boolean renameContigs = false;
431
432 /*--------------------------------------------------------------*/
433 /*---------------- I/O Fields ----------------*/
434 /*--------------------------------------------------------------*/
435
436 /** Primary input file path */
437 private String in1 = null;
438
439 private String qfin1 = null;
440
441 /** Primary output file path */
442 private String out1 = null;
443 private String outC = null;
444
445 private String qfout1 = null;
446 private String qfoutC = null;
447
448 private String agpFile = null;
449 private String legendFile = null;
450
451 /** Override input file extension */
452 private String extin = null;
453 /** Override output file extension */
454 private String extout = null;
455
456 /*--------------------------------------------------------------*/
457
458 /** Number of reads processed */
459 protected long readsProcessed = 0;
460 /** Number of bases processed */
461 protected long basesProcessed = 0;
462
463 /** Number of reads processed */
464 protected long readsOut = 0;
465 /** Number of bases processed */
466 protected long basesOut = 0;
467
468 /** Quit after processing this many input reads; -1 means no limit */
469 private long maxReads = -1;
470
471 /*--------------------------------------------------------------*/
472 /*---------------- Final Fields ----------------*/
473 /*--------------------------------------------------------------*/
474
475 /** Primary input file */
476 private final FileFormat ffin1;
477
478 /** Primary output file */
479 private final FileFormat ffout1;
480 private final FileFormat ffoutC;
481
482 /*--------------------------------------------------------------*/
483 /*---------------- Common Fields ----------------*/
484 /*--------------------------------------------------------------*/
485
486 /** Print status messages to this output stream */
487 private PrintStream outstream = System.err;
488 /** Print verbose messages */
489 public static boolean verbose = false;
490 /** True if an error was encountered */
491 public boolean errorState = false;
492 /** Overwrite existing output files */
493 private boolean overwrite = false;
494 /** Append to existing output files */
495 private boolean append = false;
496 /** This flag has no effect on singlethreaded programs */
497 private final boolean ordered = false;
498
499 }