Example #1
0
  @Test
  public void testTripleRelationshipGraph() {
    /* Layout
     *          ___
     * (a)---(b)===(c)---(d)
     */
    graph.makeEdge("a", "b");
    graph.makeEdge("b", "c");
    graph.makeEdge("b", "c");
    graph.makeEdge("b", "c");
    graph.makeEdge("c", "d");

    PathFinder<Path> finder = instantiatePathFinder(10);
    Iterable<Path> paths = finder.findAllPaths(graph.getNode("a"), graph.getNode("d"));
    assertPaths(
        paths,
        "a,b,c,d",
        "a,b,c,d",
        "a,b,c,d",
        "a,b,c,b,c,d",
        "a,b,c,b,c,d",
        "a,b,c,b,c,d",
        "a,b,c,b,c,d",
        "a,b,c,b,c,d",
        "a,b,c,b,c,d");
  }
 @Test
 public void testSingle() {
   PathFinder<Path> finder = newFinder();
   Path path = finder.findSinglePath(graph.getNode("SOURCE"), graph.getNode("TARGET"));
   assertNotNull(path);
   assertPathDef(path, "SOURCE", "z", "9", "0", "TARGET");
 }
Example #3
0
  @Test
  public void testCircularGraph() {
    /* Layout
     *
     * (a)---(b)===(c)---(e)
     *         \   /
     *          (d)
     */
    graph.makeEdge("a", "b");
    graph.makeEdge("b", "c");
    graph.makeEdge("b", "c");
    graph.makeEdge("b", "d");
    graph.makeEdge("c", "d");
    graph.makeEdge("c", "e");

    PathFinder<Path> finder = instantiatePathFinder(10);
    Iterable<Path> paths = finder.findAllPaths(graph.getNode("a"), graph.getNode("e"));
    assertPaths(
        paths,
        "a,b,c,e",
        "a,b,c,e",
        "a,b,d,c,e",
        "a,b,c,d,b,c,e",
        "a,b,c,d,b,c,e",
        "a,b,c,b,d,c,e",
        "a,b,c,b,d,c,e",
        "a,b,d,c,b,c,e",
        "a,b,d,c,b,c,e");
  }
Example #4
0
  @SuppressWarnings("rawtypes")
  public PathRepresentation findSinglePath(long startId, long endId, Map<String, Object> map) {
    FindParams findParams = new FindParams(startId, endId, map).invoke();
    PathFinder finder = findParams.getFinder();
    Node startNode = findParams.getStartNode();
    Node endNode = findParams.getEndNode();

    Path path = finder.findSinglePath(startNode, endNode);
    if (path == null) {
      throw new NotFoundException();
    }
    return findParams.pathRepresentationOf(path);
  }
Example #5
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  public ListRepresentation findPaths(long startId, long endId, Map<String, Object> map) {
    final FindParams findParams = new FindParams(startId, endId, map).invoke();
    PathFinder finder = findParams.getFinder();
    Node startNode = findParams.getStartNode();
    Node endNode = findParams.getEndNode();

    Iterable paths = finder.findAllPaths(startNode, endNode);

    IterableWrapper<PathRepresentation, Path> pathRepresentations =
        new IterableWrapper<PathRepresentation, Path>(paths) {
          @Override
          protected PathRepresentation underlyingObjectToObject(Path path) {
            return findParams.pathRepresentationOf(path);
          }
        };

    return new ListRepresentation(RepresentationType.PATH, pathRepresentations);
  }
 private static Iterator<Node> findPath(Node s, Node e) {
   Iterator<Node> it;
   try (Transaction tx = graphDb.beginTx()) {
     PathFinder<Path> finder =
         GraphAlgoFactory.shortestPath(
             PathExpanders.forTypeAndDirection(RelTypes.STD, Direction.OUTGOING), 15);
     Iterable<Path> paths = finder.findAllPaths(s, e);
     Path path = paths.iterator().next();
     it = path.nodes().iterator();
     if (it.hasNext()) {
       System.out.println(it.next().getProperty("name"));
     }
     if (it.hasNext()) {
       System.out.println(it.next().getProperty("name"));
     }
     if (it.hasNext()) {
       System.out.println(it.next().getProperty("name"));
     }
     tx.success();
   }
   return it;
 }
  public Double shortestPath() {

    s1nodes = Neo4jGraphUtils.getSourceNodes(graph, s1);
    s2nodes = Neo4jGraphUtils.getSourceNodes(graph, s2);

    log.info(
        "Compute pairwise cheapest path: S{} ({} nodes), S{} ({} nodes)",
        s1.getSnippetId(),
        s1nodes.size(),
        s2.getSnippetId(),
        s2nodes.size());

    int pathLenghtSum = 0;
    int pathCount = 0;
    int commonNodeCount = 0;

    int cacheCounter = 0;

    for (Vertex v1 : s1nodes) {
      for (Vertex v2 : s2nodes) {

        Long v1id = (Long) (v1.getId());
        Long v2id = (Long) (v2.getId());

        if (v1id.compareTo(v2id) == 0) {
          commonNodeCount++;
          // pathCount++;
          // pathLenghtSum += 0
          continue;
        }

        log.debug("Processing Node {} and Node {}", v1id, v2id);

        Node n1 = graph.getRawGraph().getNodeById(v1id);
        Node n2 = graph.getRawGraph().getNodeById(v2id);

        // Get shortest path

        Integer pathLen = null; // p.length();

        Tuple<Integer, Double> path = pathCache.getPath(v1id, v2id, log.isDebugEnabled());

        if (path != null) {

          pathLen = path.k;

          cacheCounter++;

          log.debug(
              "Path between Node{} and Node{} found, Length {}, Weight {} (from mysql cache)",
              v1id,
              v2id,
              pathLen);
        } else {

          log.debug("Start ShortestPath Node {} and Node {}", v1id, v2id);

          PathFinder<Path> shortestPathAlgo =
              GraphAlgoFactory.shortestPath(
                  (PathExpander<?>) Traversal.expanderForAllTypes(), maxPathLen.intValue());

          Path shortestPath = shortestPathAlgo.findSinglePath(n1, n2);
          StringBuffer shorestPathSteps = null;

          if (shortestPath != null) {

            pathLen = shortestPath.length();

            // Constructing path for debug logging
            if (log.isDebugEnabled()) {

              Iterator<PropertyContainer> iter = shortestPath.iterator();
              shorestPathSteps = new StringBuffer();

              while (iter.hasNext()) {
                Object e = iter.next();
                if (e instanceof NodeProxy) {
                  Node n = (Node) e;
                  shorestPathSteps.append("(" + n.getProperty("label") + ")");
                } else if (e instanceof RelationshipProxy) {
                  Relationship r = (Relationship) e;
                  shorestPathSteps.append("-[" + r.getType() + "]-");
                } else {
                  log.error("ERROR");
                }
              }

              log.debug(
                  "Path between Node{} and Node{} found, Length {}, Path {}",
                  v1id,
                  v2id,
                  pathLen,
                  shorestPathSteps);
            }
          } else {
            log.debug("Path between Node{} and Node{} not found.", v1id, v2id);
          }

          // Update mysql db cache
          if (log.isDebugEnabled()) {
            pathCache.setPath(v1id, v2id, pathLen, null, shorestPathSteps);
          } else {
            pathCache.setPath(v1id, v2id, pathLen, null);
          }
        }

        // Getting shortest path data
        if (pathLen != null) {

          if (pathLen <= maxPathLen) {
            pathLenghtSum += pathLen;

            pathCount++;
          }
        }
      }
    }

    log.info(
        "Similarity measures S{}, S{}: CommonNodes {}, PathCnt {}, MaxTheoPathCnt {}, SumPathLen {}, CacheCnt {}",
        s1.getSnippetId(),
        s2.getSnippetId(),
        commonNodeCount,
        pathCount,
        s1nodes.size() * s2nodes.size(),
        pathLenghtSum,
        cacheCounter);

    // log.info("Total path score S{}, S{}: {}", s1.getSnippetId(), s2.getSnippetId(), sim);
    return Double.valueOf(pathLenghtSum);
  }
  @Override
  public Map<String, Set<Long>> extract(
      List<DocGraph> docGraphs,
      DocGraphFilterFunction filterFunc,
      Set<String> resourceClasses,
      Set<String> documentClasses) {
    // pattern-document graph associations R_D
    Map<String, Set<Long>> associations = new HashMap<String, Set<Long>>();

    // init path finder
    initFinder();

    // G_D(filtered) <- G_D.where({G_d|filter(G_D)})
    Set<DocGraph> filteredDocGraphs = new HashSet<DocGraph>();
    if (filterFunc == null) {
      filteredDocGraphs.addAll(docGraphs);
    } else {
      for (DocGraph docGraph : docGraphs) {
        if (filterFunc.filter(docGraph)) {
          filteredDocGraphs.add(docGraph);
        }
      }
    }

    Set<Node> relevantResources = null;
    Set<Node> relevantDocuments = null;
    String r = null;
    Node v_p = null;
    boolean validPath = true;
    int pCnt = 0;
    log.info(String.format("Starting analysis of %d document graphs", filteredDocGraphs.size()));
    for (DocGraph docGraph : filteredDocGraphs) {
      log.info(
          String.format(
              "Analyzing DocGraph[%d] (%d, %d)",
              docGraph.getId(), docGraph.getNodeCount(), docGraph.getEdgeCount()));
      pCnt = 0;
      // V_R <- G_d.V.where({v|tau(mu(v)) in C_R})
      relevantResources = filterNodesByClass(docGraph.getNodes(), resourceClasses);
      // V_R <- G_d.V.where({v|tau(mu(v)) in C_D})
      relevantDocuments = filterNodesByClass(docGraph.getNodes(), documentClasses);

      preProcessGraph(docGraph, resourceClasses);
      try (Transaction tx = graphDB.beginTx()) {
        for (Node v_r : relevantResources) {
          for (Node v_d : relevantDocuments) {
            // P <- G_d.paths(v_R,v_D)
            for (Path p : finder.findAllPaths(v_r, v_d)) {
              validPath = true;
              r = String.format("%s", v_r.getProperty(Constants.ID_KEY));
              v_p = v_r;
              for (Relationship e : p.relationships()) {
                if (e.getStartNode().getId() == v_p.getId()) {
                  if (getNodeSuperClass(e.getEndNode())
                      .equals(Constants.NODE_SUPER_CLASS_RESOURCE_VALUE)) {
                    validPath = false;
                    break;
                  }
                  r =
                      String.format(
                          "%s-%s->%s", r, e.getType().name(), getNodeClass(e.getEndNode()));
                  v_p = e.getEndNode();
                } else {
                  if (getNodeSuperClass(e.getStartNode())
                      .equals(Constants.NODE_SUPER_CLASS_RESOURCE_VALUE)) {
                    validPath = false;
                    break;
                  }
                  r =
                      String.format(
                          "%s<-%s-%s", r, e.getType().name(), getNodeClass(e.getStartNode()));
                  v_p = e.getStartNode();
                }
              }
              // R_D.add(<r, G_d>)
              if (validPath) {
                associations = addPatternDocGraphAssociation(associations, r, docGraph);
                pCnt++;
              }
            }
          }
        }
        tx.success();
      }
      log.info(String.format("%d patterns in DocGraph[%d]", pCnt, docGraph.getId()));
    }
    return associations;
  }