Пример #1
0
  /** Unit tests */
  public static void main(String[] args) {
    final Tree targetTree =
        tree(
            1,
            tree(
                2,
                tree(3, tree(4), tree(3, tree(4), tree(5))),
                tree(5, tree(6, tree(7), tree(8, tree(9), tree())), tree(10, tree(11), tree()))),
            tree(12));

    System.out.println("    Test Pattern");
    checkPattern(targetTree, tree(), Optional.of(targetTree));

    checkPattern(targetTree, tree(9), Optional.of(tree(9)));
    checkPattern(targetTree, tree(12), Optional.of(tree(12)));
    checkPattern(targetTree, tree(13), Optional.empty());
    checkPattern(targetTree, tree(1), Optional.of(targetTree));

    checkPattern(targetTree, tree(2, tree(3), tree(5)), Optional.of(targetTree.left()));
    checkPattern(
        targetTree, tree(3, tree(4), tree(5)), Optional.of(targetTree.left().left().right()));
    checkPattern(
        targetTree, tree(6, tree(), tree(8)), Optional.of(targetTree.left().right().left()));
    checkPattern(targetTree, tree(6, tree(), tree(7)), Optional.empty());

    checkPattern(
        targetTree,
        tree(5, tree(6, tree(7), tree(8, tree(9), tree())), tree(10, tree(11), tree())),
        Optional.of(targetTree.left().right()));
  }
Пример #2
0
 public Forest(List<Tree> roots) {
   this.roots = roots;
   size = 0;
   for (Tree root : roots) {
     size += root.size();
   }
 }
Пример #3
0
 private static <T> void writeTreeBranch(
     Tree<T> tree, Writer writer, List<Boolean> lines, boolean lastBranch) throws IOException {
   for (boolean line : lines) {
     if (line) {
       writer.write("  |  ");
     } else {
       writer.write("     ");
     }
   }
   if (lastBranch) {
     writer.write("  '-- ");
   } else {
     writer.write("  |-- ");
   }
   writer.write(String.valueOf(tree.getNodeData()));
   writer.write("\n");
   Iterator<Tree<T>> branchIt = tree.iterator();
   while (branchIt.hasNext()) {
     Tree<T> branch = branchIt.next();
     List<Boolean> newLines = new ArrayList<Boolean>();
     newLines.addAll(lines);
     newLines.add(!lastBranch);
     writeTreeBranch(branch, writer, newLines, !branchIt.hasNext());
   }
 }
Пример #4
0
 /*.................................................................................................................*/
 public String getStringForTree(int ic) {
   if (treesBlock == null) return "";
   Tree tree = treesBlock.getTree(ic);
   if (tree == null) return "";
   if (tree.hasPolytomies(tree.getRoot())) return "Yes";
   else return "No";
 }
Пример #5
0
 private static <L> Tree<L> deepCopy(Tree<L> tree) {
   List<Tree<L>> childrenCopies = new ArrayList<Tree<L>>();
   for (Tree<L> child : tree.getChildren()) {
     childrenCopies.add(deepCopy(child));
   }
   return new Tree<L>(tree.getLabel(), childrenCopies);
 }
Пример #6
0
 public static void main(String[] args) throws java.lang.Exception {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   Tree tree = new Tree();
   int n = Integer.parseInt(br.readLine());
   int nn = n - 1;
   TreeNode[] treeNodes = new TreeNode[n];
   int i = 0;
   while (n-- > 0) {
     String[] strs = br.readLine().split(" ");
     int r = Integer.parseInt(strs[1]);
     int n1 = Integer.parseInt(strs[0]);
     treeNodes[i] = new TreeNode(n1, r);
     i = i + 1;
   }
   boolean[] x = new boolean[nn + 1];
   while (nn-- > 0) {
     String[] strs = br.readLine().split(" ");
     int s = Integer.parseInt(strs[0]);
     int t = Integer.parseInt(strs[1]);
     if (!x[s]) {
       tree.insert(treeNodes[s]);
       x[s] = true;
     }
     if (!x[t]) {
       tree.insert(treeNodes[t]);
       x[t] = true;
     }
   }
   tree.levelOrder(tree.root);
 }
Пример #7
0
 /**
  * Returns the index of <code>daughter</code> in <code>parent</code> by ==. Returns -1 if <code>
  * daughter</code> not found.
  */
 public static int objectEqualityIndexOf(Tree parent, Tree daughter) {
   for (int i = 0; i < parent.children().length; i++) {
     if (daughter == parent.children()[i]) {
       return i;
     }
   }
   return -1;
 }
Пример #8
0
 /**
  * returns the syntactic category of the tree as a list of the syntactic categories of the mother
  * and the daughters
  */
 public static List<String> localTreeAsCatList(Tree t) {
   List<String> l = new ArrayList<String>(t.children().length + 1);
   l.add(t.label().value());
   for (int i = 0; i < t.children().length; i++) {
     l.add(t.children()[i].label().value());
   }
   return l;
 }
 /*
  * Trim BST - Given min and max trim the tree so that all nodes has values between min and max
  */
 public Tree trimTree(Tree node, int min, int max) {
   if (node == null) return null;
   node.left = trimTree(node.left, min, max);
   node.right = trimTree(node.right, min, max);
   if (node.value < min) return node.right;
   else if (node.value > max) return node.left;
   else return node;
 }
Пример #10
0
 /*..........................................ContinuousHistory................*/
 private void fillDistribution(Tree tree, int node, ContinuousAdjustable dist) {
   if (tree.nodeIsTerminal(node)) {
     int t = tree.taxonNumberOfNode(node);
     for (int i = 0; i < getNumItems(); i++) dist.setState(t, i, getState(node, i));
   } else
     for (int d = tree.firstDaughterOfNode(node); tree.nodeExists(d); d = tree.nextSisterOfNode(d))
       fillDistribution(tree, d, dist);
 }
Пример #11
0
 private static <L> void appendPreTerminalYield(Tree<L> tree, List<L> yield) {
   if (tree.isPreTerminal()) {
     yield.add(tree.getLabel());
     return;
   }
   for (Tree<L> child : tree.getChildren()) {
     appendPreTerminalYield(child, yield);
   }
 }
Пример #12
0
  /**
   * Search the tree for the first instance of `pattern`, giving preference to the left child.
   *
   * <p>`pattern` is a tree, representing a pattern of nodes. `NilNode`s should be considered
   * wildcards.
   *
   * <p>Example patterns ---------------- `Tree()` Matches any tree.
   *
   * <p>`Tree(3)` Matches any tree where the root node has a value of `3`.
   *
   * <p>`Tree(3, Tree(2), Tree())` Matches any tree where the root node has a value of `3`, and a
   * left sub-tree with a root value of `2`, and any (or no) right sub-tree.
   */
  static Optional<Tree> find(Tree target, Tree pattern) {
    if (pattern.isEmpty()) return Optional.of(target);
    if (target.isEmpty()) return Optional.empty();
    if (prefixMatches(target, pattern)) return Optional.of(target);

    Optional<Tree> leftMatch = find(target.left(), pattern);
    if (leftMatch.isPresent()) return leftMatch;
    return find(target.right(), pattern);
  }
Пример #13
0
  /**
   * output the top level labels for each tree
   *
   * @param trees the trees to predict
   * @return the prediction labels for each tree
   */
  public List<Integer> predict(List<Tree> trees) {
    List<Integer> ret = new ArrayList<>();
    for (Tree t : trees) {
      forwardPropagateTree(t);
      ret.add(SimpleBlas.iamax(t.prediction()));
    }

    return ret;
  }
Пример #14
0
 private static String toLispString(Tree<?> tree) {
   final String value = String.valueOf(tree.getValue());
   if (tree.isLeaf()) {
     return value;
   } else {
     return String.format(
         "(%s %s)", value, tree.getChildren().map(Node::toLispString).mkString(" "));
   }
 }
Пример #15
0
 /*..........................................ContinuousHistory................*/
 public void calcMinMaxStates(Tree tree, int node) {
   for (int i = 0; i < getNumItems(); i++) {
     double s = getState(node, i);
     maxState = MesquiteDouble.maximum(maxState, s);
     minState = MesquiteDouble.minimum(minState, s);
   }
   for (int d = tree.firstDaughterOfNode(node); tree.nodeExists(d); d = tree.nextSisterOfNode(d))
     calcMinMaxStates(tree, d);
 }
Пример #16
0
 private static <L> List<Tree<L>> spliceNodesHelper(Tree<L> tree, Filter<L> filter) {
   List<Tree<L>> splicedChildren = new ArrayList<Tree<L>>();
   for (Tree<L> child : tree.getChildren()) {
     List<Tree<L>> splicedChildList = spliceNodesHelper(child, filter);
     splicedChildren.addAll(splicedChildList);
   }
   if (filter.accept(tree.getLabel())) return splicedChildren;
   return Collections.singletonList(new Tree<L>(tree.getLabel(), splicedChildren));
 }
Пример #17
0
  /**
   * output the prediction probabilities for each tree
   *
   * @param trees the trees to predict
   * @return the prediction probabilities for each tree
   */
  public List<FloatMatrix> output(List<Tree> trees) {
    List<FloatMatrix> ret = new ArrayList<>();
    for (Tree t : trees) {
      forwardPropagateTree(t);
      ret.add(t.prediction());
    }

    return ret;
  }
Пример #18
0
 private List<Tree> helper(List<Tree> treeList, int start) {
   List<Tree> newTreeList = new ArrayList<Tree>(treeList.size());
   for (Tree tree : treeList) {
     int end = start + tree.yield().size();
     newTreeList.add(prune(tree, start));
     start = end;
   }
   return newTreeList;
 }
Пример #19
0
 private int setWordsHelper(List<L> words, int wordNum) {
   if (isLeaf()) {
     label = words.get(wordNum);
     return wordNum + 1;
   } else {
     for (Tree<L> child : getChildren()) wordNum = child.setWordsHelper(words, wordNum);
     return wordNum;
   }
 }
Пример #20
0
  private boolean LexicalAnalyzer(ArrayList<Word> words, int index, String newWord) {
    String[] sent = toSentence(words);
    /// lexical analyzer
    List<CoreLabel> rawWords = Sentence.toCoreLabelList(sent);
    Tree parse = lp.apply(rawWords);

    //		PrintStream outa = new PrintStream(new FileOutputStream("output1.txt"));

    //	    System.setOut(outa);
    //	    System.out.println("KKKKKKK");
    //	    parse.pennPrint();
    String oldTree = parse.toString();
    //	    String oldTree=baos.toString();
    //	    System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
    //	    System.out.println(oldTree);

    words.get(index).setNewValue(newWord);
    sent = toSentence(words);
    rawWords = Sentence.toCoreLabelList(sent);
    parse = lp.apply(rawWords);
    //	    PrintStream outb = new PrintStream(new FileOutputStream("output2.txt"));
    //	    System.setOut(outb);

    //	    parse.pennPrint();
    String newTree = parse.toString();

    oldTree = oldTree.replaceAll(words.get(index).getOrigValue() + "[)]", newWord + ")");
    //	    System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
    System.out.println(oldTree + "\n" + newTree);

    //	    	System.out.println(oldTree.equals(newTree));

    if (oldTree.equals(newTree)) {
      if (index == 0) {
        String str = words.get(index).getNewValue();
        String cap = str.substring(0, 1).toUpperCase() + str.substring(1);
        words.get(index).setNewValue(cap);
      }
      return true;
    } else {
      words.get(index).setNewValue(null);
      return false;
    }

    /* catch (FileNotFoundException e) {
    	// TODO Auto-generated catch block
    	e.printStackTrace();
    	return false;
    } catch (IOException e) {
    	// TODO Auto-generated catch block
    	e.printStackTrace();
    	return false;
    }*/

    //		return true;
  }
Пример #21
0
 /**
  * Returns a new object indicating the states at the tips (used whether or not History is
  * reconstruction)
  */
 public CharacterDistribution getStatesAtTips(Tree tree) {
   if (observedStates != null) return (CharacterDistribution) observedStates.getAdjustableClone();
   else {
     ContinuousAdjustable d =
         new ContinuousAdjustable(tree.getTaxa(), tree.getTaxa().getNumTaxa());
     d.setItemsAs(this);
     fillDistribution(tree, tree.getRoot(), d);
     return d;
   }
 }
Пример #22
0
 private static <L> Tree<L> pruneNodesHelper(Tree<L> tree, Filter<L> filter) {
   if (filter.accept(tree.getLabel())) return null;
   List<Tree<L>> prunedChildren = new ArrayList<Tree<L>>();
   for (Tree<L> child : tree.getChildren()) {
     Tree<L> prunedChild = pruneNodesHelper(child, filter);
     if (prunedChild != null) prunedChildren.add(prunedChild);
   }
   if (prunedChildren.isEmpty() && !tree.isLeaf()) return null;
   return new Tree<L>(tree.getLabel(), prunedChildren);
 }
Пример #23
0
 private static void preTerminals(Tree t, List<Tree> l) {
   if (t.isPreTerminal()) {
     l.add(t);
   } else {
     Tree[] kids = t.children();
     for (int j = 0, n = kids.length; j < n; j++) {
       preTerminals(kids[j], l);
     }
   }
 }
Пример #24
0
 @Override
 public String toString() {
   String str = "forest: {\n";
   for (Tree t : roots) {
     str += t.toString(1);
     str += "-----\n";
   }
   str += "}";
   return str;
 }
 public Tree add(Tree node, int value) {
   if (node == null) {
     node = new Tree(value);
     return node;
   } else {
     if (value < node.value) node.left = add(node.left, value);
     else node.right = add(node.right, value);
   }
   return node;
 }
Пример #26
0
 private static <L> int toConstituentCollectionHelper(
     Tree<L> tree, int start, List<Constituent<L>> constituents) {
   if (tree.isLeaf() || tree.isPreTerminal()) return 1;
   int span = 0;
   for (Tree<L> child : tree.getChildren()) {
     span += toConstituentCollectionHelper(child, start + span, constituents);
   }
   constituents.add(new Constituent<L>(tree.getLabel(), start, start + span));
   return span;
 }
Пример #27
0
	public static <A> void printTree(Tree<A> tree, PrintStream ps)
	{
		ps.printf("(%s (", tree.value());
		for (Tree<A> t : tree.children())
		{
			printTree(t, ps);
			ps.print(",");
		}
		ps.print("))");
	}
Пример #28
0
 public static String transformLabel(Tree<String> tree) {
   String transformedLabel = tree.getLabel();
   int cutIndex = transformedLabel.indexOf('-');
   int cutIndex2 = transformedLabel.indexOf('=');
   if (cutIndex2 > 0 && (cutIndex2 < cutIndex || cutIndex == -1)) cutIndex = cutIndex2;
   if (cutIndex > 0 && !tree.isLeaf()) {
     transformedLabel = transformedLabel.substring(0, cutIndex);
   }
   return transformedLabel;
 }
Пример #29
0
 private static void leafLabels(Tree t, List<Label> l) {
   if (t.isLeaf()) {
     l.add(t.label());
   } else {
     Tree[] kids = t.children();
     for (int j = 0, n = kids.length; j < n; j++) {
       leafLabels(kids[j], l);
     }
   }
 }
  /** Method declaration */
  private void initGUI() {

    Panel pQuery = new Panel();
    Panel pCommand = new Panel();

    pResult = new Panel();

    pQuery.setLayout(new BorderLayout());
    pCommand.setLayout(new BorderLayout());
    pResult.setLayout(new BorderLayout());

    Font fFont = new Font("Dialog", Font.PLAIN, 12);

    txtCommand = new TextArea(5, 40);

    txtCommand.addKeyListener(this);

    txtResult = new TextArea(20, 40);

    txtCommand.setFont(fFont);
    txtResult.setFont(new Font("Courier", Font.PLAIN, 12));

    butExecute = new Button("Execute");
    butClear = new Button("Clear");

    butExecute.addActionListener(this);
    butClear.addActionListener(this);
    pCommand.add("East", butExecute);
    pCommand.add("West", butClear);
    pCommand.add("Center", txtCommand);

    gResult = new Grid();

    setLayout(new BorderLayout());
    pResult.add("Center", gResult);
    pQuery.add("North", pCommand);
    pQuery.add("Center", pResult);
    fMain.add("Center", pQuery);

    tTree = new Tree();

    // (ulrivo): screen with less than 640 width
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();

    if (d.width >= 640) {
      tTree.setMinimumSize(new Dimension(200, 100));
    } else {
      tTree.setMinimumSize(new Dimension(80, 100));
    }

    gResult.setMinimumSize(new Dimension(200, 300));
    fMain.add("West", tTree);
    doLayout();
    fMain.pack();
  }