Debian Codegraph @

current/tax/TaxFilter.java

raw symbols SCIP
1 package tax;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.HashSet;
7 import java.util.List;
8 import java.util.regex.Pattern;
9
10 import fileIO.TextFile;
11 import shared.KillSwitch;
12 import shared.Parse;
13 import shared.PreParser;
14 import shared.Tools;
15 import stream.Read;
16
17 /**
18 * @author Brian Bushnell
19 * @date Nov 30, 2015
20 *
21 */
22 public class TaxFilter {
23
24 public static void main(String[] args){
25 String regex=args[0];
26 String s=args[1];
27 Pattern regexPattern=Pattern.compile(regex);
28 boolean b=regexPattern.matcher(s).matches();
29 System.err.println(regex);
30 System.err.println(s);
31 System.err.println(b);
32 }
33
34 /*--------------------------------------------------------------*/
35 /*---------------- Constructors ----------------*/
36 /*--------------------------------------------------------------*/
37
38 /**
39 * Constructor.
40 * @param args Command line arguments
41 */
42 public static TaxFilter makeFilter(String[] args){
43
44 {//Preparse block for help, config files, and outstream
45 PreParser pp=new PreParser(args, new Object() { }.getClass().getEnclosingClass(), false);
46 args=pp.args;
47 outstream=pp.outstream;
48 }
49
50 String names=null;
51 String ids=null;
52
53 String giTableFile=null;
54 String taxTreeFile=null;
55 String accessionFile=null;
56
57 int taxLevelE=-1;
58 int reqLevels=0;
59 boolean include=false;
60 boolean promote=true;
61 String regex=null;
62 String contains=null;
63
64 for(int i=0; i<args.length; i++){
65 String arg=args[i];
66
67 //Break arguments into their constituent parts, in the form of "a=b"
68 String[] split=arg.split("=");
69 String a=split[0].toLowerCase();
70 String b=split.length>1 ? split[1] : null;
71
72 if(a.equals("table") || a.equals("gi")){
73 giTableFile=b;
74 }else if(a.equals("tree") || a.equals("taxtree")){
75 taxTreeFile=b;
76 }else if(a.equals("accession")){
77 accessionFile=b;
78 }else if(a.equals("level") || a.equals("lv") || a.equals("taxlevel") || a.equals("tl")){
79 taxLevelE=TaxTree.parseLevelExtended(b);
80 // System.err.println("Set taxLevelE = "+TaxTree.levelToStringExtended(taxLevelE)); //123
81 }else if(a.equals("reqlevel") || a.equals("requiredlevel") || a.equals("reqlevels") || a.equals("requiredlevels")){
82 assert(b!=null) : "Bad parameter: "+arg;
83 String[] split2=b.toLowerCase().split(",");
84 reqLevels=0;
85 for(String s : split2){
86 int level=TaxTree.parseLevel(s);
87 reqLevels|=(1<<level);
88 }
89 }else if(a.equals("name") || a.equals("names")){
90 names=b;
91 }else if(a.equals("regex")){
92 regex=b;
93 }else if(a.equals("contains")){
94 contains=b;
95 }else if(a.equals("printnodesadded") || a.equals("printnodes")){
96 printNodesAdded=Parse.parseBoolean(b);
97 }else if(a.equals("promote")){
98 promote=Parse.parseBoolean(b);
99 }else if(a.equals("include")){
100 include=Parse.parseBoolean(b);
101 }else if(a.equals("exclude")){
102 include=!Parse.parseBoolean(b);
103 }else if(a.equals("requirepresent")){
104 REQUIRE_PRESENT=Parse.parseBoolean(b);
105 TaxTree.SHOW_WARNINGS=REQUIRE_PRESENT;
106 }else if(a.equals("id") || a.equals("ids") || a.equals("taxid") || a.equals("tid") || a.equals("taxids")){
107 ids=b;
108 }
109 }
110
111 if("auto".equalsIgnoreCase(taxTreeFile)){taxTreeFile=TaxTree.defaultTreeFile();}
112 if("auto".equalsIgnoreCase(giTableFile)){giTableFile=TaxTree.defaultTableFile();}
113 if("auto".equalsIgnoreCase(accessionFile)){accessionFile=TaxTree.defaultAccessionFile();}
114
115 TaxTree tree=loadTree(taxTreeFile);
116 loadGiTable(giTableFile);
117 loadAccession(accessionFile, tree);
118
119 TaxFilter filter=new TaxFilter(tree, taxLevelE, reqLevels, include, promote, null, regex, contains);
120 filter.addNames(names);
121 filter.addNumbers(ids, true);
122 return filter;
123 }
124
125 /**
126 * Constructor.
127 * @param tree_
128 */
129 public TaxFilter(TaxTree tree_, boolean include_){
130 this(tree_, -1, 0, include_, true, null, null, null);
131 }
132
133 /**
134 * Constructor.
135 */
136 public TaxFilter(TaxTree tree_, int taxLevelE_, int reqLevels_, boolean include_, boolean promote_,
137 HashSet<Integer> taxSet_, String regex_, String contains_){
138 tree=tree_;
139 taxLevelE=taxLevelE_;
140 reqLevels=reqLevels_;
141 include=include_;
142 promote=promote_;
143 taxSet=(taxSet_==null ? new HashSet<Integer>() : taxSet_);
144 regex=regex_;
145 regexPattern=(regex==null ? null : Pattern.compile(regex));
146 containsString=contains_;
147 }
148
149 /** Alter taxSet and taxLevel to ensure they intersect with the file contents. */
150 public void reviseByBestEffort(String fname){
151 HashSet<Integer> desired=new HashSet<Integer>();
152 int currentLevelE=taxLevelE;
153 for(int i : taxSet){
154 int x=tree.getIdAtLevelExtended(i, currentLevelE);
155 desired.add(x);
156 }
157 HashSet<Integer> present=new HashSet<Integer>();
158 TextFile tf=new TextFile(fname);
159 for(String line=tf.nextLine(); line!=null; line=tf.nextLine()){
160 if(line.startsWith(">")){
161 TaxNode tn=tree.parseNodeFromHeader(line.substring(1), true);
162 if(tn!=null){
163 present.add(tree.getIdAtLevelExtended(tn.id, currentLevelE));
164 }
165 }
166 }
167
168 while(currentLevelE<TaxTree.LIFE_E){
169 //Intersect
170 for(Integer i : desired){
171 if(present.contains(i)){
172 if(currentLevelE!=taxLevelE){System.err.println("Widened filter from "+
173 TaxTree.levelToStringExtended(taxLevelE)+" to "+TaxTree.levelToStringExtended(currentLevelE));}
174 taxLevelE=currentLevelE;
175 taxSet=desired;
176 return;
177 }
178 }
179 currentLevelE++;
180
181 HashSet<Integer> desired2=new HashSet<Integer>();
182 for(int i : desired){
183 desired2.add(tree.getIdAtLevelExtended(i, currentLevelE));
184 }
185 desired=desired2;
186
187 HashSet<Integer> present2=new HashSet<Integer>();
188 for(int i : present){
189 present2.add(tree.getIdAtLevelExtended(i, currentLevelE));
190 }
191 present=present2;
192 }
193 }
194
195 public static boolean validArgument(String a){
196 if(a.equals("table") || a.equals("gi")){
197 }else if(a.equals("tree") || a.equals("taxtree")){
198 }else if(a.equals("accession")){
199 }else if(a.equals("taxpath")){
200 }else if(a.equals("level") || a.equals("lv") || a.equals("taxlevel") || a.equals("tl")){
201 }else if(a.equals("name") || a.equals("names")){
202 }else if(a.equals("regex")){
203 }else if(a.equals("contains")){
204 }else if(a.equals("besteffort")){
205 }else if(a.equals("include")){
206 }else if(a.equals("promote")){
207 }else if(a.equals("exclude")){
208 }else if(a.equals("printnodesadded") || a.equals("printnodes")){
209 }else if(a.equals("id") || a.equals("ids") || a.equals("taxid") || a.equals("tid") || a.equals("taxids")){
210 }else if(a.equals("requirepresent")){
211 }else if(a.equals("reqlevel") || a.equals("requiredlevel") || a.equals("reqlevels") || a.equals("requiredlevels")){
212 }else{
213 return false;
214 }
215 return true;
216 }
217
218 /*--------------------------------------------------------------*/
219 /*---------------- Initialization ----------------*/
220 /*--------------------------------------------------------------*/
221
222 private static void loadAccession(String accessionFile, TaxTree tree){
223 if(accessionFile!=null){
224 AccessionToTaxid.tree=tree;
225 assert(tree!=null);
226 outstream.println("Loading accession table.");
227 AccessionToTaxid.load(accessionFile);
228 System.gc();
229 }
230 }
231
232 public static void loadGiTable(String fname){
233 if(fname==null){return;}
234 if(PRINT_STUFF){outstream.println("Loading gi table.");}
235 GiToTaxid.initialize(fname);
236 }
237
238 public static TaxTree loadTree(String fname){
239 if(fname==null){return null;}
240 TaxTree tt=TaxTree.loadTaxTree(fname, PRINT_STUFF ? outstream : null, true, false);
241 assert(tt.nameMap!=null);
242 return tt;
243 }
244
245 public void addNamesOrNumbers(String names, boolean promote){
246 if(names==null){return;}
247 String[] array=names.split(",");
248 for(String name : array){
249 addNameOrNumber(name, promote);
250 }
251 }
252
253 public void addNameOrNumber(String s, boolean promote){
254 if(s==null || s.length()<1){return;}
255 if(Tools.isDigit(s.charAt(0))){addNumber(Integer.parseInt(s), promote);}
256 else{addName(s);}
257 }
258
259 public void addNames(String names){
260 if(names==null){return;}
261 String[] array=names.split(",");
262 for(String name : array){
263 addName(name);
264 }
265 }
266
267 public boolean addName(String name){
268 {
269 TaxNode tn=tree.parseNodeFromHeader(name, true);
270 if(tn!=null){return addNode(tn);}
271 }
272 List<TaxNode> list=tree.getNodesByNameExtended(name);
273 boolean success=false;
274 assert(list!=null) : "Could not find a node for '"+name+"'";
275 if(list==null){throw new RuntimeException("Could not find a node for '"+name+"'");}
276 for(TaxNode tn : list){
277 success=addNode(tn)|success;
278 }
279 return success;
280 }
281
282 public void addNumbers(String numbers, boolean promote){
283 if(numbers==null){return;}
284 String[] array=numbers.split(",");
285 for(String s : array){
286 if(Tools.isDigit(s.charAt(0))){
287 final int x=Integer.parseInt(s);
288 addNumber(x, promote);
289 }else if(new File(s).exists()){
290 TextFile tf=new TextFile(s);
291 for(String line=tf.nextLine(); line!=null; line=tf.nextLine()){
292 addNumbers(line, promote);
293 }
294 }else{
295 assert(tree!=null) : "Using organism names requires a taxonomic tree loaded; please use a numeric NCBI taxID.";
296 final int x=tree.parseNameToTaxid(s);
297 assert(x>0) : "Can't find a tax node for "+s;
298 addNumber(x, promote);
299 }
300 }
301 }
302
303 public boolean addNumber(int taxID, boolean promote){
304 if(promote){
305 TaxNode tn=tree.getNode(taxID);
306 assert(tn!=null) : "Could not find a node for '"+taxID+"'";
307 return addNode(tn);
308 }else{
309 maxChildLevelExtended=TaxTree.LIFE_E;
310 return taxSet.add(taxID);
311 }
312 }
313
314 public boolean addNode(TaxNode tn){
315 if(tn==null){return false;}
316 taxSet.add(tn.id);
317 maxChildLevelExtended=Tools.max(maxChildLevelExtended, tn.maxChildLevelExtended, tn.levelExtended);
318 if(printNodesAdded){System.err.println("Added node "+tn);}//123
319 while(tn.id!=tn.pid && tn.levelExtended<taxLevelE){
320 tn=tree.getNode(tn.pid);
321 if(tn.levelExtended<=taxLevelE){
322 if(printNodesAdded){System.err.println("Added node "+tn);}//123
323 taxSet.add(tn.id);
324 }
325 }
326 return true;
327 }
328
329 /*--------------------------------------------------------------*/
330 /*---------------- Outer Methods ----------------*/
331 /*--------------------------------------------------------------*/
332
333 public boolean passesFilter(final Read r){
334 return passesFilter(r.id);
335 }
336
337 public boolean passesFilterByNameOnly(final String name){
338 if(regexPattern!=null){
339 boolean b=matchesRegex(name);
340 if(b!=include){return false;}
341 }
342 if(containsString!=null){
343 boolean b=containsString(name);
344 if(b!=include){return false;}
345 }
346 return true;
347 }
348
349 public boolean passesFilter(final String name){
350 if(!passesFilterByNameOnly(name)){return false;}
351 if(taxSet.isEmpty() && reqLevels==0){return !include;}
352 TaxNode tn=tree.parseNodeFromHeader(name, true);
353 if(tn==null){tn=tree.getNodeByName(name);}
354 // assert(tn!=null || !REQUIRE_PRESENT) : "Could not find node for '"+name+"'";
355
356 if(REQUIRE_PRESENT && tn==null){
357 KillSwitch.kill("ERROR: Could not find node for '"+name+"'"
358 + "\nTo bypass this error, add the flag 'requirepresent=f'");
359 }
360
361 // assert(false) : passesFilter(tn);
362 return passesFilter(tn);
363 }
364
365 public boolean passesFilter(final int id){
366 // if((taxSet==null || taxSet.isEmpty()) && reqLevels==0){return !include;}
367 if((taxSet==null || taxSet.isEmpty()) && reqLevels==0){return true;}
368 TaxNode tn=tree.getNode(id);
369 // assert(tn!=null || !REQUIRE_PRESENT) : "Could not find node number "+id;
370
371 if(tn==null){
372 if(REQUIRE_PRESENT){
373 KillSwitch.kill("ERROR: Could not find node for "+id);
374 }else if(WARN_ABSENT_NODE){
375 System.err.println("Warning: Could not find node for "+id);
376 WARN_ABSENT_NODE=false;
377 }
378 }
379
380 return passesFilter(tn);
381 }
382
383 boolean passesFilter(final TaxNode tn0){
384 TaxNode tn=tn0;
385 if(taxSet.isEmpty() && reqLevels==0){return !include;}
386 if(tn==null){
387 assert(!REQUIRE_PRESENT) : "Null TaxNode.";
388 return !include && reqLevels==0;
389 }
390 boolean found=taxSet.contains(tn.id);
391 // System.err.println("found="+found+", node="+tn);
392 int levels=1<<tn.level;
393 while((!found || (levels&reqLevels)!=reqLevels) && tn.id!=tn.pid){
394 tn=tree.getNode(tn.pid);
395 levels|=(1<<tn.level);
396 if(promote){found=found||taxSet.contains(tn.id);}
397 // System.err.println("found="+found+", node="+tn);
398 }
399 // assert(false) : levels+", "+reqLevels+", "+tn0+", "+tree.getAncestors(tn0.pid);
400 return include==found && (levels&reqLevels)==reqLevels;
401 }
402
403 public boolean passesFilterFast(final int id){
404 assert(reqLevels==0);
405 if(taxSet==null || taxSet.isEmpty()){return true;}
406 TaxNode tn=tree.getNode(id);
407
408 if(tn==null){
409 if(REQUIRE_PRESENT){
410 KillSwitch.kill("ERROR: Could not find node for "+id);
411 }else if(WARN_ABSENT_NODE){
412 System.err.println("Warning: Could not find node for "+id);
413 WARN_ABSENT_NODE=false;
414 }
415 }
416
417 return passesFilterFast(tn);
418 }
419
420 boolean passesFilterFast(final TaxNode tn0){
421 TaxNode tn=tn0;
422 if(taxSet==null || taxSet.isEmpty()){return true;}
423 if(tn==null){
424 assert(!REQUIRE_PRESENT) : "Null TaxNode.";
425 return !include;
426 }
427 boolean found=taxSet.contains(tn.id);
428 if(!promote){return include==found;}
429
430 while(!found && tn.maxChildLevelExtended<=maxChildLevelExtended && tn.id!=tn.pid){
431 tn=tree.getNode(tn.pid);
432 found=found||taxSet.contains(tn.id);
433 }
434 return include==found;
435 }
436
437 boolean matchesRegex(String s){
438 return regexPattern.matcher(s).matches();
439 }
440
441 boolean containsString(String s){
442 return s.toLowerCase().contains(containsString);
443 }
444
445 /*--------------------------------------------------------------*/
446 /*---------------- Clone ----------------*/
447 /*--------------------------------------------------------------*/
448
449 public TaxFilter deepCopy() {
450 TaxFilter copy=null;
451 try {
452 copy=(TaxFilter) this.clone();
453 if(taxSet!=null){
454 copy.taxSet=new HashSet<Integer>();
455 copy.taxSet.addAll(taxSet);
456 }
457 } catch (CloneNotSupportedException e) {
458 // TODO Auto-generated catch block
459 e.printStackTrace();
460 }
461 return copy;
462 }
463
464 public void clearSet(){
465 taxSet=null;
466 }
467
468 public void makeSet(){
469 taxSet=new HashSet<Integer>();
470 }
471
472 // public void setInclude(boolean b){
473 // include=b;
474 // }
475
476 public void setLevel(final int newLevel, boolean promote){
477 final int newLevelE=TaxTree.levelToExtended(newLevel);
478 assert(newLevelE>=taxLevelE || newLevelE<1 || taxSet==null && taxSet.isEmpty()) : "taxLevel may only be increased when the set is non-empty.";
479 taxLevelE=newLevelE;
480 if(promote){promote();}
481 }
482
483 public void promote(){
484 if(taxSet!=null && !taxSet.isEmpty() && taxLevelE>0){
485 ArrayList<Integer> list=new ArrayList<Integer>(taxSet.size());
486 list.addAll(taxSet);
487 taxSet.clear();
488 for(Integer i : list){addNumber(i, true);}
489 }
490 }
491
492 public int size(){return (taxSet==null ? 0 : taxSet.size());}
493
494 public int taxLevel(){return TaxTree.extendedToLevel(taxLevelE);}
495 public Integer[] taxSet(){
496 return (taxSet==null || taxSet.isEmpty()) ? null : taxSet.toArray(new Integer[0]);
497 }
498 public boolean include(){return include;}
499 public void setTree(TaxTree tree_){tree=tree_;}
500 public TaxTree tree(){return tree;}
501 public void setContainsString(String s){containsString=(s==null ? null : s.toLowerCase());}
502 public String containsString(){return containsString;}
503 @Override
504 public String toString(){return ""+taxSet;}
505
506 public boolean isEmpty() {return taxSet.isEmpty();}
507
508 /*--------------------------------------------------------------*/
509 /*---------------- Fields ----------------*/
510 /*--------------------------------------------------------------*/
511
512 private TaxTree tree;
513
514 /** Level at which to filter */
515 private int taxLevelE;
516
517 /** Branch must contain ancestors at these levels (bitflag) */
518 private final int reqLevels;
519
520 /** Set of numeric NCBI TaxIDs */
521 private HashSet<Integer> taxSet;
522
523 private int maxChildLevelExtended=TaxTree.LIFE_E;
524 private final boolean include;
525 private boolean promote;
526
527 private String regex;
528 private final Pattern regexPattern;
529 private String containsString;
530
531 /*--------------------------------------------------------------*/
532 /*---------------- Static Fields ----------------*/
533 /*--------------------------------------------------------------*/
534
535 /** Print status messages to this output stream */
536 private static PrintStream outstream=System.err;
537
538 /** Print loading messages */
539 static boolean PRINT_STUFF=true;
540
541 public static boolean REQUIRE_PRESENT=true;
542 public static boolean WARN_ABSENT_NODE=true;
543 public static boolean printNodesAdded=true;
544
545 }