Search in sources :

Example 1 with PointList

use of com.graphhopper.util.PointList in project graphhopper by graphhopper.

the class AbstractEdgeElevationInterpolator method interpolateElevationsOfPillarNodes.

private void interpolateElevationsOfPillarNodes() {
    final EdgeIterator edge = storage.getAllEdges();
    final NodeAccess nodeAccess = storage.getNodeAccess();
    while (edge.next()) {
        if (isInterpolatableEdge(edge)) {
            int firstNodeId = edge.getBaseNode();
            int secondNodeId = edge.getAdjNode();
            double lat0 = nodeAccess.getLat(firstNodeId);
            double lon0 = nodeAccess.getLon(firstNodeId);
            double ele0 = nodeAccess.getEle(firstNodeId);
            double lat1 = nodeAccess.getLat(secondNodeId);
            double lon1 = nodeAccess.getLon(secondNodeId);
            double ele1 = nodeAccess.getEle(secondNodeId);
            final PointList pointList = edge.fetchWayGeometry(0);
            final int count = pointList.size();
            for (int index = 0; index < count; index++) {
                double lat = pointList.getLat(index);
                double lon = pointList.getLon(index);
                double ele = elevationInterpolator.calculateElevationBasedOnTwoPoints(lat, lon, lat0, lon0, ele0, lat1, lon1, ele1);
                pointList.set(index, lat, lon, ele);
            }
            edge.setWayGeometry(pointList);
        }
    }
}
Also used : EdgeIterator(com.graphhopper.util.EdgeIterator) PointList(com.graphhopper.util.PointList) NodeAccess(com.graphhopper.storage.NodeAccess)

Example 2 with PointList

use of com.graphhopper.util.PointList in project graphhopper by graphhopper.

the class WebHelperTest method testDecode.

@Test
public void testDecode() throws Exception {
    PointList list = WebHelper.decodePolyline("_p~iF~ps|U", 1, false);
    assertEquals(Helper.createPointList(38.5, -120.2), list);
    list = WebHelper.decodePolyline("_p~iF~ps|U_ulLnnqC_mqNvxq`@", 3, false);
    assertEquals(Helper.createPointList(38.5, -120.2, 40.7, -120.95, 43.252, -126.453), list);
}
Also used : PointList(com.graphhopper.util.PointList) Test(org.junit.Test)

Example 3 with PointList

use of com.graphhopper.util.PointList in project graphhopper by graphhopper.

the class WebHelperTest method testDecode3D.

@Test
public void testDecode3D() throws Exception {
    PointList list = WebHelper.decodePolyline("_p~iF~ps|Uo}@", 1, true);
    assertEquals(Helper.createPointList3D(38.5, -120.2, 10), list);
    list = WebHelper.decodePolyline("_p~iF~ps|Uo}@_ulLnnqC_anF_mqNvxq`@?", 3, true);
    assertEquals(Helper.createPointList3D(38.5, -120.2, 10, 40.7, -120.95, 1234, 43.252, -126.453, 1234), list);
}
Also used : PointList(com.graphhopper.util.PointList) Test(org.junit.Test)

Example 4 with PointList

use of com.graphhopper.util.PointList in project graphhopper by graphhopper.

the class RealtimeFeed method fromProtobuf.

public static RealtimeFeed fromProtobuf(Graph graph, GtfsStorage staticGtfs, PtFlagEncoder encoder, GtfsRealtime.FeedMessage feedMessage) {
    String feedKey = "gtfs_0";
    GTFSFeed feed = staticGtfs.getGtfsFeeds().get(feedKey);
    // TODO: Require configuration of feed and agency this realtime feed is for.
    // Realtime feeds are always specific to an agency.
    Agency agency = feed.agency.values().iterator().next();
    final IntHashSet blockedEdges = new IntHashSet();
    final IntLongHashMap delaysForBoardEdges = new IntLongHashMap();
    final IntLongHashMap delaysForAlightEdges = new IntLongHashMap();
    final LinkedList<VirtualEdgeIteratorState> additionalEdges = new LinkedList<>();
    final Graph overlayGraph = new Graph() {

        int nNodes = 0;

        int firstEdge = graph.getAllEdges().getMaxId() + 1;

        final NodeAccess nodeAccess = new NodeAccess() {

            IntIntHashMap additionalNodeFields = new IntIntHashMap();

            @Override
            public int getAdditionalNodeField(int nodeId) {
                return 0;
            }

            @Override
            public void setAdditionalNodeField(int nodeId, int additionalValue) {
                additionalNodeFields.put(nodeId, additionalValue);
            }

            @Override
            public boolean is3D() {
                return false;
            }

            @Override
            public int getDimension() {
                return 0;
            }

            @Override
            public void ensureNode(int nodeId) {
            }

            @Override
            public void setNode(int nodeId, double lat, double lon) {
            }

            @Override
            public void setNode(int nodeId, double lat, double lon, double ele) {
            }

            @Override
            public double getLatitude(int nodeId) {
                return 0;
            }

            @Override
            public double getLat(int nodeId) {
                return 0;
            }

            @Override
            public double getLongitude(int nodeId) {
                return 0;
            }

            @Override
            public double getLon(int nodeId) {
                return 0;
            }

            @Override
            public double getElevation(int nodeId) {
                return 0;
            }

            @Override
            public double getEle(int nodeId) {
                return 0;
            }
        };

        @Override
        public Graph getBaseGraph() {
            return graph;
        }

        @Override
        public int getNodes() {
            return graph.getNodes() + nNodes;
        }

        @Override
        public NodeAccess getNodeAccess() {
            return nodeAccess;
        }

        @Override
        public BBox getBounds() {
            return null;
        }

        @Override
        public EdgeIteratorState edge(int a, int b) {
            return null;
        }

        @Override
        public EdgeIteratorState edge(int a, int b, double distance, boolean bothDirections) {
            int edge = firstEdge++;
            final VirtualEdgeIteratorState newEdge = new VirtualEdgeIteratorState(-1, edge, a, b, distance, 0, "", new PointList());
            final VirtualEdgeIteratorState reverseNewEdge = new VirtualEdgeIteratorState(-1, edge, b, a, distance, 0, "", new PointList());
            newEdge.setReverseEdge(reverseNewEdge);
            reverseNewEdge.setReverseEdge(newEdge);
            additionalEdges.push(newEdge);
            return newEdge;
        }

        @Override
        public EdgeIteratorState getEdgeIteratorState(int edgeId, int adjNode) {
            return null;
        }

        @Override
        public AllEdgesIterator getAllEdges() {
            return null;
        }

        @Override
        public EdgeExplorer createEdgeExplorer(EdgeFilter filter) {
            return null;
        }

        @Override
        public EdgeExplorer createEdgeExplorer() {
            return graph.createEdgeExplorer();
        }

        @Override
        public Graph copyTo(Graph g) {
            return null;
        }

        @Override
        public GraphExtension getExtension() {
            throw new RuntimeException();
        }
    };
    Map<Integer, String> routes = new HashMap<>();
    Map<GtfsStorage.Validity, Integer> operatingDayPatterns = new HashMap<>(staticGtfs.getOperatingDayPatterns());
    Map<Integer, byte[]> tripDescriptors = new HashMap<>();
    Map<Integer, Integer> stopSequences = new HashMap<>();
    Map<String, int[]> boardEdgesForTrip = new HashMap<>();
    Map<String, int[]> alightEdgesForTrip = new HashMap<>();
    Map<GtfsStorage.FeedIdWithTimezone, Integer> writableTimeZones = new HashMap<>();
    GtfsStorageI gtfsStorage = new GtfsStorageI() {

        @Override
        public Map<String, Fare> getFares() {
            return null;
        }

        @Override
        public Map<GtfsStorage.Validity, Integer> getOperatingDayPatterns() {
            return operatingDayPatterns;
        }

        @Override
        public Map<GtfsStorage.FeedIdWithTimezone, Integer> getWritableTimeZones() {
            return writableTimeZones;
        }

        @Override
        public Map<Integer, byte[]> getTripDescriptors() {
            return tripDescriptors;
        }

        @Override
        public Map<Integer, Integer> getStopSequences() {
            return stopSequences;
        }

        @Override
        public Map<String, int[]> getBoardEdgesForTrip() {
            return boardEdgesForTrip;
        }

        @Override
        public Map<String, int[]> getAlightEdgesForTrip() {
            return alightEdgesForTrip;
        }

        @Override
        public Map<String, GTFSFeed> getGtfsFeeds() {
            HashMap<String, GTFSFeed> stringGTFSFeedHashMap = new HashMap<>();
            stringGTFSFeedHashMap.put(feedKey, feed);
            return stringGTFSFeedHashMap;
        }

        @Override
        public Map<String, Transfers> getTransfers() {
            return staticGtfs.getTransfers();
        }

        @Override
        public Map<String, Integer> getStationNodes() {
            return staticGtfs.getStationNodes();
        }

        @Override
        public Map<Integer, String> getRoutes() {
            return routes;
        }
    };
    final GtfsReader gtfsReader = new GtfsReader(feedKey, overlayGraph, gtfsStorage, encoder, null);
    Instant timestamp = Instant.ofEpochSecond(feedMessage.getHeader().getTimestamp());
    // FIXME
    LocalDate dateToChange = timestamp.atZone(ZoneId.of(agency.agency_timezone)).toLocalDate();
    BitSet validOnDay = new BitSet();
    LocalDate startDate = feed.calculateStats().getStartDate();
    validOnDay.set((int) DAYS.between(startDate, dateToChange));
    feedMessage.getEntityList().stream().filter(GtfsRealtime.FeedEntity::hasTripUpdate).map(GtfsRealtime.FeedEntity::getTripUpdate).filter(tripUpdate -> tripUpdate.getTrip().getScheduleRelationship() == GtfsRealtime.TripDescriptor.ScheduleRelationship.SCHEDULED).forEach(tripUpdate -> {
        String key = GtfsStorage.tripKey(tripUpdate.getTrip().getTripId(), tripUpdate.getTrip().getStartTime());
        final int[] boardEdges = staticGtfs.getBoardEdgesForTrip().get(key);
        final int[] leaveEdges = staticGtfs.getAlightEdgesForTrip().get(key);
        if (boardEdges == null || leaveEdges == null) {
            logger.warn("Trip not found: {}", tripUpdate.getTrip());
            return;
        }
        tripUpdate.getStopTimeUpdateList().stream().filter(stopTimeUpdate -> stopTimeUpdate.getScheduleRelationship() == SKIPPED).mapToInt(GtfsRealtime.TripUpdate.StopTimeUpdate::getStopSequence).forEach(skippedStopSequenceNumber -> {
            blockedEdges.add(boardEdges[skippedStopSequenceNumber]);
            blockedEdges.add(leaveEdges[skippedStopSequenceNumber]);
        });
        GtfsReader.TripWithStopTimes tripWithStopTimes = toTripWithStopTimes(feed, agency, tripUpdate);
        tripWithStopTimes.stopTimes.forEach(stopTime -> {
            if (stopTime.stop_sequence > leaveEdges.length - 1) {
                logger.warn("Stop sequence number too high {} vs {}", stopTime.stop_sequence, leaveEdges.length);
                return;
            }
            final StopTime originalStopTime = feed.stop_times.get(new Fun.Tuple2(tripUpdate.getTrip().getTripId(), stopTime.stop_sequence));
            int arrivalDelay = stopTime.arrival_time - originalStopTime.arrival_time;
            delaysForAlightEdges.put(leaveEdges[stopTime.stop_sequence], arrivalDelay * 1000);
            int departureDelay = stopTime.departure_time - originalStopTime.departure_time;
            if (departureDelay > 0) {
                int boardEdge = boardEdges[stopTime.stop_sequence];
                int departureNode = graph.getEdgeIteratorState(boardEdge, Integer.MIN_VALUE).getAdjNode();
                int timeOffset = tripUpdate.getTrip().hasStartTime() ? LocalTime.parse(tripUpdate.getTrip().getStartTime()).toSecondOfDay() : 0;
                int delayedBoardEdge = gtfsReader.addDelayedBoardEdge(ZoneId.of(agency.agency_timezone), tripUpdate.getTrip(), stopTime.stop_sequence, stopTime.departure_time + timeOffset, departureNode, validOnDay);
                delaysForBoardEdges.put(delayedBoardEdge, departureDelay * 1000);
            }
        });
    });
    feedMessage.getEntityList().stream().filter(GtfsRealtime.FeedEntity::hasTripUpdate).map(GtfsRealtime.FeedEntity::getTripUpdate).filter(tripUpdate -> tripUpdate.getTrip().getScheduleRelationship() == GtfsRealtime.TripDescriptor.ScheduleRelationship.ADDED).forEach(tripUpdate -> {
        Trip trip = new Trip();
        trip.trip_id = tripUpdate.getTrip().getTripId();
        trip.route_id = tripUpdate.getTrip().getRouteId();
        final List<StopTime> stopTimes = tripUpdate.getStopTimeUpdateList().stream().map(stopTimeUpdate -> {
            final StopTime stopTime = new StopTime();
            stopTime.stop_sequence = stopTimeUpdate.getStopSequence();
            stopTime.stop_id = stopTimeUpdate.getStopId();
            stopTime.trip_id = trip.trip_id;
            final ZonedDateTime arrival_time = Instant.ofEpochSecond(stopTimeUpdate.getArrival().getTime()).atZone(ZoneId.of(agency.agency_timezone));
            stopTime.arrival_time = (int) Duration.between(arrival_time.truncatedTo(ChronoUnit.DAYS), arrival_time).getSeconds();
            final ZonedDateTime departure_time = Instant.ofEpochSecond(stopTimeUpdate.getArrival().getTime()).atZone(ZoneId.of(agency.agency_timezone));
            stopTime.departure_time = (int) Duration.between(departure_time.truncatedTo(ChronoUnit.DAYS), departure_time).getSeconds();
            return stopTime;
        }).collect(Collectors.toList());
        GtfsReader.TripWithStopTimes tripWithStopTimes = new GtfsReader.TripWithStopTimes(trip, stopTimes, validOnDay, Collections.emptySet(), Collections.emptySet());
        gtfsReader.addTrip(ZoneId.of(agency.agency_timezone), 0, new ArrayList<>(), tripWithStopTimes, tripUpdate.getTrip());
    });
    gtfsReader.wireUpStops();
    return new RealtimeFeed(staticGtfs, feed, agency, feedMessage, blockedEdges, delaysForBoardEdges, delaysForAlightEdges, additionalEdges, tripDescriptors, stopSequences, operatingDayPatterns);
}
Also used : EdgeFilter(com.graphhopper.routing.util.EdgeFilter) Fare(com.conveyal.gtfs.model.Fare) ZonedDateTime(java.time.ZonedDateTime) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) IntIntHashMap(com.carrotsearch.hppc.IntIntHashMap) EdgeExplorer(com.graphhopper.util.EdgeExplorer) Agency(com.conveyal.gtfs.model.Agency) NO_DATA(com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.NO_DATA) Duration(java.time.Duration) Map(java.util.Map) LocalTime(java.time.LocalTime) Graph(com.graphhopper.storage.Graph) StreamSupport(java.util.stream.StreamSupport) IntLongHashMap(com.carrotsearch.hppc.IntLongHashMap) LinkedList(java.util.LinkedList) VirtualEdgeIteratorState(com.graphhopper.routing.VirtualEdgeIteratorState) GtfsRealtime(com.google.transit.realtime.GtfsRealtime) Logger(org.slf4j.Logger) EdgeIteratorState(com.graphhopper.util.EdgeIteratorState) BBox(com.graphhopper.util.shapes.BBox) GTFSFeed(com.conveyal.gtfs.GTFSFeed) SKIPPED(com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.SKIPPED) IntHashSet(com.carrotsearch.hppc.IntHashSet) Set(java.util.Set) Instant(java.time.Instant) PointList(com.graphhopper.util.PointList) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) Fun(org.mapdb.Fun) DAYS(java.time.temporal.ChronoUnit.DAYS) List(java.util.List) ChronoUnit(java.time.temporal.ChronoUnit) NodeAccess(com.graphhopper.storage.NodeAccess) StopTime(com.conveyal.gtfs.model.StopTime) Trip(com.conveyal.gtfs.model.Trip) LocalDate(java.time.LocalDate) GraphExtension(com.graphhopper.storage.GraphExtension) Optional(java.util.Optional) BitSet(java.util.BitSet) Collections(java.util.Collections) AllEdgesIterator(com.graphhopper.routing.util.AllEdgesIterator) PointList(com.graphhopper.util.PointList) HashMap(java.util.HashMap) IntIntHashMap(com.carrotsearch.hppc.IntIntHashMap) IntLongHashMap(com.carrotsearch.hppc.IntLongHashMap) IntHashSet(com.carrotsearch.hppc.IntHashSet) LocalDate(java.time.LocalDate) IntLongHashMap(com.carrotsearch.hppc.IntLongHashMap) ZonedDateTime(java.time.ZonedDateTime) GTFSFeed(com.conveyal.gtfs.GTFSFeed) StopTime(com.conveyal.gtfs.model.StopTime) Instant(java.time.Instant) BitSet(java.util.BitSet) LinkedList(java.util.LinkedList) GtfsRealtime(com.google.transit.realtime.GtfsRealtime) Graph(com.graphhopper.storage.Graph) NodeAccess(com.graphhopper.storage.NodeAccess) IntIntHashMap(com.carrotsearch.hppc.IntIntHashMap) EdgeFilter(com.graphhopper.routing.util.EdgeFilter) Fun(org.mapdb.Fun) Trip(com.conveyal.gtfs.model.Trip) Agency(com.conveyal.gtfs.model.Agency) VirtualEdgeIteratorState(com.graphhopper.routing.VirtualEdgeIteratorState) Fare(com.conveyal.gtfs.model.Fare)

Example 5 with PointList

use of com.graphhopper.util.PointList in project graphhopper by graphhopper.

the class WebHelper method decodePolyline.

public static PointList decodePolyline(String encoded, int initCap, boolean is3D) {
    PointList poly = new PointList(initCap, is3D);
    int index = 0;
    int len = encoded.length();
    int lat = 0, lng = 0, ele = 0;
    while (index < len) {
        // latitude
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int deltaLatitude = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += deltaLatitude;
        // longitute
        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int deltaLongitude = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += deltaLongitude;
        if (is3D) {
            // elevation
            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int deltaElevation = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            ele += deltaElevation;
            poly.add((double) lat / 1e5, (double) lng / 1e5, (double) ele / 100);
        } else {
            poly.add((double) lat / 1e5, (double) lng / 1e5);
        }
    }
    return poly;
}
Also used : PointList(com.graphhopper.util.PointList)

Aggregations

PointList (com.graphhopper.util.PointList)22 Test (org.junit.Test)7 GHPoint (com.graphhopper.util.shapes.GHPoint)6 NodeAccess (com.graphhopper.storage.NodeAccess)5 ArrayList (java.util.ArrayList)3 PathWrapper (com.graphhopper.PathWrapper)2 EdgeIteratorState (com.graphhopper.util.EdgeIteratorState)2 BBox (com.graphhopper.util.shapes.BBox)2 GHPoint3D (com.graphhopper.util.shapes.GHPoint3D)2 IntHashSet (com.carrotsearch.hppc.IntHashSet)1 IntIntHashMap (com.carrotsearch.hppc.IntIntHashMap)1 IntLongHashMap (com.carrotsearch.hppc.IntLongHashMap)1 GTFSFeed (com.conveyal.gtfs.GTFSFeed)1 Agency (com.conveyal.gtfs.model.Agency)1 Fare (com.conveyal.gtfs.model.Fare)1 StopTime (com.conveyal.gtfs.model.StopTime)1 Trip (com.conveyal.gtfs.model.Trip)1 GtfsRealtime (com.google.transit.realtime.GtfsRealtime)1 NO_DATA (com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.NO_DATA)1 SKIPPED (com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.SKIPPED)1