Debian Codegraph @

current/var/GenerateVarlets2.java

raw symbols SCIP
1 package var;
2
3 import java.io.OutputStream;
4 import java.io.PrintWriter;
5 import java.util.ArrayList;
6 import java.util.HashMap;
7
8 import align2.MultiStateAligner9ts;
9 import align2.TranslateColorspaceRead;
10 import dna.Data;
11 import fileIO.ReadWrite;
12 import fileIO.TextFile;
13 import pacbio.CalcCoverageFromSites;
14 import pacbio.SiteR;
15 import shared.Parse;
16 import shared.Parser;
17 import shared.PreParser;
18 import shared.Shared;
19 import shared.Timer;
20 import shared.Tools;
21 import stream.ConcurrentLegacyReadInputStream;
22 import stream.RTextInputStream;
23 import stream.Read;
24 import stream.SiteScore;
25 import stream.SiteScoreR;
26 import structures.ListNum;
27
28 /** Splits output files across blocks for low memory usage */
29 public class GenerateVarlets2 {
30
31
32 public static void main(String[] args){
33
34 {//Preparse block for help, config files, and outstream
35 PreParser pp=new PreParser(args, new Object() { }.getClass().getEnclosingClass(), false);
36 args=pp.args;
37 //outstream=pp.outstream;
38 }
39
40 Data.GENOME_BUILD=-1;
41
42 String reads1=args[0];
43 String reads2=args[1].equalsIgnoreCase("null") ? null : args[1];
44 String outname=args[2];
45 // assert(outname.contains("#"));
46
47 String sitesfile=null;
48
49 byte minChrom=1;
50 byte maxChrom=1;
51 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
52
53
54 for(int i=3; i<args.length; i++){
55 final String arg=args[i];
56 final String[] split=arg.split("=");
57 String a=split[0].toLowerCase();
58 String b=split.length>1 ? split[1] : null;
59
60 if(Parser.parseZip(arg, a, b)){
61 //do nothing
62 }else if(a.equals("condense")){
63 CONDENSE=Parse.parseBoolean(b);
64 }else if(a.equals("condensesnps")){
65 CONDENSE_SNPS=Parse.parseBoolean(b);
66 }else if(a.startsWith("splitsubs")){
67 SPLIT_SUBS=Parse.parseBoolean(b);
68 }else if(a.equals("tosssolo1")){
69 TOSS_SOLO1=Parse.parseBoolean(b);
70 }else if(a.equals("tosssolo2")){
71 TOSS_SOLO2=Parse.parseBoolean(b);
72 }else if(a.startsWith("minchrom")){
73 minChrom=Byte.parseByte(b);
74 }else if(a.startsWith("maxchrom")){
75 maxChrom=Byte.parseByte(b);
76 }else if(a.startsWith("build") || a.startsWith("genomebuild") || a.startsWith("genome")){
77 Data.setGenome(Integer.parseInt(b));
78 System.out.println("Set GENOME_BUILD to "+Data.GENOME_BUILD);
79 }else if(a.equals("threads") || a.equals("t")){
80 THREADS=(Integer.parseInt(b));
81 }else if(a.startsWith("buffer") || a.startsWith("writebuffer")){
82 WRITE_BUFFER=(Integer.parseInt(b));
83 }else if(a.startsWith("maxreads")){
84 MAX_READS=(Long.parseLong(b));
85 }else if(a.equals("blocksize")){
86 BLOCKSIZE=(Integer.parseInt(b));
87 }else if(a.startsWith("sites") || a.startsWith("sitesfile")){
88 sitesfile=b;
89 }else{
90 throw new RuntimeException("Unknown parameter "+args[i]);
91 }
92 }
93 assert(minChrom<=maxChrom && minChrom>=0);
94 if(Data.GENOME_BUILD<0){throw new RuntimeException("Please set genome number.");}
95
96 if(ReadWrite.ZIPLEVEL<2){ReadWrite.ZIPLEVEL=2;}
97 GenerateVarlets2 gv=new GenerateVarlets2(reads1, reads2, outname, minChrom, maxChrom, MAX_READS, sitesfile);
98 gv.process();
99 }
100
101 public GenerateVarlets2(String fname1, String fname2, String outname_, byte minChrom, byte maxChrom, long maxReads, String sitesfile_){
102 this(new RTextInputStream(fname1, fname2, maxReads), outname_, minChrom, maxChrom, maxReads, sitesfile_);
103 assert(fname2==null || !fname1.equals(fname2)) : "Error - input files have same name.";
104 }
105
106 public GenerateVarlets2(RTextInputStream stream_, String outname_, byte minChrom, byte maxChrom, long maxReads, String sitesfile_){
107 sitesfile=sitesfile_;
108 stream=stream_;
109 outname=outname_;
110 assert(outname==null || outname.contains("#")) : "Output file name must contain the character '#' to be used for key number.";
111 makeKeyMap();
112
113 cris=(USE_CRIS ? new ConcurrentLegacyReadInputStream(stream, maxReads) : null);
114 if(CONDENSE_SNPS){assert(!SPLIT_SUBS);}
115 }
116
117 public void finish(){
118
119 ArrayList<Long> keys=new ArrayList<Long>();
120 keys.addAll(keymap.keySet());
121 Shared.sort(keys);
122 for(long k : keys){
123 ArrayList<Varlet> vars=keymap.remove(k);
124 if(!vars.isEmpty()){writeList(vars);}
125 }
126
127 if(cris!=null){ReadWrite.closeStream(cris);}
128 else{stream.close();}
129
130 }
131
132 public void process(){
133
134 Timer t=new Timer();
135
136 if(sitesfile!=null){
137 sitemap=loadSites(sitesfile);
138 }
139
140 cris.start();
141 ProcessThread[] threadHandles=new ProcessThread[THREADS];
142 for(int i=0; i<THREADS; i++){
143 threadHandles[i]=new ProcessThread();
144 threadHandles[i].start();
145 }
146
147 long varsMade=0;
148 long norefsMade=0;
149 long snpMade=0;
150 long delMade=0;
151 long subnMade=0;
152 long subdMade=0;
153 long subiMade=0;
154 long insMade=0;
155 long deltaLen=0;
156 long sitesProcessed=0;
157 long readsProcessed=0;
158
159 for(int i=0; i<threadHandles.length; i++){
160 ProcessThread pt=threadHandles[i];
161 while(!pt.finished()){
162 synchronized(pt){
163 try {
164 pt.wait(1000);
165 } catch (InterruptedException e) {
166 // TODO Auto-generated catch block
167 e.printStackTrace();
168 }
169 }
170 }
171 varsMade+=pt.varsMade;
172 norefsMade+=pt.norefsMade;
173 snpMade+=pt.snpMade;
174 delMade+=pt.delMade;
175 subnMade+=pt.subnMade;
176 subdMade+=pt.subdMade;
177 subiMade+=pt.subiMade;
178 insMade+=pt.insMade;
179 deltaLen+=pt.deltaLen;
180 sitesProcessed+=pt.sitesProcessed;
181 readsProcessed+=pt.readsProcessed;
182 }
183
184 finish();
185
186 t.stop();
187
188 System.out.println("\nOutput variations count");
189 System.out.println("Total (minus no-ref): \t"+(varsMade-norefsMade));
190 System.out.println("Deletions: \t"+(delMade));
191 System.out.println("D-type subs: \t"+(subdMade));
192 System.out.println("Insertions: \t"+(insMade));
193 System.out.println("I-type subs: \t"+(subiMade));
194 System.out.println("Snps: \t"+(snpMade));
195 System.out.println("N-type subs: \t"+(subnMade));
196 System.out.println("No-refs: \t"+(norefsMade));
197 System.out.println("Delta Length: \t"+(deltaLen));
198 System.out.println("Sites Processed: \t"+(sitesProcessed));
199 System.out.println("Reads Processed: \t"+(readsProcessed));
200 System.out.println();
201 System.out.println("Time:\t"+t);
202 }
203
204
205 /**
206 * @param sitesfile2
207 * @return
208 */
209 private static final HashMap<Long, SiteR> loadSites(String fname) {
210 HashMap<Long, SiteR> map=new HashMap<Long, SiteR>(4096);
211 TextFile tf=new TextFile(fname, false);
212
213 for(String s=tf.nextLine(); s!=null; s=tf.nextLine()){
214 SiteScoreR[] array=CalcCoverageFromSites.toSites(s);
215 for(SiteScoreR ssr : array){
216 SiteR sr=new SiteR(ssr);
217 Long key=sr.idPairnum;
218
219 SiteR head=map.get(key);
220 sr.next=head;
221 map.put(key, sr);
222 }
223
224 }
225 return map;
226 }
227
228
229 private void writeList(ArrayList<Varlet> list){
230 assert(list!=null && list.size()>0);
231 long key=key(list.get(0).chromosome, list.get(0).beginLoc);
232 String fname=fname(key, outname);
233 boolean allowSubprocess=false;
234 OutputStream os=ReadWrite.getOutputStream(fname, true, true, allowSubprocess);
235 PrintWriter pw=new PrintWriter(os);
236
237
238 for(Varlet v : list){
239 pw.println(v.toText());
240 }
241 ReadWrite.finishWriting(pw, os, fname, allowSubprocess);
242 }
243
244
245 private final class ProcessThread extends Thread {
246
247 public ProcessThread(){
248 }
249
250 @Override
251 public void run(){
252
253 final boolean processReads=true;
254 if(!processReads){System.err.println("Warning: Skipping read processing.");}
255
256 if(cris!=null){
257 ListNum<Read> ln=cris.nextList();
258 ArrayList<Read> reads=(ln!=null ? ln.list : null);
259
260 while(!terminate && reads!=null && reads.size()>0){
261 if(processReads){processReads(reads);}
262 cris.returnList(ln);
263 ln=cris.nextList();
264 reads=(ln!=null ? ln.list : null);
265 }
266 cris.returnList(ln);
267 }else{
268 ArrayList<Read> reads=stream.nextList();
269 while(!terminate && reads!=null && reads.size()>0){
270 if(processReads){processReads(reads);}
271 reads=stream.nextList();
272 }
273 }
274
275 finished=true;
276 synchronized(this){this.notifyAll();}
277 }
278
279 private void processReads(ArrayList<Read> reads){
280
281 if(sitemap==null){
282 for(Read r : reads){
283 Read r2=r.mate;
284 assert(r2==null || r.mate.mate==r);
285
286 if(r2==null){
287 processRead(r);
288 }else{
289 if(!TOSS_SOLO1 || r.paired()){processRead(r);}
290 if(!TOSS_SOLO2 || r2.paired()){processRead(r2);}
291 }
292 }
293 }else{
294 for(Read r : reads){
295 Read r2=r.mate;
296 assert(r2==null || r.mate.mate==r);
297
298 if(r2==null){
299 multiprocessRead(r);
300 }else{
301 if(!TOSS_SOLO1 || r.paired()){multiprocessRead(r);}
302 if(!TOSS_SOLO2 || r2.paired()){multiprocessRead(r2);}
303 }
304 }
305 }
306 }
307
308 @Deprecated
309 private void multiprocessRead_old(Read r){
310 long key=r.numericID;
311 if((r.pairnum()&1)==1){
312 key=-key;
313 assert(key<0);
314 }
315 if(true){throw new RuntimeException("Deprecated.");}
316 ArrayList<SiteScoreR> alssr=null;//sitemap.get(key);
317 if(alssr==null){return;}
318
319
320 for(SiteScoreR ssr : alssr){
321 SiteScore ss=find(ssr, r.sites);
322 assert(ss!=null) : "\nCan't find ssr "+ssr+" in read\n"+r+"\n";
323
324 r.clearSite();
325 r.setFromSite(ss);
326 r.match=null;
327
328 r.setPaired(ss.pairedScore>0);
329 r.setPerfect(ss.perfect);
330 r.setRescued(ss.rescued);
331
332 processRead(r);
333 }
334 }
335
336 private void multiprocessRead(Read r){
337 long key=r.numericID;
338 if((r.pairnum()&1)==1){
339 key=-key;
340 assert(key<0);
341 }
342
343
344 SiteR head=sitemap.get(key);
345 if(head!=null){readsProcessed++;}
346
347 // assert(head==null) : "\n"+r.pairnum()+", "+key+",\n"+r.list+",\n"+r.mate.list+"\n"+head.toTextRecursive(null)+"\n";
348
349 while(head!=null){
350 SiteScore ss=find(head, r.sites);
351 assert(ss!=null) : "\nCan't find sr "+head+" in read\n"+r+"\n";
352
353 r.clearSite();
354 r.setFromSite(ss);
355 r.match=null;
356
357 r.setPaired(ss.pairedScore>0);
358 r.setPerfect(ss.perfect);
359 r.setRescued(ss.rescued);
360
361 processRead(r);
362 SiteR old=head;
363 head=old.next;
364 old.next=null; //Clears up memory.
365 }
366 }
367
368 /**
369 * @param ssr
370 * @param list
371 * @return
372 */
373 private SiteScore find(SiteScoreR ssr, ArrayList<SiteScore> list) {
374 for(SiteScore ss : list){
375 if(ssr.equals(ss)){return ss;}
376 }
377 return null;
378 }
379
380 private SiteScore find(SiteR sr, ArrayList<SiteScore> list) {
381 for(SiteScore ss : list){
382 if(sr.equals(ss)){return ss;}
383 }
384 return null;
385 }
386
387
388 private void processRead(Read r){
389 sitesProcessed++;
390
391 boolean flag=false;
392 if(false && (/*r.numericID==30719442 || r.numericID==107055007 || */ r.numericID==42829556) /*&& r.length()<=35*/){
393 System.err.println("Processing read:");
394 System.err.println("\n"+r.toText(false));
395 System.err.println("\n"+r.strand());
396 System.err.println("\n");
397 System.err.println(new String(r.bases));
398 System.err.println(r.match==null ? "null" : new String(r.match));
399 System.err.println("\n");
400 tcr.verbose=true;
401 flag=true;
402 System.err.println("Mapped Length: "+(r.stop-r.start+1));
403 }
404
405
406 // if(r.chrom<1 && r.list!=null && r.list.size()>0){
407 // SiteScore ss=r.list.get(0); //Should not be necessary
408 // r.start=ss.start;
409 // r.stop=ss.stop;
410 // r.chrom=ss.chrom;
411 // r.setStrand(ss.strand);
412 // }
413 assert((r.chrom>=1)==r.mapped()) : r.toText(false);
414 if(!r.mapped()){//Unmapped.
415 assert(r.sites==null || r.sites.isEmpty()) : r.toText(false);
416 return;
417 }
418 if(r.invalid()){return;} //Probably trimmed too short to be used.
419
420 if(r.match!=null){
421 if(r.perfect()){//Hopefully this will be set correctly...
422 assert(TranslateColorspaceRead.perfectMatch(r.match));
423 return;
424 }else if(TranslateColorspaceRead.perfectMatch(r.match)){
425 return;
426 }
427 }
428
429 if(flag){
430 System.err.println("r.match = "+(r.match==null ? null : new String(r.match)));
431 System.err.println("Mapped Length: "+(r.stop-r.start+1));
432 }
433 // if(r.match!=null){
434 // for(int i=0; i<r.match.length; i++){
435 // if(r.match[i]=='I'){
436 // r.match=null;
437 // if(flag){System.err.println("nullified match string");}
438 // break;
439 // }
440 // }
441 // }
442
443 // r.match=null; //TODO - why are some match strings backwards?
444 if(r.match==null){
445 if(flag){
446 System.err.println("realigning match string");
447 System.err.println("Mapped Length: "+(r.stop-r.start+1));
448 }
449 tcr.realign_new(r, 20, true, 0, false); //Also generates the match string
450 if(TranslateColorspaceRead.perfectMatch(r.match)){return;}
451 if(flag){
452 System.err.println("new match string:\n"+(r.match==null ? null : new String(r.match)));
453 System.err.println("Mapped Length: "+(r.stop-r.start+1));
454 }
455 }
456 r.errors=r.estimateErrors();
457
458 if(r.match==null){
459 System.err.println("Could not align read "+r.numericID);
460 return;
461 }else if(r.match[0]=='X'){
462 System.err.println("Could not align read "+r.numericID+": "+new String(r.match));
463 return;
464 }
465
466 assert(CONDENSE);
467 ArrayList<Varlet> vars=tcr.toVars(r, CONDENSE, CONDENSE_SNPS, SPLIT_SUBS);
468
469 if(vars==null){return;}
470
471 // if(r.numericID==36858949){
472 // System.err.println(r.toText(false));
473 // System.err.println(r.copies);
474 // System.err.println(r.mate.toText(false));
475 // System.err.println(r.mate.copies);
476 // System.err.println();
477 //
478 // for(Varlet v : vars){
479 // System.err.println(v.toText());
480 // System.err.println(v.numReads);
481 // }
482 // assert(false);
483 // }
484
485 for(Varlet v : vars){
486 if(v.endDist>=MIN_END_DIST){
487 assert(v.numUniqueReads==1);
488 assert(v.numSemiUniqueReads==1);
489 assert(v.numPlusReads1+v.numMinusReads1+v.numPlusReads2+v.numMinusReads2==1);
490 assert(v.numReads>=1);
491 // assert(!TranslateColorspaceReadPacBio.COUNT_DUPLICATES_WHEN_MAKING_VARLETS || v.numReads==1);
492 assert(v.numReads==r.copies);
493 assert(v.readLen==r.length());
494 varsMade++;
495 if(v.varType==Variation.NOREF){norefsMade++;}
496 else if(v.varType==Variation.SNP){snpMade++;}
497 else if(v.varType==Variation.DEL){delMade++;}
498 else if(v.varType==Variation.INS){insMade++;}
499 else if(v.varType==Variation.DELINS){
500 int a=v.lengthRef();
501 int b=v.lengthVar();
502 if(a==b){subnMade++;}
503 else if(a>b){subdMade++;}
504 else{subiMade++;}
505 }
506 deltaLen+=v.lengthDif();
507 addVar(v);
508 }
509 }
510 // System.out.println(varsMade+", "+norefsMade);
511 }
512
513 /** TODO: Synchronize once per read, not once per varlet */
514 private void addVar(Varlet v){
515 long key=key(v.chromosome, v.beginLoc);
516 ArrayList<Varlet> list=keymap.get(key);
517 assert(list!=null) : "\nCan't find "+key+" in "+keymap.keySet()+"\n";
518 synchronized(list){
519 list.add(v);
520 if(list.size()>=WRITE_BUFFER){
521
522 if(MERGE_EQUAL_VARLETS){
523 mergeEqualVarlets(list);
524 }else{
525 Shared.sort(list);
526 }
527
528 writeList(list);
529 list.clear();
530 }
531 }
532 }
533
534 private void mergeEqualVarlets(ArrayList<Varlet> vars){
535
536 Shared.sort(vars);
537 ArrayList<Varlet> list=new ArrayList<Varlet>(8);
538 for(int i=0; i<vars.size(); i++){
539 Varlet a=vars.get(i);
540 vars.set(i, null);
541 Varlet b=(list.isEmpty() ? null : list.get(0));
542 if(b==null || a.equals(b)){
543 list.add(a);
544 }else{//purge
545 Varlet c=StackVariations.mergeEqualVarlets(list);
546 vars.set(i-1, c);
547 list.clear();
548 list.add(a);
549 }
550 }
551 if(!list.isEmpty()){
552 Varlet c=StackVariations.mergeEqualVarlets(list);
553 vars.set(list.size()-1, c);
554 }
555 Tools.condenseStrict(vars);
556 }
557
558 protected boolean finished(){return finished;}
559 protected void terminate(){terminate=true;}
560
561 private final TranslateColorspaceRead tcr=new TranslateColorspaceRead(PAC_BIO_MODE ?
562 new MultiStateAligner9ts(ALIGN_ROWS, ALIGN_COLUMNS) : new MultiStateAligner9ts(ALIGN_ROWS, ALIGN_COLUMNS));
563 private boolean finished=false;
564 private boolean terminate=false;
565 private long varsMade=0;
566 private long norefsMade=0;
567 private long snpMade=0;
568 private long delMade=0;
569 private long subnMade=0;
570 private long subdMade=0;
571 private long subiMade=0;
572 private long insMade=0;
573 private long deltaLen=0;
574 private long sitesProcessed=0;
575 private long readsProcessed=0;
576
577
578 }
579
580
581 protected static final long key(int chrom, int start){
582 long k=((long)chrom<<32)+(Tools.max(start, 0))/BLOCKSIZE;
583 return k;
584 }
585
586 protected static final long[] keys(final int chrom){
587 int lim=(Data.chromLengths[chrom]+1000)/BLOCKSIZE;
588 long[] keys=new long[lim+1];
589 for(int i=0; i<=lim; i++){
590 long key=key(chrom, i*BLOCKSIZE);
591 keys[i]=key;
592 }
593 return keys;
594 }
595
596 protected static final String fname(long key, String outname){
597 if(outname==null){outname="GV2TempFile_#.txt";}
598 assert(outname.contains("#")) : outname;
599 assert(!outname.endsWith(".gz") && !outname.endsWith(".zip") && !outname.endsWith(".bz2")) : outname;
600 return outname.replace("#", "b"+Data.GENOME_BUILD+"_"+key);
601 }
602
603 private final void makeKeyMap(){
604 final String header=Varlet.textHeader()+"\n";
605 keymap=new HashMap<Long, ArrayList<Varlet>>();
606 for(int chrom=1; chrom<=Data.numChroms; chrom++){
607 long[] keys=keys(chrom);
608 for(long key : keys){
609 keymap.put(key, new ArrayList<Varlet>(WRITE_BUFFER));
610 ReadWrite.writeString(header, fname(key, outname), false);
611 }
612 }
613 }
614
615 private HashMap<Long, ArrayList<Varlet>> keymap;
616
617 public final String outname;
618 public final String sitesfile;
619 // private HashMap<Long, ArrayList<SiteScoreR>> sitemap=null;
620 private HashMap<Long, SiteR> sitemap=null;
621 private final RTextInputStream stream;
622 private final ConcurrentLegacyReadInputStream cris;
623
624
625 public static boolean USE_CRIS=true; //Similar speed either way. "true" may be better with many threads.
626
627 public static int THREADS=7;
628 public static int WRITE_BUFFER=200000; //Bigger number uses more memory, for less frequent writes.
629
630 public static boolean CONDENSE=true;
631 public static boolean CONDENSE_SNPS=true;
632 public static boolean SPLIT_SUBS=false;
633
634 public static boolean TOSS_SOLO1=false;
635 public static boolean TOSS_SOLO2=false;
636
637 public static boolean MERGE_EQUAL_VARLETS=false;
638 public static boolean PAC_BIO_MODE=true;
639 public static int ALIGN_ROWS=2020;
640 public static int ALIGN_COLUMNS=3000;
641
642 public static long MAX_READS=-1;
643 public static final int MIN_END_DIST=4;
644 public static int BLOCKSIZE=1000000;
645
646 }