Debian Codegraph @

current/var2/Realign.java

raw symbols SCIP
1 package var2;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5
6 import fileIO.ByteFile;
7 import fileIO.FileFormat;
8 import fileIO.ReadWrite;
9 import shared.Parse;
10 import shared.Parser;
11 import shared.PreParser;
12 import shared.Shared;
13 import shared.Timer;
14 import shared.Tools;
15 import shared.TrimRead;
16 import stream.ConcurrentReadInputStream;
17 import stream.ConcurrentReadOutputStream;
18 import stream.FastaReadInputStream;
19 import stream.Read;
20 import stream.ReadStreamWriter;
21 import stream.SamLine;
22 import structures.ListNum;
23 import tracker.ReadStats;
24
25 /**
26 * Realigns samlines to a reference.
27 *
28 * @author Brian Bushnell
29 * @date April 26, 2017
30 *
31 */
32 public class Realign {
33
34 /*--------------------------------------------------------------*/
35 /*---------------- Initialization ----------------*/
36 /*--------------------------------------------------------------*/
37
38 /**
39 * Code entrance from the command line.
40 * @param args Command line arguments
41 */
42 public static void main(String[] args){
43 //Start a timer immediately upon code entrance.
44 Timer t=new Timer();
45
46 //Create an instance of this class
47 Realign x=new Realign(args);
48
49 //Run the object
50 x.process(t);
51
52 //Close the print stream if it was redirected
53 Shared.closeStream(x.outstream);
54 }
55
56 /**
57 * Constructor.
58 * @param args Command line arguments
59 */
60 public Realign(String[] args){
61
62 {//Preparse block for help, config files, and outstream
63 PreParser pp=new PreParser(args, getClass(), false);
64 args=pp.args;
65 outstream=pp.outstream;
66 }
67
68 //Set static variables
69 SamLine.PARSE_OPTIONAL_MD_ONLY=true; //I only need the MD tag..
70 SamLine.RNAME_AS_BYTES=false;
71 SamLine.SET_FROM_OK=true;
72 ReadStreamWriter.USE_ATTACHED_SAMLINE=true;
73 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
74 ReadWrite.setZipThreads(Shared.threads());
75 Shared.TRIM_READ_COMMENTS=Shared.TRIM_RNAME=true;
76
77 //Create a parser object
78 Parser parser=new Parser();
79 parser.qtrimLeft=qtrimLeft;
80 parser.qtrimRight=qtrimRight;
81 parser.trimq=trimq;
82
83 samFilter.includeUnmapped=false;
84 samFilter.includeSupplimentary=false;
85 samFilter.includeDuplicate=true;
86 samFilter.includeNonPrimary=true;
87 samFilter.includeQfail=false;
88 samFilter.minMapq=4;
89
90 //Parse each argument
91 for(int i=0; i<args.length; i++){
92 String arg=args[i];
93
94 //Break arguments into their constituent parts, in the form of "a=b"
95 String[] split=arg.split("=");
96 String a=split[0].toLowerCase();
97 String b=split.length>1 ? split[1] : null;
98
99 if(a.equals("verbose")){
100 verbose=Parse.parseBoolean(b);
101 }else if(a.equals("ordered")){
102 ordered=Parse.parseBoolean(b);
103 }else if(a.equals("parse_flag_goes_here")){
104 long fake_variable=Parse.parseKMG(b);
105 //Set a variable here
106 }
107
108
109 else if(a.equals("unclip")){
110 unclip=Parse.parseBoolean(b);
111 }else if(a.equals("realignrows") || a.equals("rerows")){
112 Realigner.defaultMaxrows=Integer.parseInt(b);
113 }else if(a.equals("realigncols") || a.equals("recols")){
114 Realigner.defaultColumns=Integer.parseInt(b);
115 }else if(a.equals("realignpadding") || a.equals("repadding") || a.equals("padding")){
116 Realigner.defaultPadding=Integer.parseInt(b);
117 }else if(a.equals("msa")){
118 Realigner.defaultMsaType=b;
119 }else if(a.equals("ref")){
120 ref=b;
121 }else if(a.equals("border")){
122 border=Integer.parseInt(b);
123 }
124
125 else if(samFilter.parse(arg, a, b)){
126 //do nothing
127 }
128
129
130 else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
131 //do nothing
132 }else{
133 outstream.println("Unknown parameter "+args[i]);
134 assert(false) : "Unknown parameter "+args[i];
135 }
136 }
137
138 samFilter.setSamtoolsFilter();
139
140 {//Process parser fields
141 Parser.processQuality();
142
143 maxReads=parser.maxReads;
144
145 overwrite=ReadStats.overwrite=parser.overwrite;
146 append=ReadStats.append=parser.append;
147
148 in1=parser.in1;
149
150 out1=parser.out1;
151
152 trimq=parser.trimq;
153 trimE=parser.trimE();
154
155 extin=parser.extin;
156 extout=parser.extout;
157 }
158
159 assert(FastaReadInputStream.settingsOK());
160
161 //Ensure there is an input file
162 if(in1==null || ref==null){throw new RuntimeException("Error - one input file and one reference are required.");}
163
164 //Adjust the number of threads for input file reading
165 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
166 ByteFile.FORCE_MODE_BF2=true;
167 }
168
169 //Ensure output files can be written
170 if(!Tools.testOutputFiles(overwrite, append, false, out1)){
171 outstream.println((out1==null)+", "+out1);
172 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+"\n");
173 }
174
175 //Ensure input files can be read
176 if(!Tools.testInputFiles(false, true, in1, ref)){
177 throw new RuntimeException("\nCan't read some input files.\n");
178 }
179
180 //Ensure that no file was specified multiple times
181 if(!Tools.testForDuplicateFiles(true, in1, ref, out1)){
182 throw new RuntimeException("\nSome file names were specified multiple times.\n");
183 }
184
185 //Create output FileFormat objects
186 ffout1=FileFormat.testOutput(out1, FileFormat.SAM, extout, true, overwrite, append, ordered);
187
188 //Create input FileFormat objects
189 ffin1=FileFormat.testInput(in1, FileFormat.SAM, extin, true, true);
190
191 loadReference();
192 }
193
194 private void loadReference(){
195 if(loadedRef){return;}
196 assert(ref!=null);
197 ScafMap.loadReference(ref, scafMap, samFilter, true);
198 Realigner.map=scafMap;
199 loadedRef=true;
200 }
201
202 /*--------------------------------------------------------------*/
203 /*---------------- Outer Methods ----------------*/
204 /*--------------------------------------------------------------*/
205
206 /** Create read streams and process all data */
207 void process(Timer t){
208
209 //Turn off read validation in the input threads to increase speed
210 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
211 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
212
213 //Create a read input stream
214 final ConcurrentReadInputStream cris;
215 {
216 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, null, null, null);
217 cris.start(); //Start the stream
218 if(verbose){outstream.println("Started cris");}
219 }
220 boolean paired=cris.paired();
221 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
222
223 //Optionally create a read output stream
224 final ConcurrentReadOutputStream ros;
225 if(ffout1!=null){
226 //Select output buffer size based on whether it needs to be ordered
227 final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
228
229 //Notify user of output mode
230 if(cris.paired() && (in1!=null && !ffin1.samOrBam() && !ffout1.samOrBam())){
231 outstream.println("Writing interleaved.");
232 }
233
234 ros=ConcurrentReadOutputStream.getStream(ffout1, null, null, null, buff, null, true);
235 ros.start(); //Start the stream
236 }else{ros=null;}
237
238 //Reset counters
239 readsProcessed=0;
240 basesProcessed=0;
241
242 //Process the reads in separate threads
243 spawnThreads(cris, ros);
244
245 if(verbose){outstream.println("Finished; closing streams.");}
246
247 //Write anything that was accumulated by ReadStats
248 errorState|=ReadStats.writeAll();
249 //Close the read streams
250 errorState|=ReadWrite.closeStreams(cris, ros);
251
252 //Reset read validation
253 Read.VALIDATE_IN_CONSTRUCTOR=vic;
254
255 //Report timing and results
256 t.stop();
257 outstream.println("Realignments: \t"+realignmentsAttempted);
258 outstream.println("Successes: \t"+realignmentsSucceeded);
259 outstream.println("Improvements: \t"+realignmentsImproved);
260 outstream.println("Retained: \t"+realignmentsRetained);
261 outstream.println("Bases trimmed: \t"+basesTrimmed);
262 outstream.println();
263 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
264
265 //Throw an exception of there was an error in a thread
266 if(errorState){
267 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
268 }
269 }
270
271 /** Spawn process threads */
272 private void spawnThreads(final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros){
273
274 //Do anything necessary prior to processing
275
276 //Determine how many threads may be used
277 final int threads=Shared.threads();
278
279 //Fill a list with ProcessThreads
280 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
281 for(int i=0; i<threads; i++){
282 alpt.add(new ProcessThread(cris, ros, i));
283 }
284
285 //Start the threads
286 for(ProcessThread pt : alpt){
287 pt.start();
288 }
289
290 //Wait for completion of all threads
291 boolean success=true;
292 for(ProcessThread pt : alpt){
293
294 //Wait until this thread has terminated
295 while(pt.getState()!=Thread.State.TERMINATED){
296 try {
297 //Attempt a join operation
298 pt.join();
299 } catch (InterruptedException e) {
300 //Potentially handle this, if it is expected to occur
301 e.printStackTrace();
302 }
303 }
304
305 //Accumulate per-thread statistics
306 readsProcessed+=pt.readsProcessedT;
307 basesProcessed+=pt.basesProcessedT;
308
309 trimmedBasesProcessed+=pt.trimmedBasesProcessedT;
310 basesTrimmed+=pt.basesTrimmedT;
311 readsDiscarded+=pt.readsDiscardedT;
312 pairedInSequencingReadsProcessed+=pt.pairedInSequencingReadsProcessedT;
313 properlyPairedReadsProcessed+=pt.properlyPairedReadsProcessedT;
314
315 realignmentsAttempted+=pt.realigner.realignmentsAttempted;
316 realignmentsImproved+=pt.realigner.realignmentsImproved;
317 realignmentsSucceeded+=pt.realigner.realignmentsSucceeded;
318 realignmentsRetained+=pt.realigner.realignmentsRetained;
319
320 success&=pt.success;
321 }
322
323 //Track whether any threads failed
324 if(!success){errorState=true;}
325
326 //Do anything necessary after processing
327
328 }
329
330 /*--------------------------------------------------------------*/
331 /*---------------- Inner Methods ----------------*/
332 /*--------------------------------------------------------------*/
333
334 /*--------------------------------------------------------------*/
335 /*---------------- Inner Classes ----------------*/
336 /*--------------------------------------------------------------*/
337
338 /** This class is static to prevent accidental writing to shared variables.
339 * It is safe to remove the static modifier. */
340 private class ProcessThread extends Thread {
341
342 //Constructor
343 ProcessThread(final ConcurrentReadInputStream cris_, final ConcurrentReadOutputStream ros_, final int tid_){
344 cris=cris_;
345 ros=ros_;
346 tid=tid_;
347 realigner=new Realigner();
348 }
349
350 //Called by start()
351 @Override
352 public void run(){
353 //Do anything necessary prior to processing
354
355 //Process the reads
356 processInner();
357
358 //Do anything necessary after processing
359
360 //Indicate successful exit status
361 success=true;
362 }
363
364 /** Iterate through the reads */
365 void processInner(){
366
367 //Grab the first ListNum of reads
368 ListNum<Read> ln=cris.nextList();
369 //Grab the actual read list from the ListNum
370 ArrayList<Read> reads=(ln!=null ? ln.list : null);
371
372 //As long as there is a nonempty read list...
373 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
374 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
375
376 //Loop through each read in the list
377 for(int idx=0; idx<reads.size(); idx++){
378 final Read r1=reads.get(idx);
379
380 //Validate reads in worker threads
381 if(!r1.validated()){r1.validate(true);}
382
383 //Track the initial length for statistics
384 final int initialLength1=r1.length();
385 final int initialLength2=r1.mateLength();
386
387 //Increment counters
388 readsProcessedT+=r1.pairCount();
389 basesProcessedT+=initialLength1+initialLength2;
390
391 {
392 //Reads are processed in this block.
393 boolean keep=processRead(r1);
394 if(!keep){
395 reads.set(idx, null);
396 readsDiscardedT++;
397 }
398 }
399 }
400
401 //Output reads to the output stream
402 if(ros!=null){ros.add(reads, ln.id);}
403
404 //Notify the input stream that the list was used
405 cris.returnList(ln);
406 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
407
408 //Fetch a new list
409 ln=cris.nextList();
410 reads=(ln!=null ? ln.list : null);
411 }
412
413 //Notify the input stream that the final list was used
414 if(ln!=null){
415 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
416 }
417 }
418
419 /**
420 * Process a read.
421 * @param r Read 1
422 * @return True if the reads should be kept, false if they should be discarded.
423 */
424 boolean processRead(final Read r){
425 if(r.bases==null || r.length()<=1){return false;}
426 final SamLine sl=r.samline;
427 final int len0=r.length();
428
429 if(samFilter!=null && !samFilter.passesFilter(sl)){return false;}
430
431 if(sl.properPair()){properlyPairedReadsProcessedT++;}
432 if(sl.hasMate()){pairedInSequencingReadsProcessedT++;}
433 final Scaffold scaf=scafMap.getScaffold(sl);
434 final int scafnum=scaf.number;
435
436 // r.toLongMatchString(false); //Not necessary if scoring can be done on short match string
437 assert(sl.cigar!=null) : sl;
438 boolean realigned=realigner.realign(r, sl, scaf, unclip);
439 if(!realigned && r.match!=null){sl.cigar=SamLine.toCigar14(r.match, r.start, r.stop, scaf.length, sl.seq);}
440 assert(sl.cigar!=null) : sl;
441
442 int leftTrimAmount=border, rightTrimAmount=border;
443 if(qtrimLeft || qtrimRight){
444 long packed=TrimRead.testOptimal(r.bases, r.quality, trimE);
445 if(qtrimLeft){leftTrimAmount=Tools.max(leftTrimAmount, (int)((packed>>32)&0xFFFFFFFFL));}
446 if(qtrimRight){rightTrimAmount=Tools.max(rightTrimAmount, (int)((packed)&0xFFFFFFFFL));}
447 }
448 if(len0-leftTrimAmount-rightTrimAmount<2){return false;}
449
450 int trimmed=(leftTrimAmount<1 && rightTrimAmount<1 ? 0 : TrimRead.trimReadWithMatch(r, sl, leftTrimAmount, rightTrimAmount, 0, scaf.length, false));
451 if(trimmed<0 || r.length()<2 || sl.cigar==null){return false;}
452 basesTrimmedT+=trimmed;
453 if(trimmed>0){sl.optional=null;}
454
455 assert(sl.cigar!=null) : leftTrimAmount+", "+rightTrimAmount+", "+len0+"\n"+sl;
456 return true;
457 }
458
459 /** Number of reads processed by this thread */
460 protected long readsProcessedT=0;
461 /** Number of bases processed by this thread */
462 protected long basesProcessedT=0;
463 /** Number of trimmed, mapped bases processed. */
464 protected long trimmedBasesProcessedT=0;
465 /** Number of trimmed, mapped bases processed. */
466 protected long basesTrimmedT=0;
467 /** Number of reads discarded by this thread */
468 protected long readsDiscardedT=0;
469 /** Number of paired reads processed by this thread, whether or not they mapped as pairs */
470 protected long pairedInSequencingReadsProcessedT=0;
471 /** Number of properly paired reads processed by this thread */
472 protected long properlyPairedReadsProcessedT=0;
473
474 /** True only if this thread has completed successfully */
475 boolean success=false;
476
477 /** Shared input stream */
478 private final ConcurrentReadInputStream cris;
479 /** Shared output stream */
480 private final ConcurrentReadOutputStream ros;
481 /** For realigning reads */
482 final Realigner realigner;
483
484 /** Thread ID */
485 final int tid;
486 }
487
488 /*--------------------------------------------------------------*/
489 /*---------------- Fields ----------------*/
490 /*--------------------------------------------------------------*/
491
492 /** Primary input file path */
493 private String in1=null;
494
495 /** A fasta file. */
496 private String ref=null;
497
498 /** Primary output file path */
499 private String out1=null;
500
501 /** Override input file extension */
502 private String extin=null;
503 /** Override output file extension */
504 private String extout=null;
505
506 /*--------------------------------------------------------------*/
507
508 /** Number of reads processed */
509 protected long readsProcessed=0;
510 /** Number of bases processed */
511 protected long basesProcessed=0;
512
513 /** Quit after processing this many input reads; -1 means no limit */
514 private long maxReads=-1;
515
516 /*--------------------------------------------------------------*/
517
518
519 private boolean loadedRef=false;
520
521 private boolean qtrimLeft=false;
522 private boolean qtrimRight=true;
523 private float trimq=10;
524 private final float trimE;
525
526 /*--------------------------------------------------------------*/
527
528 /** Number of trimmed, mapped bases processed */
529 protected long trimmedBasesProcessed=0;
530 /** Number of reads discarded */
531 protected long readsDiscarded=0;
532 /** Number of paired reads processed by this thread, whether or not they mapped as pairs */
533 protected long pairedInSequencingReadsProcessed=0;
534 /** Number of properly paired reads processed */
535 protected long properlyPairedReadsProcessed=0;
536 /** Number of bases trimmed */
537 protected long basesTrimmed=0;
538
539 protected long realignmentsAttempted;
540 protected long realignmentsImproved;
541 protected long realignmentsSucceeded;
542 protected long realignmentsRetained;
543
544 public final ScafMap scafMap=new ScafMap();
545
546 public int border=0;
547 public boolean unclip=false;
548
549 public final SamFilter samFilter=new SamFilter();
550
551 /*--------------------------------------------------------------*/
552 /*---------------- Final Fields ----------------*/
553 /*--------------------------------------------------------------*/
554
555 /** Primary input file */
556 private final FileFormat ffin1;
557
558 /** Primary output file */
559 private final FileFormat ffout1;
560
561 /*--------------------------------------------------------------*/
562 /*---------------- Common Fields ----------------*/
563 /*--------------------------------------------------------------*/
564
565 /** Print status messages to this output stream */
566 private PrintStream outstream=System.err;
567 /** Print verbose messages */
568 public static boolean verbose=false;
569 /** True if an error was encountered */
570 public boolean errorState=false;
571 /** Overwrite existing output files */
572 private boolean overwrite=true;
573 /** Append to existing output files */
574 private boolean append=false;
575 /** Reads are output in input order */
576 private boolean ordered=true;
577
578 }