private static List<String> shortestCycle(DirectedGraph<String, DefaultEdge> graph) {
   FloydWarshallShortestPaths<String, DefaultEdge> floyd = new FloydWarshallShortestPaths<>(graph);
   int minDistance = Integer.MAX_VALUE;
   String minSource = null;
   String minDestination = null;
   for (DefaultEdge edge : graph.edgeSet()) {
     String src = graph.getEdgeSource(edge);
     String dst = graph.getEdgeTarget(edge);
     int dist = (int) Math.round(floyd.shortestDistance(dst, src)); // from dst to src
     if (dist < 0) {
       continue;
     }
     if (dist < minDistance) {
       minDistance = dist;
       minSource = src;
       minDestination = dst;
     }
   }
   if (minSource == null) {
     return null;
   }
   GraphPath<String, DefaultEdge> shortestPath = floyd.getShortestPath(minDestination, minSource);
   List<String> pathVertexList = Graphs.getPathVertexList(shortestPath);
   // note: pathVertexList will be [a, a] instead of [a] when the shortest path is a loop edge
   if (!Objects.equals(shortestPath.getStartVertex(), shortestPath.getEndVertex())) {
     pathVertexList.add(pathVertexList.get(0));
   }
   return pathVertexList;
 }
Example #2
0
 public void testEmptyPath() {
   List<GraphPath<Integer, DefaultEdge>> paths = new ArrayList<>();
   paths.add(new GraphWalk<>(completeGraph, null, null, Collections.emptyList(), 0));
   paths.add(new GraphWalk<>(completeGraph, Collections.emptyList(), 0));
   for (GraphPath<Integer, DefaultEdge> path : paths) {
     assertEquals(0, path.getLength());
     assertEquals(Collections.emptyList(), path.getVertexList());
     assertEquals(Collections.emptyList(), path.getEdgeList());
   }
 }
  public static void main(String[] args) {

    TAP tap = TAP.BRAESS(TADriver.class);

    List<String> odpairs = new ArrayList<>(tap.getOdpairs().keySet());
    Collections.sort(odpairs);
    String header = "average_tt";
    String results = "";

    // calculate all-shortest-path
    FloydWarshallShortestPaths fws = new FloydWarshallShortestPaths(tap.getGraph());

    // update the edges cost
    for (String odPair : odpairs) {
      String origin = odPair.split("-")[0];
      String destination = odPair.split("-")[1];

      GraphPath path = fws.getShortestPath(origin, destination);

      for (Object e : path.getEdgeList()) {
        StandardEdge edge = (StandardEdge) e;
        edge.incrementTotalFlow(tap.getOdpairs().get(odPair).demandSize());
      }
    }

    // evaluate cost per OD pair
    for (String odPair : odpairs) {
      header += Params.COLUMN_SEPARATOR + odPair;

      String origin = odPair.split("-")[0];
      String destination = odPair.split("-")[1];

      results += Params.COLUMN_SEPARATOR + fws.getShortestPath(origin, destination).getWeight();
    }

    // print Result
    List<AbstractEdge> edges = new ArrayList<>(tap.getGraph().edgeSet());
    Collections.sort(edges);
    double cost = 0.0;

    for (AbstractEdge e : edges) {
      header += Params.COLUMN_SEPARATOR + e.getName();
      results += Params.COLUMN_SEPARATOR + e.getTotalFlow();
      cost += (e.getCost() * e.getTotalFlow()) / tap.getDrivers().size();
    }
    System.out.println(header);
    System.out.println(cost + results);
  }
  @Override
  public ElementGraph next() {
    if (!pathsIterator.hasNext()) {
      current = null;
      pathsIterator = null;

      advance();

      return next();
    }

    GraphPath<FlowElement, Scope> path = pathsIterator.next();
    List<FlowElement> vertexList = getPathVertexList(path);
    List<Scope> edgeList = path.getEdgeList();

    return new ElementSubGraph(current, vertexList, edgeList);
  }
 /**
  * @param path
  * @param vertex
  * @return
  */
 private boolean containsVertex(GraphPath<IModelEntity, Relationship> path, IModelEntity vertex) {
   List<Relationship> edges = path.getEdgeList();
   for (int i = 0; i < edges.size(); i++) {
     Relationship r = (Relationship) edges.get(i);
     if (r.getSourceEntity().equals(vertex) || r.getTargetEntity().equals(vertex)) {
       return true;
     }
   }
   return false;
 }
 /**
  * Checks if the path is already contained in the map
  *
  * @param map
  * @param path
  * @return
  */
 private static boolean containsPath(
     Set<GraphPath<IModelEntity, Relationship>> map, GraphPath<IModelEntity, Relationship> path) {
   logger.debug("IN");
   Iterator<GraphPath<IModelEntity, Relationship>> iter = map.iterator();
   while (iter.hasNext()) {
     GraphPath<IModelEntity, Relationship> graphPath = iter.next();
     if (GraphUtilities.arePathsEquals(graphPath, path)) {
       logger.debug("Adding the path in the map" + path.toString());
       return true;
     }
   }
   logger.debug("OUT");
   return false;
 }
Example #7
0
  public void testNonSimplePath() {
    List<Integer> vertexList = Arrays.asList(0, 1, 2, 3, 2, 3, 4);
    List<DefaultEdge> edgeList = new ArrayList<>();
    for (int i = 0; i < vertexList.size() - 1; i++)
      edgeList.add(completeGraph.getEdge(vertexList.get(i), vertexList.get(i + 1)));
    GraphPath<Integer, DefaultEdge> p1 = new GraphWalk<>(completeGraph, 0, 4, edgeList, 10);
    assertEquals(0, p1.getStartVertex().intValue());
    assertEquals(4, p1.getEndVertex().intValue());
    assertEquals(vertexList, p1.getVertexList());
    assertEquals(edgeList.size(), p1.getLength());
    assertEquals(10.0, p1.getWeight());

    GraphPath<Integer, DefaultEdge> p2 = new GraphWalk<>(completeGraph, vertexList, 10);
    assertEquals(0, p2.getStartVertex().intValue());
    assertEquals(4, p2.getEndVertex().intValue());
    assertEquals(edgeList, p2.getEdgeList());
    assertEquals(edgeList.size(), p2.getLength());
    assertEquals(10.0, p2.getWeight());
  }
Example #8
0
  /**
   * Creates the map reduce step graph.
   *
   * @param flowName
   * @param elementGraph
   * @param traps
   */
  private void makeStepGraph(String flowName, ElementGraph elementGraph, Map<String, Tap> traps) {
    SimpleDirectedGraph<Tap, Integer> tapGraph = elementGraph.makeTapGraph();

    int numJobs = countNumJobs(tapGraph);

    Map<String, FlowStep> steps = new LinkedHashMap<String, FlowStep>();
    TopologicalOrderIterator<Tap, Integer> topoIterator =
        new TopologicalOrderIterator<Tap, Integer>(tapGraph);
    int count = 0;

    while (topoIterator.hasNext()) {
      Tap source = topoIterator.next();

      if (LOG.isDebugEnabled()) LOG.debug("handling source: " + source);

      List<Tap> sinks = Graphs.successorListOf(tapGraph, source);

      for (Tap sink : sinks) {
        if (LOG.isDebugEnabled()) LOG.debug("handling path: " + source + " -> " + sink);

        FlowStep step = getCreateFlowStep(flowName, steps, sink.toString(), numJobs);

        addVertex(step);

        if (steps.containsKey(source.toString()))
          addEdge(steps.get(source.toString()), step, count++);

        // support multiple paths from source to sink
        // this allows for self joins on groups, even with different operation stacks between them
        // note we must ignore paths with intermediate taps
        List<GraphPath<FlowElement, Scope>> paths =
            elementGraph.getAllShortestPathsBetween(source, sink);

        for (GraphPath<FlowElement, Scope> path : paths) {
          if (pathContainsTap(path)) continue;

          List<Scope> scopes = path.getEdgeList();
          String sourceName = scopes.get(0).getName(); // root node of the shortest path

          step.sources.put((Tap) source, sourceName);
          step.sink = sink;

          if (step.sink.isWriteDirect())
            step.tempSink = new TempHfs(sink.getPath().toUri().getPath());

          FlowElement lhs = source;

          step.graph.addVertex(lhs);

          boolean onMapSide = true;

          for (Scope scope : scopes) {
            FlowElement rhs = elementGraph.getEdgeTarget(scope);

            step.graph.addVertex(rhs);
            step.graph.addEdge(lhs, rhs, scope);

            if (rhs instanceof Group) {
              step.group = (Group) rhs;
              onMapSide = false;
            } else if (rhs instanceof Pipe) // add relevant traps to step
            {
              String name = ((Pipe) rhs).getName();

              if (traps.containsKey(name)) {
                if (onMapSide) step.mapperTraps.put(name, traps.get(name));
                else step.reducerTraps.put(name, traps.get(name));
              }
            }

            lhs = rhs;
          }
        }
      }
    }
  }
Example #9
0
    @Override
    public List<LogicalWaypoint> getLogicalWaypoints() {

      EnvironmentKnowledgeModule knowledge = agent.getEnvironmentKnowledge();
      // convert the exit path into a list of logical waypoints
      List<LogicalWaypoint> waypoints = new ArrayList<LogicalWaypoint>();

      if (singletonPath) {
        //                System.out.println("getLink =" + onlyLink.getId());
        //                System.out.println("agent area =" + agent.getCurrentAreaId());
        //                System.out.println("goal area =" + goalAreaId);

        IbevacLogicalWaypoint linkWaypoint =
            new IbevacLogicalWaypoint(
                onlyLink,
                knowledge.resolveAreaById(agent.getCurrentAreaId()),
                knowledge.resolveAreaById(goalAreaId),
                space,
                agent);
        waypoints.add(linkWaypoint);
        if (goalAreaId != -1) {
          IbevacLogicalWaypoint areaWaypoint =
              (new IbevacLogicalWaypoint(
                      null, knowledge.resolveAreaById(goalAreaId), null, space, agent))
                  .setInitialWayPoint(linkWaypoint.getWP1());
          waypoints.add(areaWaypoint);
        }
        return waypoints;
      }
      if (path == null) {
        return null;
      }

      List<RoomEdge> edges = path.getEdgeList();

      //            System.out.println(edges);
      CLink startLink = knowledge.resolveLinkById(path.getStartVertex());
      SpatialWaypoint lastPoint = new SpatialWaypoint(agent.getPosition());

      // If the agent is currently not at a getLink then create a waypoint for the getLink
      if (agent.getCurrentAreaId() != startLink.getId()) {

        Integer otherAreaId =
            (agent.getCurrentAreaId() == startLink.getConnectingAreas().get(0))
                ? startLink.getConnectingAreas().get(1)
                : startLink.getConnectingAreas().get(0);
        IbevacLogicalWaypoint lwp =
            new IbevacLogicalWaypoint(
                startLink,
                knowledge.resolveAreaById(agent.getCurrentAreaId()),
                knowledge.resolveAreaById(otherAreaId),
                space,
                agent);
        waypoints.add(lwp);
        lastPoint = lwp.getWP1();
      }

      CLink prevLink = startLink;

      for (RoomEdge edge : edges) {
        // get both areas that are connected by the edge (there is at least one)
        //                CArea area0 = knowledge.resolveAreaById(edge.id0());
        //                CArea area1 = knowledge.resolveAreaById(edge.id1());
        //                System.out.println(edge);
        CArea room = knowledge.resolveAreaById(edge.areaId());
        if (room instanceof CStaircase) {
          // must be a staircase. we just break here.
          // after teleporting a new path has to be calculated
          //                    assert (area0 instanceof CStaircase && area1 instanceof CStaircase);

          // create a logical waypoint, using the links and the areas
          assert edge.getRoom0() != null && edge.getRoom1() != null;
          IbevacLogicalWaypoint wp =
              new IbevacLogicalWaypoint(null, edge.getRoom0(), edge.getRoom1(), space, agent);
          waypoints.add(wp);

          break;
        }

        CLink fromLink = knowledge.resolveLinkById(edge.id0());
        CLink toLink = knowledge.resolveLinkById(edge.id1());
        //                System.out.println("prev" + prevLink.getId());
        //                System.out.println(fromLink.getId());
        //                System.out.println(toLink.getId());

        assert (prevLink.getId() == fromLink.getId() || prevLink.getId() == toLink.getId());

        // by definition, we want area0 to be the next one and area1 the one thereafter
        // if it's not the case swap...
        if (prevLink.getId() != fromLink.getId()) {
          CLink temp = fromLink;
          fromLink = toLink;
          toLink = temp;
        } // get the getLink that is associated with this edge (if any)
        prevLink = toLink;
        //                assert agent.getCurrentAreaId() == fromLink.getConnectingAreas().get(0) ||
        // agent.getCurrentAreaId() == fromLink.getConnectingAreas().get(1);

        // create a logical waypoint, using the links and the areas
        IbevacLogicalWaypoint areaWaypoint =
            (new IbevacLogicalWaypoint(null, edge.area(), null, space, agent))
                .setInitialWayPoint(lastPoint);
        waypoints.add(areaWaypoint);
        assert toLink.getConnectingAreas() != null;
        if (toLink.getConnectingAreas().size() > 1) {
          Integer otherAreaId =
              (edge.areaId() == toLink.getConnectingAreas().get(0))
                  ? toLink.getConnectingAreas().get(1)
                  : toLink.getConnectingAreas().get(0);
          IbevacLogicalWaypoint lwp =
              new IbevacLogicalWaypoint(
                  toLink, edge.area(), knowledge.resolveAreaById(otherAreaId), space, agent);
          waypoints.add(lwp);
          lastPoint = lwp.getWP1();
        } else {
          IbevacLogicalWaypoint lwp =
              new IbevacLogicalWaypoint(toLink, edge.area(), null, space, agent);
          waypoints.add(lwp);
          lastPoint = lwp.getWP1();
        }
      }
      if (goalAreaId != -1) {
        waypoints.add(
            new IbevacLogicalWaypoint(
                    null, knowledge.resolveAreaById(this.goalAreaId), null, space, agent)
                .setInitialWayPoint(lastPoint));
      }

      return waypoints;
    }
Example #10
0
  private EscapePath determineEscapePath(Collection<Integer> goalAreaIds) {
    // get the knowledge object and the current area id, we'll need it further down
    CompleteKnowledgeInverted knowledge =
        (CompleteKnowledgeInverted) agent.getEnvironmentKnowledge();
    int currentAreaId = agent.getCurrentAreaId();
    //        System.out.println("deterimining an exit path");
    //        int firstLink = currentAreaId;
    GraphPath<Integer, RoomEdge> finalPath = null;
    double minWeight = Double.MAX_VALUE;
    //        GraphPath<Integer, RoomEdge> tempPath;
    //        int tempRoom;
    int goalArea = -1;

    for (Integer goalAreaId : goalAreaIds) {
      // is current area a room?
      //            System.out.println("here" + goalAreaId + "from" + currentAreaId);
      if (knowledge.resolveAreaById(currentAreaId) == null) {
        // currently on a getLink
        //
        //                System.out.println("getLink");
        KShortestPaths<Integer, RoomEdge> ksp =
            new KShortestPaths<Integer, RoomEdge>(knowledge.getGraph(), currentAreaId, 1);
        //                KShortestPaths<Integer, RoomEdge> ksp1 = new
        // KShortestPaths<>(knowledge.getGraph(), roomId1, 1);
        TreeMap<Double, GraphPath<Integer, RoomEdge>> paths =
            new TreeMap<Double, GraphPath<Integer, RoomEdge>>();
        for (CLink connectingLink : knowledge.getConnectingLinks(goalAreaId)) {
          for (GraphPath<Integer, RoomEdge> path : ksp.getPaths(connectingLink.getId())) {
            paths.put(path.getWeight(), path);
          }
        }
        //                List<GraphPath<Integer, RoomEdge>> paths1 = ksp1.getPaths(goalAreaId);

        // there should be at least one path to the exit from each room
        assert (paths != null && !paths.isEmpty());
        GraphPath<Integer, RoomEdge> route = paths.firstEntry().getValue();

        if (minWeight >= route.getWeight()) {
          finalPath = route;
          minWeight = route.getWeight();
          goalArea = goalAreaId;
        }

      } // if not, then it must be a area
      else {
        //                System.out.println("area");
        for (CLink homeLink : knowledge.getConnectingLinks(currentAreaId)) {
          // System.out.println(knowledge.getGraph().edgeSet());
          KShortestPaths<Integer, RoomEdge> ksp =
              new KShortestPaths<Integer, RoomEdge>(knowledge.getGraph(), homeLink.getId(), 1);
          //                    System.out.println("home getLink " + homeLink.getId());
          TreeMap<Double, GraphPath<Integer, RoomEdge>> paths =
              new TreeMap<Double, GraphPath<Integer, RoomEdge>>();
          for (CLink goalLink : knowledge.getConnectingLinks(goalAreaId)) {
            //                        System.out.println("goal getLink " + goalLink.getId());
            if (goalLink.getId() == homeLink.getId()) {
              return new EscapePathImpl(goalLink, goalAreaId);
            }
            if (ksp.getPaths(goalLink.getId()) == null) {
              //                            System.out.println("no path to exit");
              continue;
            }
            for (GraphPath<Integer, RoomEdge> path : ksp.getPaths(goalLink.getId())) {

              paths.put(path.getWeight(), path);
            }
          }
          //                List<GraphPath<Integer, RoomEdge>> paths1 = ksp1.getPaths(goalAreaId);

          // there should be at least one path to the exit from each room
          assert (paths != null && !paths.isEmpty());
          GraphPath<Integer, RoomEdge> route = paths.firstEntry().getValue();

          if (minWeight >= route.getWeight()) {
            finalPath = route;
            minWeight = route.getWeight();
            //                        firstLink = homeConnectingLink;
            goalArea = goalAreaId;
          }
        }

        // there is at least one path to the exit

      }
    }
    //        if (finalPath == null) {
    //            System.out.println(((IbevacAgent) this.agent).getId() + "," +
    // goalAreaIds.iterator().next());
    //        }
    //        assert (finalPath != null);
    //        //TODO : change this stupid hack;
    //        agent.setCurrentGoal(new IbevacLogicalWaypoint(null,
    // knowledge.resolveAreaById(goalArea), null, space, agent).getWP1().getPoint());
    return new EscapePathImpl(finalPath, goalArea);
  }