Debian Codegraph @

current/repeat/RepeatFinder.java

raw symbols SCIP
1 package repeat;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5 import java.util.Collections;
6 import java.util.concurrent.locks.ReadWriteLock;
7 import java.util.concurrent.locks.ReentrantReadWriteLock;
8
9 import dna.AminoAcid;
10 import fileIO.ByteFile;
11 import fileIO.ByteStreamWriter;
12 import fileIO.FileFormat;
13 import fileIO.ReadWrite;
14 import kmer.AbstractKmerTableSet;
15 import kmer.KmerTableSet;
16 import shared.Parse;
17 import shared.Parser;
18 import shared.PreParser;
19 import shared.Shared;
20 import shared.Timer;
21 import shared.Tools;
22 import stream.ConcurrentReadInputStream;
23 import stream.ConcurrentReadOutputStream;
24 import stream.FASTQ;
25 import stream.FastaReadInputStream;
26 import stream.Read;
27 import structures.ByteBuilder;
28 import structures.CRange;
29 import structures.ListNum;
30 import template.Accumulator;
31 import template.ThreadWaiter;
32 import tracker.EntropyTracker;
33 import tracker.ReadStats;
34
35 /**
36 * This class finds probable repeats using kmer-matching,
37 * and prints them out ordered by depth, then length.
38 *
39 * The repeats are only "probable" because no alignment is done;
40 * a sequence is considered a probable repeat of depth D if
41 * if all kmers within it have a depth of at least D.
42 *
43 * @author Brian Bushnell
44 * @date June 15, 2023
45 *
46 */
47 public class RepeatFinder implements Accumulator<RepeatFinder.ProcessThread> {
48
49 /*--------------------------------------------------------------*/
50 /*---------------- Initialization ----------------*/
51 /*--------------------------------------------------------------*/
52
53 /**
54 * Code entrance from the command line.
55 * @param args Command line arguments
56 */
57 public static void main(String[] args){
58 //Start a timer immediately upon code entrance.
59 Timer t=new Timer();
60
61 //Create an instance of this class
62 RepeatFinder x=new RepeatFinder(args);
63
64 //Run the object
65 x.process(t);
66
67 //Close the print stream if it was redirected
68 Shared.closeStream(x.outstream);
69 }
70
71 /**
72 * Constructor.
73 * @param args Command line arguments
74 */
75 public RepeatFinder(String[] args){
76
77 {//Preparse block for help, config files, and outstream
78 PreParser pp=new PreParser(args, getClass(), false);
79 args=pp.args;
80 outstream=pp.outstream;
81 }
82
83 //Set shared static variables prior to parsing
84 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
85 ReadWrite.setZipThreads(Shared.threads());
86 FASTQ.TEST_INTERLEAVED=FASTQ.FORCE_INTERLEAVED=false;
87
88 {//Parse the arguments
89 final Parser parser=parse(args);
90 Parser.processQuality();
91
92 maxReads=parser.maxReads;
93 overwrite=ReadStats.overwrite=parser.overwrite;
94 append=ReadStats.append=parser.append;
95
96 in1=parser.in1;
97 extin=parser.extin;
98
99 outr=parser.out1;
100 extout=parser.extout;
101
102 k=parser.k;
103 assert(k>=1 && k<=32) : "1<=k<=31: k="+k;
104 amino=Shared.AMINO_IN;
105 }
106
107 validateParams();
108 fixExtensions(); //Add or remove .gz or .bz2 as needed
109 checkFileExistence(); //Ensure files can be read and written
110 checkStatics(); //Adjust file-related static fields as needed for this program
111
112 //Create output FileFormat objects
113 ffoutr=FileFormat.testOutput(outr, FileFormat.TXT, null, true, overwrite, append, false);
114 ffouts=FileFormat.testOutput(outs, FileFormat.FA, extout, true, overwrite, append, ordered);
115
116 //Create input FileFormat objects
117 ffin1=FileFormat.testInput(in1, FileFormat.FASTA, extin, true, true);
118
119 tables=(processDepth ? new KmerTableSet(args, 12) : null);
120
121 {//set some constants
122 bitsPerBase=(amino ? 5 : 2);
123 maxSymbol=(amino ? 20 : 3);
124 symbols=maxSymbol+1;
125 symbolArrayLen=(64+bitsPerBase-1)/bitsPerBase;
126 symbolSpace=(1<<bitsPerBase);
127 symbolMask=symbolSpace-1;
128
129 symbolToNumber=AminoAcid.symbolToNumber(amino);
130 symbolToNumber0=AminoAcid.symbolToNumber0(amino);
131 symbolToComplementNumber0=AminoAcid.symbolToComplementNumber0(amino);
132
133 clearMasks=new long[symbolArrayLen];
134 leftMasks=new long[symbolArrayLen];
135 rightMasks=new long[symbolArrayLen];
136 setMasks=new long[symbols][symbolArrayLen];
137 for(int i=0; i<symbolArrayLen; i++){
138 clearMasks[i]=~(symbolMask<<(bitsPerBase*i));
139 leftMasks[i]=((-1L)<<(bitsPerBase*i));
140 rightMasks[i]=~((-1L)<<(bitsPerBase*i));
141 for(long j=0; j<symbols; j++){
142 setMasks[(int)j][i]=(j<<(bitsPerBase*i));
143 }
144 }
145
146 // minlen=k-1;
147 shift=bitsPerBase*k;
148 shift2=shift-bitsPerBase;
149 mask=(shift>63 ? -1L : ~((-1L)<<shift));
150 }
151 middleMask=(((k|1)==1) ? ~(3<<(k/2)) : ~(15<<(k/2-1)));//Works for even kmer lengths.
152
153 baseMaskArray=new byte[127];
154 for(int i=0; i<baseMaskArray.length; i++) {
155 final byte b;
156 if(!maskRepeats) {b=(byte)i;}
157 else if(softMask) {b=Tools.toLowerCase((byte)i);
158 }else{b=maskSymbol;}
159 baseMaskArray[i]=b;
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.out1=outr;
175
176 //Parse each argument
177 for(int i=0; i<args.length; i++){
178 String arg=args[i];
179
180 //Break arguments into their constituent parts, in the form of "a=b"
181 String[] split=arg.split("=");
182 String a=split[0].toLowerCase();
183 String b=split.length>1 ? split[1] : null;
184 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
185
186 if(a.equals("verbose")){
187 verbose=Parse.parseBoolean(b);
188 }else if(a.equals("ordered")){
189 ordered=Parse.parseBoolean(b);
190 }else if(a.equals("displayprogress")){
191 DISPLAY_PROGRESS=Parse.parseBoolean(b);
192 }else if(a.equals("qhdist") || a.equals("hdist")){
193 qHammingDist=Integer.parseInt(b);
194 }else if(a.equals("maskmiddle") || a.equals("mm")){
195 maskMiddle=AbstractKmerTableSet.MASK_MIDDLE=Parse.parseBoolean(b);
196 }else if(a.equals("minrepeat") || a.equals("minlen") || a.equals("minlength")){
197 minRepeat=Integer.parseInt(b);
198 }else if(a.equals("maxgap") || a.equals("gap")){
199 maxGap=Integer.parseInt(b);
200 }else if(a.equals("maxdepth") || a.equals("maxcount")){
201 maxDepth=Integer.parseInt(b);
202 if(maxDepth<1) {maxDepth=Shared.MAX_ARRAY_LEN;}
203 }else if(a.equals("mindepth") || a.equals("mincount")){
204 minDepth=Tools.max(2, Integer.parseInt(b));
205 }else if(a.equals("printlen") || a.equals("seqlen") || a.equals("println") ||
206 a.equals("preview") || a.equals("printsequence") || a.equals("printseq")){
207 if(b==null || Character.isLetter(b.charAt(0))){
208 if(Parse.parseBoolean(b)) {
209 Repeat.SEQ_AFFIX_LEN=12;
210 }else{
211 Repeat.SEQ_AFFIX_LEN=0;
212 }
213 }else{
214 int x=Integer.parseInt(b);
215 Repeat.SEQ_AFFIX_LEN=(x-3)/2;
216 }
217 }else if(a.equals("depth") || a.equals("processdepth")){
218 processDepth=Parse.parseBoolean(b);
219 }
220
221 else if(a.equals("mask") || a.equals("maskrepeats")){
222 if("lc".equalsIgnoreCase(b) || "lowercase".equalsIgnoreCase(b) ||
223 "soft".equalsIgnoreCase(b)) {
224 maskRepeats=true;
225 softMask=true;
226 }else if("hard".equalsIgnoreCase(b)) {
227 maskRepeats=true;
228 softMask=false;
229 }else if("t".equalsIgnoreCase(b) || "f".equalsIgnoreCase(b) || b==null || b.length()>1) {
230 maskRepeats=Parse.parseBoolean(b);
231 }else{
232 maskRepeats=true;
233 softMask=false;
234 maskSymbol=(byte)b.charAt(0);
235 }
236 }else if(a.equals("softmask") || a.equals("soft")){
237 softMask=Parse.parseBoolean(b);
238 if(softMask) {maskRepeats=true;}
239 }else if(a.equals("hardmask") || a.equals("hard")){
240 softMask=!Parse.parseBoolean(b);
241 if(!softMask) {maskRepeats=true;}
242 }else if(a.equals("symbol") || a.equals("masksymbol")){
243 softMask=false;
244 maskSymbol=(byte)b.charAt(0);
245 }else if(a.equals("weak") || a.equals("weaksubsume") || a.equals("weaksubsumes") || a.equals("ignoregaps")){
246 weakSubsumes=Parse.parseBoolean(b);
247 }
248
249 else if(a.equals("maskentropy") || a.equals("entropy") || a.equals("minentropy")){
250 if(b==null){
251 processEntropy=true;
252 }else if(Tools.startsWithLetter(b)){
253 processEntropy=Parse.parseBoolean(b);
254 }else{
255 entropyMaskRatio=Float.parseFloat(b);
256 processEntropy=entropyMaskRatio>=0;
257 }
258 }else if(a.equals("maskentropywindow") || a.equals("entropymaskwindow") || a.equals("ew")){
259 entropyWindow=Integer.parseInt(b);
260 }else if(a.equals("entropyk") || a.equals("entropymaskk") || a.equals("maskentropyk") || a.equals("ek") || a.equals("ke")){
261 entropyK=Integer.parseInt(b);
262 }
263
264 else if(a.equals("shorttandem") || a.equals("tandem") || a.equals("str")){
265 processShortTandem=Parse.parseBoolean(b);
266 }else if(a.equals("shorttandemmink") || a.equals("strmink") || a.equals("stmink")){
267 shortTandemMinK=Integer.parseInt(b);
268 }else if(a.equals("shorttandemmaxk") || a.equals("strmaxk") || a.equals("stmaxk")){
269 shortTandemMaxK=Integer.parseInt(b);
270 }else if(a.equals("shorttandemmincount") || a.equals("strmincount") || a.equals("stmincount")){
271 shortTandemMincount=Integer.parseInt(b);
272 }else if(a.equals("shorttandemminlen") || a.equals("strminlen") || a.equals("stminlen")){
273 shortTandemMinlen=Integer.parseInt(b);
274 }
275
276 else if(a.equals("printrepeats") || a.equals("pr") || a.equals("print")){
277 printRepeats=Parse.parseBoolean(b);
278 maskRepeats=!printRepeats;
279 }
280
281 else if(a.equals("outs") || a.equals("outm") || a.equals("outmasked")){
282 outs=b;
283 }else if(a.equals("parse_flag_goes_here")){
284 long fake_variable=Parse.parseKMG(b);
285 //Set a variable here
286 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
287 //do nothing
288 }else if(parser.parseK(arg, a, b)){//Parse k
289 //do nothing
290 }else{
291 outstream.println("Unknown parameter "+args[i]);
292 assert(false) : "Unknown parameter "+args[i];
293 }
294 }
295
296 return parser;
297 }
298
299 /** Add or remove .gz or .bz2 as needed */
300 private void fixExtensions(){
301 in1=Tools.fixExtension(in1);
302 }
303
304 /** Ensure files can be read and written */
305 private void checkFileExistence(){
306 //Ensure output files can be written
307 if(!Tools.testOutputFiles(overwrite, append, false, outr, outs)){
308 outstream.println((outr==null)+", "+outr+", "+outs);
309 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+outr+"\n");
310 }
311
312 //Ensure input files can be read
313 if(!Tools.testInputFiles(false, true, in1)){
314 throw new RuntimeException("\nCan't read some input files.\n");
315 }
316
317 //Ensure that no file was specified multiple times
318 if(!Tools.testForDuplicateFiles(true, in1, outr, outs)){
319 throw new RuntimeException("\nSome file names were specified multiple times.\n");
320 }
321 }
322
323 /** Adjust file-related static fields as needed for this program */
324 private static void checkStatics(){
325 //Adjust the number of threads for input file reading
326 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
327 ByteFile.FORCE_MODE_BF2=true;
328 }
329
330 assert(FastaReadInputStream.settingsOK());
331 }
332
333 /** Ensure parameter ranges are within bounds and required parameters are set */
334 private boolean validateParams(){
335 // assert(minfoo>0 && minfoo<=maxfoo) : minfoo+", "+maxfoo;
336 // assert(false) : "TODO";
337 assert(k>=1 && k<=32) : k;
338 return true;
339 }
340
341 /*--------------------------------------------------------------*/
342 /*---------------- Outer Methods ----------------*/
343 /*--------------------------------------------------------------*/
344
345 /** Create read streams and process all data */
346 void process(Timer t){
347
348 //Turn off read validation in the input threads to increase speed
349 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
350 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
351
352 AbstractKmerTableSet.DISPLAY_STATS=false;
353
354 if(processDepth) {
355 /* Fill tables with kmers */
356 tables.process(t);
357
358 if(DISPLAY_PROGRESS){
359 outstream.println("After loading:");
360 Shared.printMemory();
361 outstream.println();
362 }
363 }
364
365 //Create a read input stream
366 final ConcurrentReadInputStream cris=makeCris();
367
368 //Optionally create a read output stream
369 final ConcurrentReadOutputStream ros=makeCros();
370
371 //Reset counters
372 readsProcessed=readsOut=0;
373 basesProcessed=basesOut=0;
374
375 //Process the reads in separate threads
376 spawnThreads(cris, ros);
377
378 if(verbose){outstream.println("Finished; closing streams.");}
379
380 //Write anything that was accumulated by ReadStats
381 errorState|=ReadStats.writeAll();
382 //Close the read streams
383 errorState|=ReadWrite.closeStreams(cris, ros);
384
385 //Reset read validation
386 Read.VALIDATE_IN_CONSTRUCTOR=vic;
387
388 //Show the stuff the person involved cares about
389 printRepeats(ffoutr, masterListOfRepeats);
390
391 //Report timing and results
392 t.stop();
393 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
394 outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, readsOut, basesOut, 8, false));
395 outstream.println(Tools.number("Repeat Bases: ", repeatBases, 8)+String.format(" \t%.2f%%", repeatBases*100.0/basesProcessed));
396 if(processDepth){
397 outstream.println(Tools.number(" High Depth: ", highDepthBases, 8)+String.format(" \t%.2f%%", highDepthBases*100.0/basesProcessed));
398 }
399 if(processEntropy){
400 outstream.println(Tools.number(" Low Entropy: ", lowEntropyBases, 8)+String.format(" \t%.2f%%", lowEntropyBases*100.0/basesProcessed));
401 }
402 if(processShortTandem){
403 outstream.println(Tools.number(" Short Tandem: ", shortTandemBases, 8)+String.format(" \t%.2f%%", shortTandemBases*100.0/basesProcessed));
404 }
405 if(maskRepeats && ros!=null) {
406 outstream.println(Tools.number("Bases Masked: ", basesMasked, 8)+String.format(" \t%.2f%%", basesMasked*100.0/basesProcessed));
407 }
408
409 //Throw an exception of there was an error in a thread
410 if(errorState){
411 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
412 }
413 }
414
415 void printRepeats(FileFormat ff, ArrayList<Repeat> list) {
416 Collections.sort(list);
417 Collections.reverse(list);
418 if(ff==null){return;}
419 ByteStreamWriter bsw=new ByteStreamWriter(ff);
420 bsw.start();
421 bsw.println(Repeat.tsvHeader());
422 ByteBuilder bb=new ByteBuilder();
423 for(Repeat r : list) {
424 r.appendTo(bb);
425 bsw.println(bb);
426 bb.clear();
427 }
428 bsw.poisonAndWait();
429 }
430
431 private ConcurrentReadInputStream makeCris(){
432 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, null);
433 cris.start(); //Start the stream
434 if(verbose){
435 outstream.println("Started cris");
436 boolean paired=cris.paired();
437 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
438 }
439 return cris;
440 }
441
442 private ConcurrentReadOutputStream makeCros(){
443 if(ffouts==null){return null;}
444
445 //Select output buffer size based on whether it needs to be ordered
446 final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
447
448 final ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(ffouts, null, buff, null, false);
449 ros.start(); //Start the stream
450 return ros;
451 }
452
453 /*--------------------------------------------------------------*/
454 /*---------------- Thread Management ----------------*/
455 /*--------------------------------------------------------------*/
456
457 /** Spawn process threads */
458 private void spawnThreads(final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros){
459
460 //Do anything necessary prior to processing
461
462 //Determine how many threads may be used
463 final int threads=Shared.threads();
464
465 //Fill a list with ProcessThreads
466 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
467 for(int i=0; i<threads; i++){
468 alpt.add(new ProcessThread(cris, ros, i));
469 }
470
471 //Start the threads and wait for them to finish
472 boolean success=ThreadWaiter.startAndWait(alpt, this);
473 errorState&=!success;
474
475 //Do anything necessary after processing
476
477 }
478
479 @Override
480 public final void accumulate(ProcessThread pt){
481 synchronized(pt) {
482 readsProcessed+=pt.readsProcessedT;
483 basesProcessed+=pt.basesProcessedT;
484 repeatBases+=pt.repeatBasesT;
485 basesMasked+=pt.basesMaskedT;
486 highDepthBases+=pt.highDepthBasesT;
487 lowEntropyBases+=pt.lowEntropyBasesT;
488 shortTandemBases+=pt.shortTandemBasesT;
489 readsOut+=pt.readsOutT;
490 basesOut+=pt.basesOutT;
491 errorState|=(!pt.success);
492 masterListOfRepeats.addAll(pt.repeatSet.oldRepeats);
493 }
494 }
495
496 @Override
497 public final boolean success(){return !errorState;}
498
499 /*--------------------------------------------------------------*/
500 /*---------------- Inner Methods ----------------*/
501 /*--------------------------------------------------------------*/
502
503 final long rcomp(long kmer, int len){
504 return amino ? kmer : AminoAcid.reverseComplementBinaryFast(kmer, len);
505 }
506
507 // final int maskRepeat(Repeat r) {
508 // return maskRepeat(r.contig.bases, r.start, r.stop);
509 // }
510
511 final int maskRange(CRange r) {
512 return maskRepeat(((Read)r.obj).bases, r.a, r.b);
513 }
514
515 final int maskRepeat(byte[] bases, int start, int stop) {
516 int masked=0;
517 for(int i=start; i<=stop; i++) {
518 byte b=bases[i];
519 byte b2=baseMaskArray[b];
520 bases[i]=b2;
521 masked+=(b2==b ? 0 : 1);
522 }
523 return masked;
524 }
525
526 /**
527 * Transforms a kmer into all canonical values for a given Hamming distance.
528 * Returns the maximal count stored in the tables.
529 * @param kmer Forward kmer
530 * @param rkmer Reverse kmer
531 * @param qHDist Hamming distance
532 * @return Value stored in table, or -1
533 */
534 private final int getValue(final long kmer, final long rkmer, final int qHDist){
535 if(verbose){outstream.println("getValue()");}
536 final int count=tables.getCount(kmer, rkmer);
537 int maxCount=count;
538 if(/*count<2 &&*/ qHDist>0){
539 final int qHDist2=qHDist-1;
540
541 //Sub
542 for(int j=0; j<symbols/* && count<2*/ && maxCount<maxDepth; j++){
543 for(int i=0; i<k /*&& id<1*/; i++){
544 final long temp=(kmer&clearMasks[i])|setMasks[j][i];
545 // outstream.println(i+", "+j+", "+setMasks[j][i]+", "+qHDist);
546 if(temp!=kmer){
547 long rtemp=rcomp(temp, k);
548 int keyCount=getValue(temp, rtemp, qHDist2);
549 maxCount=Tools.max(keyCount, maxCount);
550 }
551 }
552 }
553 }
554 return maxCount;
555 }
556
557 /*--------------------------------------------------------------*/
558 /*---------------- Inner Classes ----------------*/
559 /*--------------------------------------------------------------*/
560
561 /** This class is static to prevent accidental writing to shared variables.
562 * It is safe to remove the static modifier. */
563 class ProcessThread extends Thread {
564
565 //Constructor
566 ProcessThread(final ConcurrentReadInputStream cris_, final ConcurrentReadOutputStream ros_, final int tid_){
567 cris=cris_;
568 ros=ros_;
569 tid=tid_;
570
571 repeatSet=new RepeatSet(k, minDepth, maxDepth, minRepeat, maxGap, weakSubsumes, amino, entropyK, entropyWindow);
572 et=(processEntropy ? new EntropyTracker(entropyK, entropyWindow, amino, entropyMaskRatio, true) : null);
573 }
574
575 //Called by start()
576 @Override
577 public void run(){
578 //Do anything necessary prior to processing
579
580 synchronized(this) {
581 //Process the reads
582 processInner();
583
584 //Do anything necessary after processing
585
586 //Indicate successful exit status
587 success=true;
588 }
589 }
590
591 /** Iterate through the reads */
592 void processInner(){
593
594 //Grab the first ListNum of reads
595 ListNum<Read> ln=cris.nextList();
596
597 //As long as there is a nonempty read list...
598 while(ln!=null && ln.size()>0){
599 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
600
601 processList(ln);
602
603 //Notify the input stream that the list was used
604 cris.returnList(ln);
605 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
606
607 //Fetch a new list
608 ln=cris.nextList();
609 }
610
611 //Notify the input stream that the final list was used
612 if(ln!=null){
613 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
614 }
615 }
616
617 void processList(ListNum<Read> ln){
618
619 //Grab the actual read list from the ListNum
620 final ArrayList<Read> reads=ln.list;
621
622 // int maxDepthSeen=0;
623 assert(repeatSet.closedRepeats.isEmpty());
624
625 //Loop through each read in the list
626 for(int idx=0; idx<reads.size(); idx++){
627 final Read r=reads.get(idx);
628
629 //Validate reads in worker threads
630 if(!r.validated()){r.validate(true);}
631
632 //Track the initial length for statistics
633 final int initialLength1=r.length();
634 final int initialLength2=r.mateLength();
635
636 //Increment counters
637 readsProcessedT+=r.pairCount();
638 basesProcessedT+=initialLength1+initialLength2;
639
640 {//Reads are processed in this block.
641 if(processDepth) {
642 // int maxDepthThisRead=processReadDepth(r);
643 // maxDepthSeen=Tools.max(maxDepthSeen, maxDepthThisRead);
644 int x=processReadDepth(r);
645 highDepthBasesT+=x;
646 }
647 if(processEntropy){
648 int x=processReadEntropy(r);
649 lowEntropyBasesT+=x;
650 }
651 if(processShortTandem){
652 int x=processReadShortTandem(r, shortTandemMinK, shortTandemMaxK, shortTandemMincount, shortTandemMinlen);
653 shortTandemBasesT+=x;
654 }
655 repeatSet.recent.clear();
656 }
657 }
658
659 // repeatSet.collectResidual(maxDepthSeen);//Now performed per read
660
661 //This is occasionally needed due to lazy collection
662 repeatSet.subsumeClosed(weakSubsumes);
663
664 ArrayList<CRange> ranges=repeatSet.closedToRanges(true);
665
666 //Output reads to the output stream
667 if(ros!=null){
668 ArrayList<Read> seqList=reads;
669 if(maskRepeats) {
670 if(!softMask && Repeat.SEQ_AFFIX_LEN>0) {makePreview(repeatSet.closedRepeats);}
671 basesMaskedT+=maskRepeats(ranges);
672 }else if(printRepeats) {seqList=repeatSet.fetchRepeatSequence();}
673 ros.add(seqList, ln.id);
674 for(Read r : seqList) {
675 readsOutT+=r.pairCount();
676 basesOutT+=r.pairLength();
677 }
678 }
679 repeatBasesT+=countRepeatBases(ranges);
680
681 //Optionally clear sequence to save memory (but this interferes with printing repeat sequence)
682 // for(Repeat r : closedRepeats) {r.contig=null;}
683 repeatSet.retireClosed();
684 }
685
686 long maskRepeats(ArrayList<CRange> ranges) {
687 long x=0;
688 for(CRange r : ranges) {x+=maskRange(r);}
689 return x;
690 }
691
692 long countRepeatBases(ArrayList<CRange> ranges) {
693 long x=0;
694 for(CRange r : ranges) {x+=r.length();}
695 return x;
696 }
697
698 void makePreview(ArrayList<Repeat> list) {
699 assert(maskRepeats && !softMask);
700 if(list.isEmpty()){return;}
701 ByteBuilder bb=new ByteBuilder(Repeat.SEQ_AFFIX_LEN*2+3);
702 for(Repeat r : list) {r.setSeq(bb);}
703 }
704
705 //Deprecated and replaced by masking ranges
706 // void maskRepeats() {
707 // //Masking can be done on closedRepeats, but making a weakSubsumes list can save rework
708 // ArrayList<Repeat> list=closedRepeats;
709 // if(list.isEmpty()) {return;}
710 // if(!softMask) {
711 // //If hard masking, copies of the sequence need to be made first.
712 // //Skipping this will make the preview come out in lower case,
713 // //but it prevents memory crashes in the worst case.
714 // //Although it uses more memory in the expected case.
715 // ByteBuilder bb=new ByteBuilder(Repeat.SEQ_AFFIX_LEN*2+3);
716 // for(Repeat r : list) {r.setSeq(bb);}
717 // }
718 // if(list.size()>1 && !weakSubsumes) {
719 // list=(ArrayList<Repeat>) list.clone();
720 // subsume(list, true);
721 // }
722 // for(Repeat r : list) {
723 // maskRepeat(r);
724 // }
725 // }
726
727 /**
728 * Process a read.
729 * @param r1 Read 1
730 * @return max depth observed.
731 */
732 private int processReadDepth(final Read r){
733 if(r==null || r.length()<k) {return 0;}
734 final byte[] bases=r.bases;
735
736 long kmer=0;
737 long rkmer=0;
738 int len=0;
739
740 final int start=0;
741 final int stop=bases.length;
742 int max=0;
743
744 assert(repeatSet.recent.isEmpty());
745 repeatSet.recent.clear();
746
747 /* Loop through the bases, maintaining a forward and reverse kmer via bitshifts */
748 for(int i=start; i<stop; i++){
749 byte b=bases[i];
750 long x=symbolToNumber0[b];
751 long x2=symbolToComplementNumber0[b];
752 kmer=((kmer<<bitsPerBase)|x)&mask;
753 rkmer=((rkmer>>>bitsPerBase)|(x2<<shift2))&mask;
754 if(forbidNs && !isFullyDefined(b)){len=0; rkmer=0;}else{len++;}
755 //if(verbose){outstream.println("Scanning6b i="+i+", kmer="+kmer+", rkmer="+rkmer+", bases="+new String(bases, Tools.max(0, i-k2), Tools.min(i+1, k)));}
756 if(len>=k){
757 final int count=getValue(kmer, rkmer, qHammingDist);
758 if(verbose){outstream.println("Testing kmer "+kmer+"; count="+count);}
759 //assert(count>=1) : count;
760 if(count>=minDepth) {
761 repeatSet.increment(r, i, count);
762 max=Tools.max(max, count);
763 }
764 }
765 }
766
767 repeatSet.collectResidual(max);
768 ArrayList<CRange> recent=repeatSet.recentToRanges(true);
769 repeatSet.recent.clear();
770
771 int sum=0;
772 for(CRange range : recent) {
773 sum+=range.length();
774 }
775 return sum;
776 }
777
778 private int processReadEntropy(final Read rd){
779 final int window=et.windowBases();
780 if(rd==null || rd.length()<window){return 0;}
781 final byte[] bases=rd.bases;
782
783 et.clear();
784 Repeat current=new Repeat(null, -1, minDepth, window, Tools.max(0, maxGap-k)+window, minRepeat, 'E'); //TODO: Use a buffer.
785 int sum=0;
786 for(int i=0, min=window-1; i<bases.length; i++){
787 et.add(bases[i]);
788 if(i>=min && et.ns()<1 && !et.passes()){
789 int a=et.leftPos(), b=et.rightPos();
790 Repeat old=current.increment(rd, b, 2);
791 if(old!=null){
792 repeatSet.addRepeat(old);
793 sum+=old.length();
794 }
795 }
796 }
797 if(current.start>-1 && current.length()>=minRepeat){
798 assert(current.contig==rd);
799 repeatSet.addRepeat(current);
800 }
801 return sum;
802 }
803
804 private int processReadShortTandem(Read rd, int mink, int maxk, int mincount, int minlen){
805 final byte[] bases=rd.bases;
806 final ArrayList<CRange> ranges=new ArrayList<CRange>();//TODO: Make a buffer
807
808 for(int k=mink; k<=maxk; k++){
809 findShortTandem(bases, ranges, k, Tools.max(minlen, k*mincount), rd.numericID);
810 }
811 if(ranges.isEmpty()) {return 0;}
812 CRange.mergeList(ranges, maxk>mink);
813 int sum=0;
814 for(CRange range : ranges){
815 sum+=range.length();
816 //Some info is lost by waiting until here to convert to a Repeat
817 Repeat repeat=new Repeat(rd, range.a, minDepth, mink, maxGap, minRepeat, 'T');
818 repeat.stop=range.b;
819 repeat.maxDepth=minDepth;
820 repeatSet.addRepeat(repeat);
821 }
822 return sum;
823 }
824
825 // assert(currentDepth>=depth);//TODO: This can be disabled, but then the currentDepth<depth case needs to be handled; currently the function is not called inside gaps
826 // final int gap=pos-stop-1;
827 // if(contigNum==currentContig.numericID && gap<=maxGap) {//advance
828 //// System.err.println("A:"+this);
829 // stop=pos;
830 // gapLen+=gap;
831 // gapCount+=(gap>0 ? 1 : 0);
832 // gapBP+=(gap>=k ? gap-k+1 : 0);
833 // depthSum+=currentDepth;
834 // maxDepth=Tools.max(currentDepth, maxDepth);
835 // return null;
836 // }
837 //
838 // Repeat r=null;
839 // if(contigNum>=0 && length()>=minRepeat) {r=this.clone();}
840 //// System.err.println("B:"+r+", "+this);
841 // clear();
842 // contigNum=currentContig.numericID;
843 // start=pos-k+1;
844 // assert(start>=0) : start+", "+pos+", "+k;
845 // stop=pos;
846 // assert(stop<currentContig.bases.length) : stop+", "+currentContig.length();
847 // minDepth=maxDepth=depth;
848 //
849 // //These are not *strictly* needed and can use a lot of memory.
850 // //They could be cleared after calculating entropy and gc or removed entirely.
851 // contig=currentContig;
852 // contigName=currentContig.name();
853 //
854
855
856 private void findShortTandem(final byte[] bases, final ArrayList<CRange> ranges, final int k, final int minlen, final long rid){
857 final int lim=bases.length-k;
858 final int mask=(k>15 ? -1 : ~((-1)<<(2*k)));
859 CRange last=null;
860 for(int loc=0; loc<lim; loc++){
861 int len=shortTandemLength(bases, k, mask, loc);
862 if(len>=minlen){
863 int a=loc-k, b=loc-k+len-1;
864 if(last!=null && last.touches(a, b)) {
865 last.b=b;
866 }else{
867 CRange r=new CRange(rid, a, b);
868 ranges.add(r);
869 loc=Tools.max(loc, b-minlen);
870 last=r;
871 }
872 }else{
873 //System.err.println("len="+len+" < minlen="+minlen);
874 }
875 }
876 }
877
878 private int shortTandemLength(final byte[] bases, final int k, final int mask, final int loc){
879
880 final int lim=bases.length;
881 final int key=getInitialKey(bases, loc, k);
882 if(key<0){return 0;}
883 int kmer=key;
884 int gap=0, last=-1;
885 for(int i=loc; i<lim && gap<k; i++){
886 final byte b=bases[i];
887 final int n=symbolToNumber[b];
888
889 kmer=(((kmer<<2)&mask)|n);
890 if(kmer==key){
891 last=i;
892 gap=0;
893 }else if(kmer>=0){
894 gap++;
895 }else{
896 break;//Undefined symbol encountered
897 }
898 }
899
900 return (last<0 ? 0 : last-loc+k+1);
901 }
902
903 private int getInitialKey(byte[] bases, int loc, int k){
904 assert(k<16);
905 int start=loc-k;
906 int key=0;
907 if(start<0){return -1;}
908 for(int i=start; i<loc && key>=0; i++){
909 final byte b=bases[i];
910 final int n=symbolToNumber[b];
911 key=(key<<2)|n;
912 }
913 return key;
914 }
915
916 /** Number of reads processed by this thread */
917 protected long readsProcessedT=0;
918 /** Number of bases processed by this thread */
919 protected long basesProcessedT=0;
920
921 /** Number of reads retained by this thread */
922 protected long readsOutT=0;
923 /** Number of bases retained by this thread */
924 protected long basesOutT=0;
925
926 /** Number of repeat bases found by this thread */
927 protected long repeatBasesT=0;
928
929 /** Number of bases masked by this thread */
930 protected long basesMaskedT=0;
931
932 /** Number of high depth bases found by this thread */
933 protected long highDepthBasesT=0;
934
935 /** Number of low-entropy bases found by this thread */
936 protected long lowEntropyBasesT=0;
937
938 /** Number of short tandem repeat bases found by this thread */
939 protected long shortTandemBasesT=0;
940
941 /** True only if this thread has completed successfully */
942 boolean success=false;
943
944 /** Shared input stream */
945 private final ConcurrentReadInputStream cris;
946 /** Shared output stream */
947 private final ConcurrentReadOutputStream ros;
948 /** Thread ID */
949 final int tid;
950
951 final RepeatSet repeatSet;
952 final EntropyTracker et;
953 }
954
955 /*--------------------------------------------------------------*/
956 /*---------------- Fields ----------------*/
957 /*--------------------------------------------------------------*/
958
959 /** Primary input file path */
960 private String in1=null;
961
962 /** Primary output file path */
963 private String outr="stdout.txt";
964
965 /** Sequence output */
966 private String outs=null;
967
968 /** Override input file extension */
969 private String extin=null;
970 /** Override output file extension */
971 private String extout=null;
972
973 /*--------------------------------------------------------------*/
974
975 /** Number of reads processed */
976 protected long readsProcessed=0;
977 /** Number of bases processed */
978 protected long basesProcessed=0;
979
980 /** Number of reads retained */
981 protected long readsOut=0;
982 /** Number of bases retained */
983 protected long basesOut=0;
984
985 protected long repeatBases=0;
986 protected long basesMasked=0;
987
988 /** Number of high-depth bases found */
989 protected long highDepthBases=0;
990
991 /** Number of low-entropy bases found */
992 protected long lowEntropyBases=0;
993
994 /** Number of short tandem repeat bases */
995 protected long shortTandemBases=0;
996
997 /** Quit after processing this many input reads; -1 means no limit */
998 private long maxReads=-1;
999
1000 /** Display progress messages such as memory usage */
1001 public static boolean DISPLAY_PROGRESS=true;
1002
1003 boolean forbidNs=true;
1004
1005 boolean printRepeats;
1006 boolean maskRepeats=true;
1007 boolean softMask=true;
1008 byte maskSymbol='N';
1009 boolean weakSubsumes=false;
1010
1011 int minRepeat=0;
1012 int maxGap=0;
1013
1014 boolean processDepth=true;
1015 int maxDepth=Shared.MAX_ARRAY_LEN;
1016 int minDepth=2;
1017
1018 boolean processEntropy=false;
1019 int entropyWindow=80;
1020 int entropyK=5;
1021 float entropyMaskRatio=0.70f;
1022
1023 boolean processShortTandem=false;
1024 int shortTandemMinK=2;
1025 int shortTandemMaxK=15;
1026 int shortTandemMincount=4;
1027 int shortTandemMinlen=32;
1028
1029 /*--------------------------------------------------------------*/
1030 /*---------------- Final Fields ----------------*/
1031 /*--------------------------------------------------------------*/
1032
1033 /** Primary input file */
1034 private final FileFormat ffin1;
1035
1036 /** Primary output file */
1037 private final FileFormat ffoutr;
1038
1039 /** Sequence output file */
1040 private final FileFormat ffouts;
1041
1042 private final int k;
1043 private final KmerTableSet tables;
1044
1045 private final ArrayList<Repeat> masterListOfRepeats=new ArrayList<Repeat>();
1046
1047 private final byte[] baseMaskArray;
1048
1049 @Override
1050 public final ReadWriteLock rwlock() {return rwlock;}
1051 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
1052
1053 /*--------------------------------------------------------------*/
1054 /*----------- Symbol-Specific Constants ----------*/
1055 /*--------------------------------------------------------------*/
1056
1057 /** True for amino acid data, false for nucleotide data */
1058 final boolean amino;
1059 boolean maskMiddle=false;
1060 int qHammingDist=0;
1061
1062 // final int maxSupportedK;
1063 final int bitsPerBase;
1064 final int maxSymbol;
1065 final int symbols;
1066 final int symbolArrayLen;
1067 final int symbolSpace;
1068 final long symbolMask;
1069
1070 // final int minlen;
1071 final int shift;
1072 final int shift2;
1073 final long mask;
1074 final long middleMask;
1075
1076 /** x&clearMasks[i] will clear base i */
1077 final long[] clearMasks;
1078 /** x|setMasks[i][j] will set base i to j */
1079 final long[][] setMasks;
1080 /** x&leftMasks[i] will clear all bases to the right of i (exclusive) */
1081 final long[] leftMasks;
1082 /** x&rightMasks[i] will clear all bases to the left of i (inclusive) */
1083 final long[] rightMasks;
1084
1085 /** Symbol code; -1 for undefined */
1086 final byte[] symbolToNumber;
1087 /** Symbol code; 0 for undefined */
1088 final byte[] symbolToNumber0;
1089 /** Complementary symbol code; 0 for undefined */
1090 final byte[] symbolToComplementNumber0;
1091
1092 /** For verbose / debugging output */
1093 final String kmerToString(long kmer, int k){
1094 return amino ? AminoAcid.kmerToStringAA(kmer, k) : AminoAcid.kmerToString(kmer, k);
1095 }
1096
1097 /** Returns true if the symbol is not degenerate (e.g., 'N') for the alphabet in use. */
1098 final boolean isFullyDefined(byte symbol){
1099 return symbol>=0 && symbolToNumber[symbol]>=0;
1100 }
1101
1102 /*--------------------------------------------------------------*/
1103 /*---------------- Common Fields ----------------*/
1104 /*--------------------------------------------------------------*/
1105
1106 /** Print status messages to this output stream */
1107 private PrintStream outstream=System.err;
1108 /** Print verbose messages */
1109 public static boolean verbose=false;
1110 /** True if an error was encountered */
1111 public boolean errorState=false;
1112 /** Overwrite existing output files */
1113 private boolean overwrite=true;
1114 /** Append to existing output files */
1115 private boolean append=false;
1116 /** Reads are output in input order */
1117 private boolean ordered=true;
1118
1119 }