Java Code Examples for org.matsim.api.core.v01.Coord

The following examples show how to use org.matsim.api.core.v01.Coord. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: pt2matsim   Source File: NetworkTools.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Looks for nodes within search radius of <tt>coord</tt> (using {@link NetworkUtils#getNearestNodes},
 * fetches all in- and outlinks and sorts them ascending by their
 * distance to the coordinates given. A map with the distance as key and a set as value is used
 * to (1) return the already calculated distance to the coord and (2) store two opposite links under
 * the same distance.
 *
 * @param network               The network
 * @param coord                 the coordinate from which the closest links are
 *                              to be searched
 * @param nodeSearchRadius      Only links from and to nodes within this radius are considered.
 * @param allowedTransportModes Only links with at least one of these transport modes are considered. All links are considered if <tt>null</tt>.
 */
 public static Map<Double, Set<Link>> findClosestLinks(Network network, Coord coord, double nodeSearchRadius, Set<String> allowedTransportModes) {
	 Collection<Node> nearestNodes = NetworkUtils.getNearestNodes(network, coord, nodeSearchRadius);
	 SortedMap<Double, Set<Link>> closestLinksSortedByDistance = new TreeMap<>();

	 if(nearestNodes.size() != 0) {
		 // fetch every in- and outlink of each node
		 HashSet<Link> links = new HashSet<>();
		 for(Node node : nearestNodes) {
			 links.addAll(node.getOutLinks().values());
			 links.addAll(node.getInLinks().values());
		 }

		 // calculate lineSegmentDistance for all links
		 for(Link link : links) {
			 // only use links with a viable network transport mode
			 if(allowedTransportModes == null || MiscUtils.collectionsShareMinOneStringEntry(link.getAllowedModes(), allowedTransportModes)) {
				 double lineSegmentDistance = CoordUtils.distancePointLinesegment(link.getFromNode().getCoord(), link.getToNode().getCoord(), coord);
				 MapUtils.getSet(lineSegmentDistance, closestLinksSortedByDistance).add(link);
			 }
		 }
	 }
	 return closestLinksSortedByDistance;
}
 
Example 2
Source Project: amodeus   Source File: VirtualNodeGeometry.java    License: GNU General Public License v2.0 6 votes vote down vote up
VirtualNodeGeometry(MatsimAmodeusDatabase db, VirtualNetwork<Link> virtualNetwork) {
    if (Objects.isNull(virtualNetwork)) {
        inverseArea = null;
        return;
    }
    inverseArea = Array.zeros(virtualNetwork.getVirtualNodes().size());
    for (VirtualNode<Link> virtualNode : virtualNetwork.getVirtualNodes()) {
        Tensor coords = Tensors.empty();
        for (Link link : virtualNode.getLinks()) {
            OsmLink osmLink = db.getOsmLink(link);
            Coord coord = osmLink.getAt(.5);
            coords.append(Tensors.vector(coord.getX(), coord.getY()));
        }
        Tensor hull = ConvexHull.of(coords);
        convexHulls.put(virtualNode, hull);

        Scalar area = PolygonArea.FUNCTION.apply(hull);
        if (Sign.isPositive(area))
            inverseArea.set(area.reciprocal(), virtualNode.getIndex());
        else
            System.out.println("area[" + virtualNode.getIndex() + "] = " + area);
    }
}
 
Example 3
Source Project: amodeus   Source File: VirtualNodeGeometry.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** @param amodeusComponent
 * @param hull
 * @return */
static Shape createShape(AmodeusComponent amodeusComponent, Tensor hull) {
    if (Tensors.isEmpty(hull))
        return new Ellipse2D.Double(0, 0, 0, 0);
    Path2D path2d = new Path2D.Double();
    boolean init = false;
    for (Tensor vector : hull) {
        Coord coord = TensorCoords.toCoord(vector);
        Point point = amodeusComponent.getMapPositionAlways(coord);
        if (!init) {
            init = true;
            path2d.moveTo(point.getX(), point.getY());
        } else
            path2d.lineTo(point.getX(), point.getY());
    }
    path2d.closePath();
    return path2d;
}
 
Example 4
Source Project: pt2matsim   Source File: GtfsShape.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adds a new point
 */
@Override
public void addPoint(Coord point, int pos) {
	Coord check = coordSorted.put(pos, point);

	if(check != null && (check.getX() != point.getX() || check.getY() != point.getY())) {
		throw new IllegalArgumentException("Sequence position " + pos + " already defined in shape " + id);
	}

	if(point.getX() < extentSWx) {
		extentSWx = point.getX();
	}
	if(point.getY() < extentSWy) {
		extentSWy = point.getY();
	}
	if(point.getX() > extentNEx) {
		extentNEx = point.getX();
	}
	if(point.getY() > extentNEy) {
		extentNEy = point.getY();
	}
}
 
Example 5
Source Project: pt2matsim   Source File: ShapeTools.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * @return all nodes within a buffer distance from the shape
 */
public static Collection<Node> getNodesWithinBuffer(Network network, RouteShape shape, double buffer) {
	Set<Node> nodesWithinBuffer = new HashSet<>();

	List<Coord> coords = shape.getCoords();

	for(int i = 0; i < coords.size() - 1; i++) {
		Coord current = coords.get(i);
		Coord next = coords.get(i + 1);

		double dist = 0;
		double delta = buffer / 2;
		double maxDist = CoordUtils.calcEuclideanDistance(current, next);
		double az = CoordTools.getAzimuth(current, next);
		do {
			nodesWithinBuffer.addAll(NetworkUtils.getNearestNodes(network, CoordTools.calcNewPoint(current, az, dist), buffer));
			dist += delta;
		} while(dist < maxDist);
	}
	nodesWithinBuffer.addAll(NetworkUtils.getNearestNodes(network, coords.get(coords.size() - 1), buffer));

	return nodesWithinBuffer;
}
 
Example 6
Source Project: pt2matsim   Source File: CoordToolsTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void calcNewPoint() {
	Coord newPointD = CoordTools.calcNewPoint(coordA, 0.00 * Math.PI, CoordUtils.calcEuclideanDistance(coordA, coordD));
	assertEquals(newPointD.getX(), coordD.getX(), testDelta);
	assertEquals(newPointD.getY(), coordD.getY(), testDelta);

	Coord newPointX = CoordTools.calcNewPoint(coordA, 0.25 * Math.PI, CoordUtils.calcEuclideanDistance(coordA, coordC));
	assertEquals(newPointX.getX(), coordC.getX(), testDelta);
	assertEquals(newPointX.getY(), coordC.getY(), testDelta);

	Coord duplicateCoordZ = CoordTools.calcNewPoint(coordA, CoordTools.getAzimuth(coordA, coordZ), CoordUtils.calcEuclideanDistance(coordA, coordZ));
	assertEquals(duplicateCoordZ.getX(), coordZ.getX(), testDelta);
	assertEquals(duplicateCoordZ.getY(), coordZ.getY(), testDelta);

	Coord newPointB = CoordTools.calcNewPoint(coordA, 0.50 * Math.PI, 20);
	assertEquals(newPointB.getX(), coordB.getX(), testDelta);
	assertEquals(newPointB.getY(), coordB.getY(), testDelta);

	Coord newPointG = CoordTools.calcNewPoint(coordA, 1.25*Math.PI, CoordUtils.calcEuclideanDistance(coordA, coordG));
	assertEquals(newPointG.getX(), coordG.getX(), testDelta);
	assertEquals(newPointG.getY(), coordG.getY(), testDelta);
}
 
Example 7
Source Project: pt2matsim   Source File: StopReader.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void createStops() throws IOException {
	log.info("  Read transit stops...");
		BufferedReader readsLines = new BufferedReader(new InputStreamReader(new FileInputStream(pathToBFKOORD_GEOFile), "utf-8"));
		String newLine = readsLines.readLine();
		while (newLine != null) {
			/*
			1−7 INT32 Nummer der Haltestelle
			9−18 FLOAT X-Koordinate
			20−29 FLOAT Y-Koordinate
			31−36 INT16 Z-Koordinate (Tunnel und andere Streckenelemente ohne eigentliche Haltestelle haben keine Z-Koordinate)
			38ff CHAR Kommentarzeichen "%"gefolgt vom Klartext des Haltestellennamens (optional zur besseren Lesbarkeit)
			 */
			Id<TransitStopFacility> stopId = Id.create(newLine.substring(0, 7), TransitStopFacility.class);
			double xCoord = Double.parseDouble(newLine.substring(8, 18));
			double yCoord = Double.parseDouble(newLine.substring(19, 29));
			Coord coord = new Coord(xCoord, yCoord);
			if (this.transformation != null) {
				coord = this.transformation.transform(coord);
			}
			String stopName = newLine.substring(39, newLine.length());
			createStop(stopId, coord, stopName);
			newLine = readsLines.readLine();
		}
		readsLines.close();
	log.info("  Read transit stops... done.");
}
 
Example 8
Source Project: pt2matsim   Source File: StopReader.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void createStop(Id<TransitStopFacility> stopId, Coord coord, String stopName) {

		//check if coordinates are already used by another facility
		String check = usedCoordinates.put(coord, stopName);
		if(check != null && !check.equals(stopName)) {
			if(check.contains(stopName) || stopName.contains(check)) {
				log.info("Two stop facilities at " + coord + " \"" + check + "\" & \"" + stopName + "\"");
			} else {
				log.warn("Two stop facilities at " + coord + " \"" + check + "\" & \"" + stopName + "\"");
			}
		}

		TransitStopFacility stopFacility = this.scheduleBuilder.createTransitStopFacility(stopId, coord, false);
		stopFacility.setName(stopName);
		this.schedule.addStopFacility(stopFacility);
	}
 
Example 9
Source Project: pt2matsim   Source File: Schedule2Geojson.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * @return the coordinates of the transit route
 */
private List<Coord> getCoordFromRoute(TransitRoute transitRoute) {
	List<Coord> coordList = new ArrayList<>();
	List<Id<Link>> linkIds = ScheduleTools.getTransitRouteLinkIds(transitRoute);

	if(linkIds.size() > 0) {
		for(Id<Link> linkId : linkIds) {
			if(network.getLinks().containsKey(linkId)) {
				Coord coord = network.getLinks().get(linkId).getFromNode().getCoord();
				coordList.add(ct.transform(coord));
			} else {
				throw new IllegalArgumentException("Link " + linkId + " not found in network");
			}
		}
		Coord finalCoord = network.getLinks().get(linkIds.get(linkIds.size() - 1)).getToNode().getCoord();
		coordList.add(ct.transform(finalCoord));
	}
	return coordList;
}
 
Example 10
Source Project: pt2matsim   Source File: ShapeTools.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Calculates the minimal distance from a link to a given routeShape.
 * Distances are calculated in intervals of 5 map units.
 *
 * @deprecated if one of the end nodes is on the shape, distance is 0 even if
 * the link is perpendicular.
 */
@Deprecated
public static double calcMinDistanceToShapeInterval(Link link, RouteShape shape) {
	double measureInterval = 5;

	double minDist = Double.MAX_VALUE;
	double lengthOnLink = 0;
	double azimuth = CoordTools.getAzimuth(link.getFromNode().getCoord(), link.getToNode().getCoord());
	double linkLength = CoordUtils.calcEuclideanDistance(link.getFromNode().getCoord(), link.getToNode().getCoord());

	while(lengthOnLink < linkLength) {
		Coord currentPoint = CoordTools.calcNewPoint(link.getFromNode().getCoord(), azimuth, lengthOnLink);

		// look for shortest distance to shape
		double dist = ShapeTools.calcMinDistanceToShape(currentPoint, shape);
		if(dist < minDist) {
			minDist = dist;
		}
		lengthOnLink += measureInterval;
	}
	return minDist;
}
 
Example 11
Source Project: pt2matsim   Source File: CoordTools.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Calculates the extent of the given network.
 * @return Array of Coords with the minimal South-West and the
 * 		   maximal North-East Coordinates
 */
public static Coord[] getExtent(Network network) {
	double maxE = 0;
	double maxN = 0;
	double minS = Double.MAX_VALUE;
	double minW = Double.MAX_VALUE;

	for(Node node : network.getNodes().values()) {
		if(node.getCoord().getX() > maxE) {
			maxE = node.getCoord().getX();
		}
		if(node.getCoord().getY() > maxN) {
			maxN = node.getCoord().getY();
		}
		if(node.getCoord().getX() < minW) {
			minW = node.getCoord().getX();
		}
		if(node.getCoord().getY() < minS) {
			minS = node.getCoord().getY();
		}
	}

	return new Coord[]{new Coord(minW, minS), new Coord(maxE, maxN)};
}
 
Example 12
Source Project: pt2matsim   Source File: GtfsFeedImplTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void stopsAndCoordsEqualAfterRetransform() {
	Map<String, Coord> stopCoords1 = cloneFeedStopCoords(feed);

	// transform
	feed.transform(TransformationFactory.CH1903_LV03_Plus);
	Map<String, Coord> stopCoords2 = cloneFeedStopCoords(feed);

	// check if coords have been transformed
	testCoordsEqual(stopCoords1, stopCoords2, false);

	// check if StopImpl is still equal for one example stop
	Stop testStop = feed.getStops().values().stream().findFirst().
			<Stop>map(s -> new StopImpl(s.getId(), s.getName(), s.getLon(), s.getLat(), s.getLocationType(), s.getParentStationId())).
			orElse(null);
	Assert.assertNotNull(testStop);
	Assert.assertEquals(testStop, feed.getStops().get(testStop.getId()));
	Assert.assertEquals(TransformationFactory.CH1903_LV03_Plus, feed.getCurrentCoordSystem());

	// retransform
	feed.transform(TransformationFactory.WGS84);
	Map<String, Coord> stopCoords3 = cloneFeedStopCoords(feed);
	// check if coords are equal again
	testCoordsEqual(stopCoords1, stopCoords3, true);
}
 
Example 13
Source Project: amodeus   Source File: Block.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** generates a new {@link Block}.
 * 
 * @param bounds defines the bounds of the Block
 * @param network is used to find the center LInk
 * @param id is the identifier for this Block
 * @param historicalDataTime Time over how long requests are stored. Is used for balance calculation
 * @param predictedTime what is the time for which the future requests are predicted. Normally this value should be in the order of the dispatch period */
Block(Rect bounds, Network network, int id, double historicalDataTime, double predictedTime) {
    this.bounds = bounds;
    this.id = id;
    Coord centerCoord = new Coord(bounds.centerX, bounds.centerY);
    centerLink = NetworkUtils.getNearestLink(network, centerCoord);
    this.predictionFraction = predictedTime / historicalDataTime;
}
 
Example 14
Source Project: pt2matsim   Source File: NetworkToolsTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void reduceSequencedLinks() {
	List<Link> seq = new ArrayList<>();
	seq.add(getLink("AH"));
	seq.add(getLink("HZ"));
	seq.add(getLink("ZI"));

	NetworkTools.reduceSequencedLinks(seq, new Coord(2600050.0, 1200035.0));
	Assert.assertEquals(1, seq.size());
	Assert.assertEquals("AH", seq.get(0).getId().toString());

	Collection<? extends Link> seqAll = new HashSet<>(network.getLinks().values());
	NetworkTools.reduceSequencedLinks(seqAll, new Coord(2600041.0, 1200042.0));
	Assert.assertEquals(10, network.getLinks().size()-seqAll.size());
}
 
Example 15
/**
 * creates a new stop facility and adds it to the schedule
 */
public TransitStopFacility createStopFacility(Id<TransitStopFacility> facilityId, Coord coord, String name, Id<Link> linkId) {
	TransitStopFacility newTransitStopFacility = scheduleFactory.createTransitStopFacility(facilityId, coord, false);
	newTransitStopFacility.setName(name);
	newTransitStopFacility.setLinkId(linkId);
	return newTransitStopFacility;
}
 
Example 16
Source Project: amodeus   Source File: ViewerConfig.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ViewerConfig update(AmodeusComponent amodeusComponent) {
    settings.zoom = amodeusComponent.getZoom();
    ICoordinate ic = amodeusComponent.getPosition();
    settings.coord = new Coord(ic.getLon(), ic.getLat());
    amodeusComponent.viewerLayers.forEach(viewerLayer -> viewerLayer.updateSettings(settings));
    return this;
}
 
Example 17
Source Project: pt2matsim   Source File: NetworkToolsTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void getNearestLink() {
	Coord testR = new Coord(2600041.0, 1200050.0);
	Coord testL = new Coord(2600039.0, 1200050.0);

	Node nearestNode = NetworkUtils.getNearestNode(network, testR);
	Assert.assertEquals("A", nearestNode.getId().toString());

	Assert.assertEquals("AD", NetworkTools.getNearestLink(network, testR, 4).getId().toString());
	Assert.assertEquals("DA", NetworkTools.getNearestLink(network, testL, 4).getId().toString());
}
 
Example 18
Source Project: pt2matsim   Source File: ShapeTools.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Calculates the minimal distance from a point to a given routeShape
 */
public static double calcMinDistanceToShape(Coord point, RouteShape shape) {
	List<Coord> shapePoints = new ArrayList<>(shape.getCoordsSorted().values());
	double minDist = Double.MAX_VALUE;
	// look for the minimal distance between the current point and all pairs of shape points
	for(int i = 0; i < shapePoints.size() - 1; i++) {
		double dist = CoordUtils.distancePointLinesegment(shapePoints.get(i), shapePoints.get(i + 1), point);
		if(dist < minDist) {
			minDist = dist;
		}
	}
	return minDist;
}
 
Example 19
Source Project: pt2matsim   Source File: NetworkToolsTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void findClosestLinks() {
	Node node = network.getNodes().get(Id.createNodeId("G"));
	Coord coordToLookFrom = new Coord(node.getCoord().getX() + 2, node.getCoord().getY() + 2);

	Map<Double, Set<Link>> cars = NetworkTools.findClosestLinks(network, coordToLookFrom, 3, Collections.singleton("car"));
	Assert.assertEquals(1, cars.keySet().size());
	Assert.assertEquals(4, cars.get(2.0).size());

	Map<Double, Set<Link>> nullTransportModes = NetworkTools.findClosestLinks(network, coordToLookFrom, 3, null);
	Assert.assertEquals(1, nullTransportModes.keySet().size());
	Assert.assertEquals(4, nullTransportModes.get(2.0).size());

}
 
Example 20
public Coord getCenter() {
    Tensor points = Tensor.of(getOsmLinks().stream() //
            .map(osmLink -> osmLink.getAt(.5)) //
            .map(TensorCoords::toTensor));
    // Tensor mean = Mean.of(points); // <- mean is fast but doesn't produce as good estimate as median
    Tensor median = TensorMap.of(Median::of, Transpose.of(points), 1);
    return TensorCoords.toCoord(median);
}
 
Example 21
private void removeVehicle(DvrpVehicle vehicle) {
    if (!availableVehicles.contains(vehicle)) {
        throw new IllegalStateException();
    }

    availableVehicles.remove(vehicle);
    Coord coord = vehicleLinks.remove(vehicle).getCoord();
    availableVehiclesTree.remove(coord.getX(), coord.getY(), vehicle);
}
 
Example 22
Source Project: pt2matsim   Source File: GtfsConverterTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void combineRoutes() {
	TransitSchedule test = ScheduleTools.createSchedule();
	TransitScheduleFactory f = test.getFactory();
	Id<TransitLine> lineId = Id.create("L", TransitLine.class);
	TransitLine line = f.createTransitLine(lineId);
	test.addTransitLine(line);

	Id<TransitStopFacility> stopId1 = Id.create("s1", TransitStopFacility.class);
	Id<TransitStopFacility> stopId2 = Id.create("s2", TransitStopFacility.class);
	Id<TransitStopFacility> stopId3 = Id.create("s3", TransitStopFacility.class);
	test.addStopFacility(f.createTransitStopFacility(stopId1, new Coord(1, 1), true));
	test.addStopFacility(f.createTransitStopFacility(stopId2, new Coord(2, 2), true));
	test.addStopFacility(f.createTransitStopFacility(stopId3, new Coord(3, 3), true));

	List<TransitRouteStop> routeStops1 = new LinkedList<>();
	List<TransitRouteStop> routeStops2 = new LinkedList<>();
	List<TransitRouteStop> routeStops3 = new LinkedList<>();
	int t = 0;
	for(TransitStopFacility stopFacility : test.getFacilities().values()) {
		routeStops1.add(f.createTransitRouteStop(stopFacility, t * 60, t * 60 + 30));
		routeStops2.add(f.createTransitRouteStop(stopFacility, t * 40, t * 40 + 10));
		routeStops3.add(f.createTransitRouteStop(stopFacility, t * 40, t * 40 + 10));
	}
	TransitRoute route1 = f.createTransitRoute(Id.create("R1", TransitRoute.class), null, routeStops1, "bus");
	route1.addDeparture(f.createDeparture(Id.create("dep1", Departure.class), 0.0));
	TransitRoute route2 = f.createTransitRoute(Id.create("R2", TransitRoute.class), null, routeStops2, "bus");
	route1.addDeparture(f.createDeparture(Id.create("dep2", Departure.class), 0.0));
	TransitRoute route3 = f.createTransitRoute(Id.create("R3", TransitRoute.class), null, routeStops3, "bus");
	route1.addDeparture(f.createDeparture(Id.create("dep3", Departure.class), 4200.0));
	line.addRoute(route1);
	line.addRoute(route2);
	line.addRoute(route3);

	Assert.assertEquals(3, line.getRoutes().size());
	// only routes with identical stop sequence (1, 2, 3) and departure sequence (2, 3) are combined.
	gtfsConverter.combineTransitRoutes(test);
	Assert.assertEquals(2, line.getRoutes().size());
}
 
Example 23
public void testSimple() {
    Collection<Coord> collection = new ArrayList<>();
    collection.add(new Coord(1, 0));
    collection.add(new Coord(1, 1));
    collection.add(new Coord(0, 1));
    collection.add(new Coord(0, 0));

    Tensor meanOf = SingleNodeVirtualNetworkCreator.meanOf(collection, SingleNodeVirtualNetworkCreatorTest::ofCoord);
    assertEquals(meanOf, Tensors.vector(0.5, 0.5));
}
 
Example 24
Source Project: amodeus   Source File: TensorCoordsTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testSimple() {
    Coord c = TensorCoords.toCoord(Tensors.vector(3, 8));
    assertEquals(c.getX(), 3.0);
    assertEquals(c.getY(), 8.0);
    Tensor v = TensorCoords.toTensor(c);
    assertEquals(v, Tensors.vector(3, 8));
}
 
Example 25
Source Project: amod   Source File: SocketPreparer.java    License: GNU General Public License v2.0 5 votes vote down vote up
public Tensor getBoundingBox() {
    /** send initial data (bounding box), {{minX, minY}, {maxX, maxY}} */
    double[] bbox = NetworkUtils.getBoundingBox(network.getNodes().values());

    return Tensors.of(TensorCoords.toTensor( //
            scenOpt.getLocationSpec().referenceFrame().coords_toWGS84().transform(new Coord(bbox[0], bbox[1]))), //
            TensorCoords.toTensor( //
                    scenOpt.getLocationSpec().referenceFrame().coords_toWGS84().transform(new Coord(bbox[2], bbox[3]))));
}
 
Example 26
/**
 * Looks for nodes within search radius of <tt>coord</tt> (using {@link NetworkUtils#getNearestNodes},
 * fetches all in- and outlinks and sorts them ascending by their
 * distance to the coordinates given.
 * <p/>
 * The method then returns all links within <tt>maxLinkDistance</tt> or <tt>maxNLinks</tt>*
 * whichever is reached earlier. Links with the same distance (i.e. opposite links) are always returned.
 * <p/>
 * * Note: maxNLinks is not a hard constraint. This method returns more than maxNLinks links if two links
 * have the same distance to the facility. It also returns more than maxNLinks if toleranceFactor is > 1.
 * <p/>
 * Distance Link to Coordinate is calculated using {@link CoordUtils#distancePointLinesegment}).
 *
 * The abort conditions are ordered as follows:
 * <ol>
 *     <li>distance > maxLinkCandidateDistance</li>
 *     <li>distance > (distance of the maxNLinks-th link * toleranceFactor)</li>
 * </ol>
 *
 * @return list of the closest links from coordinate <tt>coord</tt>.
 */
private List<Link> findClosestLinks(Coord coord, Set<String> networkModes) {
	List<Link> closestLinks = new ArrayList<>();
	Map<Double, Set<Link>> sortedLinks = NetworkTools.findClosestLinks(network, coord, nodeSearchRadius, networkModes);

	double distanceThreshold = this.maxDistance;
	int nLink = 0;

	for(Map.Entry<Double, Set<Link>> entry : sortedLinks.entrySet()) {
		double currentDistance = entry.getKey();
		double currentNLinks = entry.getValue().size();

		// if the distance is greater than the maximum distance
		if(currentDistance > maxDistance) {
			break;
		}

		// when the link count limit is reached, set the soft constraint distance
		if(nLink < this.nLinks && nLink + currentNLinks >= this.nLinks) {
			distanceThreshold = currentDistance * this.distanceMultiplier;
		}

		// check if distance is greater than soft constraint distance
		if(nLink + currentNLinks > this.nLinks && currentDistance > distanceThreshold) {
			break;
		}

		// if no loop break has been reached, add link to list
		closestLinks.addAll(entry.getValue());
		nLink += entry.getValue().size();
	}
	return closestLinks;
}
 
Example 27
Source Project: pt2matsim   Source File: GtfsFeedImplTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
private Map<String, Coord> cloneFeedStopCoords(GtfsFeed feed) {
	Map<String, Coord> cloned = new HashMap<>();
	for(Stop stop : feed.getStops().values()) {
		cloned.put(stop.getId(), new Coord(stop.getCoord().getX(), stop.getCoord().getY()));
	}
	return cloned;
}
 
Example 28
Source Project: pt2matsim   Source File: CoordTools.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Calculates a new Coordinate given the original point, azimuth and distance.
 */
public static Coord calcNewPoint(Coord fromPoint, double azimuth, double distance) {
	double dE = Math.sin(azimuth)*distance;
	double dN = Math.cos(azimuth)*distance;

	return new Coord(fromPoint.getX()+dE, fromPoint.getY()+dN);
}
 
Example 29
Source Project: pt2matsim   Source File: GeojsonTools.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static List<Coord> links2Coords(List<Link> links) {
	List<Coord> coords = new ArrayList<>();
	coords.add(links.get(0).getFromNode().getCoord());
	for(Link link : links) {
		coords.add(link.getToNode().getCoord());
	}
	return coords;
}
 
Example 30
Source Project: pt2matsim   Source File: ScheduleCleaner.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Cuts the schedule. All routes that pass stops within radius of center are kept
 */
public static void cutSchedule(TransitSchedule schedule, Coord center, double radius) {
	Set<Id<TransitStopFacility>> stopsInArea = new HashSet<>();
	for(TransitStopFacility stopFacility : schedule.getFacilities().values()) {
		if(CoordUtils.calcEuclideanDistance(center, stopFacility.getCoord()) <= radius) {
			stopsInArea.add(stopFacility.getId());
		}
	}
	cutSchedule(schedule, stopsInArea);
}