Java Code Examples for org.matsim.api.core.v01.network.Link

The following examples show how to use org.matsim.api.core.v01.network.Link. 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
@Override
public List<DvrpVehicleSpecification> generateVehicles() {
    long generatedVehicles = 0;
    List<DvrpVehicleSpecification> vehicles = new LinkedList<>();
    while (generatedVehicles < operatorConfig.getGeneratorConfig().getNumberOfVehicles()) {
        ++generatedVehicles;

        int bound = network.getLinks().size();
        int elemRand = MatsimRandom.getRandom().nextInt(bound);
        Link link = network.getLinks().values().stream().skip(elemRand).findFirst().get();
        LOGGER.info("car placed at link " + link);

        Id<DvrpVehicle> id = AmodeusIdentifiers.createVehicleId(operatorConfig.getMode(), generatedVehicles);
        vehicles.add(ImmutableDvrpVehicleSpecification.newBuilder() //
                .id(id) //
                .serviceBeginTime(0.0) //
                .serviceEndTime(Double.POSITIVE_INFINITY) //
                .capacity(capacity) //
                .startLinkId(link.getId()) //
                .build());
    }
    return vehicles;
}
 
Example 2
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 3
Source Project: amodeus   Source File: DynamicWaitingTime.java    License: GNU General Public License v2.0 6 votes vote down vote up
private double[][] createDefaultValues(int numberOfGroups, int numberOfTimeBins) {
    double[][] values = new double[numberOfGroups][numberOfTimeBins];

    for (int groupIndex = 0; groupIndex < numberOfGroups; groupIndex++) {
        for (int timeIndex = 0; timeIndex < numberOfTimeBins; timeIndex++) {
            Collection<Id<Link>> linkIds = linkGroupDefinition.getLinkIds(groupIndex);

            if (linkIds.size() > 0) {
                double cumulativeWaitingTime = 0.0;

                for (Id<Link> linkId : linkIds) {
                    cumulativeWaitingTime += linkWaitingTimeData.getWaitingTime(linkId, defaultWaitingTime);
                }

                values[groupIndex][timeIndex] = cumulativeWaitingTime / linkIds.size();
            } else {
                values[groupIndex][timeIndex] = defaultWaitingTime;
            }
        }
    }

    return values;
}
 
Example 4
Source Project: amodeus   Source File: DualSideSearch.java    License: GNU General Public License v2.0 6 votes vote down vote up
public Collection<RoboTaxi> apply(PassengerRequest request, Map<VirtualNode<Link>, Set<RoboTaxi>> plannedLocations, //
        Scalar timeLeftForPickup, Scalar timeLeftUntilArrival) {

    /** origin cell = {@link GridCell} of {@link VirtualNode} containing the request origin link */
    GridCell oCell = gridCells.get(virtualNetwork.getVirtualNode(request.getFromLink()));
    /** destination cell = {@link GridCell} of {@link VirtualNode} containing the request destination link */
    GridCell dCell = gridCells.get(virtualNetwork.getVirtualNode(request.getToLink()));

    /** oCloseCells = cells reachable before latest pickup */
    Collection<VirtualNode<Link>> oCloseCells = oCell.nodesReachableWithin(timeLeftForPickup);
    /** dCloseCells = cells reachable before latest arrival */
    Collection<VirtualNode<Link>> dCloseCells = dCell.nodesReachableWithin(timeLeftUntilArrival);

    /** compute set of potential taxis for ride sharing with dual side search */
    return dualSideSearch(oCell, dCell, oCloseCells, dCloseCells, plannedLocations);
}
 
Example 5
/** @param network
 * @return all {@link Link}s crossing the equator of the city {@link Network} , starting
 *         with links on the equator, if no links found, the search radius is increased by 1 m */
private static List<Link> getEquator(Network network) {
    double northX = network.getLinks().values().stream().map(Link::getCoord).map(Coord::getY).max(Double::compare).get();
    double southX = network.getLinks().values().stream().map(Link::getCoord).map(Coord::getY).min(Double::compare).get();
    double equator = southX + (northX - southX) / 2;

    List<Link> equatorLinks = new ArrayList<>();
    double margin = 0.0;
    while (equatorLinks.isEmpty()) {
        for (Link l : network.getLinks().values()) {
            double fromY = l.getFromNode().getCoord().getY();
            double toY = l.getToNode().getCoord().getY();
            if ((fromY - margin <= equator && toY + margin >= equator) || //
                    (fromY + margin >= equator && toY - margin <= equator))
                equatorLinks.add(l);
        }
        margin += 1.0;
    }
    // GlobalAssert.that(equatorLinks.size() > 0); // always true
    return equatorLinks;
}
 
Example 6
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 7
Source Project: pt2matsim   Source File: PTMapperTools.java    License: 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 8
@Override
public Tensor evaluate(SimulationObject ref) {
    Tensor count = Array.zeros(virtualNetwork.getvNodesCount());
    for (RequestContainer rc : ref.requests) {
        int linkIndex = rc.fromLinkIndex;
        Link link = db.getOsmLink(linkIndex).link;
        VirtualNode<Link> vn = virtualNetwork.getVirtualNode(link);
        count.set(Increment.ONE, vn.getIndex());
    }
    return count;
}
 
Example 9
Source Project: pt2matsim   Source File: LinkCandidateImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public LinkCandidateImpl(Link link, PublicTransitStop publicTransitStop) {
	this.link = link;
	this.stop = publicTransitStop;

	this.fromNodeCoord = link.getFromNode().getCoord();
	this.toNodeCoord = link.getToNode().getCoord();
	this.stopFacilityDistance = CoordUtils.distancePointLinesegment(fromNodeCoord, toNodeCoord, publicTransitStop.getStopFacility().getCoord());
	this.isLoopLink = link.getFromNode().getId().toString().equals(link.getToNode().getId().toString());
	this.priority = 1;
}
 
Example 10
/** Assigns to every link in the @param network a capacity equal to:
 * min(@param minCapacityGlobal, link lenghth x @param capacityPerLengthUnit ) */
public ParkingCapacityLinkLength(Network network, double capacityPerLengthUnit, long minCapacityGlobal) {
    for (Link link : network.getLinks().values()) {
        long capacity = (long) Math.max(Math.floor(link.getLength() * capacityPerLengthUnit), minCapacityGlobal);
        capacities.put(link.getId(), capacity);
    }
}
 
Example 11
Source Project: pt2matsim   Source File: Schedule2Geojson.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return the sum of all link lenghts of a transit route
 */
private double getRouteLength(TransitRoute transitRoute) {
	double length = 0;
	for(Link l : NetworkTools.getLinksFromIds(network, ScheduleTools.getTransitRouteLinkIds(transitRoute))) {
		length += l.getLength();
	}
	return length;
}
 
Example 12
Source Project: amodeus   Source File: VirtualNodeGeometry.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** @param amodeusComponent
 * @return */
Map<VirtualNode<Link>, Tensor> getShapesTensor(AmodeusComponent amodeusComponent) {
    Map<VirtualNode<Link>, Tensor> map = new LinkedHashMap<>(); // ordering matters
    for (Entry<VirtualNode<Link>, Tensor> entry : convexHulls.entrySet())
        map.put(entry.getKey(), createShapeTensor(amodeusComponent, entry.getValue()));
    return map;
}
 
Example 13
Source Project: amodeus   Source File: TShareDispatcher.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected TShareDispatcher(Network network, Config config, AmodeusModeConfig operatorConfig, //
        TravelTime travelTime, AmodeusRouter router, EventsManager eventsManager, //
        MatsimAmodeusDatabase db, VirtualNetwork<Link> virtualNetwork) {
    super(config, operatorConfig, travelTime, router, eventsManager, virtualNetwork, db);
    DispatcherConfigWrapper dispatcherConfig = DispatcherConfigWrapper.wrap(operatorConfig.getDispatcherConfig());
    dispatchPeriod = dispatcherConfig.getDispatchPeriod(30);
    DistanceHeuristics distanceHeuristics = dispatcherConfig.getDistanceHeuristics(DistanceHeuristics.EUCLIDEAN);
    System.out.println("Using DistanceHeuristics: " + distanceHeuristics.name());
    distanceCashed = new CachedNetworkTimeDistance(
            EasyMinDistPathCalculator.prepPathCalculator(network, new FastAStarLandmarksFactory(Runtime.getRuntime().availableProcessors())), //
            180000.0, TimeDistanceProperty.INSTANCE);
    travelTimeCalculator = new CachedNetworkTimeDistance(
            EasyMinTimePathCalculator.prepPathCalculator(network, new FastAStarLandmarksFactory(Runtime.getRuntime().availableProcessors())), //
            180000.0, TimeDistanceProperty.INSTANCE);
    bipartiteMatchingUtils = new TShareBipartiteMatchingUtils();

    /** T-Share specific */
    SafeConfig safeConfig = SafeConfig.wrap(operatorConfig.getDispatcherConfig());
    pickupDelayMax = Quantity.of(safeConfig.getInteger("pickupDelayMax", 10 * 60), SI.SECOND);
    drpoffDelayMax = Quantity.of(safeConfig.getInteger("drpoffDelayMax", 30 * 60), SI.SECOND);

    /** initialize grid with T-cells */
    QuadTree<Link> linkTree = FastQuadTree.of(network);
    for (VirtualNode<Link> virtualNode : virtualNetwork.getVirtualNodes()) {
        System.out.println("preparing grid cell: " + virtualNode.getIndex());
        gridCells.put(virtualNode, new GridCell(virtualNode, virtualNetwork, distanceCashed, travelTimeCalculator, linkTree));
    }
    dualSideSearch = new DualSideSearch(gridCells, virtualNetwork);
    System.out.println("According to the reference, a rectangular {@link VirtualNetwork} should be used.");
    System.out.println("Ensure that VirtualNetworkCreators.RECTANGULAR is used.");
}
 
Example 14
protected void fillUsingLinks(Collection<? extends Link> possibleLinks, //
        long totSpaces, Random random) {
    Map<Id<Link>, Long> parkingCount = new HashMap<>();
    int bound = possibleLinks.size();
    for (int i = 0; i < totSpaces; ++i) {
        int elemRand = random.nextInt(bound);
        Link link = possibleLinks.stream().skip(elemRand).findFirst().get();
        parkingCount.merge(link.getId(), 1L, Long::sum);
    }
    parkingCount.forEach(capacities::put);
    GlobalAssert.that(totSpaces == capacities.values().stream().mapToLong(l -> l).sum());
}
 
Example 15
Source Project: pt2matsim   Source File: PTMapperShapesTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void linkSequences() {
	TransitSchedule initSchedule = ScheduleToolsTest.initSchedule();

	for(TransitLine l : schedule.getTransitLines().values()) {
		for(TransitRoute r : l.getRoutes().values()) {
			TransitRoute initRoute = initSchedule.getTransitLines().get(l.getId()).getRoutes().get(r.getId());
			List<Id<Link>> initLinkIds = ScheduleTools.getTransitRouteLinkIds(initRoute);
			List<Id<Link>> linkIds = ScheduleTools.getTransitRouteLinkIds(r);
			Assert.assertEquals(initLinkIds, linkIds);
		}
	}
}
 
Example 16
Source Project: amod   Source File: SocketVehicleStatistic.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** this function is called when the {@link RoboTaxi} has changed the link, then we can
 * register the distance covered by the vehicle on the previous link and associate it to
 * timesteps. The logic is that the distance is added evenly to the time steps.
 * 
 * @return vector of length 2, entries have unit "m" */
public Tensor consolidate() {
    Scalar distDrive = Quantity.of(0, SI.METER);
    Scalar distEmpty = Quantity.of(0, SI.METER);
    if (!list.isEmpty()) {
        final int linkId = list.get(0).linkTrace[list.get(0).linkTrace.length - 1];
        Link distanceLink = db.getOsmLink(linkId).link;
        /** this total distance on the link was travelled on during all simulationObjects stored
         * in the list. */
        Scalar distance = Quantity.of(distanceLink.getLength(), SI.METER);

        int part = Math.toIntExact(list.stream().filter(VehicleContainerUtils::isDriving).count());
        Scalar stepDistcontrib = distance.divide(RationalScalar.of(part, 1));

        for (VehicleContainer vehicleContainer : list) {
            switch (VehicleContainerUtils.finalStatus(vehicleContainer)) {
            case DRIVEWITHCUSTOMER:
                distDrive = distDrive.add(stepDistcontrib);
                break;
            case DRIVETOCUSTOMER:
                distEmpty = distEmpty.add(stepDistcontrib);
                break;
            case REBALANCEDRIVE:
                distEmpty = distEmpty.add(stepDistcontrib);
                break;
            default:
                break;
            }
        }
    }
    return Tensors.of(distDrive, distEmpty);
}
 
Example 17
Source Project: pt2matsim   Source File: NetworkTools.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return the network links from a given list of link ids
 */
public static List<Link> getLinksFromIds(Network network, List<Id<Link>> linkIds) {
	Map<Id<Link>, ? extends Link> links = network.getLinks();
	List<Link> list = new ArrayList<>();
	for(Id<Link> linkId : linkIds) {
		list.add(links.get(linkId));
	}
	return list;
}
 
Example 18
/** Command to rebalance {@link RoboTaxi} to a certain {@link Link} destination. The {@link RoboTaxi} will appear as
 * Rebalancing in the visualizer. Can only be used for {@link RoboTaxi} which are without a customer and divertible.
 * Function can only be invoked one time in each iteration of {@link RoboTaxiMaintainer#redispatch}
 * 
 * @param roboTaxi
 * @param destination */
public final void setRoboTaxiRebalance(final RoboTaxi roboTaxi, final Link destination) {
    GlobalAssert.that(roboTaxi.isWithoutCustomer());
    /** if {@link RoboTaxi} is during pickup, remove from pickup register */
    if (isInPickupRegister(roboTaxi)) {
        PassengerRequest toRemove = getPickupRoboTaxis().get(roboTaxi);
        removeFromPickupRegisters(toRemove);
    }
    setRoboTaxiDiversion(roboTaxi, destination, RoboTaxiStatus.REBALANCEDRIVE);
    eventsManager.processEvent(RebalanceVehicleEvent.create(getTimeNow(), roboTaxi, destination));
}
 
Example 19
public double of(Link fromLink, Link toLink, double now, boolean storeInCache) {
    travelTimeDataMap.computeIfAbsent(fromLink, l -> new HashMap<>());

    if (travelTimeDataMap.get(fromLink).containsKey(toLink))
        return travelTimeDataMap.get(fromLink).get(toLink);

    // if it reaches here, we need to calculate the travel time
    Path shortest = leastCostPathCalculator.calcLeastCostPath(fromLink.getFromNode(), toLink.getToNode(), now, null, null);
    if (storeInCache)
        travelTimeDataMap.get(fromLink).put(toLink, shortest.travelTime);

    return shortest.travelTime;
}
 
Example 20
@Test
public void testPrimaryDefaultReversedOneway() {
	Set<Link> links = osmid2link.get(7994930L);
	assertEquals("oneway", 1, links.size());
	assertEquals("oneway down south", 1, getLinksTowardsNode(links, 59836834L).size());
	assertLanes(links, 3);
	assertMaxspeed(links, 70);
}
 
Example 21
Source Project: amodeus   Source File: RunDrtTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
static public void createFleet(String path, int numberOfVehicles, Network network) {
    Random random = new Random(0);

    List<Link> links = network.getLinks().values().stream().filter(link -> link.getAllowedModes().contains("car")).collect(Collectors.toList());

    new FleetWriter(IntStream.range(0, 100).mapToObj(i -> {
        return ImmutableDvrpVehicleSpecification.newBuilder() //
                .id(Id.create("drt" + i, DvrpVehicle.class)) //
                .startLinkId(links.get(random.nextInt(links.size())).getId()) //
                .capacity(4) //
                .serviceBeginTime(0.0) //
                .serviceEndTime(30.0 * 3600.0) //
                .build();
    })).write(path);
}
 
Example 22
@Test
public void testPrimaryOnewayWithForwardLanesAndMaxspeed() {
	Set<Link> links = osmid2link.get(7994920L);
	assertEquals("oneway", 1, links.size());
	assertEquals("oneway up north", 1, getLinksTowardsNode(links, 59836807L).size());
	assertLanes(links, 3);
	assertMaxspeed(links, 70);
}
 
Example 23
@Test
public void testPrimaryWithOddLanesAndMaxspeed() {
	Set<Link> links = osmid2link.get(7994888L);
	assertEquals("bidirectional", 2, links.size());
	assertLanes(links, 3.5);
	assertMaxspeed(links, 70);
}
 
Example 24
Source Project: amodeus   Source File: LPTimeVariantBase.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** @param virtualNetwork
 * @param network
 * @param lambdaAbsolute_ij has to be integer numbered */
protected LPTimeVariantBase(VirtualNetwork<Link> virtualNetwork, Network network, Tensor lambdaAbsolute_ij, int numberVehicles, int endTime) {
    this.virtualNetwork = virtualNetwork;
    nvNodes = virtualNetwork.getvNodesCount();
    this.lambdaAbsolute_ij = LPUtils.getRoundedRequireNonNegative(lambdaAbsolute_ij);
    this.endTime = endTime;
    timeSteps = Dimensions.of(lambdaAbsolute_ij).get(0);
    timeIntervalLength = endTime / timeSteps;
    this.numberVehicles = numberVehicles;

    if (virtualNetwork.getvLinksCount() != (nvNodes * nvNodes - nvNodes))
        throw new RuntimeException("These computations are only valid for a complete graph. Aborting.");
}
 
Example 25
Source Project: amodeus   Source File: DFRStrategy.java    License: GNU General Public License v2.0 5 votes vote down vote up
private DFRStrategy(Network network, VirtualNetwork<Link> virtualNetwork, Config config, //
        AmodeusModeConfig operatorConfig, TravelTime travelTime, //
        AmodeusRouter router, EventsManager eventsManager, TravelData travelData, //
        MatsimAmodeusDatabase db) {
    super(config, operatorConfig, travelTime, router, eventsManager, virtualNetwork, db);
    DispatcherConfigWrapper dispatcherConfig = DispatcherConfigWrapper.wrap(operatorConfig.getDispatcherConfig());
    dispatchPeriod = dispatcherConfig.getDispatchPeriod(30);
    rebalancingPeriod = dispatcherConfig.getRebalancingPeriod(300);
    DistanceHeuristics distanceHeuristics = //
            dispatcherConfig.getDistanceHeuristics(DistanceHeuristics.EUCLIDEAN);
    System.out.println("Using DistanceHeuristics: " + distanceHeuristics.name());
    distanceFunction = distanceHeuristics.getDistanceFunction(network);
    this.network = network;
    this.travelData = travelData;
    this.neighboring = new Neighboring(virtualNetwork, network);
    this.ownedRoboTaxis = new OwnedRoboTaxis(virtualNetwork);
    this.rounder = new Rounder(virtualNetwork);
    this.metropolisHastings = new MetropolisHastings(virtualNetwork, neighboring).getAll();
    this.vehicleDestMatcher = new GlobalBipartiteMatching(EuclideanDistanceCost.INSTANCE);
    this.virtualNodeDest = new RandomVirtualNodeDest();
    SafeConfig safeConfig = SafeConfig.wrap(operatorConfig);
    bipartiteMatchingUtils = new ConfigurableBipartiteMatcher(network, new DistanceCost(distanceFunction), safeConfig);
    this.doDFR = dispatcherConfig.getBoolStrict("DFR");
    this.config = config;
    System.out.println("DFR is set to: " + doDFR);
    System.out.println("travelData: " + travelData.getLPName());
}
 
Example 26
static private TravelData provideTravelDataFromConfig(InstanceGetter getter) {
    try {
        AmodeusModeConfig modeConfig = getter.getModal(AmodeusModeConfig.class);
        DispatcherConfig dispatcherConfig = modeConfig.getDispatcherConfig();

        VirtualNetwork<Link> virtualNetwork = getter.getModal(new TypeLiteral<VirtualNetwork<Link>>() {
        });
        Network network = getter.getModal(Network.class);
        Config config = getter.get(Config.class);
        ScenarioOptions scenarioOptions = getter.get(ScenarioOptions.class);
        Population population = getter.get(Population.class);

        URL travelDataUrl = ConfigGroup.getInputFileURL(config.getContext(), dispatcherConfig.getTravelDataPath());
        File travelDataFile = new File(travelDataUrl.getPath());

        if (!travelDataFile.exists() || dispatcherConfig.getRegenerateTravelData()) {
            logger.info(String.format("Regenerating TravelData for mode '%s' at '%s'", modeConfig.getMode(), travelDataFile));
            logger.info("Currently we use information from ScenarioOptions for that. Later on this should be moved to a specific config module.");
            logger.info("Using StaticTravelDataCreator");

            File workingDirectory = new File(config.getContext().getPath()).getParentFile();
            int numberOfVehicles = modeConfig.getGeneratorConfig().getNumberOfVehicles();
            int interval = scenarioOptions.getdtTravelData();

            StaticTravelData travelData = StaticTravelDataCreator.create(workingDirectory, virtualNetwork, network, population, interval, numberOfVehicles, //
                    (int) config.qsim().getEndTime().seconds());
            TravelDataIO.writeStatic(travelDataFile, travelData);
        }

        logger.info(String.format("Loading TravelData for mode '%s' from '%s'", modeConfig.getMode(), travelDataFile));
        return TravelDataGet.readFile(virtualNetwork, travelDataFile);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 27
Source Project: pt2matsim   Source File: CoordTools.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * calculates the azimuth difference of two subsequent links
 *
 * @return the difference in [rad]
 */
public static double getAngleDiff(Link link1, Link link2) {
	if(!link1.getToNode().getCoord().equals(link2.getFromNode().getCoord())) {
		throw new IllegalArgumentException("link2 is not an outlink of link1");
	}
	if(link1.getFromNode().getId().equals(link2.getToNode().getId())) {
		return Math.PI;
	}
	return getAngleDiff(link1.getFromNode().getCoord(), link1.getToNode().getCoord(), link2.getToNode().getCoord());
}
 
Example 28
/**
 * "Refreshes" the transit route by routing between all referenced links
 * of the stop facilities.
 */
@Override
public void refreshTransitRoute(TransitLine transitLine, TransitRoute transitRoute) {
	List<TransitRouteStop> routeStops = transitRoute.getStops();
	List<Id<Link>> linkSequence = new ArrayList<>();
	linkSequence.add(routeStops.get(0).getStopFacility().getLinkId());

	// route
	for(int i = 0; i < routeStops.size() - 1; i++) {
		if(routeStops.get(i).getStopFacility().getLinkId() == null) {
			throw new IllegalArgumentException("stop facility " + routeStops.get(i).getStopFacility().getName() + " (" + routeStops.get(i).getStopFacility().getId() + " not referenced!");
		}
		if(routeStops.get(i + 1).getStopFacility().getLinkId() == null) {
			throw new IllegalArgumentException("stop facility " + routeStops.get(i - 1).getStopFacility().getName() + " (" + routeStops.get(i + 1).getStopFacility().getId() + " not referenced!");
		}

		Id<Link> currentLinkId = Id.createLinkId(routeStops.get(i).getStopFacility().getLinkId().toString());

		Link currentLink = network.getLinks().get(currentLinkId);
		Link nextLink = network.getLinks().get(routeStops.get(i + 1).getStopFacility().getLinkId());

		List<Id<Link>> path = PTMapperTools.getLinkIdsFromPath(routers.calcLeastCostPath(currentLink.getToNode().getId(), nextLink.getFromNode().getId(), transitLine, transitRoute));

		if(path != null)
			linkSequence.addAll(path);

		linkSequence.add(nextLink.getId());
	}

	// add link sequence to schedule
	transitRoute.setRoute(RouteUtils.createNetworkRoute(linkSequence, network));
}
 
Example 29
public ArtificialLinkWarning(TransitLine transitLine, TransitRoute transitRoute, Link link) {
	super(Type.ArtificialLinkWarning, transitLine, transitRoute);
	this.fromId = link.getFromNode().getId().toString();
	this.toId = link.getToNode().getId().toString();

	linkIdList = new ArrayList<>();
	linkIdList.add(link.getId());
}
 
Example 30
private static Map<Long, Set<Link>> collectLinkMap(Network network) {
	HashMap<Long, Set<Link>> osmid2link = new HashMap<>();
	for (Link l : network.getLinks().values()) {
		long key = (long) l.getAttributes().getAttribute("osm:way:id");
		if (!osmid2link.containsKey(key))
			osmid2link.put(key, new HashSet<>());
		osmid2link.get(key).add(l);
	}
	return osmid2link;
}