Search in sources :

Example 41 with Envelope

use of com.vividsolutions.jts.geom.Envelope in project polymap4-core by Polymap4.

the class MapViewer method handleEvent.

@Override
public void handleEvent(OlEvent ev) {
    JSONArray extent = ev.properties().optJSONArray("extent");
    if (extent != null) {
        Envelope envelope = new Envelope(extent.getDouble(0), extent.getDouble(2), extent.getDouble(1), extent.getDouble(3));
        // bypass concern, prevent loop
        this.mapExtent.info().setRawValue(envelope);
    }
    Double newResolution = ev.properties().optDouble("resolution");
    if (newResolution != null) {
        this.resolution.info().setRawValue(newResolution.floatValue());
    }
}
Also used : JSONArray(org.json.JSONArray) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) Envelope(com.vividsolutions.jts.geom.Envelope)

Example 42 with Envelope

use of com.vividsolutions.jts.geom.Envelope in project polymap4-core by Polymap4.

the class GeometryValueCoder method encode.

public boolean encode(Document doc, String key, Object value, boolean indexed) {
    if (value instanceof Geometry) {
        Geometry geom = (Geometry) value;
        // store geom -> WKT, JSON, ...
        byte[] out = encode(geom);
        Field field = (Field) doc.getFieldable(key);
        if (field != null) {
            field.setValue(out);
        } else {
            doc.add(new Field(key, out));
        }
        // store bbox
        Envelope envelop = geom.getEnvelopeInternal();
        numeric.encode(doc, key + FIELD_MAXX, envelop.getMaxX(), true, true);
        numeric.encode(doc, key + FIELD_MAXY, envelop.getMaxY(), true, true);
        numeric.encode(doc, key + FIELD_MINX, envelop.getMinX(), true, true);
        numeric.encode(doc, key + FIELD_MINY, envelop.getMinY(), true, true);
        return true;
    } else {
        return false;
    }
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) Field(org.apache.lucene.document.Field) NumericField(org.apache.lucene.document.NumericField) Envelope(com.vividsolutions.jts.geom.Envelope)

Example 43 with Envelope

use of com.vividsolutions.jts.geom.Envelope in project OpenTripPlanner by opentripplanner.

the class StreetVertexIndexServiceImpl method getEdgesForEnvelope.

@SuppressWarnings("unchecked")
@Override
public Collection<Edge> getEdgesForEnvelope(Envelope envelope) {
    List<Edge> edges = edgeTree.query(envelope);
    for (Iterator<Edge> ie = edges.iterator(); ie.hasNext(); ) {
        Edge e = ie.next();
        Envelope eenv = e.getGeometry().getEnvelopeInternal();
        // Envelope eenv = e.getEnvelope();
        if (!envelope.intersects(eenv))
            ie.remove();
    }
    return edges;
}
Also used : Envelope(com.vividsolutions.jts.geom.Envelope) Edge(org.opentripplanner.routing.graph.Edge)

Example 44 with Envelope

use of com.vividsolutions.jts.geom.Envelope in project OpenTripPlanner by opentripplanner.

the class SimpleStreetSplitter method link.

/**
 * Link this vertex into the graph
 */
public boolean link(Vertex vertex, TraverseMode traverseMode, RoutingRequest options) {
    // find nearby street edges
    // TODO: we used to use an expanding-envelope search, which is more efficient in
    // dense areas. but first let's see how inefficient this is. I suspect it's not too
    // bad and the gains in simplicity are considerable.
    final double radiusDeg = SphericalDistanceLibrary.metersToDegrees(MAX_SEARCH_RADIUS_METERS);
    Envelope env = new Envelope(vertex.getCoordinate());
    // Perform a simple local equirectangular projection, so distances are expressed in degrees latitude.
    final double xscale = Math.cos(vertex.getLat() * Math.PI / 180);
    // Expand more in the longitude direction than the latitude direction to account for converging meridians.
    env.expandBy(radiusDeg / xscale, radiusDeg);
    final double DUPLICATE_WAY_EPSILON_DEGREES = SphericalDistanceLibrary.metersToDegrees(DUPLICATE_WAY_EPSILON_METERS);
    final TraverseModeSet traverseModeSet;
    if (traverseMode == TraverseMode.BICYCLE) {
        traverseModeSet = new TraverseModeSet(traverseMode, TraverseMode.WALK);
    } else {
        traverseModeSet = new TraverseModeSet(traverseMode);
    }
    // We sort the list of candidate edges by distance to the stop
    // This should remove any issues with things coming out of the spatial index in different orders
    // Then we link to everything that is within DUPLICATE_WAY_EPSILON_METERS of of the best distance
    // so that we capture back edges and duplicate ways.
    List<StreetEdge> candidateEdges = idx.query(env).stream().filter(streetEdge -> streetEdge instanceof StreetEdge).map(edge -> (StreetEdge) edge).filter(edge -> edge.canTraverse(traverseModeSet) && // only link to edges still in the graph.
    edge.getToVertex().getIncoming().contains(edge)).collect(Collectors.toList());
    // Make a map of distances to all edges.
    final TIntDoubleMap distances = new TIntDoubleHashMap();
    for (StreetEdge e : candidateEdges) {
        distances.put(e.getId(), distance(vertex, e, xscale));
    }
    // Sort the list.
    Collections.sort(candidateEdges, (o1, o2) -> {
        double diff = distances.get(o1.getId()) - distances.get(o2.getId());
        // A Comparator must return an integer but our distances are doubles.
        if (diff < 0)
            return -1;
        if (diff > 0)
            return 1;
        return 0;
    });
    // find the closest candidate edges
    if (candidateEdges.isEmpty() || distances.get(candidateEdges.get(0).getId()) > radiusDeg) {
        // We only link to stops if we are searching for origin/destination and for that we need transitStopIndex.
        if (destructiveSplitting || transitStopIndex == null) {
            return false;
        }
        LOG.debug("No street edge was found for {}", vertex);
        // We search for closest stops (since this is only used in origin/destination linking if no edges were found)
        // in the same way the closest edges are found.
        List<TransitStop> candidateStops = new ArrayList<>();
        transitStopIndex.query(env).forEach(candidateStop -> candidateStops.add((TransitStop) candidateStop));
        final TIntDoubleMap stopDistances = new TIntDoubleHashMap();
        for (TransitStop t : candidateStops) {
            stopDistances.put(t.getIndex(), distance(vertex, t, xscale));
        }
        Collections.sort(candidateStops, (o1, o2) -> {
            double diff = stopDistances.get(o1.getIndex()) - stopDistances.get(o2.getIndex());
            if (diff < 0) {
                return -1;
            }
            if (diff > 0) {
                return 1;
            }
            return 0;
        });
        if (candidateStops.isEmpty() || stopDistances.get(candidateStops.get(0).getIndex()) > radiusDeg) {
            LOG.debug("Stops aren't close either!");
            return false;
        } else {
            List<TransitStop> bestStops = Lists.newArrayList();
            // Add stops until there is a break of epsilon meters.
            // we do this to enforce determinism. if there are a lot of stops that are all extremely close to each other,
            // we want to be sure that we deterministically link to the same ones every time. Any hard cutoff means things can
            // fall just inside or beyond the cutoff depending on floating-point operations.
            int i = 0;
            do {
                bestStops.add(candidateStops.get(i++));
            } while (i < candidateStops.size() && stopDistances.get(candidateStops.get(i).getIndex()) - stopDistances.get(candidateStops.get(i - 1).getIndex()) < DUPLICATE_WAY_EPSILON_DEGREES);
            for (TransitStop stop : bestStops) {
                LOG.debug("Linking vertex to stop: {}", stop.getName());
                makeTemporaryEdges((TemporaryStreetLocation) vertex, stop);
            }
            return true;
        }
    } else {
        // find the best edges
        List<StreetEdge> bestEdges = Lists.newArrayList();
        // add edges until there is a break of epsilon meters.
        // we do this to enforce determinism. if there are a lot of edges that are all extremely close to each other,
        // we want to be sure that we deterministically link to the same ones every time. Any hard cutoff means things can
        // fall just inside or beyond the cutoff depending on floating-point operations.
        int i = 0;
        do {
            bestEdges.add(candidateEdges.get(i++));
        } while (i < candidateEdges.size() && distances.get(candidateEdges.get(i).getId()) - distances.get(candidateEdges.get(i - 1).getId()) < DUPLICATE_WAY_EPSILON_DEGREES);
        for (StreetEdge edge : bestEdges) {
            link(vertex, edge, xscale, options);
        }
        // Warn if a linkage was made, but the linkage was suspiciously long.
        if (vertex instanceof TransitStop) {
            double distanceDegreesLatitude = distances.get(candidateEdges.get(0).getId());
            int distanceMeters = (int) SphericalDistanceLibrary.degreesLatitudeToMeters(distanceDegreesLatitude);
            if (distanceMeters > WARNING_DISTANCE_METERS) {
                // Registering an annotation but not logging because tests produce thousands of these warnings.
                graph.addBuilderAnnotation(new StopLinkedTooFar((TransitStop) vertex, distanceMeters));
            }
        }
        return true;
    }
}
Also used : P2(org.opentripplanner.common.model.P2) Iterables(com.google.common.collect.Iterables) TemporarySplitterVertex(org.opentripplanner.routing.vertextype.TemporarySplitterVertex) TemporaryFreeEdge(org.opentripplanner.routing.edgetype.TemporaryFreeEdge) TemporaryVertex(org.opentripplanner.routing.vertextype.TemporaryVertex) LocationIndexedLine(com.vividsolutions.jts.linearref.LocationIndexedLine) LoggerFactory(org.slf4j.LoggerFactory) StreetEdge(org.opentripplanner.routing.edgetype.StreetEdge) TransitStop(org.opentripplanner.routing.vertextype.TransitStop) SphericalDistanceLibrary(org.opentripplanner.common.geometry.SphericalDistanceLibrary) TemporaryStreetLocation(org.opentripplanner.routing.location.TemporaryStreetLocation) LineString(com.vividsolutions.jts.geom.LineString) NonLocalizedString(org.opentripplanner.util.NonLocalizedString) StopLinkedTooFar(org.opentripplanner.graph_builder.annotation.StopLinkedTooFar) SplitterVertex(org.opentripplanner.routing.vertextype.SplitterVertex) ArrayList(java.util.ArrayList) StopUnlinked(org.opentripplanner.graph_builder.annotation.StopUnlinked) StreetTransitLink(org.opentripplanner.routing.edgetype.StreetTransitLink) Graph(org.opentripplanner.routing.graph.Graph) BikeRentalStationVertex(org.opentripplanner.routing.vertextype.BikeRentalStationVertex) GenericLocation(org.opentripplanner.common.model.GenericLocation) SpatialIndex(com.vividsolutions.jts.index.SpatialIndex) TraverseMode(org.opentripplanner.routing.core.TraverseMode) Lists(jersey.repackaged.com.google.common.collect.Lists) HashGridSpatialIndex(org.opentripplanner.common.geometry.HashGridSpatialIndex) Coordinate(com.vividsolutions.jts.geom.Coordinate) Logger(org.slf4j.Logger) Envelope(com.vividsolutions.jts.geom.Envelope) Vertex(org.opentripplanner.routing.graph.Vertex) StreetBikeRentalLink(org.opentripplanner.routing.edgetype.StreetBikeRentalLink) TIntDoubleHashMap(gnu.trove.map.hash.TIntDoubleHashMap) BikeParkUnlinked(org.opentripplanner.graph_builder.annotation.BikeParkUnlinked) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) TraverseModeSet(org.opentripplanner.routing.core.TraverseModeSet) StreetBikeParkLink(org.opentripplanner.routing.edgetype.StreetBikeParkLink) StreetVertex(org.opentripplanner.routing.vertextype.StreetVertex) GeometryUtils(org.opentripplanner.common.geometry.GeometryUtils) List(java.util.List) TIntDoubleMap(gnu.trove.map.TIntDoubleMap) BikeRentalStationUnlinked(org.opentripplanner.graph_builder.annotation.BikeRentalStationUnlinked) GeometryFactory(com.vividsolutions.jts.geom.GeometryFactory) LinearLocation(com.vividsolutions.jts.linearref.LinearLocation) BikeParkVertex(org.opentripplanner.routing.vertextype.BikeParkVertex) RoutingRequest(org.opentripplanner.routing.core.RoutingRequest) Collections(java.util.Collections) Edge(org.opentripplanner.routing.graph.Edge) TransitStop(org.opentripplanner.routing.vertextype.TransitStop) TIntDoubleMap(gnu.trove.map.TIntDoubleMap) ArrayList(java.util.ArrayList) TraverseModeSet(org.opentripplanner.routing.core.TraverseModeSet) StreetEdge(org.opentripplanner.routing.edgetype.StreetEdge) StopLinkedTooFar(org.opentripplanner.graph_builder.annotation.StopLinkedTooFar) Envelope(com.vividsolutions.jts.geom.Envelope) TIntDoubleHashMap(gnu.trove.map.hash.TIntDoubleHashMap)

Example 45 with Envelope

use of com.vividsolutions.jts.geom.Envelope in project OpenTripPlanner by opentripplanner.

the class StreetMatcher method match.

@SuppressWarnings("unchecked")
public List<Edge> match(Geometry routeGeometry) {
    routeGeometry = removeDuplicatePoints(routeGeometry);
    if (routeGeometry == null)
        return null;
    routeGeometry = DouglasPeuckerSimplifier.simplify(routeGeometry, 0.00001);
    // initial state: start midway along a block.
    LocationIndexedLine indexedLine = new LocationIndexedLine(routeGeometry);
    LinearLocation startIndex = indexedLine.getStartIndex();
    Coordinate routeStartCoordinate = startIndex.getCoordinate(routeGeometry);
    Envelope envelope = new Envelope(routeStartCoordinate);
    double distanceThreshold = DISTANCE_THRESHOLD;
    envelope.expandBy(distanceThreshold);
    BinHeap<MatchState> states = new BinHeap<MatchState>();
    List<Edge> nearbyEdges = index.query(envelope);
    while (nearbyEdges.isEmpty()) {
        envelope.expandBy(distanceThreshold);
        distanceThreshold *= 2;
        nearbyEdges = index.query(envelope);
    }
    // compute initial states
    for (Edge initialEdge : nearbyEdges) {
        Geometry edgeGeometry = initialEdge.getGeometry();
        LocationIndexedLine indexedEdge = new LocationIndexedLine(edgeGeometry);
        LinearLocation initialLocation = indexedEdge.project(routeStartCoordinate);
        double error = MatchState.distance(initialLocation.getCoordinate(edgeGeometry), routeStartCoordinate);
        MidblockMatchState state = new MidblockMatchState(null, routeGeometry, initialEdge, startIndex, initialLocation, error, 0.01);
        // make sure all initial states are visited by inserting them at 0
        states.insert(state, 0);
    }
    // search for best-matching path
    int seen_count = 0, total = 0;
    HashSet<MatchState> seen = new HashSet<MatchState>();
    while (!states.empty()) {
        double k = states.peek_min_key();
        MatchState state = states.extract_min();
        if (++total % 50000 == 0) {
            log.debug("seen / total: " + seen_count + " / " + total);
        }
        if (seen.contains(state)) {
            ++seen_count;
            continue;
        } else {
            if (k != 0) {
                // but do not mark states as closed if we start at them
                seen.add(state);
            }
        }
        if (state instanceof EndMatchState) {
            return toEdgeList(state);
        }
        for (MatchState next : state.getNextStates()) {
            if (seen.contains(next)) {
                continue;
            }
            states.insert(next, next.getTotalError() - next.getDistanceAlongRoute());
        }
    }
    return null;
}
Also used : LocationIndexedLine(com.vividsolutions.jts.linearref.LocationIndexedLine) LinearLocation(com.vividsolutions.jts.linearref.LinearLocation) BinHeap(org.opentripplanner.common.pqueue.BinHeap) Envelope(com.vividsolutions.jts.geom.Envelope) Geometry(com.vividsolutions.jts.geom.Geometry) Coordinate(com.vividsolutions.jts.geom.Coordinate) StreetEdge(org.opentripplanner.routing.edgetype.StreetEdge) Edge(org.opentripplanner.routing.graph.Edge) HashSet(java.util.HashSet)

Aggregations

Envelope (com.vividsolutions.jts.geom.Envelope)111 Coordinate (com.vividsolutions.jts.geom.Coordinate)21 Node (org.locationtech.geogig.api.Node)16 Geometry (com.vividsolutions.jts.geom.Geometry)13 ObjectId (org.locationtech.geogig.api.ObjectId)13 ReferencedEnvelope (org.geotools.geometry.jts.ReferencedEnvelope)12 STRtree (com.vividsolutions.jts.index.strtree.STRtree)11 ArrayList (java.util.ArrayList)11 Vertex (org.opentripplanner.routing.graph.Vertex)11 Test (org.junit.Test)9 NodeRef (org.locationtech.geogig.api.NodeRef)9 Edge (org.opentripplanner.routing.graph.Edge)9 LineString (com.vividsolutions.jts.geom.LineString)8 RevTree (org.locationtech.geogig.api.RevTree)8 TransitStop (org.opentripplanner.routing.vertextype.TransitStop)7 Map (java.util.Map)6 RevFeatureType (org.locationtech.geogig.api.RevFeatureType)6 StreetEdge (org.opentripplanner.routing.edgetype.StreetEdge)6 RevFeature (org.locationtech.geogig.api.RevFeature)5 AgencyAndId (org.onebusaway.gtfs.model.AgencyAndId)5