Debian Codegraph @

current/ml/NetFilter.java

raw symbols SCIP
1 package ml;
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.concurrent.locks.ReadWriteLock;
8 import java.util.concurrent.locks.ReentrantReadWriteLock;
9
10 import dna.AminoAcid;
11 import fileIO.ByteFile;
12 import fileIO.FileFormat;
13 import fileIO.ReadWrite;
14 import shared.Parse;
15 import shared.Parser;
16 import shared.PreParser;
17 import shared.Shared;
18 import shared.Timer;
19 import shared.Tools;
20 import stream.ConcurrentReadInputStream;
21 import stream.ConcurrentReadOutputStream;
22 import stream.FASTQ;
23 import stream.FastaReadInputStream;
24 import stream.Read;
25 import structures.ListNum;
26 import structures.LongList;
27 import template.Accumulator;
28 import template.ThreadWaiter;
29 import tracker.ReadStats;
30
31 /**
32 * Filters sequences based on matching a neural network.
33 *
34 * @author Brian Bushnell
35 * @date November 1, 2023
36 *
37 */
38 public class NetFilter implements Accumulator<NetFilter.ProcessThread> {
39
40 /*--------------------------------------------------------------*/
41 /*---------------- Initialization ----------------*/
42 /*--------------------------------------------------------------*/
43
44 /**
45 * Code entrance from the command line.
46 * @param args Command line arguments
47 */
48 public static void main(String[] args){
49 //Start a timer immediately upon code entrance.
50 Timer t=new Timer();
51
52 //Create an instance of this class
53 NetFilter x=new NetFilter(args);
54
55 //Run the object
56 x.process(t);
57
58 //Close the print stream if it was redirected
59 Shared.closeStream(x.outstream);
60 }
61
62 /**
63 * Constructor.
64 * @param args Command line arguments
65 */
66 public NetFilter(String[] args){
67
68 {//Preparse block for help, config files, and outstream
69 PreParser pp=new PreParser(args, getClass(), false);
70 args=pp.args;
71 outstream=pp.outstream;
72 }
73
74 //Set shared static variables prior to parsing
75 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
76 ReadWrite.setZipThreads(Shared.threads());
77
78 {//Parse the arguments
79 final Parser parser=parse(args);
80 Parser.processQuality();
81
82 maxReads=parser.maxReads;
83 overwrite=ReadStats.overwrite=parser.overwrite;
84 append=ReadStats.append=parser.append;
85 setInterleaved=parser.setInterleaved;
86
87 in1=parser.in1;
88 in2=parser.in2;
89 qfin1=parser.qfin1;
90 qfin2=parser.qfin2;
91 extin=parser.extin;
92
93 out1=parser.out1;
94 out2=parser.out2;
95 qfout1=parser.qfout1;
96 qfout2=parser.qfout2;
97 extout=parser.extout;
98 }
99
100 validateParams();
101 doPoundReplacement(); //Replace # with 1 and 2
102 adjustInterleaving(); //Make sure interleaving agrees with number of input and output files
103 fixExtensions(); //Add or remove .gz or .bz2 as needed
104 checkFileExistence(); //Ensure files can be read and written
105 checkStatics(); //Adjust file-related static fields as needed for this program
106
107 //Create output FileFormat objects
108 ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, append, ordered);
109 ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, append, ordered);
110 ffoutu1=FileFormat.testOutput(outu1, FileFormat.FASTQ, extout, true, overwrite, append, ordered);
111 ffoutu2=FileFormat.testOutput(outu2, FileFormat.FASTQ, extout, true, overwrite, append, ordered);
112
113 //Create input FileFormat objects
114 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
115 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
116
117 ffnet=FileFormat.testOutput(netFile, FileFormat.BBNET, null, true, true, false, false);
118 net0=CellNetParser.load(netFile);
119 assert(net0!=null) : netFile;
120 if(width<0) {width=(net0.numInputs()-4)/4;}
121 else {assert(width==(net0.numInputs()-4)/4) : width+", "+net0.numInputs();}
122 if(autoCutoff) {cutoff=net0.cutoff;}
123 if(stepsize==Integer.MIN_VALUE) {stepsize=width-overlap;}
124 }
125
126 /*--------------------------------------------------------------*/
127 /*---------------- Initialization Helpers ----------------*/
128 /*--------------------------------------------------------------*/
129
130 /** Parse arguments from the command line */
131 private Parser parse(String[] args){
132
133 //Create a parser object
134 Parser parser=new Parser();
135
136 //Set any necessary Parser defaults here
137 //parser.foo=bar;
138
139 //Parse each argument
140 for(int i=0; i<args.length; i++){
141 String arg=args[i];
142
143 //Break arguments into their constituent parts, in the form of "a=b"
144 String[] split=arg.split("=");
145 String a=split[0].toLowerCase();
146 String b=split.length>1 ? split[1] : null;
147 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
148
149 if(a.equals("verbose")){
150 verbose=Parse.parseBoolean(b);
151 }else if(a.equals("ordered")){
152 ordered=Parse.parseBoolean(b);
153 }else if(a.equals("net")){
154 netFile=b;
155 }else if(a.equals("hist")){
156 histFile=b;
157 }else if(a.equals("width")){
158 width=Integer.parseInt(b);
159 }else if(a.equals("step") || a.equals("stepsize")){
160 stepsize=Integer.parseInt(b);
161 overlap=Integer.MIN_VALUE;
162 }else if(a.equals("overlap")){
163 overlap=Integer.parseInt(b);
164 stepsize=Integer.MIN_VALUE;
165 }else if(a.equals("rcomp")){
166 rcomp=Parse.parseBoolean(b);
167 }else if(a.equals("parse")){
168 parseHeader=Parse.parseBoolean(b);
169 }else if(a.equals("cutoff")){
170 if("auto".equalsIgnoreCase(b)) {
171 autoCutoff=true;
172 }else {
173 autoCutoff=false;
174 cutoff=Float.parseFloat(b);
175 }
176 filter=true;
177 }else if(a.equals("highpass")){
178 highpass=Parse.parseBoolean(b);
179 filter=true;
180 }else if(a.equals("lowpass")){
181 highpass=!Parse.parseBoolean(b);
182 filter=true;
183 }else if(a.equals("mode") || a.equals("scoremode")){
184 SCORE_MODE=parseMode(b);
185 }else if(a.equals("pairmode")){
186 PAIR_MODE=parseMode(b);
187 }else if(a.equals("filter")){
188 filter=Parse.parseBoolean(b);
189 }else if(a.equals("outu") || a.equals("outu1")){
190 outu1=b;
191 }else if(a.equals("outu2")){
192 outu2=b;
193 }else if(a.equals("annotate") || a.equals("rename")){
194 annotate=Parse.parseBoolean(b);
195 }else if(a.equals("k")){
196 k=Integer.parseInt(b);
197 }else if(a.equals("parse_flag_goes_here")){
198 long fake_variable=Parse.parseKMG(b);
199 //Set a variable here
200 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
201 //do nothing
202 }else{
203 outstream.println("Unknown parameter "+args[i]);
204 assert(false) : "Unknown parameter "+args[i];
205 }
206 }
207
208 return parser;
209 }
210
211 /** Replace # with 1 and 2 in headers */
212 private void doPoundReplacement(){
213 //Do input file # replacement
214 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
215 in2=in1.replace("#", "2");
216 in1=in1.replace("#", "1");
217 }
218
219 //Do output file # replacement
220 if(out1!=null && out2==null && out1.indexOf('#')>-1){
221 out2=out1.replace("#", "2");
222 out1=out1.replace("#", "1");
223 }
224
225 //Do output file # replacement
226 if(outu1!=null && outu2==null && outu1.indexOf('#')>-1){
227 outu2=out1.replace("#", "2");
228 outu1=out1.replace("#", "1");
229 }
230
231 //Ensure there is an input file
232 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
233
234 //Ensure out2 is not set without out1
235 if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
236 }
237
238 /** Add or remove .gz or .bz2 as needed */
239 private void fixExtensions(){
240 in1=Tools.fixExtension(in1);
241 in2=Tools.fixExtension(in2);
242 qfin1=Tools.fixExtension(qfin1);
243 qfin2=Tools.fixExtension(qfin2);
244 }
245
246 /** Ensure files can be read and written */
247 private void checkFileExistence(){
248 //Ensure output files can be written
249 if(!Tools.testOutputFiles(overwrite, append, false, out1, out2)){
250 outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2);
251 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+"\n");
252 }
253
254 //Ensure input files can be read
255 if(!Tools.testInputFiles(false, true, in1, in2)){
256 throw new RuntimeException("\nCan't read some input files.\n");
257 }
258
259 //Ensure that no file was specified multiple times
260 if(!Tools.testForDuplicateFiles(true, in1, in2, out1, out2)){
261 throw new RuntimeException("\nSome file names were specified multiple times.\n");
262 }
263 }
264
265 /** Make sure interleaving agrees with number of input and output files */
266 private void adjustInterleaving(){
267 //Adjust interleaved detection based on the number of input files
268 if(in2!=null){
269 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
270 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
271 }
272
273 //Adjust interleaved settings based on number of output files
274 if(!setInterleaved){
275 assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
276 if(in2!=null){ //If there are 2 input streams.
277 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
278 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
279 }else{ //There is one input stream.
280 if(out2!=null){
281 FASTQ.FORCE_INTERLEAVED=true;
282 FASTQ.TEST_INTERLEAVED=false;
283 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
284 }
285 }
286 }
287 }
288
289 /** Adjust file-related static fields as needed for this program */
290 private static void checkStatics(){
291 //Adjust the number of threads for input file reading
292 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
293 ByteFile.FORCE_MODE_BF2=true;
294 }
295
296 assert(FastaReadInputStream.settingsOK());
297 }
298
299 /** Ensure parameter ranges are within bounds and required parameters are set */
300 private boolean validateParams(){
301 assert(stepsize>0) : "stepsize must be greater than 0: s="+stepsize+", o="+overlap+", w="+width;
302 return true;
303 }
304
305 /*--------------------------------------------------------------*/
306 /*---------------- Outer Methods ----------------*/
307 /*--------------------------------------------------------------*/
308
309 /** Create read streams and process all data */
310 void process(Timer t){
311
312 //Turn off read validation in the input threads to increase speed
313 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
314 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
315
316 //Create a read input stream
317 final ConcurrentReadInputStream cris=makeCris();
318
319 //Optionally create a read output stream
320 final ConcurrentReadOutputStream ros=makeCros(cris.paired(), ffout1, ffout2, qfout1, qfout2);
321
322 //Unmatched read output stream
323 final ConcurrentReadOutputStream rosu=makeCros(cris.paired(), ffoutu1, ffoutu2, null, null);
324
325 //Reset counters
326 readsProcessed=readsOut=0;
327 basesProcessed=basesOut=0;
328
329 //Process the reads in separate threads
330 spawnThreads(cris, ros, rosu);
331
332 if(verbose){outstream.println("Finished; closing streams.");}
333
334 //Write anything that was accumulated by ReadStats
335 errorState|=ReadStats.writeAll();
336 //Close the read streams
337 errorState|=ReadWrite.closeStreams(cris, ros, rosu);
338
339 //Reset read validation
340 Read.VALIDATE_IN_CONSTRUCTOR=vic;
341
342 //Report timing and results
343 t.stop();
344 float mult=100f/readsProcessed;
345 outstream.println();
346 outstream.println(String.format("Average Score: \t%.4f", scoreSum/scoreCount));
347 if(parseHeader) {
348 outstream.println(String.format("Average Positive: \t%.4f\t\t%.4f%%", scoreSumPositive/scoreCountPositive, scoreCountPositive*mult));
349 outstream.println(String.format("Average Negative: \t%.4f\t\t%.4f%%", scoreSumNegative/scoreCountNegative, scoreCountNegative*mult));
350 }
351 if(filter || true) {
352 outstream.println(String.format("Average Pass: \t%.4f\t\t%.4f%%", scoreSumPass/scoreCountPass, scoreCountPass*mult));
353 outstream.println(String.format("Average Fail: \t%.4f\t\t%.4f%%", scoreSumFail/scoreCountFail, scoreCountFail*mult));
354 }
355 if(parseHeader) {
356 outstream.println(String.format("True Positive: \t%d\t\t%.4f%%", tpCount, tpCount*mult));
357 outstream.println(String.format("True Negative: \t%d\t\t%.4f%%", tnCount, tnCount*mult));
358 outstream.println(String.format("False Positive: \t%d\t\t%.4f%%", fpCount, fpCount*mult));
359 outstream.println(String.format("False Negative: \t%d\t\t%.4f%%", fnCount, fnCount*mult));
360 }
361 outstream.println();
362 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
363 outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, readsOut, basesOut, 8, false));
364
365 //Throw an exception of there was an error in a thread
366 if(errorState){
367 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
368 }
369 }
370
371 private ConcurrentReadInputStream makeCris(){
372 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, qfin1, qfin2);
373 cris.start(); //Start the stream
374 if(verbose){outstream.println("Started cris");}
375 boolean paired=cris.paired();
376 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
377 return cris;
378 }
379
380 private ConcurrentReadOutputStream makeCros(boolean pairedInput, FileFormat ff1, FileFormat ff2, String qf1, String qf2){
381 if(ff1==null){return null;}
382
383 //Select output buffer size based on whether it needs to be ordered
384 final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
385
386 // //Notify user of output mode
387 // if(pairedInput && out2==null && (in1!=null && !ffin1.samOrBam() && !ffout1.samOrBam())){
388 // outstream.println("Writing interleaved.");
389 // }
390
391 final ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(ff1, ff2, qf1, qf2, buff, null, false);
392 ros.start(); //Start the stream
393 return ros;
394 }
395
396 /*--------------------------------------------------------------*/
397 /*---------------- Thread Management ----------------*/
398 /*--------------------------------------------------------------*/
399
400 /** Spawn process threads */
401 private void spawnThreads(final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros,
402 final ConcurrentReadOutputStream rosu){
403
404 //Do anything necessary prior to processing
405
406 //Determine how many threads may be used
407 final int threads=Shared.threads();
408
409 //Fill a list with ProcessThreads
410 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
411 for(int i=0; i<threads; i++){
412 alpt.add(new ProcessThread(cris, ros, rosu, i));
413 }
414
415 //Start the threads and wait for them to finish
416 boolean success=ThreadWaiter.startAndWait(alpt, this);
417 errorState&=!success;
418
419 //Do anything necessary after processing
420
421 }
422
423 @Override
424 public final void accumulate(ProcessThread pt){
425 synchronized(pt) {
426 readsProcessed+=pt.readsProcessedT;
427 basesProcessed+=pt.basesProcessedT;
428 readsOut+=pt.readsOutT;
429 basesOut+=pt.basesOutT;
430
431 scoreSum+=pt.scoreSumT;
432 scoreSumPositive+=pt.scoreSumPositiveT;
433 scoreSumNegative+=pt.scoreSumNegativeT;
434 scoreSumPass+=pt.scoreSumPassT;
435 scoreSumFail+=pt.scoreSumFailT;
436
437 scoreCount+=pt.scoreCountT;
438 scoreCountPositive+=pt.scoreCountPositiveT;
439 scoreCountNegative+=pt.scoreCountNegativeT;
440 scoreCountPass+=pt.scoreCountPassT;
441 scoreCountFail+=pt.scoreCountFailT;
442
443 fpCount+=pt.fpCountT;
444 fnCount+=pt.fnCountT;
445 tpCount+=pt.tpCountT;
446 tnCount+=pt.tnCountT;
447
448 phist.incrementBy(pt.phistT);
449 mhist.incrementBy(pt.mhistT);
450 errorState|=(!pt.success);
451 }
452 }
453
454 @Override
455 public final boolean success(){return !errorState;}
456
457 /*--------------------------------------------------------------*/
458 /*---------------- Inner Methods ----------------*/
459 /*--------------------------------------------------------------*/
460
461 /*--------------------------------------------------------------*/
462 /*---------------- Inner Classes ----------------*/
463 /*--------------------------------------------------------------*/
464
465 // /** This class is static to prevent accidental writing to shared variables.
466 // * It is safe to remove the static modifier. */
467 class ProcessThread extends Thread {
468
469 //Constructor
470 ProcessThread(final ConcurrentReadInputStream cris_, final ConcurrentReadOutputStream ros_,
471 final ConcurrentReadOutputStream rosu_, final int tid_){
472 cris=cris_;
473 ros=ros_;
474 rosu=rosu_;
475 tid=tid_;
476 }
477
478 //Called by start()
479 @Override
480 public void run(){
481 //Do anything necessary prior to processing
482 net=net0.copy(false);
483 vec=new float[net.numInputs()];
484
485 //Process the reads
486 processInner();
487
488 //Do anything necessary after processing
489
490 //Indicate successful exit status
491 success=true;
492 }
493
494 /** Iterate through the reads */
495 void processInner(){
496
497 //Grab the first ListNum of reads
498 ListNum<Read> ln=cris.nextList();
499
500 //Check to ensure pairing is as expected
501 if(ln!=null && !ln.isEmpty()){
502 Read r=ln.get(0);
503 // assert(ffin1.samOrBam() || (r.mate!=null)==cris.paired()); //Disabled due to non-static access
504 }
505
506 //As long as there is a nonempty read list...
507 while(ln!=null && ln.size()>0){
508 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
509
510 processList(ln);
511
512 //Notify the input stream that the list was used
513 cris.returnList(ln);
514 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
515
516 //Fetch a new list
517 ln=cris.nextList();
518 }
519
520 //Notify the input stream that the final list was used
521 if(ln!=null){
522 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
523 }
524 }
525
526 void processList(ListNum<Read> ln){
527
528 //Grab the actual read list from the ListNum
529 final ArrayList<Read> reads=ln.list;
530 final ArrayList<Read> ureads=(rosu==null ? null : new ArrayList<Read>(reads.size()));
531
532 //Loop through each read in the list
533 for(int idx=0; idx<reads.size(); idx++){
534 final Read r1=reads.get(idx);
535 final Read r2=r1.mate;
536
537 //Validate reads in worker threads
538 if(!r1.validated()){r1.validate(true);}
539 if(r2!=null && !r2.validated()){r2.validate(true);}
540
541 //Track the initial length for statistics
542 final int initialLength1=r1.length();
543 final int initialLength2=r1.mateLength();
544
545 //Increment counters
546 readsProcessedT+=r1.pairCount();
547 basesProcessedT+=initialLength1+initialLength2;
548
549 {
550 //Reads are processed in this block.
551 boolean keep=processReadPair(r1, r2);
552
553 if(keep){
554 readsOutT+=r1.pairCount();
555 basesOutT+=r1.pairLength();
556 }else{
557 reads.set(idx, null);
558 if(ureads!=null) {ureads.add(r1);}
559 }
560 }
561 }
562
563 //Output reads to the output stream
564 if(ros!=null){ros.add(reads, ln.id);}
565 if(rosu!=null){rosu.add(ureads, ln.id);}
566 }
567
568 /**
569 * Process a read or a read pair.
570 * @param r1 Read 1
571 * @param r2 Read 2 (may be null)
572 * @return True if the reads should be kept, false if they should be discarded.
573 */
574 boolean processReadPair(final Read r1, final Read r2){
575 float score1=processRead(r1, vec);
576 float score2=(r2==null ? score1 : processRead(r2, vec));
577 float score=(r2==null || PAIR_MODE==SINGLE ? score1 :
578 PAIR_MODE==AVERAGE ? (score1+score2)*0.5f :
579 PAIR_MODE==MAX ? Tools.max(score1, score2) :
580 Tools.min(score1, score2));
581 boolean pass=(!filter ? true : (score>=cutoff)==highpass);
582 return pass;
583 }
584
585 private float processRead(Read r, float[] vec) {
586 if(r==null) {return -1;}
587 float result=(parseHeader ? Parse.parseFloat(r.id, "result=", '\t') : 0);
588 float score=score(r.bases, vec, k, net, rcomp);
589
590 boolean pass=(!filter ? true : (score>=cutoff)==highpass);
591 boolean positive=(result>=0.5f);
592 boolean correct=(positive==(score>=cutoff));
593 scoreSumT+=score;
594 scoreCountT++;
595
596 if(positive) {
597 scoreSumPositiveT+=score;
598 scoreCountPositiveT++;
599 tpCountT+=(correct ? 1 : 0);
600 fnCountT+=(correct ? 0 : 1);
601 }else {
602 scoreSumNegativeT+=score;
603 scoreCountNegativeT++;
604 tnCountT+=(correct ? 1 : 0);
605 fpCountT+=(correct ? 0 : 1);
606 }
607
608 if(pass) {
609 scoreSumPassT+=score;
610 scoreCountPassT++;
611 }else {
612 scoreSumFailT+=score;
613 scoreCountFailT++;
614 }
615
616 int iscore=Tools.mid(0, Math.round(score*100), 100);
617 if(result<0.5f) {mhistT.increment(iscore);}
618 else {phistT.increment(iscore);}
619 if(annotate) {r.id+=String.format("\tscore=%.4f", score);}
620 return score;
621 }
622
623 /** Number of reads processed by this thread */
624 protected long readsProcessedT=0;
625 /** Number of bases processed by this thread */
626 protected long basesProcessedT=0;
627
628 /** Number of reads retained by this thread */
629 protected long readsOutT=0;
630 /** Number of bases retained by this thread */
631 protected long basesOutT=0;
632
633 double scoreSumT=0;
634 double scoreSumPositiveT=0;
635 double scoreSumNegativeT=0;
636 double scoreSumPassT=0;
637 double scoreSumFailT=0;
638 long scoreCountT=0;
639 long scoreCountPositiveT=0;
640 long scoreCountNegativeT=0;
641 long scoreCountPassT=0;
642 long scoreCountFailT=0;
643
644 long fpCountT=0;
645 long fnCountT=0;
646 long tpCountT=0;
647 long tnCountT=0;
648
649 /** True only if this thread has completed successfully */
650 boolean success=false;
651
652 private LongList phistT=new LongList(101);
653 private LongList mhistT=new LongList(101);
654
655 private CellNet net;
656 private float[] vec;
657
658 /** Shared input stream */
659 private final ConcurrentReadInputStream cris;
660 /** Shared output stream */
661 private final ConcurrentReadOutputStream ros;
662 /** Shared unmatched output stream */
663 private final ConcurrentReadOutputStream rosu;
664 /** Thread ID */
665 final int tid;
666 }
667
668 /*--------------------------------------------------------------*/
669
670 float score(byte[] bases, float[] vec, int k, CellNet net, boolean rcomp) {
671 final float f=score(bases, vec, k, net), r;
672 if(rcomp) {
673 AminoAcid.reverseComplementBasesInPlace(bases);
674 r=score(bases, vec, k, net);
675 AminoAcid.reverseComplementBasesInPlace(bases);
676 }else {r=f;}
677 return Tools.max(r, f);
678 }
679
680 float score(byte[] bases, float[] vec, int k, CellNet net) {
681 if(SCORE_MODE==SINGLE) {
682 return scoreSingle(bases, vec, k, net);
683 }else {
684 return scoreFrames(bases, vec, k, net, SCORE_MODE, stepsize, width);
685 }
686 }
687
688 public static float scoreSingle(byte[] bases, float[] vec, int k, CellNet net) {
689 assert(vec!=null);
690 SequenceToVector.fillVector(bases, vec, k);
691 net.applyInput(vec);
692 final float f=net.feedForward();
693 return f;
694 }
695
696 public static float scoreFrames(byte[] bases, float[] vec, int k, CellNet net, int SCORE_MODE, int stepsize, int width) {
697 assert(vec!=null);
698 assert(SCORE_MODE>=0 && SCORE_MODE!=SINGLE) : SCORE_MODE;
699 float min=9999, max=-9999;
700 double sum=0;
701 long frames=1;
702 int start=0, stop=width;
703 do {
704 SequenceToVector.fillVector(bases, vec, k, start, stop);
705 net.applyInput(vec);
706 final float f=net.feedForward();
707 frames++;
708 sum+=f;
709 min=Tools.min(min, f);
710 max=Tools.max(max, f);
711 start+=stepsize;
712 stop+=stepsize;
713 }while(stop<bases.length-1);
714 return SCORE_MODE==AVERAGE ? (float)(sum/frames) : SCORE_MODE==MIN ? min : max;
715 }
716
717 public static float score(byte[] bases, float[] vec, int k, CellNet net, int from, int to) {
718 SequenceToVector.fillVector(bases, vec, k, from, to);
719 net.applyInput(vec);
720 final float f=net.feedForward();
721 return f;
722 }
723
724 private static int parseMode(String b) {
725 int x=Tools.find(b.toLowerCase(), MODES);
726 if(x<0) {throw new RuntimeException("Unknown mode "+b+"; must be one of "+Arrays.toString(MODES));}
727 return x;
728 }
729
730 /*--------------------------------------------------------------*/
731 /*---------------- Fields ----------------*/
732 /*--------------------------------------------------------------*/
733
734 /** Primary input file path */
735 private String in1=null;
736 /** Secondary input file path */
737 private String in2=null;
738
739 private String qfin1=null;
740 private String qfin2=null;
741
742 /** Primary output file path */
743 private String out1=null;
744 /** Secondary output file path */
745 private String out2=null;
746
747 private String outu1=null;
748 private String outu2=null;
749
750 private String qfout1=null;
751 private String qfout2=null;
752
753 /** Override input file extension */
754 private String extin=null;
755 /** Override output file extension */
756 private String extout=null;
757
758 /** Whether interleaved was explicitly set. */
759 private boolean setInterleaved=false;
760
761 private String netFile=null;
762 private String histFile=null;
763 private final FileFormat ffnet;
764
765 private LongList phist=new LongList(101);
766 private LongList mhist=new LongList(101);
767
768 /*--------------------------------------------------------------*/
769
770
771 private boolean parseHeader=false;
772 private final CellNet net0;
773
774 /** For raw sequence classification */
775 private boolean rcomp=false;
776 private int width=-1;
777
778 /** For kmer spectrum classification */
779 private int k=0;
780 private int dims; //asdf//TODO
781
782 private boolean filter=true;
783 private boolean highpass=true;
784 private boolean annotate=false;
785 private float cutoff=0.5f;
786 private boolean autoCutoff=true;
787 private int stepsize=1;
788 private int overlap=Integer.MIN_VALUE;
789
790 private int SCORE_MODE=SINGLE;
791 private int PAIR_MODE=AVERAGE;
792 private static final int SINGLE=0, AVERAGE=1, MAX=2, MIN=3;
793 private static final String[] MODES= {"single", "average", "max", "min"};
794
795 /*--------------------------------------------------------------*/
796
797 /** Number of reads processed */
798 protected long readsProcessed=0;
799 /** Number of bases processed */
800 protected long basesProcessed=0;
801
802 /** Number of reads retained */
803 protected long readsOut=0;
804 /** Number of bases retained */
805 protected long basesOut=0;
806
807 double scoreSum=0;
808 double scoreSumPositive=0;
809 double scoreSumNegative=0;
810 double scoreSumPass=0;
811 double scoreSumFail=0;
812 long scoreCount=0;
813 long scoreCountPositive=0;
814 long scoreCountNegative=0;
815 long scoreCountPass=0;
816 long scoreCountFail=0;
817 long fpCount=0;
818 long fnCount=0;
819 long tpCount=0;
820 long tnCount=0;
821
822 /** Quit after processing this many input reads; -1 means no limit */
823 private long maxReads=-1;
824
825 /*--------------------------------------------------------------*/
826 /*---------------- Final Fields ----------------*/
827 /*--------------------------------------------------------------*/
828
829 /** Primary input file */
830 private final FileFormat ffin1;
831 /** Secondary input file */
832 private final FileFormat ffin2;
833
834 /** Primary output file */
835 private final FileFormat ffout1;
836 /** Secondary output file */
837 private final FileFormat ffout2;
838
839 /** Unmatched output file */
840 private final FileFormat ffoutu1;
841 /** Secondary unmatched output file */
842 private final FileFormat ffoutu2;
843
844 @Override
845 public final ReadWriteLock rwlock() {return rwlock;}
846 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
847
848 /*--------------------------------------------------------------*/
849 /*---------------- Common Fields ----------------*/
850 /*--------------------------------------------------------------*/
851
852 /** Print status messages to this output stream */
853 private PrintStream outstream=System.err;
854 /** Print verbose messages */
855 public static boolean verbose=false;
856 /** True if an error was encountered */
857 public boolean errorState=false;
858 /** Overwrite existing output files */
859 private boolean overwrite=true;
860 /** Append to existing output files */
861 private boolean append=false;
862 /** Reads are output in input order */
863 private boolean ordered=true;
864
865 }