Пример #1
0
 public synchronized void initIndexes() {
   if (vertexIndex != null) {
     return;
   }
   graphService.setLoadLevel(LoadLevel.DEBUG);
   Graph graph = graphService.getGraph();
   vertexIndex = new STRtree();
   edgeIndex = new STRtree();
   for (Vertex v : graph.getVertices()) {
     Envelope vertexEnvelope = new Envelope(v.getCoordinate());
     vertexIndex.insert(vertexEnvelope, v);
     for (Edge e : v.getOutgoing()) {
       Envelope envelope;
       Geometry geometry = e.getGeometry();
       if (geometry == null) {
         envelope = vertexEnvelope;
       } else {
         envelope = geometry.getEnvelopeInternal();
       }
       edgeIndex.insert(envelope, e);
     }
   }
   vertexIndex.build();
   edgeIndex.build();
 }
Пример #2
0
  public static int getPreviousArriveTime(
      RoutingRequest request, int arrivalTime, Vertex stopVertex) {

    int bestArrivalTime = -1;

    request.arriveBy = true;

    // find the alights
    for (Edge prealight : stopVertex.getIncoming()) {
      if (prealight instanceof PreAlightEdge) {
        Vertex arrival = prealight.getFromVertex(); // this is the arrival vertex
        for (Edge alight : arrival.getIncoming()) {
          if (alight instanceof TransitBoardAlight) {
            State state = new State(alight.getToVertex(), arrivalTime, request);
            State result = alight.traverse(state);
            if (result == null) continue;
            int time = (int) result.getTime();
            if (time > bestArrivalTime) {
              bestArrivalTime = time;
            }
          }
        }
      }
    }

    request.arriveBy = false;
    return bestArrivalTime;
  }
Пример #3
0
  /**
   * Get edges inside a bbox.
   *
   * @return
   */
  @Secured({"ROLE_USER"})
  @GET
  @Path("/edges")
  @Produces({MediaType.APPLICATION_JSON})
  public Object getEdges(
      @QueryParam("lowerLeft") String lowerLeft,
      @QueryParam("upperRight") String upperRight,
      @QueryParam("exactClass") String className,
      @QueryParam("skipTransit") boolean skipTransit,
      @QueryParam("skipStreets") boolean skipStreets,
      @QueryParam("skipNoGeometry") boolean skipNoGeometry) {

    initIndexes();

    Envelope envelope = getEnvelope(lowerLeft, upperRight);

    EdgeSet out = new EdgeSet();
    Graph graph = graphService.getGraph();

    @SuppressWarnings("unchecked")
    List<Edge> query = edgeIndex.query(envelope);
    out.edges = new ArrayList<WrappedEdge>();
    for (Edge e : query) {
      if (skipStreets && (e instanceof StreetEdge)) continue;
      if (skipTransit && !(e instanceof StreetEdge)) continue;
      if (skipNoGeometry && e.getGeometry() == null) continue;
      if (className != null && !e.getClass().getName().endsWith("." + className)) continue;
      out.edges.add(new WrappedEdge(e, graph.getIdForEdge(e)));
    }
    return out.withGraph(graph);
  }
  private void fixupTransitLeg(Leg leg, State state, TransitIndexService transitIndex) {
    Edge en = state.getBackEdge();
    leg.route = en.getName();
    Trip trip = state.getBackTrip();
    leg.headsign = state.getBackDirection();
    if (trip != null) {
      // this is the stop headsign
      // leg.headsign = "This is the headsign";
      // handle no stop headsign
      if (leg.headsign == null) leg.headsign = trip.getTripHeadsign();

      leg.tripId = trip.getId().getId();
      leg.agencyId = trip.getId().getAgencyId();
      leg.tripShortName = trip.getTripShortName();
      leg.routeShortName = trip.getRoute().getShortName();
      leg.routeLongName = trip.getRoute().getLongName();
      leg.routeColor = trip.getRoute().getColor();
      leg.routeTextColor = trip.getRoute().getTextColor();
      leg.routeId = trip.getRoute().getId().getId();
      if (transitIndex != null) {
        Agency agency = transitIndex.getAgency(leg.agencyId);
        leg.agencyName = agency.getName();
        leg.agencyUrl = agency.getUrl();
      }
    }
    leg.mode = state.getBackMode().toString();
    leg.startTime = makeCalendar(state.getBackState());
  }
Пример #5
0
  public static int getNextDepartTime(
      RoutingRequest request, int departureTime, Vertex stopVertex) {

    int bestArrivalTime = Integer.MAX_VALUE;

    request.arriveBy = false;

    // find the boards
    for (Edge preboard : stopVertex.getOutgoing()) {
      if (preboard instanceof PreBoardEdge) {
        Vertex departure = preboard.getToVertex(); // this is the departure vertex
        for (Edge board : departure.getOutgoing()) {
          if (board instanceof TransitBoardAlight) {
            State state = new State(board.getFromVertex(), departureTime, request);
            State result = board.traverse(state);
            if (result == null) continue;
            int time = (int) result.getTime();
            if (time < bestArrivalTime) {
              bestArrivalTime = time;
            }
          }
        }
      }
    }

    request.arriveBy = true;
    return bestArrivalTime;
  }
  public void drawAnotation(GraphBuilderAnnotation anno) {
    Envelope env = new Envelope();

    Edge e = anno.getReferencedEdge();
    if (e != null) {
      this.enqueueHighlightedEdge(e);
      env.expandToInclude(e.getFromVertex().getCoordinate());
      env.expandToInclude(e.getToVertex().getCoordinate());
    }

    ArrayList<Vertex> vertices = new ArrayList<Vertex>();
    Vertex v = anno.getReferencedVertex();
    if (v != null) {
      env.expandToInclude(v.getCoordinate());
      vertices.add(v);
    }

    if (e == null && v == null) return;

    // make it a little bigger, especially needed for STOP_UNLINKED
    env.expandBy(0.02);

    // highlight relevant things
    this.clearHighlights();
    this.setHighlightedVertices(vertices);

    // zoom the graph display
    this.zoomToEnvelope(env);

    // and draw
    this.draw();
  }
 private int drawEdge(Edge e) {
   if (e.getGeometry() == null) return 0; // do not attempt to draw geometry-less edges
   Coordinate[] coords = e.getGeometry().getCoordinates();
   beginShape();
   for (int i = 0; i < coords.length; i++)
     vertex((float) toScreenX(coords[i].x), (float) toScreenY(coords[i].y));
   endShape();
   return coords.length; // should be used to count segments, not edges drawn
 }
Пример #8
0
 protected List<Edge> getOutgoingMatchableEdges(Vertex vertex) {
   List<Edge> edges = new ArrayList<Edge>();
   for (Edge e : vertex.getOutgoing()) {
     if (!(e instanceof StreetEdge)) continue;
     if (e.getGeometry() == null) continue;
     edges.add(e);
   }
   return edges;
 }
Пример #9
0
  public static DisjointSet<Vertex> getConnectedComponents(Graph graph) {
    DisjointSet<Vertex> components = new DisjointSet<Vertex>();

    for (Vertex v : graph.getVertices()) {
      for (Edge e : v.getOutgoing()) {
        components.union(e.getFromVertex(), e.getToVertex());
      }
    }
    return components;
  }
Пример #10
0
  private boolean testForUshape(
      Edge edge,
      long maxTime,
      long fromTime,
      long toTime,
      double angleLimit,
      double distanceTolerance,
      double userSpeed,
      boolean hasCar,
      boolean performSpeedTest) {

    LineString ls = (LineString) edge.getGeometry();
    if (ls.getNumPoints() <= 3) { // first filter since u-shapes need at least 4 pts
      // this is the normal case
      return false;
    } else {
      // try to identify u-shapes by checking if the angle EndPoint-StartPoint-StartPoint+1
      // is about 90 degrees (using Azimuths on the sphere)
      double diffTo90Azimuths = 360;
      if (edge instanceof PlainStreetEdge) {
        double firstSegmentAngle = DirectionUtils.getFirstAngle(edge.getGeometry());
        if (firstSegmentAngle < 0) firstSegmentAngle = firstSegmentAngle + Math.PI;
        double firstToLastSegmentAngle = getFirstToLastSegmentAngle(edge.getGeometry());
        if (firstToLastSegmentAngle < 0)
          firstToLastSegmentAngle = firstToLastSegmentAngle + Math.PI;
        double diffAzimuths = Math.abs(firstToLastSegmentAngle - firstSegmentAngle);
        diffTo90Azimuths = Math.abs(diffAzimuths - (Math.PI / 2.0));
      } else {
        // this will happen in particular for transit routes
        // LOG.debug("Edge is not a PlainStreetEdge");
      }
      if (diffTo90Azimuths < angleLimit) {
        // no need to test further if we know its a u-shape
        // System.out.println("u-shape found, (spherical) angle: " + diffTo90Azimuths* 180/Math.PI);
        return true;
      } else {
        if (performSpeedTest) {
          // Use also a distance based criteria since the angle criteria may fail.
          // However a distance based one may fail as well for steep terrain.
          long dt = Math.abs(toTime - fromTime);
          double lineDist = edge.getDistance();
          double distanceToWalkInTimeMissing =
              distanceToMoveInRemainingTime(maxTime, fromTime, dt, userSpeed, edge, hasCar, false);
          double approxWalkableDistanceInTime = distanceToWalkInTimeMissing * distanceTolerance;
          if ((approxWalkableDistanceInTime < lineDist)) {
            return true;
          }
        }
        return false;
      }
    }
  }
Пример #11
0
 public StateEditor(State parent, Edge e) {
   child = parent.clone();
   child.backState = parent;
   child.backEdge = e;
   // We clear child.next here, since it could have already been set in the
   // parent
   child.next = null;
   if (e == null) {
     child.backState = null;
     child.hops = 0;
     child.vertex = parent.vertex;
     child.stateData = child.stateData.clone();
   } else {
     child.hops = parent.hops + 1;
     // be clever
     // Note that we use equals(), not ==, here to allow for dynamically
     // created vertices
     if (e.getFromVertex().equals(e.getToVertex()) && parent.vertex.equals(e.getFromVertex())) {
       // TODO LG: We disable this test: the assumption that
       // the from and to vertex of an edge are not the same
       // is not true anymore: bike rental on/off edges.
       traversingBackward = parent.getOptions().isArriveBy();
       child.vertex = e.getToVertex();
     } else if (parent.vertex.equals(e.getFromVertex())) {
       traversingBackward = false;
       child.vertex = e.getToVertex();
     } else if (parent.vertex.equals(e.getToVertex())) {
       traversingBackward = true;
       child.vertex = e.getFromVertex();
     } else {
       // Parent state is not at either end of edge.
       LOG.warn("Edge is not connected to parent state: {}", e);
       LOG.warn("   from   vertex: {}", e.getFromVertex());
       LOG.warn("   to     vertex: {}", e.getToVertex());
       LOG.warn("   parent vertex: {}", parent.vertex);
       defectiveTraversal = true;
     }
     if (traversingBackward != parent.getOptions().isArriveBy()) {
       LOG.error(
           "Actual traversal direction does not match traversal direction in TraverseOptions.");
       defectiveTraversal = true;
     }
     if (parent.stateData.noThruTrafficState == NoThruTrafficState.INIT
         && !(e instanceof FreeEdge)) {
       setNoThruTrafficState(NoThruTrafficState.BETWEEN_ISLANDS);
     }
   }
 }
Пример #12
0
 private WalkStep createWalkStep(State s) {
   Edge en = s.getBackEdge();
   WalkStep step;
   step = new WalkStep();
   step.streetName = en.getName();
   step.lon = en.getFromVertex().getX();
   step.lat = en.getFromVertex().getY();
   step.elevation = encodeElevationProfile(s.getBackEdge(), 0);
   step.bogusName = en.hasBogusName();
   step.addAlerts(s.getBackAlerts());
   step.angle = DirectionUtils.getFirstAngle(s.getBackEdge().getGeometry());
   if (s.getBackEdge() instanceof AreaEdge) {
     step.area = true;
   }
   return step;
 }
Пример #13
0
  /**
   * Get vertices connected to an edge
   *
   * @return
   */
  @Secured({"ROLE_USER"})
  @GET
  @Path("/verticesForEdge")
  @Produces({MediaType.APPLICATION_JSON})
  public Object getVerticesForEdge(@QueryParam("edge") int edgeId) {

    Graph graph = graphService.getGraph();
    Edge edge = graph.getEdgeById(edgeId);

    VertexSet out = new VertexSet();
    out.vertices = new ArrayList<Vertex>(2);
    out.vertices.add(edge.getFromVertex());
    out.vertices.add(edge.getToVertex());

    return out.withGraph(graph);
  }
Пример #14
0
  private void treatAndAddUshapeWithinTimeLimits(
      long maxTime,
      double userSpeed,
      ArrayList<LineString> walkShedEdges,
      Edge edge,
      long fromTime,
      long toTime,
      LineString ls,
      boolean hasCar) {

    // check if the u-shape can be traveled within the remaining time
    long dt = Math.abs(toTime - fromTime);
    double distanceToMoveInTimeMissing =
        distanceToMoveInRemainingTime(maxTime, fromTime, dt, userSpeed, edge, hasCar, true);
    double lineDist = edge.getDistance();
    double fraction = (double) distanceToMoveInTimeMissing / (double) lineDist;
    // get the sub-edge geom
    LineString subLine = null;
    if (fraction < 1.0) {
      // the u-shape is not fully walkable in maxTime
      subLine = this.getSubLineString(ls, fraction);
      walkShedEdges.add(subLine);
      // if it is smaller we need also to calculate the LS from the other side
      LineString reversedLine = (LineString) ls.reverse();
      double distanceToMoveInTimeMissing2 =
          distanceToMoveInRemainingTime(maxTime, toTime, dt, userSpeed, edge, hasCar, true);
      double fraction2 = (double) distanceToMoveInTimeMissing2 / (double) lineDist;
      LineString secondsubLine = this.getSubLineString(reversedLine, fraction2);
      ;
      walkShedEdges.add(secondsubLine);
    } else { // the whole u-shape is within the time
      // add only once
      walkShedEdges.add(ls);
    }
  }
Пример #15
0
 /**
  * Makes a new empty leg from a starting edge
  *
  * @param itinerary
  */
 private Leg makeLeg(Itinerary itinerary, State s) {
   Leg leg = new Leg();
   itinerary.addLeg(leg);
   leg.startTime = makeCalendar(s.getBackState());
   leg.distance = 0.0;
   String name;
   Edge backEdge = s.getBackEdge();
   if (backEdge instanceof StreetEdge) {
     name = backEdge.getName();
   } else {
     name = s.getVertex().getName();
   }
   leg.from = makePlace(s.getBackState(), name, false);
   leg.mode = s.getBackMode().toString();
   if (s.isBikeRenting()) {
     leg.rentedBike = true;
   }
   return leg;
 }
 /* use endpoints instead of geometry for quick updating */
 private void drawEdgeFast(Edge e) {
   Coordinate[] coords = e.getGeometry().getCoordinates();
   Coordinate c0 = coords[0];
   Coordinate c1 = coords[coords.length - 1];
   line(
       (float) toScreenX(c0.x),
       (float) toScreenY(c0.y),
       (float) toScreenX(c1.x),
       (float) toScreenY(c1.y));
 }
  public InferredEdge(@Nonnull Edge edge, @Nonnull Integer edgeId, @Nonnull OtpGraph graph) {
    Preconditions.checkNotNull(edge);
    Preconditions.checkNotNull(graph);
    Preconditions.checkNotNull(edgeId);

    assert !(edge instanceof TurnEdge || edge == null);

    this.graph = graph;
    this.edgeId = edgeId;
    this.edge = edge;

    /*
     * Warning: this geometry is in lon/lat and may contain more than one
     * straight line.
     */
    this.geometry = edge.getGeometry();

    this.locationIndexedLine = new LocationIndexedLine(geometry);
    this.lengthIndexedLine = new LengthIndexedLine(geometry);
    this.lengthLocationMap = new LengthLocationMap(geometry);

    this.startVertex = edge.getFromVertex();
    this.endVertex = edge.getToVertex();

    final Coordinate startPointCoord =
        this.locationIndexedLine.extractPoint(this.locationIndexedLine.getStartIndex());

    this.startPoint =
        VectorFactory.getDefault().createVector2D(startPointCoord.x, startPointCoord.y);

    final Coordinate endPointCoord =
        this.locationIndexedLine.extractPoint(this.locationIndexedLine.getEndIndex());
    this.endPoint = VectorFactory.getDefault().createVector2D(endPointCoord.x, endPointCoord.y);

    this.velocityPrecisionDist =
        // ~4.4 m/s, std. dev ~ 30 m/s, Gamma with exp. value = 30 m/s
        // TODO perhaps variance of velocity should be in m/s^2. yeah...
        new NormalInverseGammaDistribution(
            4.4d, 1d / Math.pow(30d, 2d), 1d / Math.pow(30d, 2d) + 1d, Math.pow(30d, 2d));
    this.velocityEstimator =
        new UnivariateGaussianMeanVarianceBayesianEstimator(velocityPrecisionDist);
  }
 /*
  * Iterate through all vertices and their (outgoing) edges. If they are of 'interesting' types, add them to the corresponding spatial index.
  */
 public synchronized void buildSpatialIndex() {
   vertexIndex = new STRtree();
   edgeIndex = new STRtree();
   Envelope env;
   // int xminx, xmax, ymin, ymax;
   for (Vertex v : graph.getVertices()) {
     Coordinate c = v.getCoordinate();
     env = new Envelope(c);
     vertexIndex.insert(env, v);
     for (Edge e : v.getOutgoing()) {
       if (e.getGeometry() == null) continue;
       if (e instanceof PatternEdge || e instanceof StreetTransitLink || e instanceof StreetEdge) {
         env = e.getGeometry().getEnvelopeInternal();
         edgeIndex.insert(env, e);
       }
     }
   }
   vertexIndex.build();
   edgeIndex.build();
 }
Пример #19
0
 /**
  * Internals of getRegionsForVertex; keeps track of seen vertices to avoid loops.
  *
  * @param regionData
  * @param vertex
  * @param seen
  * @param depth
  * @return
  */
 private static HashSet<Integer> getRegionsForVertex(
     RegionData regionData, Vertex vertex, HashSet<Vertex> seen, int depth) {
   seen.add(vertex);
   HashSet<Integer> regions = new HashSet<Integer>();
   int region = vertex.getGroupIndex();
   if (region >= 0) {
     regions.add(region);
   } else {
     for (Edge e : vertex.getOutgoing()) {
       final Vertex tov = e.getToVertex();
       if (!seen.contains(tov))
         regions.addAll(getRegionsForVertex(regionData, tov, seen, depth + 1));
     }
     for (Edge e : vertex.getIncoming()) {
       final Vertex fromv = e.getFromVertex();
       if (!seen.contains(fromv))
         regions.addAll(getRegionsForVertex(regionData, fromv, seen, depth + 1));
     }
   }
   return regions;
 }
  public void testBoardAlight() throws Exception {
    Vertex stop_a_depart = graph.getVertex("agency:A_depart");
    Vertex stop_b_depart = graph.getVertex("agency:B_depart");

    assertEquals(1, stop_a_depart.getDegreeOut());
    assertEquals(3, stop_b_depart.getDegreeOut());

    for (Edge e : stop_a_depart.getOutgoing()) {
      assertEquals(TransitBoardAlight.class, e.getClass());
      assertTrue(((TransitBoardAlight) e).boarding);
    }

    TransitBoardAlight pb = (TransitBoardAlight) stop_a_depart.getOutgoing().iterator().next();
    Vertex journey_a_1 = pb.getToVertex();

    assertEquals(1, journey_a_1.getDegreeIn());

    for (Edge e : journey_a_1.getOutgoing()) {
      if (e.getToVertex() instanceof TransitStop) {
        assertEquals(TransitBoardAlight.class, e.getClass());
      } else {
        assertEquals(PatternHop.class, e.getClass());
      }
    }
  }
Пример #21
0
  private void finalizeLeg(
      Leg leg,
      State state,
      List<State> states,
      int start,
      int end,
      CoordinateArrayListSequence coordinates,
      Itinerary itinerary) {

    // this leg has already been added to the itinerary, so we actually want the penultimate leg, if
    // any
    if (states != null) {
      int extra = 0;
      WalkStep continuation = null;
      if (itinerary.legs.size() >= 2) {
        Leg previousLeg = itinerary.legs.get(itinerary.legs.size() - 2);
        if (previousLeg.walkSteps != null) {
          continuation = previousLeg.walkSteps.get(previousLeg.walkSteps.size() - 1);
          extra = 1;
        }
      }
      if (end == states.size() - 1) {
        extra = 1;
      }

      leg.walkSteps = getWalkSteps(states.subList(start, end + extra), continuation);
    }
    leg.endTime = makeCalendar(state.getBackState());
    Geometry geometry = GeometryUtils.getGeometryFactory().createLineString(coordinates);
    leg.legGeometry = PolylineEncoder.createEncodings(geometry);
    Edge backEdge = state.getBackEdge();
    String name;
    if (backEdge instanceof StreetEdge) {
      name = backEdge.getName();
    } else {
      name = state.getVertex().getName();
    }
    leg.to = makePlace(state, name, true);
    coordinates.clear();
  }
  public boolean canTurnOnto(Edge e, State state, TraverseMode mode) {
    for (TurnRestriction turnRestriction : getTurnRestrictions(state.getOptions().rctx.graph)) {
      /* FIXME: This is wrong for trips that end in the middle of turnRestriction.to
       */

      // NOTE(flamholz): edge to be traversed decides equivalence. This is important since
      // it might be a temporary edge that is equivalent to some graph edge.
      if (turnRestriction.type == TurnRestrictionType.ONLY_TURN) {
        if (!e.isEquivalentTo(turnRestriction.to)
            && turnRestriction.modes.contains(mode)
            && turnRestriction.active(state.getTimeSeconds())) {
          return false;
        }
      } else {
        if (e.isEquivalentTo(turnRestriction.to)
            && turnRestriction.modes.contains(mode)
            && turnRestriction.active(state.getTimeSeconds())) {
          return false;
        }
      }
    }
    return true;
  }
    @SuppressWarnings("unchecked")
    public Void call() throws Exception {
      // LOG.debug("ORIGIN " + origin);
      int oi = stopIndices.get(origin); // origin index
      // first check for walking transfers
      // LOG.debug("    Walk");

      BinHeap<State> heap;
      try {
        heap = (BinHeap<State>) heapPool.borrowObject();
      } catch (Exception e) {
        throw new RuntimeException(e);
      }

      BasicShortestPathTree spt = new BasicShortestPathTree(500000);
      State s0 = new State(origin, options);
      spt.add(s0);
      heap.insert(s0, s0.getWeight());
      while (!heap.empty()) {
        double w = heap.peek_min_key();
        State u = heap.extract_min();
        if (!spt.visit(u)) continue;
        Vertex uVertex = u.getVertex();
        // LOG.debug("heap extract " + u + " weight " + w);
        if (w > MAX_WEIGHT) break;
        if (uVertex instanceof TransitStop) {
          int di = stopIndices.get(uVertex); // dest index
          table[oi][di] = (float) w;
          // LOG.debug("    Dest " + u + " w=" + w);
        }
        for (Edge e : uVertex.getOutgoing()) {
          if (!(e instanceof PreBoardEdge)) {
            State v = e.optimisticTraverse(u);
            if (v != null && spt.add(v)) heap.insert(v, v.getWeight());
          }
        }
      }

      // then check what is accessible in one transit trip
      heap.reset(); // recycle heap
      spt = new BasicShortestPathTree(50000);
      // first handle preboard edges
      Queue<Vertex> q = new ArrayDeque<Vertex>(100);
      q.add(origin);
      while (!q.isEmpty()) {
        Vertex u = q.poll();
        for (Edge e : u.getOutgoing()) {
          if (e instanceof PatternBoard) {
            Vertex v = ((PatternBoard) e).getToVertex();
            // give onboard vertices same index as their
            // corresponding station
            stopIndices.put(v, oi);
            StateEditor se = (new State(u, options)).edit(e);
            se.incrementWeight(OPTIMISTIC_BOARD_COST);
            s0 = se.makeState();
            spt.add(s0);
            heap.insert(s0, s0.getWeight());
            // _log.debug("    board " + tov);
          } else if (e instanceof FreeEdge) { // handle preboard
            Vertex v = ((FreeEdge) e).getToVertex();
            // give onboard vertices same index as their
            // corresponding station
            stopIndices.put(v, oi);
            q.add(v);
          }
        }
      }
      // all boarding edges for this stop have now been traversed
      // LOG.debug("    Transit");
      while (!heap.empty()) {
        // check for transit stops when pulling off of heap
        // and continue when one is found
        // this is enough to prevent reboarding
        // need to mark closed vertices because otherwise cycles may
        // appear (interlining...)
        double w = heap.peek_min_key();
        State u = heap.extract_min();
        if (!spt.visit(u)) continue;
        // LOG.debug("    Extract " + u + " w=" + w);
        Vertex uVertex = u.getVertex();
        if (uVertex instanceof TransitStop) {
          int di = stopIndices.get(uVertex); // dest index
          if (table[oi][di] > w) {
            table[oi][di] = (float) w;
            // LOG.debug("    Dest " + u + "w=" + w);
          }
          continue;
        }
        for (Edge e : uVertex.getOutgoing()) {
          // LOG.debug("        Edge " + e);
          State v = e.optimisticTraverse(u);
          if (v != null && spt.add(v)) heap.insert(v, v.getWeight());
          // else LOG.debug("        (skip)");
        }
      }
      heapPool.returnObject(heap);
      incrementCount();
      return null;
    }
  @Test
  public final void testOnBoardDepartureTime() {
    Coordinate[] coordinates = new Coordinate[5];
    coordinates[0] = new Coordinate(0.0, 0.0);
    coordinates[1] = new Coordinate(0.0, 1.0);
    coordinates[2] = new Coordinate(2.0, 1.0);
    coordinates[3] = new Coordinate(5.0, 1.0);
    coordinates[4] = new Coordinate(5.0, 5.0);

    PatternDepartVertex depart = mock(PatternDepartVertex.class);
    PatternArriveVertex dwell = mock(PatternArriveVertex.class);
    PatternArriveVertex arrive = mock(PatternArriveVertex.class);
    Graph graph = mock(Graph.class);
    RoutingRequest routingRequest = mock(RoutingRequest.class);
    ServiceDay serviceDay = mock(ServiceDay.class);

    when(graph.getTimeZone()).thenReturn(TimeZone.getTimeZone("GMT"));

    GeometryFactory geometryFactory = GeometryUtils.getGeometryFactory();
    CoordinateSequenceFactory coordinateSequenceFactory =
        geometryFactory.getCoordinateSequenceFactory();
    CoordinateSequence coordinateSequence = coordinateSequenceFactory.create(coordinates);
    LineString geometry = new LineString(coordinateSequence, geometryFactory);
    ArrayList<Edge> hops = new ArrayList<Edge>(2);
    RoutingContext routingContext = new RoutingContext(routingRequest, graph, null, arrive);
    AgencyAndId agencyAndId = new AgencyAndId("Agency", "ID");
    Route route = new Route();
    ArrayList<StopTime> stopTimes = new ArrayList<StopTime>(3);
    StopTime stopDepartTime = new StopTime();
    StopTime stopDwellTime = new StopTime();
    StopTime stopArriveTime = new StopTime();
    Stop stopDepart = new Stop();
    Stop stopDwell = new Stop();
    Stop stopArrive = new Stop();
    Trip trip = new Trip();

    routingContext.serviceDays = new ArrayList<ServiceDay>(Collections.singletonList(serviceDay));
    route.setId(agencyAndId);
    stopDepart.setId(agencyAndId);
    stopDwell.setId(agencyAndId);
    stopArrive.setId(agencyAndId);
    stopDepartTime.setStop(stopDepart);
    stopDepartTime.setDepartureTime(0);
    stopDwellTime.setArrivalTime(20);
    stopDwellTime.setStop(stopDwell);
    stopDwellTime.setDepartureTime(40);
    stopArriveTime.setArrivalTime(60);
    stopArriveTime.setStop(stopArrive);
    stopTimes.add(stopDepartTime);
    stopTimes.add(stopDwellTime);
    stopTimes.add(stopArriveTime);
    trip.setId(agencyAndId);
    trip.setTripHeadsign("The right");

    TripTimes tripTimes = new TripTimes(trip, stopTimes, new Deduplicator());
    StopPattern stopPattern = new StopPattern(stopTimes);
    TripPattern tripPattern = new TripPattern(route, stopPattern);

    when(depart.getTripPattern()).thenReturn(tripPattern);
    when(dwell.getTripPattern()).thenReturn(tripPattern);

    PatternHop patternHop0 = new PatternHop(depart, dwell, stopDepart, stopDwell, 0);
    PatternHop patternHop1 = new PatternHop(dwell, arrive, stopDwell, stopArrive, 1);

    hops.add(patternHop0);
    hops.add(patternHop1);

    when(graph.getEdges()).thenReturn(hops);
    when(depart.getCoordinate()).thenReturn(new Coordinate(0, 0));
    when(dwell.getCoordinate()).thenReturn(new Coordinate(0, 0));
    when(arrive.getCoordinate()).thenReturn(new Coordinate(0, 0));
    when(routingRequest.getFrom()).thenReturn(new GenericLocation());
    when(routingRequest.getStartingTransitTripId()).thenReturn(agencyAndId);
    when(serviceDay.secondsSinceMidnight(anyInt())).thenReturn(9);

    patternHop0.setGeometry(geometry);
    tripPattern.add(tripTimes);
    graph.index = new GraphIndex(graph);

    coordinates = new Coordinate[3];
    coordinates[0] = new Coordinate(3.5, 1.0);
    coordinates[1] = new Coordinate(5.0, 1.0);
    coordinates[2] = new Coordinate(5.0, 5.0);

    coordinateSequence = coordinateSequenceFactory.create(coordinates);
    geometry = new LineString(coordinateSequence, geometryFactory);

    Vertex vertex = onBoardDepartServiceImpl.setupDepartOnBoard(routingContext);
    Edge edge = vertex.getOutgoing().toArray(new Edge[1])[0];

    assertEquals(vertex, edge.getFromVertex());
    assertEquals(dwell, edge.getToVertex());
    assertEquals("The right", edge.getDirection());
    assertEquals(geometry, edge.getGeometry());

    assertEquals(coordinates[0].x, vertex.getX(), 0.0);
    assertEquals(coordinates[0].y, vertex.getY(), 0.0);
  }
  @Override
  public List<GraphPath> plan(State origin, Vertex target, int nItineraries) {

    TraverseOptions options = origin.getOptions();

    if (_graphService.getCalendarService() != null)
      options.setCalendarService(_graphService.getCalendarService());
    options.setTransferTable(_graphService.getGraph().getTransferTable());

    options.setServiceDays(origin.getTime(), _graphService.getGraph().getAgencyIds());
    if (options.getModes().getTransit()
        && !_graphService.getGraph().transitFeedCovers(new Date(origin.getTime() * 1000))) {
      // user wants a path through the transit network,
      // but the date provided is outside those covered by the transit feed.
      throw new TransitTimesException();
    }

    // always use the bidirectional heuristic because the others are not precise enough
    RemainingWeightHeuristic heuristic =
        new BidirectionalRemainingWeightHeuristic(_graphService.getGraph());

    // the states that will eventually be turned into paths and returned
    List<State> returnStates = new LinkedList<State>();

    // Populate any extra edges
    final ExtraEdgesStrategy extraEdgesStrategy = options.extraEdgesStrategy;
    OverlayGraph extraEdges = new OverlayGraph();
    extraEdgesStrategy.addEdgesFor(extraEdges, origin.getVertex());
    extraEdgesStrategy.addEdgesFor(extraEdges, target);

    BinHeap<State> pq = new BinHeap<State>();
    //        List<State> boundingStates = new ArrayList<State>();

    // initialize heuristic outside loop so table can be reused
    heuristic.computeInitialWeight(origin, target);

    // increase maxWalk repeatedly in case hard limiting is in use
    WALK:
    for (double maxWalk = options.getMaxWalkDistance();
        maxWalk < 100000 && returnStates.isEmpty();
        maxWalk *= 2) {
      LOG.debug("try search with max walk {}", maxWalk);
      // increase maxWalk if settings make trip impossible
      if (maxWalk
          < Math.min(
              origin.getVertex().distance(target),
              origin.getVertex().getDistanceToNearestTransitStop()
                  + target.getDistanceToNearestTransitStop())) continue WALK;
      options.setMaxWalkDistance(maxWalk);
      // reinitialize states for each retry
      HashMap<Vertex, List<State>> states = new HashMap<Vertex, List<State>>();
      pq.reset();
      pq.insert(origin, 0);
      long startTime = System.currentTimeMillis();
      long endTime = startTime + (int) (_timeouts[0] * 1000);
      LOG.debug("starttime {} endtime {}", startTime, endTime);
      QUEUE:
      while (!pq.empty()) {

        if (System.currentTimeMillis() > endTime) {
          LOG.debug("timeout at {} msec", System.currentTimeMillis() - startTime);
          if (returnStates.isEmpty()) continue WALK;
          else {
            storeMemory();
            break WALK;
          }
        }

        State su = pq.extract_min();

        //                for (State bs : boundingStates) {
        //                    if (eDominates(bs, su)) {
        //                        continue QUEUE;
        //                    }
        //                }

        Vertex u = su.getVertex();

        if (traverseVisitor != null) {
          traverseVisitor.visitVertex(su);
        }

        if (u.equals(target)) {
          //                    boundingStates.add(su);
          returnStates.add(su);
          if (!options.getModes().getTransit()) break QUEUE;
          // options should contain max itineraries
          if (returnStates.size() >= _maxPaths) break QUEUE;
          if (returnStates.size() < _timeouts.length) {
            endTime = startTime + (int) (_timeouts[returnStates.size()] * 1000);
            LOG.debug(
                "{} path, set timeout to {}",
                returnStates.size(),
                _timeouts[returnStates.size()] * 1000);
          }
          continue QUEUE;
        }

        for (Edge e : u.getEdges(extraEdges, null, options.isArriveBy())) {
          STATE:
          for (State new_sv = e.traverse(su); new_sv != null; new_sv = new_sv.getNextResult()) {
            if (traverseVisitor != null) {
              traverseVisitor.visitEdge(e, new_sv);
            }

            double h = heuristic.computeForwardWeight(new_sv, target);
            //                    for (State bs : boundingStates) {
            //                        if (eDominates(bs, new_sv)) {
            //                            continue STATE;
            //                        }
            //                    }
            Vertex v = new_sv.getVertex();
            List<State> old_states = states.get(v);
            if (old_states == null) {
              old_states = new LinkedList<State>();
              states.put(v, old_states);
            } else {
              for (State old_sv : old_states) {
                if (eDominates(old_sv, new_sv)) {
                  continue STATE;
                }
              }
              Iterator<State> iter = old_states.iterator();
              while (iter.hasNext()) {
                State old_sv = iter.next();
                if (eDominates(new_sv, old_sv)) {
                  iter.remove();
                }
              }
            }
            if (traverseVisitor != null) traverseVisitor.visitEnqueue(new_sv);

            old_states.add(new_sv);
            pq.insert(new_sv, new_sv.getWeight() + h);
          }
        }
      }
    }
    storeMemory();

    // Make the states into paths and return them
    List<GraphPath> paths = new LinkedList<GraphPath>();
    for (State s : returnStates) {
      LOG.debug(s.toStringVerbose());
      paths.add(new GraphPath(s, true));
    }
    // sort by arrival time, though paths are already in order of increasing difficulty
    // Collections.sort(paths, new PathComparator(origin.getOptions().isArriveBy()));
    return paths;
  }
Пример #26
0
 private State getStateDepartAt(RaptorData data, ArrayList<RaptorState> states) {
   State state = new State(states.get(0).getRequest());
   for (int i = states.size() - 1; i >= 0; --i) {
     RaptorState cur = states.get(i);
     if (cur.walkPath != null) { // a walking step
       GraphPath path = new GraphPath(cur.walkPath, false);
       for (Edge e : path.edges) {
         State oldState = state;
         state = e.traverse(state);
         if (state == null) {
           e.traverse(oldState);
         }
       }
     } else {
       // so, cur is at this point at a transit stop; we have a route to board
       if (cur.getParent() == null || !cur.getParent().interlining) {
         for (Edge e : state.getVertex().getOutgoing()) {
           if (e instanceof PreBoardEdge) {
             state = e.traverse(state);
             break;
           }
         }
         TransitBoardAlight board = cur.getRoute().boards[cur.boardStopSequence][cur.patternIndex];
         state = board.traverse(state);
       }
       // now traverse the hops and dwells until we find the alight we're looking for
       HOP:
       while (true) {
         for (Edge e : state.getVertex().getOutgoing()) {
           if (e instanceof PatternDwell) {
             state = e.traverse(state);
           } else if (e instanceof PatternHop) {
             state = e.traverse(state);
             if (cur.interlining) {
               for (Edge e2 : state.getVertex().getOutgoing()) {
                 RaptorState next = states.get(i - 1);
                 if (e2 instanceof PatternInterlineDwell) {
                   Stop toStop = ((TransitVertex) e2.getToVertex()).getStop();
                   Stop expectedStop = next.boardStop.stopVertex.getStop();
                   if (toStop.equals(expectedStop)) {
                     State newState = e2.traverse(state);
                     if (newState == null) continue;
                     if (newState.getTripId() != next.tripId) continue;
                     state = newState;
                     break HOP;
                   }
                 }
               }
             } else {
               for (Edge e2 : state.getVertex().getOutgoing()) {
                 if (e2 instanceof TransitBoardAlight) {
                   for (Edge e3 : e2.getToVertex().getOutgoing()) {
                     if (e3 instanceof PreAlightEdge) {
                       if (data.raptorStopsForStopId.get(
                               ((TransitStop) e3.getToVertex()).getStopId())
                           == cur.stop) {
                         state = e2.traverse(state);
                         state = e3.traverse(state);
                         break HOP;
                       }
                     }
                   }
                 }
               }
             }
           }
         }
       }
     }
   }
   return state;
 }
Пример #27
0
  /**
   * Calculates what distance can be traveled with the remaining time and given speeds. For car use
   * the speed limit is taken from the edge itself. Slopes are accounted for when walking and
   * biking. A minimal slope of 0.06 (6m/100m) is necessary.
   *
   * @param maxTime in sec, the time we have left
   * @param fromTime in sec, the time when we enter the edge
   * @param traverseTime in sec, original edge traverse time needed to adjust the speed based
   *     calculation to slope effects
   * @param userSpeed in m/sec, dependent on traversal mode
   * @param edge the edge itself (used to the get the speed in car mode)
   * @param usesCar if we traverse the edge in car mode
   * @param hasUshape if know, indicate if the edge has a u-shape
   * @return the distance in meter that can be moved until maxTime
   */
  double distanceToMoveInRemainingTime(
      long maxTime,
      long fromTime,
      double traverseTime,
      double userSpeed,
      Edge edge,
      boolean usesCar,
      boolean hasUshape) {

    boolean isTooFast = false;
    String msg = "";

    double originalTravelSpeed =
        edge.getDistance() / traverseTime; // this may be wrong for u-shapes

    if (originalTravelSpeed < userSpeed) {
      // we may have slope effects
      if (edge instanceof PlainStreetEdge) {
        PlainStreetEdge pe = (PlainStreetEdge) edge;
        double maxSlope = pe.getElevationProfileSegment().getMaxSlope();
        // if we are over the slope limit, then we should use the slower speed
        if (maxSlope > 0.06) { // limit 6m/100m = 3.4 degree
          userSpeed = originalTravelSpeed;
        }
      }
    } else {
      // in this case we may have a u-shape, or the user speeds are too small, or something else.
      double vdiff = Math.abs(originalTravelSpeed - userSpeed);
      double vDiffPercent = vdiff / (userSpeed / 100.0);
      if (vDiffPercent > 20) {
        isTooFast = true;
        // [sstein Dec 2012]: Note, it seems like most of these edges are indeed of u-shape type,
        // i.e. small roads that come from and return from (the same) main road
        msg =
            "v_traversed is much faster than (allowed) v_user, edgeName: "
                + edge.getName()
                + ", >>> (in m/s): v_traversed="
                + (int) Math.floor(originalTravelSpeed)
                + ", v_maxUser="******", known u-shape, ";
        }
        if ((usesCar == false) && (hasUshape == false)) {
          this.tooFastTraversedEdgeGeoms.add(edge.getGeometry());
          LOG.debug(msg);
        } // otherwise we print msg below
      }
    }
    // correct speed for car use, as each road has its speed limits
    if (usesCar) {
      if (edge instanceof PlainStreetEdge) {
        PlainStreetEdge pe = (PlainStreetEdge) edge;
        userSpeed = pe.getCarSpeed();
        // we need to check again if the originalTravelSpeed is faster
        if ((isTooFast == true) && (originalTravelSpeed > userSpeed) && (hasUshape == false)) {
          this.tooFastTraversedEdgeGeoms.add(edge.getGeometry());
          LOG.debug(msg + "; setting v_PlainStreetEdge=" + (int) Math.floor(userSpeed));
        }
      }
    }
    // finally calculate how far we can travel with the remaining time
    long timeMissing = maxTime - fromTime;
    double distanceToWalkInTimeMissing = timeMissing * userSpeed;
    return distanceToWalkInTimeMissing;
  }
Пример #28
0
 private State getStateArriveBy(RaptorData data, ArrayList<RaptorState> states) {
   RoutingRequest options = states.get(0).getRequest();
   State state = new State(options.rctx.origin, options);
   for (int i = states.size() - 1; i >= 0; --i) {
     RaptorState cur = states.get(i);
     if (cur.walkPath != null) {
       GraphPath path = new GraphPath(cur.walkPath, false);
       for (ListIterator<Edge> it = path.edges.listIterator(path.edges.size());
           it.hasPrevious(); ) {
         Edge e = it.previous();
         State oldState = state;
         state = e.traverse(state);
         if (state == null) {
           e.traverse(oldState);
         }
       }
     } else {
       // so, cur is at this point at a transit stop; we have a route to alight from
       if (cur.getParent() == null || !cur.getParent().interlining) {
         for (Edge e : state.getVertex().getIncoming()) {
           if (e instanceof PreAlightEdge) {
             state = e.traverse(state);
           }
         }
         TransitBoardAlight alight =
             cur.getRoute().alights[cur.boardStopSequence - 1][cur.patternIndex];
         State oldState = state;
         state = alight.traverse(state);
         if (state == null) {
           state = alight.traverse(oldState);
         }
       }
       // now traverse the hops and dwells until we find the board we're looking for
       HOP:
       while (true) {
         for (Edge e : state.getVertex().getIncoming()) {
           if (e instanceof PatternDwell) {
             state = e.traverse(state);
           } else if (e instanceof PatternHop) {
             state = e.traverse(state);
             if (cur.interlining) {
               for (Edge e2 : state.getVertex().getIncoming()) {
                 RaptorState next = states.get(i - 1);
                 if (e2 instanceof PatternInterlineDwell) {
                   Stop fromStop = ((TransitVertex) e2.getFromVertex()).getStop();
                   Stop expectedStop = next.boardStop.stopVertex.getStop();
                   if (fromStop.equals(expectedStop)) {
                     State newState = e2.traverse(state);
                     if (newState == null) continue;
                     if (newState.getTripId() != next.tripId) continue;
                     state = newState;
                     break HOP;
                   }
                 }
               }
             } else {
               for (Edge e2 : state.getVertex().getIncoming()) {
                 if (e2 instanceof TransitBoardAlight) {
                   for (Edge e3 : e2.getFromVertex().getIncoming()) {
                     if (e3 instanceof PreBoardEdge) {
                       if (data.raptorStopsForStopId.get(
                               ((TransitStop) e3.getFromVertex()).getStopId())
                           == cur.stop) {
                         state = e2.traverse(state);
                         state = e3.traverse(state);
                         break HOP;
                       }
                     }
                   }
                 }
               }
             }
           }
         }
       }
     }
   }
   return state;
 }
Пример #29
0
  /**
   * Calculates walksheds for a given location, based on time given to walk and the walk speed.
   *
   * <p>Depending on the value for the "output" parameter (i.e. "POINTS", "SHED" or "EDGES"), a
   * different type of GeoJSON geometry is returned. If a SHED is requested, then a ConcaveHull of
   * the EDGES/roads is returned. If that fails, a ConvexHull will be returned.
   *
   * <p>The ConcaveHull parameter is set to 0.005 degrees. The offroad walkspeed is assumed to be
   * 0.83333 m/sec (= 3km/h) until a road is hit.
   *
   * <p>Note that the set of EDGES/roads returned as well as POINTS returned may contain duplicates.
   * If POINTS are requested, then not the end-points are returned at which the max time is reached,
   * but instead all the graph nodes/crossings that are within the time limits.
   *
   * <p>In case there is no road near by within the given time, then a circle for the walktime limit
   * is created and returned for the SHED parameter. Otherwise the edge with the direction towards
   * the closest road. Note that the circle is calculated in Euclidian 2D coordinates, and
   * distortions towards an ellipse will appear if it is transformed/projected to the user location.
   *
   * <p>An example request may look like this:
   * localhost:8080/otp-rest-servlet/ws/iso?layers=traveltime&styles=mask&batch=true&fromPlace=51.040193121307176
   * %2C-114.04471635818481&toPlace
   * =51.09098935%2C-113.95179705&time=2012-06-06T08%3A00%3A00&mode=WALK&maxWalkDistance=10000&walkSpeed=1.38&walkTime=10.7&output=EDGES
   * Though the first parameters (i) layer, (ii) styles and (iii) batch could be discarded.
   *
   * @param walkmins Maximum number of minutes to walk.
   * @param output Can be set to "POINTS", "SHED" or "EDGES" to return different types of GeoJSON
   *     geometry. SHED returns a ConcaveHull or ConvexHull of the edges/roads. POINTS returns all
   *     graph nodes that are within the time limit.
   * @return a JSON document containing geometries (either points, lineStrings or a polygon).
   * @throws Exception
   * @author sstein---geo.uzh.ch
   */
  @GET
  @Produces({MediaType.APPLICATION_JSON})
  public String getIsochrone(
      @QueryParam("walkTime") @DefaultValue("15") double walkmins,
      @QueryParam("output") @DefaultValue("POINTS") String output)
      throws Exception {

    this.debugGeoms = new ArrayList();
    this.tooFastTraversedEdgeGeoms = new ArrayList();

    RoutingRequest sptRequestA = buildRequest(0);
    String from = sptRequestA.getFrom().toString();
    int pos = 1;
    float lat = 0;
    float lon = 0;
    for (String s : from.split(",")) {
      if (s.isEmpty()) {
        // no location
        Response.status(Status.BAD_REQUEST).entity("no position").build();
        return null;
      }
      try {
        float num = Float.parseFloat(s);
        if (pos == 1) {
          lat = num;
        }
        if (pos == 2) {
          lon = num;
        }
      } catch (Exception e) {
        throw new WebApplicationException(
            Response.status(Status.BAD_REQUEST)
                .entity(
                    "Could not parse position string to number. Require numerical lat & long coords.")
                .build());
      }
      pos++;
    }

    GeometryFactory gf = new GeometryFactory();

    Coordinate dropPoint = new Coordinate(lon, lat);

    int walkInMin = (int) Math.floor(walkmins);
    double walkInSec = walkmins * 60;
    LOG.debug(
        "given travel time: " + walkInMin + " mins + " + (walkInSec - (60 * walkInMin)) + " sec");
    // restrict the evaluated SPT size to 30mins for requests with walking < 30min
    // if larger walking times are requested we adjust the evaluated
    // graph dynamically by 1.3 * min -> this should save processing time
    if (walkInMin < 30) {
      sptRequestA.worstTime = sptRequestA.dateTime + (30 * 60);
    } else {
      sptRequestA.worstTime = sptRequestA.dateTime + Math.round(walkInMin * 1.3 * 60);
    }
    // set the switch-time for shed/area calculation, i.e. to decide if the hull is calculated based
    // on points or on edges
    TraverseModeSet modes = sptRequestA.modes;
    LOG.debug("mode(s): " + modes);
    if ((modes.contains(TraverseMode.TRANSIT))
        || (modes.contains(TraverseMode.BUSISH))
        || (modes.contains(TraverseMode.TRAINISH))) {
      shedCalcMethodSwitchTimeInSec =
          60 * 20; // 20min (use 20min for transit, since buses may not come all the time)
    } else if (modes.contains(TraverseMode.CAR)) {
      shedCalcMethodSwitchTimeInSec = 60 * 10; // 10min
    } else if (modes.contains(TraverseMode.BICYCLE)) {
      shedCalcMethodSwitchTimeInSec = 60 * 10; // 10min
    } else {
      shedCalcMethodSwitchTimeInSec = 60 * 20; // 20min
    }
    // set the maxUserSpeed, which is used later to check for u-type streets/crescents when
    // calculating sub-edges;
    // Note, that the car speed depends on the edge itself, so this value may be replaced later
    this.usesCar = false;
    int numberOfModes = modes.getModes().size();
    if (numberOfModes == 1) {
      if (modes.getWalk()) {
        this.maxUserSpeed = sptRequestA.getWalkSpeed();
      } else if (modes.getBicycle()) {
        this.maxUserSpeed = sptRequestA.getBikeSpeed();
      } else if (modes.getDriving()) {
        this.maxUserSpeed = sptRequestA.getCarSpeed();
        this.usesCar = true;
      }
    } else { // for all other cases (multiple-modes)
      // sstein: I thought I may set it to 36.111 m/sec = 130 km/h,
      // but maybe it is better to assume walk speed for transit, i.e. treat it like if the
      // person gets off the bus on the last crossing and walks the "last mile".
      this.maxUserSpeed = sptRequestA.getWalkSpeed();
    }

    if (doSpeedTest) {
      LOG.debug("performing angle and speed based test to detect u-shapes");
    } else {
      LOG.debug("performing only angle based test to detect u-shapes");
    }

    // TODO: OTP prefers to snap to car-roads/ways, which is not so nice, when walking,
    // and a footpath is closer by. So far there is no option to switch that off

    // create the ShortestPathTree
    try {
      sptRequestA.setRoutingContext(graphService.getGraph());
    } catch (Exception e) {
      // if we get an exception here, and in particular a VertexNotFoundException,
      // then it is likely that we chose a (transit) mode without having that (transit) modes data
      LOG.debug("cannot set RoutingContext: " + e.toString());
      LOG.debug("cannot set RoutingContext: setting mode=WALK");
      sptRequestA.setMode(TraverseMode.WALK); // fall back to walk mode
      sptRequestA.setRoutingContext(graphService.getGraph());
    }
    ShortestPathTree sptA = sptService.getShortestPathTree(sptRequestA);
    StreetLocation origin = (StreetLocation) sptRequestA.rctx.fromVertex;
    sptRequestA.cleanup(); // remove inserted points

    // create a LineString for display
    Coordinate pathToStreetCoords[] = new Coordinate[2];
    pathToStreetCoords[0] = dropPoint;
    pathToStreetCoords[1] = origin.getCoordinate();
    LineString pathToStreet = gf.createLineString(pathToStreetCoords);

    // get distance between origin and drop point for time correction
    double distanceToRoad =
        this.distanceLibrary.distance(origin.getY(), origin.getX(), dropPoint.y, dropPoint.x);
    long offRoadTimeCorrection = (long) (distanceToRoad / this.offRoadWalkspeed);

    //
    // --- filter the states ---
    //
    Set<Coordinate> visitedCoords = new HashSet<Coordinate>();
    ArrayList<Edge> allConnectingEdges = new ArrayList<Edge>();
    Coordinate coords[] = null;
    long maxTime = (long) walkInSec - offRoadTimeCorrection;
    // System.out.println("Reducing walktime from: " + (int)(walkmins * 60) + "sec to " + maxTime +
    // "sec due to initial walk of " + distanceToRoad
    // + "m");

    // if the initial walk is already to long, there is no need to parse...
    if (maxTime <= 0) {
      noRoadNearBy = true;
      long timeToWalk = (long) walkInSec;
      long timeBetweenStates = offRoadTimeCorrection;
      long timeMissing = timeToWalk;
      double fraction = (double) timeMissing / (double) timeBetweenStates;
      pathToStreet = getSubLineString(pathToStreet, fraction);
      LOG.debug(
          "no street found within giving travel time (for off-road walkspeed: {} m/sec)",
          this.offRoadWalkspeed);
    } else {
      noRoadNearBy = false;
      Map<ReversibleLineStringWrapper, Edge> connectingEdgesMap = Maps.newHashMap();
      for (State state : sptA.getAllStates()) {
        long et = state.getElapsedTimeSeconds();
        if (et <= maxTime) {
          // -- filter points, as the same coordinate may be passed several times due to the graph
          // structure
          // in a Calgary suburb family homes neighborhood with a 15min walkshed it filtered about
          // 250 points away (while 145 were finally displayed)
          if (visitedCoords.contains(state.getVertex().getCoordinate())) {
            continue;
          } else {
            visitedCoords.add(state.getVertex().getCoordinate());
          }
          // -- get all Edges needed later for the edge representation
          // and to calculate an edge-based walkshed
          // Note, it can happen that we get a null geometry here, e.g. for hop-edges!
          Collection<Edge> vertexEdgesIn = state.getVertex().getIncoming();
          for (Iterator<Edge> iterator = vertexEdgesIn.iterator(); iterator.hasNext(); ) {
            Edge edge = (Edge) iterator.next();
            Geometry edgeGeom = edge.getGeometry();
            if (edgeGeom != null) { // make sure we get only real edges
              if (edgeGeom instanceof LineString) {
                // allConnectingEdges.add(edge); // instead of this, use a map now, so we don't have
                // similar edge many times
                connectingEdgesMap.put(
                    new ReversibleLineStringWrapper((LineString) edgeGeom), edge);
              }
            }
          }
          Collection<Edge> vertexEdgesOut = state.getVertex().getOutgoing();
          for (Iterator<Edge> iterator = vertexEdgesOut.iterator(); iterator.hasNext(); ) {
            Edge edge = (Edge) iterator.next();
            Geometry edgeGeom = edge.getGeometry();
            if (edgeGeom != null) {
              if (edgeGeom instanceof LineString) {
                // allConnectingEdges.add(edge); // instead of this, use a map now, so we don't
                // similar edge many times
                connectingEdgesMap.put(
                    new ReversibleLineStringWrapper((LineString) edgeGeom), edge);
              }
            }
          }
        } // end : if(et < maxTime)
      }
      // --
      // points from list to array, for later
      coords = new Coordinate[visitedCoords.size()];
      int i = 0;
      for (Coordinate c : visitedCoords) coords[i++] = c;

      // connection edges from Map to List
      allConnectingEdges.clear();
      for (Edge tedge : connectingEdgesMap.values()) allConnectingEdges.add(tedge);
    }
    StringWriter sw = new StringWriter();
    GeoJSONBuilder json = new GeoJSONBuilder(sw);
    //
    // -- create the different outputs ---
    //
    try {
      if (output.equals(IsoChrone.RESULT_TYPE_POINTS)) {
        // in case there was no road we create a circle and
        // and return those points
        if (noRoadNearBy) {
          Geometry circleShape = createCirle(dropPoint, pathToStreet);
          coords = circleShape.getCoordinates();
        }
        // -- the states/nodes with time elapsed <= X min.
        LOG.debug("write multipoint geom with {} points", coords.length);
        json.writeGeom(gf.createMultiPoint(coords));
        LOG.debug("done");
      } else if (output.equals(IsoChrone.RESULT_TYPE_SHED)) {

        Geometry geomsArray[] = null;
        // in case there was no road we create a circle
        if (noRoadNearBy) {
          Geometry circleShape = createCirle(dropPoint, pathToStreet);
          json.writeGeom(circleShape);
        } else {
          if (maxTime > shedCalcMethodSwitchTimeInSec) { // eg., walkshed > 20 min
            // -- create a point-based walkshed
            // less exact and should be used for large walksheds with many edges
            LOG.debug("create point-based shed (not from edges)");
            geomsArray = new Geometry[coords.length];
            for (int j = 0; j < geomsArray.length; j++) {
              geomsArray[j] = gf.createPoint(coords[j]);
            }
          } else {
            // -- create an edge-based walkshed
            // it is more exact and should be used for short walks
            LOG.debug("create edge-based shed (not from points)");
            Map<ReversibleLineStringWrapper, LineString> walkShedEdges = Maps.newHashMap();
            // add the walk from the pushpin to closest street point
            walkShedEdges.put(new ReversibleLineStringWrapper(pathToStreet), pathToStreet);
            // get the edges and edge parts within time limits
            ArrayList<LineString> withinTimeEdges =
                this.getLinesAndSubEdgesWithinMaxTime(
                    maxTime,
                    allConnectingEdges,
                    sptA,
                    angleLimitForUShapeDetection,
                    distanceToleranceForUShapeDetection,
                    maxUserSpeed,
                    usesCar,
                    doSpeedTest);
            for (LineString ls : withinTimeEdges) {
              walkShedEdges.put(new ReversibleLineStringWrapper(ls), ls);
            }
            geomsArray = new Geometry[walkShedEdges.size()];
            int k = 0;
            for (LineString ls : walkShedEdges.values()) geomsArray[k++] = ls;
          } // end if-else: maxTime condition
          GeometryCollection gc = gf.createGeometryCollection(geomsArray);
          // create the concave hull, but in case it fails we just return the convex hull
          Geometry outputHull = null;
          LOG.debug(
              "create concave hull from {} geoms with edge length limit of about {} m (distance on meridian)",
              geomsArray.length,
              concaveHullAlpha * 111132);
          // 1deg at Latitude phi = 45deg is about 111.132km
          // (see wikipedia:
          // http://en.wikipedia.org/wiki/Latitude#The_length_of_a_degree_of_latitude)
          try {
            ConcaveHull hull = new ConcaveHull(gc, concaveHullAlpha);
            outputHull = hull.getConcaveHull();
          } catch (Exception e) {
            outputHull = gc.convexHull();
            LOG.debug("Could not generate ConcaveHull for WalkShed, using ConvexHull instead.");
          }
          LOG.debug("write shed geom");
          json.writeGeom(outputHull);
          LOG.debug("done");
        }
      } else if (output.equals(IsoChrone.RESULT_TYPE_EDGES)) {
        // in case there was no road we return only the suggested path to the street
        if (noRoadNearBy) {
          json.writeGeom(pathToStreet);
        } else {
          // -- if we would use only the edges from the paths to the origin we will miss
          // some edges that will be never on the shortest path (e.g. loops/crescents).
          // However, we can retrieve all edges by checking the times for each
          // edge end-point
          Map<ReversibleLineStringWrapper, LineString> walkShedEdges = Maps.newHashMap();
          // add the walk from the pushpin to closest street point
          walkShedEdges.put(new ReversibleLineStringWrapper(pathToStreet), pathToStreet);
          // get the edges and edge parts within time limits
          ArrayList<LineString> withinTimeEdges =
              this.getLinesAndSubEdgesWithinMaxTime(
                  maxTime,
                  allConnectingEdges,
                  sptA,
                  angleLimitForUShapeDetection,
                  distanceToleranceForUShapeDetection,
                  maxUserSpeed,
                  usesCar,
                  doSpeedTest);
          for (LineString ls : withinTimeEdges) {
            walkShedEdges.put(new ReversibleLineStringWrapper(ls), ls);
          }
          Geometry mls = null;
          LineString edges[] = new LineString[walkShedEdges.size()];
          int k = 0;
          for (LineString ls : walkShedEdges.values()) edges[k++] = ls;
          LOG.debug("create multilinestring from {} geoms", edges.length);
          mls = gf.createMultiLineString(edges);
          LOG.debug("write geom");
          json.writeGeom(mls);
          LOG.debug("done");
        }
      } else if (output.equals("DEBUGEDGES")) {
        // -- for debugging, i.e. display of detected u-shapes/crescents
        ArrayList<LineString> withinTimeEdges =
            this.getLinesAndSubEdgesWithinMaxTime(
                maxTime,
                allConnectingEdges,
                sptA,
                angleLimitForUShapeDetection,
                distanceToleranceForUShapeDetection,
                maxUserSpeed,
                usesCar,
                doSpeedTest);
        if (this.showTooFastEdgesAsDebugGeomsANDnotUShapes) {
          LOG.debug("displaying edges that are traversed too fast");
          this.debugGeoms = this.tooFastTraversedEdgeGeoms;
        } else {
          LOG.debug("displaying detected u-shaped roads/crescents");
        }
        LineString edges[] = new LineString[this.debugGeoms.size()];
        int k = 0;
        for (Iterator iterator = debugGeoms.iterator(); iterator.hasNext(); ) {
          LineString ls = (LineString) iterator.next();
          edges[k] = ls;
          k++;
        }
        Geometry mls = gf.createMultiLineString(edges);
        LOG.debug("write debug geom");
        json.writeGeom(mls);
        LOG.debug("done");
      }
    } catch (org.codehaus.jettison.json.JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return sw.toString();
  }
Пример #30
0
  /**
   * Filters all input edges and returns all those as LineString geometries, that have at least one
   * end point within the time limits. If they have only one end point inside, then the sub-edge is
   * returned.
   *
   * @param maxTime the time limit in seconds that defines the size of the walkshed
   * @param allConnectingStateEdges all Edges that have been found to connect all states < maxTime
   * @param spt the ShortestPathTree generated for the pushpin drop point as origin
   * @param angleLimit the angle tolerance to detect roads with u-shapes, i.e. Pi/2 angles, in
   *     Radiant.
   * @param distanceTolerance in percent (e.g. 1.1 = 110%) for u-shape detection based on distance
   *     criteria
   * @param hasCar is travel mode by CAR?
   * @param performSpeedTest if true applies a test to each edge to check if the edge can be
   *     traversed in time. The test can detect u-shaped roads.
   * @return
   */
  ArrayList<LineString> getLinesAndSubEdgesWithinMaxTime(
      long maxTime,
      ArrayList<Edge> allConnectingStateEdges,
      ShortestPathTree spt,
      double angleLimit,
      double distanceTolerance,
      double userSpeed,
      boolean hasCar,
      boolean performSpeedTest) {

    LOG.debug("maximal userSpeed set to: " + userSpeed + " m/sec ");
    if (hasCar) {
      LOG.debug("travel mode is set to CAR, hence the given speed may be adjusted for each edge");
    }

    ArrayList<LineString> walkShedEdges = new ArrayList<LineString>();
    ArrayList<LineString> otherEdges = new ArrayList<LineString>();
    ArrayList<LineString> borderEdges = new ArrayList<LineString>();
    ArrayList<LineString> uShapes = new ArrayList<LineString>();
    int countEdgesOutside = 0;
    // -- determination of walkshed edges via edge states
    for (Iterator iterator = allConnectingStateEdges.iterator(); iterator.hasNext(); ) {
      Edge edge = (Edge) iterator.next();
      State sFrom = spt.getState(edge.getFromVertex());
      State sTo = spt.getState(edge.getToVertex());
      if ((sFrom != null) && (sTo != null)) {
        long fromTime = sFrom.getElapsedTimeSeconds();
        long toTime = sTo.getElapsedTimeSeconds();
        long dt = Math.abs(toTime - fromTime);
        Geometry edgeGeom = edge.getGeometry();
        if ((edgeGeom != null) && (edgeGeom instanceof LineString)) {
          LineString ls = (LineString) edgeGeom;
          // detect u-shape roads/crescents - they need to be treated separately
          boolean uShapeOrLonger =
              testForUshape(
                  edge,
                  maxTime,
                  fromTime,
                  toTime,
                  angleLimit,
                  distanceTolerance,
                  userSpeed,
                  hasCar,
                  performSpeedTest);
          if (uShapeOrLonger) {
            uShapes.add(ls);
          }

          // evaluate if an edge is completely within the time or only with one end
          if ((fromTime < maxTime) && (toTime < maxTime)) {
            // this one is within the time limit on both ends, however we need to do
            // a second test if we have a u-shaped road.
            if (uShapeOrLonger) {
              treatAndAddUshapeWithinTimeLimits(
                  maxTime, userSpeed, walkShedEdges, edge, fromTime, toTime, ls, hasCar);
            } else {
              walkShedEdges.add(ls);
            }
          } // end if:fromTime & toTime < maxTime
          else {
            // check if at least one end is inside, because then we need to
            // create the sub edge
            if ((fromTime < maxTime) || (toTime < maxTime)) {
              double lineDist = edge.getDistance();
              LineString inputLS = ls;
              double fraction = 1.0;
              if (fromTime < toTime) {
                double distanceToWalkInTimeMissing =
                    distanceToMoveInRemainingTime(
                        maxTime, fromTime, dt, userSpeed, edge, hasCar, uShapeOrLonger);
                fraction = (double) distanceToWalkInTimeMissing / (double) lineDist;
              } else {
                // toTime < fromTime : invert the edge direction
                inputLS = (LineString) ls.reverse();
                double distanceToWalkInTimeMissing =
                    distanceToMoveInRemainingTime(
                        maxTime, toTime, dt, userSpeed, edge, hasCar, uShapeOrLonger);
                fraction = (double) distanceToWalkInTimeMissing / (double) lineDist;
              }
              // get the subedge
              LineString subLine = this.getSubLineString(inputLS, fraction);
              borderEdges.add(subLine);
            } else {
              // this edge is completely outside - this should actually not happen
              // we will not do anything, just count
              countEdgesOutside++;
            }
          } // end else: fromTime & toTime < maxTime
        } // end if: edge instance of LineString
        else {
          // edge is not instance of LineString
          LOG.debug("edge not instance of LineString");
        }
      } // end if(sFrom && sTo != null) start Else
      else {
        // LOG.debug("could not retrieve state for edge-endpoint"); //for a 6min car ride, there can
        // be (too) many of such messages
        Geometry edgeGeom = edge.getGeometry();
        if ((edgeGeom != null) && (edgeGeom instanceof LineString)) {
          otherEdges.add((LineString) edgeGeom);
        }
      } // end else: sFrom && sTo != null
    } // end for loop over edges
    walkShedEdges.addAll(borderEdges);
    this.debugGeoms.addAll(uShapes);
    LOG.debug("number of detected u-shapes/crescents: " + uShapes.size());
    return walkShedEdges;
  }