Debian Codegraph @

current/consensus/ConsensusMaker.java

raw symbols SCIP
1 package consensus;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5 import java.util.LinkedHashMap;
6 import java.util.Map.Entry;
7 import java.util.concurrent.locks.ReadWriteLock;
8 import java.util.concurrent.locks.ReentrantReadWriteLock;
9
10 import fileIO.ByteFile;
11 import fileIO.ByteStreamWriter;
12 import fileIO.FileFormat;
13 import fileIO.ReadWrite;
14 import prok.ProkObject;
15 import shared.Parse;
16 import shared.Parser;
17 import shared.PreParser;
18 import shared.Shared;
19 import shared.Timer;
20 import shared.Tools;
21 import sketch.SketchObject;
22 import stream.ConcurrentReadInputStream;
23 import stream.ConcurrentReadOutputStream;
24 import stream.FASTQ;
25 import stream.FastaReadInputStream;
26 import stream.Read;
27 import stream.SamLine;
28 import stream.SamReadStreamer;
29 import stream.SamStreamer;
30 import structures.ByteBuilder;
31 import structures.ListNum;
32 import template.Accumulator;
33 import template.ThreadWaiter;
34 import tracker.ReadStats;
35 import var2.Realigner;
36 import var2.SamFilter;
37
38 /**
39 * Alters a reference to represent the consensus of aligned reads.
40 *
41 * @author Brian Bushnell
42 * @date September 6, 1019
43 *
44 */
45 public class ConsensusMaker extends ConsensusObject implements Accumulator<ConsensusMaker.ProcessThread> {
46
47 /*--------------------------------------------------------------*/
48 /*---------------- Initialization ----------------*/
49 /*--------------------------------------------------------------*/
50
51 /**
52 * Code entrance from the command line.
53 * @param args Command line arguments
54 */
55 public static void main(String[] args){
56 //Start a timer immediately upon code entrance.
57 Timer t=new Timer();
58
59 //Create an instance of this class
60 ConsensusMaker x=new ConsensusMaker(args);
61
62 //Run the object
63 x.process(t);
64
65 //Close the print stream if it was redirected
66 Shared.closeStream(x.outstream);
67 }
68
69 /**
70 * Constructor.
71 * @param args Command line arguments
72 */
73 public ConsensusMaker(String[] args){
74
75 {//Preparse block for help, config files, and outstream
76 PreParser pp=new PreParser(args, getClass(), false);
77 args=pp.args;
78 outstream=pp.outstream;
79 }
80
81 //Set shared static variables prior to parsing
82 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
83 ReadWrite.setZipThreads(Shared.threads());
84 FASTQ.TEST_INTERLEAVED=FASTQ.FORCE_INTERLEAVED=false;
85
86 samFilter.includeUnmapped=false;
87 // samFilter.includeSupplimentary=false;
88 // samFilter.includeDuplicate=false;
89 samFilter.includeNonPrimary=false;
90 samFilter.includeQfail=false;
91 // samFilter.minMapq=4;
92
93 {//Parse the arguments
94 final Parser parser=parse(args);
95
96 Parser.processQuality();
97
98 maxReads=parser.maxReads;
99 overwrite=ReadStats.overwrite=parser.overwrite;
100 append=ReadStats.append=parser.append;
101
102 in=parser.in1;
103 extin=parser.extin;
104
105 out=parser.out1;
106 extout=parser.extout;
107 silent=Parser.silent;
108 }
109
110 {
111 // if("auto".equalsIgnoreCase(atomic)){Scaffold.setCA3A(Shared.threads()>8);}
112 // else{Scaffold.setCA3A(Parse.parseBoolean(atomic));}
113
114 if(ploidy<1){System.err.println("WARNING: ploidy not set; assuming ploidy=1."); ploidy=1;}
115 samFilter.setSamtoolsFilter();
116
117 streamerThreads=Tools.max(1, Tools.min(streamerThreads, Shared.threads()));
118 assert(streamerThreads>0) : streamerThreads;
119 }
120
121 validateParams();
122 fixExtensions(); //Add or remove .gz or .bz2 as needed
123 checkFileExistence(); //Ensure files can be read and written
124 checkStatics(); //Adjust file-related static fields as needed for this program
125
126 //Create output FileFormat objects
127 ffout=FileFormat.testOutput(out, FileFormat.FASTA, extout, true, overwrite, append, ordered);
128 ffmodel=FileFormat.testOutput(outModel, FileFormat.ALM, null, true, overwrite, false, ordered);
129
130 //Create input FileFormat objects
131 ffin=FileFormat.testInput(in, FileFormat.SAM, extin, true, true);
132 ffref=FileFormat.testInput(ref, FileFormat.FASTA, null, true, true);
133
134 if(inModelFile!=null){
135 ArrayList<BaseGraph> list=(ArrayList<BaseGraph>)ReadWrite.readObject(inModelFile, false);
136 inModel=list.get(0);
137 inModel.calcProbs();
138 inModel.makeWeights();
139 }
140 }
141
142 /*--------------------------------------------------------------*/
143 /*---------------- Initialization Helpers ----------------*/
144 /*--------------------------------------------------------------*/
145
146 /** Parse arguments from the command line */
147 private Parser parse(String[] args){
148
149 //Create a parser object
150 Parser parser=new Parser();
151
152 //Set any necessary Parser defaults here
153 //parser.foo=bar;
154
155 //Parse each argument
156 for(int i=0; i<args.length; i++){
157 String arg=args[i];
158
159 //Break arguments into their constituent parts, in the form of "a=b"
160 String[] split=arg.split("=");
161 String a=split[0].toLowerCase();
162 String b=split.length>1 ? split[1] : null;
163 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
164
165 if(a.equals("verbose")){
166 verbose=Parse.parseBoolean(b);
167 BaseGraph.verbose=verbose;
168 }else if(a.equals("ref")){
169 ref=b;
170 }else if(a.equals("outm") || a.equals("outmodel") || a.equals("model") || a.equals("alm")){
171 outModel=b;
172 }else if(a.equals("inm") || a.equals("inmodel")){
173 inModelFile=b;
174 }else if(a.equals("hist") || a.equals("histogram")){
175 outHistFile=b;
176 }else if(a.equals("realign")){
177 realign=Parse.parseBoolean(b);
178 }else if(a.equals("printscores")){
179 printScores=Parse.parseBoolean(b);
180 }else if(a.equalsIgnoreCase("useMapq")){
181 useMapq=Parse.parseBoolean(b);
182 }else if(a.equalsIgnoreCase("identityCeiling") || a.equalsIgnoreCase("idceiling") || a.equalsIgnoreCase("ceiling")){
183 double d=Double.parseDouble(b);
184 if(d<=2){d=d*100;}
185 identityCeiling=(int)d;
186 invertIdentity=true;
187 }else if(a.equalsIgnoreCase("invertIdentity")){
188 invertIdentity=Parse.parseBoolean(b);
189 }else if(a.equals("name") || a.equals("rename") || a.equals("header")){
190 name=b;
191 }else if(a.equals("noindels")){
192 noIndels=Parse.parseBoolean(b);
193 }else if(a.equalsIgnoreCase("onlyConvertNs") || a.equalsIgnoreCase("nOnly") || a.equalsIgnoreCase("onlyN")){
194 onlyConvertNs=Parse.parseBoolean(b);
195 }else if(a.equals("ploidy")){
196 ploidy=Integer.parseInt(b);
197 }else if(a.equals("mindepth")){
198 minDepth=Integer.parseInt(b);
199 }else if(a.equals("trimdepth") || a.equals("trimdepthfraction")){
200 trimDepthFraction=Float.parseFloat(b);
201 }else if(a.equalsIgnoreCase("trimNs")){
202 trimNs=Parse.parseBoolean(b);
203 }else if(a.equalsIgnoreCase("mafn") || a.equals("mafnoref")){
204 MAF_noref=Float.parseFloat(b);
205 }else if(a.equalsIgnoreCase("mafsub")){
206 MAF_sub=Float.parseFloat(b);
207 }else if(a.equalsIgnoreCase("mafdel")){
208 MAF_del=Float.parseFloat(b);
209 }else if(a.equalsIgnoreCase("mafins")){
210 MAF_ins=Float.parseFloat(b);
211 }else if(a.equalsIgnoreCase("maf")){
212 MAF_ins=MAF_noref=MAF_del=MAF_sub=Float.parseFloat(b);
213 }else if(a.equalsIgnoreCase("mafindel")){
214 MAF_ins=MAF_del=Float.parseFloat(b);
215 }else if(a.equals("clearfilters")){
216 if(Parse.parseBoolean(b)){
217 samFilter.clear();
218 }
219 }else if(a.equals("parse_flag_goes_here")){
220 long fake_variable=Parse.parseKMG(b);
221 //Set a variable here
222 }else if(samFilter.parse(arg, a, b)){
223 //do nothing
224 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
225 //do nothing
226 }else{
227 outstream.println("Unknown parameter "+args[i]);
228 assert(false) : "Unknown parameter "+args[i];
229 }
230 }
231
232 if(ref!=null && !Tools.existsInput(ref)){
233 specialRef=ProkObject.isSpecialType(ref);
234 }
235
236 return parser;
237 }
238
239 /** Add or remove .gz or .bz2 as needed */
240 private void fixExtensions(){
241 in=Tools.fixExtension(in);
242 if(!specialRef){ref=Tools.fixExtension(ref);}
243 }
244
245 /** Ensure files can be read and written */
246 private void checkFileExistence(){
247
248 //Ensure there is an input file
249 if(in==null){throw new RuntimeException("Error - an input file is required.");}
250
251 //Ensure there is an input file
252 if(ref==null){throw new RuntimeException("Error - a reference file is required.");}
253
254 //Ensure output files can be written
255 if(!Tools.testOutputFiles(overwrite, append, false, out, outModel, outHistFile)){
256 outstream.println((out==null)+", "+out);
257 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+out+" or "+outModel+"\n");
258 }
259
260 //Ensure input files can be read
261 if(!Tools.testInputFiles(true, true, in, inModelFile, (specialRef ? null : ref))){
262 throw new RuntimeException("\nCan't read some input files.\n");
263 }
264
265 //Ensure that no file was specified multiple times
266 if(!Tools.testForDuplicateFiles(true, in, ref, out, outModel, outHistFile, inModelFile)){
267 throw new RuntimeException("\nSome file names were specified multiple times.\n");
268 }
269 }
270
271 /** Adjust file-related static fields as needed for this program */
272 private static void checkStatics(){
273 //Adjust the number of threads for input file reading
274 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
275 ByteFile.FORCE_MODE_BF2=true;
276 }
277
278 assert(FastaReadInputStream.settingsOK());
279 }
280
281 /** Ensure parameter ranges are within bounds and required parameters are set */
282 private boolean validateParams(){
283 // assert(minfoo>0 && minfoo<=maxfoo) : minfoo+", "+maxfoo;
284 return true;
285 }
286
287 private void writeHist(String fname){
288 ByteStreamWriter bsw=new ByteStreamWriter(fname, overwrite, append, false);
289 bsw.start();
290 bsw.print("#Value\tIdentity");
291 if(inModel!=null){
292 bsw.print("\tScore");
293 }
294 bsw.nl();
295 for(int i=0; i<idHist.length; i++){
296 bsw.print(0.01f*i, 2).tab().print(idHist[i]);
297 if(inModel!=null){
298 bsw.tab().print(scoreHist[i]);
299 }
300 bsw.nl();
301 }
302 errorState=bsw.poisonAndWait()|errorState;
303 }
304
305 /*--------------------------------------------------------------*/
306 /*---------------- Outer Methods ----------------*/
307 /*--------------------------------------------------------------*/
308
309 /** Create read streams and process all data */
310 void process(Timer t){
311
312 //Turn off read validation in the input threads to increase speed
313 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
314 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
315
316 //Load reference;
317 refMap=loadReferenceCustom();
318 makeRefMap2();
319
320 //Reset counters
321 readsProcessed=readsOut=0;
322 basesProcessed=basesOut=0;
323 alignedReads=0;
324
325 if(ffin.samOrBam()){
326 //Create a read input stream
327 final SamStreamer ss=makeStreamer(ffin);
328 //Process the reads in separate threads
329 spawnThreads(ss);
330 }else{
331 Shared.capBufferLen(40);
332 //Create a read input stream
333 final ConcurrentReadInputStream cris=makeCris(ffin);
334 //Process the reads in separate threads
335 spawnThreads(cris);
336 }
337
338 //Optionally create a read output stream
339 final ConcurrentReadOutputStream ros=makeCros();
340
341 outputConsensus(ros);
342
343 if(outHistFile!=null){
344 writeHist(outHistFile);
345 }
346
347 if(verbose){outstream.println("Finished; closing streams.");}
348
349 //Write anything that was accumulated by ReadStats
350 errorState|=ReadStats.writeAll();
351 //Close the read streams
352 errorState|=ReadWrite.closeStream(ros);
353
354 //Reset read validation
355 Read.VALIDATE_IN_CONSTRUCTOR=vic;
356
357 //Report timing and results
358 t.stop();
359 if(!silent){
360 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
361 outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, readsOut, basesOut, 8, false));
362 outstream.println();
363 }
364 outstream.println(Tools.number("Ref Count:", refCount, 8));
365 outstream.println(Tools.number("Sub Count:", subCount, 8));
366 outstream.println(Tools.number("Del Count:", delCount, 8));
367 outstream.println(Tools.number("Ins Count:", insCount, 8));
368 outstream.println(Tools.number("Avg Identity:", 100*identitySum/alignedReads, 3, 8));
369 if(scoreSum>0){
370 outstream.println(Tools.number("Avg Score:", 100*scoreSum/alignedReads, 3, 8));
371 }
372
373 //Throw an exception of there was an error in a thread
374 if(errorState){
375 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
376 }
377 }
378
379 private synchronized LinkedHashMap<String, BaseGraph> loadReferenceCustom(){
380 assert(!loadedRef);
381 if(specialRef){return loadReferenceSpecial();}
382 ConcurrentReadInputStream cris=makeRefCris();
383 LinkedHashMap<String, BaseGraph> map=new LinkedHashMap<String, BaseGraph>();
384 ListNum<Read> ln=cris.nextList();
385 for(; ln!=null && !ln.isEmpty(); ln=cris.nextList()){
386 if(verbose){outstream.println("Fetched "+ln.size()+" reference sequences.");}
387 for(Read r : ln){
388 if(r.bases!=null && r.bases.length>0){
389 BaseGraph bg=new BaseGraph(r.id, r.bases, r.quality, r.numericID, 0);
390 map.put(r.name(), bg);
391 // if(inModel!=null && inModel.name.equals(bg.name)){
392 //// assert(false) : Arrays.toString(bg.refWeights)+"\n"+Arrays.toString(inModel.refWeights);
393 // bg.refWeights=inModel.refWeights;
394 // bg.insWeights=inModel.insWeights;
395 // bg.delWeights=inModel.delWeights;
396 // }else{
397 // bg.insWeights=new float[bg.ref.length];
398 // bg.delWeights=new float[bg.ref.length];
399 // Arrays.fill(bg.insWeights, 1);
400 // Arrays.fill(bg.delWeights, 1);
401 //// assert(false) : Arrays.toString(bg.delWeights);
402 // }
403 }
404 }
405 if(ln!=null){
406 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
407 }
408 }
409 if(verbose){outstream.println("Loaded "+map.size()+" reference sequences.");}
410 loadedRef=true;
411 return map;
412 }
413
414 //For ribo subunits in resources directory
415 private synchronized LinkedHashMap<String, BaseGraph> loadReferenceSpecial(){
416 assert(!loadedRef);
417 Read[] array=ProkObject.loadConsensusSequenceType(ref, false, false);
418 Read r=array[0];
419 BaseGraph bg=new BaseGraph(r.id, r.bases, r.quality, r.numericID, 0);
420 LinkedHashMap<String, BaseGraph> map=new LinkedHashMap<String, BaseGraph>();
421 map.put(r.name(), bg);
422 return map;
423 }
424
425 private synchronized void makeRefMap2(){
426 assert(refMap!=null && refMap2==null);
427 if(verbose){outstream.println("Making refMap2.");}
428 refMap2=new LinkedHashMap<String, BaseGraph>((refMap.size()*3)/2);
429 for(Entry<String, BaseGraph> e : refMap.entrySet()){
430 String key=e.getKey();
431 if(verbose){outstream.println("Considering "+key);}
432 BaseGraph value=e.getValue();
433 String key2=Tools.trimToWhitespace(key);
434 if(verbose){outstream.println("key2="+key2);}
435 // if(verbose){outstream.println("put "+key2+", "+value);}
436 refMap2.put(key2, value);
437 // if(verbose){outstream.println("putted "+key2+", "+value);}
438
439 if(defaultRname==null){defaultRname=key;}
440 }
441 // assert(false) : refMap+"\n"+refMap2;
442 if(verbose){outstream.println("Made refMap2.");}
443 }
444
445 private ConcurrentReadInputStream makeRefCris(){
446 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffref, null);
447 cris.start(); //Start the stream
448 if(verbose){outstream.println("Started cris");}
449 boolean paired=cris.paired();
450 assert(!paired) : "References should not be paired.";
451 return cris;
452 }
453
454 private SamStreamer makeStreamer(FileFormat ff){
455 if(ff==null){return null;}
456 SamStreamer ss=new SamReadStreamer(ff, streamerThreads, true, maxReads);
457 ss.start(); //Start the stream
458 if(verbose){outstream.println("Started Streamer");}
459 return ss;
460 }
461
462 private ConcurrentReadInputStream makeCris(FileFormat ff){
463 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ff, null);
464 cris.start(); //Start the stream
465 if(verbose){outstream.println("Started cris");}
466 boolean paired=cris.paired();
467 assert(!paired);
468 return cris;
469 }
470
471 private ConcurrentReadOutputStream makeCros(){
472 if(ffout==null){return null;}
473
474 //Select output buffer size based on whether it needs to be ordered
475 final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
476
477 final ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(ffout, null, buff, null, false);
478 ros.start(); //Start the stream
479 return ros;
480 }
481
482 /*--------------------------------------------------------------*/
483 /*---------------- Thread Management ----------------*/
484 /*--------------------------------------------------------------*/
485
486 /** Spawn process threads */
487 private void spawnThreads(final SamStreamer ss){
488
489 //Do anything necessary prior to processing
490
491 //Determine how many threads may be used
492 final int threads=Shared.threads();
493
494 //Fill a list with ProcessThreads
495 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
496 for(int i=0; i<threads; i++){
497 alpt.add(new ProcessThread(ss, i));
498 }
499
500 //Start the threads
501 for(ProcessThread pt : alpt){
502 pt.start();
503 }
504 if(verbose){outstream.println("Started worker threads.");}
505
506 //Wait for threads to finish
507 boolean success=ThreadWaiter.waitForThreadsToFinish(alpt, this);
508 errorState&=!success;
509
510 //Do anything necessary after processing
511
512 }
513
514 /** Spawn process threads */
515 private void spawnThreads(final ConcurrentReadInputStream cris){
516
517 //Do anything necessary prior to processing
518
519 //Determine how many threads may be used
520 final int threads=Shared.threads();
521
522 //Fill a list with ProcessThreads
523 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
524 for(int i=0; i<threads; i++){
525 alpt.add(new ProcessThread(cris, i));
526 }
527
528 //Start the threads
529 for(ProcessThread pt : alpt){
530 pt.start();
531 }
532 if(verbose){outstream.println("Started worker threads.");}
533
534 //Wait for threads to finish
535 boolean success=ThreadWaiter.waitForThreadsToFinish(alpt, this);
536 errorState&=!success;
537
538 //Do anything necessary after processing
539 ReadWrite.closeStreams(cris);
540 }
541
542 private void outputConsensus(ConcurrentReadOutputStream ros){
543 if(verbose){outstream.println("Making consensus.");}
544 ArrayList<Read> consensusList=new ArrayList<Read>(200);
545 ArrayList<BaseGraph> graphList=new ArrayList<BaseGraph>(200);
546 long num=0;
547 for(Entry<String, BaseGraph> e : refMap.entrySet()){
548 BaseGraph bg=e.getValue();
549 graphList.add(bg);
550
551 Read r=bg.traverse();
552 if(name!=null){r.id=name;}
553 consensusList.add(r);
554
555 refCount+=bg.refCount;
556 subCount+=bg.subCount;
557 delCount+=bg.delCount;
558 insCount+=bg.insCount;
559
560 readsOut++;
561 basesOut+=r.length();
562
563 if(consensusList.size()>=200){
564 if(ros!=null){ros.add(consensusList, num);}
565 consensusList=new ArrayList<Read>(200);
566 num++;
567 }
568 }
569 if(consensusList.size()>0){
570 if(ros!=null){ros.add(consensusList, num);}
571 consensusList=new ArrayList<Read>(200);
572 num++;
573 }
574 if(graphList.size()>0 && ffmodel!=null){
575 // ReadWrite.writeObjectInThread(graphList, ffmodel.name(), true);
576 ReadWrite.writeAsync(graphList, ffmodel.name(), true);
577 }
578 }
579
580 @Override
581 public final void accumulate(ProcessThread pt){
582 readsProcessed+=pt.readsProcessedT;
583 basesProcessed+=pt.basesProcessedT;
584 alignedReads+=pt.alignedReadsT;
585 identitySum+=pt.identitySumT;
586 scoreSum+=pt.scoreSumT;
587 for(int i=0; i<idHist.length; i++){
588 idHist[i]+=pt.idHistT[i];
589 scoreHist[i]+=pt.scoreHistT[i];
590 }
591 errorState|=(!pt.success);
592 }
593
594 @Override
595 public final boolean success(){return !errorState;}
596
597 /*--------------------------------------------------------------*/
598 /*---------------- Inner Methods ----------------*/
599 /*--------------------------------------------------------------*/
600
601 @Override
602 public ByteBuilder toText() {
603 // TODO Auto-generated method stub
604 return null;
605 }
606
607 /*--------------------------------------------------------------*/
608 /*---------------- Inner Classes ----------------*/
609 /*--------------------------------------------------------------*/
610
611 /** This class is static to prevent accidental writing to shared variables.
612 * It is safe to remove the static modifier. */
613 class ProcessThread extends Thread {
614
615 //Constructor
616 ProcessThread(final SamStreamer ss_, final int tid_){
617 ss=ss_;
618 cris=null;
619 tid=tid_;
620 realigner=(realign ? new Realigner() : null);
621 }
622
623 //Constructor
624 ProcessThread(final ConcurrentReadInputStream cris_, final int tid_){
625 ss=null;
626 cris=cris_;
627 tid=tid_;
628 realigner=null;//(realign ? new Realigner() : null);
629 }
630
631 //Called by start()
632 @Override
633 public void run(){
634 //Do anything necessary prior to processing
635
636 //Process the reads
637 processInner();
638
639 //Do anything necessary after processing
640
641 //Indicate successful exit status
642 success=true;
643 }
644
645 /** Iterate through the reads */
646 void processInner(){
647
648
649 //Grab and process all lists
650
651 if(ss!=null){
652 for(ListNum<Read> ln=ss.nextReads(); ln!=null; ln=ss.nextReads()){
653 processList(ln);
654 }
655 }else{
656 for(ListNum<Read> ln=cris.nextList(); ln!=null && ln.size()>0; ln=cris.nextList()){
657 processList(ln);
658 cris.returnList(ln);
659 }
660 }
661
662 }
663
664 void processList(ListNum<Read> ln){
665
666 //Loop through each read in the list
667 for(Read r : ln){
668
669 //Validate reads in worker threads
670 if(!r.validated()){r.validate(true);}
671
672 //Track the initial length for statistics
673 final int initialLength=r.length();
674
675 //Increment counters
676 readsProcessedT++;
677 basesProcessedT+=initialLength;
678
679 {
680 //Reads are processed in this block.
681 processRead(r);
682 }
683 }
684 }
685
686 /**
687 * Process a read or a read pair.
688 * @param r Read 1
689 * @param r2 Read 2 (may be null)
690 * @return True if the reads should be kept, false if they should be discarded.
691 */
692 void processRead(final Read r){
693 if(r.bases==null || r.length()<=1){return;}
694
695 final SamLine sl=r.samline;
696 if(sl!=null && !sl.mapped()){return;}
697 final String rname=(sl==null ? defaultRname : sl.rnameS());
698 BaseGraph bg=refMap.get(rname);
699 if(bg==null){bg=refMap2.get(Tools.trimToWhitespace(rname));}
700 assert(bg!=null) : "Can't find graph for "+rname;
701 float identity;
702 float score=0;//unused
703
704 // assert(false) : r;
705 if(sl==null){
706 // identity=SketchObject.alignAndMakeMatch(r, bg.original);
707 // assert(false) : bg.refWeights[0];
708 // identity=SketchObject.alignAndMakeMatch(r, bg.original, bg.refWeights, bg.insWeights, bg.delWeights);
709 identity=SketchObject.alignAndMakeMatch(r, bg.original, bg.refWeights);
710 if(identity<=0){return;}
711 assert(r.match!=null) : identity+", "+r;
712 }else{
713 assert(sl!=null && sl.mapped() && sl.seq!=null) : sl;
714 assert(r.match!=null);
715 if(samFilter!=null && !samFilter.passesFilter(sl)){return;}
716 identity=sl.calcIdentity();
717 }
718 assert(r.match!=null && identity>0) : identity+", "+r;
719
720 if(inModel!=null){
721
722 if(verbose){System.err.println(r.start+"\t"+r.stop+"\t"+new String(r.match));}
723 score=inModel.score(r, false, true);
724 if(printScores){
725 // System.err.println(identity+"\t"+score+"\t"+inModel.score(r, false, true));
726 System.err.println(String.format("%.5f\t%.5f", identity, score));
727 }
728 // assert(false);
729 // if(score<0){
730 // verbose=true;
731 // inModel.score(r, false, false);
732 // }
733 // assert(!verbose);
734 }
735
736 alignedReadsT++;
737 identitySumT+=identity;
738 scoreSumT+=score;
739 idHistT[Tools.mid(0, Math.round(100*identity), 100)]++;
740 scoreHistT[Tools.mid(0, Math.round(100*score), 100)]++;
741
742
743
744 // assert(sl.calcIdentity()<=0.78) : sl.calcIdentity()+", "+samFilter.maxId;
745 // assert(false) : sl.cigar+", "+sl.calcIdentity();
746
747 // System.err.println(rname);
748
749 if(realigner!=null) {
750 assert(false);
751 realigner.realign(r, sl, bg.original, true);
752 }
753
754 bg.add(r);
755 }
756
757 long[] idHistT=new long[101];
758 long[] scoreHistT=new long[101];
759
760 /** Number of reads processed by this thread */
761 protected long readsProcessedT=0;
762 /** Number of bases processed by this thread */
763 protected long basesProcessedT=0;
764
765 protected long alignedReadsT=0;
766
767 double identitySumT=0;
768 double scoreSumT=0;
769
770 /** True only if this thread has completed successfully */
771 boolean success=false;
772
773 /** Shared input stream */
774 private final SamStreamer ss;
775 /** Alternate input stream */
776 private final ConcurrentReadInputStream cris;
777 /** Thread ID */
778 final int tid;
779 /** For realigning reads */
780 final Realigner realigner;
781 }
782
783 /*--------------------------------------------------------------*/
784 /*---------------- Fields ----------------*/
785 /*--------------------------------------------------------------*/
786
787 /** Read input file path */
788 private String in=null;
789 /** Reference input file path */
790 private String ref=null;
791
792 private String inModelFile;
793 private BaseGraph inModel;
794 private String outHistFile;
795
796 /** Consensus output file path */
797 private String out=null;
798 /** Model output file path */
799 private String outModel=null;
800
801 /** Override input file extension */
802 private String extin=null;
803 /** Override output file extension */
804 private String extout=null;
805
806 /*--------------------------------------------------------------*/
807
808 /** Number of reads processed */
809 protected long readsProcessed=0;
810 /** Number of bases processed */
811 protected long basesProcessed=0;
812
813 protected long alignedReads=0;
814
815 protected double identitySum=0;
816 protected double scoreSum=0;
817
818 /** Number of reads retained */
819 protected long readsOut=0;
820 /** Number of bases retained */
821 protected long basesOut=0;
822
823 /** Quit after processing this many input reads; -1 means no limit */
824 private long maxReads=-1;
825
826 public long subCount=0;
827 public long refCount=0;
828 public long delCount=0;
829 public long insCount=0;
830
831 long[] idHist=new long[101];
832 long[] scoreHist=new long[101];
833 boolean printScores=false;
834
835 /*--------------------------------------------------------------*/
836
837 /** Threads dedicated to reading the sam file */
838 private int streamerThreads=SamStreamer.DEFAULT_THREADS;
839
840 private String name=null;
841
842 private boolean loadedRef=false;
843 private boolean specialRef=false;
844
845 private boolean realign=false;
846
847 private int ploidy=1;
848
849 private final boolean silent;
850
851 public final SamFilter samFilter=new SamFilter();
852 /** Uses full ref names */
853 public LinkedHashMap<String, BaseGraph> refMap;
854 /** Uses truncated ref names */
855 public LinkedHashMap<String, BaseGraph> refMap2;
856
857 private String defaultRname=null;
858
859 /*--------------------------------------------------------------*/
860 /*---------------- Final Fields ----------------*/
861 /*--------------------------------------------------------------*/
862
863 /** Read input file */
864 private final FileFormat ffin;
865 /** Reference input file */
866 private final FileFormat ffref;
867
868 /** Consensus output file */
869 private final FileFormat ffout;
870 /** Model output file */
871 private final FileFormat ffmodel;
872
873 @Override
874 public final ReadWriteLock rwlock() {return rwlock;}
875 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
876
877 /*--------------------------------------------------------------*/
878 /*---------------- Common Fields ----------------*/
879 /*--------------------------------------------------------------*/
880
881 /** Print status messages to this output stream */
882 private PrintStream outstream=System.err;
883 /** True if an error was encountered */
884 public boolean errorState=false;
885 /** Overwrite existing output files */
886 private boolean overwrite=true;
887 /** Append to existing output files */
888 private boolean append=false;
889 /** Reads ARE output in input order, even though this is false */
890 private final boolean ordered=false;
891
892 }