Debian Codegraph @

current/cluster/ReclusterByKmer.java

raw symbols SCIP
1 package cluster;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.Random;
7
8 import dna.Data;
9 import fileIO.ByteFile;
10 import fileIO.ByteFile1;
11 import fileIO.ByteFile2;
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.ConcurrentGenericReadInputStream;
21 import stream.ConcurrentReadInputStream;
22 import stream.ConcurrentReadOutputStream;
23 import stream.FASTQ;
24 import stream.FastaReadInputStream;
25 import stream.Read;
26 import structures.ListNum;
27
28 /**
29 * @author Brian Bushnell
30 * @date Feb 7, 2014
31 *
32 */
33 public class ReclusterByKmer {
34
35 public static void main(String[] args){
36 Timer t=new Timer();
37 ReclusterByKmer x=new ReclusterByKmer(args);
38 x.process(t);
39
40 //Close the print stream if it was redirected
41 Shared.closeStream(x.outstream);
42 }
43
44 public ReclusterByKmer(String[] args){
45
46 {//Preparse block for help, config files, and outstream
47 PreParser pp=new PreParser(args, getClass(), false);
48 args=pp.args;
49 outstream=pp.outstream;
50 }
51
52 boolean setInterleaved=false; //Whether it was explicitly set.
53
54 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
55
56
57 int k1_=12;
58 int k2_=3;
59 Parser parser=new Parser();
60
61 for(int i=0; i<args.length; i++){
62 String arg=args[i];
63 String[] split=arg.split("=");
64 String a=split[0].toLowerCase();
65 String b=split.length>1 ? split[1] : null;
66
67 if(Parser.parseZip(arg, a, b)){
68 //do nothing
69 }else if(Parser.parseCommonStatic(arg, a, b)){
70 //do nothing
71 }else if(Parser.parseFasta(arg, a, b)){
72 //do nothing
73 }else if(Parser.parseQuality(arg, a, b)){
74 //do nothing
75 }else if(parser.parseInterleaved(arg, a, b)){
76 //do nothing
77 }else if(parser.parseFiles(arg, a, b)){
78 //do nothing
79 }else if(parser.parseCommon(arg, a, b)){
80 //do nothing
81 }else if(a.equals("verbose")){
82 verbose=Parse.parseBoolean(b);
83 ByteFile1.verbose=verbose;
84 ByteFile2.verbose=verbose;
85 stream.FastaReadInputStream.verbose=verbose;
86 ConcurrentGenericReadInputStream.verbose=verbose;
87 stream.FastqReadInputStream.verbose=verbose;
88 ReadWrite.verbose=verbose;
89 }else if(a.equals("build") || a.equals("genome")){
90 Data.setGenome(Integer.parseInt(b));
91 }else if(in1==null && i==0 && Tools.looksLikeInputStream(arg)){
92 in1=arg;
93 }else{
94 System.err.println("Unknown parameter "+args[i]);
95 assert(false) : "Unknown parameter "+args[i];
96 // throw new RuntimeException("Unknown parameter "+args[i]);
97 }
98 }
99
100 {//Process parser fields
101 Parser.processQuality();
102
103 maxReads=parser.maxReads;
104 overwrite=parser.overwrite;
105 append=parser.append;
106
107 setInterleaved=parser.setInterleaved;
108
109 in1=parser.in1;
110 in2=parser.in2;
111 // qfin1=parser.qfin1;
112 // qfin2=parser.qfin2;
113
114 out1=parser.out1;
115 out2=parser.out2;
116 // qfout1=parser.qfout1;
117 // qfout2=parser.qfout2;
118
119 extin=parser.extin;
120 extout=parser.extout;
121 }
122
123
124 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
125 in2=in1.replace("#", "2");
126 in1=in1.replace("#", "1");
127 }
128 if(out1!=null && out2==null && out1.indexOf('#')>-1){
129 out2=out1.replace("#", "2");
130 out1=out1.replace("#", "1");
131 }
132 if(in2!=null){
133 if(FASTQ.FORCE_INTERLEAVED){System.err.println("Reset INTERLEAVED to false because paired input files were specified.");}
134 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
135 }
136
137 assert(FastaReadInputStream.settingsOK());
138
139 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
140 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
141 // if(ReadWrite.isCompressed(in1)){ByteFile.FORCE_MODE_BF2=true;}
142 ByteFile.FORCE_MODE_BF2=true;
143 }
144
145 if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
146
147 if(!setInterleaved){
148 assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
149 if(in2!=null){ //If there are 2 input streams.
150 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
151 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
152 }else{ //There is one input stream.
153 if(out2!=null){
154 FASTQ.FORCE_INTERLEAVED=true;
155 FASTQ.TEST_INTERLEAVED=false;
156 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
157 }
158 }
159 }
160
161 if(out1!=null && out1.equalsIgnoreCase("null")){out1=null;}
162 if(out2!=null && out2.equalsIgnoreCase("null")){out2=null;}
163
164 if(!Tools.testOutputFiles(overwrite, append, false, out1, out2)){
165 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+"\n");
166 }
167
168 ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, append, false);
169 ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, append, false);
170
171 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
172 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
173
174 /* Check for output file collisions */
175 Tools.testOutputFiles(overwrite, append, false, out1, out2);
176
177 k1=k1_;
178 assert(k1>=-1 && k1<=15) : "k1 must lie between 1 and 15, inclusive (0 to disable)";
179 k2=k2_;
180 assert(k2>=-1 && k2<=6) : "k2 must lie between 1 and 6, inclusive (0 to disable)";
181
182 arraylen1=(k1>0 ? ClusterTools.maxCanonicalKmer(k1)+1 : 0);
183 arraylen2=(k2>0 ? ClusterTools.maxCanonicalKmer(k2)+1 : 0);
184 }
185
186 /*--------------------------------------------------------------*/
187
188 void process(Timer t){
189
190
191 final ConcurrentReadInputStream cris;
192 {
193 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, null, null);
194 if(verbose){System.err.println("Started cris");}
195 cris.start(); //4567
196 }
197 boolean paired=cris.paired();
198 if(verbose){System.err.println("Input is "+(paired ? "paired" : "unpaired"));}
199
200 ConcurrentReadOutputStream ros=null;
201 if(out1!=null){
202 final int buff=4;
203
204 if(cris.paired() && out2==null && (in1==null || !in1.contains(".sam"))){
205 outstream.println("Writing interleaved.");
206 }
207
208 assert(!out1.equalsIgnoreCase(in1) && !out1.equalsIgnoreCase(in1)) : "Input file and output file have same name.";
209 assert(out2==null || (!out2.equalsIgnoreCase(in1) && !out2.equalsIgnoreCase(in2))) : "out1 and out2 have same name.";
210
211 ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, null, null, buff, null, false);
212 ros.start();
213 }
214
215 long readsProcessed=0;
216 long basesProcessed=0;
217
218 {
219
220 ListNum<Read> ln=cris.nextList();
221 ArrayList<Read> reads=(ln!=null ? ln.list : null);
222
223 // System.err.println("Fetched "+reads);
224
225 if(reads!=null && !reads.isEmpty()){
226 Read r=reads.get(0);
227 assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
228 }
229
230 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
231
232 for(int idx=0; idx<reads.size(); idx++){
233 final Read r1=reads.get(idx);
234 final Read r2=r1.mate;
235
236 {
237 readsProcessed++;
238 basesProcessed+=r1.length();
239 }
240 if(r2!=null){
241 readsProcessed++;
242 basesProcessed+=r2.length();
243 }
244
245
246 boolean remove=false;
247 if(remove){reads.set(idx, null);}
248 }
249
250 if(ros!=null){ros.add(reads, ln.id);}
251
252 cris.returnList(ln);
253 ln=cris.nextList();
254 reads=(ln!=null ? ln.list : null);
255 }
256 if(ln!=null){
257 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
258 }
259 }
260
261 errorState|=ReadWrite.closeStreams(cris, ros);
262
263 t.stop();
264 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
265
266 if(errorState){
267 throw new RuntimeException("ReformatReads terminated in an error state; the output may be corrupt.");
268 }
269 }
270
271 /*--------------------------------------------------------------*/
272
273 Cluster fetchCluster(int x){
274 if(x>clusterList.size()){
275 synchronized(clusterList){
276 clusterList.ensureCapacity(2*x);
277 for(int i=clusterList.size(); i<x; i++){
278 clusterList.add(new Cluster(i, k1, k2, arraylen1, arraylen2));
279 }
280 clusterList.notifyAll();
281 }
282 }
283 Cluster c=clusterList.get(x);
284 while(c==null){
285 synchronized(clusterList){
286 c=clusterList.get(x);
287 assert(c!=null);
288 }
289 }
290 return c;
291 }
292
293 /**
294 * Creates clusters; Generates kmer spectra for clusters
295 * @param t
296 */
297 private void findKmerSpectra(Timer t){
298
299 /* Create read input stream */
300 final ConcurrentReadInputStream cris;
301 {
302 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2);
303 cris.start(); //4567
304 if(verbose){System.err.println("Started cris");}
305 }
306
307 /* Create ClusterThreads */
308 ArrayList<ClusterThread> alct=new ArrayList<ClusterThread>(THREADS);
309
310 for(int i=0; i<THREADS; i++){alct.add(new ClusterThread(i, CLUSTER_MODE_CREATE, -1, cris));}
311 for(ClusterThread ct : alct){ct.start();}
312
313 long readsIn=0, basesIn=0;
314
315 /* Wait for threads to die, and gather statistics */
316 for(ClusterThread ct : alct){
317 while(ct.getState()!=Thread.State.TERMINATED){
318 try {
319 ct.join();
320 } catch (InterruptedException e) {
321 // TODO Auto-generated catch block
322 e.printStackTrace();
323 }
324 }
325 readsIn+=ct.readsInT;
326 basesIn+=ct.basesInT;
327 }
328
329 /* Shut down I/O streams; capture error status */
330 errorState|=ReadWrite.closeStreams(cris);
331 }
332
333 /**
334 * Assign reads to clusters using additional kmer information.
335 * @param t
336 */
337 private void recluster(Timer t){
338
339 /* Create read input stream */
340 final ConcurrentReadInputStream cris;
341 {
342 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2);
343 cris.start(); //4567
344 if(verbose){System.err.println("Started cris");}
345 }
346
347 /* Create ClusterThreads */
348 ArrayList<ClusterThread> alct=new ArrayList<ClusterThread>(THREADS);
349 for(int i=0; i<THREADS; i++){alct.add(new ClusterThread(i, CLUSTER_MODE_RECLUSTER, ambigMode, cris));}
350 for(ClusterThread ct : alct){ct.start();}
351
352 long readsIn=0, basesIn=0;
353
354 /* Wait for threads to die, and gather statistics */
355 for(ClusterThread ct : alct){
356 while(ct.getState()!=Thread.State.TERMINATED){
357 try {
358 ct.join();
359 } catch (InterruptedException e) {
360 // TODO Auto-generated catch block
361 e.printStackTrace();
362 }
363 }
364 readsIn+=ct.readsInT;
365 basesIn+=ct.basesInT;
366 }
367
368 /* Shut down I/O streams; capture error status */
369 errorState|=ReadWrite.closeStreams(cris);
370 }
371
372 /*--------------------------------------------------------------*/
373
374 private class ClusterThread extends Thread{
375
376 public ClusterThread(int id_, int clusterMode_, int ambigMode_, ConcurrentReadInputStream cris_){
377 id=id_;
378 ambigModeT=ambigMode_;
379 clusterMode=clusterMode_;
380 cris=cris_;
381 }
382
383 @Override
384 public void run(){
385 randy=(ambigModeT==AMBIG_MODE_RAND) ? Shared.threadLocalRandom() : null;
386
387 ListNum<Read> ln=cris.nextList();
388 ArrayList<Read> reads=(ln!=null ? ln.list : null);
389
390 //While there are more reads lists...
391 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
392
393 //For each read (or pair) in the list...
394 for(int i=0; i<reads.size(); i++){
395 processRead(reads.get(i));
396 }
397
398 //Fetch a new read list
399 cris.returnList(ln);
400 ln=cris.nextList();
401 reads=(ln!=null ? ln.list : null);
402 }
403 cris.returnList(ln);
404 }
405
406
407 private void processRead(final Read r1){
408 final Read r2=r1.mate;
409
410 if(verbose){System.err.println("Considering read "+r1.id+" "+new String(r1.bases));}
411
412 readsInT++;
413 basesInT+=r1.length();
414 if(r2!=null){
415 readsInT++;
416 basesInT+=r2.length();
417 }
418
419 final ReadTag rt1=new ReadTag(r1);
420 final ReadTag rt2=(r2==null ? null : new ReadTag(r2));
421
422 r1.obj=rt1;
423 if(r2!=null){r2.obj=rt2;}
424
425 if(clusterMode==CLUSTER_MODE_CREATE){
426 addToCluster(r1, r2, rt1, rt2);
427 }else if(clusterMode==CLUSTER_MODE_RECLUSTER){
428 reCluster(r1, r2, rt1, rt2);
429 }else{
430 throw new RuntimeException("Unknown mode "+clusterMode);
431 }
432 }
433
434 private void addToCluster(Read r1, Read r2, ReadTag rt1, ReadTag rt2){
435 final int cn1=rt1.cluster0;
436 final int cn2=rt2==null ? cn1 : rt2.cluster0;
437 if(cn1==cn2){
438 Cluster c1=fetchCluster(cn1);
439 c1.add(r1);
440 c1.add(r2);
441 }else{
442 Cluster c1=fetchCluster(cn1);
443 Cluster c2=fetchCluster(cn2);
444 c1.add(r1);
445 c1.add(r2);
446 c2.add(r1);
447 c2.add(r2);
448 }
449 }
450
451 private void reCluster(Read r1, Read r2, ReadTag rt1, ReadTag rt2){
452
453 assert(false) : "TODO";
454
455 Cluster bestCluster1=null;
456 Cluster bestCluster2=null;
457
458 float bestScore1=-999999999, bestScore1_2=-999999999;
459 float bestScore2=-999999999, bestScore2_1=-999999999;
460
461 for(Cluster c : clusterList){
462
463 float score1=c.score(r1);
464 float score2=c.score(r2);
465
466 if(bestCluster1==null || score1>bestScore1){
467 bestCluster1=c;
468 bestScore1=score1;
469 bestScore1_2=score2;
470 }
471 if(bestCluster2==null || score2>bestScore2){
472 bestCluster2=c;
473 bestScore2=score2;
474 bestScore2_1=score1;
475 }
476 }
477
478 if(r2==null){
479 rt1.cluster1=bestCluster1.id;
480 }else if(bestCluster1==bestCluster2){
481 rt1.cluster1=rt2.cluster1=bestCluster1.id;
482 }else{
483 assert(r1!=null && r2!=null && bestCluster1!=bestCluster2);
484
485 float a=bestScore1+bestScore1_2;
486 float b=bestScore2+bestScore2_1;
487
488 if(ambigModeT==AMBIG_MODE_BEST){
489 if(a>=b){
490 rt1.cluster1=rt2.cluster1=bestCluster1.id;
491 }else{
492 rt1.cluster1=rt2.cluster1=bestCluster2.id;
493 }
494 }else if(ambigModeT==AMBIG_MODE_BOTH){
495 assert(false) : "TODO";
496 }else if(ambigModeT==AMBIG_MODE_TOSS){
497 rt1.cluster1=rt2.cluster1=-1;
498 }else if(ambigModeT==AMBIG_MODE_RAND){
499 if(a<0 || b<0){
500 float c=0-(Tools.min(a, b))*1.5f;
501 a=a+c;
502 b=a+c;
503 }
504 float coin=randy.nextFloat()*(a+b);
505 if(coin<=a){
506 rt1.cluster1=rt2.cluster1=bestCluster1.id;
507 }else{
508 rt1.cluster1=rt2.cluster1=bestCluster2.id;
509 }
510 }
511 }
512
513 }
514
515 final int id;
516 final int clusterMode;
517 final int ambigModeT;
518 final ConcurrentReadInputStream cris;
519
520 Random randy;
521
522 long readsInT;
523 long basesInT;
524
525 }
526
527 /*--------------------------------------------------------------*/
528
529 /*--------------------------------------------------------------*/
530
531 /*--------------------------------------------------------------*/
532
533 /*--------------------------------------------------------------*/
534
535 public boolean errorState=false;
536
537 final ArrayList<Cluster> clusterList=new ArrayList<Cluster>(256);
538
539 /** 'big' kmer */
540 public final int k1;
541 /** 'small' kmer */
542 public final int k2;
543
544 public final int arraylen1;
545 public final int arraylen2;
546
547 private String in1=null;
548 private String in2=null;
549
550 private String out1=null;
551 private String out2=null;
552
553 private String extin=null;
554 private String extout=null;
555
556 private boolean overwrite=true;
557 private boolean append=false;
558
559 private long maxReads=-1;
560
561 private int ambigMode=AMBIG_MODE_RAND;
562
563 private final FileFormat ffin1;
564 private final FileFormat ffin2;
565
566 private final FileFormat ffout1;
567 private final FileFormat ffout2;
568
569 private PrintStream outstream=System.err;
570
571 private int THREADS=Shared.threads();
572
573 /*--------------------------------------------------------------*/
574
575 public static boolean verbose=false;
576
577 public static final int CLUSTER_MODE_CREATE=0;
578 public static final int CLUSTER_MODE_RECLUSTER=1;
579 public static final int CLUSTER_MODE_REFINE=2;
580
581 public static final int AMBIG_MODE_BEST=0;
582 public static final int AMBIG_MODE_BOTH=1;
583 public static final int AMBIG_MODE_TOSS=2;
584 public static final int AMBIG_MODE_RAND=3;
585
586 }