org.matsim.api.core.v01.network.Node Java Examples

The following examples show how to use org.matsim.api.core.v01.network.Node. 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 File: MatsimRectangleVirtualNetworkCreator.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
public static VirtualNetwork<Link> createVirtualNetwork( //
        Population population, Network network, boolean completeGraph, //
        int divLat, int divLng) {
    /** bounds */
    Tensor bounds = NetworkBounds.of(network);
    Tensor lbounds = bounds.get(0);
    Tensor ubounds = bounds.get(1);
    Tensor xBounds = Tensors.of(lbounds.Get(0), ubounds.Get(0));
    Tensor yBounds = Tensors.of(lbounds.Get(1), ubounds.Get(1));
    System.out.println("Network bounds:  " + xBounds + " , " + yBounds);

    /** u elements to determine neighbors */
    Map<Node, Set<Link>> uElements = NodeAdjacencyMap.of(network);

    @SuppressWarnings("unchecked")
    Collection<Link> elements = (Collection<Link>) network.getLinks().values();
    RectangleGridVirtualNetworkCreator<Link, Node> creator = //
            new RectangleGridVirtualNetworkCreator<>( //
                    elements, TensorLocation::of, NetworkCreatorUtils::linkToID, //
                    divLat, divLng, xBounds, yBounds, //
                    uElements, completeGraph);
    return creator.getVirtualNetwork();
}
 
Example #2
Source File: Network2ShapeFile.java    From pt2matsim with GNU General Public License v2.0 6 votes vote down vote up
public void convertNodes(String nodesOutputFile) {
	Collection<SimpleFeature> nodeFeatures = new ArrayList<>();
	PointFeatureFactory pointFeatureFactory = new PointFeatureFactory.Builder()
			.setName("nodes")
			.setCrs(MGC.getCRS(crs))
			.addAttribute("id", String.class)
			.addAttribute("inLinks", Double.class)
			.addAttribute("outLinks", Double.class)
			.create();

	for(Node node : network.getNodes().values()) {
		SimpleFeature f = pointFeatureFactory.createPoint(MGC.coord2Coordinate(node.getCoord()));
		f.setAttribute("id", node.getId());
		f.setAttribute("inLinks", node.getInLinks());
		f.setAttribute("outLinks", node.getOutLinks());
		nodeFeatures.add(f);
	}

	ShapeFileWriter.writeGeometries(nodeFeatures, nodesOutputFile);
}
 
Example #3
Source File: BasicScheduleEditor.java    From pt2matsim with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adds a link to the network. Uses the attributes (freespeed, nr of lanes, transportModes)
 * of the attributeLink.
 */
@Override
public void addLink(Id<Link> newLinkId, Id<Node> fromNodeId, Id<Node> toNodeId, Id<Link> attributeLinkId) {
	Node fromNode = network.getNodes().get(fromNodeId);
	Node toNode = network.getNodes().get(toNodeId);

	Link newLink = networkFactory.createLink(newLinkId, fromNode, toNode);

	if(attributeLinkId != null) {
		Link attributeLink = network.getLinks().get(attributeLinkId);

		newLink.setAllowedModes(attributeLink.getAllowedModes());
		newLink.setCapacity(attributeLink.getCapacity());
		newLink.setFreespeed(attributeLink.getFreespeed());
		newLink.setNumberOfLanes(attributeLink.getNumberOfLanes());
	}

	network.addLink(newLink);
}
 
Example #4
Source File: ShapeTools.java    From pt2matsim with 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 #5
Source File: Neighboring.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
public Neighboring(VirtualNetwork<Link> virtualNetwork, Network network) {
    neighbors = Array.zeros(virtualNetwork.getvNodesCount(), virtualNetwork.getvNodesCount());

    Map<Node, Set<Link>> uElements = network.getNodes().values().stream().collect(Collectors.toMap(n -> n, n -> new HashSet<>()));
    network.getLinks().values().stream().collect(Collectors.groupingBy(Link::getFromNode)).forEach((node, links) -> uElements.get(node).addAll(links));
    network.getLinks().values().stream().collect(Collectors.groupingBy(Link::getToNode)).forEach((node, links) -> uElements.get(node).addAll(links));

    GenericButterfliesAndRainbows<Link, Node> gbar = new GenericButterfliesAndRainbows<>();
    uElements.forEach((node, links) -> links.stream().map(virtualNetwork::getVirtualNode).forEach(vn -> gbar.add(node, vn)));

    Collection<IntPoint> collection = gbar.allPairs();

    System.out.println("collection.size " + collection.size());

    for (IntPoint point : collection) {
        System.out.println("point:  " + point);
        VirtualNode<Link> vNfrom = virtualNetwork.getVirtualNode(point.x);
        VirtualNode<Link> vNto = virtualNetwork.getVirtualNode(point.y);
        neighbors.set(RealScalar.ONE, vNfrom.getIndex(), vNto.getIndex());
    }
}
 
Example #6
Source File: PTMapperTools.java    From pt2matsim with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a node and dummy/loop link on the coordinate of the stop facility and
 * adds both to the network. The stop facility is NOT referenced.
 *
 * @return the new link or the existing link if it's already present in the network
 */
public static Link createArtificialStopFacilityLink(TransitStopFacility stopFacility, Network network, String prefix, double freespeed, Set<String> transportModes) {
	Id<Link> dummyLinkId = createArtificialLinkId(stopFacility);

	Link dummyLink = network.getLinks().get(dummyLinkId);
	if(dummyLink != null) {
		return dummyLink;
	} else {
		Node dummyNode = NetworkUtils.createNode(Id.createNodeId(prefix + stopFacility.getId()), stopFacility.getCoord());
		network.addNode(dummyNode);
		dummyLink = NetworkUtils.createLink(dummyLinkId, dummyNode, dummyNode, network, 10, freespeed, 9999, 1);
		dummyLink.setAllowedModes(transportModes);
		network.addLink(dummyLink);

		return dummyLink;
	}
}
 
Example #7
Source File: NetworkTools.java    From pt2matsim with 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 #8
Source File: CoordTools.java    From pt2matsim with 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 #9
Source File: ScheduleRoutersGtfsShapes.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
@Override
public LeastCostPathCalculator.Path calcLeastCostPath(Id<Node> fromNodeId, Id<Node> toNodeId, TransitLine transitLine, TransitRoute transitRoute) {
	Network n = networks.get(transitLine).get(transitRoute);
	if(n == null) return null;

	Node fromNode = n.getNodes().get(fromNodeId);
	Node toNode = n.getNodes().get(toNodeId);
	if(fromNode == null || toNode == null) return null;

	return pathCalculators.get(transitLine).get(transitRoute).calcPath(fromNode, toNode);
}
 
Example #10
Source File: MatsimRingCentroidVirtualNetworkCreator.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
public static VirtualNetwork<Link> createVirtualNetwork(Population population, Network network, int numVNodes, //
        boolean completeGraph) {
    @SuppressWarnings("unchecked")
    Collection<Link> elements = (Collection<Link>) network.getLinks().values();
    Map<Node, Set<Link>> uElements = NodeAdjacencyMap.of(network);

    /** generating centroids on a ring */
    List<Link> centroids = getRingCentroids(network, numVNodes);

    /** create the virtual network using the centroidvirtualNetworkCreator */
    CentroidVirtualNetworkCreator<Link, Node> vnc = new CentroidVirtualNetworkCreator<>(//
            elements, centroids, TensorLocation::of, NetworkCreatorUtils::linkToID, uElements, completeGraph);
    return vnc.getVirtualNetwork();
}
 
Example #11
Source File: ScheduleRoutersStandard.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
@Override
public LeastCostPathCalculator.Path calcLeastCostPath(Id<Node> fromNodeId, Id<Node> toNodeId, TransitLine transitLine, TransitRoute transitRoute) {
	Network n = networksByMode.get(transitRoute.getTransportMode());
	if(n == null) return null;

	Node fromNode = n.getNodes().get(fromNodeId);
	Node toNode = n.getNodes().get(toNodeId);
	if(fromNode == null || toNode == null) return null;

	return pathCalculatorsByMode.get(transitRoute.getTransportMode()).calcPath(fromNode, toNode);
}
 
Example #12
Source File: ScheduleRoutersOsmAttributes.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
@Override
public LeastCostPathCalculator.Path calcLeastCostPath(Id<Node> fromNodeId, Id<Node> toNodeId, TransitLine transitLine, TransitRoute transitRoute) {
    Network n = networksByMode.get(transitRoute.getTransportMode());
    Node fromNode = n.getNodes().get(fromNodeId);
    Node toNode = n.getNodes().get(toNodeId);

    if (fromNode != null && toNode != null) {
        return pathCalculatorsByMode.get(transitRoute.getTransportMode()).calcPath(fromNode, toNode);
    } else {
        return null;
    }
}
 
Example #13
Source File: LoopWarning.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
public LoopWarning(TransitLine transitLine, TransitRoute transitRoute, Node node, Link firstLoopLink, Link lastLoopLink) {
	super(Type.LoopWarning, transitLine, transitRoute);
	this.node = node;

	linkIdList = ScheduleTools.getLoopSubRouteLinkIds(transitRoute, firstLoopLink.getId(), lastLoopLink.getId());

	fromId = firstLoopLink.getId().toString();
	toId = lastLoopLink.getId().toString();
}
 
Example #14
Source File: PlausibilityCheck.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
public static void setLogLevels() {
	Logger.getLogger(MGC.class).setLevel(Level.ERROR);
	Logger.getLogger(MatsimFileTypeGuesser.class).setLevel(Level.ERROR);
	Logger.getLogger(Network.class).setLevel(Level.ERROR);
	Logger.getLogger(Node.class).setLevel(Level.ERROR);
	Logger.getLogger(Link.class).setLevel(Level.ERROR);
	Logger.getLogger(MatsimXmlParser.class).setLevel(Level.ERROR);
}
 
Example #15
Source File: NetworkTools.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the nearest link for the given coordinate.
 * Looks for nodes within search radius of coord (using {@link NetworkUtils#getNearestNodes},
 * fetches all in- and outlinks returns the link with the smallest distance
 * to the given coordinate. If there are two opposite links, the link with
 * the coordinate on its right side is returned.<p/>
 *
 * NOTE: In contrast to {@link NetworkUtils#getNearestLink}, this method looks for the
 * nearest link passing the coordinate from a reasonable set of nearby nodes instead
 * of the closest link originating from or ending in the closest node.
 *
 * @param network network
 * @param coord   the coordinate
 * @param nodeSearchRadius links from/to nodes within this radius are considered
 */
public static Link getNearestLink(Network network, Coord coord, double nodeSearchRadius) {
	Link closestLink = null;
	double minDistance = Double.MAX_VALUE;

	Collection<Node> nearestNodes = NetworkUtils.getNearestNodes(network, coord, nodeSearchRadius);

	while(nearestNodes.size() == 0) {
		nodeSearchRadius *= 2;
		nearestNodes = NetworkUtils.getNearestNodes(network, coord, nodeSearchRadius);
	}
	// check every in- and outlink of each node
	for(Node node : nearestNodes) {
		Set<Link> links = new HashSet<>(node.getOutLinks().values());
		links.addAll(node.getInLinks().values());
		double lineSegmentDistance;

		for(Link link : links) {
			// only use links with a viable network transport mode
			lineSegmentDistance = CoordUtils.distancePointLinesegment(link.getFromNode().getCoord(), link.getToNode().getCoord(), coord);

			if(lineSegmentDistance < minDistance) {
				minDistance = lineSegmentDistance;
				closestLink = link;
			}

		}
	}

	// check for opposite link
	Link oppositeLink = getOppositeLink(closestLink);
	if(oppositeLink != null && !coordIsOnRightSideOfLink(coord, closestLink)) {
		return oppositeLink;
	} else {
		return closestLink;
	}
}
 
Example #16
Source File: NetworkTools.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
public static void cutNetwork(Network network, Coord SW, Coord NE) {
	for(Node n : new HashSet<>(network.getNodes().values())) {
		if(!CoordTools.isInArea(n.getCoord(), SW, NE)) {
			network.removeNode(n.getId());
		}
	}
}
 
Example #17
Source File: NetworkTools.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes all nodes with no in- or outgoing links from a network
 */
public static void removeNotUsedNodes(Network network) {
	for(Node n : new HashSet<>(network.getNodes().values())) {
		if(n.getInLinks().size() == 0 && n.getOutLinks().size() == 0) {
			network.removeNode(n.getId());
		}
	}
}
 
Example #18
Source File: NetworkTools.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes all nodes that are not specified from the network
 */
public static void cutNetwork(Network network, Collection<Node> nodesToKeep) {
	for(Node n : new HashSet<>(network.getNodes().values())) {
		if(!nodesToKeep.contains(n)) {
			network.removeNode(n.getId());
		}
	}
}
 
Example #19
Source File: Network2Geojson.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
private void convertNodes() {
		for(Node node : network.getNodes().values()) {
			Feature f = GeojsonTools.createPointFeature(ct.transform(node.getCoord()));
			f.setProperty("id", node.getId().toString());
//			f.setProperty("inLinks", MiscUtils.collectionToString(node.getInLinks().values()));
//			f.setProperty("outLinks", MiscUtils.collectionToString(node.getOutLinks().values()));
			this.nodeFeatures.add(f);
		}
	}
 
Example #20
Source File: NetworkToolsTest.java    From pt2matsim with 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 #21
Source File: NetworkToolsTest.java    From pt2matsim with 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 #22
Source File: InteractionLinkData.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
public InteractionLinkData(Collection<Link> links) {
    Set<Node> nodes = new HashSet<>();
    nodes.addAll(links.stream().map(Link::getFromNode).collect(Collectors.toSet()));
    nodes.addAll(links.stream().map(Link::getToNode).collect(Collectors.toSet()));

    double[] bounds = NetworkUtils.getBoundingBox(nodes);
    this.index = new QuadTree<>(bounds[0], bounds[1], bounds[2], bounds[3]);

    links.stream().forEach(l -> index.put(l.getCoord().getX(), l.getCoord().getY(), l));
}
 
Example #23
Source File: DefaultParallelLeastCostPathCalculator.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Future<Path> calcLeastCostPath(Node fromNode, Node toNode, double starttime, Person person, Vehicle vehicle) {
    Future<Path> future = executor.submit(() -> {
        LeastCostPathCalculator calculator = calculators.take();
        Path path = calculator.calcLeastCostPath(fromNode, toNode, starttime, person, vehicle);
        calculators.put(calculator);
        return path;
    });

    // futures.add(future);
    return future;
}
 
Example #24
Source File: ArtificialLinkImpl.java    From pt2matsim with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Id<Node> getToNodeId() {
	return toNodeId;
}
 
Example #25
Source File: DefaultAStarLMRouter.java    From amodeus with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Future<Path> calcLeastCostPath(Node fromNode, Node toNode, double starttime, //
        Person person, Vehicle vehicle) {
    return delegate.calcLeastCostPath(fromNode, toNode, starttime, person, vehicle);
}
 
Example #26
Source File: NetworkDistanceFunction.java    From amodeus with GNU General Public License v2.0 4 votes vote down vote up
@Override
public final double getDistance(RoboTaxi roboTaxi, PassengerRequest avrequest) {
    Node from = roboTaxi.getDivertableLocation().getFromNode();
    Node to = avrequest.getFromLink().getFromNode();
    return distNetwork(from, to);
}
 
Example #27
Source File: ShapeToolsTest.java    From pt2matsim with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void getNodesWithinBuffer() {
	Collection<Node> nodes = ShapeTools.getNodesWithinBuffer(NetworkToolsTest.initNetwork(), shapeB, 1.0);
	Assert.assertEquals(9, nodes.size());
}
 
Example #28
Source File: NetworkDistanceFunction.java    From amodeus with GNU General Public License v2.0 4 votes vote down vote up
@Override
public final double getDistance(RoboTaxi roboTaxi, Link link) {
    Node from = roboTaxi.getDivertableLocation().getFromNode();
    Node to = link.getFromNode();
    return distNetwork(from, to);
}
 
Example #29
Source File: NetworkDistanceFunction.java    From amodeus with GNU General Public License v2.0 4 votes vote down vote up
@Override
public final double getDistance(Link link1, Link link2) {
    Node from = link1.getFromNode();
    Node to = link2.getFromNode();
    return distNetwork(from, to);
}
 
Example #30
Source File: NetworkDistanceFunction.java    From amodeus with GNU General Public License v2.0 4 votes vote down vote up
private double getTravelTime(Node from, Node to) {
    LeastCostPathCalculator.Path path = execPathCalculator(from, to);
    return path.travelTime;
}