Debian Codegraph @

current/var2/ApplyVariants.java

raw symbols SCIP
1 package var2;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5 import java.util.HashMap;
6
7 import fileIO.ByteFile;
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.ConcurrentReadInputStream;
17 import stream.ConcurrentReadOutputStream;
18 import stream.FASTQ;
19 import stream.FastaReadInputStream;
20 import stream.Read;
21 import structures.ByteBuilder;
22 import structures.CoverageArray;
23 import structures.CoverageArray2;
24 import structures.ListNum;
25 import tracker.ReadStats;
26
27 /**
28 * Applies variants
29 *
30 * @author Brian Bushnell
31 * @date August 27, 2019
32 *
33 */
34 public class ApplyVariants {
35
36 /*--------------------------------------------------------------*/
37 /*---------------- Initialization ----------------*/
38 /*--------------------------------------------------------------*/
39
40 /**
41 * Code entrance from the command line.
42 * @param args Command line arguments
43 */
44 public static void main(String[] args){
45 //Start a timer immediately upon code entrance.
46 Timer t=new Timer();
47
48 //Create an instance of this class
49 ApplyVariants x=new ApplyVariants(args);
50
51 //Run the object
52 x.process(t);
53
54 //Close the print stream if it was redirected
55 Shared.closeStream(x.outstream);
56 }
57
58 /**
59 * Constructor.
60 * @param args Command line arguments
61 */
62 public ApplyVariants(String[] args){
63
64 {//Preparse block for help, config files, and outstream
65 PreParser pp=new PreParser(args, getClass(), false);
66 args=pp.args;
67 outstream=pp.outstream;
68 }
69
70 //Set shared static variables prior to parsing
71 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
72 ReadWrite.setZipThreads(Shared.threads());
73 Shared.capBuffers(4); //Only for singlethreaded programs
74
75 {//Parse the arguments
76 final Parser parser=parse(args);
77 Parser.processQuality();
78
79 maxReads=parser.maxReads;
80 overwrite=ReadStats.overwrite=parser.overwrite;
81 append=ReadStats.append=parser.append;
82
83 in1=parser.in1;
84 extin=parser.extin;
85
86 out1=parser.out1;
87 extout=parser.extout;
88 }
89
90 doPoundReplacement(); //Replace # with 1 and 2
91 adjustInterleaving(); //Make sure interleaving agrees with number of input and output files
92 fixExtensions(); //Add or remove .gz or .bz2 as needed
93 checkFileExistence(); //Ensure files can be read and written
94 checkStatics(); //Adjust file-related static fields as needed for this program
95
96 //Create output FileFormat objects
97 ffout1=FileFormat.testOutput(out1, FileFormat.FASTA, extout, true, overwrite, append, ordered);
98
99 //Create input FileFormat objects
100 ffin1=FileFormat.testInput(in1, FileFormat.FASTA, extin, true, true);
101 ffvcf=FileFormat.testInput(inVcf, FileFormat.VCF, null, true, true);
102 ffdepth=FileFormat.testInput(inDepth, FileFormat.TXT, null, true, false);
103 }
104
105 /*--------------------------------------------------------------*/
106 /*---------------- Initialization Helpers ----------------*/
107 /*--------------------------------------------------------------*/
108
109 /** Parse arguments from the command line */
110 private Parser parse(String[] args){
111
112 //Create a parser object
113 Parser parser=new Parser();
114
115 //Set any necessary Parser defaults here
116 //parser.foo=bar;
117
118 //Parse each argument
119 for(int i=0; i<args.length; i++){
120 String arg=args[i];
121
122 //Break arguments into their constituent parts, in the form of "a=b"
123 String[] split=arg.split("=");
124 String a=split[0].toLowerCase();
125 String b=split.length>1 ? split[1] : null;
126 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
127
128 if(a.equals("verbose")){
129 verbose=Parse.parseBoolean(b);
130 }else if(a.equals("vcf") || a.equals("vars")){
131 inVcf=b;
132 }else if(a.equals("name") || a.equals("sample") || a.equals("samplename")){
133 sampleName=b;
134 }else if(a.equals("addnumbers")){
135 addContigNumbers=Parse.parseBoolean(b);
136 }else if(a.equals("useprefix") || a.equals("prefix")){
137 usePrefix=Parse.parseBoolean(b);
138 }else if(a.equals("delimiter")){
139 delimiter=Parse.parseSymbolToCharacter(b);
140 }else if(a.equals("cov") || a.equals("depth") || a.equals("indepth") || a.equals("basecov")){
141 inDepth=b;
142 }else if(a.equals("mindepth") || a.equals("mincov")){
143 minDepth=Integer.parseInt(b);
144 }else if(a.equals("maxindel")){
145 maxIndel=Integer.parseInt(b);
146 if(maxIndel<0){maxIndel=Integer.MAX_VALUE;}
147 }else if(a.equals("noindels")){
148 noIndels=Parse.parseBoolean(b);
149 }else if(a.equals("noframeshifts") || a.equals("banframeshifts")){
150 noFrameshifts=Parse.parseBoolean(b);
151 }else if(a.equals("frameshifts")){
152 noFrameshifts=!Parse.parseBoolean(b);
153 }else if(a.equals("parse_flag_goes_here")){
154 long fake_variable=Parse.parseKMG(b);
155 //Set a variable here
156 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
157 //do nothing
158 }else{
159 outstream.println("Unknown parameter "+args[i]);
160 assert(false) : "Unknown parameter "+args[i];
161 }
162 }
163
164 return parser;
165 }
166
167 /** Replace # with 1 and 2 in headers */
168 private void doPoundReplacement(){
169
170 //Ensure there is an input file
171 if(in1==null || inVcf==null){throw new RuntimeException("Error - one sequence and one vcf file are required.");}
172
173 if(minDepth>0 && inDepth==null){throw new RuntimeException("Error - mindepth requires a coverage file.");}
174
175 }
176
177 /** Add or remove .gz or .bz2 as needed */
178 private void fixExtensions(){
179 in1=Tools.fixExtension(in1);
180 inVcf=Tools.fixExtension(inVcf);
181 inDepth=Tools.fixExtension(inDepth);
182 }
183
184 /** Ensure files can be read and written */
185 private void checkFileExistence(){
186 //Ensure output files can be written
187 if(!Tools.testOutputFiles(overwrite, append, false, out1)){
188 outstream.println((out1==null)+", "+out1);
189 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+"\n");
190 }
191
192 //Ensure input files can be read
193 if(!Tools.testInputFiles(false, true, in1, inVcf, inDepth)){
194 throw new RuntimeException("\nCan't read some input files.\n");
195 }
196
197 //Ensure that no file was specified multiple times
198 if(!Tools.testForDuplicateFiles(true, in1, inVcf, out1)){
199 throw new RuntimeException("\nSome file names were specified multiple times.\n");
200 }
201 }
202
203 /** Make sure interleaving agrees with number of input and output files */
204 private void adjustInterleaving(){
205 FASTQ.FORCE_INTERLEAVED=false;
206 FASTQ.TEST_INTERLEAVED=false;
207 }
208
209 /** Adjust file-related static fields as needed for this program */
210 private static void checkStatics(){
211 //Adjust the number of threads for input file reading
212 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
213 ByteFile.FORCE_MODE_BF2=true;
214 }
215
216 assert(FastaReadInputStream.settingsOK());
217 }
218
219 /*--------------------------------------------------------------*/
220 /*---------------- Outer Methods ----------------*/
221 /*--------------------------------------------------------------*/
222
223 /** Create read streams and process all data */
224 void process(Timer t){
225
226 VCFFile vfile=new VCFFile(ffvcf);
227
228 //Load vcf
229 if(ScafMap.defaultScafMap()==null){
230 ScafMap.setDefaultScafMap(vfile.toScafMap(null), ffvcf.name());
231 }
232
233 if(ffdepth!=null && minDepth>0){
234 depthMap=CoverageArray.loadDepth(ffdepth, CoverageArray2.class);
235 }
236
237 ArrayList<VCFLine> lines=vfile.lines(true);
238 varMap=new HashMap<String, ArrayList<Var>>(ScafMap.defaultScafMap().size());
239 for(VCFLine line : lines){
240 ArrayList<Var> value=varMap.get(line.scaf);
241 if(value==null){
242 value=new ArrayList<Var>();
243 varMap.put(line.scaf, value);
244 }
245 value.add(line.toVar());
246 }
247
248 //Create a read input stream
249 final ConcurrentReadInputStream cris=makeCris();
250
251 //Optionally create a read output stream
252 final ConcurrentReadOutputStream ros=makeCros();
253
254 //Reset counters
255 readsProcessed=readsOut=0;
256 basesProcessed=basesOut=0;
257
258 //Process the read stream
259 processInner(cris, ros);
260
261 if(verbose){outstream.println("Finished; closing streams.");}
262
263 //Write anything that was accumulated by ReadStats
264 errorState|=ReadStats.writeAll();
265 //Close the read streams
266 errorState|=ReadWrite.closeStreams(cris, ros);
267
268 //Report timing and results
269 t.stop();
270 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
271 outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, readsOut, basesOut, 8, false));
272
273 //Throw an exception of there was an error in a thread
274 if(errorState){
275 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
276 }
277 }
278
279 /*--------------------------------------------------------------*/
280 /*---------------- Inner Methods ----------------*/
281 /*--------------------------------------------------------------*/
282
283 private ConcurrentReadInputStream makeCris(){
284 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, null);
285 cris.start(); //Start the stream
286 if(verbose){outstream.println("Started cris");}
287 boolean paired=cris.paired();
288 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
289 return cris;
290 }
291
292 private ConcurrentReadOutputStream makeCros(){
293 if(ffout1==null){return null;}
294
295 //Select output buffer size based on whether it needs to be ordered
296 final int buff=4;
297
298 final ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(ffout1, null, buff, null, false);
299 ros.start(); //Start the stream
300 return ros;
301 }
302
303 /** Iterate through the reads */
304 void processInner(final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros){
305
306 //Do anything necessary prior to processing
307
308 {
309 //Grab the first ListNum of reads
310 ListNum<Read> ln=cris.nextList();
311
312 //Check to ensure pairing is as expected
313 if(ln!=null && !ln.isEmpty()){
314 Read r=ln.get(0);
315 assert(ffin1.samOrBam() || (r.mate!=null)==cris.paired());
316 }
317
318 //As long as there is a nonempty read list...
319 while(ln!=null && ln.size()>0){
320 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
321
322 processList(ln, cris, ros);
323
324 //Fetch a new list
325 ln=cris.nextList();
326 }
327
328 //Notify the input stream that the final list was used
329 if(ln!=null){
330 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
331 }
332 }
333
334 //Do anything necessary after processing
335
336 }
337
338 /**
339 * Process a list of Reads.
340 * @param ln The list.
341 * @param cris Read Input Stream
342 * @param ros Read Output Stream for reads that will be retained
343 */
344 void processList(ListNum<Read> ln, final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros){
345
346 //Grab the actual read list from the ListNum
347 final ArrayList<Read> reads=ln.list;
348
349 //Loop through each read in the list
350 for(int idx=0; idx<reads.size(); idx++){
351 final Read r=reads.get(idx);
352
353 //Validate reads in worker threads
354 if(!r.validated()){r.validate(true);}
355
356 //Track the initial length for statistics
357 final int initialLength1=r.length();
358
359 //Increment counters
360 readsProcessed+=r.pairCount();
361 basesProcessed+=initialLength1;
362
363 Read mutant=processRead(r);
364 reads.set(idx, mutant);
365 readsOut+=mutant.pairCount();
366 basesOut+=mutant.pairLength();
367 }
368
369 //Output reads to the output stream
370 if(ros!=null){ros.add(reads, ln.id);}
371
372 //Notify the input stream that the list was used
373 cris.returnList(ln);
374 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
375 }
376
377 @SuppressWarnings("unused")
378 private void applyDepth(Read r){applyDepth(r, null);}
379
380 private void applyDepth(Read r, CoverageArray ca){
381 if(ca==null){ca=depthMap.get(r.id);}
382 if(ca==null){
383 String s=Tools.trimToWhitespace(r.id);
384 ca=depthMap.get(s);
385 }
386 assert(ca!=null) : "Can't find "+r.id+" in depth map.";
387 final byte[] bases=r.bases;
388 for(int i=0; i<r.bases.length; i++){
389 if(ca.get(i)<minDepth){bases[i]=noCovSymbol;}
390 }
391
392 ArrayList<Var> vars=varMap.get(r.id);
393 if(vars==null){
394 String sub=Tools.trimToWhitespace(r.id);
395 vars=varMap.get(sub);//Handles truncated sequence names
396 }
397 if(vars==null){return;}
398 int removed=0;
399 for(int i=0; i<vars.size(); i++){
400 Var v=vars.get(i);
401 if(ca.get(v.start)<minDepth && v.indel()){
402 vars.set(i, null);
403 removed++;
404 }
405 }
406 if(removed>0){Tools.condenseStrict(vars);}
407 }
408
409 private void filterIndels(final Read r){
410 filterIndels(r, null);
411 }
412
413 private void filterIndels(final Read r, CoverageArray ca){
414 if(minDepth<=0 && maxIndel==Integer.MAX_VALUE && !noIndels && !noFrameshifts){return;}
415
416 if(minDepth>0 && ca==null){
417 ca=depthMap.get(r.id);
418 if(ca==null){
419 String s=Tools.trimToWhitespace(r.id);
420 ca=depthMap.get(s);
421 }
422 assert(ca!=null) : "Can't find "+r.id+" in depth map.";
423 }
424
425 ArrayList<Var> vars=varMap.get(r.id);
426 if(vars==null){
427 String sub=Tools.trimToWhitespace(r.id);
428 vars=varMap.get(sub);//Handles truncated sequence names
429 }
430 if(vars==null){return;}
431 int removed=0;
432 for(int i=0; i<vars.size(); i++){
433 Var v=vars.get(i);
434 boolean remove=false;
435 if(noFrameshifts && v.frameshift()){
436 remove=true;
437 }else if(v.indel()){
438 if(noIndels || Tools.max(v.reflen(), v.readlen())>maxIndel
439 || (ca!=null && ca.get(v.start)<minDepth))
440 remove=true;
441 }
442 if(remove){
443 vars.set(i, null);
444 removed++;
445 }
446 }
447 if(removed>0){Tools.condenseStrict(vars);}
448 }
449
450 /**
451 * Process a single read.
452 * @param r Read 1
453 */
454 Read processRead(final Read r){
455
456 CoverageArray ca=null;
457 if(minDepth>0){
458 assert(depthMap!=null) : "minDepth is "+minDepth+" but depthMap is null. "
459 + "You need a coverage file which includes this contig.";
460 ca=depthMap.get(r.id);
461 if(ca==null){
462 String s=Tools.trimToWhitespace(r.id);
463 ca=depthMap.get(s);
464 }
465 assert(ca!=null) : "Can't find "+r.id+" in depth map.";
466 applyDepth(r, ca);
467 }
468 filterIndels(r, ca);
469
470 String name=r.id;
471 final byte[] bases=r.bases;
472 ArrayList<Var> vars=varMap.get(name);
473 if(vars==null){return r;}
474 HashMap<Integer, Var> map=new HashMap<Integer, Var>();
475 for(Var v : vars){
476 Integer key=v.start;
477 Var old=map.get(key);
478 if(old==null || old.alleleCount()<v.alleleCount()){//TODO: allow retaining the higher quality one
479 map.put(key, v);
480 }
481 }
482
483 ByteBuilder bb=new ByteBuilder();
484 for(int i=0; i<bases.length; ){
485 Var v=map.get(i);
486 if(v==null){
487 bb.append(bases[i]);
488 i++;
489 }else{
490
491 final int reflen=v.reflen();
492 final int readlen=v.readlen();
493
494 applied++;
495
496 //Old code, did not handle 'N' for low coverage
497 // if(readlen>0){
498 // bb.append(v.allele);
499 // }
500 // if(reflen==0){//insertion
501 // bb.append(bases[i]);
502 // i++;
503 // }else{
504 // i+=reflen;
505 // }
506
507 //low-depth indels should have already been removed
508 if(reflen==0){//insertion
509 // final int depth2=(ca==null || minDepth<1 ? 9999 : ca.get(i));
510 // if(depth2>=minDepth){//Apply ins
511 // bb.append(v.allele);
512 // }
513 bb.append(bases[i]);
514 i++;
515 }else if(readlen==0){//del
516 // final int depth2=(ca==null || minDepth<1 ? 9999 : ca.get(i));
517 // if(depth2>=minDepth){//Apply del
518 i+=reflen;
519 // }else{//Ignore del
520 // bb.append(bases[i]);
521 // i++;
522 // }
523 }else if(readlen!=reflen){//complex
524 int lim=i+reflen;
525 for(int j=0; i<lim; i++, j++){
526 final int depth2=(ca==null || minDepth<1 ? 9999 : ca.get(i));
527 byte b=(j<v.allele.length ? v.allele[j] : bases[i]);
528 bb.append(depth2>=minDepth ? b : (byte)'N');
529 }
530 }else{//sub
531 assert(v.reflen()==v.readlen()) : v;
532 for(byte b : v.allele){
533 final int depth2=(ca==null || minDepth<1 ? 9999 : ca.get(i));
534 bb.append(depth2>=minDepth ? b : (byte)'N');
535 i++;
536 }
537 }
538 }
539 }
540
541 final String name2=rename(name, r.numericID);
542
543 Read mutant=new Read(bb.toBytes(), null, name2, r.numericID);
544 return mutant;
545 }
546
547 private String rename(String old, long number){
548 if(sampleName==null){return old;}
549 nameBuilder.clear();
550 if(usePrefix){
551 return nameBuilder.append(sampleName).append(delimiter).append(old).toString();
552 }else if(addContigNumbers){
553 return nameBuilder.append(sampleName).append(delimiter).append(number).toString();
554 }
555 return sampleName;
556 }
557
558 /*--------------------------------------------------------------*/
559 /*---------------- Fields ----------------*/
560 /*--------------------------------------------------------------*/
561
562 /** Primary input file path */
563 private String in1=null;
564 /** Variant input file */
565 private String inVcf;
566 /** Per-base coverage depth file (optional) */
567 private String inDepth;
568
569 /** Primary output file path */
570 private String out1=null;
571
572 /** Override input file extension */
573 private String extin=null;
574 /** Override output file extension */
575 private String extout=null;
576
577 /** If positive, change regions below this depth to N */
578 private int minDepth=0;
579
580 private byte noCovSymbol='N';
581
582 HashMap<String, ArrayList<Var>> varMap;
583
584 HashMap<String, CoverageArray> depthMap;
585
586 /** Name of output sequences, if different from input */
587 String sampleName=null;
588 /** Add numbers as a suffix to the name of each contig, if they will be renamed */
589 boolean addContigNumbers=true;
590 /** Use samplename as prefix, rather than replacing the existing name. */
591 boolean usePrefix=false;
592 /** Delimits modified names. */
593 char delimiter='_';
594
595 /** Ignore non-multiple-of-3 indels */
596 private boolean noFrameshifts=false;
597 /** Ignore indels longer than this */
598 private int maxIndel=Integer.MAX_VALUE;
599 /** Ignore indels */
600 private boolean noIndels=false;
601
602 private ByteBuilder nameBuilder=new ByteBuilder();
603
604 /*--------------------------------------------------------------*/
605
606 /** Number of reads processed */
607 protected long readsProcessed=0;
608 /** Number of bases processed */
609 protected long basesProcessed=0;
610
611 /** Number of reads retained */
612 protected long readsOut=0;
613 /** Number of bases retained */
614 protected long basesOut=0;
615
616 /** Quit after processing this many input reads; -1 means no limit */
617 private long maxReads=-1;
618
619 private long applied=0;
620
621 /*--------------------------------------------------------------*/
622 /*---------------- Final Fields ----------------*/
623 /*--------------------------------------------------------------*/
624
625 /** Primary input file */
626 private final FileFormat ffin1;
627 /** Variant input file */
628 private final FileFormat ffvcf;
629 /** Coverage input file */
630 private final FileFormat ffdepth;
631
632 /** Primary output file */
633 private final FileFormat ffout1;
634
635 /*--------------------------------------------------------------*/
636 /*---------------- Common Fields ----------------*/
637 /*--------------------------------------------------------------*/
638
639 /** Print status messages to this output stream */
640 private PrintStream outstream=System.err;
641 /** Print verbose messages */
642 public static boolean verbose=false;
643 /** True if an error was encountered */
644 public boolean errorState=false;
645 /** Overwrite existing output files */
646 private boolean overwrite=true;
647 /** Append to existing output files */
648 private boolean append=false;
649 /** This flag has no effect on singlethreaded programs */
650 private final boolean ordered=false;
651
652 }