Debian Codegraph @

current/jgi/CheckStrand.java

raw symbols SCIP
1 package jgi;
2
3 import java.io.File;
4 import java.util.ArrayList;
5 import java.util.Arrays;
6 import java.util.HashMap;
7 import java.util.Random;
8
9 import dna.Data;
10 import fileIO.ByteStreamWriter;
11 import fileIO.FileFormat;
12 import fileIO.ReadWrite;
13 import fileIO.TextFile;
14 import gff.GffLine;
15 import prok.CallGenes;
16 import prok.GeneCaller;
17 import prok.GeneModel;
18 import prok.GeneModelParser;
19 import prok.Orf;
20 import shared.Parse;
21 import shared.Parser;
22 import shared.PreParser;
23 import shared.Shared;
24 import shared.Timer;
25 import shared.Tools;
26 import sketch.Sketch;
27 import sketch.SketchMakerMini;
28 import sketch.SketchObject;
29 import sketch.SketchTool;
30 import stream.ConcurrentReadInputStream;
31 import stream.FASTQ;
32 import stream.Read;
33 import stream.ReadInputStream;
34 import structures.DoubleList;
35 import structures.Feature;
36 import structures.ListNum;
37
38 /**
39 * Checks the strandedness of RNA-seq reads.
40 *
41 * @author Brian Bushnell
42 * @date Aug 4, 2023
43 *
44 */
45 public class CheckStrand {
46
47 /**
48 * Code entrance from the command line.
49 * @param args Command line arguments
50 */
51 public static void main(String[] args){
52 //Start a timer immediately upon code entrance.
53 Timer t=new Timer();
54
55 //Create an instance of this class
56 CheckStrand x=new CheckStrand(args);
57
58 //Run the object
59 x.process(t);
60
61 //Close the print stream if it was redirected
62 Shared.closeStream(x.outstream);
63 }
64
65 /**
66 * Constructor.
67 * @param args Command line arguments
68 */
69 public CheckStrand(String[] args){
70
71 {//Preparse block for help, config files, and outstream
72 PreParser pp=new PreParser(args, getClass(), false);
73 args=pp.args;
74 outstream=pp.outstream;
75 }
76
77 Parser parser=new Parser();
78 parser.out1=out1;
79 for(int i=0; i<args.length; i++){
80 String arg=args[i];
81 String[] split=arg.split("=");
82 String a=split[0].toLowerCase();
83 String b=split.length>1 ? split[1] : null;
84 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
85
86 if(a.equals("parse_flag_goes_here")){
87 //Set a variable here
88 }else if(a.equals("size") || a.equals("len") || a.equals("length") || a.equals("sketchsize")){
89 sketchSize=Parse.parseIntKMG(b);
90 }else if(a.equals("samplerate")){
91 samplerate=Float.parseFloat(b);
92 }else if(a.equals("sampleseed") || a.equals("seed")){
93 sampleseed=Long.parseLong(b);
94 }else if(a.equals("normalize")){
95 normalize=Parse.parseBoolean(b);
96 }else if(a.equals("ref") || a.equals("fna")){
97 fna=b;
98 }else if(a.equals("gff")){
99 gff=b;
100 }else if(parser.parse(arg, a, b)){
101 //do nothing
102 }else{
103 // throw new RuntimeException("Unknown parameter "+args[i]);
104 assert(false) : "Unknown parameter "+args[i];
105 outstream.println("Unknown parameter "+args[i]);
106 }
107 }
108
109 {//Process parser fields
110 Parser.processQuality();
111
112 maxReads=parser.maxReads;
113 in1=parser.in1;
114 out1=parser.out1;
115 }
116
117 ffout1=FileFormat.testOutput(out1, FileFormat.TXT, null, true, true, false, false);
118 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, null, true, true);
119 }
120
121 void process(Timer t){
122 if(verbose){System.err.println("Setting sketch params.");}
123 setSketchStatics();
124
125 SketchTool canonTool=new SketchTool(sketchSize, 0, true, true, true);
126 SketchTool forwardTool=new SketchTool(sketchSize, 0, true, true, false);
127
128 FASTQ.PAIR_READS=false;
129 final int threads=Tools.min(Shared.threads(), 16); //Can't seem to scale beyond around 8 threads...
130
131 System.err.println("Making canonical sketch.");
132 Sketch canonSketch=canonTool.processReadsMT(in1, threads, maxReads, SketchObject.ONE_SKETCH,
133 samplerate, 0, 0, (byte)0, false);
134
135 System.err.println("Making forward sketch.");
136 Sketch fwdSketch=forwardTool.processReadsMT(in1, threads, maxReads, SketchObject.ONE_SKETCH,
137 samplerate, 0, 0, (byte)0, false);
138
139 final double[] refResults=calcPMRatioWithRef(canonTool, forwardTool, canonSketch, fwdSketch);
140
141 FASTQ.PAIR_READS=true;
142 if(verbose){outstream.println("Finished reading data.");}
143
144 outstream.println();
145 double[] results=calcStrandedness(canonSketch, fwdSketch);
146 if(normalize) {results=calcStrandednessNormalized(canonSketch, fwdSketch);}
147
148 outputResults(results, refResults);
149
150 outstream.println();
151 t.stop("Time:\t");
152 assert(!errorState) : "An error was encountered.";
153 }
154
155 private void setSketchStatics() {
156 SketchObject.AUTOSIZE=false;
157 SketchObject.k=32;
158 SketchObject.k2=-1;//Otherwise the estimates are too high
159 SketchObject.setK=true;
160 SketchObject.sampleseed=sampleseed;
161 // SketchObject.defaultParams.minKeyOccuranceCount=2;
162
163 SketchObject.AUTOSIZE=false;
164 SketchObject.AUTOSIZE_LINEAR=false;
165 SketchObject.targetSketchSize=sketchSize;
166 SketchObject.SET_TARGET_SIZE=true;
167 SketchObject.processSSU=false;
168
169 SketchObject.defaultParams.parse("trackcounts", "trackcounts", null);
170 SketchObject.defaultParams.samplerate=samplerate;
171 SketchObject.postParse();
172 }
173
174 //Old version
175 // @Deprecated
176 // private double[] calcPMRatio_old(SketchTool canonTool, SketchTool fwdTool,
177 // Sketch canonSketch, Sketch fwdSketch) {
178 //
179 // FASTQ.PAIR_READS=false;
180 // SketchObject.rcomp=false;
181 //
182 // if(fna==null) {return null;}
183 //
184 // ArrayList<Read> genes=null;
185 // if(gff!=null) {
186 // ArrayList<GffLine> lines=getGffLines(gff, types);
187 // HashMap<String, Read> seqMap=getSequenceMap(fna);
188 // genes=CheckStrand.grabGenes(lines, seqMap);
189 // }else{
190 // System.err.println("Calling genes.");
191 // genes=callGenes(fna);
192 // }
193 // if(genes==null || genes.isEmpty()) {return null;}
194 // System.err.println("Processing "+genes.size()+" genes.");
195 //
196 // Sketch[] geneSketches=sketchGenes(genes, canonTool, fwdTool);
197 // Sketch canonGeneSketch=geneSketches[0], plusSketch=geneSketches[1], minusSketch=geneSketches[2];
198 //
199 // double[] p=CheckStrand.countSharedSum(fwdSketch, plusSketch);
200 // double[] m=CheckStrand.countSharedSum(fwdSketch, minusSketch);
201 //
202 // double ratio=p[3]/(p[3]+m[3]);
203 // double[] abFractions=CheckStrand.calcCoverage(canonSketch, canonGeneSketch);
204 //
205 // double[] ret={ratio, abFractions[0], abFractions[1]};
206 // return ret;
207 // }
208
209 /**
210 * Calculate the Plus/Minus mapping ratio using transcriptome kmers.
211 * @param canonTool SketchTool for canonical kmers.
212 * @param fwdTool SketchTool for forward kmers.
213 * @param canonSketch Read Sketch using canonical kmers.
214 * @param fwdSketch Read Sketch using forward kmers.
215 * @return Array of results (see calcPMRatio).
216 */
217 private double[] calcPMRatioWithRef(SketchTool canonTool, SketchTool fwdTool,
218 Sketch canonSketch, Sketch fwdSketch) {
219 ArrayList<Read> genes=grabGenes();
220 if(genes==null) {return null;}
221 outstream.println("Processing "+genes.size()+" genes.");
222 Sketch[] geneSketches=sketchGenes(genes, canonTool, fwdTool);
223 Sketch canonGeneSketch=geneSketches[0], plusSketch=geneSketches[1], minusSketch=geneSketches[2];
224 return calcPMRatioWithGeneSketches(canonSketch, fwdSketch, canonGeneSketch, plusSketch, minusSketch);
225 }
226
227 /**
228 * Generate a list of gene sequences from the reference.
229 * @return The list.
230 */
231 private ArrayList<Read> grabGenes(){
232 if(fna==null) {return null;}
233
234 ArrayList<Read> genes=null;
235 if(gff!=null) {
236 ArrayList<GffLine> lines=getGffLines(gff, types);
237 HashMap<String, Read> map=getSequenceMap(fna);
238 genes=CheckStrand.grabGenes(lines, map);
239 }else{
240 System.err.println("Calling genes.");
241 genes=callGenes(fna);
242 }
243 return (genes==null || genes.isEmpty()) ? null : genes;
244 }
245
246 /**
247 * Calculate the Plus/Minus mapping ratio using transcriptome kmers.
248 * @param canonSketch Read Sketch using canonical kmers.
249 * @param fwdSketch Read Sketch using forward kmers.
250 * @param canonGeneSketch Transcriptome Sketch using canonical kmers.
251 * @param plusSketch Transcriptome Sketch using plus-strand forward kmers.
252 * @param minusSketch Transcriptome Sketch using minus-strand forward kmers.
253 * @return Results vector: {ratio, abFractions[0], abFractions[1]}
254 */
255 static double[] calcPMRatioWithGeneSketches(Sketch canonSketch, Sketch fwdSketch,
256 Sketch canonGeneSketch, Sketch plusSketch, Sketch minusSketch) {
257 double[] p=CheckStrand.countSharedSum(fwdSketch, plusSketch);
258 double[] m=CheckStrand.countSharedSum(fwdSketch, minusSketch);
259
260 double ratio=p[3]/(p[3]+m[3]);
261 double[] abFractions=CheckStrand.calcCoverage(canonSketch, canonGeneSketch);
262
263 double[] ret={ratio, abFractions[0], abFractions[1]};
264 return ret;
265 }
266
267 /**
268 * Create sketches of the transcriptome.
269 * @param genes List of gene sequences (sense on plus strand).
270 * @param canonTool SketchTool for canonical kmers.
271 * @param fwdTool SketchTool for forward kmers.
272 * @return Vector of: {canonGeneSketch, plusSketch, minusSketch}
273 */
274 static Sketch[] sketchGenes(ArrayList<Read> genes, SketchTool canonTool, SketchTool fwdTool) {
275 SketchMakerMini smmPlus=new SketchMakerMini(fwdTool, SketchObject.ONE_SKETCH, SketchObject.defaultParams);
276 SketchMakerMini smmMinus=new SketchMakerMini(fwdTool, SketchObject.ONE_SKETCH, SketchObject.defaultParams);
277 SketchMakerMini smmCanon=new SketchMakerMini(canonTool, SketchObject.ONE_SKETCH, SketchObject.defaultParams);
278 for(Read r : genes) {
279 smmCanon.processRead(r);
280 smmPlus.processRead(r);
281 r.reverseComplement();
282 r.setStrand(0);
283 smmMinus.processRead(r);
284 }
285 Sketch canonGeneSketch=smmCanon.toSketch(0);
286 Sketch plusSketch=smmPlus.toSketch(0);
287 Sketch minusSketch=smmMinus.toSketch(0);
288 return new Sketch[] {canonGeneSketch, plusSketch, minusSketch};
289 }
290
291 /**
292 * Print the final program results.
293 * @param results Results from read kmer depth analysis
294 * @param refResults Results based on transcriptome kmer comparison
295 */
296 private void outputResults(double[] results, double[] refResults){
297 if(ffout1==null) {return;}
298 ByteStreamWriter bsw=new ByteStreamWriter(ffout1);
299 bsw.start();
300
301 double strandedness=results[4];
302 double depth=results[5];
303
304 //Write stuff to the bsw
305 bsw.println(String.format("Strandedness:\t%.2f%%", strandedness*100));
306 bsw.println(String.format("AvgKmerDepth:\t%.2f", depth));
307 if(refResults!=null) {
308 double pmRatio=refResults[0];
309 double aFraction=refResults[1];
310 double bFraction=refResults[2];
311 bsw.println(String.format("P/(P+M)_Ratio:\t%.6f", pmRatio));
312 bsw.println("MajorStrand:\t"+((pmRatio>=0.5) ? "Plus" : "Minus"));
313 bsw.println(String.format("GeneCoverage:\t%.4f", aFraction));
314 bsw.println(String.format("GenePrecision:\t%.4f", bFraction));
315 }
316
317 errorState=bsw.poisonAndWait() | errorState;
318 }
319
320 /*--------------------------------------------------------------*/
321
322 /**
323 * Determine the strandedness of a set of reads by comparing a Sketch of
324 * canonical kmers to forward kmers.
325 * @param saCanon Sketch of canonical kmers.
326 * @param sbFwd Sketch of forward kmers.
327 * @return Results vector: {totalSum, minSum, expectedMinSum, maxPossibleMinSum,
328 * strandedness, depth, matches, nonUniqueFraction}
329 */
330 static double[] calcStrandedness(Sketch saCanon, Sketch sbFwd) {
331 final long[] a=saCanon.keys, b=sbFwd.keys;
332 final int[] aCounts=saCanon.keyCounts, bCounts=sbFwd.keyCounts;
333
334 int matches=0;
335 int totalCount=0;
336 long sharedSum=0;
337 long nonUniqueCount=0;
338 double totalSum=0;
339 double minSum=0;
340 double expectedMinSum=0;
341 double maxPossibleMinSum=0;
342
343 //Here we walk down the Sketches and find where they share kmers.
344 //In those cases, the counts are compared to determine balance.
345 for(int i=0, j=0; i<a.length && j<b.length; ){
346 final long ka=a[i], kb=b[j];
347 if(ka==kb){//Match
348 matches++;
349 final int ca=aCounts[i];
350 final int cb=bCounts[j];
351 final int cmin=Tools.min(cb, ca-cb);
352 assert(cmin>=0) : ca+", "+cb;
353 nonUniqueCount+=(ca>1 ? 1 : 0);
354 totalSum+=ca;
355 totalCount++;
356 sharedSum+=ca;
357 minSum+=cmin;
358 maxPossibleMinSum+=(ca/2);
359 expectedMinSum+=expectedMinorAlleleCount(ca);
360 i++;
361 j++;
362 }else if(ka<kb){//kb was missing; thus it had a minor count of 0
363 final int ca=aCounts[i];
364 final int cb=0;
365 final int cmin=Tools.min(cb, ca-cb);//Should always be cb
366 assert(cmin>=0);//Should always be 0
367 nonUniqueCount+=(ca>1 ? 1 : 0);
368 totalSum+=ca;
369 totalCount++;
370 minSum+=cmin;
371 maxPossibleMinSum+=(ca/2);
372 expectedMinSum+=expectedMinorAlleleCount(ca);
373 i++;
374 }else{//ka was missing; thus this is a noncanonical key
375 j++;
376 }
377 }
378
379 //Strandedness will be (0.5-1.0) for normal (fully unstranded-fully stranded) libraries.
380 //Synthetic or binned libraries with a perfectly flat distribution will get 0.0,
381 //but anything between 0.0 and 0.5 would be unusual.
382 //Basically 1.0 is preference for a strand, 0.5 is no preference for a strand,
383 //and 0.0 is preference for perfect balance between strands - as you would get
384 //if you treated paired reads as single-ended.
385 double strandedness;
386 if(minSum<=expectedMinSum) {//Normal case; strandedness between 0 and 50%
387 // strandedness=1-(minSum/(expectedMinSum+minSum));//Not sure about the proper formula; needs thought
388 strandedness=0.5+(1-(minSum/expectedMinSum))*0.5;
389 }else{//Odd case; distribution is more even than expected by chance
390 assert(minSum<=maxPossibleMinSum) : minSum+", "+maxPossibleMinSum;
391 double range=(maxPossibleMinSum-expectedMinSum);
392 double delta=minSum-expectedMinSum;
393 assert(delta>=0 && delta<=range);
394 double x=0.5*(1-(delta/range));
395 strandedness=x;//Not really sure about this either
396 }
397 double depth=totalSum/totalCount;
398 double nonUniqueFraction=nonUniqueCount/(1.0*totalCount);
399 return new double[] {totalSum, minSum, expectedMinSum, maxPossibleMinSum,
400 strandedness, depth, matches, nonUniqueFraction};
401 }
402
403 /**
404 * Determine the strandedness of a set of reads by comparing a Sketch of
405 * canonical kmers to forward kmers.
406 * In this mode, each kmer contributes 0-1.0 strandedness regardless of its depth.
407 * @param saCanon Sketch of canonical kmers.
408 * @param sbFwd Sketch of forward kmers.
409 * @return Results vector: {totalSum, minSum, expectedMinSum, maxPossibleMinSum,
410 * strandedness, depth, matches, nonUniqueFraction}
411 */
412 static double[] calcStrandednessNormalized(Sketch saCanon, Sketch sbFwd) {
413 final long[] a=saCanon.keys, b=sbFwd.keys;
414 final int[] aCounts=saCanon.keyCounts, bCounts=sbFwd.keyCounts;
415
416 int matches=0;
417 int totalCount=0;
418 long sharedSum=0;
419 long nonUniqueCount=0;
420 double totalSum=0;
421 double minSum=0;
422 double expectedMinSum=0;
423 double maxPossibleMinSum=0;
424
425 //Here we walk down the Sketches and find where they share kmers.
426 //In those cases, the counts are compared to determine balance.
427 for(int i=0, j=0; i<a.length && j<b.length; ){
428 final long ka=a[i], kb=b[j];
429 if(ka==kb){//Match
430 final int ca=aCounts[i];
431 final int cb=bCounts[j];
432 if(ca>1) {
433 matches++;
434 final int cmin=Tools.min(cb, ca-cb);
435 assert(cmin>=0) : ca+", "+cb;
436 nonUniqueCount+=(ca>1 ? 1 : 0);
437 double expectedMinor=expectedMinorAlleleCount(ca);
438 assert(expectedMinor>0);
439 double ratio=cmin/(double)ca;
440 totalSum+=ca;
441 totalCount++;
442 sharedSum+=ca;
443 minSum+=ratio;
444 maxPossibleMinSum+=((ca/2)/(double)ca);
445 expectedMinSum+=(expectedMinor/ca);
446 }
447 i++;
448 j++;
449 }else if(ka<kb){//kb was missing; thus it had a minor count of 0
450 final int ca=aCounts[i];//TODO
451 final int cb=0;
452 if(ca>1) {
453 final int cmin=Tools.min(cb, ca-cb);//Should always be cb
454 assert(cmin>=0);//Should always be 0
455 nonUniqueCount+=(ca>1 ? 1 : 0);
456 double expectedMinor=expectedMinorAlleleCount(ca);
457 double ratio=cmin/(double)ca;
458 totalSum+=ca;
459 totalCount++;
460 sharedSum+=ca;
461 minSum+=ratio;
462 maxPossibleMinSum+=((ca/2)/(double)ca);
463 expectedMinSum+=(expectedMinor/ca);
464 }
465 i++;
466 }else{//ka was missing; thus this is a noncanonical key
467 j++;
468 }
469 }
470
471 //Strandedness will be (0.5-1.0) for normal (fully unstranded-fully stranded) libraries.
472 //Synthetic or binned libraries with a perfectly flat distribution will get 0.0,
473 //but anything between 0.0 and 0.5 would be unusual.
474 //Basically 1.0 is preference for a strand, 0.5 is no preference for a strand,
475 //and 0.0 is preference for perfect balance between strands - as you would get
476 //if you treated paired reads as single-ended.
477 double strandedness;
478 if(minSum<=expectedMinSum) {//Normal case; strandedness between 0 and 50%
479 // strandedness=1-(minSum/(expectedMinSum+minSum));//Not sure about the proper formula; needs thought
480 strandedness=0.5+(1-(minSum/expectedMinSum))*0.5;
481 }else{//Odd case; distribution is more even than expected by chance
482 assert(minSum<=maxPossibleMinSum) : minSum+", "+maxPossibleMinSum;
483 double range=(maxPossibleMinSum-expectedMinSum);
484 double delta=minSum-expectedMinSum;
485 assert(delta>=0 && delta<=range);
486 double x=0.5*(1-(delta/range));
487 strandedness=x;//Not really sure about this either
488 }
489 double depth=totalSum/totalCount;
490 double nonUniqueFraction=nonUniqueCount/(1.0*totalCount);
491 return new double[] {totalSum, minSum, expectedMinSum, maxPossibleMinSum,
492 strandedness, depth, matches, nonUniqueFraction};
493 }
494
495 static float strandedness(long plus, long minus) {
496 long sum=plus+minus;
497 long maxPossibleMinor=sum/2;
498 float expectedMinor=(float)expectedMinorAlleleCount(sum);
499 assert(expectedMinor>0);
500
501 return strandedness(plus, minus, maxPossibleMinor, expectedMinor);
502 }
503
504 static float strandedness(long plus, long minus, long maxPossibleMinor, float expectedMinor) {
505 long sum=plus+minus;
506 long min=Math.min(plus, minus);
507 assert(expectedMinor>0);
508
509 if(min<=expectedMinor) {//Expected case
510 float strandedness=1-0.5f*(min/expectedMinor);//0.5-1
511 assert(strandedness>=0 && strandedness<=1.01) : strandedness+
512 ", "+plus+", "+minus+", "+sum+", "+min+", "+expectedMinor;
513 return strandedness;
514 }else{//Rare case; overly unstranded
515 float range=maxPossibleMinor-expectedMinor;
516 float dif=min-expectedMinor;
517 float strandedness=0.5f*(1-(dif/range));
518 assert(strandedness>=0 && strandedness<=1.01) : strandedness+", "+plus+", "+minus+
519 ", "+sum+", "+min+", "+expectedMinor+", "+range+", "+dif;
520 return strandedness;
521 }
522 }
523
524 /**
525 * Counts the fraction of total kmers shared between sketches, which includes their counts.
526 * @param saFwd Forward sketch of reads.
527 * @param sbTranscriptStrand Forward (or reverse) sketch of transcriptome.
528 * @return Results vector: {totalSum, depth, matches, sharedSum}
529 */
530 static double[] countSharedSum(Sketch saFwd, Sketch sbTranscriptStrand) {
531 final long[] a=saFwd.keys, b=sbTranscriptStrand.keys;
532 final int[] aCounts=saFwd.keyCounts, bCounts=sbTranscriptStrand.keyCounts;
533
534 int matches=0;
535 int totalCount=0;
536 long sharedSum=0;
537 double totalSum=0;
538
539 for(int i=0, j=0; i<a.length && j<b.length; ){
540 final long ka=a[i], kb=b[j];
541 if(ka==kb){//Match
542 matches++;
543 final int ca=aCounts[i];
544 totalSum+=ca;
545 totalCount++;
546 sharedSum+=ca;
547 i++;
548 j++;
549 }else if(ka<kb){//kb was missing
550 final int ca=aCounts[i];
551 totalSum+=ca;
552 totalCount++;
553 i++;
554 }else{//ka was missing
555 j++;
556 }
557 }
558
559 double depth=sharedSum/(double)Tools.max(matches, 1);
560 return new double[] {totalSum, depth, matches, sharedSum};
561 }
562
563 /**
564 * Calculate each sketch's fractional coverage of the other sketch, ignoring counts.
565 * @return Results vector: {aFraction, bFraction},
566 * where aFraction is sketch a's coverage of sketch b.
567 */
568 static double[] calcCoverage(Sketch sa, Sketch sb) {
569 final long[] a=sa.keys, b=sb.keys;
570 final int[] aCounts=sa.keyCounts, bCounts=sb.keyCounts;
571
572 int matches=0;
573
574 int i=0, j=0;
575 for(; i<a.length && j<b.length; ){
576 final long ka=a[i], kb=b[j];
577 if(ka==kb){//Match
578 matches++;
579 i++;
580 j++;
581 }else if(ka<kb){//kb was missing
582 i++;
583 }else{//ka was missing
584 j++;
585 }
586 }
587
588 double aFraction=matches/(double)j;
589 double bFraction=matches/(double)i;
590
591 return new double[] {aFraction, bFraction};
592 }
593
594 /*--------------------------------------------------------------*/
595
596 /**
597 * This works for a diploid het allele, or a fair coin, or other things with 50/50 outcomes.
598 * Returns the expected minor allele frequency for a given depth.
599 * @param depth i.e., number of observations.
600 * @return Expected number of observations of the minor allele.
601 */
602 public static final double expectedMinorAlleleFrequency(final long depth) {
603 if(depth<expectedMinorAlleleFreq.length) {return depth>1 ? expectedMinorAlleleFreq[(int)depth] : 0;}
604 long d=depth;
605 double mult=1.0;
606
607 //If the depth is greater than array length, downscale it.
608 //This could alternatively use power-of-two multipliers
609 //like 2 and 4, or 8 and 64, where one is the square of the other.
610 //Or probably some formula using logs.
611 //TODO: Consider switching to a log-based formula instead of a loop
612 while(d>=expectedMinorAlleleFreq.length) {
613 d=d/100;
614 mult*=0.1;
615 }
616 double maf=expectedMinorAlleleFreq[(int)d];
617 double dif=0.5-maf;
618 return 0.5-(dif*mult);
619 }
620
621 public static final double expectedMinorAlleleCount(final long depth) {
622 if(depth<expectedMinorAlleleCount.length) {return depth>1 ? expectedMinorAlleleCount[(int)depth] : 0;}
623 return depth*expectedMinorAlleleFrequency(depth);
624 }
625
626 /** This is for generating the stats file for loading later; only needed once. */
627 private static void printMinorAlleleCount() {
628 System.out.println("#Expected minor allele count for N coin flips, starting at 0, 10m simulations.");
629 for(int i=0; i<expectedMinorAlleleCount.length; i++) {
630 double c=expectedMinorAlleleCount[i];
631 int decimals=Tools.max(1, 7-Integer.toString((int)c).length());
632 System.out.println(String.format("%."+decimals+"f", expectedMinorAlleleCount[i]));
633 }
634 }
635
636 /**
637 * Runs a simulation. This will happen automatically if minorAlleleCount.txt is not found,
638 * but it will be less precise due to fewer trials. The total number of coin flips
639 * is maxDepth*trials.
640 * @param maxDepth Max total allele count (coin flips in a series).
641 * @param trials Number of simulated series.
642 * @return Array of average minor allele counts.
643 */
644 public static final double[] makeExpectedMinorAlleleArray(final int maxDepth, final int trials) {
645 {
646 double[] d=loadExpectedMinorAlleleArray();
647 if(d!=null) {return d;}
648 }
649 final long[] minorSum=new long[maxDepth+1];
650 final Random randy=Shared.threadLocalRandom();
651 final int[] headsTails=new int[2];
652 for(int trial=0; trial<trials; trial++) {
653 headsTails[0]=headsTails[1]=0;
654 for(int i=1; i<maxDepth+1; i++) {
655 int bit=randy.nextInt()&1;
656 headsTails[bit]++;
657 minorSum[i]+=Tools.min(headsTails[0], headsTails[1]);
658 }
659 }
660 final double[] expected=new double[maxDepth+1];
661 final double mult=1.0/trials;
662 for(int i=0; i<maxDepth+1; i++) {
663 expected[i]=minorSum[i]*mult;
664 }
665 return expected;
666 }
667
668 /**
669 * Load minor allele counts from a file.
670 * It should be in bbmap/resources/minorAlleleCount.txt
671 * */
672 public static double[] loadExpectedMinorAlleleArray() {
673 String path=Data.findPath("?minorAlleleCount.txt", true);
674 if(path==null) {return null;}
675 File f=new File(path);
676 if(!f.exists() || !f.canRead()) {return null;}
677
678 DoubleList dl=new DoubleList();
679 String[] lines=TextFile.toStringLines(path);
680 for(String s : lines) {
681 if(!Tools.startsWith(s, '#')) {
682 double d=Parse.parseDouble(s, 0, s.length());
683 dl.add(d);
684 }
685 }
686 return dl.toArray();
687 }
688
689 /** Make the frequency array from the count array */
690 private static double[] makeExpectedMinorAlleleFreq(double[] counts) {
691 double[] freq=new double[counts.length];
692 for(int i=1; i<counts.length; i++) {
693 freq[i]=counts[i]/i;
694 }
695 return freq;
696 }
697
698 /*--------------------------------------------------------------*/
699
700 /**
701 * Load a gff file.
702 * @param gff The file path.
703 * @param types Types of features to load, such as "CDS,rRNA".
704 * @return
705 */
706 static ArrayList<GffLine> getGffLines(String gff, String types){
707 return GffLine.loadGffFile(gff, types, false);
708 }
709
710 /**
711 * Load a fasta file as a HashMap of names to sequences.
712 * @param fna Fasta file.
713 * @return Map of names to sequences.
714 */
715 static HashMap<String, Read> getSequenceMap(String fna){
716 ArrayList<Read> list=ReadInputStream.toReads(fna, FileFormat.FA, -1);
717 return getSequenceMap(list);
718 }
719
720 /**
721 * Generate a map of names to sequences from a list of sequences.
722 * Also maps name prefix up to the first whitespace.
723 * @param list List of sequences.
724 * @return The map.
725 */
726 static HashMap<String, Read> getSequenceMap(ArrayList<Read> list){
727 HashMap<String, Read> map=new HashMap<String, Read>(1+list.size()*3);
728
729 for(Read r : list){
730 map.put(r.id, r);
731 //Faster to use a lineparser but they don't support whitespaceplus
732 String id2=Tools.whitespacePlus.split(r.id)[0];
733 if(!id2.equals(r.id)) {map.put(id2, r);}
734 }
735 return map;
736 }
737
738 /**
739 * Generates a list of sequences by cutting out the specified regions.
740 * Intended for generating gene sequences given a list of GffLines.
741 * @param <K> A Feature such as a GffLine.
742 * @param lines List of features.
743 * @param map Map of name to sequence (for the reference genome).
744 * @return A list of sequences of the input features, named by the features.
745 */
746 static <K extends Feature> ArrayList<Read> grabGenes(ArrayList<? extends K> lines, HashMap<String, Read> map){
747 ArrayList<Read> list=null;
748
749 // HashSet<String> set=new HashSet<String>();
750 // for(String s : types) {set.add(s);}
751
752 for(K gline : lines){
753 // if(set.contains(gline.type)){
754 Read scaf=map.get(gline.seqid());
755 assert(scaf!=null) : "Can't find "+gline.seqid()+" in "+map.keySet();
756
757 final int start=gline.start();
758 final int stop=gline.stop();
759
760
761 if(start>=0 && stop<scaf.length()){
762 String id=gline.name();
763 Read r=new Read(Arrays.copyOfRange(scaf.bases, start, stop+1), null, id, 1);
764
765 // assert(!r.containsLowercase()) : r.toFasta()+"\n"
766 // + "validated="+r.validated()+", scaf.validated="+scaf.validated()+", tuc="+Read.TO_UPPER_CASE+", vic="+Read.VALIDATE_IN_CONSTRUCTOR;
767 if(r!=null){
768 if(gline.strand()==1){r.reverseComplement();}
769 if(list==null){list=new ArrayList<Read>(8);}
770 list.add(r);
771 }
772 // }
773
774 }
775 }
776 return list;
777 }
778
779 /**
780 * Call genes from a reference file and return the gene sequences.
781 * @param fna Fasta reference.
782 * @return Gene sequences.
783 */
784 private ArrayList<Read> callGenes(String fna){
785 final ConcurrentReadInputStream cris=makeFastaCris(fna);
786
787 if(pgmFile==null){
788 pgmFile=Data.findPath("?model.pgm");
789 }
790 GeneModel pgm=GeneModelParser.loadModel(pgmFile);
791 GeneCaller gCaller=CallGenes.makeGeneCaller(pgm);
792 ArrayList<Read> genes=callGenes(cris, gCaller);
793
794 //Close the input stream
795 errorState|=ReadWrite.closeStream(cris);
796 return genes;
797 }
798
799 /**
800 * Makes a read input stream for a file (assumed to be fasta).
801 * @param fname File path.
802 * @return The read input stream.
803 */
804 private ConcurrentReadInputStream makeFastaCris(String fname){
805 FileFormat ffin=FileFormat.testInput(fname, FileFormat.FA, null, true, true);
806 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, false, ffin, null);
807 cris.start(); //Start the stream
808 if(verbose){outstream.println("Started cris");}
809 return cris;
810 }
811
812 /**
813 * Call genes from a read stream and return the gene sequences.
814 * @param cris Read stream.
815 * @param gCaller The gene caller.
816 * @return Gene sequences.
817 */
818 static ArrayList<Read> callGenes(ConcurrentReadInputStream cris, GeneCaller gCaller){
819 ArrayList<Read> genes=new ArrayList<Read>();
820
821 //Grab the first ListNum of reads
822 ListNum<Read> ln=cris.nextList();
823
824 CallGenes.callCDS=true;
825 CallGenes.calltRNA=CallGenes.call16S=CallGenes.call23S
826 =CallGenes.call5S=CallGenes.call18S=true;
827
828 //As long as there is a nonempty read list...
829 while(ln!=null && ln.size()>0){
830
831 for(Read r : ln) {
832 ArrayList<Orf> orfs=gCaller.callGenes(r);
833 if(orfs!=null) {
834 for(Orf orf : orfs) {
835 Read gene=CallGenes.fetch(orf, r);
836 genes.add(gene);
837 }
838 }
839 // System.err.println(r.length()+", "+orfs.size()+", "+orfs);
840 }
841 //Fetch a new list
842 ln=cris.nextList();
843 }
844
845 //Notify the input stream that the final list was used
846 if(ln!=null){
847 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
848 }
849 return genes;
850 }
851
852 /*--------------------------------------------------------------*/
853
854 private int sketchSize=20000;
855
856 private String in1=null;
857 private String out1="stdout.txt";
858 String fna=null;
859 String gff=null;
860 String pgmFile=null;
861
862 private final FileFormat ffin1;
863 private final FileFormat ffout1;
864
865 /** Features to pull from gff files */
866 private String types="CDS,rRNA,tRNA,ncRNA,exon,5S,16S,23S";
867
868 /*--------------------------------------------------------------*/
869
870 private boolean normalize=false;
871 private long maxReads=-1;
872 private float samplerate=1;
873 private long sampleseed=17;
874 private boolean errorState=false;
875
876 /*--------------------------------------------------------------*/
877
878 static final double[] expectedMinorAlleleCount=
879 makeExpectedMinorAlleleArray(10000, 100000);
880 static final double[] expectedMinorAlleleFreq=
881 makeExpectedMinorAlleleFreq(expectedMinorAlleleCount);
882
883 /*--------------------------------------------------------------*/
884
885 /** Output screen messages here */
886 private java.io.PrintStream outstream=System.err;
887 public static boolean verbose=false;
888
889 }