@Test public void validates_supported_simple_types() { assertThat( visitor().visit( typeMirrorTestUtils().typeOf( String.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( Number.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( Long.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( TypeKind.LONG ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( Double.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( TypeKind.DOUBLE ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( Boolean.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( TypeKind.BOOLEAN ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( Path.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( Node.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( Relationship.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( Object.class ) ) ).isTrue(); }
@Test public void validates_supported_generic_types() { assertThat( visitor().visit( typeMirrorTestUtils().typeOf( Map.class, String.class, Object.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( HashMap.class, String.class, Object.class ) ) ) .isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( LinkedHashMap.class, String.class, Object.class ) ) ) .isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( List.class, String.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( LinkedList.class, Number.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( ArrayList.class, Long.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( List.class, Double.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( List.class, Boolean.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( List.class, Path.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( List.class, Node.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( List.class, Relationship.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils().typeOf( List.class, Object.class ) ) ).isTrue(); assertThat( visitor().visit( typeMirrorTestUtils() .typeOf( List.class, typeMirrorTestUtils().typeOf( Map.class, String.class, Object.class ) ) ) ) .isTrue(); assertThat( visitor().visit( typeMirrorTestUtils() .typeOf( List.class, typeMirrorTestUtils().typeOf( LinkedList.class, Long.class ) ) ) ).isTrue(); }
@Test public void supported_simple_type_is_valid() { assertThat( validator.test( typeMirrorTestUtils.typeOf( BOOLEAN ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( LONG ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( DOUBLE ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( Boolean.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( Long.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( Double.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( String.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( Number.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( Object.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( Node.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( Relationship.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( Path.class ) ) ).isTrue(); }
public static List<String> getHypernyms(String cui){ List<String> hypers = new ArrayList<>(); try ( Transaction tx = graphDb.beginTx() ){ TraversalDescription td = graphDb.traversalDescription() .breadthFirst() .relationships(RelReader.RelTypes.ISA, Direction.OUTGOING) .evaluator(Evaluators.excludeStartPosition()); Node cuiNode = graphDb.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, cui); if(cuiNode == null) return hypers; Traverser traverser = td.traverse(cuiNode); for(Path path : traverser){ hypers.add(path.endNode().getProperty(RelReader.CUI_PROPERTY).toString()); } tx.success(); } return hypers; }
public static List<String> getHyponyms(String cui){ List<String> hypos = new ArrayList<>(); try ( Transaction tx = graphDb.beginTx() ){ TraversalDescription td = graphDb.traversalDescription() .breadthFirst() .relationships(RelReader.RelTypes.ISA, Direction.INCOMING) .evaluator(Evaluators.excludeStartPosition()); Node cuiNode = graphDb.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, cui); if(cuiNode == null) return hypos; Traverser traverser = td.traverse(cuiNode); for(Path path : traverser){ hypos.add(path.endNode().getProperty(RelReader.CUI_PROPERTY).toString()); } tx.success(); } return hypos; }
public static int minDistance(String cui1, String cui2){ int distance = -1; try ( Transaction tx = graphDb.beginTx() ){ Node cui1Node = graphDb.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, cui1); Node cui2Node = graphDb.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, cui2); if(cui1Node == null || cui2Node == null) return distance; TraversalDescription td = graphDb.traversalDescription() .breadthFirst() .relationships(RelReader.RelTypes.ISA, Direction.OUTGOING) .evaluator(Evaluators.excludeStartPosition()) .evaluator(Evaluators.includeWhereEndNodeIs(cui2Node)); Traverser traverser = td.traverse(cui1Node); for(Path path : traverser){ int len = path.length(); if(distance == -1 || len < distance){ distance = len; } } tx.success(); } return distance; }
@Test public void testRelReader() throws IOException{ RelReader reader = new RelReader(neo4jLocation); reader.batchBuildGraph(new File("my_test_umls/"), "CtakesAllTuis.txt", "SNOMEDCT_US"); GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(new File(neo4jLocation)); try ( Transaction tx = db.beginTx() ){ TraversalDescription td = db.traversalDescription() .breadthFirst() .relationships(RelReader.RelTypes.ISA, Direction.INCOMING) .evaluator(Evaluators.excludeStartPosition()); Node cuiNode = db.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, "C0007102"); Assert.assertNotNull(cuiNode); Traverser traverser = td.traverse(cuiNode); for(Path path : traverser){ System.out.println("At depth " + path.length() + " => " + path.endNode().getProperty("cui")); } } db.shutdown(); }
public void traverse() { if (null != graph && null != root) { try (Transaction tx = graph.beginTx()) { PathFinder<Path> finder = GraphAlgoFactory.allPaths( PathExpanders.forTypesAndDirections(RelTypes.CHILD_HI, Direction.OUTGOING, RelTypes.CHILD_LO, Direction.OUTGOING), 5); // 5 is the number of original relationships + 1 Iterable<Path> paths = finder.findAllPaths(root, one); double total = 0.0; for (Path path : paths) { double current = 1.0; for (Relationship relationship : path.relationships()) { current *= (double) relationship.getProperty(PROB, 1.0); } total += current; } System.out.format("The probability is %.2f.\n", total); tx.success(); } } }
public void stamp() { if (null != graph && null != root) { try (Transaction tx = graph.beginTx()) { PathFinder<Path> finder = GraphAlgoFactory.allPaths( PathExpanders.forTypesAndDirections(RelTypes.CHILD_HI, Direction.OUTGOING, RelTypes.CHILD_LO, Direction.OUTGOING), 5); // 5 is the number of original relationships + 1 Iterable<Path> paths = finder.findAllPaths(root, one); for (Path path : paths) { boolean first = true; for (Relationship relationship : path.relationships()) { if (first) { System.out.format("(%s)", relationship.getStartNode().getProperty(ID)); first = false; } System.out.format(" --[%s,%.2f]-> ", relationship.getType().name(), relationship.getProperty(PROB, 1.0)); System.out.format("(%s)", relationship.getEndNode().getProperty(ID)); } System.out.println(); } tx.success(); } } }
private void analyseDb() { Transaction tx = graphDb.beginTx(); try { PathFinder<Path> finder = GraphAlgoFactory.allPaths(// PathExpanders.forTypeAndDirection(RelTypes.KNOWS, Direction.BOTH), -1); Iterable<Path> paths = finder.findAllPaths(firstNode, secondNode); for (Path path : paths) { for (Node node : path.nodes()) { for (String prop : node.getPropertyKeys()) System.out.print(prop); System.out.print(node.toString()); } for (Relationship relationship : path.relationships()) System.out.print(relationship.toString()); } tx.success(); } finally { tx.finish(); } }
public String printNeoFriends() { try (Transaction tx = graphDb.beginTx()) { Node neoNode = getNeoNode(); // START SNIPPET: friends-usage int numberOfFriends = 0; String output = neoNode.getProperty("name") + "'s friends:\n"; Traverser friendsTraverser = getFriends(neoNode); for (Path friendPath : friendsTraverser) { output += "At depth " + friendPath.length() + " => " + friendPath.endNode().getProperty("name") + "\n"; numberOfFriends++; } output += "Number of friends found: " + numberOfFriends + "\n"; // END SNIPPET: friends-usage return output; } }
public double traverse() { if (null != root && value < 0.0) { try (Transaction ignore = graph.beginTx()) { value = 0.0; PathFinder<Path> finder = GraphAlgoFactory.allPaths( PathExpanders.forTypesAndDirections(RelType.LO_CHILD, Direction.OUTGOING, RelType.HI_CHILD, Direction.OUTGOING), max); Iterable<Path> paths = finder.findAllPaths(root, one); for (Path path : paths) { double current = 1.0; for (Relationship relationship : path.relationships()) { current *= (double) relationship.getProperty(PROB, 1.0); } value += current; } } } return value; }
/** * Evaluates a node and determines whether to include and / or continue. * Continues on and returns exactly those nodes that: * <ul> * <li>haven't been visited yet and</li> * <li>are the start node * <ul> * <li>have a sequence < threshold (and thus belong to the same cluster)</li> * </ul> * </ul> */ @Override public Evaluation evaluate(Path path) { Node end = path.endNode(); int score = is.compute(new Neo4jScoreContainer(end)); end.setProperty(SequenceProperties.INTERESTINGNESS.name(), score); String id = (String) end.getProperty(ID.name()); if (!visited.contains(id) && (path.startNode().getId() == path.endNode().getId() || score < threshold)) { visited.add(id); return Evaluation.INCLUDE_AND_CONTINUE; } return Evaluation.EXCLUDE_AND_PRUNE; }
@Override public Map<String, Set<Long>> call() throws Exception { logger.info("Processsing " + category); Map<String, Set<Long>> map = new HashMap<String, Set<Long>>(); Set<Long> nodeSet = new HashSet<Long>(); Transaction tx = graphDb.beginTx(); try { for (Path position : graphDb.traversalDescription().uniqueness(Uniqueness.NODE_GLOBAL).depthFirst() .relationships(OwlRelationships.RDFS_SUBCLASS_OF, Direction.INCOMING).relationships(OwlRelationships.RDF_TYPE, Direction.INCOMING) .relationships(OwlRelationships.OWL_EQUIVALENT_CLASS, Direction.BOTH).relationships(OwlRelationships.OWL_SAME_AS, Direction.BOTH) .traverse(root)) { Node end = position.endNode(); nodeSet.add(end.getId()); } logger.info("Discovered " + nodeSet.size() + " nodes for " + category); map.put(category, nodeSet); } catch (Exception e) { logger.warning("IRI not found for category: " + category); } finally { tx.success(); tx.close(); } return map; }
public Graph getEdges(RelationshipType type, boolean entail, long skip, long limit) { String query = "MATCH path = (start)-[r:" + type.name() + (entail ? "!" : "") + "]->(end) " + " RETURN path " // TODO: This slows down the query dramatically. // + " ORDER BY ID(r) " + " SKIP " + skip + " LIMIT " + limit; Graph graph = new TinkerGraph(); TinkerGraphUtil tgu = new TinkerGraphUtil(graph, curieUtil); Result result; try { result = cypherUtil.execute(query); while (result.hasNext()) { Map<String, Object> map = result.next(); Path path = (Path) map.get("path"); tgu.addPath(path); } } catch (ArrayIndexOutOfBoundsException e) { // Return and empty graph if the limit is too high... } return graph; }
public String knowsLikesTraverser( Node node ) { String output = ""; // START SNIPPET: knowslikestraverser for ( Path position : db.traversalDescription() .depthFirst() .relationships( Rels.KNOWS ) .relationships( Rels.LIKES, Direction.INCOMING ) .evaluator( Evaluators.toDepth( 5 ) ) .traverse( node ) ) { output += position + "\n"; } // END SNIPPET: knowslikestraverser return output; }
@Override public String relationshipRepresentation(final Path path, final Node from, final Relationship relationship) { final String prefix; final String suffix; if (from.equals(relationship.getEndNode())) { prefix = PREFIX; suffix = INTERMEDIATE; } else { suffix = SUFFIX; prefix = INTERMEDIATE; } final StringBuilder sb = new StringBuilder(); sb.append(prefix).append(GraphDBPrintUtil.printRelationship(relationship)).append(suffix); return sb.toString(); }
/** * note: should be run in transaction scope * * @param graphDB * @param prefixedResourceURI * @return */ public static Iterable<Path> getResourcePaths(final GraphDatabaseService graphDB, final String prefixedResourceURI) { final Node resourceNode = getResourceNode(graphDB, prefixedResourceURI); // TODO: maybe replace with gethEntityPaths(GraphdataBaseService, Node) final Iterable<Path> paths = graphDB.traversalDescription().uniqueness(Uniqueness.RELATIONSHIP_GLOBAL) .order(BranchOrderingPolicies.POSTORDER_BREADTH_FIRST).expand(PathExpanderBuilder.allTypes(Direction.OUTGOING).build()) .evaluator(path -> { final boolean hasLeafLabel = path.endNode() != null && path.endNode().hasLabel(org.dswarm.graph.GraphProcessingStatics.LEAF_LABEL); if (hasLeafLabel) { return org.neo4j.graphdb.traversal.Evaluation.INCLUDE_AND_CONTINUE; } return org.neo4j.graphdb.traversal.Evaluation.EXCLUDE_AND_CONTINUE; }).traverse(resourceNode); return paths; }
/** * note: should be run in transaction scope * * @param graphDB * @param resourceNode * @return */ public static Iterable<Path> getResourcePaths(final GraphDatabaseService graphDB, final Node resourceNode) { // TODO: maybe replace with gethEntityPaths(GraphdataBaseService, Node) final Iterable<Path> paths = graphDB.traversalDescription().uniqueness(Uniqueness.RELATIONSHIP_GLOBAL) .order(BranchOrderingPolicies.POSTORDER_BREADTH_FIRST).expand(PathExpanderBuilder.allTypes(Direction.OUTGOING).build()) .evaluator(path -> { final boolean reachedEndOfResourcePath = path.length() >= 1 && (path.endNode().hasProperty(org.dswarm.graph.model.GraphStatics.URI_PROPERTY) || path.endNode() .hasProperty(org.dswarm.graph.model.GraphStatics.VALUE_PROPERTY)); if (reachedEndOfResourcePath) { return org.neo4j.graphdb.traversal.Evaluation.INCLUDE_AND_CONTINUE; } return org.neo4j.graphdb.traversal.Evaluation.EXCLUDE_AND_CONTINUE; }).traverse(resourceNode); return paths; }
/** * note: should be executed in transaction scope * * @param deltaState * @param graphDB * @param pathEndNodeIds * @param nodeId */ public static void determineNonMatchedSubGraphPathEndNodes(final DeltaState deltaState, final GraphDatabaseService graphDB, final Set<Long> pathEndNodeIds, final long nodeId) throws DMPGraphException { if (deltaState == DeltaState.ADDITION || deltaState == DeltaState.DELETION) { final Iterable<Path> nonMatchedSubGraphPaths = getNonMatchedSubGraphPaths(nodeId, graphDB); if (nonMatchedSubGraphPaths != null && nonMatchedSubGraphPaths.iterator().hasNext()) { for (final Path nonMatchtedSubGraphPath : nonMatchedSubGraphPaths) { GraphDBUtil.addNodeId(pathEndNodeIds, nonMatchtedSubGraphPath.endNode().getId()); } } } }
public static String dump(Path data) { StringBuilder builder = new StringBuilder(); builder.append("!Path "); Node node = null; char link = '['; for (PropertyContainer entity : data) { builder.append(link); if (entity instanceof Node) { node = (Node) entity; builder.append(dump(node)); } else if (entity instanceof Relationship) { Relationship rel = (Relationship) entity; if (node != null) { long nodeID = node.getId(); if (rel.getStartNode().getId() != nodeID && rel.getEndNode().getId() == nodeID) { builder.append(dumpRev(rel)); } else { builder.append(dumpRel(rel)); } } } link = ','; } builder.append(']'); return builder.toString(); }
@Override public final Iterable<Relationship> expand(final Path path, final BranchState state) { List<Relationship> result = new ArrayList<>(); if (this.since == Long.MIN_VALUE && this.until == Long.MAX_VALUE) { return path.endNode().getRelationships(); } if (path.length() >= this.depth) { return result; } for (Relationship rel : path.endNode().getRelationships()) { long current = Long.parseLong(rel.getProperty("timestamp").toString()); if (until > current && current > since) { result.add(rel); } } return result; }
private StepExpander buildStepExpander( RelationshipFilterDescriptor relationshipDescriptor ) { List<PropertyContainerPredicate> relationshipPredicateList = relationshipDescriptor.getFilterPredicates(); final PredicateGroup<PropertyContainer> relationshipPredicates = ( relationshipPredicateList.isEmpty() ) ? null : new PredicateGroup<PropertyContainer>( relationshipPredicateList.toArray( new PropertyContainerPredicate[relationshipPredicateList.size()] ) ); final Function<Node, Iterator<Relationship>> expandFun = relationshipDescriptor.expandFun(); return new StepExpander() { @Override public Iterable<Relationship> expand( Path path, BranchState<StepState> state ) { final Node startNode = path.endNode(); Iterator<Relationship> relationships = ( null == relationshipPredicates ) ? expandFun.apply( startNode ) : Iterators.filter( expandFun.apply( startNode ), relationshipPredicates ); return ImmutableList.copyOf( relationships ); } }; }
public static String pathString(Path path) { StringBuilder sb = new StringBuilder(); Node lastNode = null; for (PropertyContainer thing : path) { if (thing instanceof Node) { lastNode = (Node) thing; sb.append("(").append( Sets.newHashSet(lastNode.getLabels()).toString().replace("[", "").replace("]", "")).append( ")"); } if (thing instanceof Relationship) { Relationship relationship = (Relationship) thing; if (relationship.getStartNode().equals(lastNode)) { sb.append("-[").append(relationship.getType().name()).append("]->"); } else { sb.append("<-[").append(relationship.getType().name()).append("]-"); } } } return sb.toString(); }
public WeightedPath findSinglePath( Node start, Node end ) { Doer doer = new Doer( start, end ); while ( doer.hasNext() ) { Node node = doer.next(); GraphDatabaseService graphDb = node.getGraphDatabase(); if ( node.equals( end ) ) { // Hit, return path double weight = doer.score.get( node.getId() ).wayLength; LinkedList<Relationship> rels = new LinkedList<Relationship>(); Relationship rel = graphDb.getRelationshipById( doer.cameFrom.get( node.getId() ) ); while ( rel != null ) { rels.addFirst( rel ); node = rel.getOtherNode( node ); Long nextRelId = doer.cameFrom.get( node.getId() ); rel = nextRelId == null ? null : graphDb.getRelationshipById( nextRelId ); } Path path = toPath( start, rels ); return new WeightedPathImpl( weight, path ); } } return null; }
private static Iterable<Path> hitsToPaths( Collection<Hit> depthHits, Node start, Node end ) { Collection<Path> paths = new ArrayList<Path>(); for ( Hit hit : depthHits ) { Iterable<LinkedList<Relationship>> startPaths = getPaths( hit, hit.start ); Iterable<LinkedList<Relationship>> endPaths = getPaths( hit, hit.end ); for ( LinkedList<Relationship> startPath : startPaths ) { PathImpl.Builder startBuilder = toBuilder( start, startPath ); for ( LinkedList<Relationship> endPath : endPaths ) { PathImpl.Builder endBuilder = toBuilder( end, endPath ); Path path = startBuilder.build( endBuilder ); paths.add( path ); } } } return paths; }
private Path[] goOneStep( Node node, Iterator<Path> visitor, Map<Node, Visit> visits ) { if ( !visitor.hasNext() ) { return null; } Path position = visitor.next(); Visit visit = visits.get( position.endNode() ); if ( visit != null ) { if ( visitor != visit.visitor ) { return new Path[] { visit.position, position }; } } else { visits.put( position.endNode(), new Visit( position, visitor ) ); } return null; }
public Iterable<WeightedPath> findAllPaths( Node start, final Node end ) { Predicate<Path> filter = new Predicate<Path>() { public boolean accept( Path position ) { return position.endNode().equals( end ); } }; final Traverser traverser = TRAVERSAL.expand( expander ).order( new SelectorFactory( costEvaluator ) ).filter( filter ).traverse( start ); return new Iterable<WeightedPath>() { public Iterator<WeightedPath> iterator() { return new StopAfterWeightIterator( traverser.iterator(), costEvaluator ); } }; }
public Iterable<WeightedPath> findAllPaths( Node start, final Node end ) { Predicate<Path> filter = new Predicate<Path>() { public boolean accept( Path position ) { return position.endNode().equals( end ); } }; final Traverser traverser = traversalDescription.order( new SelectorFactory( end ) ).filter( filter ).traverse( start ); return new Iterable<WeightedPath>() { public Iterator<WeightedPath> iterator() { return new StopAfterWeightIterator( traverser.iterator(), costEvaluator ); } }; }
/** * Combines two {@link TraversalBranch}s with a common * {@link TraversalBranch#node() head node} in order to obtain an * {@link TraversalBranch} representing a path from the start node of the * <code>source</code> {@link TraversalBranch} to the start node of the * <code>target</code> {@link TraversalBranch}. The resulting * {@link TraversalBranch} will not {@link TraversalBranch#next() expand * further}, and does not provide a {@link TraversalBranch#parent() parent} * {@link TraversalBranch}. * * @param source the {@link TraversalBranch} where the resulting path starts * @param target the {@link TraversalBranch} where the resulting path ends * @throws IllegalArgumentException if the {@link TraversalBranch#node() * head nodes} of the supplied {@link TraversalBranch}s does not * match * @return an {@link TraversalBranch} that represents the path from the * start node of the <code>source</code> {@link TraversalBranch} to * the start node of the <code>target</code> {@link TraversalBranch} */ public static TraversalBranch combineSourcePaths( TraversalBranch source, TraversalBranch target ) { if ( !source.node().equals( target.node() ) ) { throw new IllegalArgumentException( "The nodes of the head and tail must match" ); } Path headPath = source.position(), tailPath = target.position(); Relationship[] relationships = new Relationship[headPath.length() + tailPath.length()]; Iterator<Relationship> iter = headPath.relationships().iterator(); for ( int i = 0; iter.hasNext(); i++ ) { relationships[i] = iter.next(); } iter = tailPath.relationships().iterator(); for ( int i = relationships.length - 1; iter.hasNext(); i-- ) { relationships[i] = iter.next(); } return new FinalTraversalBranch( tailPath.startNode(), relationships ); }
/** * Returns a filter which accepts items accepted by at least one of the * supplied filters. * * @param filters to group together. * @return a {@link Predicate} which accepts if any of the filters accepts. */ public static Predicate<Path> returnAcceptedByAny( final Predicate<Path>... filters ) { return new Predicate<Path>() { public boolean accept( Path item ) { for ( Predicate<Path> filter : filters ) { if ( filter.accept( item ) ) { return true; } } return false; } }; }
@Override protected Path fetchNextOrNull() { TraversalBranch result = null; while ( true ) { result = sourceSelector.next(); if ( result == null ) { return null; } if ( result.evaluation().includes() ) { return result.position(); } } }
@Override public Iterable<Relationship> expand(Path path, BranchState state) { List<Relationship> children = CHILDREN_ORDER.sortedCopy(path.endNode().getRelationships(RelType.PARENT_OF, Direction.OUTGOING)); if (synRels.isEmpty()) { return children; } else { List<Iterable<Relationship>> synResults = Lists.newArrayList(); for (RelType rt : synRels) { synResults.add(path.endNode().getRelationships(rt, Direction.INCOMING)); } return Iterables.concat( SYNONYM_ORDER.sortedCopy(Iterables.concat(synResults)), children ); } }
@Override public Iterable<Relationship> expand(Path path, BranchState branchState) { if (path.endNode().hasLabel(stopLabel)) { return Collections.emptyList(); } if (path.length() % 2 == 0) { return path.endNode().getRelationships(Direction.INCOMING); } else { return path.endNode().getRelationships(Direction.OUTGOING); } }
@Override public Evaluation evaluate(Path path, BranchState branchState) { if (path.endNode().hasLabel(stopLabel)) { return Evaluation.EXCLUDE_AND_PRUNE; } else { return Evaluation.INCLUDE_AND_CONTINUE; } }
@Override public Evaluation evaluate(Path path, BranchState<Double> branchState) { // Path with just the single node, ignore it and continue if (path.length() == 0 ) { return Evaluation.INCLUDE_AND_CONTINUE; } // Make sure last Equipment voltage is equal to or lower than previous voltage Double voltage = (Double) path.endNode().getProperty("voltage", 999.0); if (voltage <= branchState.getState()) { return Evaluation.INCLUDE_AND_CONTINUE; } else { return Evaluation.EXCLUDE_AND_PRUNE; } }
public final Collection<TypeMirror> procedureAllowedTypes() { PrimitiveType bool = primitive( TypeKind.BOOLEAN ); PrimitiveType longType = primitive( TypeKind.LONG ); PrimitiveType doubleType = primitive( TypeKind.DOUBLE ); return asList( bool, boxed( bool ), longType, boxed( longType ), doubleType, boxed( doubleType ), typeMirror( String.class ), typeMirror( Number.class ), typeMirror( Object.class ), typeMirror( Map.class ), typeMirror( List.class ), typeMirror( Node.class ), typeMirror( Relationship.class ), typeMirror( Path.class ) ); }
@Test public void supported_list_type_is_valid() { assertThat( validator.test( typeMirrorTestUtils.typeOf( List.class, Boolean.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( List.class, Long.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( List.class, Double.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( List.class, String.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( List.class, Number.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( List.class, Object.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( List.class, Node.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( List.class, Relationship.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( List.class, Path.class ) ) ).isTrue(); }
@Test public void supported_map_type_is_valid() { assertThat( validator.test( typeMirrorTestUtils.typeOf( Map.class, String.class, Boolean.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( Map.class, String.class, Long.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( Map.class, String.class, Double.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( Map.class, String.class, String.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( Map.class, String.class, Number.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( Map.class, String.class, Object.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( Map.class, String.class, Node.class ) ) ).isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( Map.class, String.class, Relationship.class ) ) ) .isTrue(); assertThat( validator.test( typeMirrorTestUtils.typeOf( Map.class, String.class, Path.class ) ) ).isTrue(); }
public void stamp() { if (null != graph && null != root) { try (Transaction tx = graph.beginTx()) { // Traverser traverser = // graph.traversalDescription().relationships(RelTypes.LINKS, // Direction.OUTGOING) // .evaluator(Evaluators.excludeStartPosition()).traverse(root); // for (Path path : traverser) { PathFinder<Path> finder = GraphAlgoFactory.allPaths(// PathExpanders.forTypeAndDirection(RelTypes.LINKS, Direction.OUTGOING), 4); // 4 // is // the // number // of // nodes // + // 1 Iterable<Path> paths = finder.findAllPaths(root, done); for (Path path : paths) { boolean first = true; for (Relationship relationship : path.relationships()) { if (first) { System.out.format("(%s)", relationship.getStartNode().getProperty(ID)); first = false; } System.out.format(" --[%s:%d,%.2f]-> ", RelTypes.LINKS, relationship.getProperty(ID), relationship.getProperty(PROB, 1.0)); System.out.format("(%s)", relationship.getEndNode().getProperty(ID)); } System.out.println(); // System.out.println(Paths.defaultPathToString(path)); } tx.success(); } } }