Debian Codegraph @

current/var/GenerateVarlets.java

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