private Traverser getPatternMatch(Node startNode, final List<String> patterns, final List<NodeLabel> nodeLabels, final List<LinkLabel> linkLabels) { TraversalDescription td = database.traversalDescription() .depthFirst() .evaluator( new Evaluator() { public Evaluation evaluate( final org.neo4j.graphdb.Path path ) { if ( path.length() == 0 ) { return Evaluation.EXCLUDE_AND_CONTINUE; } boolean isToken = path.endNode().hasLabel(NodeLabel.WordToken); boolean included = isToken && (path.length() == 1 || nodeHasAnnotation(path.endNode(), linkLabels.get(path.length() - 1), patterns.get(path.length() - 1))); boolean continued = path.length() < patterns.size(); return Evaluation.of( included, continued ); } } ) .relationships(LinkLabel.NEXT, Direction.OUTGOING) .relationships(LinkLabel.HAS_TYPE, Direction.INCOMING) .relationships(LinkLabel.HAS_LEMMA, Direction.INCOMING) .relationships(LinkLabel.HAS_POS_TAG, Direction.INCOMING) .relationships(LinkLabel.HAS_HEAD, Direction.INCOMING); return td.traverse(startNode); }
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 boolean isa(String cui1, String cui2){ boolean match=false; 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 match; TraversalDescription td = graphDb.traversalDescription() .breadthFirst() .relationships(RelReader.RelTypes.ISA, Direction.OUTGOING) .evaluator(Evaluators.excludeStartPosition()) .evaluator(Evaluators.includeWhereEndNodeIs(cui2Node)); Traverser traverser = td.traverse(cui1Node); if(traverser.iterator().hasNext()){ match = true; } tx.success(); } return match; }
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 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 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 ); } }; }
public String printMatrixHackers() { try (Transaction tx = graphDb.beginTx()) { // START SNIPPET: find--hackers-usage String output = "Hackers:\n"; int numberOfHackers = 0; Traverser traverser = findHackers(getNeoNode()); for (Path hackerPath : traverser) { output += "At depth " + hackerPath.length() + " => " + hackerPath.endNode().getProperty("name") + "\n"; numberOfHackers++; } output += "Number of hackers found: " + numberOfHackers + "\n"; // END SNIPPET: find--hackers-usage return output; } }
private void fillNodesFromBeginning(Node currentNode, ViralShortUrl url) { // nodes from beginning, counted via a simple depth-first traversal // in the opposite direction Traverser t = Traversal.description().depthFirst() .evaluator(Evaluators.excludeStartPosition()) .relationships(LinkRelationship.SPAWNS, Direction.INCOMING) .traverse(currentNode); int nodesFromBeginning = IteratorUtil.count(t); url.setNodesFromBeginning(nodesFromBeginning); }
public void getAncestors(String task){ final Traverser traverser = getTraverser(task, Direction.OUTGOING); for (Path path : traverser) { System.out.println(pathToString(path, TASK_PATH_PRINTER)); } System.out.println("----------------------------------------------"); }
public void getDescendants(String task){ final Traverser traverser = getTraverser(task, Direction.INCOMING); for (Path path : traverser) { System.out.println(pathToString(path, TASK_PATH_PRINTER)); } System.out.println("----------------------------------------------"); }
public Traverser getTraverser(String task, Direction direction){ TraversalDescription td = Traversal.description() .breadthFirst() .relationships( TaskRelations.DEPENDS_ON, direction ) .evaluator(Evaluators.excludeStartPosition()); return td.traverse(getNode(task)); }
@GET @Path("/cc/{name}") public String getConnectedComponentsCount(@PathParam("name") String name, @Context GraphDatabaseService db) throws IOException { int CCid = 0; for ( Node n : GlobalGraphOperations.at( db ).getAllNodes() ) { if(!n.hasProperty("CCId")) { Transaction tx = db.beginTx(); try { Traverser traverser = Traversal.description() .breadthFirst() .relationships(DynamicRelationshipType.withName(name), Direction.BOTH) .evaluator(Evaluators.excludeStartPosition()) .uniqueness(Uniqueness.NODE_GLOBAL) .traverse(n); int currentCCid = CCid; CCid++; n.setProperty("CCId", currentCCid); for ( org.neo4j.graphdb.Path p : traverser ) { p.endNode().setProperty("CCId", currentCCid); } tx.success(); } catch ( Exception e ) { tx.failure(); } finally { tx.finish(); } } } return String.valueOf(CCid); }
private Traverser getFriends(final Node person) { TraversalDescription td = graphDb.traversalDescription().breadthFirst().relationships(RelTypes.KNOWS, Direction.OUTGOING) .evaluator(Evaluators.excludeStartPosition()); return td.traverse(person); }
private Traverser findHackers(final Node startNode) { TraversalDescription td = graphDb.traversalDescription().breadthFirst().relationships(RelTypes.CODED_BY, Direction.OUTGOING) .relationships(RelTypes.KNOWS, Direction.OUTGOING).evaluator(Evaluators.includeWhereLastRelationshipTypeIs(RelTypes.CODED_BY)); return td.traverse(startNode); }
public Traverser traverse( Node startNode ) { return new TraverserImpl( this, startNode ); }
public static List<CostFunction> getCostFunctionsForNode(Long id, EmbeddedGraphDatabase database) { List<CostFunction> costFunctions = new ArrayList<CostFunction>(); boolean transactionAllreadyRunning = false; try { transactionAllreadyRunning = (database.getTxManager().getStatus() == Status.STATUS_ACTIVE); } catch (SystemException ex) { log.error(ex.getMessage(), ex); } Transaction tx = (transactionAllreadyRunning) ? null : database.beginTx(); try { Node parentNode = database.getNodeById(id); if (parentNode == null) { return costFunctions; } //search from this node with ID=id the target nodes for which it has a HAS_COST_FUNCTION relationship TraversalDescription description = Traversal.traversal() .evaluator(Evaluators.excludeStartPosition()) .relationships(ServiceUnitRelationship.hasCostFunction, Direction.OUTGOING) .uniqueness(Uniqueness.NODE_PATH); Traverser traverser = description.traverse(parentNode); for (Path path : traverser) { Node node = path.endNode(); CostFunction costFunction = new CostFunction(); costFunction.setId(node.getId()); if (node.hasProperty(KEY)) { costFunction.setName(node.getProperty(KEY).toString()); } else { log.warn("Retrieved CostFunction " + node + " has no " + KEY); } if (node.hasProperty(UUID)) { costFunction.setUuid(java.util.UUID.fromString(node.getProperty(UUID).toString())); } else { log.warn("Retrieved CloudProvider " + costFunction + " has no " + UUID); } //carefull. this can lead to infinite recursion (is still a graph. maybe improve later) costFunction.getAppliedIfServiceInstanceUses().addAll(getAppliedInConjunctionWithEntities(node.getId(), database)); //need to also retrieve Resurce and Quality costFunction.getCostElements().addAll(CostElementDAO.getCostElementPropertiesForNode(node.getId(), database)); if (costFunction != null) { //hack. if the costFunction has allready been added (equals is done on the DB Node), //this means ServiceUnit has elasticity capability on it, and the old is also removed if (costFunctions.contains(costFunction)) { costFunctions.remove(costFunction); } else { costFunctions.add(costFunction); } } } if (!transactionAllreadyRunning) { tx.success(); } } catch (Exception e) { log.error(e.getMessage(), e); e.printStackTrace(); } finally { if (!transactionAllreadyRunning) { tx.finish(); } } return costFunctions; }
/** * Counts how many elasticity characteristic nodes point to it with a * "elasticityCapabilityFor" relationship * * @param id * @param database * @return sum of incoming MANDATORY_ASSOCIATION and OPTIONAL_ASSOCIATION * elasticity capabilities if returns -1, means error encountered. otherwise * the result is always >= 0 */ public static int getElasticityDependency(long id, EmbeddedGraphDatabase database) { CloudOfferedService elTarget = null; int incomingPaths = 0; boolean transactionAllreadyRunning = false; try { transactionAllreadyRunning = (database.getTxManager().getStatus() == Status.STATUS_ACTIVE); } catch (SystemException ex) { log.error(ex.getMessage(), ex); } Transaction tx = (transactionAllreadyRunning) ? null : database.beginTx(); try { Node parentNode = database.getNodeById(id); if (parentNode == null) { log.error("Node with id " + id + " was not found"); return 0; } TraversalDescription description = Traversal.traversal() .evaluator(Evaluators.excludeStartPosition()) .relationships(ServiceUnitRelationship.hasElasticityCapability, Direction.OUTGOING) .uniqueness(Uniqueness.NODE_PATH); Traverser traverser = description.traverse(parentNode); //for each incoming path, if is MANDATORY_ASSOCIATION decrease the in for (Path path : traverser) { incomingPaths++; } if (!transactionAllreadyRunning) { if (!transactionAllreadyRunning) { tx.success(); } } } catch (Exception e) { log.error(e.getMessage(), e); e.printStackTrace(); } finally { if (!transactionAllreadyRunning) { tx.finish(); } } return incomingPaths; }
public static CloudOfferedService getByID(Long nodeID, EmbeddedGraphDatabase database) { CloudOfferedService serviceUnit = null; boolean transactionAllreadyRunning = false; try { transactionAllreadyRunning = (database.getTxManager().getStatus() == Status.STATUS_ACTIVE); } catch (SystemException ex) { log.error(ex.getMessage(), ex); } Transaction tx = (transactionAllreadyRunning) ? null : database.beginTx(); try { Node parentNode = database.getNodeById(nodeID); if (parentNode == null) { return serviceUnit; } TraversalDescription description = Traversal.traversal() .evaluator(Evaluators.excludeStartPosition()) .relationships(ServiceUnitRelationship.elasticityCapabilityFor, Direction.OUTGOING) .uniqueness(Uniqueness.NODE_PATH); Traverser traverser = description.traverse(parentNode); for (Path path : traverser) { Node node = path.endNode(); if (!node.hasLabel(LABEL)) { continue; } serviceUnit = new CloudOfferedService(); serviceUnit.setId(node.getId()); if (node.hasProperty(KEY)) { serviceUnit.setName(node.getProperty(KEY).toString()); } else { log.warn("Retrieved serviceUnit " + nodeID + " has no " + KEY); } if (node.hasProperty(CATEGORY)) { serviceUnit.setCategory(node.getProperty(CATEGORY).toString()); } else { log.warn("Retrieved serviceUnit " + nodeID + " has no " + CATEGORY); } if (node.hasProperty(SUBCATEGORY)) { serviceUnit.setSubcategory(node.getProperty(SUBCATEGORY).toString()); } else { log.warn("Retrieved serviceUnit " + nodeID + " has no " + SUBCATEGORY); } if (node.hasProperty(UUID)) { serviceUnit.setUuid(java.util.UUID.fromString(node.getProperty(UUID).toString())); } else { log.warn("Retrieved CloudProvider " + serviceUnit + " has no " + UUID); } serviceUnit.getResourceProperties().addAll(ResourceDAO.getResourcePropertiesForNode(node.getId(), database)); serviceUnit.getQualityProperties().addAll(QualityDAO.getQualityPropertiesForNode(node.getId(), database)); serviceUnit.getCostFunctions().addAll(CostFunctionDAO.getCostFunctionsForNode(node.getId(), database)); serviceUnit.getElasticityCapabilities().addAll(ElasticityCapabilityDAO.getELasticityCapabilitiesForNode(node.getId(), database)); //serviceUnit.setElasticityQuantification(getElasticityDependency(node.getId(), database)); } if (!transactionAllreadyRunning) { if (!transactionAllreadyRunning) { tx.success(); } } } catch (Exception e) { log.error(e.getMessage(), e); e.printStackTrace(); } finally { if (!transactionAllreadyRunning) { tx.finish(); } } return serviceUnit; }