Debian Codegraph @

current/jasper/NCBISparseTreeValidate.java

raw symbols SCIP
1 package jasper;
2
3 import java.io.File;
4 import java.io.FileNotFoundException;
5 import java.io.FileWriter;
6 import java.io.IOException;
7 import java.util.ArrayList;
8 import java.util.Collections;
9
10 import shared.Parser;
11 import shared.PreParser;
12 import shared.Timer;
13
14
15
16 public class NCBISparseTreeValidate {
17
18 /*--------------------------------------------------------------*/
19 /*---------------- Initialization ----------------*/
20 /*--------------------------------------------------------------*/
21
22 public static void main(String[] args) throws FileNotFoundException, IOException {
23
24 //Start a timer immediately upon code entrance.
25 Timer t=new Timer();
26
27 //Create an instance of this class
28 NCBISparseTreeValidate x=new NCBISparseTreeValidate(args);
29
30 //Run the object
31 x.process(t);
32
33
34
35 }
36
37 /**
38 * Handles pre-parsing and parsing of user flags.
39 * Reads in the sketch similarity file (sim) and organism-parent relationship file (tree).
40 *
41 * @param args string of the arguments input at the commandline.
42 */
43 public NCBISparseTreeValidate(String[] args) {
44
45 {//Preparse block for help, config files, and outstream
46 PreParser pp=new PreParser(args, getClass(), false);
47 args=pp.args;
48 outstream=pp.outstream;
49 }
50
51 //Primary parsing of standard arguments found in all bbmap programs (maxReads, parseSam, parseZip, etc).
52 Parser parser=new Parser();
53
54 //Loop through arguments up to the maximum number of arguments input.
55 //process all remaining arguments.
56 for(int i=0; i<args.length; i++){
57
58 //Grab argument string at index.
59 String arg=args[i];
60
61 //Split argument string on "=".
62 String[] split=arg.split("=");
63
64 //Convert the left side to lowercase.
65 String a=split[0].toLowerCase();
66
67 //Ternary conditional statement: is the length of the split greater than 1 (thus, an actual input)?
68 //if so, the right side of the split is the b variable, if not, b is null.
69 String b=split.length>1 ? split[1] : null;
70
71 //If b isn't null but a string "null" was input, convert b to null.
72 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
73
74 //Unused example statement. does nothing currently. start here for adding new flag parsing.
75 if(a.equals("parse_flag_goes_here")){
76
77 //Handle similarities file variable assignment.
78 }else if(a.equals("sim")){
79 sim=b;
80
81 //Handle tree file variable assignment.
82 }else if(a.equals("tree")){
83 treeFileName=b;
84
85 //Handle whether using NCBI files as input (default)
86 //or a test dataset.
87 }else if(a.equals("test")) {
88 test=true;
89 ncbi=false;
90
91 //Handles which mode is used to assess problematic placements within the tree.
92 }else if(a.equals("mode")) {
93 if(b.equals("average")){mode=AVERAGE_IDENTITY_MODE;}
94 else if(b.equals("identity")) {mode=IDENTITY_MODE;}
95 else if(b.equals("vote")) {mode=VOTE_MODE;}
96 else if(b.equals("both")) {mode=BOTH_MODE;}
97 else {assert false : "Unknown Mode: " + arg;}
98
99 //Tells program to write tree graphs in .dot format.
100 }else if(a.equals("writetrees")) {
101 writeTrees = true;
102
103 }else if(a.equals("allnodes")) {
104 printAllNodes = true;
105
106 }else if(a.equals("treestoprint")) {
107 goodTreesToPrint = badTreesToPrint = Integer.parseInt(b);
108
109 //If writetrees is true and the path to an output dir is included
110 //set variable to the path to the desired directory
111 }else if(a.equals("outpath")) {
112 outpath=b;
113 if(outpath.endsWith("/")) {System.out.println("output path correct");}
114 else {outpath = outpath + "/";}
115
116 //Parses in and out flags, handles all flags not recognized earlier in class.
117 }else if(parser.parse(arg, a, b)){
118
119 //If not one of the known parameters, let the user know they made a mistake.
120 }else{
121 assert(false) : "Unknown parameter "+args[i];
122 outstream.println("Unknown parameter "+args[i]);
123 }
124
125 }
126 }
127
128
129 /*--------------------------------------------------------------*/
130 /*---------------- Outer Methods ----------------*/
131 /*--------------------------------------------------------------*/
132
133
134 /**
135 * Creates the similarity matrix and the relationship tree.
136 * Also passes these objects to the inner processing method for analysis.
137 *
138 * @param t
139 * @throws FileNotFoundException
140 * @throws IOException
141 */
142 void process(Timer t) throws FileNotFoundException, IOException{
143
144 //Pass input file to Tree class to create tree
145 tree=new NCBISparseTree(treeFileName);
146
147 System.out.println(tree.getOrgCount());
148
149 System.out.println("Mode of analysis: " + mode);
150
151 System.out.println("If writing out trees, write all nodes: " + printAllNodes);
152
153 //System.out.println(relationshipTree.getNode(3).taxonomicRank);
154
155 //Pass similarity file to create similarity matrix object
156 NCBISparseSimilarityMatrix matrix=new NCBISparseSimilarityMatrix(sim, tree, ncbi);
157
158 //System.out.println(matrix.getSize());
159
160 //Add parent node similarity percentages to each node in the tree.
161 //addRelationSims(relationshipTree, matrix);
162
163 //Traverse the tree and add levels to all nodes.
164 //Hardcoded to start at node "0" or "life" node.
165 tree.beginTraverse(1);
166
167 //Sets the identities by beginning at a particular node and working backwards.
168 //relationshipTree.setIdentity(relationshipTree.getNode(10), matrix);
169
170 //TODO: remove 10 since this is just part of testing/percolate
171 //relationshipTree.root.percolateIdentityUp(10);
172
173 //Check similarities.
174 checkSimilarities(tree, matrix);
175
176 System.out.println("Node placement check complete.");
177
178
179 t.stop();
180
181 outstream.println("Time: \t"+t);
182
183 }
184
185 /*--------------------------------------------------------------*/
186 /*---------------- Inner Methods ----------------*/
187 /*--------------------------------------------------------------*/
188 // /**
189 // * Iterate over nodes in the Tree and compare present relationships
190 // * with values found in the similarity matrix.
191 // *
192 // * @param tree Tree object containing TreeNode objects detailing the parent and children of each node.
193 // * @param matrix SimilarityMatrix2 object containing percentage similarity of sketches.
194 // */
195 // void addRelationSims(NCBISparseTree tree, SparseSimilarityMatrix matrix){
196 //
197 // //Iterate over organisms/nodes in the tree.
198 // for ( String keyOrg : tree.keySet() ) {
199 //
200 // //add the node of current focus to a variable in the loop.
201 // TreeNode keyNode = tree.getNode(keyOrg);
202 //
203 // //Get Parent node of keyNode.
204 // TreeNode parentNode = keyNode.parentNode;
205 //
206 // //If statement to ignore the root/"life" node when obtaining similarities.
207 // //Then get the parent nodes similarity to the key node.
208 // //add the similarity value to the key node.
209 // if(!parentNode.orgName.equals("0")) {
210 //
211 // keyNode.addParSim(parentNode.averageIdentity());
212 // System.out.println(parentNode.averageIdentity());
213 // }
214 // }
215 // }
216
217
218 /**
219 * Method to check tree for surprising similarity values for each node in the tree.
220 * Ignores the root/"life" node, any node without any sequence.
221 * Any node with a higher similarity to another node than to its parent that
222 * isn't an descendant is flagged as possibly erroneous.
223 *
224 * @param tree The tree object storing taxon nodes (TreeNode objects).
225 * @param matrix The sparse similarity matrix containing all possible pairwise similarity values.
226 */
227 void checkSimilarities(NCBISparseTree tree, NCBISparseSimilarityMatrix matrix) {
228
229 System.out.println("Begining to compare sequence similarity values to the stated tree structure.");
230 //Iterate over organisms/nodes in the tree.
231 //for ( Integer keyTaxonID : tree.keySet() ) {
232 for(NCBITreeNode keyNode : tree.nodeList) {
233
234 Integer keyTaxonID = keyNode.taxID;
235
236 System.out.println("Analyzing Taxon ID :" + keyTaxonID);
237
238 //If the organism isn't the life/0 node.
239 //NCBI taxon ID == 1.
240 //Node ID == 0.
241 if(!keyTaxonID.equals(1) && matrix.numComparisonsByTaxonID(keyTaxonID) > 0) {
242
243 //Reset the identity values of the TreeNodes
244 //This is done so all identity values are relative to the current keyNode.
245 tree.root.resetRecursively();
246
247 //Set the identities of the tree based on the current keyNode.
248 tree.setIdentity(keyNode, matrix);
249
250 keyNode.votes++;
251
252 //Percolate the average identities of each node upwards through the tree
253 //relative to the current keyNode.
254 tree.root.percolateIdentityUp(keyNode.nodeId);
255
256 //Handle writing tree relationships in .dot format.
257 //If selected by user.
258 if(writeTrees == true && outpath != null) {
259
260 //Creates the tree output file name along with the path to the desired directory.
261 String currentTreeName = outpath + "SimilarityTree_" + keyNode.orgName + "_.dot";
262
263 //Create the output file.
264 createFile(currentTreeName);
265
266 //Write the .dot formatted tree to the file.
267 writeToFile(currentTreeName, tree.root.toDot(printAllNodes));
268
269 //assert false;
270 }
271
272 if(mode==AVERAGE_IDENTITY_MODE) {
273 //checkSimilaritiesForOneNode(keyNode, matrix);
274 NCBITreeNode problemNode = checkAverageIdentityForOneNode(keyNode);
275
276 if(problemNode != null) {
277 System.out.println("Highest problem node for Taxon ID: " + keyNode.taxID + " is: " + problemNode);
278 if(badTreesToPrint > 0) {
279 writeTrees(keyNode, tree);
280 badTreesToPrint = badTreesToPrint - 1;
281 }
282 }else if(problemNode == null && goodTreesToPrint > 0) {
283 writeTrees(keyNode, tree);
284 goodTreesToPrint = goodTreesToPrint - 1;
285 }
286 }
287 else if(mode==VOTE_MODE) {
288 NCBITreeNode problemNode = checkVotesForOneNode(keyNode);
289
290 if(problemNode != null) {
291 System.out.println("Highest problem node for Taxon ID: " + keyNode.taxID + " is: " + problemNode);
292 if(badTreesToPrint > 0) {
293 writeTrees(keyNode, tree);
294 badTreesToPrint--;
295 }
296 }else if(problemNode == null && goodTreesToPrint > 0) {
297 writeTrees(keyNode, tree);
298 goodTreesToPrint--;
299 }
300
301 //The primary mode
302 }else if(mode==BOTH_MODE) {
303
304 NCBITreeNode voteProblemNode = checkVotesForOneNode(keyNode);
305
306 if(voteProblemNode != null) {
307
308 NCBITreeNode avgIDProblemNode = checkAverageIdentityForOneNode(keyNode);
309
310 if(avgIDProblemNode != null) {
311
312 setNodeColors(keyNode, voteProblemNode, avgIDProblemNode);
313
314 System.out.println("Problem found at Taxon ID: " + keyNode.taxID
315 + " The highest vote problem node is: " + voteProblemNode
316 + " and the highest identity problem node is: " + avgIDProblemNode);
317
318 if(badTreesToPrint > 0) {
319 writeTrees(keyNode, tree);
320 badTreesToPrint--;
321 }
322 }else if(avgIDProblemNode == null) {
323 keyNode.color = "blue";
324 if(goodTreesToPrint > 0) {
325 writeTrees(keyNode, tree);
326 goodTreesToPrint--;
327 }
328 }
329 }
330 }else { throw new RuntimeException("Uknown Mode" + mode);}
331 //checkSimilaritiesForOneNode(keyNode, matrix);
332
333 }
334 }
335 }
336
337 /**
338 * Used to identify and flag suspicious placements of nodes within a taxonomic tree.
339 * @param keyNode Query node of interest. Votes are calculated from this node in relation to the tree.
340 * @return TreeNode the problematic node compared to the query node
341 *
342 */
343 public NCBITreeNode checkVotesForOneNode(final NCBITreeNode keyNode) {
344
345 NCBITreeNode current=keyNode.parentNode;
346
347 NCBITreeNode previous=keyNode;
348
349 NCBITreeNode highestProblemNode = null;
350
351 NCBITreeNode problemChild = null;
352
353 while(current.parentNode != current) {
354
355 int currentMaxVotes = previous.votes;
356
357 NCBITreeNode maxChild = previous;
358
359 for(NCBITreeNode descendantNode : current.childNodes) {
360
361 if(descendantNode.votes > currentMaxVotes) {
362
363 currentMaxVotes = descendantNode.votes;
364 maxChild = descendantNode;
365
366 }
367
368 }
369
370 if(maxChild != previous) {
371
372 current.flaggedNode = true;
373 System.out.println("Problem found at: [" + current.taxID + "] Taxon rank: [" + current.taxonomicRank + "]");
374 highestProblemNode = current;
375 problemChild = maxChild;
376 }
377
378 previous = current;
379 current = current.parentNode;
380
381 }
382 if(highestProblemNode != null && highestProblemNode != keyNode.parentNode) {
383 problemChild.color = "pink";
384 }
385
386 return highestProblemNode == keyNode.parentNode ? null : highestProblemNode;
387 }
388
389 /**
390 * Used to check sequence identities and flag suspicious node placements.
391 * @param keyNode Query node of interest.
392 * @param matrix Matrix of similarity comparisons.
393 */
394 @Deprecated
395 public void checkSimilaritiesForOneNode(NCBITreeNode keyNode, NCBISparseSimilarityMatrix matrix) {
396 //Prevents analysis of "empty" nodes that don't contain sequences (genus/phylum/etc).
397 //TODO: if there are no sibling nodes, the parent sim could be 0.
398 if(keyNode.parentNode.averageIdentity() != 0.0) {
399
400 //Get the row of similarity values associated with
401 //the key node and each other node.
402 ArrayList<NCBIComparison> keyOrgRow = matrix.getOrgRowByTaxonID(keyNode.taxID);
403
404 Collections.sort(keyOrgRow);
405
406 //Iterate over the node organism names.
407 for(NCBIComparison rowOrgComparison : keyOrgRow) {
408
409 NCBITreeNode matrixOrgNode = tree.getNodeByNodeID(rowOrgComparison.refNodeID);
410
411 boolean b = isSuspicious(keyNode, matrixOrgNode, rowOrgComparison);
412 keyNode.flaggedNode = b;
413 if(b) {
414 printSuspicious(keyNode, rowOrgComparison, matrixOrgNode);
415 }
416 }
417 }
418 }
419
420
421 public NCBITreeNode checkAverageIdentityForOneNode(final NCBITreeNode keyNode) {
422 NCBITreeNode current=keyNode.parentNode;
423
424 NCBITreeNode previous=keyNode;
425
426 NCBITreeNode highestProblemNode = null;
427
428 NCBITreeNode problemChild = null;
429
430 while(current.parentNode != current) {
431
432 double currentMaxAverage = previous.averageIdentity();
433 NCBITreeNode maxChild = previous;
434
435 for(NCBITreeNode descendantNode : current.childNodes) {
436
437 if(descendantNode.averageIdentity() > currentMaxAverage) {
438
439 currentMaxAverage = descendantNode.averageIdentity();
440 maxChild = descendantNode;
441
442 }
443
444 }
445
446 if(maxChild != previous) {
447
448 current.flaggedNode = true;
449 System.out.println("Problem found at: [" + current.taxID + "] Taxon rank: [" + current.taxonomicRank + "]");
450 highestProblemNode = current;
451 problemChild = maxChild;
452
453 }
454
455 previous = current;
456 current = current.parentNode;
457
458 }
459
460 if(highestProblemNode != null && highestProblemNode != keyNode.parentNode) {
461 problemChild.color = "yellow";
462 }
463
464 return highestProblemNode == keyNode.parentNode ? null : highestProblemNode;
465 }
466
467
468 /**
469 * Uses Similarity values to determine if the placement of a node is suspicious and requires investigation.
470 *
471 * @param keyNode
472 * @param matrixOrgNode
473 * @param rowOrgComparison
474 * @return
475 */
476 public boolean isSuspicious(NCBITreeNode keyNode, NCBITreeNode matrixOrgNode, NCBIComparison rowOrgComparison) {
477
478 if(!matrixOrgNode.isDescendantOf(keyNode.parentNode) &&
479 !matrixOrgNode.isAncestorOf(keyNode)) {
480
481 //Get similarity between the key node and any pairwise compared node
482 double matrixOrgSim = rowOrgComparison.identity;
483
484 //If the similarity value is higher than the similarity
485 //between the key node and its parent.
486 if(matrixOrgSim > keyNode.parentSimilarity()) {
487
488 return true;
489 }
490
491 }
492 return false;
493 }
494
495 public void setNodeColors(NCBITreeNode keyNode, NCBITreeNode voteProblemNode, NCBITreeNode avgIDProblemNode) {
496 keyNode.color = "blue";
497 voteProblemNode.color = "red";
498 avgIDProblemNode.color = "green";
499 }
500
501 public void printSuspicious(NCBITreeNode keyNode, NCBIComparison rowOrgComparison, NCBITreeNode matrixOrgNode) {
502 System.out.println();
503 System.out.println("problem");
504 System.out.println("key org taxon ID " + keyNode.taxID);
505 System.out.println("matrix org " + matrixOrgNode.taxID);
506 System.out.println("par org taxon ID " + keyNode.getParentTaxonID());
507 System.out.println("other org " + rowOrgComparison);
508 System.out.println("par sim " + keyNode.parentSimilarity());
509
510 System.out.println("matrix sim " + rowOrgComparison.identity);
511 }
512
513
514 /**
515 * Method for creating a file with an input file name.
516 * @param fileName String for the file name.
517 */
518 void createFile(String fileName) {
519
520 try {
521
522 //Creates a file object using the input file name.
523 File myObj = new File(fileName);
524
525 //If the file is successfully created, print a message saying so.
526 if (myObj.createNewFile()) {
527 System.out.println("File created: " + myObj.getName());
528
529 //If the file cannot be created, the file already exists
530 } else {
531 System.out.println("File already exists.");
532 }
533
534 //Catch a message if their are exceptions.
535 } catch (IOException e) {
536 System.out.println("An error occurred.");
537 e.printStackTrace();
538 }
539 }
540
541 /**
542 * Method to write information to a file.
543 * @param fileName Name of the file created using the createFile method.
544 * @param sb StringBuilder containing information to be written to the file.
545 */
546 void writeToFile(String fileName, StringBuilder sb) {
547
548 try {
549
550 //Create a FileWriter object using the name of the file.
551 FileWriter myWriter = new FileWriter(fileName);
552
553 //Write the StringBuilder contents to the file
554 myWriter.write(sb.toString());
555
556 //Close the FileWriter object.
557 myWriter.close();
558
559 //Message on success.
560 System.out.println("Successfully wrote to the file.");
561
562 //Catch exceptions and write a message to alert the user.
563 } catch (IOException e) {
564 System.out.println("An error occurred.");
565 e.printStackTrace();
566 }
567 }
568
569 public void writeTrees(NCBITreeNode keyNode, NCBISparseTree tree) {
570 //Creates the tree output file name along with the path to the desired directory.
571 String currentTreeName = outpath + "SimilarityTree_" + keyNode.orgName + "_.dot";
572
573 //Create the output file.
574 createFile(currentTreeName);
575
576 //Write the .dot formatted tree to the file.
577 writeToFile(currentTreeName, tree.root.toDot(printAllNodes));
578 }
579
580 /*--------------------------------------------------------------*/
581 /*---------------- Fields ----------------*/
582 /*--------------------------------------------------------------*/
583
584 /**
585 * Pairwise similarity file generated by BBSketch.
586 */
587 private String sim=null;
588
589 /**
590 * Tree file containing taxonomic relationships.
591 */
592 private String treeFileName=null;
593
594 /**
595 * Output file name.
596 */
597 private String out=null;
598
599 /**
600 * Output path for any output files.
601 */
602 private String outpath=null;
603
604 /**
605 * Flag for indicating whether to write tree .dot files.
606 * If present in commandline args, set to true.
607 */
608 private boolean writeTrees = false;
609
610 private boolean test=false;
611
612 private boolean ncbi=true;
613
614 private int mode=BOTH_MODE;
615
616 private NCBISparseTree tree = null;
617
618 private boolean printAllNodes = false;
619
620 private int goodTreesToPrint=0;
621
622 private int badTreesToPrint=0;
623
624 /*--------------------------------------------------------------*/
625
626 private long linesProcessed=0;
627 private long linesOut=0;
628 private long bytesProcessed=0;
629 private long bytesOut=0;
630 private long taxa=0;
631
632 /*--------------------------------------------------------------*/
633
634 public static int MAX_VOTES=20;
635 public static final int VOTE_MODE=0;
636 public static final int IDENTITY_MODE=1;
637 public static final int AVERAGE_IDENTITY_MODE=2;
638 public static final int BOTH_MODE=3;
639
640
641 /*--------------------------------------------------------------*/
642 /*---------------- Final Fields ----------------*/
643 /*--------------------------------------------------------------*/
644
645 private String[] header;
646 //private final FileFormat ffin;
647 //private final FileFormat ffout;
648
649 /*--------------------------------------------------------------*/
650 /*---------------- Common Fields ----------------*/
651 /*--------------------------------------------------------------*/
652
653 //private PrintStream outstream=System.err;
654 public static boolean verbose=false;
655 public boolean errorState=false;
656 private boolean overwrite=true;
657 private boolean append=false;
658 /**Output stream that output statistics are piped through to the output file. */
659 private java.io.PrintStream outstream=System.err;
660
661
662 }