Debian Codegraph @

current/tax/TaxTree.java

raw symbols SCIP
1 package tax;
2
3 import java.io.PrintStream;
4 import java.io.Serializable;
5 import java.util.ArrayList;
6 import java.util.Arrays;
7 import java.util.HashMap;
8 import java.util.LinkedHashMap;
9 import java.util.List;
10 import java.util.regex.Pattern;
11
12 import fileIO.ByteFile;
13 import fileIO.ReadWrite;
14 import fileIO.TextFile;
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 structures.ByteBuilder;
22 import structures.IntHashMap;
23 import structures.IntList;
24 import structures.IntLongHashMap;
25
26 /**
27 * Represents a taxonomic tree.
28 * Usually just one of these needs to be created for a process.
29 * Designed for NCBI's taxdmp.zip file contents.
30 * @author Brian Bushnell
31 * @date Mar 6, 2015
32 *
33 */
34 public class TaxTree implements Serializable{
35
36 /**
37 *
38 */
39 private static final long serialVersionUID = 5894416521711540017L;
40
41 /*--------------------------------------------------------------*/
42 /*---------------- Main ----------------*/
43 /*--------------------------------------------------------------*/
44
45 /**
46 * Code entrance from the command line.
47 * This is not called normally, only when converting NCBI text files
48 * into a binary representation and writing it to disk.
49 * @param args Command line arguments
50 */
51 public static void main(String[] args){
52
53 {//Preparse block for help, config files, and outstream
54 PreParser pp=new PreParser(args, outstream, null, false);
55 args=pp.args;
56 outstream=pp.outstream;
57 }
58
59 assert(args.length>=4) : "TaxTree syntax:\ntaxtree.sh names.dmp nodes.dmp merged.dmp tree.taxtree.gz\n";
60 ReadWrite.USE_UNPIGZ=true;
61 ReadWrite.USE_PIGZ=true;
62 ReadWrite.ZIPLEVEL=(Shared.threads()>2 ? 11 : 9);
63 ReadWrite.PIGZ_BLOCKSIZE=256;
64 ReadWrite.PIGZ_ITERATIONS=60;
65
66 Timer t=new Timer();
67 TaxTree tree=new TaxTree(args);
68 t.stop();
69
70 outstream.println("Retained "+tree.nodeCount+" nodes:");
71
72 for(int i=tree.treeLevelsExtended.length-1; i>=0; i--){
73 outstream.print(tree.nodesPerLevelExtended[i]+"\t"+taxLevelNamesExtended[i]);
74 if(verbose){
75 int lim=10;
76 for(int j=0; j<lim && j<tree.treeLevelsExtended[i].length; j++){
77 TaxNode n=tree.treeLevelsExtended[i][j];
78 outstream.print("\n"+n+" -> "+tree.nodes[n.pid]);
79 }
80 for(int j=tree.treeLevelsExtended[i].length-lim; j<tree.treeLevelsExtended[i].length; j++){
81 if(j>=lim){
82 TaxNode n=tree.treeLevelsExtended[i][j];
83 outstream.print("\n"+n+" -> "+tree.nodes[n.pid]);
84 }
85 }
86 }
87 outstream.println();
88 }
89
90
91 outstream.println();
92 outstream.println("Time: \t"+t);
93
94 if(args.length>2){//Write a tree
95 ReadWrite.write(tree, args[3], true);
96 }
97 }
98
99 /** Parse arguments from the command line */
100 private Parser parse(String[] args){
101
102 //Create a parser object
103 Parser parser=new Parser();
104
105 //Set any necessary Parser defaults here
106 //parser.foo=bar;
107
108 //Parse each argument
109 for(int i=0; i<args.length; i++){
110 String arg=args[i];
111
112 //Break arguments into their constituent parts, in the form of "a=b"
113 String[] split=arg.split("=");
114 String a=split[0].toLowerCase();
115 String b=split.length>1 ? split[1] : null;
116 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
117
118 if(a.equals("verbose")){
119 verbose=Parse.parseBoolean(b);
120 }else if(a.equals("parse_flag_goes_here")){
121 long fake_variable=Parse.parseKMG(b);
122 //Set a variable here
123 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
124 //do nothing
125 }else if(i>3){
126 outstream.println("Unknown parameter "+args[i]);
127 assert(false) : "Unknown parameter "+args[i];
128 }
129 }
130
131 return parser;
132 }
133
134 /*--------------------------------------------------------------*/
135 /*---------------- Initialization ----------------*/
136 /*--------------------------------------------------------------*/
137
138 /*--------------------------------------------------------------*/
139 /*---------------- Constructors ----------------*/
140 /*--------------------------------------------------------------*/
141
142 /**
143 * Constructor using filenames from command line arguments, in the format of:
144 * {names, nodes, merged}
145 * @param args Command line arguments
146 */
147 private TaxTree(String[] args){
148 this(args[0], args[1], args[2], args);
149 }
150
151 /**
152 * @param namesFile NCBI names.txt
153 * @param nodesFile NCBI nodes.txt
154 * @param mergedFile NCBI merged.txt
155 * @param args
156 */
157 private TaxTree(String namesFile, String nodesFile, String mergedFile, String[] args){
158
159 if(args!=null) {
160 Parser parser=parse(args);
161 }
162
163 nodes=getNames(namesFile);
164 getNodes(nodesFile, nodes);
165
166 mergedMap=getMerged(mergedFile);
167
168 countChildren();
169 outstream.println("Counted children.");
170 int rounds=percolate();
171 outstream.println("Percolated "+rounds+" rounds to fixpoint.");
172
173 if(assignStrains){
174 assignStrains();
175 rounds=percolate();
176 outstream.println("Percolated "+rounds+" rounds to fixpoint.");
177 }
178
179 if(simplify){
180 if(verbose){outstream.println("Simplifying.");}
181 int removed=simplify(nodes);
182 if(verbose){outstream.println("Removed "+removed+" nodes.");}
183 rounds=percolate();
184 outstream.println("Percolated "+rounds+" rounds to fixpoint.");
185 }
186 int errors=test(nodes);
187 // assert(errors==0); //Not possible since the tree is wrong.
188 if(errors>0) {
189 System.err.println("Found "+errors+" errors in tree.");
190 }
191
192 for(TaxNode n : nodes){
193 if(n!=null){
194 nodesPerLevel[n.level]++;
195 nodesPerLevelExtended[n.levelExtended]++;
196 }
197 }
198
199 // for(int i=0; i<nodesPerLevel.length; i++){
200 // treeLevels[i]=new TaxNode[nodesPerLevel[i]];
201 // }
202 for(int i=0; i<nodesPerLevelExtended.length; i++){
203 treeLevelsExtended[i]=new TaxNode[nodesPerLevelExtended[i]];
204 }
205
206 // {
207 // int[] temp=new int[nodesPerLevel.length];
208 // for(TaxNode n : nodes){
209 // if(n!=null){
210 // int level=n.level;
211 // treeLevels[level][temp[level]]=n;
212 // temp[level]++;
213 // }
214 // }
215 // }
216
217 {
218 int[] temp=new int[nodesPerLevelExtended.length];
219 for(TaxNode n : nodes){
220 if(n!=null){
221 int level=n.levelExtended;
222 treeLevelsExtended[level][temp[level]]=n;
223 temp[level]++;
224 }
225 }
226 }
227 nodeCount=(int)shared.Vector.sum(nodesPerLevelExtended);
228
229 }
230
231 /*--------------------------------------------------------------*/
232 /*--------------- Loaders ----------------*/
233 /*--------------------------------------------------------------*/
234
235
236 /**
237 * Load a tax tree from disk.
238 * @param taxTreeFile Serialized TaxTree.
239 * @param hashNames Hash nodes using names as keys
240 * @param hashDotFormat Hash nodes using abbreviations, e.g. H.sapiens
241 * @return
242 */
243 public static final TaxTree loadTaxTree(String taxTreeFile, PrintStream outstream, boolean hashNames,
244 boolean hashDotFormat){
245 if(taxTreeFile==null){return null;}
246 return loadTaxTree(taxTreeFile, null, null, null, outstream, hashNames, hashDotFormat);
247 }
248
249 /**
250 * Load a tax tree from disk, either from a binary tree file,
251 * or from NCBI text files.
252 * @param taxTreeFile Binary representation; mutually exclusive with other files.
253 * @param taxNameFile NCBI names.txt
254 * @param taxNodeFile NCBI nodes.txt
255 * @param taxMergedFile NCBI merged.txt
256 * @param hashNames Hash nodes using names as keys
257 * @param hashDotFormat Hash nodes using abbreviations, e.g. H.sapiens
258 * @return The loaded tree
259 */
260 public static final TaxTree loadTaxTree(String taxTreeFile, String taxNameFile, String taxNodeFile,
261 String taxMergedFile, PrintStream outstream, boolean hashNames, boolean hashDotFormat){
262 if(taxTreeFile!=null || taxNodeFile==null){
263 TaxTree tree=sharedTree(taxTreeFile, hashNames, hashDotFormat, outstream);
264 if(tree!=null){return tree;}
265 }
266 if("auto".equalsIgnoreCase(taxTreeFile)){taxTreeFile=defaultTreeFile();}
267 assert(taxTreeFile!=null || (taxNameFile!=null && taxNodeFile!=null)) : "Must specify both taxname and taxnode files.";
268 Timer t=new Timer();
269 if(outstream!=null){outstream.print("\nLoading tax tree; ");}
270 final TaxTree tree;
271 if(taxTreeFile!=null){
272 tree=ReadWrite.read(TaxTree.class, taxTreeFile, true);
273 }else{
274 tree=new TaxTree(taxNameFile, taxNodeFile, taxMergedFile, null);
275 }
276 t.stop();
277 if(hashNames){
278 if(outstream!=null){outstream.println("Hashing names.");}
279 tree.hashNames(hashDotFormat);
280 }
281 if(outstream!=null){
282 outstream.println("Time: \t"+t);
283 Shared.printMemory();
284 outstream.println();
285 }
286 if(ALLOW_SHARED_TREE){sharedTree=tree;}
287 return tree;
288 }
289
290 /*--------------------------------------------------------------*/
291 /*--------------- Constructor Helpers ----------------*/
292 /*--------------------------------------------------------------*/
293
294 /**
295 * Finds unranked nodes in the archaeal and bacterial kingdoms.
296 * If these are below species level, have a ranked parent,
297 * and have no ranked children, they are assigned strain or substrain.
298 */
299 private void assignStrains(){
300
301 outstream.println("Assigning strains.");
302 int strains=0, substrains=0;
303 TaxNode bacteria=getNode(BACTERIA_ID); //Can't do a name lookup since the names are not hashed yet
304 TaxNode archaea=getNode(ARCHAEA_ID);
305 assert(bacteria.name.equalsIgnoreCase("Bacteria"));
306 assert(archaea.name.equalsIgnoreCase("Archaea"));
307
308 ArrayList<TaxNode> bactList=new ArrayList<TaxNode>();
309 ArrayList<TaxNode> archList=new ArrayList<TaxNode>();
310 for(TaxNode tn : nodes){
311 if(tn!=null && tn.originalLevel()==NO_RANK && tn.minParentLevelExtended<=SPECIES_E){
312 if(descendsFrom(tn, bacteria)){
313 bactList.add(tn);
314 }else if(descendsFrom(tn, archaea)){
315 archList.add(tn);
316 }
317 }
318 }
319
320 ArrayList<TaxNode> prokList=new ArrayList<TaxNode>(bactList.size()+archList.size());
321 prokList.addAll(bactList);
322 prokList.addAll(archList);
323
324 for(TaxNode tn : prokList){
325 if(tn.maxDescendantLevelIncludingSelf()==NO_RANK){
326 TaxNode parent=nodes[tn.pid];
327 if(parent.levelExtended==SPECIES_E || parent.levelExtended==SUBSPECIES_E){
328 tn.levelExtended=STRAIN_E;
329 tn.level=SUBSPECIES;
330 tn.setOriginalLevel(STRAIN_E);
331 strains++;
332 }
333 }
334 }
335
336 // outstream.println("Assigned "+strains+" strains.");
337 for(TaxNode tn : prokList){
338 if(tn.maxDescendantLevelIncludingSelf()==NO_RANK){
339 TaxNode parent=nodes[tn.pid];
340 if(parent.levelExtended==STRAIN_E){
341 tn.levelExtended=SUBSTRAIN_E;
342 tn.level=SUBSPECIES;
343 tn.setOriginalLevel(SUBSTRAIN_E);
344 substrains++;
345 }
346 }
347 }
348 // outstream.println("Assigned "+substrains+" substrains.");
349 }
350
351 @Deprecated
352 private void assignStrainsOld(){
353
354 outstream.println("Assigning strains.");
355 int strains=0, substrains=0;
356 TaxNode bacteria=getNode(BACTERIA_ID); //Can't do a name lookup since the names are not hashed
357 assert(bacteria.name.equalsIgnoreCase("Bacteria"));
358 for(TaxNode tn : nodes){
359 if(tn!=null && tn.originalLevel()==NO_RANK){
360 TaxNode parent=nodes[tn.pid];
361 if(parent.levelExtended==SPECIES_E && commonAncestor(parent, bacteria)==bacteria){
362 // nodesPerLevelExtended[STRAIN_E]++;
363 // nodesPerLevelExtended[tn.levelExtended]--;
364 tn.levelExtended=STRAIN_E;
365 tn.level=SUBSPECIES;
366 tn.setOriginalLevel(STRAIN_E);
367 strains++;
368 }
369 }
370 }
371 // outstream.println("Assigned "+strains+" strains.");
372 for(TaxNode tn : nodes){
373 if(tn!=null && tn.originalLevel()==NO_RANK){
374 TaxNode parent=nodes[tn.pid];
375 if(parent.levelExtended==STRAIN_E && commonAncestor(parent, bacteria)==bacteria){
376 // nodesPerLevelExtended[SUBSTRAIN_E]++;
377 // nodesPerLevelExtended[tn.levelExtended]--;
378 tn.levelExtended=SUBSTRAIN_E;
379 tn.level=SUBSPECIES;
380 tn.setOriginalLevel(SUBSTRAIN_E);
381 substrains++;
382 }
383 }
384 }
385 // outstream.println("Assigned "+substrains+" substrains.");
386 }
387
388 /*--------------------------------------------------------------*/
389 /*---------------- Construction ----------------*/
390 /*--------------------------------------------------------------*/
391
392 /**
393 * Create tax nodes using names in the designated file.
394 * @param fname NCBI names.txt
395 * @return Array of created nodes, where array[x] contains the node with TaxID x.
396 */
397 private static TaxNode[] getNames(String fname){
398 ArrayList<TaxNode> list=new ArrayList<TaxNode>(200000);
399 int max=0;
400
401 TextFile tf=new TextFile(fname, false);
402 for(String s=tf.nextLine(); s!=null; s=tf.nextLine()){
403 if(s.contains("scientific name")){
404 String[] split=delimiter.split(s, 3);
405 assert(split.length==3) : s;
406 int id=Integer.parseInt(split[0]);
407 String name=split[1];
408 if(id==1 && name.equalsIgnoreCase("root")){name="Life";}
409 max=Tools.max(max, id);
410 list.add(new TaxNode(id, name));
411 }
412 }
413
414 TaxNode[] nodes=new TaxNode[max+1];
415 for(TaxNode n : list){
416 assert(nodes[n.id]==null || nodes[n.id].equals(n)) : nodes[n.id]+" -> "+n;
417 nodes[n.id]=n;
418 }
419
420 return nodes;
421 }
422
423 /**
424 * Parses names file a second time to fill in additional information.
425 * Should really be merged into getNames.
426 * @TODO Merge into getNames
427 */
428 private static TaxNode[] getNodes(String fname, TaxNode[] nodes){
429
430 int max=0;
431
432 LinkedHashMap<String, int[]> oddNames=new LinkedHashMap<String, int[]>();
433
434 TextFile tf=new TextFile(fname, false);
435 for(String s=tf.nextLine(); s!=null; s=tf.nextLine()){
436 String[] split=delimiter.split(s, 4);
437 assert(split.length==4) : s;
438 int id=-1, pid=-1, level=-1, levelExtended=-1;
439
440 id=Integer.parseInt(split[0]);
441 try {
442 pid=Integer.parseInt(split[1]);
443 } catch (NumberFormatException e) {
444 // TODO Auto-generated catch block
445 e.printStackTrace();
446 System.err.println("Bad line: "+s+"\n"+Arrays.toString(split));
447 }
448 boolean alt=false;
449 {
450 String key=split[2];
451 Integer obj0=levelMap.get(key);
452 Integer obj=levelMapExtended.get(key);
453 assert(obj!=null) : "No level found for "+key+"; line="+Arrays.toString(split);
454
455 if(obj0==null){
456 obj0=altLevelMap.get(key);
457 alt=true;
458 }
459 if(obj0!=null){
460 level=obj0;
461 levelExtended=obj;
462 if(id==pid){
463 level=LIFE;
464 levelExtended=LIFE_E;
465 alt=false;
466 }
467 }else{
468 if(id==pid){
469 level=LIFE;
470 levelExtended=LIFE_E;
471 alt=false;
472 }else{
473 int[] count=oddNames.get(key);
474 if(count==null){
475 count=new int[1];
476 oddNames.put(key, count);
477 }
478 count[0]++;
479 }
480 }
481 }
482 max=Tools.max(max, id);
483 TaxNode n=nodes[id];
484 assert(n!=null && n.pid<0) : n+" -> "+s;
485 n.pid=pid;
486 n.level=level;
487 n.levelExtended=levelExtended;
488 n.setOriginalLevel(levelExtended);
489 n.setCanonical(!alt);
490 assert(n.canonical()==n.isSimple() || n.levelExtended==NO_RANK_E) : n.canonical()+", "+n.isSimple()+", "+n.level+", "+n.levelExtended+"\n"+n.toString()+"\n";
491 }
492
493 if(oddNames.size()>0){
494 outstream.println("Found "+oddNames.size()+" unknown taxonomic levels:");
495 if(verbose){
496 for(String s : oddNames.keySet()){
497 outstream.println(oddNames.get(s)[0]+"\t"+s);
498 }
499 }
500 }
501
502 return nodes;
503 }
504
505 /**
506 * Count child nodes of each node.
507 * This can be used to size arrays or determine which nodes are leaves.
508 */
509 private void countChildren(){
510 for(TaxNode child : nodes){
511 if(child!=null && child.pid!=child.id){
512 TaxNode parent=getNode(child.pid);
513 if(parent!=child){parent.numChildren++;}
514 }
515 }
516 }
517
518 //TODO - This could be finished in 2 passes using the childTable.
519 /**
520 * Fill derived fields minParentLevelExtended and maxChildLevelExtended
521 * by percolating information through the tree until a fixpoint is reached.
522 * @TODO This could be finished in 2 passes using the childTable.
523 * @return Number of rounds required to reach fixpoint.
524 */
525 private int percolate(){
526 boolean changed=true;
527 int rounds=0;
528 while(changed){
529 changed=false;
530 rounds++;
531 for(TaxNode child : nodes){
532 if(child!=null && child.pid!=child.id){
533 TaxNode parent=getNode(child.pid);
534 changed=(child.discussWithParent(parent) | changed);
535 }
536 }
537
538 if(!changed){break;}
539 changed=false;
540 rounds++;
541 for(int i=nodes.length-1; i>=0; i--){
542 TaxNode child=nodes[i];
543 if(child!=null && child.pid!=child.id){
544 TaxNode parent=getNode(child.pid);
545 changed=(child.discussWithParent(parent) | changed);
546 }
547 }
548 }
549 return rounds;
550 }
551
552 /**
553 * Load nodes into the nameMap and nameMapLower, mapped to their names.
554 * @param genusDotSpecies Also hash abbreviations such as E.coli.
555 */
556 public synchronized void hashNames(boolean genusDotSpecies){
557 if(nameMap!=null){return;}
558 assert(nameMap==null);
559 assert(nameMapLower==null);
560 final int size=((int)Tools.mid(2, (nodes.length+(genusDotSpecies ? nodesPerLevelExtended[SPECIES_E] : 0))*1.5, Shared.MAX_ARRAY_LEN));
561 nameMap=new HashMap<String, ArrayList<TaxNode>>(size);
562 nameMapLower=new HashMap<String, ArrayList<TaxNode>>(size);
563
564 //Hash the names, both lowercase and uppercase
565 for(TaxNode n : nodes){
566 if(n!=null){
567 String name=n.name;
568 if(name.indexOf('_')>=0){
569 name=name.replace('_', ' ').trim();
570 }
571 if(name!=null && !name.equals("environmental samples")){
572 {
573 ArrayList<TaxNode> list=nameMap.get(name);
574 if(list==null){
575 list=new ArrayList<TaxNode>();
576 nameMap.put(name, list);
577 }
578 list.add(n);
579 }
580 {
581 String lc=name.toLowerCase();
582 ArrayList<TaxNode> list=nameMapLower.get(lc);
583 if(list==null){
584 list=new ArrayList<TaxNode>();
585 nameMapLower.put(lc, list);
586 }
587 list.add(n);
588 }
589 }
590 }
591 }
592
593 //Hash G.species versions of the names, both lowercase and uppercase
594 if(genusDotSpecies){
595 ByteBuilder bb=new ByteBuilder(64);
596 for(TaxNode n : nodes){
597 if(n!=null && n.levelExtended==SPECIES_E){
598 String name=n.name;
599 if(name.indexOf('_')>=0){
600 name=name.replace('_', ' ').trim();
601 }
602 if(name!=null && !name.equals("environmental samples")){
603 final String dotFormat=dotFormat(name, bb);
604 if(dotFormat!=null){
605 {
606 ArrayList<TaxNode> list=nameMap.get(dotFormat);
607 if(list==null){
608 list=new ArrayList<TaxNode>();
609 nameMap.put(dotFormat, list);
610 }
611 list.add(n);
612 }
613 {
614 String lc=dotFormat.toLowerCase();
615 ArrayList<TaxNode> list=nameMapLower.get(lc);
616 if(list==null){
617 list=new ArrayList<TaxNode>();
618 nameMapLower.put(lc, list);
619 }
620 list.add(n);
621 }
622 }
623 }
624 }
625 }
626 }
627 }
628
629 /**
630 * Generate the "dot format" name of a node.
631 * For example, transform "Homo sapiens" to "H.sapiens"
632 * @param name Node name
633 * @param buffer A ByteBuilder that may be modified
634 * @return Dot format
635 */
636 private static String dotFormat(String name, ByteBuilder buffer){
637 if(name==null || name.indexOf('.')>=0){return null;}
638 final int firstSpace=name.indexOf(' ');
639 if(firstSpace<0 || firstSpace>=name.length()-1){return null;}
640 final int lastSpace=name.lastIndexOf(' ');
641 if(firstSpace!=lastSpace){return null;}
642 final String a=name.substring(0, firstSpace);
643 final String b=name.substring(lastSpace+1);
644 final char ca=a.charAt(0);
645 final char cb=b.charAt(0);
646 if(!Tools.isUpperCase(ca) || !Tools.isLowerCase(cb)){return null;}
647 if(buffer==null){buffer=new ByteBuilder(2+b.length());}
648 else{buffer.clear();}
649 buffer.append(ca).append('.').append(b);
650 return buffer.toString();
651 }
652
653 /**
654 * Fill childMap, which maps nodes to their children.
655 */
656 public synchronized void hashChildren(){
657 assert(childMap==null);
658 int nodesWithChildren=0;
659 for(TaxNode tn : nodes){
660 if(tn!=null && tn.numChildren>0){nodesWithChildren++;}
661 }
662 childMap=new HashMap<TaxNode, ArrayList<TaxNode>>((int)Tools.mid(2, nodesWithChildren*1.5, Shared.MAX_ARRAY_LEN));
663 for(TaxNode tn : nodes){
664 if(tn!=null){
665 if(tn.numChildren>0){
666 childMap.put(tn, new ArrayList<TaxNode>(tn.numChildren));
667 }
668 }
669 }
670 for(TaxNode tn : nodes){
671 if(tn!=null){
672 if(tn.id!=tn.pid){
673 ArrayList<TaxNode> list=childMap.get(getNode(tn.pid));
674 if(list!=null){list.add(tn);}
675 }
676 }
677 }
678 }
679
680 /**
681 * Fetch this node's children.
682 * @param parent Node in question
683 * @return List of child nodes
684 */
685 public ArrayList<TaxNode> getChildren(TaxNode parent){
686 if(parent.numChildren<1){return null;}
687 if(childMap!=null){return childMap.get(parent);}
688 ArrayList<TaxNode> list=new ArrayList<TaxNode>(parent.numChildren);
689 for(TaxNode tn : nodes){
690 if(tn!=null && tn.id!=tn.pid && tn.pid==parent.id){
691 list.add(tn);
692 }
693 }
694 return list;
695 }
696
697 /**
698 * Load a map of old to new TaxIDs.
699 * @param mergedFile NCBI merged.txt.
700 * @return Map of old to new TaxIDs
701 */
702 private static IntHashMap getMerged(String mergedFile) {
703 if(mergedFile==null){return null;}
704 String[] lines=TextFile.toStringLines(mergedFile);
705 if(lines.length<1){return null;}
706 IntHashMap map=new IntHashMap((int)(lines.length*1.3));
707 for(String line : lines){
708 String[] split=delimiterTab.split(line);
709 int a=Integer.parseInt(split[0]);
710 int b=Integer.parseInt(split[2]);
711 map.put(a, b);
712 }
713 return map;
714 }
715
716 /**
717 * Simplify the tree by assigning ranks to unranked nodes,
718 * where possible, through inference.
719 * Optionally removes unranked nodes based on the skipNorank field.
720 * @param nodes Array of all TaxNodes.
721 * @return Number of nodes removed.
722 */
723 private int simplify(TaxNode nodes[]){
724
725 int failed=test(nodes);
726
727 int removed=0;
728 int reassigned=0;
729
730 if(reassign){
731 boolean changed=true;
732 int changedCount=0;
733 while(changed){
734 changed=false;
735 for(int i=0; i<nodes.length; i++){
736 TaxNode n=nodes[i];
737 if(n!=null && n.levelExtended<1){
738 int pid=n.pid;
739 TaxNode parent=nodes[pid];
740 assert(parent!=null) : n;
741 if(n.maxDescendantLevelIncludingSelf()<SUBSPECIES_E &&
742 parent.minAncestorLevelIncludingSelf()<=SPECIES_E && parent.minAncestorLevelIncludingSelf()>=SUBSPECIES_E){
743 // if(parent.levelExtended==SPECIES_E || parent.levelExtended==SUBSPECIES_E){
744 changed=true;
745 n.levelExtended=SUBSPECIES_E;
746 n.level=SUBSPECIES;
747 changedCount++;
748 }
749 }
750 }
751 }
752 System.err.println("Assigned levels to "+changedCount+" unranked nodes.");
753 }
754
755
756 if(skipNorank){//Skip nodes with unknown taxa
757 if(verbose){outstream.println("A0");}
758
759 for(int i=0; i<nodes.length; i++){
760 TaxNode n=nodes[i];
761 if(n!=null){
762 int pid=n.pid;
763 TaxNode parent=nodes[pid];
764 assert(parent!=null) : n;
765 assert(parent!=n || pid==1) : n+", "+pid;
766 while(parent.levelExtended<1 && n.levelExtended>parent.levelExtended){
767 //System.err.println("Reassigned from "+parent);
768 assert(parent.id!=parent.pid);
769 parent=nodes[parent.pid];
770 n.pid=parent.id;
771 reassigned++;
772 }
773 }
774 }
775
776 for(int i=0; i<nodes.length; i++){
777 if(nodes[i]!=null && nodes[i].levelExtended<0){
778 System.err.println("Removed "+nodes[i]);
779 nodes[i]=null;
780 removed++;
781 }
782 }
783 if(verbose){outstream.println("Skipped "+reassigned+" unranked parents, removed "+removed+" invalid nodes.");}
784 }
785
786 if(inferRankLimit>0){//Infer level for unset nodes (from "no rank")
787 if(verbose){outstream.println("A");}
788 int changed=1;
789 while(changed>0){
790 changed=0;
791 for(final TaxNode n : nodes){
792 if(n!=null){
793 if(n.levelExtended==0){
794 TaxNode parent=nodes[n.pid];
795 if(n!=parent && parent.levelExtended>0 && parent.levelExtended<=inferRankLimit+1){
796 n.levelExtended=Tools.max(1, parent.levelExtended-1);
797 assert(n.levelExtended>0 && n.levelExtended<=parent.levelExtended && n.levelExtended<=inferRankLimit);
798 changed++;
799 }
800 }
801 }
802 }
803 if(verbose){outstream.println("changed: "+changed);}
804 }
805
806 // outstream.println("B");
807 // for(TaxNode n : nodes){
808 // if(n!=null && n.level==0){
809 // n.level=-1;
810 // }
811 // }
812 }
813
814 failed=test(nodes);
815
816 // if(reassign){//Skip nodes with duplicate taxa
817 // if(verbose){outstream.println("D");}
818 // int changed=1;
819 // while(changed>0){
820 // changed=0;
821 // for(final TaxNode n : nodes){
822 // if(n!=null){
823 // TaxNode parent=nodes[n.pid];
824 // TaxNode grandparent=nodes[parent.pid];
825 // assert(n.level<=parent.level || parent.level<1 || !parent.canonical()) : n+" -> "+parent+" -> "+grandparent;
826 // assert(parent.level<=grandparent.level || grandparent.level<1 || !grandparent.canonical()) : n+" -> "+parent+" -> "+grandparent;
827 //
828 // while(parent!=grandparent && (parent.level<0 || (parent.level==grandparent.level && !parent.canonical()) ||
829 // n.level>parent.level || (n.level==parent.level))){
830 // parent=grandparent;
831 // grandparent=nodes[parent.pid];
832 // n.pid=parent.id;
833 // reassigned++;
834 // changed++;
835 // }
836 // }
837 // }
838 // if(verbose){outstream.println("changed: "+changed);}
839 // }
840 // if(verbose){outstream.println("E");}
841 // for(int i=0; i<nodes.length; i++){
842 // if(nodes[i]!=null && nodes[i].level<0){
843 // nodes[i]=null;
844 // removed++;
845 // }
846 // }
847 // }
848
849 failed=test(nodes);
850
851 if(verbose){outstream.println("F");}
852 {//Ensure the tree is now clean
853 for(int i=0; i<nodes.length; i++){
854 TaxNode n=nodes[i];
855 if(n!=null){
856 TaxNode parent=nodes[n.pid];
857 TaxNode grandparent=nodes[parent.pid];
858 assert(n==parent || n.levelExtended<=parent.levelExtended || !n.canonical() || n.levelExtended<1 || parent.levelExtended<1) : n+" -> "+parent+" -> "+grandparent;
859 assert(parent==grandparent || parent.levelExtended<=grandparent.levelExtended || !parent.canonical() || parent.levelExtended<1 || grandparent.levelExtended<1) : n+" -> "+parent+" -> "+grandparent;
860 }
861 }
862 }
863
864 // if(verbose){System.err.println("Reassignments: "+reassigned);}
865
866 return removed;
867 }
868
869 /*--------------------------------------------------------------*/
870 /*---------------- Validation ----------------*/
871 /*--------------------------------------------------------------*/
872
873 /**
874 * Ensure tree has monotonically increasing (or nondescending) ranks.
875 * @param nodes All TaxNodes.
876 * @return Number of violations.
877 */
878 private static int test(TaxNode[] nodes){
879 int failed=0;
880 for(final TaxNode n : nodes){
881 if(n!=null){
882 TaxNode parent=nodes[n.pid];
883 try {
884 assert(n==parent || n.level<=parent.level || parent.level<1 || !parent.canonical()) :
885 "\n"+n+" -> "+parent+", level="+n.level+", plevel="+parent.level+", pcanon="+parent.canonical()+"\n"
886 + "levelE="+n.levelExtended+", plevelE="+parent.levelExtended;
887 assert(n==parent || n.levelExtended<=parent.levelExtended || parent.levelExtended<1) : n+" -> "+parent;
888 // assert(n==parent || n.level<parent.level || parent.level<1 || !n.canonical() || !parent.canonical()) : n+" -> "+parent;
889 if(n!=parent && n.level>parent.level && parent.level>=1 && n.canonical() && parent.canonical()){
890 if(verbose){outstream.println("Error: "+n+" -> "+parent);}
891 failed++;
892 }else if(n!=parent && parent.levelExtended>=1 && n.levelExtended>=parent.levelExtended){
893 // if(verbose){outstream.println("Error: "+n+" -> "+parent);}
894 // failed++;
895 }
896 assert(n!=parent || n.id<=1) : n;
897 } catch (Throwable e) {
898 // TODO Auto-generated catch block
899 e.printStackTrace();
900 failed++;
901 }
902 }
903 }
904 if(verbose || failed>0){outstream.println(failed+" nodes failed.");}
905 return failed;
906 }
907
908 /*--------------------------------------------------------------*/
909 /*---------------- Print Methods ----------------*/
910 /*--------------------------------------------------------------*/
911
912 /**
913 * Format full name in semicolon format, e.g.
914 * "SK:Bacteria;P:Protobacteria;..."
915 * @param tn0 Base node
916 * @param skipNonCanonical Ignore noncanonical (aka "nonsimple") levels like Tribe.
917 * @return Resultant String
918 */
919 public String toSemicolon(final TaxNode tn0, boolean skipNonCanonical, boolean mononomial){
920 StringBuilder sb=new StringBuilder();
921 if(tn0==null){return "Not found";}
922 String semi="";
923 ArrayList<TaxNode> list=toAncestors(tn0, skipNonCanonical);
924 boolean addTaxLevel=true;
925 for(int i=list.size()-1; i>=0; i--){
926 sb.append(semi);
927 TaxNode tn=list.get(i);
928 if(tn.id!=LIFE_ID || list.size()==1){
929 if(addTaxLevel && tn.canonical() && !tn.levelChanged() && tn.isSimple()){
930 sb.append(tn.levelToStringShort()).append(':');
931 }
932 sb.append(mononomial ? mononomial(tn) : tn.name);
933 semi=";";
934 }
935 }
936 return sb.toString();
937 }
938
939 /**
940 * Return a list of TaxIDs of all ancestors.
941 * @param tn0 Base node
942 * @param skipNonCanonical Ignore noncanonical (aka "nonsimple") levels like Tribe.
943 * @return List of TaxIDs.
944 */
945 public IntList toAncestorIds(final TaxNode tn0, boolean skipNonCanonical){
946 if(tn0==null){return null;}
947 IntList list=new IntList(8);
948
949 TaxNode tn=tn0;
950 while(tn!=null){
951 if(!skipNonCanonical || tn.isSimple()){
952 if(tn.id!=CELLULAR_ORGANISMS_ID || tn==tn0){list.add(tn.id);}
953 }
954 if(tn.pid==tn.id){break;}
955 tn=getNode(tn.pid);
956 }
957 if(list.isEmpty()){list.add(tn0.id);}
958 return list;
959 }
960
961 /**
962 * Return a list of all ancestors.
963 * @param tn0 Base node
964 * @param skipNonCanonical Ignore noncanonical (aka "nonsimple") levels like Tribe.
965 * @return List of ancestor nodes.
966 */
967 public ArrayList<TaxNode> toAncestors(final TaxNode tn0, boolean skipNonCanonical){
968 if(tn0==null){return null;}
969 ArrayList<TaxNode> list=new ArrayList<TaxNode>(8);
970
971 TaxNode tn=tn0;
972 while(tn!=null){
973 if(!skipNonCanonical || tn.isSimple()){
974 if(tn.id!=CELLULAR_ORGANISMS_ID || tn==tn0){list.add(tn);}
975 }
976 if(tn.pid==tn.id){break;}
977 tn=getNode(tn.pid);
978 }
979 if(list.isEmpty()){list.add(tn0);}
980 return list;
981 }
982
983 /**
984 * Generate a path to the genome of an organism on the filesystem;
985 * used by ExplodeTree. Intended for internal JGI use.
986 * @param root Location of the exploded tree.
987 * @return Path to a genome.
988 */
989 public String toDir(TaxNode node, String root){
990 StringBuilder sb=new StringBuilder();
991 if(root==null){root="";}
992 sb.append(root);
993 if(root.length()>0 && !root.endsWith("/")){sb.append('/');}
994 IntList list=toAncestorIds(node, false);
995 list.reverse();
996 assert(list.get(0)==1) : list + "," +getNode(list.get(0));
997 for(int i=0; i<list.size(); i++){
998 sb.append(list.get(i));
999 sb.append('/');
1000 }
1001 return sb.toString();
1002 }
1003
1004 /*--------------------------------------------------------------*/
1005 /*---------------- Outer Methods ----------------*/
1006 /*--------------------------------------------------------------*/
1007
1008 /**
1009 * Use various techniques to get a TaxID from an unknown String, such as parsing,
1010 * name lookups, and accession translation.
1011 * @param s String to process.
1012 * @return Decoded TaxID.
1013 */
1014 public static int getID(String s){return GiToTaxid.getID(s);}
1015
1016 /**
1017 * Use various techniques to get a TaxID from an unknown byte[], such as parsing,
1018 * name lookups, and accession translation.
1019 * @param s String to process.
1020 * @return Decoded TaxID.
1021 */
1022 public static int getID(byte[] s){return GiToTaxid.getID(s);}
1023
1024 /** Return the lowest ancestor of the named node with taxonomic level at least minLevel */
1025 public TaxNode getNode(String s, int minLevelExtended){
1026 TaxNode tn=parseNodeFromHeader(s, true);
1027 while(tn!=null && tn.levelExtended<minLevelExtended && tn.pid!=tn.id){
1028 tn=getNode(tn.pid);
1029 }
1030 return tn;
1031 }
1032
1033 /**
1034 * Determine whether a node is a descendant of another.
1035 * @param child Possible child TaxID.
1036 * @param parent Possible parent TaxID.
1037 * @return true iff child descends from parent.
1038 */
1039 public boolean descendsFrom(final int child, final int parent){
1040 TaxNode cn=getNode(child), pn=getNode(parent);
1041 assert(cn!=null) : "Invalid taxID: "+child;
1042 assert(pn!=null) : "Invalid taxID: "+parent;
1043 return descendsFrom(cn, pn);
1044 }
1045
1046 /**
1047 * Determine whether a node is a descendant of another.
1048 * @param child Possible child node.
1049 * @param parent Possible parent node.
1050 * @return true iff child descends from parent.
1051 */
1052 public boolean descendsFrom(TaxNode child, TaxNode parent){
1053 assert(child!=null && parent!=null) : "Null parameters.";
1054 if(child==null || parent==null){return false;}
1055
1056 while(child!=parent && child.levelExtended<=parent.levelExtended && child.id!=child.pid){
1057 child=getNode(child.pid);
1058 }
1059 return child==parent;
1060 }
1061
1062 /**
1063 * Determine whether an organism is classified as X.
1064 * @param taxID taxID of organism.
1065 * @param ancestorID taxID of possible ancestor.
1066 * @return true if the organism is an X.
1067 */
1068 public boolean descendsFrom2(int taxID, final int ancestorID) {
1069 TaxNode tn=getNode(taxID);
1070 while(tn.id!=tn.pid){
1071 if(tn.id==ancestorID){return true;}
1072 tn=getNode(tn.pid);
1073 }
1074 return false;
1075 }
1076
1077 /** Determine whether an organism is classified as a plant. */
1078 public boolean isPlant(int taxID) {return descendsFrom2(taxID, VIRIDIPLANTAE_ID);}
1079
1080 /** Determine whether an organism is classified as an animal. */
1081 public boolean isAnimal(int taxID) {return descendsFrom2(taxID, METAZOA_ID);}
1082
1083 /** Determine whether an organism is classified as a fungus. */
1084 public boolean isFungus(int taxID) {return descendsFrom2(taxID, FUNGI_ID);}
1085
1086 /** Determine whether an organism is classified as a eukaryote. */
1087 public boolean isEukaryote(int taxID) {return descendsFrom2(taxID, EUKARYOTA_ID);}
1088
1089 /** Determine whether an organism is classified as a prokaryote. */
1090 public boolean isProkaryote(int taxID) {
1091 TaxNode tn=getNode(taxID);
1092 if(tn==null){
1093 System.err.println("*** Warning: Can't find node "+taxID+" ***");
1094 return false;
1095 }
1096 while(tn.id!=tn.pid){
1097 if(tn.id==BACTERIA_ID || tn.id==ARCHAEA_ID){return true;}
1098 tn=getNode(tn.pid);
1099 }
1100 return false;
1101 }
1102
1103 /**
1104 * Calculate the taxLevel of the common ancestor of two nodes.
1105 * @param a TaxID of a node.
1106 * @param b TaxID of a node.
1107 * @return Common ancestor ID of a and b.
1108 */
1109 public int commonAncestorLevel(final int a, final int b){
1110 if(a<1 || b<1) {return -1;}
1111 TaxNode an=getNode(a), bn=getNode(b);
1112 assert(an!=null) : "Invalid taxID: "+a;
1113 assert(bn!=null) : "Invalid taxID: "+b;
1114 TaxNode cn=commonAncestor(an, bn);
1115 assert(cn!=null) : "No common ancestor: "+an+", "+bn;
1116 if(cn==null){return -1;}
1117 return cn.level;
1118 }
1119
1120 /**
1121 * Calculate the common ancestor of two nodes.
1122 * @param a TaxID of a node.
1123 * @param b TaxID of a node.
1124 * @return Common ancestor ID of a and b.
1125 */
1126 public int commonAncestor(final int a, final int b){
1127 TaxNode an=getNode(a), bn=getNode(b);
1128 assert(an!=null) : "Invalid taxID: "+a;
1129 assert(bn!=null) : "Invalid taxID: "+b;
1130 TaxNode cn=commonAncestor(an, bn);
1131 assert(cn!=null) : "No common ancestor: "+an+", "+bn;
1132 if(cn==null){return -1;}
1133 return cn.id;
1134 }
1135
1136 /**
1137 * Calculate the common ancestor of two nodes.
1138 * @param a A node.
1139 * @param b A node.
1140 * @return Common ancestor of a and b.
1141 */
1142 public TaxNode commonAncestor(TaxNode a, TaxNode b){
1143 assert(a!=null && b!=null) : "Null parameters.";
1144 if(a==null){return b;}
1145 if(b==null){return a;}
1146
1147 while(a!=b){
1148 if(a.levelExtended<b.levelExtended){
1149 a=getNode(a.pid);
1150 }else{
1151 b=getNode(b.pid);
1152 }
1153 }
1154 return a;
1155 }
1156
1157 /**
1158 * Identify the highest ancestor of a node;
1159 * this will presumably be "Life".
1160 * @param a Node
1161 * @return Highest ancestor
1162 */
1163 public TaxNode highestAncestor(TaxNode a){
1164 assert(a!=null);
1165 while(a.id!=a.pid){a=getNode(a.pid);}
1166 return a;
1167 }
1168
1169 /*--------------------------------------------------------------*/
1170 /*---------------- Header Parsing ----------------*/
1171 /*--------------------------------------------------------------*/
1172
1173 /**
1174 * Determine the TaxID of a String,
1175 * without a loaded TaxTree.
1176 * This only works if the literal TaxID is embedded in the String.
1177 * @param header Typically a sequence header
1178 * @return Decoded TaxID, or -1 if unsuccessful
1179 */
1180 public static int parseHeaderStatic(String header){
1181 if(header.length()<3){return -1;}
1182 if(header.charAt(0)=='>'){header=header.substring(1);}
1183 if(!header.startsWith("tid|")){return -1;}
1184 int idx=3;
1185 int idx2=header.indexOf('|', 4);
1186 if(idx2<5){return -1;}
1187 int id=-1;
1188 try {
1189 id=Parse.parseInt(header, idx+1, idx2);
1190 // System.err.println("d"+", "+header.substring(idx+1, idx2));
1191 } catch (Throwable e) {
1192 // System.err.println("e"+", "+header.substring(idx+1, idx2));
1193 //ignore
1194 }
1195 return id;
1196 }
1197
1198 /** New and improved. Tree is optional. */
1199 public static int parseHeaderStatic2(String header, TaxTree tree) {
1200 int tid=-1;
1201 if(header==null) {return -1;}
1202 if(tid<0) {tid=parseTaxID(header, "tid");}
1203 if(tid<0) {tid=parseTaxID(header, "ncbi");}
1204 if(tid>=0 || tree==null) {return tid;}
1205 TaxNode tn=tree.parseNodeFromHeader(header, true);
1206 return tn==null ? tid : tn.id;
1207 }
1208
1209 /** Header should contain something like "tid|1234" somewhere;
1210 * delimiter is autodetected. */
1211 private static int parseTaxID(String header, String term) {
1212 int loc=header.indexOf(term);
1213 // System.err.println("a) loc="+loc+", term="+term+", header="+header);
1214 if(loc<0) {return -1;}
1215 int start=loc+term.length();
1216 // System.err.println("b) start="+start);
1217 if(header.length()<start+2) {return -1;}
1218 final char c=header.charAt(start);
1219 // System.err.println("c) c="+c);
1220 if(Tools.isDigitOrSign(c)) {return -1;}
1221 start++;
1222 final char d=header.charAt(start);
1223 // System.err.println("d) d="+d);
1224 if(!Tools.isDigitOrSign(d)) {return -1;}
1225 int stop=start+1;
1226 // System.err.println("e) stop="+stop);
1227 while(stop<header.length() && Tools.isDigitOrSign(header.charAt(stop))) {stop++;}
1228 // System.err.println("f) stop="+stop);
1229 // System.err.println("g) start="+start+", stop="+stop+", int="+Parse.parseInt(header, start, stop));
1230 return Parse.parseInt(header, start, stop);
1231 }
1232
1233 /**
1234 * Determine the TaxID of a String.
1235 * @param header Typically a sequence header or file name
1236 * @param bestEffort In some cases, try certain substrings if the name is not found.
1237 * @return
1238 */
1239 public TaxNode parseNodeFromHeader(String header, boolean bestEffort){
1240 if(header==null || header.length()<2){return null;}
1241 if(header.charAt(0)=='>'){header=header.substring(1);}
1242 if(header.endsWith(".gz")) {header=header.substring(0, header.lastIndexOf('.'));}
1243 if(header.endsWith(".fa") || header.endsWith(".fna") || header.endsWith(".fasta") || header.endsWith(".faa")) {
1244 header=header.substring(0, header.lastIndexOf('.'));
1245 }
1246 TaxNode tn;
1247 if(SILVA_MODE){
1248 tn=getNodeSilva(header, bestEffort);
1249 }else if(UNITE_MODE){
1250 tn=getNodeUnite(header, bestEffort);
1251 }else{
1252 final char delimiter=ncbiHeaderDelimiter(header);
1253 if(delimiter==' '){
1254 tn=getNodeNewStyle(header);
1255 }else{
1256 tn=getNodeOldStyle(header, delimiter);
1257 if(tn==null && delimiter=='|'){
1258 // System.err.println("A: "+header);
1259 int id=-1;
1260 String[] split=header.split("\\|");
1261 if(AccessionToTaxid.LOADED()){
1262 for(int i=0; i<split.length && id<0; i++){//Try accessions first
1263 if(AccessionToTaxid.isValidAccession(split[i])){
1264 id=AccessionToTaxid.get(split[i]);
1265 }
1266 }
1267 }
1268 for(int i=0; i<split.length && id<0; i++){//Then names
1269 id=parseNameToTaxid(split[i]);
1270 }
1271 // System.err.println("E: "+id);
1272 if(id>=0){tn=getNode(id);}
1273 // System.err.println("F: "+tn);
1274 }
1275 }
1276 }
1277 return tn;
1278 }
1279
1280 /**
1281 * Guess the delimiter character in a String;
1282 * typically assumed to be '|', '~', or ' '.
1283 */
1284 public static char ncbiHeaderDelimiter(String header){
1285 for(int i=0; i<header.length(); i++){
1286 final char c=header.charAt(i);
1287 if(c=='|' || c=='~'){
1288 assert(i>0) : "i="+i+"; malformatted header '"+header+"'";
1289 return c;
1290 }else if(Character.isWhitespace(c)){
1291 return ' ';
1292 }
1293 }
1294 return ' ';
1295 }
1296
1297 /**
1298 * Parse a Silva header to a Node.
1299 * @param s Silva header.
1300 * @param bestEffort Try certain substrings if the name is not found.
1301 * @return Node
1302 */
1303 TaxNode getNodeSilva(String s, boolean bestEffort){
1304 if(s==null){return null;}
1305 if(s.length()>=5 && s.startsWith("tid") && (s.charAt(3)=='|' || s.charAt(3)=='~') && Tools.isDigit(s.charAt(4))){
1306 return getNodeOldStyle(s, s.charAt(3));
1307 }
1308 String[] split=Tools.semiPattern.split(s);
1309
1310 int number=-1;
1311 // final boolean chloroplast=(split.length>1 && split[split.length-1].equals("Chloroplast"));
1312 // if(chloroplast){return null;}
1313 for(int i=split.length-1; number<0 && i>=0; i--){
1314 String last=split[i];
1315 int paren=last.indexOf('(');
1316 if(paren>=0){last=last.substring(0, paren);}
1317 last=last.trim();
1318
1319 if(!last.startsWith("uncultured") && !last.startsWith("unidentified")){
1320 number=parseNameToTaxid(last);
1321 }
1322
1323 if(number>=0){return getNode(number);}
1324 else if(!bestEffort){break;}
1325 }
1326 return null;
1327 }
1328
1329 /**
1330 * Parse a Unite header to a Node.
1331 * @param s Unite header.
1332 * @param bestEffort Try certain substrings if the name is not found.
1333 * @return Node
1334 */
1335 TaxNode getNodeUnite(String s, boolean bestEffort){
1336 if(s==null){return null;}
1337 if(s.length()>=5 && s.startsWith("tid") && (s.charAt(3)=='|' || s.charAt(3)=='~') && Tools.isDigit(s.charAt(4))){
1338 return getNodeOldStyle(s, s.charAt(3));
1339 }
1340 String[] split=Tools.pipePattern.split(s);
1341
1342 int number=-1;
1343 String name=split[0];
1344 String acc=split[1];
1345 if(AccessionToTaxid.LOADED() && acc.length()>0){
1346 number=AccessionToTaxid.get(acc);
1347 }
1348 if(number<1){
1349 TaxNode tn=getNodeByName(name);
1350 if(tn!=null){number=tn.id;}
1351 }
1352
1353 if(number>=0){return getNode(number);}
1354 return null;
1355 }
1356
1357 /** Parses sequence headers using NCBI's old-style header system, prior to Accessions. */
1358 private TaxNode getNodeOldStyle(final String s, char delimiter){
1359 {
1360 int index=s.indexOf(delimiter);
1361 if(index<0){
1362 delimiter='~';
1363 index=s.indexOf(delimiter);
1364 if(index<0){
1365 delimiter='_';
1366 index=s.indexOf(delimiter);
1367 }
1368 }
1369 int number=-1;
1370
1371 Throwable e=null;
1372
1373 if(index==2 && s.length()>3 && s.startsWith("gi") && Tools.isDigit(s.charAt(3))){
1374 // System.err.println("Parsing gi number.");
1375
1376 if(GiToTaxid.isInitialized()){
1377 try {
1378 number=GiToTaxid.parseGiToTaxid(s, delimiter);
1379 } catch (Throwable e2) {
1380 e=e2;
1381 }
1382 }else{
1383 assert(!CRASH_IF_NO_GI_TABLE) : "To use gi numbers, you must load a gi table.\n"+s;
1384 }
1385 // if(number!=-1){System.err.println("number="+number);}
1386 }else if(index==3 && s.length()>4 && s.startsWith("tid") && Tools.isDigit(s.charAt(4))){
1387 // System.err.println("Parsing ncbi number.");
1388 number=GiToTaxid.parseTaxidNumber(s, delimiter);
1389 }else if(index==3 && s.length()>4 && s.startsWith("img") && Tools.isDigit(s.charAt(4))){
1390 // System.err.println("Parsing ncbi number.");
1391 long img=parseDelimitedNumber(s, delimiter);
1392 ImgRecord record=imgMap.get(img);
1393 number=(record==null ? -1 : record.taxID);
1394 }else if(index==4 && s.length()>5 && s.startsWith("ncbi") && Tools.isDigit(s.charAt(5))){//obsolete
1395 // System.err.println("Parsing ncbi number.");
1396 number=GiToTaxid.parseTaxidNumber(s, delimiter);
1397 }
1398
1399 if(number<0 && index>=0 && (delimiter=='|' || delimiter=='~')){
1400 String[] split=(delimiter=='|' ? delimiterPipe.split(s) : delimiterTilde.split(s));
1401 if(AccessionToTaxid.LOADED()){
1402 number=parseAccessionToTaxid(split);
1403 }
1404 if(number<0){
1405 number=parseHeaderNameToTaxid(split);
1406 }
1407 }
1408
1409 if(number<0 && e!=null){
1410 assert(false) : e;
1411 throw new RuntimeException(e);
1412 }
1413
1414 //TaxServer code could go here...
1415
1416 if(number>=0){return getNode(number);}
1417 }
1418 if(verbose){System.err.println("Can't process name "+s);}
1419 if(Tools.isDigit(s.charAt(0)) && s.length()<=9){
1420 try {
1421 return getNode(Integer.parseInt(s));
1422 } catch (NumberFormatException e) {
1423 //ignore
1424 }
1425 }
1426 return null;
1427 }
1428
1429 /** Parse a delimited number from a header, or return -1 if formatted incorrectly. */
1430 static long parseDelimitedNumber(String s, char delimiter){
1431 if(s==null){return -1;}
1432 int i=0;
1433 while(i<s.length() && s.charAt(i)!=delimiter){i++;}
1434 i++;
1435 if(i>=s.length() || !Tools.isDigit(s.charAt(i))){return -1;}
1436
1437 long number=0;
1438 while(i<s.length()){
1439 char c=s.charAt(i);
1440 if(c==delimiter || c==' ' || c=='\t'){break;}
1441 assert(Tools.isDigit(c)) : c+"\n"+s;
1442 number=(number*10)+(c-'0');
1443 i++;
1444 }
1445 return number;
1446 }
1447
1448 /** Parses sequence headers using NCBI's current header system, with Accessions. */
1449 private TaxNode getNodeNewStyle(final String s){
1450
1451 int space=s.indexOf(' ');
1452 int number=-1;
1453
1454 if(AccessionToTaxid.LOADED()){
1455 if(space>0){
1456 number=AccessionToTaxid.get(s.substring(0, space));
1457 }else{
1458 number=AccessionToTaxid.get(s);
1459 }
1460 }
1461
1462 if(number<0 && Tools.isDigit(s.charAt(0)) && s.length()<=9 && space<0){
1463 try {
1464 return getNode(Integer.parseInt(s));
1465 } catch (NumberFormatException e) {
1466 //ignore
1467 }
1468 }
1469
1470 if(number<0 && space>0){
1471 number=parseNameToTaxid(s.substring(space+1));
1472 }
1473
1474 if(number>-1){return getNode(number);}
1475 if(space<0 && s.indexOf('_')>0){
1476 return getNodeNewStyle(s.replace('_', ' '));
1477 }
1478 return null;
1479 }
1480
1481 /**
1482 * For parsing old-style NCBI headers.
1483 */
1484 public int parseAccessionToTaxid(String[] split){
1485 if(split.length<4){
1486 return -1;
1487 }
1488 int ncbi=AccessionToTaxid.get(split[3]);
1489 return ncbi;
1490 }
1491
1492 /**
1493 * For parsing old-style NCBI headers.
1494 */
1495 public int parseHeaderNameToTaxid(String[] split){
1496 if(split.length<5){
1497 return -1;
1498 }
1499 return parseNameToTaxid(split[4]);
1500 }
1501
1502 /**
1503 * Returns the TaxID from the organism's scientific name (e.g. "Homo sapiens").
1504 * If multiple nodes share the same name, returns the first; to get the full list,
1505 * use getNodesByNameExtended.
1506 * @param name Organism name.
1507 * @return Organism TaxID, or -1 if not found.
1508 */
1509 public int parseNameToTaxid(String name){
1510 // assert(false) : name+", "+(nameMap==null)+", "+(nameMap==null ? 0 : nameMap.size());
1511 List<TaxNode> list=null;
1512
1513 list=getNodesByNameExtended(name);
1514
1515 if(list==null || list.size()>1){return -1;}
1516 return list.get(0).id;
1517 }
1518
1519 /**
1520 * Fetch nodes indicated by this name.
1521 * @param name A taxonomic name delimited by space or underscore.
1522 * @return Nodes corresponding to the name.
1523 */
1524 public List<TaxNode> getNodesByNameExtended(String name){
1525 List<TaxNode> list=null;
1526
1527 list=getNodesByName(name);
1528 if(list!=null){return list;}
1529
1530 name=name.replaceAll("_", " ").trim();
1531 list=getNodesByName(name);
1532 if(list!=null){return list;}
1533
1534 String[] split2=name.split(" ");
1535
1536 if(split2.length>7){
1537 String term=split2[0]+" "+split2[1]+" "+split2[2]+" "+split2[3]+" "+split2[4]+" "+split2[5]+" "+split2[6]+" "+split2[7];
1538 list=getNodesByName(term);
1539 // System.err.println("6:\n"+Arrays.toString(split)+"\n"+Arrays.toString(split2)+"\n"+term+" -> "+list);
1540 if(list!=null){return list;}
1541 }
1542
1543 if(split2.length>6){
1544 String term=split2[0]+" "+split2[1]+" "+split2[2]+" "+split2[3]+" "+split2[4]+" "+split2[5]+" "+split2[6];
1545 list=getNodesByName(term);
1546 // System.err.println("6:\n"+Arrays.toString(split)+"\n"+Arrays.toString(split2)+"\n"+term+" -> "+list);
1547 if(list!=null){return list;}
1548 }
1549
1550 if(split2.length>5){
1551 String term=split2[0]+" "+split2[1]+" "+split2[2]+" "+split2[3]+" "+split2[4]+" "+split2[5];
1552 list=getNodesByName(term);
1553 // System.err.println("6:\n"+Arrays.toString(split)+"\n"+Arrays.toString(split2)+"\n"+term+" -> "+list);
1554 if(list!=null){return list;}
1555 }
1556 if(split2.length>4){
1557 String term=split2[0]+" "+split2[1]+" "+split2[2]+" "+split2[3]+" "+split2[4];
1558 list=getNodesByName(term);
1559 // System.err.println("5:\n"+Arrays.toString(split)+"\n"+Arrays.toString(split2)+"\n"+term+" -> "+list);
1560 if(list!=null){return list;}
1561 }
1562 if(split2.length>3){
1563 String term=split2[0]+" "+split2[1]+" "+split2[2]+" "+split2[3];
1564 list=getNodesByName(term);
1565 // System.err.println("4:\n"+Arrays.toString(split)+"\n"+Arrays.toString(split2)+"\n"+term+" -> "+list);
1566 if(list!=null){return list;}
1567 }
1568 if(split2.length>2){
1569 String term=split2[0]+" "+split2[1]+" "+split2[2];
1570 list=getNodesByName(term);
1571 // System.err.println("3:\n"+Arrays.toString(split)+"\n"+Arrays.toString(split2)+"\n"+term+" -> "+list);
1572 if(list!=null){return list;}
1573 }
1574 if(split2.length>1){
1575 String term=split2[0]+" "+split2[1];
1576 list=getNodesByName(term);
1577 // System.err.println("2:\n"+Arrays.toString(split)+"\n"+Arrays.toString(split2)+"\n"+term+" -> "+list);
1578 if(list!=null){return list;}
1579 }
1580 if(split2.length>0){
1581 String term=split2[0];
1582 list=getNodesByName(term);
1583 // System.err.println("1:\n"+Arrays.toString(split)+"\n"+Arrays.toString(split2)+"\n"+term+" -> "+list);
1584 if(list!=null){return list;}
1585 }
1586
1587 return null;
1588 }
1589
1590 /*--------------------------------------------------------------*/
1591 /*---------------- Assorted Methods ----------------*/
1592 /*--------------------------------------------------------------*/
1593
1594 /**
1595 * Return the TaxID of the lowest ancestor node at least the specified level,
1596 * including this node itself. Level is the normal (non-extended) level.
1597 * @param taxID
1598 * @param taxLevel
1599 * @return
1600 */
1601 public int promote(final int taxID, int taxLevel){
1602 TaxNode tn=null;
1603 tn=(taxID<1 ? null : getNode(taxID));
1604 tn=promote(tn, taxLevel);
1605 return (tn==null ? taxID : tn.id);
1606 }
1607
1608 /**
1609 * Fetch the first node in this node's lineage of at least the indicated level.
1610 * This can be the node itself or an ancestor.
1611 * @see getNodeAtLevelExtended
1612 * @param tn Node in question
1613 * @param taxLevel Desired minimum level
1614 * @return A node at the desired level
1615 */
1616 public TaxNode promote(TaxNode tn, int taxLevel){
1617 while(tn!=null && tn.pid!=tn.id && tn.level<taxLevel){
1618 TaxNode temp=getNode(tn.pid);
1619 if(temp==null || temp==tn || temp.level>=TaxTree.LIFE || temp.level>taxLevel){break;}
1620 tn=temp;
1621 }
1622 return tn;
1623 }
1624
1625 /**
1626 * Determine the TaxID of the node's parent.
1627 * @param id TaxID of child node
1628 * @return Parent TaxID
1629 */
1630 public int getParentID(int id){
1631 assert(id<nodes.length) : id+", "+nodes.length+"\nYou have encountered a TaxID more recent than your NCBI dump."
1632 + "\nPlease redownload it and regenerate the taxtree.";
1633 if(id<0 || id>=nodes.length){return -1;}
1634 TaxNode tn=nodes[id];
1635 if(tn==null && mergedMap!=null){tn=getNode(mergedMap.get(id), true);}
1636 return tn==null ? -1 : tn.pid;
1637 }
1638
1639 /**
1640 * Fetch the node with this TaxID.
1641 * @param id TaxID
1642 * @return Node
1643 */
1644 public TaxNode getNode(int id){
1645 assert(id<nodes.length) : id+", "+nodes.length+"\nYou have encountered a TaxID more recent than your NCBI dump."
1646 + "\nPlease redownload it and regenerate the taxtree.";
1647 if(id<0 || id>=nodes.length){return null;}
1648 TaxNode tn=nodes[id];
1649 if(tn!=null || mergedMap==null){return tn;}
1650 return getNode(mergedMap.get(id), true);
1651 }
1652
1653 /**
1654 * Fetch the node with this TaxID, but don't throw assertions upon failure.
1655 * @param id TaxID
1656 * @return Node
1657 */
1658 public TaxNode getNode(int id, boolean skipAssertion){
1659 assert(skipAssertion || id<nodes.length) : id+", "+nodes.length+"\nYou have encountered a TaxID more recent than your NCBI dump."
1660 + "\nPlease redownload it and regenerate the taxtree.";
1661 if(id<0 || id>=nodes.length){return null;}
1662 TaxNode tn=nodes[id];
1663 if(tn!=null || mergedMap==null){return tn;}
1664 return getNode(mergedMap.get(id), true);
1665 }
1666
1667 public TaxNode getNodeAtLevel(int id, int minLevel){
1668 return getNodeAtLevel(id, minLevel, DOMAIN);
1669 }
1670
1671 public TaxNode getNodeAtLevelExtended(int id, int minLevelE){
1672 return getNodeAtLevelExtended(id, minLevelE, DOMAIN_E);
1673 }
1674
1675 public TaxNode getNodeAtLevel(int id, int minLevel, int maxLevel){
1676 final int minLevelExtended=levelToExtended(minLevel);
1677 final int maxLevelExtended=levelToExtended(maxLevel);
1678 return getNodeAtLevelExtended(id, minLevelExtended, maxLevelExtended);
1679 }
1680
1681 public TaxNode getNodeAtLevelExtended(int id, int minLevelE, int maxLevelE){
1682 TaxNode tn=getNode(id);
1683 while(tn!=null && tn.pid!=tn.id && tn.levelExtended<minLevelE){
1684 TaxNode temp=getNode(tn.pid);
1685 if(temp==null || temp.levelExtended>maxLevelE){break;}
1686 tn=temp;
1687 }
1688 return tn;
1689 }
1690
1691 public int getIdAtLevelExtended(int taxID, int taxLevelExtended){
1692 if(taxLevelExtended<0){return taxID;}
1693 TaxNode tn=getNode(taxID);
1694 while(tn!=null && tn.id!=tn.pid && tn.levelExtended<taxLevelExtended){
1695 tn=getNode(tn.pid);
1696 if(tn.levelExtended>taxLevelExtended){break;}
1697 taxID=tn.id;
1698 }
1699 return taxID;
1700 }
1701
1702 /**
1703 * Fetch the node with this name.
1704 * Throw an assertion if there are multiple such nodes.
1705 * @param s Organism name.
1706 * @return Node with given name.
1707 */
1708 public TaxNode getNodeByName(String s){
1709 List<TaxNode> list=getNodesByName(s, false);
1710 if(list==null){list=getNodesByName(s, true);}
1711 if(list==null || list.isEmpty()){return null;}
1712 if(list.size()==1){return list.get(0);}
1713 assert(false) : "Found multiple nodes for '"+s+"':\n"+list+"\n";
1714 TaxNode a=list.get(0);
1715 for(int i=1; i<list.size(); i++){
1716 TaxNode b=list.get(i);
1717 //Keep the most specific node
1718 // if(a==null || (b!=null && b.minAncestorLevelIncludingSelf()<a.minAncestorLevelIncludingSelf())){//not necessary
1719 if(b.minAncestorLevelIncludingSelf()<a.minAncestorLevelIncludingSelf()){
1720 a=b;
1721 }
1722 }
1723 return a;
1724 }
1725
1726 /**
1727 * Fetch a list of all nodes with this name.
1728 * @param s Organism name.
1729 * @return Nodes with given name.
1730 */
1731 public List<TaxNode> getNodesByName(String s){
1732 List<TaxNode> list=getNodesByName(s, false);
1733 if(list==null){list=getNodesByName(s, true);}
1734 return list;
1735 }
1736
1737 /**
1738 * Fetch a map of names to nodes. If absent, create it first.
1739 * @param lowercase If true, return the map with lowercase keys.
1740 * @return Map of names to nodes.
1741 */
1742 private HashMap<String, ArrayList<TaxNode>> getMap(boolean lowercase){
1743 HashMap<String, ArrayList<TaxNode>> map=(lowercase ? nameMapLower : nameMap);
1744 if(map==null){
1745 synchronized(this){hashNames(true);}
1746 map=(lowercase ? nameMapLower : nameMap);
1747 }
1748 assert(map!=null) : "Tax names were not hashed.";
1749 return map;
1750 }
1751
1752 private List<TaxNode> getNodesByName(String s, boolean lowercase){
1753 if(s==null){return null;}
1754 if(s.indexOf('_')>=0){s=s.replace('_', ' ');}
1755 if(lowercase){s=s.toLowerCase();}
1756 // System.err.println("Searching for "+s);
1757 final HashMap<String, ArrayList<TaxNode>> map=getMap(lowercase);
1758 ArrayList<TaxNode> list=map.get(s);
1759 if(list!=null){return list;}
1760 // System.err.println("No matches for '"+s+"'");
1761
1762 // assert(false) : nameMap.containsKey(s)+", "+nameMapLower.containsKey(s);
1763
1764 if(s.indexOf('_')<0 && s.indexOf(' ')<0){return null;}
1765 String[] split=delimiter2.split(lowercase ? s.toLowerCase() : s, 8);
1766 // System.err.println("Array: "+Arrays.toString(split));
1767 list=map.get(split[split.length-1]);
1768 if(list==null){return list;}
1769 // System.err.println(list==null ? "No matches for "+split[split.length-1] : "Found list( "+list.size()+")");
1770
1771 int matchCount=0;
1772 for(TaxNode tn : list){
1773 if(tn.matchesName(split, split.length-1, this)){matchCount++;}
1774 }
1775 if(matchCount==list.size()){return list;}
1776 if(matchCount<1){return null;}
1777 ArrayList<TaxNode> hits=new ArrayList<TaxNode>(matchCount);
1778 for(TaxNode tn : list){
1779 if(tn.matchesName(split, split.length-1, this)){hits.add(tn);}
1780 }
1781 return hits;
1782 }
1783 public ArrayList<TaxNode> getAncestors(int id){
1784 TaxNode current=getNode(id);
1785 ArrayList<TaxNode> list=new ArrayList<TaxNode>();
1786 while(current!=null && current.pid!=current.id){//ignores root
1787 list.add(current);
1788 current=getNode(current.pid);
1789 }
1790 //optionally add root here
1791 return list;
1792 }
1793
1794 public void increment(IntList ids, IntList counts, boolean sync){
1795
1796 ids.sort();
1797 ids.getUniqueCounts(counts);
1798
1799 if(!sync){
1800 for(int i=0; i<ids.size; i++){
1801 int id=ids.get(i);
1802 int count=counts.get(i);
1803 incrementRaw(id, count);
1804 }
1805 }else{
1806 synchronized(this){
1807 for(int i=0; i<ids.size; i++){
1808 int id=ids.get(i);
1809 int count=counts.get(i);
1810 incrementRaw(id, count);
1811 }
1812 }
1813 }
1814 }
1815
1816 public void incrementRaw(int id, long amt){
1817 assert(id>=0 && id<nodes.length) : "TaxID "+id+" is out of range."+(id<0 ? "" : " Possibly the taxonomy data needs to be updated.");
1818 assert(nodes[id]!=null) : "No node for TaxID "+id+"; possibly the taxonomy data needs to be updated.";
1819 nodes[id].incrementRaw(amt);
1820 }
1821
1822 public void percolateUp(){
1823 for(int i=0; i<treeLevelsExtended.length; i++){
1824 percolateUp(i);
1825 }
1826 }
1827
1828 public void percolateUp(final int fromLevel){
1829 final TaxNode[] stratum=treeLevelsExtended[fromLevel];
1830 for(final TaxNode n : stratum){
1831 n.incrementSum(n.countRaw);
1832 TaxNode parent=nodes[n.pid];
1833 if(n!=parent){
1834 parent.incrementSum(n.countSum);
1835 }
1836 }
1837 }
1838
1839 /** Add this amount to the node and all its ancestors. */
1840 public void percolateUp(TaxNode node, long amt){
1841 if(amt==0){return;}
1842 if(verbose){System.err.println("percolateUp("+amt+") node: "+node);}
1843 while(node.id!=node.pid){
1844 node.incrementSum(amt);
1845 node=nodes[node.pid];
1846 }
1847 node.incrementSum(amt);
1848 }
1849
1850 public ArrayList<TaxNode> gatherNodesAtLeastLimit(final long limit){
1851 return gatherNodesAtLeastLimit(limit, 0, nodesPerLevelExtended.length-1);
1852 }
1853
1854 public ArrayList<TaxNode> gatherNodesAtLeastLimit(final long limit, final int minLevel, final int maxLevel){
1855 final int minLevelExtended=levelToExtended(minLevel);
1856 final int maxLevelExtended=levelToExtended(maxLevel);
1857 // assert(false) : limit+", "+minLevel+", "+maxLevel+", "+minLevelExtended+", "+maxLevelExtended;
1858 ArrayList<TaxNode> list=new ArrayList<TaxNode>();
1859 for(int i=minLevelExtended; i<nodesPerLevelExtended.length && i<=maxLevelExtended; i++){
1860 list.addAll(gatherNodesAtLeastLimitExtended(i, limit));
1861 }
1862 Shared.sort(list, TaxNode.countComparator);
1863 return list;
1864 }
1865
1866 public ArrayList<TaxNode> gatherNodesAtLeastLimitExtended(final int fromLevelExtended, final long limit){
1867 ArrayList<TaxNode> list=new ArrayList<TaxNode>();
1868 final TaxNode[] stratum=treeLevelsExtended[fromLevelExtended];
1869 for(final TaxNode n : stratum){
1870 if(n.countSum>=limit){
1871 list.add(n);
1872 TaxNode parent=nodes[n.pid];
1873 if(n!=parent){
1874 percolateUp(parent, -n.countSum);//123 This was negative for some reason
1875 }
1876 }
1877 }
1878 Shared.sort(list, TaxNode.countComparator);
1879 return list;
1880 }
1881
1882 /*--------------------------------------------------------------*/
1883 /*---------------- Static Initializers ----------------*/
1884 /*--------------------------------------------------------------*/
1885
1886 /**
1887 * Generate the name to level number map.
1888 */
1889 private static HashMap<String, Integer> makeLevelMap() {
1890 HashMap<String, Integer> map=new HashMap<String, Integer>(31);
1891 for(int i=0; i<taxLevelNames.length; i++){
1892 map.put(taxLevelNames[i], i);
1893 map.put(taxLevelNames[i].toUpperCase(), i);
1894 }
1895 map.put("clade", NO_RANK);
1896 map.put("clade".toUpperCase(), NO_RANK);
1897 return map;
1898 }
1899
1900 /**
1901 * Generate the name to extended level number map.
1902 */
1903 private static HashMap<String, Integer> makeLevelMapExtended() {
1904 HashMap<String, Integer> map=new HashMap<String, Integer>(129);
1905 for(int i=0; i<taxLevelNamesExtended.length; i++){
1906 map.put(taxLevelNamesExtended[i], i);
1907 map.put(taxLevelNamesExtended[i].toUpperCase(), i);
1908 }
1909 map.put("clade", NO_RANK_E);
1910 map.put("clade".toUpperCase(), NO_RANK_E);
1911 return map;
1912 }
1913
1914 /**
1915 * I think this maps normal and extend names to normal level numbers.
1916 */
1917 private static HashMap<String, Integer> makeAltLevelMap() {
1918 HashMap<String, Integer> map=new HashMap<String, Integer>(129);
1919 for(int i=0; i<taxLevelNames.length; i++){
1920 map.put(taxLevelNames[i], i);
1921 map.put(taxLevelNames[i].toUpperCase(), i);
1922 }
1923 map.put("clade", NO_RANK);
1924 map.put("clade".toUpperCase(), NO_RANK);
1925
1926 //Add synonyms
1927 // map.put("subfamily", map.get("family"));
1928 // map.put("tribe", map.get("family"));
1929 // map.put("varietas", map.get("subspecies"));
1930 // map.put("subgenus", map.get("genus"));
1931 // map.put("forma", map.get("subspecies"));
1932 // map.put("species group", map.get("genus"));
1933 // map.put("species subgroup", map.get("genus"));
1934 // map.put("cohort", map.get("class"));
1935 // map.put("subclass", map.get("class"));
1936 // map.put("infraorder", map.get("order"));
1937 // map.put("superorder", map.get("class"));
1938 // map.put("subphylum", map.get("phylum"));
1939 // map.put("infraclass", map.get("class"));
1940 // map.put("superkingdom", map.get("division"));
1941 // map.put("parvorder", map.get("order"));
1942 // map.put("superclass", map.get("phylum"));
1943 // map.put("superphylum", map.get("kingdom"));
1944 // map.put("subkingdom", map.get("kingdom"));
1945 // map.put("superfamily", map.get("order"));
1946 // map.put("superkingdom", map.get("domain"));
1947 // map.put("suborder", map.get("order"));
1948 // map.put("subtribe", map.get("family"));
1949
1950 for(String[] array : taxLevelNamesExtendedMatrix){
1951 String head=array[array.length-1];
1952 Integer value=map.get(head);
1953 assert(value!=null) : head;
1954 for(String key : array){
1955 if(key!=head){
1956 assert(!map.containsKey(key)) : "Map already contains key "+key+": "+Arrays.toString(array);
1957 map.put(key, value);
1958 map.put(key.toUpperCase(), value);
1959 }
1960 }
1961 }
1962
1963 return map;
1964 }
1965
1966 /*--------------------------------------------------------------*/
1967 /*---------------- Size ----------------*/
1968 /*--------------------------------------------------------------*/
1969
1970 /** Number of bp associated with this node in RefSeq */
1971 public long toSize(TaxNode tn){
1972 if(tn==null){return 0;}
1973 if(refseqSizeMap==null){return -1L;}
1974 final long x=refseqSizeMap.get(tn.id);
1975 return Tools.max(0, x);
1976 }
1977
1978 /** Number of bp associated with this node and descendants in RefSeq */
1979 public long toSizeC(TaxNode tn){
1980 if(tn==null){return 0;}
1981 if(refseqSizeMapC==null){return -1L;}
1982 final long x=refseqSizeMapC.get(tn.id);
1983 return Tools.max(0, x);
1984 }
1985
1986 /** Number of sequences associated with this node in RefSeq */
1987 public int toSeqs(TaxNode tn){
1988 if(tn==null){return 0;}
1989 if(refseqSeqMap==null){return -1;}
1990 final int x=refseqSeqMap.get(tn.id);
1991 return Tools.max(0, x);
1992 }
1993
1994 /** Number of sequences associated with this node and descandants in RefSeq */
1995 public long toSeqsC(TaxNode tn){
1996 if(tn==null){return 0;}
1997 if(refseqSeqMapC==null){return -1L;}
1998 final long x=refseqSeqMapC.get(tn.id);
1999 return Tools.max(0, x);
2000 }
2001
2002 /** Number of descendants of this node */
2003 public int toNodes(TaxNode tn){
2004 if(tn==null){return 0;}
2005 if(nodeMapC==null){return -1;}
2006 final int x=nodeMapC.get(tn.id);
2007 return Tools.max(0, x);
2008 }
2009
2010 /**
2011 * Fills refseqSizeMap, refseqSizeMapC, etc. from a file containing the summary.
2012 * @param fname Size file name
2013 */
2014 public void loadSizeFile(String fname){
2015 if(fname==null){return;}
2016 assert(refseqSizeMap==null);
2017 refseqSizeMap=new IntLongHashMap();
2018 refseqSizeMapC=new IntLongHashMap();
2019 refseqSeqMap=new IntHashMap();
2020 refseqSeqMapC=new IntLongHashMap();
2021 nodeMapC=new IntHashMap();
2022
2023 final ByteFile bf=ByteFile.makeByteFile(fname, true);
2024 final byte delimiter='\t';
2025 for(byte[] line=bf.nextLine(); line!=null; line=bf.nextLine()){
2026 if(line.length>0 && line[0]!='#'){
2027 int a=0, b=0;
2028
2029 while(b<line.length && line[b]!=delimiter){b++;}
2030 assert(b>a) : "Missing field 0: "+new String(line);
2031 int tid=Parse.parseInt(line, a, b);
2032 b++;
2033 a=b;
2034
2035 while(b<line.length && line[b]!=delimiter){b++;}
2036 assert(b>a) : "Missing field 1: "+new String(line);
2037 long size=Parse.parseLong(line, a, b);
2038 b++;
2039 a=b;
2040
2041 while(b<line.length && line[b]!=delimiter){b++;}
2042 assert(b>a) : "Missing field 2: "+new String(line);
2043 long csize=Parse.parseLong(line, a, b);
2044 b++;
2045 a=b;
2046
2047 while(b<line.length && line[b]!=delimiter){b++;}
2048 assert(b>a) : "Missing field 3: "+new String(line);
2049 int seqs=Parse.parseInt(line, a, b);
2050 b++;
2051 a=b;
2052
2053 while(b<line.length && line[b]!=delimiter){b++;}
2054 assert(b>a) : "Missing field 4: "+new String(line);
2055 long cseqs=Parse.parseLong(line, a, b);
2056 b++;
2057 a=b;
2058
2059 while(b<line.length && line[b]!=delimiter){b++;}
2060 assert(b>a) : "Missing field 5: "+new String(line);
2061 int cnodes=Parse.parseInt(line, a, b);
2062 b++;
2063 a=b;
2064
2065 if(refseqSizeMap!=null && size>0){refseqSizeMap.put(tid, size);}
2066 if(refseqSizeMapC!=null && csize>0){refseqSizeMapC.put(tid, csize);}
2067 if(refseqSeqMap!=null && seqs>0){refseqSeqMap.put(tid, seqs);}
2068 if(refseqSeqMapC!=null && cseqs>0){refseqSeqMapC.put(tid, cseqs);}
2069 if(nodeMapC!=null && cnodes>0){nodeMapC.put(tid, cnodes);}
2070 }
2071 }
2072 bf.close();
2073 }
2074
2075 /*--------------------------------------------------------------*/
2076 /*---------------- IMG ----------------*/
2077 /*--------------------------------------------------------------*/
2078
2079 public static int imgToTaxid(long img){
2080 ImgRecord ir=imgMap.get(img);
2081 // assert(false) : "\n"+img+"\n"+imgMap.get(img)+"\n"+562+"\n"+imgMap.get(562)+"\n"+imgMap.size()+"\n"+IMGHQ+"\n"+defaultImgFile()+"\n";
2082 return ir==null ? -1 : ir.taxID;
2083 }
2084
2085 public TaxNode imgToTaxNode(long img){
2086 int tid=imgToTaxid(img);
2087 return tid<1 ? null : getNode(tid);
2088 }
2089
2090 // public static int loadIMGOld(String fname, boolean storeName, PrintStream outstream){
2091 // assert(imgMap==null);
2092 // if(fname==null){return 0;}
2093 // ImgRecord2.storeName=storeName;
2094 // if(outstream!=null){System.err.println("Loading IMG.");}
2095 // Timer t=new Timer(outstream, false);
2096 // ImgRecord2[] array=ImgRecord2.toArray(fname);
2097 // int x=loadIMG(array);
2098 // t.stopAndPrint();
2099 // return x;
2100 // }
2101
2102 public static int loadIMG(String fname, boolean storeName, PrintStream outstream){
2103 assert(imgMap==null);
2104 if(fname==null){return 0;}
2105 ImgRecord.storeName=storeName;
2106 if(outstream!=null){System.err.println("Loading IMG.");}
2107 Timer t=new Timer(outstream, false);
2108 ImgRecord[] array=ImgRecord.toArray(fname, IMG_HQ);
2109 int x=loadIMG(array);
2110 t.stopAndPrint();
2111 return x;
2112 }
2113
2114 public static int loadIMG(ImgRecord[] array){
2115 assert(imgMap==null);
2116 imgMap=new HashMap<Long, ImgRecord>((int)(array.length*1.5));
2117 for(ImgRecord record : array){
2118 imgMap.put(record.imgID, record);
2119 }
2120 return imgMap.size();
2121 }
2122
2123 @Deprecated
2124 public static int parseLevel(String b){
2125 final int level;
2126 if(b==null){level=-1;}
2127 else if(Tools.isNumeric(b.charAt(0))){
2128 level=Integer.parseInt(b);
2129 }else{
2130 level=stringToLevel(b.toLowerCase());
2131 }
2132 return level;
2133 }
2134
2135 public static int parseLevelExtended(String b){
2136 final int level;
2137 if(b==null){level=-1;}
2138 else if(Tools.isNumeric(b.charAt(0))){
2139 level=levelToExtended(Integer.parseInt(b));
2140 }else{
2141 level=stringToLevelExtended(b.toLowerCase());
2142 }
2143 return level;
2144 }
2145
2146 public boolean isUnclassified(int tid){
2147 TaxNode tn=getNode(tid);
2148 while(tn!=null && tn.id!=tn.pid){
2149 if(tn.isUnclassified()){return true;}
2150 if(tn.pid==tn.id){break;}
2151 tn=getNode(tn.pid);
2152 }
2153 return false;
2154 }
2155
2156 public boolean isEnvironmentalSample(int tid){
2157 TaxNode tn=getNode(tid);
2158 while(tn!=null && tn.id!=tn.pid){
2159 if(tn.isEnvironmentalSample()){return true;}
2160 if(tn.pid==tn.id){break;}
2161 tn=getNode(tn.pid);
2162 }
2163 return false;
2164 }
2165
2166 public boolean isVirus(int tid){
2167 TaxNode tn=getNode(tid);
2168 while(tn!=null && tn.id!=tn.pid){
2169 if(tn.id==VIRUSES_ID){return true;}
2170 if(tn.pid==tn.id){break;}
2171 tn=getNode(tn.pid);
2172 }
2173 return false;
2174 }
2175
2176 public long definedLevels(int tid){
2177 long levels=0;
2178 TaxNode tn=getNode(tid);
2179 while(tn!=null && tn.id!=tn.pid){
2180 levels=levels|(1L<<tn.level);
2181 }
2182 return levels;
2183 }
2184
2185 public long definedLevelsExtended(int tid){
2186 long levels=0;
2187 TaxNode tn=getNode(tid);
2188 while(tn!=null && tn.id!=tn.pid){
2189 levels=levels|(1L<<tn.levelExtended);
2190 }
2191 return levels;
2192 }
2193
2194 /**
2195 * Generates the mononomial name for this taxonomic level based on the scientific name.
2196 * For example, "Homo sapiens" -> "Sapiens"
2197 * @param tid TaxID
2198 * @return Correct name for this node.
2199 */
2200 public String mononomial(int tid){return mononomial(getNode(tid));}
2201 public String mononomial(TaxNode tn){
2202 if(tn==null){return null;}
2203 String name=tn.name;
2204 if(name.indexOf(' ')<0){return name;}
2205 TaxNode parent=getNode(tn.pid);
2206 if(parent==null){return name;}
2207 String pname=parent.name;
2208 if(name.length()>pname.length() && name.charAt(pname.length())==' ' && name.startsWith(pname)){
2209 name=name.substring(pname.length()+1);
2210 }
2211 return name;
2212 }
2213
2214 /*--------------------------------------------------------------*/
2215 /*---------------- Fields ----------------*/
2216 /*--------------------------------------------------------------*/
2217
2218 /** All nodes in the tree in a flat array, indexed by TaxiD */
2219 public final TaxNode[] nodes;
2220
2221 /** Number of nodes per normal level */
2222 public final int[] nodesPerLevel=new int[taxLevelNames.length];
2223
2224 /** Number of nodes per extended level */
2225 public final int[] nodesPerLevelExtended=new int[taxLevelNamesExtended.length];
2226
2227 /** Number of nodes in the tree */
2228 public final int nodeCount;
2229
2230 /** Maps old TaxIDs to new TaxIDs */
2231 public final IntHashMap mergedMap;
2232
2233 /** Arrays of all nodes at a given taxonomic level (extended) */
2234 public final TaxNode[][] treeLevelsExtended=new TaxNode[taxLevelNamesExtended.length][];
2235
2236 /** Map of names to nodes */
2237 HashMap<String, ArrayList<TaxNode>> nameMap;
2238 /** Map of lowercase names to nodes */
2239 HashMap<String, ArrayList<TaxNode>> nameMapLower;
2240 /** Map of nodes to child nodes */
2241 HashMap<TaxNode, ArrayList<TaxNode>> childMap;
2242 public HashMap<String, ArrayList<TaxNode>> nameMap(){return nameMap;}
2243
2244 @Deprecated
2245 public int minValidTaxa=0; //TODO: Remove (will break serialization)
2246
2247 /** Infer ranks for no-rank nodes, when possible */
2248 public boolean simplify=true;
2249 /** See simplify() for details, works in conjunction with simplify */
2250 public boolean reassign=true;
2251 /** Discard no-rank nodes */
2252 public boolean skipNorank=false;
2253 public int inferRankLimit=0;//levelMap.get("species");
2254
2255 //Node Statistics
2256 /** Number of bases assigned to this TaxID in RefSeq */
2257 private IntLongHashMap refseqSizeMap;
2258 /** Number of bases assigned to this TaxID and descendants in RefSeq */
2259 private IntLongHashMap refseqSizeMapC;
2260 /** Number of sequences assigned to this TaxID in RefSeq */
2261 private IntHashMap refseqSeqMap;
2262 /** Number of sequences assigned to this TaxID and descendants in RefSeq */
2263 private IntLongHashMap refseqSeqMapC;
2264 /** Number of descendant nodes, inclusive, for each TaxID */
2265 private IntHashMap nodeMapC;
2266
2267 /*--------------------------------------------------------------*/
2268 /*---------------- Statics ----------------*/
2269 /*--------------------------------------------------------------*/
2270
2271 /** Assign levels to unranked nodes below species level, when possible */
2272 public static boolean assignStrains=true;
2273 /** Assume headers are in Silva format */
2274 public static boolean SILVA_MODE=false;
2275 /** Assume headers are in Unite format */
2276 public static boolean UNITE_MODE=false;
2277 /** Probably unnecessary at this point... present for legacy reasons */
2278 public static boolean CRASH_IF_NO_GI_TABLE=true;
2279
2280 public static boolean verbose=false;
2281 public static boolean SHOW_WARNINGS=false;
2282
2283 /** Maps IMG IDs to records from the dump file */
2284 private static HashMap<Long, ImgRecord> imgMap;
2285
2286 /** Set to false if the tree is expected to be mutated.
2287 * @TODO Remove mutable fields from the tree (like counters).
2288 */
2289 public static boolean ALLOW_SHARED_TREE=true;
2290
2291 /** Universal location of the shared TaxTree used by various classes */
2292 private static TaxTree sharedTree;
2293
2294 /** A simpler and probably less safe version of sharedTree(...) */
2295 public static TaxTree getTree(){return sharedTree;}
2296
2297 /**
2298 * Fetch the shared tree, loading it from file if not present.
2299 * @return A tree.
2300 * @TODO: Check proper-construction of double-checked synchronize
2301 */
2302 private static TaxTree sharedTree(String fname, boolean hashNames, boolean hashDotFormat, PrintStream outstream) {
2303 if(!ALLOW_SHARED_TREE){return null;}
2304 if(sharedTree==null && fname!=null){
2305 if("auto".equalsIgnoreCase(fname)){fname=defaultTreeFile();}
2306 synchronized(TaxTree.class){
2307 if(sharedTree==null){
2308 // if(outstream!=null){outstream.println("Loading tax tree.");}
2309 if(outstream!=null){outstream.println("Loading tax tree from "+fname);} //Useful for debugging
2310 Timer t=new Timer(outstream, false);
2311 setSharedTree(ReadWrite.read(TaxTree.class, fname, true), hashNames, hashDotFormat);
2312 t.stopAndPrint();
2313 }
2314 }
2315 }
2316 if(hashNames && sharedTree.nameMap==null){
2317 synchronized(sharedTree){
2318 if(sharedTree.nameMap==null){
2319 if(outstream!=null){outstream.println("Hashing names.");}
2320 Timer t=new Timer(outstream, false);
2321 sharedTree.hashNames(hashDotFormat);
2322 t.stopAndPrint();
2323 }
2324 }
2325 }
2326 return sharedTree;
2327 }
2328
2329 /**
2330 * For initialization. Normally only one tree is needed by a process so it is set here.
2331 * If the tree is already set nothing will happen, unless additional hashing is needed.
2332 */
2333 private static synchronized void setSharedTree(TaxTree tree, boolean hashNames, boolean hashDotFormat){
2334 assert(ALLOW_SHARED_TREE);
2335 assert(sharedTree==null);
2336 sharedTree=tree;
2337 if(hashNames && sharedTree.nameMap==null){
2338 synchronized(sharedTree){
2339 if(sharedTree.nameMap==null){
2340 sharedTree.hashNames(hashDotFormat);
2341 }
2342 }
2343 }
2344 }
2345
2346 /**
2347 * Determine whether a taxonomic level is standard. e.g.:<br>
2348 * isSimple("phylum")=true<br>
2349 * isSimple("subphylum")=false<br>
2350 * isSimple("no-rank")=false
2351 * @param levelExtended The extended level to test.
2352 * @return True if this level is not no-rank, and the names of the normal and extended levels match.
2353 */
2354 public static boolean isSimple(int levelExtended){
2355 int level=extendedToLevel(levelExtended);
2356 return levelExtended!=NO_RANK_E && (levelExtended==levelToExtended(level));
2357 }
2358
2359 /**
2360 * Determine whether a taxonomic level is standard, but allows substrain and lower. e.g.:<br>
2361 * isSimple("phylum")=true<br>
2362 * isSimple("substrain")=true<br>
2363 * isSimple("subphylum")=false<br>
2364 * isSimple("no-rank")=false
2365 * @param levelExtended The extended level to test.
2366 * @return True if this level is not no-rank, and the names of the normal and extended levels match.
2367 */
2368 public static boolean isSimple2(int levelExtended){
2369 int level=extendedToLevel(levelExtended);
2370 return levelExtended!=NO_RANK_E && (levelExtended==levelToExtended(level)
2371 || levelExtended==STRAIN_E || levelExtended==SUBSPECIES_E || levelExtended==SUBSTRAIN_E);
2372 }
2373
2374 /*--------------------------------------------------------------*/
2375 /*---------------- Constants ----------------*/
2376 /*--------------------------------------------------------------*/
2377
2378 /** Get the number for the normal level of this name */
2379 public static final int stringToLevel(String s){return altLevelMap.get(s);}
2380 public static final boolean levelMapExtendedContains(String s){return levelMapExtended.containsKey(s);}
2381 /** Get the number for the extended level of this name */
2382 public static final int stringToLevelExtended(String s){return levelMapExtended.get(s);}
2383 /** Get the normal name for this normal level */
2384 public static final String levelToString(int x){return taxLevelNames[x];}
2385 /** Get the extended name for this extended level */
2386 public static final String levelToStringExtended(int x){return taxLevelNamesExtended[x];}
2387 /** Get the abbreviated name for this normal level */
2388 public static final String levelToStringShort(int x){return taxLevelNamesShort[x];}
2389
2390 /** Normal, aka canonical, aka simple tax level names */
2391 private static final String[] taxLevelNames=new String[] {
2392 "no rank", "subspecies", "species", "genus",
2393 "family", "order", "class", "phylum",
2394 "kingdom", "superkingdom", "domain", "life"
2395 };
2396 public static final int numTaxLevelNames=taxLevelNames.length;
2397
2398 /**
2399 * Definitive representation of all NCBI taxonomic level names.
2400 * All levels used by NCBI must be present here, or parsing a new NCBI tax tree will crash.
2401 * The first dimension maps normal ranks to extended ranks.
2402 * Both dimensions are ordered ascending.
2403 * @TODO Note! If this goes over 63 names it will cause a problem with getDefinedLevels().
2404 */
2405 //TODO See @TODO
2406 private static final String[][] taxLevelNamesExtendedMatrix=new String[][] {
2407 {"no rank"},
2408 {"subgenotype", "genotype", "substrain", "isolate", "strain", "pathotype", "pathogroup",
2409 "biotype", "serotype", "serogroup", "morph", "forma specialis", "forma", "subvariety", "varietas",
2410 "subspecies"},
2411 {"species"},
2412 {"species subgroup", "species group", "series", "subsection", "section", "subgenus", "genus"},
2413 {"subtribe", "tribe", "subfamily", "family"},
2414 {"superfamily", "parvorder", "infraorder", "suborder", "order"},
2415 {"superorder", "subcohort", "cohort", "infraclass", "subclass", "class"},
2416 {"superclass", "subdivision", "division", "subphylum", "phylum"},
2417 {"superphylum", "subkingdom", "kingdom"},
2418 {"superkingdom"},
2419 {"domain"},
2420 {"life"}
2421 };
2422
2423 /** Extended tax level names as a 1D array */
2424 private static final String[] taxLevelNamesExtended=makeNamesExtended();
2425 /** Number of extended tax levels */
2426 public static final int numTaxLevelNamesExtended=taxLevelNamesExtended.length;
2427
2428 /** Flatten the extended tax level names matrix to a 1D array */
2429 private static final String[] makeNamesExtended(){
2430 ArrayList<String> list=new ArrayList<String>();
2431 for(String[] s : taxLevelNamesExtendedMatrix){
2432 for(String ss : s){
2433 list.add(ss);
2434 }
2435 }
2436 return list.toArray(new String[0]);
2437 }
2438
2439 /** Abbreviations of tax level names, mainly for semicolon form */
2440 private static final String[] taxLevelNamesShort=new String[] {
2441 "nr", "ss", "s", "g",
2442 "f", "o", "c", "p",
2443 "k", "sk", "d", "l"
2444 };
2445
2446 /** Normal tax level numbers as constants */
2447 public static final int NO_RANK=0, SUBSPECIES=1, SPECIES=2, GENUS=3,
2448 FAMILY=4, ORDER=5, CLASS=6, PHYLUM=7, KINGDOM=8, SUPERKINGDOM=9, DOMAIN=10, LIFE=11;
2449
2450 /** TaxID of Life node */
2451 public static final int LIFE_ID=1;
2452 /** TaxID of Cellular Organisms node */
2453 public static final int CELLULAR_ORGANISMS_ID=131567;
2454 /** TaxID of Bacteria node */
2455 public static final int BACTERIA_ID=2; //Is this safe? Who knows...
2456 /** TaxID of Archaea node */
2457 public static final int ARCHAEA_ID=2157;
2458 /** TaxID of Euk node */
2459 public static final int EUKARYOTA_ID=2759;
2460 /** TaxID of Animal node */
2461 public static final int METAZOA_ID=33208, ANIMALIA_ID=33208;
2462 /** TaxID of Plant node */
2463 public static final int VIRIDIPLANTAE_ID=33090, PLANTAE_ID=33090;
2464 /** TaxID of Fungi node */
2465 public static final int FUNGI_ID=4751;
2466 /** TaxID of Virus node */
2467 public static final int VIRUSES_ID=10239;
2468 /** TaxID of Viroids node (now defunct) */
2469 public static final int VIROIDS_ID=12884;
2470
2471 /** Maps normal level names to normal level numbers */
2472 private static final HashMap<String, Integer> levelMap=makeLevelMap();
2473 /** Maps extended level names to extended level numbers */
2474 private static final HashMap<String, Integer> levelMapExtended=makeLevelMapExtended();
2475 /** Maps extended level names to normal level numbers */
2476 private static final HashMap<String, Integer> altLevelMap=makeAltLevelMap();
2477
2478 /** Common extended level numbers as constants */
2479 public static final int NO_RANK_E=NO_RANK,
2480 SUBSTRAIN_E=stringToLevelExtended("substrain"), STRAIN_E=stringToLevelExtended("strain"),
2481 SUBSPECIES_E=stringToLevelExtended("subspecies"),
2482 SPECIES_E=stringToLevelExtended("species"), GENUS_E=stringToLevelExtended("genus"),
2483 FAMILY_E=stringToLevelExtended("family"), ORDER_E=stringToLevelExtended("order"),
2484 CLASS_E=stringToLevelExtended("class"), PHYLUM_E=stringToLevelExtended("phylum"),
2485 KINGDOM_E=stringToLevelExtended("kingdom"), SUPERKINGDOM_E=stringToLevelExtended("superkingdom"),
2486 DOMAIN_E=stringToLevelExtended("domain"), LIFE_E=stringToLevelExtended("life");
2487
2488 /** Map of normal to extended level numbers */
2489 private static final int[] levelToExtended=new int[] {
2490 NO_RANK_E, SUBSPECIES_E, SPECIES_E, GENUS_E, FAMILY_E,
2491 ORDER_E, CLASS_E, PHYLUM_E, KINGDOM_E, SUPERKINGDOM_E, DOMAIN_E, LIFE_E
2492 };
2493
2494 /** Map of extended to normal level numbers */
2495 private static final int[] extendedToLevel=makeExtendedToLevel();
2496
2497 /** Creates extendedToLevel from taxaNamesExtendedMatrix during initialization. */
2498 private static int[] makeExtendedToLevel(){
2499 int len=0;
2500 for(String[] array : taxLevelNamesExtendedMatrix){
2501 len+=array.length;
2502 }
2503 int[] ret=new int[len];
2504
2505 int pos=0;
2506 for(int level=0; level<taxLevelNamesExtendedMatrix.length; level++){
2507 String[] array=taxLevelNamesExtendedMatrix[level];
2508 for(int i=0; i<array.length; i++){
2509 ret[pos]=level;
2510 pos++;
2511 }
2512 }
2513 return ret;
2514 }
2515
2516 /** Convert a standard level number (like KINGDOM) to extended (like KINGDOM_E). */
2517 public static final int levelToExtended(int level){
2518 return level<0 ? level : levelToExtended[level];
2519 }
2520
2521 /** Convert an extended level number (like PHYLUM_E) to extended (like PHYLUM).
2522 * Non-standard levels will be converted to the next higher standard level;
2523 * e.g., subphylum -> phylum */
2524 public static final int extendedToLevel(int extended){
2525 return extended<0 ? -1 : extendedToLevel[extended];
2526 }
2527
2528 /* Pre-compiled delimiters to save time when splitting lines */
2529 private static final Pattern delimiterTab = Pattern.compile("\t");
2530 private static final Pattern delimiter = Pattern.compile("\t\\|\t");
2531 private static final Pattern delimiterPipe = Pattern.compile("\\|");
2532 private static final Pattern delimiterTilde = Pattern.compile("\\~");
2533 private static final Pattern delimiter2 = Pattern.compile("[\\s_]+");
2534
2535 public static boolean IMG_HQ=false;
2536
2537 /* For these fields, see the corresponding functions, below.
2538 * They define the default paths to various data on NERSC. */
2539
2540 private static final String defaultTaxPathNersc="/global/cfs/cdirs/bbtools/tax/latest";
2541 private static final String defaultTaxPathAws="/test1/tax/latest";
2542 private static final String defaultTaxPathIGBVM="/data/tax/latest";
2543 private static final String defaultTaxPathDori="/clusterfs/jgi/groups/gentech/homes/bbushnell/tax/latest";
2544 private static final String default16SFileNersc="/global/cfs/cdirs/bbtools/silva/16S_consensus_with_silva_maxns10_taxsorted.fa.gz";
2545 private static final String default16SFileAws="/test1/16S_consensus_with_silva_maxns10_taxsorted.fa.gz";
2546 private static final String default16SFileIGBVM="/data/sketch/silva/16S_consensus_with_silva_maxns10_taxsorted.fa.gz";
2547 private static final String default18SFileNersc="/global/cfs/cdirs/bbtools/silva/18S_consensus_silva_maxns10_taxsorted.fa.gz";
2548 private static final String default18SFileAws="/test1/18S_consensus_silva_maxns10_taxsorted.fa.gz";
2549 private static final String default18SFileIGBVM="/data/sketch/silva/18S_consensus_with_silva_maxns10_taxsorted.fa.gz";
2550
2551 private static final String defaultImgFile="TAX_PATH/imgDump.txt";
2552 private static final String defaultTableFileInt="TAX_PATH/gitable.int1d.gz";
2553 private static final String defaultTableFile="TAX_PATH/gitable.int2d.gz";
2554 private static final String defaultTreeFile="TAX_PATH/tree.taxtree.gz";
2555 private static final String defaultPatternFile="TAX_PATH/patterns.txt";
2556 private static final String defaultSizeFile="TAX_PATH/taxsize.tsv.gz";
2557
2558 private static final String defaultAccessionFile=
2559 //"TAX_PATH/shrunk.protF.accession2taxid.gz," +
2560 "TAX_PATH/shrunk.prot.accession2taxid.gz,"
2561 + "TAX_PATH/shrunk.nucl_wgs.accession2taxid.gz,"
2562 + "TAX_PATH/shrunk.nucl_gb.accession2taxid.gz,"
2563 + "TAX_PATH/shrunk.dead_prot.accession2taxid.gz,"
2564 // + "TAX_PATH/shrunk.nucl_est.accession2taxid.gz,"
2565 + "TAX_PATH/shrunk.dead_wgs.accession2taxid.gz,"
2566 // + "TAX_PATH/shrunk.nucl_gss.accession2taxid.gz,"
2567 + "TAX_PATH/shrunk.dead_nucl.accession2taxid.gz,"
2568 + "TAX_PATH/shrunk.pdb.accession2taxid.gz";
2569
2570 /** For setting TAX_PATH, the root to taxonomy files */
2571 public static final String defaultTaxPath(){
2572 return (Shared.AWS && !Shared.NERSC) ? defaultTaxPathAws : Shared.IGBVM ? defaultTaxPathIGBVM : Shared.DORI ? defaultTaxPathDori : defaultTaxPathNersc;
2573 }
2574
2575 /** 16S consensus sequences per TaxID */
2576 public static final String default16SFile(){
2577 return (Shared.AWS && !Shared.NERSC) ? default16SFileAws : Shared.IGBVM ? default16SFileIGBVM : default16SFileNersc;
2578 }
2579
2580 /** 18S consensus sequences per TaxID */
2581 public static final String default18SFile(){
2582 return (Shared.AWS && !Shared.NERSC) ? default18SFileAws : Shared.IGBVM ? default18SFileIGBVM : default18SFileNersc;
2583 }
2584
2585 /** Path to all taxonomy files, substituted in to make specific file paths */
2586 public static String TAX_PATH=defaultTaxPath();
2587
2588 /** Location of gitable.int2d.gz for gi lookups */
2589 public static final String defaultTableFile(){return defaultTableFile.replaceAll("TAX_PATH", TAX_PATH);}
2590 /** Location of tree.taxtree.gz */
2591 public static final String defaultTreeFile(){return defaultTreeFile.replaceAll("TAX_PATH", TAX_PATH);}
2592
2593 //Use the prot.FULL.gz ncbi file.
2594 public static boolean protFull=false;
2595
2596 /** Location of shrunk.*.accession2taxid.gz (all accession files, comma-delimited) */
2597 public static final String defaultAccessionFile(){
2598 String s=(protFull ? "TAX_PATH/shrunk.protF.accession2taxid.gz," : "")+defaultAccessionFile;
2599 return s.replaceAll("TAX_PATH", TAX_PATH);
2600 }
2601 /** Location of patterns.txt, which holds information about observed accession string formats */
2602 public static final String defaultPatternFile(){return defaultPatternFile.replaceAll("TAX_PATH", TAX_PATH);}
2603 /** Location of imgDump.txt, which translates IMG to NCBI IDs for internal JGI use */
2604 public static final String defaultImgFile(){return defaultImgFile.replaceAll("TAX_PATH", TAX_PATH);}
2605 /** Location of taxsize.tsv, which indicates the amount of sequence associated with a TaxID */
2606 public static final String defaultSizeFile(){return defaultSizeFile.replaceAll("TAX_PATH", TAX_PATH);}
2607
2608 /** Screen output gets printed here */
2609 private static PrintStream outstream=System.out;
2610
2611 }