Debian Codegraph @

current/dna/Data.java

raw symbols SCIP
1 package dna;
2 import java.io.File;
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.PrintStream;
6 import java.net.URL;
7 import java.util.ArrayList;
8 import java.util.Arrays;
9 import java.util.HashMap;
10 import java.util.HashSet;
11 import java.util.concurrent.ConcurrentHashMap;
12
13 import align2.AbstractIndex;
14 import align2.AbstractMapper;
15 import align2.BBSplitter;
16 import align2.ChromLoadThread;
17 import align2.RefToIndex;
18 import driver.Search;
19 import fileIO.ChainBlock;
20 import fileIO.ChainLine;
21 import fileIO.ReadWrite;
22 import fileIO.TextFile;
23 import server.PercentEncoding;
24 import shared.Parse;
25 import shared.Primes;
26 import shared.Shared;
27 import shared.Tools;
28 import structures.ByteBuilder;
29 import structures.Range;
30 import var.Variation;
31
32 public class Data {
33
34
35 public static void main(String[] args){}
36
37
38 //TODO IMPORTANT! Ensure that this unloads everything big, AND that reloading subsequently works OK.
39 public static void unloadAll(){
40 chromosomePlusMatrix=null;
41 AbstractIndex.clear();
42 RefToIndex.clear();
43
44 AbstractMapper.minChrom=1;
45 AbstractMapper.maxChrom=Integer.MAX_VALUE;
46
47 numChroms=0;
48 numBases=0;
49 numDefinedBases=0;
50 numContigs=0;
51 numScaffolds=0;
52 interScaffoldPadding=0;
53 chromLengths=null;
54 chromDefinedBases=null;
55 chromUndefinedBases=null;
56 chromContigs=null;
57 chromScaffolds=null;
58 chromStartPad=null;
59
60 scaffoldNames=null;
61 scaffoldLocs=null;
62 scaffoldLengths=null;
63
64 BBSplitter.setCountTable=null;
65 BBSplitter.scafCountTable=null;
66 BBSplitter.streamTable=null;
67 BBSplitter.streamTableAmbiguous=null;
68
69 scaffoldNameTable=null;
70 genomeSource=null;
71 name=null;
72
73 GENOME_BUILD=-1;
74 genome_set_to=-1;
75 }
76
77
78 //TODO IMPORTANT! Ensure that this unloads everything big, AND that reloading subsequently works OK.
79 public static void unload(int chrom, boolean unloadSoft){
80
81 // unloadGenes(chrom);
82
83 chromosomePlusMatrix[chrom]=null;
84 }
85
86 public static void unloadGenes(int chrom){
87 geneMatrix[chrom]=null;
88 geneSetMatrix[chrom]=null;
89 geneTxRangeMatrix[chrom]=null;
90 geneSetRangeMatrix[chrom]=null;
91 geneCodeRangeMatrix[chrom]=null;
92 geneCodeAndExonRangeMatrix[chrom]=null;
93 geneNearbyRangeMatrix[chrom]=null;
94 exonRangeMatrix[chrom]=null;
95 }
96
97 public static byte find(int x, byte[] array){
98 for(byte i=0; i<array.length; i++){
99 if(array[i]==x){return i;}
100 }
101 return -1;
102 }
103
104 public static void reverse(byte[] array){
105 int mid=array.length/2;
106 for(int i=0; i<mid; i++){
107 byte temp=array[i];
108 array[i]=array[array.length-i-1];
109 array[array.length-i-1]=temp;
110 }
111 }
112
113
114 public static Gene[] getGenes(int chrom){
115 if(geneMatrix[chrom]==null){
116 loadGenes(chrom);
117 }
118 return geneMatrix[chrom];
119 }
120
121
122 public static Gene[] getGenes(int chrom, byte strand){
123 ArrayList<Gene> genes=new ArrayList<Gene>();
124 for(Gene g : getGenes(chrom)){
125 if(g.strand==strand){
126 genes.add(g);
127 }
128 }
129 return genes.toArray(new Gene[genes.size()]);
130 }
131
132
133 public static GeneSet[] getGeneSets(int chrom){
134 if(geneSetMatrix[chrom]==null){
135 loadGenes(chrom);
136 }
137 return geneSetMatrix[chrom];
138 }
139
140
141 public static HashMap<Integer, ArrayList<GeneSet>> getGeneIDTable(){
142 if(geneIDTable==null){
143
144 // System.err.println("WAITING FOR CS");
145 synchronized(GENEIDLOCK){
146 // System.err.println("ENTER CS");
147 if(geneIDTable==null){
148 // System.err.println("ENTER CS2");
149 HashMap<Integer, ArrayList<GeneSet>> temp=new HashMap<Integer, ArrayList<GeneSet>>(2048);
150 for(byte chrom=1; chrom<=25; chrom++){
151 GeneSet[] set=getGeneSets(chrom);
152 for(GeneSet gs : set){
153 int id=-1;
154 for(Gene g : gs.genes){
155 if(id==-1){id=g.id;}
156 else{assert(id==g.id) : gs+"\n"+gs.genes+"\n";}
157 }
158 assert(id>-1);
159 Integer key=Integer.valueOf(id);
160 ArrayList<GeneSet> value=temp.get(key);
161 // assert(old==null || chrom>22) : "\nCollision!\n\n"+gs+"\n\nis overwriting\n\n"+old;
162 if(value==null){
163 value=new ArrayList<GeneSet>(2);
164 temp.put(key, value);
165 }
166 value.add(gs);
167 }
168 }
169 // System.err.println("EXIT CS2");
170 geneIDTable=temp;
171 }
172 // System.err.println("EXIT CS");
173 }
174
175 }
176 // System.err.println("GeneIDTable contains "+geneIDTable.size()+" entries.");
177 return geneIDTable;
178 }
179
180 public static ChromosomeArray getChromosome(int chrom){
181 assert(chromosomePlusMatrix!=null);
182 assert(chromosomePlusMatrix.length>chrom) : chromosomePlusMatrix.length+", "+chrom;
183 if(chromosomePlusMatrix[chrom]==null){
184 synchronized(CHROMLOCKS[chrom%CHROMLOCKS.length]){
185 if(chromosomePlusMatrix[chrom]==null){loadChromosome(chrom);}
186 }
187 }
188 assert(chromosomePlusMatrix[chrom].array[0]=='N') : (char)chromosomePlusMatrix[chrom].array[0]+
189 "\nIf you see this message, please regenerate your index.\n"/*+new String(chromosomePlusMatrix[chrom].array)*/;//startpad was too low or for some reason invalid.
190 return chromosomePlusMatrix[chrom];
191 }
192
193 private static void loadGenes(int chrom){
194
195 if(geneMatrix[chrom]!=null){return;} //In case another thread already loaded the chromosome
196 synchronized(CHROMLOCKS[chrom%CHROMLOCKS.length]){
197 if(geneMatrix[chrom]==null){
198
199 // Gene[] genes=FindExons.readGenes(ROOT_GENE+"ref/chr"+chrom+".Ref.Table", Gene.FORMAT_NM);
200 // Gene[] genes=FindExons.readGenes(ROOT_GENE+"ref2/ccds-chr"+chrom+"-genes.txt", Gene.FORMAT_CCDS);
201 // Gene[] genes=FindExons.readGenes(ROOT_GENE+"ref3/ccds-chr"+chrom+"-genes.txt", Gene.FORMAT_CCDS);
202
203 // Gene[] genes=ReadWrite.readArray(Gene.class, ROOT_GENE+"seqGene/chr"+chrom+".ga");
204
205 String fname=ROOT_GENE+"Build"+GENOME_BUILD+"/"+GENE_MAP+"/chr"+chrom+".ga";
206
207 Gene[] genes=ReadWrite.readArray(Gene.class, fname, true);
208
209 Arrays.sort(genes);
210 // geneMatrix[chrom]=genes;
211
212 geneTxRangeMatrix[chrom]=findGeneRanges(genes, TX_RANGE);
213 geneCodeRangeMatrix[chrom]=findGeneRanges(genes, CODE_RANGE);
214 geneCodeAndExonRangeMatrix[chrom]=findCodeAndExonRanges(genes, false, true);
215 exonRangeMatrix[chrom]=findCodeAndExonRanges(genes, false, false);
216 geneNearbyRangeMatrix[chrom]=findCodeAndExonRanges(genes, true, true);
217
218 HashMap<String, ArrayList<Gene>> temp=new HashMap<String, ArrayList<Gene>>();
219 HashMap<String, GeneSet> gntable=new HashMap<String, GeneSet>();
220 HashMap<String, Gene> tntable=new HashMap<String, Gene>();
221
222 for(Gene g : genes){
223
224 String trkey=g.mrnaAcc;
225 if(trkey==null){trkey=g.chromosome+"_"+g.id;}
226 if(trkey!=null){
227 Gene old=tntable.get(trkey);
228 if(old!=null){
229 // stdout.println("For transcript '"+g.nameTranscript+"': Overwrote \n"+old+"\nwith\n"+g+"\n");
230 }
231 tntable.put(trkey, g);
232 }
233
234 String key=g.symbol;
235 if(key==null){key=g.mrnaAcc;}
236 ArrayList<Gene> list=temp.get(key);
237 if(list==null){
238 list=new ArrayList<Gene>(8);
239 temp.put(key, list);
240 }
241 list.add(g);
242 }
243
244 GeneSet[] gsm=new GeneSet[temp.size()];
245 String[] keys=temp.keySet().toArray(new String[temp.size()]);
246 for(int i=0; i<keys.length; i++){
247 String key=keys[i];
248 ArrayList<Gene> list=temp.get(key);
249 GeneSet gs=new GeneSet(key, list);
250 gsm[i]=gs;
251 gntable.put(key, gs);
252 }
253
254 geneNameTable[chrom]=gntable;
255 transcriptNameTable[chrom]=tntable;
256 geneSetMatrix[chrom]=gsm;
257 Arrays.sort(geneSetMatrix[chrom]);
258
259 geneSetRangeMatrix[chrom]=findGeneSetRanges(geneSetMatrix[chrom]);
260
261 {
262 assert(geneMatrix[chrom]==null) : "Need to sync.";
263 geneMatrix[chrom]=genes;
264 }
265 }
266 }
267 }
268
269 public static void loadChromosomes(int min, int max){
270 synchronized(CHROMLOCKS){
271 String pattern=chromFname(GENOME_BUILD);
272 ChromLoadThread.loadAll(pattern, min, max, chromosomePlusMatrix);
273 }
274 }
275
276 private static void loadChromosome(int chrom){
277 // assert(false);
278 assert(chromosomePlusMatrix[chrom]==null);
279 // assert(chrom>0) : chrom; //No longer valid since chrom 0 is now semi-allowed
280
281 String fname=chromFname(chrom, GENOME_BUILD);
282 sysout.println("Loading "+fname);
283 chromosomePlusMatrix[chrom]=ReadWrite.read(ChromosomeArray.class, fname, false);
284 assert(chromosomePlusMatrix[chrom].chromosome==chrom);
285 }
286
287 public static final String chromExtension(){
288 return ".chrom"+(CHROMGZ ? ".gz" : "");
289 }
290
291 public static final String chromFname(int chrom, int genome){
292 return ROOT_GENOME+genome+"/chr"+chrom+chromExtension();
293 }
294
295 public static final String chromFname(int genome){
296 return ROOT_GENOME+genome+"/chr#"+chromExtension();
297 }
298
299 public static Range[] findGeneRanges(Gene[] genes, final int mode){
300
301 ArrayList<Range> list=new ArrayList<Range>(8192);
302 ArrayList<Gene> glist=new ArrayList<Gene>(64);
303
304 Range current=null;
305 for(int i=0; i<genes.length; i++){
306 Gene g=genes[i];
307 Range r;
308
309 int a, b;
310
311 switch(mode){
312 case TX_RANGE: {a=g.txStart; b=g.txStop;}
313 break;
314
315 case CODE_RANGE: {a=g.codeStart; b=g.codeStop;}
316 break;
317
318 default: {throw new RuntimeException();}
319 }
320
321 if(b>=a){
322 r=new Range(a, b);
323
324 if(current==null){
325 current=r;
326 glist.add(g);
327 }else if(current.touches(r)){
328 current=current.merge(r);
329 glist.add(g);
330 }else{
331 current.obj1=glist.toArray(new Gene[glist.size()]);
332 glist.clear();
333 glist.add(g);
334 list.add(current);
335 current=r;
336 }
337 }
338 }
339 if(current!=null){ //i.e., if there were any genes
340 current.obj1=glist.toArray(new Gene[glist.size()]);
341 list.add(current);
342 }
343
344 return list.toArray(new Range[list.size()]);
345 }
346
347 public static Range[] findGeneSetRanges(GeneSet[] genes){
348
349 ArrayList<Range> list=new ArrayList<Range>(8192);
350 ArrayList<GeneSet> glist=new ArrayList<GeneSet>(64);
351
352 Range current=null;
353 for(int i=0; i<genes.length; i++){
354 GeneSet g=genes[i];
355 Range r;
356
357 int a=g.minStart-NEAR, b=g.maxEnd+NEAR;
358
359 if(b>=a){
360 r=new Range(a, b);
361
362 if(current==null){
363 current=r;
364 glist.add(g);
365 }else if(current.touches(r)){
366 current=current.merge(r);
367 glist.add(g);
368 }else{
369 current.obj1=glist.toArray(new GeneSet[glist.size()]);
370 glist.clear();
371 glist.add(g);
372 list.add(current);
373 current=r;
374 }
375 }
376 }
377 if(current!=null){ //i.e., if there were any genes
378 current.obj1=glist.toArray(new GeneSet[glist.size()]);
379 list.add(current);
380 }
381
382 return list.toArray(new Range[list.size()]);
383 }
384
385
386 public static Range[] findCodeAndExonRanges(Gene[] genes, boolean nearby, boolean codingOnly){
387
388
389 ArrayList<Range> list=new ArrayList<Range>(32768);
390
391 for(int i=0; i<genes.length; i++){
392 Gene g=genes[i];
393 Range r;
394
395 for(Exon ex : g.exons){
396
397 int a=ex.a, b=ex.b;
398
399 if(codingOnly){
400 a=max(ex.a, g.codeStart);
401 b=min(ex.b, g.codeStop);
402 }
403
404 assert(ex.a<=ex.b);
405 assert(g.codeStart<=g.codeStop+1) : g;
406
407 if(nearby){
408 a=a-NEAR;
409 b=b+NEAR;
410 }
411
412 if(a<=b){
413 r=new Range(a, b);
414 r.obj1=g;
415 // r.obj2=ex;
416 list.add(r);
417
418 }
419
420 }
421 }
422
423 ArrayList<Range> list2=new ArrayList<Range>(list.size());
424 Shared.sort(list);
425
426
427 HashSet<Gene> gset=new HashSet<Gene>(64);
428 Range current=null;
429 for(Range r : list){
430 if(current==null){
431 gset.add((Gene)r.obj1);
432 current=r;
433 }else if(current.touches(r)){
434 gset.add((Gene)r.obj1);
435 current=current.merge(r);
436 }else{
437 current.obj1=gset.toArray(new Gene[gset.size()]);
438 list2.add(current);
439 gset.clear();
440 gset.add((Gene)r.obj1);
441 current=r;
442 }
443 }
444
445 if(current!=null){
446 current.obj1=gset.toArray(new Gene[gset.size()]);
447 list2.add(current);
448 Shared.sort(list2);
449 }
450
451 return list2.toArray(new Range[list2.size()]);
452 }
453
454 public static Range[] geneSetRangeMatrix(int chrom){
455 if(geneSetRangeMatrix[chrom]==null){
456 loadGenes(chrom);
457 }
458 assert(geneSetRangeMatrix[chrom]!=null);
459 return geneSetRangeMatrix[chrom];
460 }
461
462 public static Range[] exonRangeMatrix(int chrom){
463 if(exonRangeMatrix[chrom]==null){
464 loadGenes(chrom);
465 }
466 assert(exonRangeMatrix[chrom]!=null);
467 return exonRangeMatrix[chrom];
468 }
469
470 public static Range[] geneCodeAndExonRangeMatrix(int chrom){
471 if(geneCodeAndExonRangeMatrix[chrom]==null){
472 loadGenes(chrom);
473 }
474 assert(geneCodeAndExonRangeMatrix[chrom]!=null);
475 return geneCodeAndExonRangeMatrix[chrom];
476 }
477
478 public static Range[] geneNearbyRangeMatrix(int chrom){
479 if(geneNearbyRangeMatrix[chrom]==null){
480 loadGenes(chrom);
481 }
482 assert(geneNearbyRangeMatrix[chrom]!=null);
483 return geneNearbyRangeMatrix[chrom];
484 }
485
486 public static HashMap<String, GeneSet> geneNameTable(int chrom){
487 if(geneNameTable[chrom]==null){
488 loadGenes(chrom);
489 }
490 assert(geneNameTable[chrom]!=null);
491 return geneNameTable[chrom];
492 }
493
494 public static HashMap<String, Gene> transcriptNameTable(int chrom){
495 if(transcriptNameTable[chrom]==null){
496 loadGenes(chrom);
497 }
498 assert(transcriptNameTable[chrom]!=null);
499 return transcriptNameTable[chrom];
500 }
501
502
503 public static GeneSet[] getNearestGeneSets(int chrom, int loc){
504 Range[] r=geneSetRangeMatrix(chrom);
505 int index=driver.Search.findPointBinary(loc, r);
506 GeneSet[] sets=(GeneSet[]) r[index].obj1;
507 if(sets==null || sets.length==0){
508 assert(false);
509 return null;
510 }
511 return sets;
512 }
513
514 /** Returns genesets overlapping the range */
515 public static GeneSet[] getNearestGeneSets(int chrom, int loc1, int loc2){
516 assert(loc2>=loc1);
517
518 // boolean flag=(chrom==21 && loc1<38540895 && loc2>38540895);//TODO UNDO
519 //
520 // if(flag){
521 // stdout.println(loc1+", "+loc2+", "+((loc1+loc2)/2));
522 // for(GeneSet gs : Data.geneNameTable[chrom].values()){
523 // if(gs.intersects(loc1, loc2)){
524 // stdout.println("%%% "+gs);
525 // }
526 // }
527 // }
528
529 Range[] ranges=geneSetRangeMatrix(chrom);
530 if(ranges==null || ranges.length==0){return null;}
531 int index=driver.Search.findPointBinary(loc1, ranges);
532
533
534 // if(flag){
535 // Range r0=ranges[index-1];
536 // Range r1=ranges[index];
537 // Range r2=ranges[index+1];
538 //
539 // stdout.println("r0: "+r0+"\n"+Arrays.toString((GeneSet[])r0.obj1)+"\n");
540 // stdout.println("r1: "+r1+"\n"+Arrays.toString((GeneSet[])r1.obj1)+"\n");
541 // stdout.println("r2: "+r2+"\n"+Arrays.toString((GeneSet[])r2.obj1)+"\n");
542 //
543 // }
544 // if(flag){stdout.println("c");}
545
546 Range r1=ranges[index];
547 Range r2=(index>=ranges.length-1 ? null : ranges[index+1]);
548
549 if(ranges[index].b>=loc2 || r2==null || r2.a>loc2){
550 return (GeneSet[])r1.obj1;
551 }
552
553 //// if(flag){stdout.println("e");}
554 // if(ranges[index].b>=loc2 || (index==ranges.length-1) || ranges[index+1].a>loc2){
555 //// if(flag){
556 //// stdout.println("f");
557 //// stdout.println(ranges[index].b<=loc2);
558 //// stdout.println((index==ranges.length-1));
559 //// stdout.println(ranges[index+1].a>loc2);
560 //// stdout.println(".......");
561 //// }
562 // return sets1;
563 // }
564
565 if(loc1>r1.b && loc2<r2.a){
566 //No-man's land: Return closer of the bounding ranges.
567 int dist1=loc1-r1.b;
568 int dist2=r2.a-loc2;
569 if(dist1>=dist2){
570 return (GeneSet[])r1.obj1;
571 }else{
572 return (GeneSet[])r2.obj1;
573 }
574 }
575
576 // assert(false) : "Test: This should be very rare, since it is slow.";
577
578 //Otherwise, return all overlapping ranges.
579 ArrayList<GeneSet> list=new ArrayList<GeneSet>(4);
580
581 while(index<ranges.length && ranges[index].b<loc1){index++;} //Spin until in range
582 for(; index<ranges.length && loc2>=ranges[index].a; index++){
583 // if(flag){stdout.println("ADDED RANGE "+ranges[index]);}
584 GeneSet[] gsa=(GeneSet[]) ranges[index].obj1;
585 for(GeneSet gs : gsa){list.add(gs);}
586 }
587 return list.toArray(new GeneSet[list.size()]);
588 }
589
590
591 public static boolean isExonic(byte chrom, int point, int thresh, boolean isCoding){
592 Range[] ranges=(isCoding ? Data.geneCodeAndExonRangeMatrix(chrom) : Data.exonRangeMatrix(chrom));
593 return Search.containsPointBinary(point, ranges, thresh);
594 }
595
596
597 public static final String padFront(String num, int width, String symbol){
598 String r=num;
599 while(r.length()<width){r=symbol+r;}
600 return r;
601 }
602
603 public static final String toBinaryString(long num, int width){
604 String r=Long.toBinaryString(num);
605 while(r.length()<width){r="0"+r;}
606 return r;
607 }
608
609 public static final String toString(double[][] a){
610 StringBuilder sb=new StringBuilder(256);
611 sb.append("[\n");
612 for(double[] b : a){
613 sb.append(" ").append(Arrays.toString(b)).append(",\n");
614 }
615 sb.append("]");
616 return sb.toString();
617 }
618
619 public static final <X> String toStringRecursive(Iterable<X> a){
620 if(a==null){return "null";}
621 StringBuilder sb=new StringBuilder(256);
622 String prefix="";
623 sb.append("[");
624 for(X x : a){
625 sb.append(toStringRecursive(a));
626 if(x!=null && x instanceof Iterable<?>){
627 sb.append("\n");
628 }else{
629 sb.append(", ");
630 }
631 }
632 sb.append("]");
633 return sb.toString();
634 }
635
636 public static final HashMap<String, Integer> geneNameToIdTable(){
637 if(geneNameToIdTable==null){
638 geneIdToNameTable();
639 assert(geneIdToNameTable!=null);
640 assert(geneNameToIdTable!=null);
641 }
642 return geneNameToIdTable;
643 }
644
645 public static final HashMap<Integer, String> geneIdToNameTable(){
646 if(geneIdToNameTable==null){
647
648 synchronized(GENEIDLOCK){
649 if(geneIdToNameTable==null){
650
651 // TextFile tf=new TextFile(ROOT_GENE+"gene_names_36.3.txt");
652 TextFile tf=new TextFile(ROOT_GENE+"gene_names_37.1.txt", false);
653 String[] lines=tf.toStringLines();
654 tf.close();
655 HashMap<Integer, String> table=new HashMap<Integer, String>((lines.length*3)/2);
656 for(String s : lines){
657 if(!s.startsWith("#")){
658 String[] line=s.split("\t", -1);
659 // assert(line.length==3) : "'"+s+"'";
660 if(line.length>=3){
661
662 int key=-1;
663 try {
664 key=Integer.parseInt(line[1]);
665 } catch (NumberFormatException e) {
666 System.err.println("Bad line: "+s);
667 throw new RuntimeException(e);
668 }
669
670 table.put(key, (line[2]==null || line[2].length()==0) ? line[1] : line[2]);
671 }
672 }
673 }
674
675 geneIdToNameTable=table;
676
677 HashMap<String, Integer> table2=new HashMap<String, Integer>((lines.length*3)/2);
678 for(Integer id : geneIdToNameTable.keySet()){
679 table2.put(geneIdToNameTable.get(id), id);
680 }
681 geneNameToIdTable=table2;
682 }
683 }
684 }
685 return geneIdToNameTable;
686 }
687
688
689 public static ChainLine[][] getChainLines(int from, int to){
690 if(from==36 && to==37){
691 if(chains36to37==null){
692 chains36to37=ChainBlock.loadChainLines(ROOT_CHAIN+"hg18ToHg19.over.chain");
693 }
694 return chains36to37;
695 }else if(from==37 && to==36){
696 if(chains37to36==null){
697 chains37to36=ChainBlock.loadChainLines(ROOT_CHAIN+"hg19ToHg18.over.chain");
698 }
699 return chains37to36;
700 }
701 throw new RuntimeException("Unknown chain file: "+from+" -> "+to);
702 }
703
704
705 public static final String toStringRecursive(Object a){
706 return a==null ? "null" : a.toString();
707 }
708
709 public static boolean isBaited(Variation v){
710 return isBaited(v, 0);
711 }
712
713 public static boolean isBaited(Variation v, int thresh){
714 int mid=(v.beginLoc+v.endLoc)/2;
715 int len=v.endLoc-v.beginLoc+1;
716 return isBaited(v.chromosome, mid, len/2+thresh);
717 }
718
719 public static boolean isBaited(int chrom, int point, int thresh){
720 if(BAITS==null){
721 BAITS=(int[][][]) ReadWrite.readObject("UNDEFINED_ROOT"+"baits_"+"BAIT_FILE"+"_build"+GENOME_BUILD+".int3d", false);
722 }
723 return isBaited(point, BAITS[chrom], thresh);
724 }
725
726 /** Is this point within "thresh" of a bait */
727 private static boolean isBaited(int point, int[][] baits, int thresh){
728
729 if(baits==null || baits[0].length==0){return false;}
730
731 int[] starts=baits[0];
732 int[] stops=baits[1];
733 int index=Arrays.binarySearch(stops, point);
734
735 if(index>=0){return true;} //Hit inside a bait
736 index=(-index)-1;
737
738 if(index>=stops.length){return point<=(stops[stops.length-1]+thresh);}
739
740 // if(index<0 || index>=stops.length){
741 // System.err.println(point+" in "+starts[0]+", "+stops[stops.length-1]+" -> "+index+"/"+(stops.length-1));
742 // }
743
744 final int a=point-thresh;
745 final int b=point+thresh;
746
747 if(overlap(a, b, starts[index], stops[index])){return true;}
748 for(int i=index+1; i<starts.length && b>=starts[i]; i++){
749 if(overlap(a, b, starts[i], stops[i])){return true;}
750 }
751 for(int i=index-1; i>=0 && a<=stops[i]; i++){
752 if(overlap(a, b, starts[i], stops[i])){return true;}
753 }
754 return false;
755 //
756 // return point>=(starts[index]-thresh) && point<=(stops[index]+thresh);
757 }
758
759 private static boolean overlap(int a1, int b1, int a2, int b2){
760 assert(a1<=b1 && a2<=b2) : a1+", "+b1+", "+a2+", "+b2;
761 return a2<=b1 && b2>=a1;
762 }
763
764
765 public static final synchronized void setGenome(int g){
766 assert(g>0) : "Genome build number must be at least 1.";
767 if(genome_set_to==g){return;}
768 if(genome_set_to<0){
769 setGenome2(g);
770 }else{
771 throw new RuntimeException("Changing genomes is not currently supported.");
772 }
773 }
774
775 private static final synchronized void setGenome2(int g){
776 assert(genome_set_to!=g);
777 GENOME_BUILD=g;
778 genome_set_to=g;
779 numChroms=-1;
780 numBases=-1;
781 numDefinedBases=-1;
782 numContigs=-1;
783 numScaffolds=-1;
784 name=null;
785 genomeSource=null;
786 scaffoldPrefixes=false;
787 long fastabytes=-1;
788 long fastatime=-1;
789 final int currentVersion=FastaToChromArrays2.currentVersion();
790 int version=0;
791
792 if(GENOME_BUILD==FastaToChromArrays2.LISTBUILD && FastaToChromArrays2.SUMMARY_LIST!=null){
793 for(int i=0; i<FastaToChromArrays2.SUMMARY_LIST.size(); i++){
794 final String s=FastaToChromArrays2.SUMMARY_LIST.get(i);
795 FastaToChromArrays2.SUMMARY_LIST.set(i, null);
796 if(s.charAt(0)=='#'){
797 if(s.startsWith("#Version")){
798 String[] split=s.split("\t");
799 version=(split.length>1 ? Integer.parseInt(split[1]) : 0);
800 }
801 }else{
802 String[] split=s.split("\t");
803 String a=split[0];
804 String b=split[1];
805 if(a.equalsIgnoreCase("chroms")){numChroms=(int)Long.parseLong(b);}
806 else if(a.equalsIgnoreCase("bases")){numBases=Long.parseLong(b);}
807 else if(a.equalsIgnoreCase("defined")){numDefinedBases=Long.parseLong(b);}
808 else if(a.equalsIgnoreCase("contigs")){numContigs=Integer.parseInt(b);}
809 else if(a.equalsIgnoreCase("scaffolds")){numScaffolds=Integer.parseInt(b);}
810 else if(a.equalsIgnoreCase("interpad")){interScaffoldPadding=Integer.parseInt(b);}
811 else if(a.equalsIgnoreCase("undefined")){}
812 else if(a.equalsIgnoreCase("name")){name=b;}
813 else if(a.equalsIgnoreCase("source")){genomeSource=b;}
814 else if(a.equalsIgnoreCase("bytes")){fastabytes=Long.parseLong(b);}
815 else if(a.equalsIgnoreCase("last modified")){fastatime=Long.parseLong(b);}
816 else if(a.equalsIgnoreCase("scafprefixes")){scaffoldPrefixes=Parse.parseBoolean(b);}
817 else{assert(version<currentVersion) : "In array: Unknown term "+s;}
818 }
819 }
820 FastaToChromArrays2.SUMMARY_LIST=null;
821 }else{
822 String s;
823 TextFile tf=new TextFile(ROOT_GENOME+GENOME_BUILD+"/summary.txt", false);
824 for(s=tf.nextLine(); s!=null; s=tf.nextLine()){
825 if(s.charAt(0)=='#'){
826 if(s.startsWith("#Version")){
827 String[] split=s.split("\t");
828 version=(split.length>1 ? Integer.parseInt(split[1]) : 0);
829 }
830 }else{
831 String[] split=s.split("\t");
832 String a=split[0];
833 String b=split[1];
834 if(a.equalsIgnoreCase("chroms")){numChroms=(int)Long.parseLong(b);}
835 else if(a.equalsIgnoreCase("bases")){numBases=Long.parseLong(b);}
836 else if(a.equalsIgnoreCase("defined")){numDefinedBases=Long.parseLong(b);}
837 else if(a.equalsIgnoreCase("contigs")){numContigs=Integer.parseInt(b);}
838 else if(a.equalsIgnoreCase("scaffolds")){numScaffolds=Integer.parseInt(b);}
839 else if(a.equalsIgnoreCase("interpad")){interScaffoldPadding=Integer.parseInt(b);}
840 else if(a.equalsIgnoreCase("undefined")){}
841 else if(a.equalsIgnoreCase("name")){name=b;}
842 else if(a.equalsIgnoreCase("source")){genomeSource=b;}
843 else if(a.equalsIgnoreCase("bytes")){fastabytes=Long.parseLong(b);}
844 else if(a.equalsIgnoreCase("last modified")){fastatime=Long.parseLong(b);}
845 else if(a.equalsIgnoreCase("scafprefixes")){scaffoldPrefixes=Parse.parseBoolean(b);}
846 else{assert(version<currentVersion) : "In file "+tf.name+": Unknown term "+s;}
847 }
848 }
849 tf.close();
850 }
851 if(numScaffolds==-1){numScaffolds=numChroms;}
852
853 if(version<currentVersion){
854 assert(false) : "The index format has changed in this version of BBTools. Please delete the /ref/ directory and re-index from the reference fasta," +
855 " or use an older version of BBTools.";
856 if(new File(ROOT_GENOME+GENOME_BUILD+"/info.txt").exists()){new File(ROOT_GENOME+GENOME_BUILD+"/info.txt").delete();}
857 if(new File(ROOT_GENOME+GENOME_BUILD+"/scaffolds.txt").exists()){new File(ROOT_GENOME+GENOME_BUILD+"/scaffolds.txt").delete();}
858 if(new File(ROOT_GENOME+GENOME_BUILD+"/scaffolds.txt.gz").exists()){new File(ROOT_GENOME+GENOME_BUILD+"/scaffolds.txt.gz").delete();}
859 sysout.println("Regenerating genome info in new format, version "+currentVersion+".");
860 dna.FastaToChromArrays2.writeInfo(GENOME_BUILD, numChroms, name, genomeSource, true, scaffoldPrefixes);
861 genome_set_to=-1;
862 setGenome2(g);
863 return;
864 }
865
866 assert(numChroms>0 || allowZeroSizedGenome) : "Genome "+g+": numChroms="+numChroms;
867 assert(numBases>0 || allowZeroSizedGenome) : "Genome "+g+": numBases="+numBases;
868 assert(numDefinedBases>0 || allowZeroSizedGenome) : "Genome "+g+": numDefinedBases="+numDefinedBases;
869 assert(numBases>=numDefinedBases) : "Genome "+g+": numBases>numDefinedBases : "+numBases+">"+numDefinedBases;
870
871 chromosomePlusMatrix=new ChromosomeArray[numChroms+1];
872 chromLengths=new int[numChroms+1];
873 chromDefinedBases=new int[numChroms+1];
874 chromUndefinedBases=new int[numChroms+1];
875 chromContigs=new int[numChroms+1];
876 chromStartPad=new int[numChroms+1];
877 chromScaffolds=new int[numChroms+1];
878
879 scaffoldNames=new byte[numChroms+1][][];
880 scaffoldLocs=new int[numChroms+1][];
881 scaffoldLengths=new int[numChroms+1][];
882
883 if(GENOME_BUILD==FastaToChromArrays2.LISTBUILD && FastaToChromArrays2.INFO_LIST!=null){
884 for(int i=0; i<FastaToChromArrays2.INFO_LIST.size(); i++){
885 final String s=FastaToChromArrays2.INFO_LIST.get(i);
886 FastaToChromArrays2.INFO_LIST.set(i, null);
887 if(s.charAt(0)=='#'){
888 if(s.startsWith("#Version")){
889 String[] split=s.split("\t");
890 version=(split.length>1 ? Integer.parseInt(split[1]) : 0);
891 }
892 }else{
893 assert(version==currentVersion);
894 String[] split=s.split("\t");
895 int chrom=Integer.parseInt(split[0]);
896 chromScaffolds[chrom]=Integer.parseInt(split[1]);
897 chromContigs[chrom]=(split.length>2 ? Integer.parseInt(split[2]) : -1);
898 chromLengths[chrom]=Integer.parseInt(split[3]);
899 chromDefinedBases[chrom]=Integer.parseInt(split[4]);
900 chromUndefinedBases[chrom]=(split.length>5 ? Integer.parseInt(split[5]) : -1);
901 chromStartPad[chrom]=(split.length>6 ? Integer.parseInt(split[6]) : -1);
902 // chromStopPad[chrom]=(split.length>7 ? Integer.parseInt(split[7]) : -1);
903
904 }
905 }
906 FastaToChromArrays2.INFO_LIST=null;
907 }else{
908 String s;
909 TextFile tf=new TextFile(ROOT_GENOME+GENOME_BUILD+"/info.txt", false);
910 for(s=tf.nextLine(); s!=null; s=tf.nextLine()){
911 if(s.charAt(0)=='#'){
912 if(s.startsWith("#Version")){
913 String[] split=s.split("\t");
914 version=(split.length>1 ? Integer.parseInt(split[1]) : 0);
915 }
916 }else{
917
918 if(version>=currentVersion){
919 String[] split=s.split("\t");
920 int chrom=Integer.parseInt(split[0]);
921 chromScaffolds[chrom]=Integer.parseInt(split[1]);
922 chromContigs[chrom]=(split.length>2 ? Integer.parseInt(split[2]) : -1);
923 chromLengths[chrom]=Integer.parseInt(split[3]);
924 chromDefinedBases[chrom]=Integer.parseInt(split[4]);
925 chromUndefinedBases[chrom]=(split.length>5 ? Integer.parseInt(split[5]) : -1);
926 chromStartPad[chrom]=(split.length>6 ? Integer.parseInt(split[6]) : -1);
927 // chromStopPad[chrom]=(split.length>7 ? Integer.parseInt(split[7]) : -1);
928 }else{
929 tf.close();
930 if(new File(ROOT_GENOME+GENOME_BUILD+"/info.txt").exists()){new File(ROOT_GENOME+GENOME_BUILD+"/info.txt").delete();}
931 if(new File(ROOT_GENOME+GENOME_BUILD+"/scaffolds.txt").exists()){new File(ROOT_GENOME+GENOME_BUILD+"/scaffolds.txt").delete();}
932 if(new File(ROOT_GENOME+GENOME_BUILD+"/scaffolds.txt.gz").exists()){new File(ROOT_GENOME+GENOME_BUILD+"/scaffolds.txt.gz").delete();}
933 sysout.println("Regenerating genome info in new format.");
934 dna.FastaToChromArrays2.writeInfo(GENOME_BUILD, numChroms, name, genomeSource, true, scaffoldPrefixes);
935 tf=new TextFile(ROOT_GENOME+GENOME_BUILD+"/info.txt", false);
936 }
937 }
938
939 }
940
941 tf.close();
942 }
943
944 String fname=ROOT_GENOME+GENOME_BUILD+"/scaffolds.txt.gz";
945 boolean hasList=(GENOME_BUILD==FastaToChromArrays2.LISTBUILD && FastaToChromArrays2.SCAF_LIST!=null);
946
947 if(!LOAD_SCAFFOLDS || (!hasList && !new File(fname).exists())){
948 for(int i=0; i<scaffoldNames.length; i++){
949 scaffoldNames[i]=new byte[][] {("chr"+i).getBytes()};
950 scaffoldLocs[i]=new int[] {chromStartPad[i]<0 ? 0 : chromStartPad[i]};
951 scaffoldLengths[i]=new int[] {chromLengths[i]};
952 if(!LOAD_SCAFFOLDS){chromScaffolds[i]=1;}
953
954 assert(chromScaffolds[i]==1) : "This appears to be an old index version. " +
955 "\nPlease regenerate it from the fasta file by rerunning this program,\nusing the ref=<reference file> and overwrite=true flags.\n"+i+", "+chromScaffolds[i];
956 }
957 }else{
958 for(int chrom=0; chrom<scaffoldNames.length; chrom++){
959 int num=chromScaffolds[chrom];
960 assert(chrom==0 || num>=1) : chrom+", "+num+", "+Arrays.toString(chromScaffolds);
961 if(num>0){
962 scaffoldNames[chrom]=new byte[num][];
963 scaffoldLocs[chrom]=new int[num];
964 scaffoldLengths[chrom]=new int[num];
965 }
966 }
967 int[] count=new int[numChroms+1];
968
969 if(hasList){
970
971 if(verbose){System.err.println("Fetching scaffold names from list:\n\n"+FastaToChromArrays2.SCAF_LIST+"\n\n");}
972
973 for(int i=0; i<FastaToChromArrays2.SCAF_LIST.size(); i++){
974 final String s=FastaToChromArrays2.SCAF_LIST.get(i);
975
976 if(verbose){System.err.println("Processing "+s);}
977
978 FastaToChromArrays2.SCAF_LIST.set(i, null);
979 if(s.charAt(0)=='#'){
980 if(verbose){System.err.println("Control string");}
981 if(s.startsWith("#Version")){
982 assert(version==currentVersion) : "Wrong index version; please delete /ref/genome/\n"+version+", "+currentVersion;
983 // String[] split=s.split("\t");
984 // version=(split.length>1 ? Integer.parseInt(split[1]) : 0);
985 // assert(version==currentVersion) : "Wrong version: "+version+", "+currentVersion;
986 }
987 }else{
988 String[] split=s.split("\t");
989 if(verbose){System.err.println("Split into "+Arrays.toString(split));}
990 int chrom=Integer.parseInt(split[0]);
991 int x=count[chrom];
992 count[chrom]++;
993
994 int scaffoldID=Integer.parseInt(split[1]);
995 scaffoldLocs[chrom][x]=Integer.parseInt(split[2]);
996 scaffoldLengths[chrom][x]=Integer.parseInt(split[3]);
997 scaffoldNames[chrom][x]=split[4].getBytes();
998 if(verbose){System.err.println("Set scaffoldNames["+chrom+"]["+x+" to "+(scaffoldNames[chrom][x]==null ? "null" : new String(scaffoldNames[chrom][x])));}
999 }
1000 }
1001 FastaToChromArrays2.SCAF_LIST=null;
1002 }else{
1003
1004 String s;
1005 TextFile tf=new TextFile(fname, false);
1006 for(s=tf.nextLine(); s!=null; s=tf.nextLine()){
1007 if(s.charAt(0)=='#'){
1008 if(s.startsWith("#Version")){
1009 assert(version==currentVersion) : "Wrong index version; please delete /ref/genome/\n"+version+", "+currentVersion;
1010 // String[] split=s.split("\t");
1011 // version=(split.length>1 ? Integer.parseInt(split[1]) : 0);
1012 // assert(version==currentVersion) : "Wrong version: "+version+", "+currentVersion;
1013 }
1014 }else{
1015 String[] split=s.split("\t");
1016 int chrom=Integer.parseInt(split[0]);
1017 int x=count[chrom];
1018 count[chrom]++;
1019
1020 int scaffoldID=Integer.parseInt(split[1]);
1021 scaffoldLocs[chrom][x]=Integer.parseInt(split[2]);
1022 scaffoldLengths[chrom][x]=Integer.parseInt(split[3]);
1023 scaffoldNames[chrom][x]=split[4].getBytes();
1024 }
1025
1026 }
1027
1028 tf.close();
1029 }
1030 }
1031
1032 // assert(false) : (numChroms+1)+", "+(scaffoldLengths==null)+", "+(scaffoldLengths[0]==null)+", "+(scaffoldLengths[1]==null);
1033
1034 // for(int i=1; i<scaffoldNames.length; i++){
1035 // stdout.println(Arrays.toString(scaffoldLocs[i]));
1036 // stdout.println(Arrays.toString(scaffoldLengths[i]));
1037 // stdout.println(Arrays.toString(scaffoldNames[i]));
1038 // }
1039
1040 }
1041
1042
1043 // public static String contigName(int x){return scaffoldName(x);}
1044 //
1045 // public static String scaffoldName(int x){
1046 // if(scaffoldNames==null){return "chr"+x;}
1047 // return scaffoldNames[x][0];
1048 // }
1049
1050 public static HashMap<String, ScafLoc> scafNameTable(){
1051
1052 if(GENOME_BUILD<0){
1053 assert(scaffoldNameTable==null);
1054 return null;
1055 }
1056 if(scaffoldNameTable!=null){return scaffoldNameTable;}
1057 synchronized(SCAFMAPLOCK){
1058 if(scaffoldNameTable!=null){return scaffoldNameTable;}
1059 scaffoldNameTable=new HashMap<String, ScafLoc>((int)Tools.min(2L*numScaffolds+10, 1000000000));
1060 for(int chrom=0; chrom<scaffoldNames.length; chrom++){
1061 if(scaffoldNames[chrom]!=null){
1062 for(int scafnum=0; scafnum<scaffoldNames[chrom].length; scafnum++){
1063 byte[] name=scaffoldNames[chrom][scafnum];
1064 if(name!=null){
1065 int loc=scaffoldLocs[chrom][scafnum];
1066 ScafLoc sc=new ScafLoc(new String(name), chrom, loc);
1067 scaffoldNameTable.put(sc.name, sc);
1068 }
1069 }
1070 }
1071 }
1072 }
1073 return scaffoldNameTable;
1074 }
1075
1076
1077 public static ScafLoc getScafLoc(byte[] name){
1078 HashMap<String, ScafLoc> map=scafNameTable();
1079 if(map==null){return null;}
1080 return map.get(new String(name));
1081 }
1082 public static ScafLoc getScafLoc(String name){
1083 HashMap<String, ScafLoc> map=scafNameTable();
1084 if(map==null){return null;}
1085 return map.get(name);
1086 }
1087
1088 public static byte[] scaffoldName(int chrom, int loc, int idx){return scaffoldNames[chrom][idx];}
1089 public static int scaffoldRelativeLoc(int chrom, int loc, int idx){return loc-scaffoldLocs[chrom][idx];}
1090
1091 public static int scaffoldIndex(int chrom, int loc){
1092 int[] array=scaffoldLocs[chrom];
1093 if(array==null || array.length<2){return 0;}
1094
1095 assert(interScaffoldPadding>0);
1096 loc=loc+interScaffoldPadding/2; //Puts it on closest scaffold if it is between scaffolds
1097
1098 int idx=Arrays.binarySearch(array, loc);
1099 if(idx>=0){return idx;} //Perfect hit
1100
1101 //Otherwise, return closest scaffold.
1102 int insertPoint=-1-idx;
1103 assert(insertPoint>=0 && insertPoint<=array.length);
1104 int r=max(0, insertPoint-1);
1105 assert(r>=0 && r<array.length);
1106 assert(r==0 || loc>array[r]);
1107 assert(r==array.length-1 || loc<array[r+1]);
1108 return r;
1109 }
1110
1111 /** TODO: This can be made faster */
1112 public static boolean isSingleScaffold(int chrom, int loc1, int loc2){
1113 assert(loc2>=loc1);
1114 if(scaffoldLocs==null){return true;}
1115 assert(chrom>=0 && chrom<scaffoldLocs.length) : chrom+", "+scaffoldLocs.length;
1116 int[] array=scaffoldLocs[chrom];
1117 if(array==null || array.length<2){return true;}
1118 assert(interScaffoldPadding>0);
1119
1120 int idx=Arrays.binarySearch(array, loc1+interScaffoldPadding);
1121 final int scaf;
1122 if(idx>=0){scaf=idx;} //Perfect hit
1123 else{
1124 int insertPoint=-1-idx;
1125 assert(insertPoint>=0 && insertPoint<=array.length);
1126 scaf=max(0, insertPoint-1);
1127 assert(scaf>=0 && scaf<array.length);
1128 assert(scaf==0 || loc1+interScaffoldPadding>array[scaf]);
1129 assert(scaf==array.length-1 || loc1+interScaffoldPadding<array[scaf+1]);
1130 }
1131 if(scaf==array.length-1){return true;}
1132
1133 int lowerBound=array[scaf]-interScaffoldPadding;
1134 int upperBound=array[scaf+1];
1135
1136 if(loc2<lowerBound || loc1>upperBound){return false;} //This could happen if a random read was generated in the start or stop padding.
1137 assert(scaf==0 || scaf==array.length-1 || (loc1>=lowerBound && loc1<upperBound)) :
1138 "chrom="+chrom+", loc1="+loc1+", lowerBound="+lowerBound+", loc2="+loc2+", upperBound="+upperBound;
1139 return loc2<upperBound;
1140 }
1141
1142 /** Returns overlap of these two points with the scaffold on which they are centered */
1143 public static int scaffoldOverlapLength(int chrom, int loc1, int loc2){
1144 assert(loc2>=loc1);
1145 int len=loc2-loc1+1;
1146 if(scaffoldLocs==null){return len;}
1147 int[] array=scaffoldLocs[chrom];
1148 if(array==null || array.length<2){return len;}
1149 assert(interScaffoldPadding>0);
1150
1151 int mid=loc1+(interScaffoldPadding+len)/2;
1152 int idx=Arrays.binarySearch(array, mid);
1153 final int scaf;
1154 if(idx>=0){scaf=idx;} //Perfect hit
1155 else{
1156 int insertPoint=-1-idx;
1157 assert(insertPoint>=0 && insertPoint<=array.length);
1158 scaf=max(0, insertPoint-1);
1159 assert(scaf>=0 && scaf<array.length);
1160 assert(scaf==0 || mid>array[scaf]);
1161 assert(scaf==array.length-1 || mid<array[scaf+1]) : "\nscaf="+scaf+", array.length="+array.length+"\n"+
1162 "loc1="+loc1+", loc2="+loc2+", mid="+mid+", interScaffoldPadding="+interScaffoldPadding+", "+array[scaf]+", "+array[scaf+1]+"\n"+
1163 (loc1+interScaffoldPadding)+", "+array[scaf+1];
1164 }
1165
1166 int lowerBound=array[scaf];
1167 int upperBound=lowerBound+scaffoldLengths[chrom][scaf];
1168 // assert(upperBound==array[scaf+1]) : lowerBound+", "+upperBound+", "+array[scaf+1]+", "+interScaffoldPadding; //This should fail.
1169
1170 return Tools.overlapLength(loc1, loc2, lowerBound, upperBound);
1171 }
1172
1173 public static void trimScaffoldNames(){
1174 if(scaffoldNames!=null){
1175 for(int i=0; i<scaffoldNames.length; i++){
1176 byte[][] matrix=scaffoldNames[i];
1177 if(matrix!=null){
1178 for(int j=0; j<matrix.length; j++){
1179 byte[] array=matrix[j];
1180 if(array!=null){
1181 for(int k=0; k<array.length; k++){
1182 if(Character.isWhitespace(array[k])){
1183 matrix[j]=Arrays.copyOf(array, k);
1184 break;
1185 }
1186 }
1187 }
1188 }
1189 }
1190 }
1191 }
1192 }
1193
1194 public static final String findPath(String fname){return findPath(fname, true);}
1195
1196 public static final String findPath(String fname, boolean warn){
1197 assert(fname!=null);
1198 if(fname.startsWith("?")){//Look in standard locations
1199 fname=fname.substring(1);
1200 }else{//Use this as the literal path
1201 return fname;
1202 }
1203 String path=ROOT+fname;
1204 boolean vb=false;
1205 {
1206 File f=new File(path);
1207 if(!f.exists()){
1208 if(vb){System.err.println("Did not find "+fname+" at "+path);}
1209 f=new File(ROOT);
1210 String res=f.getParent();
1211 if(res.length()>0 && !res.endsWith("/")){res=res+"/";}
1212 res=res+"resources/"+fname;
1213 f=new File(res);
1214 if(f.exists()){path=res;}
1215 else{if(vb){System.err.println("Did not find "+fname+" at "+res);}}
1216 }
1217 if(!f.exists()){
1218 if(vb){System.err.println("Considering fixing "+path+"\n"+path.contains("/file:"));}
1219 if(path.contains("/file:")){
1220 String fixed=path.substring(path.lastIndexOf("/file:")+1);
1221 f=new File(fixed);
1222 if(f.exists()){path=fixed;}
1223 else{if(vb){System.err.println("Did not find "+fname+" at "+fixed);}}
1224 }
1225 }
1226 if(!f.exists()){
1227 if(vb){System.err.println("Considering getResource");}
1228 URL url=Primes.class.getResource("/"+fname);
1229 if(url!=null){
1230 String temp=PercentEncoding.codeToSymbol(url.toString());
1231 if(vb){System.err.println("Found URL "+temp);}
1232 f=new File(temp);
1233 // if(f.exists()){fname=temp;}
1234 // else{System.err.println("Did not find "+fname+" at "+temp);}
1235 path=temp;
1236 }
1237 }
1238 if(!f.exists() && !path.startsWith("jar:")){
1239 String hardlink="/global/cfs/cdirs/bbtools/resources/"+fname;
1240 f=new File(hardlink);
1241 if(f.exists()){path=hardlink;}
1242 else{if(vb){System.err.println("Did not find "+fname+" at "+hardlink);}}
1243 }
1244 if(!f.exists() && !path.startsWith("jar:")){
1245 if(warn){
1246 System.err.println("Warning! Cannot find "+fname+" "+path);
1247 new Exception().printStackTrace();
1248 }
1249 return null;
1250 }
1251 }
1252 if(vb){System.err.println("Found "+fname+" at "+path);}
1253 return path;
1254 }
1255
1256 public static final int min(int x, int y){return x<y ? x : y;}
1257 public static final int max(int x, int y){return x>y ? x : y;}
1258
1259 public static final byte min(byte x, byte y){return x<y ? x : y;}
1260 public static final byte max(byte x, byte y){return x>y ? x : y;}
1261
1262 public static final long min(long x, long y){return x<y ? x : y;}
1263 public static final long max(long x, long y){return x>y ? x : y;}
1264
1265 public static final double min(double x, double y){return x<y ? x : y;}
1266 public static final double max(double x, double y){return x>y ? x : y;}
1267
1268 public static final float min(float x, float y){return x<y ? x : y;}
1269 public static final float max(float x, float y){return x>y ? x : y;}
1270
1271 public static int numChroms;
1272 public static long numBases;
1273 public static long numDefinedBases;
1274 public static int numContigs;
1275 public static int numScaffolds;
1276 public static int interScaffoldPadding;
1277 public static int[] chromLengths;
1278 public static int[] chromDefinedBases;
1279 public static int[] chromUndefinedBases;
1280 public static int[] chromContigs;
1281 public static int[] chromScaffolds;
1282 public static int[] chromStartPad;
1283
1284 public static boolean allowZeroSizedGenome=true;
1285
1286 public static byte[][][] scaffoldNames;
1287 public static int[][] scaffoldLocs;
1288 /** Does NOT include interScaffoldPadding */
1289 public static int[][] scaffoldLengths;
1290 /** Should be true if scaffold names have extra prefixes (for BBSplitter mode), false otherwise */
1291 public static boolean scaffoldPrefixes;
1292
1293 /** Allows translation of sam coordinates back to native coordinates */
1294 public static HashMap<String, ScafLoc> scaffoldNameTable;
1295
1296 public static String genomeSource;
1297 public static String name;
1298
1299 private static final GeneSet[][] geneSetMatrix=new GeneSet[63][];
1300 private static final Gene[][] geneMatrix=new Gene[63][];
1301 public static final Range[][] geneSetRangeMatrix=new Range[63][];
1302 public static final Range[][] geneTxRangeMatrix=new Range[63][];
1303 public static final Range[][] geneCodeRangeMatrix=new Range[63][];
1304 private static final Range[][] geneCodeAndExonRangeMatrix=new Range[63][];
1305 public static final Range[][] exonRangeMatrix=new Range[63][];
1306 public static HashMap<Integer, ArrayList<GeneSet>> geneIDTable;
1307
1308 /** Ranges within genes and exons or within NEAR their ends */
1309 public static final Range[][] geneNearbyRangeMatrix=new Range[63][];
1310
1311 public static ChromosomeArray[] chromosomePlusMatrix;
1312
1313 private static HashMap<Integer, String> geneIdToNameTable;
1314 private static HashMap<String, Integer> geneNameToIdTable;
1315
1316 private static final HashMap<String, GeneSet>[] geneNameTable=new HashMap[63];
1317 private static final HashMap<String, Gene>[] transcriptNameTable=new HashMap[63];
1318
1319 public static ChainLine[][] chains36to37;
1320 public static ChainLine[][] chains37to36;
1321
1322 public static int[][][] BAITS;
1323
1324 private static final int TX_RANGE=0;
1325 private static final int CODE_RANGE=1;
1326
1327
1328 public static final int NEAR=200;
1329
1330 public static String ROOT(){return ROOT;}
1331
1332
1333 /** Should be the same as ROOT_BASE but is found dynamically */
1334 private static String ROOT;
1335
1336 public static String ROOT_BASE;
1337 public static String ROOT_REF;
1338 public static String ROOT_GENOME;
1339 public static String ROOT_INDEX;
1340 public static String ROOT_GENE;
1341 public static String ROOT_CHAIN;
1342 public static String ROOT_TEMPDIR;
1343 public static String ROOT_CURRENT;
1344 public static String ROOT_QUALITY;
1345
1346 static{
1347 String s=new File(Data.class.getClassLoader().getResource(
1348 Data.class.getName().replace('.', '/') + ".class").getFile()).getAbsolutePath();
1349 s=PercentEncoding.codeToSymbol(s);
1350 ROOT=s.replace('\\', '/').replace("dna/Data.class", "");
1351 setPath(Shared.WINDOWS ? "?Shared.WINDOWS" : "?unix");
1352 if(!Shared.WINDOWS || true){setPath("?local");}
1353 }
1354
1355 public static void setPath(String path){
1356 // System.err.println("***"+path);
1357 if(path.indexOf('\\')>=0){path=path.replace('\\', '/');}
1358 String mode=(path==null ? "null" : path.toLowerCase());
1359 boolean local=mode.equals("?local") || mode.equals(".") || mode.equals("/.") || mode.equals("./");
1360 boolean win=mode.equals("?Shared.WINDOWS");
1361 boolean unix=mode.equals("?unix");
1362
1363 ROOT_CURRENT=System.getProperty("user.dir");
1364
1365 ROOT_BASE="";
1366 ROOT_REF="ref/";
1367 ROOT_GENOME=ROOT_REF+"genome/";
1368 ROOT_INDEX=ROOT_REF+"index/";
1369 ROOT_GENE=ROOT_REF+"genes/";
1370 ROOT_CHAIN=ROOT_REF+"chain/";
1371 ROOT_QUALITY=ROOT_REF+"qual/";
1372
1373 if(local){
1374 ROOT_TEMPDIR=ROOT_BASE;
1375 }else if(win){
1376 ROOT_TEMPDIR="C:/workspace/tempdir/";
1377 }else if(unix){
1378 String s=System.getenv().get("TEMPDIR");
1379 ROOT_TEMPDIR=(s==null ? ROOT_BASE : s+"/");
1380 }else if(!"null".equals(mode)){
1381 if(!path.endsWith("/")){path=path+"/";}
1382 ROOT_BASE=path;
1383 ROOT_REF=path+"ref/";
1384 ROOT_GENOME=ROOT_REF+"genome/";
1385 ROOT_INDEX=ROOT_REF+"index/";
1386 ROOT_GENE=ROOT_REF+"genes/";
1387 ROOT_CHAIN=ROOT_REF+"chain/";
1388 ROOT_QUALITY=ROOT_REF+"qual/";
1389 }else{
1390 ROOT_BASE=null;
1391 ROOT_REF=null;
1392 ROOT_GENOME=null;
1393 ROOT_GENE=null;
1394 ROOT_CHAIN=null;
1395 ROOT_QUALITY=null;
1396 ROOT_TEMPDIR=null;
1397 }
1398 }
1399
1400 public static final String VAR_FOLDER="VAR/";
1401 public static final String GENE_FOLDER="GENE/";
1402
1403 public static int GENOME_BUILD=-1;
1404 private static int genome_set_to=-1;
1405
1406 public static final boolean verbose=false;
1407
1408 /** seqGene, knownGene, refGene, unionGene, seqRefGene, ccs */
1409 public static String GENE_MAP="seqRefGene";
1410
1411 private static final String GENEIDLOCK=new String("GENEIDLOCK");
1412
1413 private static final String[] CHROMLOCKS=new String[256];
1414
1415 static{
1416 for(int i=0; i<CHROMLOCKS.length; i++){
1417 CHROMLOCKS[i]=new String(i+"");
1418 }
1419 }
1420
1421 private static final int INTERN_MAP_SIZE=20011; //Do NOT look up in primes; causes an init ordering issue.
1422 private static final int INTERN_MAP_LIMIT=(int)(INTERN_MAP_SIZE*0.75f);
1423
1424 private static final ConcurrentHashMap<String, String> INTERNMAP=new ConcurrentHashMap<String, String>(INTERN_MAP_SIZE);
1425 // public static final void unloadInternMap(){
1426 // INTERNMAP=new HashMap<String, String>(INTERN_MAP_SIZE);
1427 // }
1428
1429 public static final void intern(String[] s){
1430 if(s==null){return;}
1431 for(int i=0; i<s.length; i++){s[i]=intern(s[i]);}
1432 }
1433 public static String intern(String s){
1434 if(s==null || s.length()>25){return s;}
1435 // calls++;
1436 //
1437 // if(s.length()>0 && s.charAt(0)!='?'){
1438 // s=condense(s);
1439 // }
1440
1441 if(s.length()<2){
1442 // return s.intern();
1443 return forceIntern(s);
1444 }
1445 boolean acgtn=AminoAcid.containsOnlyACGTNQ(s);
1446
1447 if(acgtn){
1448 if(s.length()<4){
1449 // return s.intern();
1450 return forceIntern(s);
1451 }
1452 if(s.length()>6){
1453 return new String(s);
1454 }
1455 }
1456
1457 //Otherwise it is non-base string of length 2 to 20, or a base string of length 4 to 6.
1458 return forceIntern(s);
1459 }
1460
1461 public static String forceIntern(final String s0){
1462 assert(s0!=null);
1463 calls++;
1464
1465 // if(s.length()<2){return s.intern();}
1466 // boolean acgtn=AminoAcid.containsOnlyACGTNQ(s);
1467 //
1468 // if(acgtn){
1469 // if(s.length()<4){return s.intern();}
1470 // }
1471
1472 if(INTERNMAP.size()>INTERN_MAP_LIMIT){
1473 synchronized(INTERNMAP){
1474 if(INTERNMAP.size()>INTERN_MAP_LIMIT){
1475 // System.err.println("INTERNMAP overflow caused by "+s0);
1476 INTERNMAP.clear();
1477 }
1478 }
1479 }
1480 String s=INTERNMAP.putIfAbsent(s0, s0);
1481 return s==null ? s0 : s;
1482 }
1483 static int calls=0;
1484
1485 public static PrintStream sysout=System.err;//System.out;
1486
1487 public static boolean CHROMGZ=true;
1488 public static boolean LOAD_SCAFFOLDS=true;
1489
1490 // private static final boolean GUNZIP=testExecute("gunzip --help");
1491 // private static final boolean GZIP=testExecute("gzip --help");
1492 // private static final boolean SAMTOOLS=testExecute("samtools --help");
1493
1494 public static boolean GUNZIP(){return GUNZIP==0 ? GZIP() : GUNZIP>0;}
1495 // public static boolean UNPIGZ(){return UNPIGZ==0 ? PIGZ() : UNPIGZ>0;}
1496
1497 /**
1498 * Note:
1499 * Magic number of bgzip files is (first 4 bytes):
1500 * 1f 8b 08 04
1501 * 31 139 8 4
1502 * = 529205252
1503 *
1504 * gzip/pigz:
1505 * 1f 8b 08 00 (actually I've seen it as 1f 8b 08 08 also)
1506 * 31 139 8 0
1507 * = 529205248
1508 *
1509 * od --format=x1 --read-bytes=16 names.txt_gzip.gz
1510 */
1511 public static boolean BGZIP(){
1512 // System.err.println("Looking for bgzip.");
1513 if(BGZIP==0 && !Shared.WINDOWS){
1514 synchronized(SUBPROCSYNC){
1515 if(BGZIP==0){
1516 ByteBuilder bb=new ByteBuilder();
1517 BGZIP=testExecute("bgzip -h", bb);
1518
1519 try {
1520 if(BGZIP>0){
1521 String[] lines=bb.toString().split("\n");
1522 for(String line : lines){
1523 if(line.startsWith("Version:")){
1524 String[] split=line.split("\\s+");
1525 if(split.length>1){
1526 BGZIP_VERSION=split[1];
1527
1528 BGZIP_VERSION_threadsFlag=false;
1529 BGZIP_VERSION_levelFlag=false;
1530
1531 String[] ss=BGZIP_VERSION.split("[-\\.]");
1532
1533 // System.err.println(Arrays.toString("1.7-8".split("[-\\.]")));
1534
1535 int[] is=new int[3];
1536 for(int i=0; i<3 && i<ss.length; i++){
1537 String s=ss[i];
1538 int x=Integer.parseInt(s);
1539 is[i]=x;
1540 }
1541
1542 if(is[0]<1){
1543 //do nothing
1544 }else if(is[1]>=9){
1545 BGZIP_VERSION_threadsFlag=BGZIP_VERSION_levelFlag=true;
1546 }else if(is[1]>=4){
1547 BGZIP_VERSION_threadsFlag=true;
1548 }else if(is[1]>=3 && is[2]>=1){
1549 BGZIP_VERSION_threadsFlag=true;
1550 }
1551 }
1552 }
1553 }
1554 // System.err.println("Found BGZIP"+(BGZIP_VERSION==null ? "." : " "+BGZIP_VERSION));
1555 }else{
1556 // System.err.println("Could not find BGZIP.");
1557 }
1558 } catch (NumberFormatException e) {
1559 System.err.println("Warning - trouble parsing BGZIP version:\n"+BGZIP_VERSION);
1560 }
1561
1562 }
1563 }
1564 }
1565 // System.err.println("BGZIP="+BGZIP);
1566 // assert(BGZIP>0) : "bgzip not found.";
1567 return BGZIP>0;
1568 }
1569 public static boolean GZIP(){
1570 if(GZIP==0 && !Shared.WINDOWS){
1571 synchronized(SUBPROCSYNC){
1572 if(GZIP==0){
1573 ByteBuilder bb=new ByteBuilder();
1574 GZIP=testExecute("gzip --version", bb);
1575 }
1576 }
1577 }
1578 return GZIP>0;
1579 }
1580 public static boolean PIGZ(){
1581 if(PIGZ==0){
1582 synchronized(SUBPROCSYNC){
1583 if(PIGZ==0){
1584 ByteBuilder bb=new ByteBuilder();
1585 PIGZ=testExecute("pigz --version", bb);
1586
1587 try {
1588 if(PIGZ>0){
1589 String[] lines=bb.toString().split("\n");
1590 for(String line : lines){
1591 if(line.startsWith("pigz")){
1592 String[] split=line.split("\\s+");
1593 if(split.length>1){
1594 PIGZ_VERSION=split[1];
1595 PIGZ_VERSION_23plus=false;
1596 PIGZ_VERSION_231plus=false;
1597
1598 String[] ss=PIGZ_VERSION.split("\\.");
1599 int[] is=new int[3];
1600 for(int i=0; i<3 && i<ss.length; i++){
1601 String s=ss[i];
1602 int x=Integer.parseInt(s);
1603 is[i]=x;
1604 }
1605
1606 if(is[0]>2){
1607 PIGZ_VERSION_231plus=PIGZ_VERSION_23plus=true;
1608 }else if(is[0]==2){
1609 if(is[1]>3){
1610 PIGZ_VERSION_231plus=PIGZ_VERSION_23plus=true;
1611 }else if(is[1]==3){
1612 PIGZ_VERSION_23plus=true;
1613 if(is[2]>=1){
1614 PIGZ_VERSION_231plus=true;
1615 }
1616 }
1617 }
1618 }
1619 }
1620 }
1621 // System.err.println("Found pigz"+(PIGZ_VERSION==null ? "." : " "+PIGZ_VERSION));
1622 }else{
1623 // System.err.println("Could not find pigz.");
1624 }
1625 } catch (NumberFormatException e) {
1626 System.err.println("Warning - trouble parsing pigz version:\n"+PIGZ_VERSION);
1627 }
1628 }
1629 }
1630 }
1631 return PIGZ>0;
1632 }
1633 public static boolean DSRC(){
1634 if(DSRC==0){
1635 synchronized(SUBPROCSYNC){
1636 if(DSRC==0){
1637 ByteBuilder bb=new ByteBuilder();
1638 DSRC=testExecute("dsrc --version", bb);
1639 }
1640 }
1641 }
1642 return DSRC>0;
1643 }
1644 public static boolean BZIP2(){
1645 if(BZIP2==0 && !Shared.WINDOWS){
1646 synchronized(SUBPROCSYNC){
1647 if(BZIP2==0){
1648 ByteBuilder bb=new ByteBuilder();
1649 BZIP2=testExecute("bzip2 --version", bb);
1650 }
1651 }
1652 }
1653 return BZIP2>0;
1654 }
1655 public static boolean PBZIP2(){
1656 if(PBZIP2==0 && !Shared.WINDOWS){
1657 synchronized(SUBPROCSYNC){
1658 if(PBZIP2==0){
1659 ByteBuilder bb=new ByteBuilder();
1660 PBZIP2=testExecute("pbzip2 --version", bb);
1661 }
1662 }
1663 }
1664 return PBZIP2>0;
1665 }
1666 public static boolean LBZIP2(){
1667 if(LBZIP2==0 && !Shared.WINDOWS){
1668 synchronized(SUBPROCSYNC){
1669 if(LBZIP2==0){
1670 ByteBuilder bb=new ByteBuilder();
1671 LBZIP2=testExecute("lbzip2 --version", bb);
1672 }
1673 }
1674 }
1675 return LBZIP2>0;
1676 }
1677 public static boolean SAMTOOLS(){
1678 if(SAMTOOLS==0 && !Shared.WINDOWS){
1679 synchronized(SUBPROCSYNC){
1680 if(!USE_SAMTOOLS){SAMTOOLS=-1;}
1681 if(SAMTOOLS==0){
1682 ByteBuilder bb=new ByteBuilder();
1683 SAMTOOLS=testExecute("samtools", bb);
1684
1685 if(SAMTOOLS>0){
1686 String[] lines=bb.toString().split("\n");
1687 for(String line : lines){
1688 if(line.startsWith("Version:")){
1689 String[] split=line.split("\\s+");
1690 if(split.length>1){
1691 SAMTOOLS_VERSION=split[1];
1692 SAMTOOLS_VERSION_1x=SAMTOOLS_VERSION.startsWith("1.");
1693 }
1694 }
1695 }
1696 System.err.println("Found samtools"+(SAMTOOLS_VERSION==null ? "." : " "+SAMTOOLS_VERSION));
1697 }else{
1698 System.err.println("Could not find samtools.");
1699 }
1700 }
1701 }
1702 }
1703 return SAMTOOLS>0;
1704 }
1705 public static boolean SAMBAMBA(){
1706 if(SAMBAMBA==0 && !Shared.WINDOWS){
1707 synchronized(SUBPROCSYNC){
1708 if(!USE_SAMBAMBA){SAMBAMBA=-1;}
1709 if(SAMBAMBA==0){
1710 ByteBuilder bb=new ByteBuilder();
1711 SAMBAMBA=testExecute("sambamba -q", bb);
1712 if(SAMBAMBA>0){System.err.println("Found sambamba.");}else{System.err.println("Could not find sambamba.");}
1713 }
1714 }
1715 }
1716 return SAMBAMBA>0;
1717 }
1718 public static boolean SH(){
1719 if(SH==0 && !Shared.WINDOWS){
1720 synchronized(SUBPROCSYNC){
1721 if(SH==0){
1722 ByteBuilder bb=new ByteBuilder();
1723 SH=testExecute("sh --version", bb);
1724 }
1725 }
1726 // System.err.println(SH>0 ? "Found sh." : "Could not find sh.");
1727 if(SH<0){System.err.println("Could not find sh; won't launch I/O subprocesses.");}
1728 }
1729 return SH>0;
1730 }
1731 private static final String SUBPROCSYNC=new String("SUBPROCSYNC");
1732 private static final String SCAFMAPLOCK=new String("SCAFMAPLOCK");
1733
1734 /* Set these to zero to enable or -1 to disable */
1735 private static int GUNZIP=-1;
1736 // private static int UNPIGZ=0;
1737 private static int GZIP=0;
1738 private static int BGZIP=0;
1739 private static int PIGZ=0;
1740 private static int DSRC=0;
1741 private static int BZIP2=0;
1742 private static int PBZIP2=0;
1743 private static int LBZIP2=0;
1744 private static int SAMTOOLS=0;
1745 private static int SAMBAMBA=0;
1746 public static boolean USE_SAMTOOLS=true;
1747 public static boolean USE_SAMBAMBA=true;
1748 public static String SAMTOOLS_VERSION=null;
1749 public static boolean SAMTOOLS_VERSION_1x=true;
1750 public static String PIGZ_VERSION=null;
1751 public static boolean PIGZ_VERSION_231plus=false; //Allows -I flag
1752 public static boolean PIGZ_VERSION_23plus=false; //Allows -11 flag
1753 public static String BGZIP_VERSION=null;
1754 public static boolean BGZIP_VERSION_threadsFlag=false; //Allows -@ flag; not sure about the minimum version, but 1.4 is capable
1755 public static boolean BGZIP_VERSION_levelFlag=false; //Allows -l flag; not sure about the minimum version, but 1.9 is capable
1756 private static int SH=0;
1757
1758 private static int testExecute_old(String s, ByteBuilder bb){
1759 // System.err.println("Testing "+s);
1760 try {
1761 Process p=Runtime.getRuntime().exec(s);
1762 // System.err.println("Got process.");
1763
1764 InputStream stream=p.getErrorStream();
1765 if(bb==null){
1766 while(stream.read()>-1){}
1767 }else{
1768 bb.clear();
1769 for(int b=stream.read(); b>=0; b=stream.read()){
1770 bb.append((char)b);
1771 // System.err.print((char)b);
1772 // System.err.print(""+(int)b);
1773 }
1774 }
1775
1776 int exitValue=0;
1777 while(p.isAlive()){
1778 try {
1779 exitValue=p.waitFor();
1780 } catch (InterruptedException e) {
1781 // TODO Auto-generated catch block
1782 e.printStackTrace();
1783 }
1784 }
1785 if(exitValue>=126){return -1;}
1786
1787 // return p.exitValue()==0;
1788 // System.err.println("This system does has "+s+" installed.");
1789 } catch (IOException e) {
1790 // System.err.println("This system does not have "+s+" installed.");
1791 // TODO Auto-generated catch block
1792 // e.printStackTrace();
1793 return -1;
1794 }
1795 return 1;
1796 }
1797
1798 /** Georg Rath Version -
1799 * fixed by closing stdin and ensuring both stdout and stderr are consumed. */
1800 private static int testExecute(String s, ByteBuilder bb){
1801 // System.err.println("Testing "+s);
1802 try {
1803 ProcessBuilder pb = new ProcessBuilder(s.split("\\s+"));
1804 // System.err.println("Made builder.");
1805 pb.redirectErrorStream(true); //redirect to stdout
1806 // System.err.println("Redirected stderr.");
1807 Process p = pb.start();
1808 // System.err.println("Got process.");
1809 p.getOutputStream().close(); //close stdin
1810 // System.err.println("Closed stdin.");
1811 // InputStream stream=p.getErrorStream();
1812 InputStream stream=p.getInputStream(); //stdout
1813 // System.err.println("Grabbed stdout.");
1814
1815 if(bb==null){
1816 // System.err.println("Reading to null.");
1817 while(stream.read()>-1){}
1818 }else{
1819 // System.err.println("Reading to buffer.");
1820 bb.clear();
1821 for(int b=stream.read(); b>=0; b=stream.read()){
1822 bb.append((char)b);
1823 // System.err.print((char)b);
1824 // System.err.print(""+(int)b);
1825 }
1826 }
1827 // System.err.println("Finished reading.");
1828 int exitValue=0;
1829 while(p.isAlive()){
1830 try {
1831 exitValue=p.waitFor();
1832 } catch (InterruptedException e) {
1833 // TODO Auto-generated catch block
1834 e.printStackTrace();
1835 }
1836 }
1837 // System.err.println("Process terminated.");
1838 if(exitValue>=126){
1839 // System.err.println("Returning -1 due to 126.");
1840 return -1;
1841 }
1842 // return p.exitValue()==0;
1843 // System.err.println("This system has "+s+" installed.");
1844 } catch (IOException e) {
1845 // System.err.println("Returning -1 due to exception: "+e);
1846 // System.err.println("This system does not have "+s+" installed.");
1847 // TODO Auto-generated catch block
1848 // e.printStackTrace();
1849 return -1;
1850 }
1851 // System.err.println("Returning 1");
1852 return 1;
1853 }
1854
1855 }