Debian Codegraph @

current/jgi/FindPrimers.java

raw symbols SCIP
1 package jgi;
2
3 import java.io.File;
4 import java.util.ArrayList;
5 import java.util.concurrent.atomic.AtomicIntegerArray;
6 import java.util.concurrent.locks.ReadWriteLock;
7 import java.util.concurrent.locks.ReentrantReadWriteLock;
8
9 import aligner.Aligner;
10 import aligner.MultiStateAligner9PacBioAdapter2;
11 import aligner.SingleStateAlignerFlat;
12 import aligner.SingleStateAlignerFlat2;
13 import aligner.SingleStateAlignerFlat2Amino;
14 import aligner.SingleStateAlignerFlat2_1D;
15 import dna.AminoAcid;
16 import fileIO.FileFormat;
17 import fileIO.ReadWrite;
18 import shared.Parse;
19 import shared.Parser;
20 import shared.PreParser;
21 import shared.Shared;
22 import shared.Timer;
23 import shared.Tools;
24 import stream.ConcurrentReadInputStream;
25 import stream.ConcurrentReadOutputStream;
26 import stream.FastaReadInputStream;
27 import stream.Read;
28 import stream.ReadStreamWriter;
29 import stream.SamLine;
30 import stream.SiteScore;
31 import structures.ByteBuilder;
32 import structures.ListNum;
33 import template.Accumulator;
34 import template.ThreadWaiter;
35
36 /**
37 * @author Brian Bushnell
38 * @date Oct 6, 2014
39 *
40 */
41 public class FindPrimers implements Accumulator<FindPrimers.ProcessThread> {
42
43 public static void main(String[] args){
44 Timer t=new Timer();
45 FindPrimers x=new FindPrimers(args);
46 x.process(t);
47
48 //Close the print stream if it was redirected
49 Shared.closeStream(x.outstream);
50 }
51
52 public FindPrimers(String[] args){
53
54 {//Preparse block for help, config files, and outstream
55 PreParser pp=new PreParser(args, getClass(), false);
56 args=pp.args;
57 outstream=pp.outstream;
58 }
59
60 Shared.capBufferLen(8);
61
62 float cutoff_=0;
63 String literal_=null;
64 String ref_=null;
65 Parser parser=new Parser();
66 for(int i=0; i<args.length; i++){
67 String arg=args[i];
68 String[] split=arg.split("=");
69 String a=split[0].toLowerCase();
70 String b=split.length>1 ? split[1] : null;
71
72 if(a.equals("rcomp")){
73 rcomp=Parse.parseBoolean(b);
74 }else if(a.equals("usemsa2") || a.equals("msa2")){
75 useMSA2=Parse.parseBoolean(b);
76 }else if(a.equals("usessa2") || a.equals("ssa2")){
77 useSSA2=Parse.parseBoolean(b);
78 }else if(a.equalsIgnoreCase("usessa1d") || a.equalsIgnoreCase("ssa1d")){
79 useSSA1D=Parse.parseBoolean(b);
80 }else if(a.equals("swap")){
81 swapQuery=Parse.parseBoolean(b);
82 }else if(a.equals("printzeros")){
83 printZeros=Parse.parseBoolean(b);
84 }else if(a.equals("twocolumn") || a.equals("2column")){
85 oneColumn=!Parse.parseBoolean(b);
86 }else if(a.equals("onecolumn")){
87 oneColumn=Parse.parseBoolean(b);
88 }else if(a.equals("addr")){
89 addR=Parse.parseBoolean(b);
90 }else if(a.equals("replicate") || a.equals("expand")){
91 replicateAmbiguous=Parse.parseBoolean(b);
92 }else if(a.equals("literal")){
93 literal_=b;
94 }else if(a.equals("cutoff") || a.equals("minid")){
95 cutoff_=Float.parseFloat(b);
96 if(cutoff_>1){cutoff_=cutoff_/100;}
97 assert(cutoff_>=0 && cutoff_<=1) : "Cutoff should range from 0 to 1";
98 }else if(a.equals("primer") || a.equals("query") || a.equals("ref")){
99 if(new File(b).exists()){ref_=b;}
100 else{literal_=b;}
101 }else if(a.equals("idhist")){
102 outIdHist=b;
103 }else if(a.equals("parse_flag_goes_here")){
104 //Set a variable here
105 }else if(parser.parse(arg, a, b)){
106 //do nothing
107 }else{
108 outstream.println("Unknown parameter "+args[i]);
109 assert(false) : "Unknown parameter "+args[i];
110 // throw new RuntimeException("Unknown parameter "+args[i]);
111 }
112 }
113
114 {//Process parser fields
115 Parser.processQuality();
116
117 maxReads=parser.maxReads;
118 in1=parser.in1;
119 out1=parser.out1;
120 }
121 cutoff=cutoff_;
122
123 // ArrayList<byte[]> sharedHeader=new ArrayList<byte[]>();
124 ByteBuilder sharedHeader=new ByteBuilder();
125 sharedHeader.append("@HD\tVN:1.4\tSO:unsorted\n");
126 if(ref_!=null){
127 ArrayList<Read> list=FastaReadInputStream.toReads(ref_, FileFormat.FASTA, -1);
128 int max=0;
129 queries=new ArrayList<Read>();
130 // assert(false) : list;
131 for(int i=0; i<list.size(); i++){
132 Read r=list.get(i);
133 max=Tools.max(max, r.length());
134 if(swapQuery){
135 sharedHeader.append("@SQ\tSN:"+r.name()+"\tLN:"+r.length()).nl();
136 }
137 queries.add(r);
138 // if(rcomp){
139 // r=r.copy();
140 // r.reverseComplement();
141 // if(addR){r.id="r_"+r.id;}
142 // r.setStrand(1);
143 // queries.add(r);
144 // }
145 }
146 maxqlen=max;
147 }else if(literal_!=null){
148 int max=0;
149 String[] s2=literal_.split(",");
150 queries=new ArrayList<Read>();
151 for(int i=0; i<s2.length; i++){
152 Read r=new Read(s2[i].getBytes(), null, "query"+i, i);
153 max=Tools.max(max, r.length());
154 queries.add(r);
155 if(swapQuery){
156 sharedHeader.append("@SQ\tSN:"+r.name()+"\tLN:"+r.length()).nl();
157 }
158 }
159 maxqlen=max;
160 }else{
161 queries=null;
162 maxqlen=0;
163 }
164
165 if(sharedHeader.length()>0) {
166 ReadStreamWriter.HEADER=sharedHeader;
167 }
168
169 if(replicateAmbiguous){
170 queries=Tools.replicateAmbiguous(queries, 1);
171 }
172 if(Shared.AMINO_IN){rcomp=false;}
173 if(rcomp){
174 for(int i=0, max=queries.size(); i<max; i++){
175 Read r=queries.get(i).copy();
176 r.reverseComplement();
177 if(addR){r.id="r_"+r.id;}
178 r.setStrand(1);
179 queries.add(r);
180 }
181 }
182
183 // assert(false) : queries;
184
185 ffout1=FileFormat.testOutput(out1, FileFormat.ATTACHMENT, "attachment", true, true, false, ordered);
186 // assert(ffout1.type()==FileFormat.ATTACHMENT) : ffout1;
187 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, null, true, true);
188 }
189
190 void process(Timer t){
191
192 final ConcurrentReadInputStream cris;
193 {
194 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, null);
195 if(verbose){outstream.println("Started cris");}
196 cris.start(); //4567
197 }
198 boolean paired=cris.paired();
199
200 final ConcurrentReadOutputStream ros=makeCros();
201
202 // final ByteStreamWriter bsw;
203 // if(out1!=null){
204 //
205 // assert(!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1)) : "Input file and output file have same name.";
206 //
207 // bsw=new ByteStreamWriter(ffout1);
208 // bsw.start();
209 // }else{bsw=null;}
210
211 spawnThreads(cris, ros);
212
213 // if(bsw!=null){bsw.poisonAndWait();}
214 ReadWrite.closeStreams(cris, ros);
215
216 int minid=100;
217 {
218 ByteBuilder bb=new ByteBuilder();
219 bb.append(oneColumn ? ReadWrite.stripToCore(outIdHist) : "ID\tCount").nl();
220 for(int i=0; i<idHist.length(); i++){
221 int count=idHist.get(i);
222 if(count>0 || printZeros) {
223 if(!oneColumn){bb.append(i).tab();}
224 bb.append(count).nl();
225 if(count>0){minid=Tools.min(minid, i);}
226 }
227 }
228 if(outIdHist!=null){ReadWrite.writeString(bb, outIdHist);}
229 }
230
231 if(verbose){outstream.println("Finished.");}
232
233 t.stop();
234 outstream.println("Time: \t"+t);
235 outstream.println("Reads Processed: "+readsProcessed+" \t"+Tools.format("%.2fk reads/sec", (readsProcessed/(double)(t.elapsed))*1000000));
236 outstream.println("Average Identity: "+Tools.format("%.3f%%", (identitySum*100/identityCount)));
237 outstream.println("Min Identity: "+minid);
238 }
239
240 private ConcurrentReadOutputStream makeCros(){
241 if(ffout1==null){return null;}
242
243 //Select output buffer size based on whether it needs to be ordered
244 final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
245
246 final ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(ffout1, null, buff, null, true);
247 ros.start(); //Start the stream
248 return ros;
249 }
250
251 /*--------------------------------------------------------------*/
252 /*---------------- Thread Management ----------------*/
253 /*--------------------------------------------------------------*/
254
255 /** Spawn process threads */
256 private void spawnThreads(final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros){
257
258 //Do anything necessary prior to processing
259
260 //Determine how many threads may be used
261 final int threads=Shared.threads();
262
263 //Fill a list with ProcessThreads
264 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
265 for(int i=0; i<threads; i++){
266 alpt.add(new ProcessThread(cris, ros, i));
267 }
268
269 //Start the threads and wait for them to finish
270 boolean success=ThreadWaiter.startAndWait(alpt, this);
271 errorState&=!success;
272
273 //Do anything necessary after processing
274
275 }
276
277 @Override
278 public final void accumulate(ProcessThread pt){
279 readsProcessed+=pt.readsProcessedT;
280 basesProcessed+=pt.basesProcessedT;
281 readsOut+=pt.readsOutT;
282 basesOut+=pt.basesOutT;
283 identitySum+=pt.identitySumT;
284 identityCount+=pt.identityCountT;
285 errorState|=(!pt.success);
286 }
287
288 @Override
289 public final boolean success(){return !errorState;}
290
291 /*--------------------------------------------------------------*/
292 /*---------------- Inner Classes ----------------*/
293 /*--------------------------------------------------------------*/
294
295 /** This class is static to prevent accidental writing to shared variables.
296 * It is safe to remove the static modifier. */
297 class ProcessThread extends Thread {
298
299 //Constructor
300 ProcessThread(final ConcurrentReadInputStream cris_, final ConcurrentReadOutputStream ros_, final int tid_){
301 cris=cris_;
302 ros=ros_;
303 tid=tid_;
304 }
305
306 //Called by start()
307 @Override
308 public void run(){
309 //Do anything necessary prior to processing
310
311 //Process the reads
312 processInner();
313
314 //Do anything necessary after processing
315
316 //Indicate successful exit status
317 success=true;
318 }
319
320 /** Iterate through the reads */
321 void processInner(){
322
323 //Grab the first ListNum of reads
324 ListNum<Read> ln=cris.nextList();
325
326 //Check to ensure pairing is as expected
327 if(ln!=null && !ln.isEmpty()){
328 Read r=ln.get(0);
329 // assert(ffin1.samOrBam() || (r.mate!=null)==cris.paired()); //Disabled due to non-static access
330 }
331
332 //As long as there is a nonempty read list...
333 while(ln!=null && ln.size()>0){
334 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
335
336 processList(ln);
337
338 //Notify the input stream that the list was used
339 cris.returnList(ln);
340 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
341
342 //Fetch a new list
343 ln=cris.nextList();
344 }
345
346 //Notify the input stream that the final list was used
347 if(ln!=null){
348 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
349 }
350 }
351
352 void processList(ListNum<Read> ln){
353
354 //Grab the actual read list from the ListNum
355 final ArrayList<Read> reads=ln.list;
356
357 //Loop through each read in the list
358 for(int idx=0; idx<reads.size(); idx++){
359 final Read r=reads.get(idx);
360 assert(r.mate==null);
361
362 //Validate reads in worker threads
363 if(!r.validated()){r.validate(true);}
364
365 //Track the initial length for statistics
366 final int initialLength1=r.length();
367
368 //Increment counters
369 readsProcessedT+=r.pairCount();
370 basesProcessedT+=initialLength1;
371
372 {
373 //Reads are processed in this block.
374 boolean keep=processRead(r);
375
376 if(!keep){reads.set(idx, null);}
377 else{
378 readsOutT+=r.pairCount();
379 basesOutT+=r.pairLength();
380 }
381 }
382 }
383
384 //Output reads to the output stream
385 if(ros!=null){ros.add(reads, ln.id);}
386 }
387
388 /**
389 * Process a read or a read pair.
390 * @param r1 Read 1
391 * @param r2 Read 2 (may be null)
392 * @return True if the reads should be kept, false if they should be discarded.
393 */
394 boolean processRead(final Read r){
395
396 final int a=0, b=(swapQuery ? maxqlen-1 : r.length()-1);
397 int[] max;
398
399
400 SiteScore bestSite=null;
401 Read bestQuery=null;
402 for(int qnum=0; qnum<queries.size(); qnum++){
403 final Read query=queries.get(qnum);
404
405 // System.err.println("msa.maxColumns()="+msa.maxColumns()+", msa.maxRows()="+msa.maxRows()+
406 // ", maxqlen="+maxqlen+", rlen="+r.length()+", qlen="+query.length());
407
408
409 //{rows, maxCol, maxState, maxScore, maxStart}
410 if(swapQuery){
411 max=msa.fillUnlimited(r.bases, query.bases, a, b, -999999);
412 }else{
413 max=msa.fillUnlimited(query.bases, r.bases, a, b, -999999);
414 }
415 // assert(false) : new String(r.bases)+"\n"+new String(queries.get(0).bases);
416
417 // System.err.println("\nAligned: "+new String(r.bases).substring(0, 10)+"..."+new String(r.bases).substring(r.bases.length-11)+
418 // ", "+new String(query.bases).substring(0, 10)+"..."+new String(query.bases).substring(query.bases.length-11));
419
420 if(max!=null){
421
422 final int rows=max[0];
423 final int maxCol=max[1];
424 final int maxState=max[2];
425 // final int maxScore=max[3];
426 // final int maxStart=max[4];
427
428 //{score, bestRefStart, bestRefStop}
429 //byte[] read, byte[] ref, int refStartLoc, int refEndLoc, int maxRow, int maxCol, int maxState
430 // int[] score=msa.score(query.bases, r.bases, a, b, max[0], max[1], max[2]);
431 int[] score;
432 if(swapQuery){
433 score=msa.score(r.bases, query.bases, a, b, rows, maxCol, maxState);
434 }else{
435 //returns {score, bestRefStart, bestRefStop}
436 score=msa.score(query.bases, r.bases, a, b, rows, maxCol, maxState);
437 }
438 SiteScore ss=new SiteScore(1, query.strand(), score[1], score[2], 1, score[0]);
439 // System.err.println("Score: "+ss.quickScore);
440 if(bestSite==null || ss.quickScore>bestSite.quickScore){
441 bestQuery=query;
442 ss.setSlowScore(ss.quickScore);
443 ss.score=ss.quickScore;
444 // ss.match=msa.traceback(query.bases, r.bases, a, b, score[3], score[4], score[5], false);
445
446 //(byte[] read, byte[] ref, int refStartLoc, int refEndLoc, int row, int col, int state)
447 //int refStartLoc, int refEndLoc, int row, int col, int state
448 if(swapQuery){
449 ss.match=msa.traceback(r.bases, query.bases, a, b, rows, maxCol, maxState);
450 }else{
451 ss.match=msa.traceback(query.bases, r.bases, a, b, rows, maxCol, maxState);
452 }
453 // System.err.println(new String(ss.match));
454 // System.err.println(Read.identity(ss.match));
455 bestSite=ss;
456 }
457 }
458 }
459
460 ByteBuilder bb2=new ByteBuilder(toBytes(r, bestQuery, bestSite));
461 r.obj=bb2;
462
463 return true;
464 }
465
466
467 /*--------------------------------------------------------------*/
468
469 private ByteBuilder toBytes(Read r, Read query, SiteScore ss){
470 bb.clear();
471 if(ss==null){return toBytes(r, query);}
472 float identity=Read.identity(ss.match);
473 idHist.incrementAndGet((int)(100*identity));
474 if(identity<cutoff){return toBytes(r, query);}
475 if(swapQuery){
476 bb.append(r.id).append('\t');
477 }else{
478 bb.append(query.id).append('\t');
479 }
480 bb.append(makeFlag(ss)).append('\t');
481 if(swapQuery){
482 bb.append(query.id).append('\t');
483 }else{
484 bb.append(r.id.replace('\t', '_')).append('\t');
485 }
486 bb.append(Tools.max(0, ss.start)+1).append('\t');
487 bb.append(Tools.max(ss.score/query.length(), 4)).append('\t');
488 String cigar;
489 if(swapQuery){
490 cigar=SamLine.toCigar14(ss.match, ss.start, ss.stop, query.length(), r.bases);
491 // assert(SamLine.calcCigarReadLength(cigar, true, false)==r.length()) :
492 // "cigar="+SamLine.calcCigarReadLength(cigar, true, false)+", r="+r.length()+", q="+query.length()+", swap="+swapQuery+", rid="+r.id;
493 }else{
494 cigar=SamLine.toCigar14(ss.match, ss.start, ss.stop, r.length(), query.bases);
495 // assert(SamLine.calcCigarReadLength(cigar, true, false)==query.length()) :
496 // "cigar="+SamLine.calcCigarReadLength(cigar, true, false)+", r="+r.length()+", q="+query.length()+", swap="+swapQuery+", rid="+r.id;
497 }
498 if(cigar==null){bb.append('*').append('\t');}else{bb.append(cigar).append('\t');}
499 bb.append('*').append('\t');
500 bb.append('0').append('\t');
501 bb.append('0').append('\t');
502
503 if(swapQuery){
504 if(ss.strand()==Shared.MINUS){
505 for(int i=r.bases.length-1; i>=0; i--){bb.append(AminoAcid.baseToComplementExtended[r.bases[i]]);}
506 bb.tab();
507 }else{
508 bb.append(r.bases).append('\t');
509 }
510 }else{
511 bb.append(query.bases).append('\t');
512 }
513 // assert(ss.strand()!=Shared.MINUS) : bb+"\n"+new String(r.bases);
514 bb.append('*').append('\t');
515
516 identitySumT+=identity;
517 identityCountT++;
518 bb.append("YI:f:").append(100*identity, 2);
519
520 return bb;
521 }
522
523 private ByteBuilder toBytes(Read r, Read query){
524 bb.clear();
525 // if(cutoff>0){return bb;}
526 if(swapQuery){
527 bb.append(r.id).append('\t');
528 }else{
529 bb.append(query.id).append('\t');
530 }
531 bb.append(4).append('\t');
532 bb.append('*').append('\t');
533 bb.append(0).append('\t');
534 bb.append(0).append('\t');
535 bb.append('*').append('\t');
536 bb.append('*').append('\t');
537 bb.append('0').append('\t');
538 bb.append('0').append('\t');
539
540 if(swapQuery){
541 bb.append(r.bases).append('\t');
542 }else{
543 bb.append(query.bases).append('\t');
544 }
545 bb.append('*').append('\t');
546
547 // identitySumT+=f;
548 // identityCountT++;
549 // bb.append("YI:f:").append(100*f, 2);
550
551 return bb;
552 }
553
554 //This seems to be up to 30% faster if the raw class rather than interface is used.
555 Aligner msa=Shared.AMINO_IN ? new SingleStateAlignerFlat2Amino() : useMSA2 ? new MultiStateAligner9PacBioAdapter2() :
556 useSSA1D ? new SingleStateAlignerFlat2_1D() : useSSA2 ? new SingleStateAlignerFlat2() : new SingleStateAlignerFlat();
557 // SingleStateAlignerFlat msa=new SingleStateAlignerFlat(maxqlen+5, maxqlen+5);
558
559 SingleStateAlignerFlat xxx0; //Never fastest
560 MultiStateAligner9PacBioAdapter2 xxx1; //Best for indels, but slowest
561 SingleStateAlignerFlat2 xxx2; //Fastest for 16S
562 SingleStateAlignerFlat2_1D xxx3; //Fastest for 23S
563 Aligner xxx9;
564
565 /** Number of reads processed by this thread */
566 protected long readsProcessedT=0;
567 /** Number of bases processed by this thread */
568 protected long basesProcessedT=0;
569
570 /** Number of reads retained by this thread */
571 protected long readsOutT=0;
572 /** Number of bases retained by this thread */
573 protected long basesOutT=0;
574
575 double identitySumT=0;
576 long identityCountT=0;
577
578 /** True only if this thread has completed successfully */
579 boolean success=false;
580
581 private ByteBuilder bb=new ByteBuilder(1000);
582
583 /** Shared input stream */
584 private final ConcurrentReadInputStream cris;
585 /** Shared output stream */
586 private final ConcurrentReadOutputStream ros;
587 /** Thread ID */
588 final int tid;
589 }
590
591 public static int makeFlag(SiteScore ss){
592 int flag=0;
593 if(ss.strand()==Shared.MINUS){flag|=0x10;}
594 return flag;
595 }
596
597
598
599 /*--------------------------------------------------------------*/
600
601 /*--------------------------------------------------------------*/
602
603 private String in1=null;
604 private String out1=null;
605 private String outIdHist=null;
606
607 private AtomicIntegerArray idHist=new AtomicIntegerArray(101);
608
609 private final float cutoff;
610 private boolean rcomp=true;
611 private boolean replicateAmbiguous=false;
612 private boolean swapQuery=false;
613 private boolean addR=false;
614 private boolean printZeros=true;
615 private boolean oneColumn=false;
616 private boolean useMSA2=false;
617 private boolean useSSA2=true;
618 private boolean useSSA1D=false;
619
620 private final FileFormat ffin1;
621 private final FileFormat ffout1;
622 private ArrayList<Read> queries;
623 private final int maxqlen;
624
625 @Override
626 public final ReadWriteLock rwlock() {return rwlock;}
627 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
628
629 /*--------------------------------------------------------------*/
630
631 protected long readsProcessed=0;
632 protected long basesProcessed=0;
633
634 protected long readsOut=0;
635 protected long basesOut=0;
636
637 private long maxReads=-1;
638
639 double identitySum=0;
640 long identityCount=0;
641
642 boolean ordered=true;
643 boolean errorState=false;
644
645 /*--------------------------------------------------------------*/
646
647 private java.io.PrintStream outstream=System.err;
648 public static boolean verbose=false;
649
650 }