/** * Get the path from the source TreebankNode to the target TreebankNode via the least common * ancestor. * * @param source * The TreebankNode where the path should start. * @param target * The TreebankNode where the path should end. * @return The path from the source node to the target node. */ public static TreebankNodePath getPath(TreebankNode source, TreebankNode target) { List<TreebankNode> sourceToRoot = getPathToRoot(source); List<TreebankNode> targetToRoot = getPathToRoot(target); TreebankNode ancestor = null; while (sourceToRoot.size() > 0 && targetToRoot.size() > 0 && sourceToRoot.get(sourceToRoot.size() - 1) == targetToRoot.get(targetToRoot.size() - 1)) { ancestor = sourceToRoot.remove(sourceToRoot.size() - 1); ancestor = targetToRoot.remove(targetToRoot.size() - 1); } return new TreebankNodePath(ancestor, sourceToRoot, targetToRoot); }
protected static String noLeavesPath(TreebankNodePath path) { if (path.getCommonAncestor() == null) { return null; } List<String> sourceTypes = new ArrayList<String>(); for (TreebankNode node : path.getSourceToAncestorPath()) { if (!node.getLeaf()) { sourceTypes.add(node.getNodeType()); } } List<String> targetTypes = new ArrayList<String>(); for (TreebankNode node : path.getTargetToAncestorPath()) { if (!node.getLeaf()) { targetTypes.add(node.getNodeType()); } } Collections.reverse(targetTypes); StringBuilder builder = new StringBuilder(); for (String type : sourceTypes) { builder.append(type).append('>'); } builder.append(path.getCommonAncestor().getNodeType()); for (String type : targetTypes) { builder.append('<').append(type); } return builder.toString(); } }
public List<Feature> extract(JCas jCas, T source, U target) { List<Feature> features = new ArrayList<Feature>(); TreebankNode sourceNode = TreebankNodeUtil.selectMatchingLeaf(jCas, source); TreebankNode targetNode = TreebankNodeUtil.selectMatchingLeaf(jCas, target); if (sourceNode != null && targetNode != null) { TreebankNodePath path = TreebankNodeUtil.getPath(sourceNode, targetNode); TreebankNode ancestor = path.getCommonAncestor(); features.add(new Feature("CommonAncestor", ancestor == null ? null : ancestor.getNodeType())); features.add(new Feature("SourceToAncestor", pathString(path.getSourceToAncestorPath()))); features.add(new Feature("TargetToAncestor", pathString(path.getTargetToAncestorPath()))); } return features; }