org.matsim.core.network.NetworkUtils Java Examples

The following examples show how to use org.matsim.core.network.NetworkUtils. 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: 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 #2
Source File: FirstComeFirstServedStrategy.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
protected FirstComeFirstServedStrategy(Network network, //
        Config config, AmodeusModeConfig operatorConfig, //
        TravelTime travelTime, AmodeusRouter router, EventsManager eventsManager, MatsimAmodeusDatabase db) {
    super(config, operatorConfig, travelTime, router, eventsManager, db);

    double[] networkBounds = NetworkUtils.getBoundingBox(network.getNodes().values());
    this.unassignedRoboTaxis = new TreeMaintainer<>(networkBounds, this::getRoboTaxiLoc);
    this.unassignedRequests = new TreeMultipleItems<>(PassengerRequest::getSubmissionTime);
    this.requestsLastHour = new TreeMultipleItems<>(PassengerRequest::getSubmissionTime);

    FastAStarLandmarksFactory factory = new FastAStarLandmarksFactory(Runtime.getRuntime().availableProcessors());
    LeastCostPathCalculator calculator = EasyMinTimePathCalculator.prepPathCalculator(network, factory);
    timeDb = new CachedNetworkTimeDistance(calculator, MAXLAGTRAVELTIMECALCULATION, TimeDistanceProperty.INSTANCE);

    this.kockelmanRebalancing = new BlockRebalancing(network, timeDb, MINNUMBERROBOTAXISINBLOCKTOREBALANCE, BINSIZETRAVELDEMAND, dispatchPeriod, REBALANCINGGRIDDISTANCE);
}
 
Example #3
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 #4
Source File: ExtDemandSupplyBeamSharing.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
protected ExtDemandSupplyBeamSharing(Network network, //
        Config config, AmodeusModeConfig operatorConfig, //
        TravelTime travelTime, AmodeusRouter router, EventsManager eventsManager, //
        MatsimAmodeusDatabase db) {
    super(config, operatorConfig, travelTime, router, eventsManager, db);
    DispatcherConfigWrapper dispatcherConfig = DispatcherConfigWrapper.wrap(operatorConfig.getDispatcherConfig());
    dispatchPeriod = dispatcherConfig.getDispatchPeriod(60);
    SafeConfig safeConfig = SafeConfig.wrap(operatorConfig.getDispatcherConfig());
    sharingPeriod = safeConfig.getInteger("sharingPeriod", 10); // makes sense to choose this value similar to the pickup duration
    double rMax = safeConfig.getDouble("rMax", 1000.0);
    double phiMax = Pi.in(100).multiply(RealScalar.of(safeConfig.getDouble("phiMaxDeg", 5.0) / 180.0)).number().doubleValue();
    beamExtensionForSharing = new BeamExtensionForSharing(rMax, phiMax);
    double[] networkBounds = NetworkUtils.getBoundingBox(network.getNodes().values());
    this.requestMaintainer = new TreeMaintainer<>(networkBounds, this::getLocation);
    this.unassignedRoboTaxis = new TreeMaintainer<>(networkBounds, this::getRoboTaxiLoc);
}
 
Example #5
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 #6
Source File: RestrictedLinkCapacityDispatcher.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
protected RestrictedLinkCapacityDispatcher(Network network, //
        Config config, AmodeusModeConfig operatorConfig, //
        TravelTime travelTime, AmodeusRouter router, EventsManager eventsManager, //
        MatsimAmodeusDatabase db, ParkingStrategy parkingStrategy, //
        ParkingCapacity avSpatialCapacityAmodeus) {
    super(config, operatorConfig, travelTime, router, eventsManager, db);
    DispatcherConfigWrapper dispatcherConfig = DispatcherConfigWrapper.wrap(operatorConfig.getDispatcherConfig());
    dispatchPeriod = dispatcherConfig.getDispatchPeriod(60);
    SafeConfig safeConfig = SafeConfig.wrap(operatorConfig.getDispatcherConfig());
    sharingPeriod = safeConfig.getInteger("sharingPeriod", 10); // makes sense to choose this value similar to the pickup duration
    double rMax = safeConfig.getDouble("rMax", 1000.0);
    double phiMax = Pi.in(100).multiply(RealScalar.of(safeConfig.getDouble("phiMaxDeg", 5.0) / 180.0)).number().doubleValue();
    beamExtensionForSharing = new BeamExtensionForSharing(rMax, phiMax);
    this.networkBounds = NetworkUtils.getBoundingBox(network.getNodes().values());
    this.requestMaintainer = new TreeMaintainer<>(networkBounds, this::getLocation);

    /** PARKING EXTENSION */
    this.parkingStrategy = parkingStrategy;
    DistanceHeuristics distanceHeuristics = //
            dispatcherConfig.getDistanceHeuristics(DistanceHeuristics.ASTARLANDMARKS);
    this.parkingStrategy.setRuntimeParameters(avSpatialCapacityAmodeus, network, distanceHeuristics.getDistanceFunction(network));
    /** PARKING EXTENSION */
}
 
Example #7
Source File: StandardMATSimScenarioTest.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
private static void fixInvalidActivityLocations(Network network, Population population) {
    // In the test fixture there are agents who start and end activities on non-car links. This should not be happen and is fixed here.

    Network roadNetwork = NetworkUtils.createNetwork();
    new TransportModeNetworkFilter(network).filter(roadNetwork, Collections.singleton("car"));

    for (Person person : population.getPersons().values())
        for (Plan plan : person.getPlans())
            for (PlanElement element : plan.getPlanElements())
                if (element instanceof Activity) {
                    Activity activity = (Activity) element;

                    Link link = network.getLinks().get(activity.getLinkId());

                    if (!link.getAllowedModes().contains("car")) {
                        link = NetworkUtils.getNearestLink(roadNetwork, link.getCoord());
                        activity.setLinkId(link.getId());
                    }
                }
}
 
Example #8
Source File: RunVehicleAnalysis.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
static public void main(String[] args) throws ConfigurationException, IOException {
    CommandLine cmd = new CommandLine.Builder(args) //
            .requireOptions("events-path", "network-path", "movements-output-path", "activities-output-path") //
            .build();

    String eventsPath = cmd.getOptionStrict("events-path");
    String networkPath = cmd.getOptionStrict("network-path");
    String movementsOutputPath = cmd.getOptionStrict("movements-output-path");
    String activitiesOutputPath = cmd.getOptionStrict("activities-output-path");

    Network network = NetworkUtils.createNetwork();
    new MatsimNetworkReader(network).readFile(networkPath);

    LinkFinder linkFinder = new LinkFinder(network);
    VehicleAnalysisListener listener = new VehicleAnalysisListener(linkFinder);

    EventsManager eventsManager = EventsUtils.createEventsManager();
    eventsManager.addHandler(listener);
    new MatsimEventsReader(eventsManager).readFile(eventsPath);

    new VehicleAnalysisWriter(listener).writeMovements(new File(movementsOutputPath));
    new VehicleAnalysisWriter(listener).writeActivities(new File(activitiesOutputPath));
}
 
Example #9
Source File: RunPassengerAnalysis.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
static public void main(String[] args) throws ConfigurationException, IOException {
    CommandLine cmd = new CommandLine.Builder(args) //
            .requireOptions("events-path", "network-path", "output-path", "modes") //
            .build();

    String eventsPath = cmd.getOptionStrict("events-path");
    String networkPath = cmd.getOptionStrict("network-path");
    String outputPath = cmd.getOptionStrict("output-path");

    String rawModes = cmd.getOptionStrict("modes");
    Set<String> modes = Arrays.asList(rawModes.split(",")).stream().map(String::trim).collect(Collectors.toSet());

    Network network = NetworkUtils.createNetwork();
    new MatsimNetworkReader(network).readFile(networkPath);

    LinkFinder linkFinder = new LinkFinder(network);
    PassengerAnalysisListener listener = new PassengerAnalysisListener(modes, linkFinder);

    EventsManager eventsManager = EventsUtils.createEventsManager();
    eventsManager.addHandler(listener);
    new MatsimEventsReader(eventsManager).readFile(eventsPath);

    new PassengerAnalysisWriter(listener).writeRides(new File(outputPath));
}
 
Example #10
Source File: MatsimRingCentroidVirtualNetworkCreator.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
private static List<Link> getRingCentroids(Network network, int numVNodes) {
    List<Link> centroids = new ArrayList<>();
    double[] bounds = NetworkUtils.getBoundingBox(network.getNodes().values()); // minX, minY, maxX, maxY
    QuadTree<Link> quadTree = FastQuadTree.of(network);

    // center location
    double centerX = bounds[0] + 0.5 * (bounds[2] - bounds[0]);
    double centerY = bounds[1] + 0.5 * (bounds[3] - bounds[1]);

    double radius = 0.5 * Math.min(bounds[2] - bounds[0], bounds[3] - bounds[1]);
    centroids.add(quadTree.getClosest(centerX, centerY));

    for (int count = 1; count < numVNodes; ++count) {
        double arg = count / (numVNodes - 1.0) * 2 * Math.PI;
        double posX = centerX + radius * Math.cos(arg);
        double posY = centerY + radius * Math.sin(arg);
        Link closest = quadTree.getClosest(posX, posY);
        centroids.add(closest);
    }
    GlobalAssert.that(centroids.size() == numVNodes);
    return centroids;
}
 
Example #11
Source File: MultiODHeuristic.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
public MultiODHeuristic(String mode, EventsManager eventsManager, Network network, AggregateRideAppender appender, FactorTravelTimeEstimator estimator,
        double replanningInterval, long numberOfSeats) {
    this.mode = mode;
    this.eventsManager = eventsManager;
    this.appender = appender;
    this.estimator = estimator;
    this.replanningInterval = replanningInterval;
    this.numberOfSeats = numberOfSeats;

    double[] bounds = NetworkUtils.getBoundingBox(network.getNodes().values()); // minx, miny, maxx, maxy

    availableVehiclesTree = new QuadTree<>(bounds[0], bounds[1], bounds[2], bounds[3]);
    pendingRequestsTree = new QuadTree<>(bounds[0], bounds[1], bounds[2], bounds[3]);
}
 
Example #12
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 #13
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 #14
Source File: SocketPreparer.java    From amod with 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 #15
Source File: SingleHeuristicDispatcher.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
public SingleHeuristicDispatcher(String mode, EventsManager eventsManager, Network network, SingleRideAppender appender, double replanningInterval) {
    this.appender = appender;
    this.mode = mode;
    this.eventsManager = eventsManager;
    this.replanningInterval = replanningInterval;

    double[] bounds = NetworkUtils.getBoundingBox(network.getNodes().values()); // minx, miny, maxx, maxy

    availableVehiclesTree = new QuadTree<>(bounds[0], bounds[1], bounds[2], bounds[3]);
    pendingRequestsTree = new QuadTree<>(bounds[0], bounds[1], bounds[2], bounds[3]);
}
 
Example #16
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 #17
Source File: ClosestLinkInteractionFinder.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
private Facility findFacility(Facility baseFacility) {
    if (baseFacility.getCoord() == null) {
        throw new IllegalStateException("Trying to find closest interaction facility, but not coords are given.");
    }

    return new LinkWrapperFacility(NetworkUtils.getNearestLink(network, baseFacility.getCoord()));
}
 
Example #18
Source File: AbstractNoExplicitCommunication.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
protected AbstractNoExplicitCommunication(Network network, Config config, //
        AmodeusModeConfig operatorConfig, TravelTime travelTime, //
        AmodeusRouter router, EventsManager eventsManager, MatsimAmodeusDatabase db) {
    super(config, operatorConfig, travelTime, router, eventsManager, db);
    DispatcherConfigWrapper dispatcherConfig = DispatcherConfigWrapper.wrap(operatorConfig.getDispatcherConfig());
    dispatchPeriod = dispatcherConfig.getDispatchPeriod(30);
    this.network = network;
    double[] networkBounds = NetworkUtils.getBoundingBox(network.getNodes().values());
    requestMaintainer = new TreeMaintainer<>(networkBounds, TensorLocation::of);
}
 
Example #19
Source File: BeamExtensionForSharing.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
private boolean checkIfPossibleSharing(RoboTaxi roboTaxi, PassengerRequest request2, AtomicInteger numberAdded) {
    /** Check if the Robotaxi can Pickup a new customer on board or if it is allready full */
    if (!oneMorePickupPossible(roboTaxi, numberAdded))
        return false;

    /** Check if the distance of the Robotaxi to the customer is within a Radius rMax */
    if (NetworkUtils.getEuclideanDistance(roboTaxi.getDivertableLocation().getCoord(), request2.getFromLink().getCoord()) > rMax)
        return false;

    /** check if the direction of the Request is similar */
    return directionAngle(roboTaxi, request2).map(angle -> Scalars.lessThan(angle, phiMax)).orElse(false);
}
 
Example #20
Source File: Block.java    From amodeus with 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 #21
Source File: DemandSupplyBalancingDispatcher.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
protected DemandSupplyBalancingDispatcher(Config config, AmodeusModeConfig operatorConfig, //
        TravelTime travelTime, AmodeusRouter router, EventsManager eventsManager, Network network, //
        MatsimAmodeusDatabase db) {
    super(config, operatorConfig, travelTime, router, eventsManager, db);
    DispatcherConfigWrapper dispatcherConfig = DispatcherConfigWrapper.wrap(operatorConfig.getDispatcherConfig());
    dispatchPeriod = dispatcherConfig.getDispatchPeriod(10);
    double[] networkBounds = NetworkUtils.getBoundingBox(network.getNodes().values());
    this.requestMaintainer = new TreeMaintainer<>(networkBounds, this::getLocation);
    this.unassignedRoboTaxis = new TreeMaintainer<>(networkBounds, this::getRoboTaxiLoc);
}
 
Example #22
Source File: ArtificialScenarioCreator.java    From amodeus with GNU General Public License v2.0 4 votes vote down vote up
public ArtificialScenarioCreator(Config config) {
    network = (config == null) ? NetworkUtils.createNetwork() : NetworkUtils.createNetwork(config);

    Id<Node> nodeid1 = Id.createNodeId("node1");
    Coord coord1 = new Coord(100, 100);
    node1 = NetworkUtils.createNode(nodeid1, coord1);
    network.addNode(node1);

    Id<Node> nodeid2 = Id.createNodeId("node2");
    Coord coord2 = new Coord(100, 200);
    node2 = NetworkUtils.createNode(nodeid2, coord2);
    network.addNode(node2);

    Id<Node> nodeid3 = Id.createNodeId("node3");
    Coord coord3 = new Coord(200, 200);
    node3 = NetworkUtils.createNode(nodeid3, coord3);
    network.addNode(node3);

    Id<Node> nodeid4 = Id.createNodeId("node4");
    Coord coord4 = new Coord(200, 100);
    node4 = NetworkUtils.createNode(nodeid4, coord4);
    network.addNode(node4);

    Id<Node> depotId = Id.createNodeId("depot");
    Coord depotCoord = new Coord(100, 0);
    depot = NetworkUtils.createNode(depotId, depotCoord);
    network.addNode(depot);

    Id<Link> idUp = Id.createLinkId("linkUp");
    linkUp = NetworkUtils.createLink(idUp, node1, node2, network, length, freespeed, capacity, lanes);
    Id<Link> idRight = Id.createLinkId("linkRight");
    linkRight = NetworkUtils.createLink(idRight, node2, node3, network, length, freespeed, capacity, lanes);
    Id<Link> idDown = Id.createLinkId("linkDown");
    linkDown = NetworkUtils.createLink(idDown, node3, node4, network, length, freespeed, capacity, lanes);
    Id<Link> idLeft = Id.createLinkId("linkLeft");
    linkLeft = NetworkUtils.createLink(idLeft, node4, node1, network, length, freespeed, capacity, lanes);

    Id<Link> iddepotIn = Id.createLinkId("linkDepotIn");
    linkDepotIn = NetworkUtils.createLink(iddepotIn, node1, depot, network, length, freespeed, capacity, lanes);
    Id<Link> iddepotOut = Id.createLinkId("linkDepotOut");
    linkDepotOut = NetworkUtils.createLink(iddepotOut, depot, node1, network, length, freespeed, capacity, lanes);

    network.addLink(linkUp);
    network.addLink(linkRight);
    network.addLink(linkDown);
    network.addLink(linkLeft);
    network.addLink(linkDepotIn);
    network.addLink(linkDepotOut);

    avRequest1 = new AmodeusRequest(Id.create("p1", Request.class), null, linkUp, linkDown, 0.0, AmodeusModeConfig.DEFAULT_MODE, null);
    avRequest2 = new AmodeusRequest(Id.create("p2", Request.class), null, linkRight, linkLeft, 0.0, AmodeusModeConfig.DEFAULT_MODE, null);
    avRequest3 = new AmodeusRequest(Id.create("p3", Request.class), null, linkRight, linkUp, 0.0, AmodeusModeConfig.DEFAULT_MODE, null);
    avRequest4 = new AmodeusRequest(Id.create("p4", Request.class), null, linkRight, linkDown, 0.0, AmodeusModeConfig.DEFAULT_MODE, null);
    avRequest5 = new AmodeusRequest(Id.create("p5", Request.class), null, linkUp, linkRight, 0.0, AmodeusModeConfig.DEFAULT_MODE, null);
    avRequest6 = new AmodeusRequest(Id.create("p6", Request.class), null, linkUp, linkLeft, 0.0, AmodeusModeConfig.DEFAULT_MODE, null);
    avRequest7 = new AmodeusRequest(Id.create("p7", Request.class), null, linkRight, linkLeft, 0.0, AmodeusModeConfig.DEFAULT_MODE, null);
    avRequestDepotOut = new AmodeusRequest(Id.create("depotRequestOut", Request.class), null, linkDepotOut, linkDepotOut, 0.0, AmodeusModeConfig.DEFAULT_MODE, null);
    avRequestDepotIn = new AmodeusRequest(Id.create("depotRequestIn", Request.class), null, linkDepotIn, linkDepotIn, 0.0, AmodeusModeConfig.DEFAULT_MODE, null);

}
 
Example #23
Source File: TestPreparer.java    From amodeus with GNU General Public License v2.0 4 votes vote down vote up
private TestPreparer(File workingDirectory) throws Exception {
    System.out.println("working directory: " + workingDirectory);

    // run preparer in simulation working directory
    ScenarioOptions scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault());

    // load Settings from IDSC Options
    File configFile = new File(scenarioOptions.getPreparerConfigName());

    AmodeusConfigGroup avConfigGroup = new AmodeusConfigGroup();
    Config config = ConfigUtils.loadConfig(configFile.getAbsolutePath(), avConfigGroup);
    Scenario scenario = ScenarioUtils.loadScenario(config);
    GeneratorConfig avGeneratorConfig = //
            avConfigGroup.getModes().values().iterator().next().getGeneratorConfig();
    int numRt = avGeneratorConfig.getNumberOfVehicles();
    int endTime = (int) config.qsim().getEndTime().seconds();

    // 1) cut network (and reduce population to new network)
    networkPrepared = scenario.getNetwork();        
    NetworkPreparer.run(networkPrepared, scenarioOptions);

    // 2) adapt the population to new network
    populationPrepared = scenario.getPopulation();

    // To make Test input data consistent (e.g. avoid people departing fom "tram" links)
    SnapToClosestNetworkLink.run(populationPrepared, networkPrepared, TransportMode.car);

    PopulationPreparer.run(networkPrepared, populationPrepared, scenarioOptions, config, 10);

    // 3) create virtual Network
    
    // Amodeus uses internally a mode-filtered network (default is the car network). The provided
    // VirtualNetwork needs to be consistent with this node-filtered network.
    Network roadNetwork = NetworkUtils.createNetwork();
    new TransportModeNetworkFilter(networkPrepared).filter(roadNetwork, Collections.singleton("car"));
    new NetworkCleaner().run(roadNetwork);
    
    VirtualNetworkPreparer virtualNetworkPreparer = VirtualNetworkPreparer.INSTANCE;
    VirtualNetwork<Link> virtualNetwork = //
            virtualNetworkPreparer.create(roadNetwork, populationPrepared, scenarioOptions, numRt, endTime);

    // 4) create TravelData
    /** reading the customer requests */
    StaticTravelData travelData = StaticTravelDataCreator.create( //
            scenarioOptions.getWorkingDirectory(), //
            virtualNetwork, roadNetwork, populationPrepared, //
            scenarioOptions.getdtTravelData(), numRt, endTime);
    File travelDataFile = new File(scenarioOptions.getVirtualNetworkDirectoryName(), scenarioOptions.getTravelDataName());
    TravelDataIO.writeStatic(travelDataFile, travelData);

    // 5) save a simulation config file
    // IncludeActTypeOf.BaselineCH(config); // Only needed in Some Scenarios
    ConfigCreator.createSimulationConfigFile(config, scenarioOptions);
}
 
Example #24
Source File: VoronoiPartition.java    From amodeus with GNU General Public License v2.0 4 votes vote down vote up
public VoronoiPartition(Network network, Function<T, Coord> location) {
    this.network = network;
    this.location = location;
    double[] networkBounds = NetworkUtils.getBoundingBox(network.getNodes().values());
    tree = new QuadTree<>(networkBounds[0], networkBounds[1], networkBounds[2], networkBounds[3]);
}
 
Example #25
Source File: NetworkTools.java    From pt2matsim with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Reads and returns a network
 */
public static Network readNetwork(String fileName) {
	Network network = NetworkUtils.createNetwork();
	new MatsimNetworkReader(network).readFile(fileName);
	return network;
}
 
Example #26
Source File: NetworkTools.java    From pt2matsim with GNU General Public License v2.0 4 votes vote down vote up
public static Network createNetwork() {
	return NetworkUtils.createNetwork();
}
 
Example #27
Source File: RoboTaxiHandler.java    From amodeus with GNU General Public License v2.0 4 votes vote down vote up
public RoboTaxiHandler(Network network) {
    maxSpeed = maxSpeed(network);
    double[] networkBounds = NetworkUtils.getBoundingBox(network.getNodes().values());
    this.allRoboTaxis = new TreeMaintainer<>(networkBounds, this::getRoboTaxiLoc);
}
 
Example #28
Source File: NetworkTools.java    From pt2matsim with GNU General Public License v2.0 4 votes vote down vote up
public static double calcRouteLength(Network network, TransitRoute transitRoute, boolean euclidian) {
	return calcRouteLength(NetworkUtils.getLinks(network, ScheduleTools.getTransitRouteLinkIds(transitRoute)), euclidian);
}