Esempio n. 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()));
  }
Esempio n. 2
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());
   }
 }
Esempio n. 3
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);
 }
Esempio n. 4
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;
 }
Esempio n. 5
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;
 }
Esempio n. 6
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);
  }
Esempio n. 7
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(" "));
   }
 }
Esempio n. 8
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;
  }
Esempio n. 9
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);
     }
   }
 }
Esempio n. 10
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);
     }
   }
 }
  public static ArrayList<TaggedWord> StanfordParse(String sentence, LexicalizedParser lp) {

    TokenizerFactory<CoreLabel> tokenizerFactory =
        PTBTokenizer.factory(new CoreLabelTokenFactory(), "");
    List<CoreLabel> rawWords2 =
        tokenizerFactory.getTokenizer(new StringReader(sentence)).tokenize();
    Tree parse = lp.apply(rawWords2);
    ArrayList<TaggedWord> taggedWords = parse.taggedYield();

    return taggedWords;
  }
Esempio n. 12
0
 static <T> Stream<T> levelOrder(Tree<T> tree) {
   Stream<T> result = Stream.empty();
   final java.util.Queue<Tree<T>> queue = new java.util.LinkedList<>();
   queue.add(tree);
   while (!queue.isEmpty()) {
     final Tree<T> next = queue.remove();
     result = result.prepend(next.getValue());
     queue.addAll(next.getChildren().toJavaList());
   }
   return result.reverse();
 }
Esempio n. 13
0
 /**
  * Gets the <i>i</i>th leaf of a tree from the left. The leftmost leaf is numbered 0.
  *
  * @return The <i>i</i><sup>th</sup> leaf as a Tree, or <code>null</code> if there is no such
  *     leaf.
  */
 public static Tree getLeaf(Tree tree, int i) {
   int count = -1;
   for (Tree next : tree) {
     if (next.isLeaf()) {
       count++;
     }
     if (count == i) {
       return next;
     }
   }
   return null;
 }
Esempio n. 14
0
 private static void taggedLeafLabels(Tree t, List<CoreLabel> l) {
   if (t.isPreTerminal()) {
     CoreLabel fl = (CoreLabel) t.getChild(0).label();
     fl.set(TagLabelAnnotation.class, t.label());
     l.add(fl);
   } else {
     Tree[] kids = t.children();
     for (int j = 0, n = kids.length; j < n; j++) {
       taggedLeafLabels(kids[j], l);
     }
   }
 }
Esempio n. 15
0
 static <T> Stream<T> inOrder(Tree<T> tree) {
   if (tree.isLeaf()) {
     return Stream.of(tree.getValue());
   } else {
     final List<Node<T>> children = tree.getChildren();
     return children
         .tail()
         .foldLeft(Stream.<T>empty(), (acc, child) -> acc.appendAll(inOrder(child)))
         .prepend(tree.getValue())
         .prependAll(inOrder(children.head()));
   }
 }
Esempio n. 16
0
  static boolean prefixMatches(Tree target, Tree pattern) {
    if (pattern.isEmpty()) return true;
    if (target.isEmpty() || target.value() != pattern.value()) return false;

    return prefixMatches(target.left(), pattern.left())
        && prefixMatches(target.right(), pattern.right());
  }
Esempio n. 17
0
 /** replaces all instances (by ==) of node with node1. Doesn't affect the node t itself */
 public static void replaceNode(Tree node, Tree node1, Tree t) {
   if (t.isLeaf()) return;
   Tree[] kids = t.children();
   List<Tree> newKids = new ArrayList<Tree>(kids.length);
   for (int i = 0, n = kids.length; i < n; i++) {
     if (kids[i] != node) {
       newKids.add(kids[i]);
       replaceNode(node, node1, kids[i]);
     } else {
       newKids.add(node1);
     }
   }
   t.setChildren(newKids);
 }
Esempio n. 18
0
 /**
  * returns the maximal projection of <code>head</code> in <code>root</code> given a {@link
  * HeadFinder}
  */
 public static Tree maximalProjection(Tree head, Tree root, HeadFinder hf) {
   Tree projection = head;
   if (projection == root) {
     return root;
   }
   Tree parent = projection.parent(root);
   while (hf.determineHead(parent) == projection) {
     projection = parent;
     if (projection == root) {
       return root;
     }
     parent = projection.parent(root);
   }
   return projection;
 }
  private ArrayList<TaggedWord> parseSentenceTD(String text) {
    System.out.println("Parsing sentence...");

    ArrayList<TaggedWord> tw = new ArrayList<TaggedWord>();

    Reader reader = new StringReader(text);

    for (List<HasWord> sentence : new DocumentPreprocessor(reader)) {

      Tree parse = lp.apply(sentence);

      tw = parse.taggedYield();
    }
    return tw;
  }
Esempio n. 20
0
 public static String treeToLatexEven(Tree t) {
   StringBuilder connections = new StringBuilder();
   StringBuilder hierarchy = new StringBuilder();
   int maxDepth = t.depth();
   treeToLatexEvenHelper(t, connections, hierarchy, 0, 1, 0, 0, maxDepth);
   return "\\tree" + hierarchy + '\n' + connections + '\n';
 }
Esempio n. 21
0
 /** returns true iff <code>head</code> (transitively) heads <code>node</code> */
 public static boolean heads(Tree head, Tree node, HeadFinder hf) {
   if (node.isLeaf()) {
     return false;
   } else {
     return heads(head, hf.determineHead(node), hf);
   }
 }
  public static ArrayList<ArrayList<TaggedWord>> getPhrases(Tree parse, int phraseSizeLimit) {
    ArrayList<ArrayList<TaggedWord>> newList = new ArrayList<ArrayList<TaggedWord>>();
    List<Tree> leaves = parse.getLeaves();

    if (leaves.size() <= phraseSizeLimit) {
      // ArrayList<TaggedWord> phraseElements = PreprocessPhrase(parse.taggedYield());
      ArrayList<TaggedWord> phraseElements = Preprocess(parse.taggedYield());
      if (phraseElements.size() > 0) newList.add(phraseElements);
    } else {
      Tree[] childrenNodes = parse.children();
      for (int i = 0; i < childrenNodes.length; i++) {
        Tree currentParse = childrenNodes[i];
        newList.addAll(getPhrases(currentParse, phraseSizeLimit));
      }
    }
    return newList;
  }
Esempio n. 23
0
 private static void extractSubtrees(List<String> codeStrings, String treeFile) {
   List<Pair<Integer, Integer>> codes = new ArrayList<Pair<Integer, Integer>>();
   for (String s : codeStrings) {
     Matcher m = codePattern.matcher(s);
     if (m.matches())
       codes.add(
           new Pair<Integer, Integer>(Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2))));
     else throw new RuntimeException("Error: illegal node code " + s);
   }
   TreeReaderFactory trf = new TRegexTreeReaderFactory();
   MemoryTreebank treebank = new MemoryTreebank(trf);
   treebank.loadPath(treeFile, null, true);
   for (Pair<Integer, Integer> code : codes) {
     Tree t = treebank.get(code.first() - 1);
     t.getNodeNumber(code.second()).pennPrint();
   }
 }
Esempio n. 24
0
 static boolean rightEdge(Tree t, Tree t1, MutableInteger i) {
   if (t == t1) {
     return true;
   } else if (t1.isLeaf()) {
     int j = t1.yield().size(); // so that empties don't add size
     i.set(i.intValue() - j);
     return false;
   } else {
     Tree[] kids = t1.children();
     for (int j = kids.length - 1; j >= 0; j--) {
       if (rightEdge(t, kids[j], i)) {
         return true;
       }
     }
     return false;
   }
 }
Esempio n. 25
0
  /**
   * Return information about the objects in this Tree.
   *
   * @param t The tree to examine.
   * @return A human-readable String
   */
  public static String toDebugStructureString(Tree t) {
    StringBuilder sb = new StringBuilder();
    String tCl = StringUtils.getShortClassName(t);
    String tfCl = StringUtils.getShortClassName(t.treeFactory());
    String lCl = StringUtils.getShortClassName(t.label());
    String lfCl = StringUtils.getShortClassName(t.label().labelFactory());
    Set<String> otherClasses = new HashSet<String>();
    for (Tree st : t) {
      String stCl = StringUtils.getShortClassName(st);
      String stfCl = StringUtils.getShortClassName(st.treeFactory());
      String slCl = StringUtils.getShortClassName(st.label());
      String slfCl = StringUtils.getShortClassName(st.label().labelFactory());

      if (!tCl.equals(stCl)) {
        otherClasses.add(stCl);
      }
      if (!tfCl.equals(stfCl)) {
        otherClasses.add(stfCl);
      }
      if (!lCl.equals(slCl)) {
        otherClasses.add(slCl);
      }
      if (!lfCl.equals(slfCl)) {
        otherClasses.add(slfCl);
      }
    }
    sb.append("Tree with root of class ").append(tCl).append(" and factory ").append(tfCl);
    sb.append(" with label class ").append(lCl).append(" and factory ").append(lfCl);
    if (!otherClasses.isEmpty()) {
      sb.append(" with the following classes also found within the tree: ").append(otherClasses);
    }
    return sb.toString();
  }
 public static void main(String args[]) {
   //        String sentence1 = "A large bird standing on a table picks up a plastic glass
   // containing liquid and places it in a bowl of something.";
   //        String sentence2 = "A bird picks up a plastic cup containing a liquid with it's beak
   // and puts the cup into a bowl.";
   //        LexicalizedParser lp = new LexicalizedParser("englishPCFG.ser.gz");
   //        LeskWSD tm = new LeskWSD(lp);
   //        WordNetSimilarity ws = new WordNetSimilarity();
   //
   //        System.out.println(LexicalSimilarityScoreWordNet(sentence1, sentence2, tm, lp, ws));
   String sentence =
       "The broader Standard & Poor's 500 Index <.SPX> shed 2.38 points, or 0.24 percent, at 995.10.";
   LexicalizedParser lp = new LexicalizedParser("englishPCFG.ser.gz");
   Tree parse = lp.apply(sentence);
   ArrayList<TaggedWord> taggedWords = parse.taggedYield();
   taggedWords = Preprocess(taggedWords);
   for (int i = 0; i < taggedWords.size(); i++) System.out.println(taggedWords.get(i).word());
 }
Esempio n. 27
0
 /**
  * Returns the positional index of the right edge of a tree <i>t</i> within a given root, as
  * defined by the size of the yield of all material preceding <i>t</i> plus all the material
  * contained in <i>t</i>.
  */
 public static int rightEdge(Tree t, Tree root) {
   MutableInteger i = new MutableInteger(root.yield().size());
   if (rightEdge(t, root, i)) {
     return i.intValue();
   } else {
     throw new RuntimeException("Tree is not a descendent of root.");
     //      return root.yield().size() + 1;
   }
 }
Esempio n. 28
0
 public static Tree copyHelper(Tree t, Map<Tree, Tree> newToOld, Map<Tree, Tree> oldToNew) {
   Tree[] kids = t.children();
   Tree[] newKids = new Tree[kids.length];
   for (int i = 0, n = kids.length; i < n; i++) {
     newKids[i] = copyHelper(kids[i], newToOld, oldToNew);
   }
   TreeFactory tf = t.treeFactory();
   if (kids.length == 0) {
     Tree newLeaf = tf.newLeaf(t.label());
     newToOld.put(newLeaf, t);
     oldToNew.put(newLeaf, t);
     return newLeaf;
   }
   Tree newNode = tf.newTreeNode(t.label(), Arrays.asList(newKids));
   newToOld.put(newNode, t);
   oldToNew.put(t, newNode);
   return newNode;
 }
Esempio n. 29
0
  public static void main(String[] args) throws Exception {
    InputStream in;

    System.out.print("loading WiX grammar... ");

    CharParser meta = new CharParser(GrammarAST.getMetaGrammar());

    System.out.print("wix.g ");
    in = BuildParser.class.getClassLoader().getResourceAsStream("wix.g");
    Tree wix = meta.parse(in).expand1();
    System.out.print("indent.g ");
    in = BuildParser.class.getClassLoader().getResourceAsStream("indent.g");
    Tree indent = meta.parse(in).expand1();
    System.out.print("tokens.g ");
    in = BuildParser.class.getClassLoader().getResourceAsStream("tokens.g");
    Tree tokens = meta.parse(in).expand1();
    System.out.print("url.g ");
    in = BuildParser.class.getClassLoader().getResourceAsStream("url.g");
    Tree url = meta.parse(in).expand1();
    System.out.println("done.");

    System.out.print("writing WiXGrammar.java... ");
    Writer out = new FileWriter("build/WiXGrammar.java");

    out.write("/* AUTO GENERATED, DO NOT EDIT */\n");
    out.write("package com.zentus.wixer;\n");
    out.write("import edu.berkeley.sbp.*;\n");
    out.write("public class WiXGrammar {\n\n");
    out.write("public static final Tree wix, indent, tokens, url;\n\n");
    out.write("static {\n");
    out.write("  Tree w = null, i = null, t = null, u = null;\n");
    out.write("  try {\n");
    out.write("  w = \n");
    wix.toJava(out);
    out.write("  ;\n");
    out.write("  i = \n");
    indent.toJava(out);
    out.write("  ;\n");
    out.write("  t = \n");
    tokens.toJava(out);
    out.write("  ;\n");
    out.write("  u = \n");
    url.toJava(out);
    out.write("  ;\n");
    out.write("  } catch (Exception e) {throw new RuntimeException(e);}\n");
    out.write("  wix    = w;\n");
    out.write("  indent = i;\n");
    out.write("  tokens = t;\n");
    out.write("  url    = u;\n");
    out.write("}\n");
    out.write("}\n");
    out.close();
    System.out.println("done.");
  }
Esempio n. 30
0
 private MutableTreeNode populateTree(Tree t) throws SQLException {
   DefaultMutableTreeNode tree = new DefaultMutableTreeNode(t);
   // tree.add(populateAttributes(t));
   Statement stmt = db.statement();
   for (Cavity c : t.loadCavities(stmt)) {
     tree.add(populateCavity(c));
   }
   stmt.close();
   return tree;
 }