Debian Codegraph @

current/jgi/CheckStrand2.java

raw symbols SCIP
1 package jgi;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.Arrays;
7 import java.util.HashMap;
8 import java.util.concurrent.ConcurrentHashMap;
9 import java.util.concurrent.locks.ReadWriteLock;
10 import java.util.concurrent.locks.ReentrantReadWriteLock;
11
12 import dna.AminoAcid;
13 import dna.Data;
14 import fileIO.ByteFile;
15 import fileIO.ByteStreamWriter;
16 import fileIO.FileFormat;
17 import fileIO.ReadWrite;
18 import gff.GffLine;
19 import prok.CallGenes;
20 import prok.GeneCaller;
21 import prok.GeneModel;
22 import prok.GeneModelParser;
23 import prok.Orf;
24 import prok.ProkObject;
25 import shared.Parse;
26 import shared.Parser;
27 import shared.PreParser;
28 import shared.Shared;
29 import shared.Timer;
30 import shared.Tools;
31 import sketch.Sketch;
32 import sketch.SketchHeap;
33 import sketch.SketchMakerMini;
34 import sketch.SketchObject;
35 import sketch.SketchTool;
36 import stream.ConcurrentReadInputStream;
37 import stream.ConcurrentReadOutputStream;
38 import stream.FASTQ;
39 import stream.FastaReadInputStream;
40 import stream.Read;
41 import stream.ReadInputStream;
42 import stream.SamLine;
43 import structures.ListNum;
44 import structures.LongPair;
45 import structures.Range;
46 import template.Accumulator;
47 import template.ThreadWaiter;
48 import tracker.ReadStats;
49
50 /**
51 * Checks the strandedness of RNA-seq reads.
52 *
53 * @author Brian Bushnell
54 * @date August 7, 2023
55 *
56 */
57 public class CheckStrand2 implements Accumulator<CheckStrand2.ProcessThread> {
58
59 /*--------------------------------------------------------------*/
60 /*---------------- Initialization ----------------*/
61 /*--------------------------------------------------------------*/
62
63 /**
64 * Code entrance from the command line.
65 * @param args Command line arguments
66 */
67 public static void main(String[] args){
68 //Start a timer immediately upon code entrance.
69 Timer t=new Timer();
70
71 //Create an instance of this class
72 CheckStrand2 x=new CheckStrand2(args);
73
74 //Run the object
75 x.process(t);
76
77 //Close the print stream if it was redirected
78 Shared.closeStream(x.outstream);
79 }
80
81 /**
82 * Constructor.
83 * @param args Command line arguments
84 */
85 public CheckStrand2(String[] args){
86
87 {//Preparse block for help, config files, and outstream
88 PreParser pp=new PreParser(args, getClass(), false);
89 args=pp.args;
90 outstream=pp.outstream;
91 }
92
93 //Set shared static variables prior to parsing
94 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
95 ReadWrite.setZipThreads(Shared.threads());
96
97 {//Parse the arguments
98 final Parser parser=parse(args);
99 Parser.processQuality();
100
101 maxReads=parser.maxReads;
102 overwrite=ReadStats.overwrite=parser.overwrite;
103 append=ReadStats.append=parser.append;
104 setInterleaved=parser.setInterleaved;
105
106 in1=parser.in1;
107 in2=parser.in2;
108 qfin1=parser.qfin1;
109 qfin2=parser.qfin2;
110 extin=parser.extin;
111
112 out1=parser.out1;
113 extout=parser.extout;
114 }
115
116 validateParams();
117 doPoundReplacement(); //Replace # with 1 and 2
118 adjustInterleaving(); //Make sure interleaving agrees with number of input and output files
119 fixExtensions(); //Add or remove .gz or .bz2 as needed
120 checkFileExistence(); //Ensure files can be read and written
121 checkStatics(); //Adjust file-related static fields as needed for this program
122
123 //Create output FileFormat objects
124 ffout1=FileFormat.testOutput(out1, FileFormat.TXT, extout, true, overwrite, append, false);
125
126 //Create input FileFormat objects
127 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
128 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
129
130 //Allows unchanged sam output for sam input.
131 SamLine.SET_FROM_OK=true;
132
133 //If there is a gff file that will not be used, nullify it.
134 if(gff!=null) {
135 if(transcriptome) {
136 System.err.println("Ignoring gff file due to transcriptome mode.");
137 gff=null;
138 }else if(!ffin1.samOrBam() && fna==null) {
139 System.err.println("Ignoring gff file due to using unaligned reads with no reference.");
140 gff=null;
141 }
142 }
143
144 //Decide whether gene-calling is needed, and pick a gene model.
145 if((fna!=null && (gff==null || passes>1) && !transcriptome && !rnaContigs) || scoreReadGenes) {
146 if(pgmFile==null){pgmFile=Data.findPath("?model.pgm");}
147 final GeneModel pgm0=GeneModelParser.loadModel(pgmFile);
148 if(passes<2 || fna==null || transcriptome) {pgm=pgm0;}
149 else {
150 Timer t=new Timer();
151 System.err.print("Refining gene model: ");
152 pgm=CallGenes.makeMultipassModel(pgm0, genomeSequence(), gff, passes);
153 if(streamGenome) {genomeSequenceCache=null;}//To save memory
154 t.stopAndPrint();
155 }
156 gCaller=CallGenes.makeGeneCaller(pgm);
157 }else {
158 pgm=null;
159 gCaller=null;
160 }
161 }
162
163 /*--------------------------------------------------------------*/
164 /*---------------- Initialization Helpers ----------------*/
165 /*--------------------------------------------------------------*/
166
167 /** Parse arguments from the command line */
168 private Parser parse(String[] args){
169
170 //Create a parser object
171 Parser parser=new Parser();
172
173 //Set any necessary Parser defaults here
174 //parser.foo=bar;
175 parser.out1=out1;
176
177 //Parse each argument
178 for(int i=0; i<args.length; i++){
179 String arg=args[i];
180
181 //Break arguments into their constituent parts, in the form of "a=b"
182 String[] split=arg.split("=");
183 String a=split[0].toLowerCase();
184 String b=split.length>1 ? split[1] : null;
185 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
186
187 if(a.equals("verbose")){
188 verbose=Parse.parseBoolean(b);
189 }else if(a.equals("parse_flag_goes_here")){
190 long fake_variable=Parse.parseKMG(b);
191 //Set a variable here
192 }else if(a.equals("size") || a.equals("len") || a.equals("length") ||
193 a.equals("sketchsize") || a.equals("sketchlen")){
194 sketchSize=Parse.parseIntKMG(b);
195 }else if(a.equals("samplerate")){
196 samplerate=Float.parseFloat(b);
197 }else if(a.equals("sampleseed") || a.equals("seed")){
198 sampleseed=Long.parseLong(b);
199 }else if(a.equals("ref") || a.equals("fna")){
200 fna=b;
201 }else if(a.equals("gff")){
202 gff=b;
203 }else if(a.equals("merge")){
204 mergePairs=Parse.parseBoolean(b);
205 }else if(a.equals("bin") || a.equals("binlen")){
206 binlen=Parse.parseIntKMG(b);
207 }else if(a.equals("scoregenes") || a.equals("scorereads") || a.equals("callgenes")
208 || a.equals("callreads") || a.equals("kfa")){
209 scoreReadGenes=Parse.parseBoolean(b);
210 }else if(a.equals("pgm") || a.equals("model")){
211 pgmFile=b;
212 }else if(a.equals("streamgenome")){
213 streamGenome=Parse.parseBoolean(b);
214 }else if(a.equals("stopanalysis") || a.equals("orf")){
215 doStopAnalysis=Parse.parseBoolean(b);
216 }else if(a.equalsIgnoreCase("polya")){
217 testPolyA=Parse.parseBoolean(b);
218 }else if(a.equalsIgnoreCase("transcriptome")){
219 transcriptome=Parse.parseBoolean(b);
220 }else if(a.equalsIgnoreCase("rnacontigs")){
221 rnaContigs=Parse.parseBoolean(b);
222 }else if(a.equalsIgnoreCase("normalize")){
223 normalize=Parse.parseBoolean(b);
224 }else if(a.equalsIgnoreCase("minreads")){
225 minReads=Integer.parseInt(b);
226 }else if(a.equalsIgnoreCase("genome")){
227 transcriptome=!Parse.parseBoolean(b);
228 }else if(a.equalsIgnoreCase("outp") || a.equalsIgnoreCase("outplus")){
229 outPlus=b;
230 }else if(a.equalsIgnoreCase("outm") || a.equalsIgnoreCase("outminus")){
231 outMinus=b;
232 }else if(a.equalsIgnoreCase("firstorf")){
233 useFirstORF=Parse.parseBoolean(b);
234 }else if(a.equalsIgnoreCase("minpolya") || a.equalsIgnoreCase("polyalen")
235 || a.equalsIgnoreCase("polyalength")){
236 minPolyA=Integer.parseInt(b);
237 }else if(a.equalsIgnoreCase("passes")){
238 passes=Integer.parseInt(b);
239 }else if(a.equalsIgnoreCase("2pass") || a.equalsIgnoreCase("twopass")){
240 if(Parse.parseBoolean(b)) {passes=2;}
241 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
242 //do nothing
243 }else{
244 boolean parsed=false;
245 if(b==null && arg.indexOf('=')<0) {
246 File f=new File(arg);
247 String ext=ReadWrite.rawExtension(a);
248 if(f.isFile() && f.canRead()) {
249 if(parser.in1==null && (FileFormat.isSamOrBamExt(ext) || FileFormat.isFastqExt(ext))) {
250 outstream.println("Set input to "+f.getName());
251 parser.in1=arg;
252 parsed=true;
253 }else if(gff==null && FileFormat.isGffExt(ext)) {
254 outstream.println("Set gff to "+f.getName());
255 gff=arg;
256 parsed=true;
257 }else if(fna==null && FileFormat.isFastaExt(ext)) {
258 outstream.println("Set ref to "+f.getName());
259 fna=arg;
260 parsed=true;
261 }
262 }
263 }
264 if(!parsed) {
265 outstream.println("Unknown parameter "+args[i]);
266 assert(false) : "Unknown parameter "+args[i];
267 }
268 }
269 }
270
271 return parser;
272 }
273
274 /** Replace # with 1 and 2 in headers */
275 private void doPoundReplacement(){
276 //Do input file # replacement
277 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
278 in2=in1.replace("#", "2");
279 in1=in1.replace("#", "1");
280 }
281
282 //Ensure there is an input file
283 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
284 }
285
286 /** Add or remove .gz or .bz2 as needed */
287 private void fixExtensions(){
288 in1=Tools.fixExtension(in1);
289 in2=Tools.fixExtension(in2);
290 qfin1=Tools.fixExtension(qfin1);
291 qfin2=Tools.fixExtension(qfin2);
292 }
293
294 /** Ensure files can be read and written */
295 private void checkFileExistence(){
296 //Ensure output files can be written
297 if(!Tools.testOutputFiles(overwrite, append, false, out1, outPlus, outMinus)){
298 outstream.println((out1==null)+", "+(outPlus==null)+", "+(outMinus==null)+
299 ", "+out1+", "+outPlus+", "+outMinus);
300 throw new RuntimeException("\n\noverwrite="+overwrite+"; "
301 + "Can't write to output files "+out1+", "+outPlus+", "+outMinus+"\n");
302 }
303
304 //Ensure input files can be read
305 if(!Tools.testInputFiles(false, true, in1, in2)){
306 throw new RuntimeException("\nCan't read some input files.\n");
307 }
308
309 //Ensure that no file was specified multiple times
310 if(!Tools.testForDuplicateFiles(true, in1, in2, out1, outPlus, outMinus)){
311 throw new RuntimeException("\nSome file names were specified multiple times.\n");
312 }
313 }
314
315 /** Make sure interleaving agrees with number of input and output files */
316 private void adjustInterleaving(){
317 //Adjust interleaved detection based on the number of input files
318 if(in2!=null){
319 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
320 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
321 }
322
323 //Adjust interleaved settings based on number of output files
324 if(!setInterleaved){
325 if(in2!=null){ //If there are 2 input streams.
326 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
327 // outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
328 }
329 }
330 }
331
332 /** Adjust file-related static fields as needed for this program */
333 private static void checkStatics(){
334 //Adjust the number of threads for input file reading
335 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
336 ByteFile.FORCE_MODE_BF2=true;
337 }
338
339 assert(FastaReadInputStream.settingsOK());
340 }
341
342 /** Ensure parameter ranges are within bounds and required parameters are set */
343 private boolean validateParams(){
344 // assert(minfoo>0 && minfoo<=maxfoo) : minfoo+", "+maxfoo;
345 return true;
346 }
347
348 /*--------------------------------------------------------------*/
349 /*---------------- Outer Methods ----------------*/
350 /*--------------------------------------------------------------*/
351
352 /** Create read streams and process all data */
353 void process(Timer t){
354
355 //Turn off read validation in the input threads to increase speed
356 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
357 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
358
359 makeTools();
360 makeGeneSketches();
361
362 if(ffin1.samOrBam()) {//Aligned reads
363 if(gffLines==null) {//Features not yet loaded
364 if(gff!=null) {
365 gffLines=CheckStrand.getGffLines(gff, types);
366 }else if(fna!=null && !transcriptome && !rnaContigs) {
367 ArrayList<Read> reads=genomeSequence();
368 System.err.print("Calling genes from genome: ");
369 ArrayList<Orf> orfs=gCaller.callGenes(reads);
370 gffLines=Orf.toGffLines(orfs);
371 }
372 }
373 if(gffLines!=null) {
374 SamLine.RNAME_AS_BYTES=false;//Must come before cris starts
375 rangeMap=GffLine.makeRangeMap(gffLines);
376 }
377 if(binlen>0) {
378 binMap=new ConcurrentHashMap<String, ArrayList<LongPair>>();
379 }
380 }
381
382 //Create a read input stream
383 final ConcurrentReadInputStream cris=makeCris();
384 final ConcurrentReadOutputStream crosP=makeCros(outPlus);
385 final ConcurrentReadOutputStream crosM=makeCros(outMinus);
386
387 //Reset counters
388 readsIn=readsProcessed=0;
389 basesIn=basesProcessed=0;
390 readsMerged=0;
391
392 //Process the reads in separate threads
393 spawnThreads(cris, crosP, crosM);
394
395 if(verbose){outstream.println("Finished; closing streams.");}
396
397 //Write anything that was accumulated by ReadStats
398 errorState|=ReadStats.writeAll();
399 //Close the read streams
400 errorState|=ReadWrite.closeStreams(cris, crosP, crosM);
401
402 //Reset read validation
403 Read.VALIDATE_IN_CONSTRUCTOR=vic;
404
405 outstream.println();
406 analyze();
407
408 //Report timing and results
409 t.stop();
410
411 outstream.println();
412 outstream.println(Tools.timeReadsBasesProcessed(t, readsIn, basesIn, 8));
413 // outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, readsOut, basesOut, 8, false));
414
415 //Throw an exception of there was an error in a thread
416 if(errorState){
417 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
418 }
419 }
420
421 /** Do math on the raw results to determine strandedness and major strand */
422 void analyze() {
423 double[] results=CheckStrand.calcStrandedness(canonSketch, fwdSketch);
424 double[] resultsN=CheckStrand.calcStrandednessNormalized(canonSketch, fwdSketch);
425
426 double[] refResults=(canonGeneSketch==null ? null : CheckStrand.calcPMRatioWithGeneSketches(
427 canonSketch, fwdSketch, canonGeneSketch, plusSketch, minusSketch));
428 outputResults(results, resultsN, refResults);
429 }
430
431 /**
432 * Start a read input stream from the read files
433 * @return The stream.
434 */
435 private ConcurrentReadInputStream makeCris(){
436 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(
437 maxReads, true, ffin1, ffin2, qfin1, qfin2);
438 cris.setSampleRate(samplerate, sampleseed);
439 cris.start(); //Start the stream
440 if(verbose){outstream.println("Started cris");}
441 boolean paired=cris.paired();
442 if(!ffin1.samOrBam()){//Announce whether the data is being procesed as paired
443 outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));
444 }
445 return cris;
446 }
447
448 /**
449 * Start a read output stream for some destination
450 * @param fname Destination file for stream
451 * @return The stream.
452 */
453 private ConcurrentReadOutputStream makeCros(String fname){
454 if(fname==null) {return null;}
455
456 //Select output buffer size based on whether it needs to be ordered
457 final boolean ordered=true;
458 final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
459
460 final FileFormat ffout=FileFormat.testOutput(
461 fname, ffin1.format(), null, true, overwrite, false, ordered);
462 final ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(
463 ffout, null, buff, null, true);
464 ros.start(); //Start the stream
465 return ros;
466 }
467
468 /**
469 * Set Sketch static parameters and generate SketchTools
470 * for forward and canonical kmers.
471 */
472 private void makeTools() {
473
474 if(verbose){System.err.println("Setting sketch params.");}
475 SketchObject.AUTOSIZE=false;
476 SketchObject.k=32;
477 SketchObject.k2=-1;//Otherwise the estimates are too high
478 SketchObject.setK=true;
479 SketchObject.sampleseed=sampleseed;
480 // SketchObject.defaultParams.minKeyOccuranceCount=2;
481
482 SketchObject.AUTOSIZE=false;
483 SketchObject.AUTOSIZE_LINEAR=false;
484 SketchObject.targetSketchSize=sketchSize;
485 SketchObject.SET_TARGET_SIZE=true;
486 SketchObject.processSSU=false;
487
488 SketchObject.defaultParams.parse("trackcounts", "trackcounts", null);
489 SketchObject.defaultParams.samplerate=samplerate;
490 SketchObject.postParse();
491
492 canonTool=new SketchTool(sketchSize, 0, true, true, true);
493 fwdTool=new SketchTool(sketchSize, 0, true, true, false);
494 }
495
496 /*--------------------------------------------------------------*/
497 /*---------------- Thread Management ----------------*/
498 /*--------------------------------------------------------------*/
499
500 /** Spawn process threads */
501 private void spawnThreads(final ConcurrentReadInputStream cris,
502 ConcurrentReadOutputStream crosP, ConcurrentReadOutputStream crosM){
503
504 //Do anything necessary prior to processing
505
506 //Determine how many threads may be used
507 final int maxThreads=mergePairs ? 64 : 16; //This is to limit memory use by sketches
508 final int threads=Tools.min(maxThreads, Shared.threads());
509
510 //Fill a list with ProcessThreads
511 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
512 for(int i=0; i<threads; i++){
513 alpt.add(new ProcessThread(cris, crosP, crosM, i));
514 }
515
516 //Start the threads and wait for them to finish
517 ThreadWaiter.startThreads(alpt);
518 //
519 // //While that's going, process the ref
520 // makeGeneSketches();
521
522 boolean success=ThreadWaiter.waitForThreadsToFinish(alpt, this);
523 outstream.println("Finished processing "+readsIn+" reads and "+basesIn+" bases.");
524 errorState&=!success;
525
526 //Do anything necessary after processing
527 //This transforms SketchHeaps (used for building Sketches) into finished Sketches.
528 canonSketch=new Sketch(canonHeap, false, true, null);
529 fwdSketch=new Sketch(fwdHeap, false, true, null);
530 }
531
532 @Override
533 public final void accumulate(ProcessThread pt){
534 synchronized(pt) {
535 readsIn+=pt.readsInT;
536 basesIn+=pt.basesInT;
537 readsProcessed+=pt.readsProcessedT;
538 basesProcessed+=pt.basesProcessedT;
539 readsMerged+=pt.readsMergedT;
540
541 fCountSum+=pt.fCountSumT;
542 rCountSum+=pt.rCountSumT;
543 fPosSum+=pt.fPosSumT;
544 rPosSum+=pt.rPosSumT;
545
546 Tools.add(fBestFrame, pt.fBestFrameT);
547 Tools.add(rBestFrame, pt.rBestFrameT);
548 Tools.add(ACGTCount, pt.ACGTCountT);
549
550 polyACount+=pt.polyACountT;
551 polyTCount+=pt.polyTCountT;
552
553 gCallerPlusCount+=pt.gCallerPlusCountT;
554 gCallerMinusCount+=pt.gCallerMinusCountT;
555 gCallerPlusCalled+=pt.gCallerPlusCalledT;
556 gCallerMinusCalled+=pt.gCallerMinusCalledT;
557 gCallerPlusScore+=pt.gCallerPlusScoreT;
558 gCallerMinusScore+=pt.gCallerMinusScoreT;
559
560 plusAlignedReads+=pt.plusAlignedReadsT;
561 minusAlignedReads+=pt.minusAlignedReadsT;
562 allAlignedReads+=pt.allAlignedReadsT;
563
564 samLinesProcessed+=pt.samLinesProcessedT;
565 samLinesAlignedToFeatures+=pt.samLinesAlignedToFeaturesT;
566
567 errorState|=(!pt.success);
568
569 if(!pt.canonSmm.isEmpty()) {
570 if(canonHeap==null){canonHeap=pt.canonSmm.heap();}
571 else{canonHeap.add(pt.canonSmm.heap());}
572 }
573 if(!pt.fwdSmm.isEmpty()) {
574 if(fwdHeap==null){fwdHeap=pt.fwdSmm.heap();}
575 else{fwdHeap.add(pt.fwdSmm.heap());}
576 }
577 }
578 }
579
580 @Override
581 public final boolean success(){return !errorState;}
582
583 /*--------------------------------------------------------------*/
584 /*---------------- Inner Methods ----------------*/
585 /*--------------------------------------------------------------*/
586
587 /**
588 * Generate sketches of the reference transcriptome.
589 * @return True if successful.
590 */
591 private boolean makeGeneSketches() {
592 genes=grabGenes();
593 if(genes==null) {return false;}
594 outstream.println("Processing "+genes.size()+" genes.");
595 Sketch[] geneSketches=CheckStrand.sketchGenes(genes, canonTool, fwdTool);
596 if(geneSketches==null) {return false;}
597 canonGeneSketch=geneSketches[0];
598 plusSketch=geneSketches[1];
599 minusSketch=geneSketches[2];
600 return true;
601 }
602
603 /**
604 * Load the reference transcriptome; requires a reference fasta file.
605 * In transcriptome mode, the fasta file is simply loaded and returned.
606 * In genome mode, uses a gff if provided, otherwise the genes are called
607 * using CallGenes. Then the genes are cut from the reference like CutGff.
608 * Does not currently fuse exons together, and is untested on Euk annotations,
609 * but they are expected to work fine (as long as a gff is provided).
610 * @return Gene sequences, sense strand as plus.
611 */
612 private ArrayList<Read> grabGenes(){
613 if(fna==null) {return null;}
614
615 final ArrayList<Read> genes;
616 Timer t=new Timer();
617
618 if(transcriptome || rnaContigs) {
619 System.err.print("Loading genes from transcriptome: ");
620 genes=genomeSequence(); //Skips loading if already cached
621 }else if(gff!=null) {
622 System.err.print("Loading genes from genome and gff: ");
623 HashMap<String, Read> map=(genomeSequenceCache==null ?
624 CheckStrand.getSequenceMap(fna) : CheckStrand.getSequenceMap(genomeSequence()));
625 genes=CheckStrand.grabGenes(gffLines, map);
626 }else{
627 ArrayList<Read> reads=genomeSequence();
628 if(gffLines==null) {
629 System.err.print("Calling genes from genome: ");
630 ArrayList<Orf> orfs=gCaller.callGenes(reads);
631 gffLines=Orf.toGffLines(orfs);
632 }
633 HashMap<String, Read> map=CheckStrand.getSequenceMap(reads);
634 genes=CheckStrand.grabGenes(gffLines, map);
635 }
636 t.stopAndPrint();
637
638 return (genes==null || genes.isEmpty()) ? null : genes;
639 }
640
641 /**
642 * Calls genes while streaming the fasta to save memory.
643 * Works fine but for some reason is extremely slow.
644 * @param fna Genome fasta.
645 * @return Gene sequences.
646 */
647 @Deprecated
648 private ArrayList<Read> callGenes(String fna){
649 final ConcurrentReadInputStream cris=makeFastaCris(fna);
650
651 ArrayList<Read> genes=CheckStrand.callGenes(cris, gCaller);
652
653 //Close the input stream
654 errorState|=ReadWrite.closeStream(cris);
655 return genes;
656 }
657
658 /**
659 * Creates a read input stream for the fasta reference.
660 * @param fname Fasta path.
661 * @return The stream.
662 */
663 private ConcurrentReadInputStream makeFastaCris(String fname){
664 FileFormat ffin=FileFormat.testInput(fname, FileFormat.FA, null, true, true);
665 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(-1, false, ffin, null);
666 cris.start(); //Start the stream
667 if(verbose){outstream.println("Started cris");}
668 return cris;
669 }
670
671 /**
672 * Print the final program results.
673 * @param results Results from read kmer depth analysis
674 * @param refResults Results based on transcriptome kmer comparison
675 */
676 private void outputResults(double[] results, double[] resultsN, double[] refResults){
677 if(ffout1==null) {return;}
678 ByteStreamWriter bsw=new ByteStreamWriter(ffout1);
679 bsw.start();
680
681 final double invReads=1.0/readsProcessed;
682 final double invBases=1.0/basesProcessed;
683
684 //Results based on read kmer depth
685 if(doDepthAnalysis){
686 double strandedness=results[4];
687 double strandednessN=resultsN[4];
688 double depth=results[5];
689 double nonUniqueFraction=results[7];
690
691 bsw.println("Depth_Analysis:");
692 bsw.println(String.format("Strandedness:\t%.2f%%", strandedness*100));
693 bsw.println(String.format("StrandednessN:\t%.2f%%", strandednessN*100));
694 bsw.println(String.format("AvgKmerDepth:\t%.3f", depth));
695 bsw.println(String.format("Kmers>Depth1:\t%.4f", nonUniqueFraction));
696 }
697
698 //Results based on stop codons
699 if(doStopAnalysis){
700 bsw.println();
701 boolean plus=(fPosSum>=rPosSum);
702 double gc=(ACGTCount[1]+ACGTCount[2])/(1.0*shared.Vector.sum(ACGTCount));
703 bsw.println("Stop_Codon_Analysis:");
704 bsw.println(String.format("MajorStrandORF:\t"+(plus ? "Plus" : "Minus")));
705 bsw.println(String.format("AvgReadLen:\t%.2f", basesProcessed*invReads));
706 bsw.println(String.format("AvgORFLen+:\t%.2f", fPosSum*invReads));
707 bsw.println(String.format("AvgORFLen-:\t%.2f", rPosSum*invReads));
708 bsw.println(String.format("AvgStopCount+:\t%.4f", fCountSum*invReads));
709 bsw.println(String.format("AvgStopCount-:\t%.4f", rCountSum*invReads));
710 bsw.println(String.format("GC_Content:\t%.4f", gc));
711
712 //Frame analysis seemed useless so I suppressed it,
713 //but this prints which frame has the longest ORF
714 long[] bestFrame=(plus ? fBestFrame : rBestFrame);
715 double invSum=1.0/shared.Vector.sum(bestFrame);
716 // bsw.println(String.format("FrameStats"/*+(plus ? "+" : "-")*/+":\t%.4f\t%.4f\t%.4f",
717 // bestFrame[0]*invSum, bestFrame[1]*invSum, bestFrame[2]*invSum));
718 }
719
720 //Results based on terminal poly-As versus poly-Ts
721 //TODO: Read 2 should also be used for this analysis... otherwise the insert size interferes...
722 if(testPolyA) {
723 bsw.println();
724 boolean plus=(polyACount>=polyTCount);
725 bsw.println("PolyA_Analysis:");
726 bsw.println(String.format("MajorStrandPA:\t"+(plus ? "Plus" : "Minus")));
727 bsw.println(String.format("PolyA/(PA+PT):\t%.6f", (polyACount/(1.0*(polyACount+polyTCount)))));
728 bsw.println(String.format("PolyAFraction:\t%.6f", polyACount*invReads));
729 }
730
731 //Results based on comparing transcriptome kmers to read kmers
732 if(refResults!=null) {
733 bsw.println();
734 double pmRatio=refResults[0];
735 double aFraction=refResults[1];
736 double bFraction=refResults[2];
737 boolean plus=(pmRatio>=0.5);
738 bsw.println("Ref_Analysis:");
739 bsw.println("MajorStrandREF:\t"+(plus ? "Plus" : "Minus"));
740 bsw.println(String.format("P/(P+M)_Ratio:\t%.6f", pmRatio));
741 bsw.println(String.format("GeneCoverage:\t%.4f", aFraction));
742 bsw.println(String.format("GenePrecision:\t%.4f", bFraction));
743 }
744
745 // if(scoreReadGenes) {
746 // bsw.println();
747 // double readsCalled=(gCallerPlusCount+gCallerMinusCount);
748 // double pmRatio=gCallerPlusCount/(1.0*readsCalled);
749 // double pScore=gCallerPlusScore/(1.0*readsCalled);
750 // double mScore=gCallerMinusScore/(1.0*readsCalled);
751 // boolean plus=(pmRatio>=0.5);
752 // bsw.println("Kmer_Frequency_Analysis:");
753 // bsw.println("MajorStrandKFA:\t"+(plus ? "Plus" : "Minus"));
754 // bsw.println(String.format("P/(P+M)_Ratio:\t%.6f", pmRatio));
755 // bsw.println(String.format("AvgScorePlus:\t%.6f", pScore));
756 // bsw.println(String.format("AvgScoreMinus:\t%.6f", mScore));
757 // bsw.println(String.format("UsedFraction:\t%.6f", readsCalled*invReads));
758 // }
759
760 //Results based on calling and scoring genes on each side of the read
761 if(scoreReadGenes) {
762 bsw.println();
763 double readsCalled=(gCallerPlusCount+gCallerMinusCount);
764 double pmRatio=gCallerPlusCount/(1.0*readsCalled);
765 double pScore=gCallerPlusScore/(1.0*gCallerPlusCalled);
766 double mScore=gCallerMinusScore/(1.0*gCallerMinusCalled);
767 boolean plus=(pmRatio>=0.5);
768 bsw.println("Read_Gene_Calling_Analysis:");
769 bsw.println("MajorStrandRGC:\t"+(plus ? "Plus" : "Minus"));
770 bsw.println(String.format("P/(P+M)_Ratio:\t%.6f", pmRatio));
771 bsw.println(String.format("AvgScorePlus:\t%.6f", pScore));
772 bsw.println(String.format("AvgScoreMinus:\t%.6f", mScore));
773 bsw.println(String.format("UsedFraction:\t%.6f", readsCalled*invReads));
774 }
775
776 //Alignment-based results
777 //TODO: Add a flag; should probably be disabled for euks with no gff
778 if(ffin1.samOrBam() && (transcriptome || rnaContigs || gff!=null || fna!=null)) {
779 long genesAligned=0;
780 long genesGT1=0;
781 double strandednessSumNorm=0;
782 double pmRatioSum=0;
783 long plusGeneCount=0;
784 double minorSum=0, majorSum=0, maxMinorSum=0, expectedSum=0;
785 {//Normalized Statistics
786 for(LongPair p : geneMap.values()) {
787 if(p.a+p.b>0) {
788 float pmRatio=p.a/(float)(p.a+p.b);
789 genesAligned++;
790 pmRatioSum+=pmRatio;
791 plusGeneCount+=(pmRatio>0.5f ? 1 : 0);
792 if(p.a+p.b>=minReads) {
793 float strandedness=CheckStrand.strandedness(p.a, p.b);
794 assert(strandedness>=0 && strandedness<=1.01) : strandedness+", "+p.a+", "+p.b;
795 strandednessSumNorm+=strandedness;
796 genesGT1++;
797 assert(strandednessSumNorm<=genesGT1) : strandednessSumNorm+", "+genesGT1;
798 minorSum+=p.min();
799 majorSum+=p.max();
800 maxMinorSum+=p.sum()/2;
801 expectedSum+=CheckStrand.expectedMinorAlleleCount(p.sum());
802 }
803 }
804 }
805 }
806 final double[] binStrandedness=binStrandedness();
807
808 final boolean plus=(plusAlignedReads>=minusAlignedReads);
809 final long readsAligned0=plusAlignedReads+minusAlignedReads;
810 final long readsAligned=Tools.max(1, readsAligned0);
811 final double alignmentRate=allAlignedReads/(1.0*samLinesProcessed);
812 final double alignmentRate2=samLinesAlignedToFeatures/(1.0*samLinesProcessed);
813 final double pmRatio=plusAlignedReads/(1.0*readsAligned);
814 double strandednessALN=Tools.max(plusAlignedReads, minusAlignedReads)/(1.0*readsAligned);
815 if(rnaContigs) {
816 //strandednessALN=CheckStrand.strandedness(minorSum, majorSum);
817 if(minorSum<=expectedSum) {//Expected case
818 strandednessALN=1-0.5f*(minorSum/expectedSum);//0.5-1
819 }else{//Rare case; overly unstranded
820 double range=maxMinorSum-expectedSum;
821 double dif=minorSum-expectedSum;
822 strandednessALN=0.5f*(1-(dif/range));
823 }
824 }
825
826 bsw.println();
827 bsw.println("Alignment_Results:");
828 bsw.println(String.format("StrandednessAL:\t%.2f%%", strandednessALN*100));
829 assert(strandednessSumNorm<=genesGT1) : strandednessSumNorm+", "+genesGT1;
830 bsw.println(String.format("StrandednessAN:\t%.2f%%", 100*strandednessSumNorm/genesGT1));
831 // assert(false) : strandednessSumNorm+", "+genesGT1;
832 if(binStrandedness!=null) {
833 bsw.println(String.format("StrandednessB:\t%.2f%%", binStrandedness[0]*100));
834 bsw.println(String.format("StrandednessBN:\t%.2f%%", binStrandedness[1]*100));
835 bsw.println(String.format("StrandednessBS:\t%.2f%%", binStrandedness[2]*100));
836 bsw.println(String.format("StrandednessBNS:\t%.2f%%", binStrandedness[3]*100));
837 }
838 if(!rnaContigs) {
839 bsw.println("MajorStrandAL:\t"+(plus ? "Plus" : "Minus"));
840 bsw.println(String.format("P/(P+M)_Ratio:\t%.6f", pmRatio));
841 bsw.println(String.format("P/(P+M)_RatioN:\t%.6f", pmRatioSum/genesAligned));
842 }
843 if(!transcriptome) {
844 bsw.println(String.format("PlusFeatures:\t%.6f", plusGeneCount/(float)genesAligned));
845 }
846 bsw.println(String.format("AlignmentRate:\t%.6f", alignmentRate));
847 if(!transcriptome && !rnaContigs) {bsw.println(String.format("Feature-Mapped:\t%.6f", alignmentRate2));}
848
849 // bsw.println(String.format("Plus-mapped:\t%d", plusAlignedReads));
850 // bsw.println(String.format("Minus-mapped:\t%d", minusAlignedReads));
851 }
852
853 //Displays fraction of reads merged
854 if(mergePairs && readsProcessed<readsIn) {
855 bsw.println();
856 bsw.println(String.format("PairMergeRate:\t%.4f", readsMerged/(1.0*readsProcessed)));
857 }
858
859 errorState=bsw.poisonAndWait() | errorState;
860 }
861
862 double[] binStrandedness() {
863 if(binMap==null || binMap.isEmpty()) {return null;}
864 long binsAligned=0;
865 long binsGT1=0;
866 double strandednessSumNorm=0;
867 double pmRatioSum=0;
868 double simpleSumNorm=0;
869 long plusBinCount=0;
870 double minorSum=0, majorSum=0, maxMinorSum=0, expectedSum=0;
871 for(ArrayList<LongPair> list : binMap.values()) {
872 for(LongPair p : list) {
873 if(p!=null && p.a+p.b>0) {
874 float pmRatio=p.a/(float)(p.a+p.b);
875 binsAligned++;
876 pmRatioSum+=pmRatio;
877 plusBinCount+=(pmRatio>0.5f ? 1 : 0);
878 if(p.a+p.b>=minReads) {
879 float strandedness=CheckStrand.strandedness(p.a, p.b);
880 assert(strandedness>=0 && strandedness<=1.01) : strandedness+", "+p.a+", "+p.b;
881 strandednessSumNorm+=strandedness;
882 binsGT1++;
883 assert(strandednessSumNorm<=binsGT1) : strandednessSumNorm+", "+binsGT1;
884 minorSum+=p.min();
885 majorSum+=p.max();
886 maxMinorSum+=p.sum()/2;
887 expectedSum+=CheckStrand.expectedMinorAlleleCount(p.sum());
888 simpleSumNorm+=p.max()/(double)p.sum();
889 }
890 }
891 }
892 }
893 double strandedness=CheckStrand.strandedness((long)minorSum, (long)majorSum, (long)maxMinorSum, (float)expectedSum);
894 double strandednessN=strandednessSumNorm/binsGT1;
895 double strandednessS=majorSum/(majorSum+minorSum);
896 double strandednessNS=simpleSumNorm/binsGT1;
897 return new double[] {strandedness, strandednessN, strandednessS, strandednessNS};
898 }
899
900 /**
901 * Manages a cached copy of the ref fasta to prevent reading it multiple times.
902 * @return The reference, as Read objects.
903 */
904 private ArrayList<Read> genomeSequence(){
905 assert(fna!=null);
906 if(genomeSequenceCache==null) {
907 genomeSequenceCache=ReadInputStream.toReads(fna, FileFormat.FASTA, -1);
908 }
909 return genomeSequenceCache;
910 }
911
912 /*--------------------------------------------------------------*/
913
914 void incrementGeneMap(String gene, ConcurrentHashMap<String, LongPair> map, int senseStrand, int amt){
915 if(gene==null) {return;}
916 LongPair pair=map.get(gene);
917 if(pair==null) {
918 map.putIfAbsent(gene, new LongPair());
919 pair=map.get(gene);
920 }
921 synchronized(pair) {
922 if(senseStrand==0) {pair.a+=amt;}
923 else {pair.b+=amt;}
924 }
925 }
926
927 void incrementBinMap(String gene, ConcurrentHashMap<String, ArrayList<LongPair>> map, int pos, int strand, int amt){
928 if(gene==null || map==null) {return;}
929 ArrayList<LongPair> list=map.get(gene);
930 if(list==null) {
931 map.putIfAbsent(gene, new ArrayList<LongPair>());
932 list=map.get(gene);
933 }
934 int idx=Tools.max(0, pos)/binlen;
935 increment(list, idx, strand, amt);
936 }
937
938 void increment(ArrayList<LongPair> list, int idx, int strand, int amt) {
939 LongPair bin;
940 synchronized(list) {
941 while(list.size()<=idx) {list.add(null);}
942 bin=list.get(idx);
943 if(bin==null) {
944 bin=new LongPair();
945 list.set(idx, bin);
946 }
947 }
948 synchronized(bin) {
949 if(strand==0) {bin.a+=amt;}
950 else {bin.b+=amt;}
951 }
952 }
953
954 /*--------------------------------------------------------------*/
955 /*---------------- Inner Classes ----------------*/
956 /*--------------------------------------------------------------*/
957
958 /**
959 * Handles all operations on input reads,
960 * such as merging, sketching, and stop-codon finding. */
961 class ProcessThread extends Thread {
962
963 //Constructor
964 ProcessThread(final ConcurrentReadInputStream cris_,
965 ConcurrentReadOutputStream crosP_, ConcurrentReadOutputStream crosM_, final int tid_){
966 cris=cris_;
967 crosP=crosP_;
968 crosM=crosM_;
969 tid=tid_;//Thread ID
970 canonSmm=new SketchMakerMini(canonTool, SketchObject.ONE_SKETCH, minEntropy, minProb, minQual);
971 fwdSmm=new SketchMakerMini(fwdTool, SketchObject.ONE_SKETCH, minEntropy, minProb, minQual);
972 gCallerT=(scoreReadGenes ? CallGenes.makeGeneCaller(pgm) : null);
973 // if(gCallerT!=null) {gCallerT.keepAtLeastOneOrf=true;}//Increases usage rate, but decreases precision
974 }
975
976 //Called by start()
977 @Override
978 public void run(){
979 //Do anything necessary prior to processing
980
981 //Process the reads
982 processInner();
983
984 //Do anything necessary after processing
985
986 //Indicate successful exit status
987 success=true;
988 }
989
990 /** Fetch lists of reads from the input stream. */
991 void processInner(){
992
993 //Grab the first ListNum of reads
994 ListNum<Read> ln=cris.nextList();
995
996 //As long as there is a nonempty read list...
997 while(ln!=null && ln.size()>0){
998 if(verbose){outstream.println("Fetched "+ln.size()+" reads.");}
999
1000 processList(ln);
1001
1002 //Notify the input stream that the list was used
1003 cris.returnList(ln);
1004
1005 //Fetch a new list
1006 ln=cris.nextList();
1007 }
1008
1009 //Notify the input stream that the final list was used
1010 if(ln!=null){
1011 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
1012 }
1013 }
1014
1015 /** Iterate through the reads */
1016 void processList(ListNum<Read> ln){
1017
1018 //Grab the actual read list from the ListNum
1019 final ArrayList<Read> reads=ln.list;
1020 pReads=(crosP==null ? null : new ArrayList<Read>());
1021 mReads=(crosM==null ? null : new ArrayList<Read>());
1022
1023 //Loop through each read in the list
1024 for(int idx=0; idx<reads.size(); idx++){
1025 final Read r1=reads.get(idx);
1026 final Read r2=r1.mate;
1027
1028 //Validate reads in worker threads
1029 if(!r1.validated()){r1.validate(true);}
1030 if(r2!=null && !r2.validated()){r2.validate(true);}
1031
1032 //Track the initial length for statistics
1033 final int initialLength1=r1.length();
1034 final int initialLength2=r1.mateLength();
1035
1036 //Increment counters
1037 readsInT+=r1.pairCount();
1038 basesInT+=initialLength1+initialLength2;
1039
1040 processReadPair(r1, r2);
1041 }
1042
1043 //Output reads to the output streams
1044 if(crosP!=null){crosP.add(pReads, ln.id);}
1045 if(crosM!=null){crosM.add(mReads, ln.id);}
1046 pReads=mReads=null;
1047 }
1048
1049 /**
1050 * Process a read or a read pair.
1051 * @param r1 Read 1
1052 * @param r2 Read 2 (may be null)
1053 */
1054 void processReadPair(Read r1, Read r2){
1055 if(r1.bases==null) {return;} //Especially for sam lines
1056 final SamLine sl=r1.samline;
1057
1058 if(sl!=null) {//This means the input was a sam or bam file
1059 processSamLine(r1, sl);
1060 if(sl.pairnum()>0) {return;}//Don't process read 2 from sam input
1061 }
1062
1063 //Merge pairs here if needed.
1064 if(mergePairs && r2!=null){
1065 final int insert=BBMerge.findOverlapStrict(r1, r2, false);
1066 if(insert>0){
1067 r2.reverseComplement();
1068 r1=r1.joinRead(insert);
1069 r2=null;
1070 readsMergedT++;
1071 }
1072 }
1073
1074 readsProcessedT++;
1075 basesProcessedT+=r1.length();
1076 r1.mate=null;
1077 if(doStopAnalysis) {countStopCodons(r1);}
1078 canonSmm.processReadNucleotide(r1);
1079 fwdSmm.processReadNucleotide(r1);
1080 if(testPolyA) {analyzePolyA(r1);}
1081 if(scoreReadGenes) {scoreGenes2(r1);}
1082 }
1083
1084 /**
1085 * Counts stop codons in each frame, and the longest ORF per frame.
1086 */
1087 void countStopCodons(Read r) {
1088 final byte[] bases=r.bases;
1089 if(bases.length<5) {return;}
1090
1091 final int k=3;
1092 final int shift=2*k;
1093 final int shift2=shift-2;
1094 final int mask=0b111111;
1095
1096 int kmer=0;
1097 int rkmer=0;
1098 int len=0;
1099
1100 Arrays.fill(fCount, 0);
1101 Arrays.fill(rCount, 0);
1102 Arrays.fill(fPos, bases.length);
1103 Arrays.fill(rPos, bases.length);
1104
1105 Arrays.fill(fMaxOrf, -1);
1106 Arrays.fill(rMaxOrf, -1);
1107 Arrays.fill(fLastStop, 0);
1108 Arrays.fill(rLastStop, 0);
1109
1110 for(int i=0; i<bases.length; i++){
1111 byte b=bases[i];
1112 int x=AminoAcid.baseToNumber[b];
1113 int x2=AminoAcid.baseToComplementNumber[b];
1114 kmer=((kmer<<2)|x)&mask;
1115 rkmer=((rkmer>>>2)|(x2<<shift2))&mask;
1116 if(x<0){
1117 len=0;
1118 rkmer=0;
1119 }else{
1120 len++;
1121 ACGTCountT[x]++;
1122 }
1123 if(len>=k){
1124 final int j=i%3;
1125 final byte aa=AminoAcid.codeToByte[kmer];
1126 final byte raa=AminoAcid.codeToByte[rkmer];
1127 if(aa=='*'){
1128 // System.err.println("aa="+Character.toString(aa));
1129 fCount[j]++;
1130 fPos[j]=Tools.min(fPos[j], i);//TODO: This only tracks the first ORF, not the longest
1131
1132 final int orfLen=i-fLastStop[j];
1133 fLastStop[j]=i;
1134 fMaxOrf[j]=Tools.max(fMaxOrf[j], orfLen);
1135 }
1136 if(raa=='*') {
1137 final int i2=bases.length-i-2;
1138 rCount[j]++;
1139 rPos[j]=Tools.min(rPos[j], i2);
1140
1141 final int orfLen=rLastStop[j]-i2;
1142 rLastStop[j]=i2;
1143 rMaxOrf[j]=Tools.max(rMaxOrf[j], orfLen);
1144 // System.err.println(i2+", "+rLastStop[j]+", "+rMaxOrf[j]);
1145 }
1146 }
1147 }
1148 fCountSumT+=Tools.min(fCount);
1149 rCountSumT+=Tools.min(rCount);
1150
1151 for(int i=0; i<3; i++) {
1152 if(fMaxOrf[i]<0) {fMaxOrf[i]=bases.length;}
1153 if(rMaxOrf[i]<0) {rMaxOrf[i]=bases.length;}
1154 }
1155
1156 final int[] fORF=(useFirstORF ? fPos : fMaxOrf);
1157 final int[] rORF=(useFirstORF ? rPos : rMaxOrf);
1158 final int mfp=Tools.max(fORF);
1159 final int mrp=Tools.max(rORF);
1160 fPosSumT+=mfp;
1161 rPosSumT+=mrp;
1162
1163 // fBestFrameT[Tools.maxIndex(fORF)]++;
1164 // rBestFrameT[Tools.maxIndex(rORF)]++;
1165 for(int i=0; i<3; i++) {//This is better since it increments all equal ones
1166 if(fORF[i]==mfp){fBestFrameT[i]++;}
1167 if(rORF[i]==mrp){rBestFrameT[i]++;}
1168 }
1169 // assert(false) : "\n"+Arrays.toString(fCount)+"\n"+Arrays.toString(rCount)+"\n"+Arrays.toString(fPos)+"\n"+Arrays.toString(rPos);
1170 }
1171
1172 /**
1173 * Counts tip poly-As and poly-Ts.
1174 * TODO: Should take into account pairnum so read 2 can be used.
1175 */
1176 void analyzePolyA(Read r) {
1177 final int trailingPolyA=r.countTrailing('A'), leadingPolyT=r.countLeading('T');
1178 // final int trailingPolyT, leadingPolyA;//These two should be spurious, but could be used to infer whether the poly-A is due to real poly-A tails.
1179
1180 if(trailingPolyA>leadingPolyT && trailingPolyA>minPolyA) {polyACountT++;}
1181 else if(trailingPolyA<leadingPolyT && leadingPolyT>minPolyA) {polyTCountT++;}
1182
1183 }
1184
1185 /**
1186 * Calls genes on both strands, and records which strand
1187 * had the highest-scoring gene.
1188 */
1189 void scoreGenes2(Read r) {
1190 ArrayList<Orf> list;
1191 list=gCallerT.callGenes(r, true);
1192 // System.err.print((list==null ? 0 : list.size())+", ");
1193 // Orf bestPlus=null;
1194 // Orf bestMinus=null;
1195 final float min=-99999;
1196 float plusScore=min, minusScore=min;
1197 if(list!=null && !list.isEmpty()) {
1198 for(Orf orf : list) {
1199 // if(orf.strand==0) {
1200 // if(bestPlus==null || bestPlus.score()<orf.score()) {bestPlus=orf;}
1201 // }else {
1202 // if(bestMinus==null || bestMinus.score()<orf.score()) {bestMinus=orf;}
1203 // }
1204 if(orf.strand==0) {
1205 plusScore=Tools.max(plusScore, orf.score());
1206 }else {
1207 minusScore=Tools.max(minusScore, orf.score());
1208 }
1209 }
1210 }
1211
1212 //This block is to ensure the uncalled strand gets a lower score,
1213 //in case the called strand has a negative score
1214 if(plusScore==min && minusScore==min) {
1215 plusScore=minusScore=0;
1216 }else if(plusScore==min) {
1217 plusScore=Tools.min(0, minusScore*1.5f-1);
1218 }else if(minusScore==min) {
1219 minusScore=Tools.min(0, plusScore*1.5f-1);
1220 }
1221
1222 // if(plusScore<=0 && minusScore<=0) {return;}
1223
1224 gCallerPlusScoreT+=plusScore;
1225 gCallerMinusScoreT+=minusScore;
1226 if(plusScore>minusScore) {gCallerPlusCountT++;}
1227 else if(minusScore>plusScore){gCallerMinusCountT++;}
1228 if(plusScore>0){gCallerPlusCalledT++;}
1229 if(minusScore>0){gCallerMinusCalledT++;}
1230
1231 }
1232
1233 @Deprecated
1234 /**
1235 * Old version; just looked at enriched interior kmers instead of
1236 * doing normal gene-calling. Didn't work very will.
1237 */
1238 void scoreGenes(Read r) {
1239 byte[] bases=r.bases;
1240 double plusScoreCDS=gCaller.scoreFeature(bases, ProkObject.CDS);//These scores are suspiciously low; I wonder if frame tracking is working correctly?
1241 double plusScore16S=gCaller.scoreFeature(bases, ProkObject.r16S);
1242 double plusScore5S=gCaller.scoreFeature(bases, ProkObject.r5S);
1243 AminoAcid.reverseComplementBasesInPlace(bases);
1244 double minusScoreCDS=gCaller.scoreFeature(bases, ProkObject.CDS);
1245 double minusScore16S=gCaller.scoreFeature(bases, ProkObject.r16S);
1246 double minusScore5S=gCaller.scoreFeature(bases, ProkObject.r5S);
1247 AminoAcid.reverseComplementBasesInPlace(bases);
1248
1249 double maxCDS=Tools.max(plusScoreCDS, minusScoreCDS)*1.6;
1250 double max16S=Tools.max(plusScore16S, minusScore16S)*1.2;
1251 double max5S=Tools.max(plusScore5S, minusScore5S)*0.9;
1252 boolean cds=maxCDS>=max16S;
1253 boolean r5s=max5S>=max16S && max5S>=maxCDS;
1254 double plusScore=r5s ? plusScore5S : cds ? plusScoreCDS : plusScore16S;
1255 double minusScore=r5s ? minusScore5S : cds ? minusScoreCDS : minusScore16S;
1256
1257 //Doesn't fit the model well...
1258 if(plusScore<0.97 && minusScore<0.97) {return;}
1259
1260 gCallerPlusScoreT+=plusScore;
1261 gCallerMinusScoreT+=minusScore;
1262 if(plusScore>=minusScore) {gCallerPlusCountT++;}
1263 else {gCallerMinusCountT++;}
1264 }
1265
1266 /**
1267 * Associate an aligned read with the plus or minus strand.
1268 * @param r1 The read.
1269 * @param sl The read's SamLine.
1270 */
1271 void processSamLine(final Read r1, final SamLine sl) {
1272 if(!sl.primary() || sl.supplementary()) {return;}
1273 samLinesProcessedT++;
1274 if(!sl.mapped()) {return;}
1275 allAlignedReadsT++;
1276
1277 //Flip read 2's associated strand.
1278 final int mappedStrand=(sl.strand()^sl.pairnum());
1279
1280 //The strand on which the gene is located.
1281 int senseStrand=-1;
1282 String gene=null;
1283 if(transcriptome) {
1284 senseStrand=mappedStrand;
1285 gene=sl.rnameS();
1286 }else if(rnaContigs) {
1287 senseStrand=mappedStrand;
1288 gene=sl.rnameS();
1289 }else if(gffLines!=null){//Try to figure out the sense strand
1290 final int start=sl.start(false, false);
1291 // final int stop=sl.stop(start, false, false);
1292 // final int p=(start+stop)/2;
1293 final int p=start;//A point used as proxy for the read location
1294
1295 //Get the ranges for the contig
1296 String rname=sl.rnameS();
1297 Range[] ranges=rangeMap.get(rname);
1298
1299 //Retry the name, trimmed to the first whitespace
1300 if(ranges==null) {ranges=rangeMap.get(sl.rnamePrefix());}
1301 // assert(ranges!=null) : "Can't find rname "+sl.rnameS()+":\n"+sl+"\n";// in "+rangeMap.keySet()+"\n"+sl;
1302
1303 if(ranges!=null) {
1304 //Find the range containing the proxy point
1305 int idx=Range.findIndex(p, ranges);
1306 if(idx<0) {idx=-idx-1;}
1307 if(idx<0 || idx>=ranges.length){return;}
1308 final Range r=ranges[idx];
1309
1310 //List of features overlapping the point
1311 final ArrayList<GffLine> lines=(ArrayList<GffLine>) r.obj1;
1312 for(int i=lines.size()-1; i>=0; i--) {//Now to select a line...
1313 final GffLine line=lines.get(i);
1314 //TODO: With multiple overlapping features, this may or may not be the best one
1315 if(r.intersects(line.start, line.stop)) {
1316 senseStrand=mappedStrand^line.strand;
1317 gene=sl.rnameS();
1318 break;
1319 }
1320 }
1321 }
1322 }
1323
1324 if(gene!=null) {
1325 incrementGeneMap(gene, geneMap, senseStrand, 1);
1326 incrementBinMap(gene, binMap, sl.pos, mappedStrand, 1);
1327
1328 //Track results according to the determined strand
1329 if(senseStrand==0) {
1330 samLinesAlignedToFeaturesT++;
1331 plusAlignedReadsT++;
1332 if(crosP!=null) {pReads.add(r1);}
1333 }else if(senseStrand==1){
1334 samLinesAlignedToFeaturesT++;
1335 minusAlignedReadsT++;
1336 if(crosM!=null) {mReads.add(r1);}
1337 }else {
1338 assert(senseStrand==-1);
1339 }
1340 }
1341
1342 }
1343
1344 /** Number of reads in to this thread */
1345 protected long readsInT=0;
1346 /** Number of bases in to this thread */
1347 protected long basesInT=0;
1348
1349 /** Number of reads processed by this thread */
1350 protected long readsProcessedT=0;
1351 /** Number of bases processed by this thread */
1352 protected long basesProcessedT=0;
1353
1354 /** Number of reads merged by this thread */
1355 protected long readsMergedT=0;
1356
1357 /** True only if this thread has completed successfully */
1358 boolean success=false;
1359
1360 /** Shared input stream */
1361 private final ConcurrentReadInputStream cris;
1362
1363 private final ConcurrentReadOutputStream crosP;
1364 private final ConcurrentReadOutputStream crosM;
1365
1366 private ArrayList<Read> pReads, mReads;
1367
1368 final SketchMakerMini canonSmm;
1369 final SketchMakerMini fwdSmm;
1370
1371 //These are just buffers
1372 /** Counts of stop codons on forward strand */
1373 private final int[] fCount=new int[3];
1374 /** Counts of stop codons on reverse strand */
1375 private final int[] rCount=new int[3];
1376 /** Longest initial ORF on forward strand */
1377 private final int[] fPos=new int[3];
1378 /** Longest initial ORF on reverse strand */
1379 private final int[] rPos=new int[3];
1380
1381 /** Longest ORF on forward strand */
1382 private final int[] fMaxOrf=new int[3];
1383 /** Longest ORF on reverse strand */
1384 private final int[] rMaxOrf=new int[3];
1385 /** Last stop seen on forward strand */
1386 private final int[] fLastStop=new int[3];
1387 /** Last stop seen on reverse strand */
1388 private final int[] rLastStop=new int[3];
1389
1390 private long fCountSumT;
1391 private long rCountSumT;
1392 private long fPosSumT;
1393 private long rPosSumT;
1394
1395 private final long[] fBestFrameT=new long[3];
1396 private final long[] rBestFrameT=new long[3];
1397 private final long[] ACGTCountT=new long[4];
1398
1399 private long polyACountT=0;
1400 private long polyTCountT=0;
1401
1402 private long gCallerPlusCountT=0;
1403 private long gCallerMinusCountT=0;
1404 private long gCallerPlusCalledT=0;
1405 private long gCallerMinusCalledT=0;
1406 private double gCallerPlusScoreT=0;
1407 private double gCallerMinusScoreT=0;
1408
1409 private long plusAlignedReadsT=0;
1410 private long minusAlignedReadsT=0;
1411 private long allAlignedReadsT=0;
1412
1413 private long samLinesProcessedT=0;
1414 private long samLinesAlignedToFeaturesT=0;
1415
1416 private GeneCaller gCallerT;
1417
1418 /** Thread ID */
1419 final int tid;
1420 }
1421
1422 /*--------------------------------------------------------------*/
1423 /*---------------- Fields ----------------*/
1424 /*--------------------------------------------------------------*/
1425
1426 /** Primary input file path */
1427 private String in1=null;
1428 /** Secondary input file path */
1429 private String in2=null;
1430
1431 private String qfin1=null;
1432 private String qfin2=null;
1433
1434 String fna=null;
1435 String gff=null;
1436 String pgmFile=null;
1437 private String types="CDS,rRNA,tRNA,ncRNA,exon,5S,16S,23S";
1438 private ArrayList<GffLine> gffLines=null;
1439
1440 private ConcurrentHashMap<String, ArrayList<LongPair>> binMap;
1441
1442 /**
1443 * Map associating with contig names with ordered arrays of nonoverlapping ranges
1444 * Each range has attached a list of features that fully contain it. */
1445 private HashMap<String, Range[]> rangeMap;
1446
1447 /** Primary output file path */
1448 private String out1="stdout.txt";
1449
1450 /** Output file path for plus-aligned reads */
1451 private String outPlus=null;
1452
1453 /** Output file path for minus-aligned reads */
1454 private String outMinus=null;
1455
1456 /** Override input file extension */
1457 private String extin=null;
1458 /** Override output file extension */
1459 private String extout=null;
1460
1461 /** Whether interleaved was explicitly set. */
1462 private boolean setInterleaved=false;
1463
1464 private int binlen=0;
1465
1466 /*--------------------------------------------------------------*/
1467
1468 /** Number of reads processed */
1469 protected long readsIn=0;
1470 /** Number of bases processed */
1471 protected long basesIn=0;
1472
1473 /** Number of reads processed */
1474 protected long readsProcessed=0;
1475 /** Number of bases processed */
1476 protected long basesProcessed=0;
1477
1478 protected long readsMerged=0;
1479
1480 /** Quit after processing this many input reads; -1 means no limit */
1481 private long maxReads=-1;
1482
1483 private float samplerate=1;
1484 private long sampleseed=17;
1485 private int sketchSize=80000;
1486
1487 private float minEntropy=0;
1488 private float minProb=0;
1489 private byte minQual=0;
1490 private boolean mergePairs=false;
1491 private final boolean doDepthAnalysis=true;
1492 private boolean doStopAnalysis=true;
1493 private boolean testPolyA=true;
1494
1495 private ArrayList<Read> genes;
1496
1497 private SketchTool canonTool;
1498 private SketchTool fwdTool;
1499
1500 private SketchHeap canonHeap=null;
1501 private SketchHeap fwdHeap=null;
1502
1503 private Sketch canonSketch=null;
1504 private Sketch fwdSketch=null;
1505
1506 private Sketch canonGeneSketch=null;
1507 private Sketch plusSketch=null;
1508 private Sketch minusSketch=null;
1509
1510 private long fCountSum=0;
1511 private long rCountSum=0;
1512 private long fPosSum=0;
1513 private long rPosSum=0;
1514
1515 private boolean useFirstORF=false;
1516 private final long[] fBestFrame=new long[3];
1517 private final long[] rBestFrame=new long[3];
1518 private final long[] ACGTCount=new long[4];
1519
1520 private long polyACount=0;
1521 private long polyTCount=0;
1522 private int minPolyA=6;
1523
1524 private long gCallerPlusCount=0;
1525 private long gCallerMinusCount=0;
1526 private long gCallerPlusCalled=0;
1527 private long gCallerMinusCalled=0;
1528 private double gCallerPlusScore=0;
1529 private double gCallerMinusScore=0;
1530
1531 private long plusAlignedReads=0;
1532 private long minusAlignedReads=0;
1533 private long allAlignedReads=0;
1534 private long samLinesProcessed=0;
1535 private long samLinesAlignedToFeatures=0;
1536
1537 //Possibly should change this to scoring the best orf per strand
1538 //This gave the wrong answer for a metatranscriptome
1539 private boolean scoreReadGenes=true;
1540 private final GeneModel pgm;
1541 private final GeneCaller gCaller;
1542 private int passes=2;
1543 private boolean streamGenome=false;
1544 private ArrayList<Read> genomeSequenceCache=null;
1545
1546 ConcurrentHashMap<String, LongPair> geneMap=new ConcurrentHashMap<String, LongPair>();
1547
1548 /** Whether the input reference is a transcriptome or genome */
1549 private boolean transcriptome=false;
1550 /** True for unknown sense contigs from RNA-seq data */
1551 private boolean rnaContigs=false;
1552
1553 private boolean normalize=false;
1554 private int minReads=2;//Don't calculate strandedness from fewer reads
1555
1556 /*--------------------------------------------------------------*/
1557 /*---------------- Final Fields ----------------*/
1558 /*--------------------------------------------------------------*/
1559
1560 /** Primary input file */
1561 private final FileFormat ffin1;
1562 /** Secondary input file */
1563 private final FileFormat ffin2;
1564
1565 /** Primary output file */
1566 private final FileFormat ffout1;
1567
1568 @Override
1569 public final ReadWriteLock rwlock() {return rwlock;}
1570 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
1571
1572 /*--------------------------------------------------------------*/
1573 /*---------------- Static Fields ----------------*/
1574 /*--------------------------------------------------------------*/
1575
1576 /*--------------------------------------------------------------*/
1577 /*---------------- Common Fields ----------------*/
1578 /*--------------------------------------------------------------*/
1579
1580 /** Print status messages to this output stream */
1581 private PrintStream outstream=System.err;
1582 /** Print verbose messages */
1583 public static boolean verbose=false;
1584 /** True if an error was encountered */
1585 public boolean errorState=false;
1586 /** Overwrite existing output files */
1587 private boolean overwrite=true;
1588 /** Append to existing output files */
1589 private boolean append=false;
1590
1591 }