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

The following examples show how to use org.matsim.api.core.v01.network.Link. 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: 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 #2
Source File: DynamicWaitingTime.java    From amodeus with 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 #3
Source File: RandomDensityGenerator.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
@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 #4
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 #5
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 #6
Source File: DualSideSearch.java    From amodeus with 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 #7
Source File: NorthPoleSharedDispatcher.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
/** @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 #8
Source File: NetworkTools.java    From pt2matsim with 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 #9
Source File: OsmMultimodalNetworkConverterTest.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testPrimaryWithOddLanesAndMaxspeed() {
	Set<Link> links = osmid2link.get(7994888L);
	assertEquals("bidirectional", 2, links.size());
	assertLanes(links, 3.5);
	assertMaxspeed(links, 70);
}
 
Example #10
Source File: OsmMultimodalNetworkConverterTest.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
@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 #11
Source File: RunDrtTest.java    From amodeus with 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 #12
Source File: OsmMultimodalNetworkConverterTest.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
@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 #13
Source File: TravelTimeComputation.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
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 #14
Source File: DFRStrategy.java    From amodeus with 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 #15
Source File: Schedule2Geojson.java    From pt2matsim with 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 #16
Source File: SocketVehicleStatistic.java    From amod with 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 File: PTMapperShapesTest.java    From pt2matsim with 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 #18
Source File: ParkingCapacityLinkLength.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
/** 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 #19
Source File: LPTimeVariantBase.java    From amodeus with 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 #20
Source File: RebalancingDispatcher.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
/** 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 #21
Source File: VirtualNetworkModeModule.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
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 #22
Source File: CoordTools.java    From pt2matsim with 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 #23
Source File: BasicScheduleEditor.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
/**
 * "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 #24
Source File: ArtificialLinkWarning.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
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 #25
Source File: OsmMultimodalNetworkConverterTest.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #26
Source File: RoboTaxiLocation.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
/** @param roboTaxi
 * @return link or null with a small chance */
public static Link of(RoboTaxi roboTaxi) {
    Schedule schedule = Objects.requireNonNull(roboTaxi.getSchedule());
    /** {@link ScheduleImpl.failIfNotStarted} triggers, very likely you have
     * entered a simulation start time other than 0:00. Check that in the
     * av_config.xml file. */
    return new RoboTaxiLocation(schedule.getCurrentTask()).link;
}
 
Example #27
Source File: PopulationDensityGenerator.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
@Override
public List<DvrpVehicleSpecification> generateVehicles() {
    List<DvrpVehicleSpecification> vehicles = new LinkedList<>();
    Random random = new Random(randomSeed);

    int generatedNumberOfVehicles = 0;
    while (generatedNumberOfVehicles < numberOfVehicles) {
        generatedNumberOfVehicles++;

        // Multinomial selection
        double r = random.nextDouble();
        Link selectedLink = linkList.get(0);

        for (Link link : linkList) {
            if (r <= cumulativeDensity.get(link)) {
                selectedLink = link;
                break;
            }
        }

        Id<DvrpVehicle> id = AmodeusIdentifiers.createVehicleId(mode, generatedNumberOfVehicles);

        vehicles.add(ImmutableDvrpVehicleSpecification.newBuilder() //
                .id(id) //
                .serviceBeginTime(0.0) //
                .serviceEndTime(Double.POSITIVE_INFINITY) //
                .capacity(capacity) //
                .startLinkId(selectedLink.getId()) //
                .build());
    }

    return vehicles;
}
 
Example #28
Source File: ShapeTools.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Converts a list of link ids to an array of coordinates for shp features
 */
public static Coordinate[] linkIdList2Coordinates(Network network, List<Id<Link>> linkIdList) {
	List<Coordinate> coordList = new ArrayList<>();
	for(Id<Link> linkId : linkIdList) {
		if(network.getLinks().containsKey(linkId)) {
			coordList.add(MGC.coord2Coordinate(network.getLinks().get(linkId).getFromNode().getCoord()));
		} else {
			throw new IllegalArgumentException("Link " + linkId + " not found in network");
		}
	}
	coordList.add(MGC.coord2Coordinate(network.getLinks().get(linkIdList.get(linkIdList.size() - 1)).getToNode().getCoord()));
	Coordinate[] coordinates = new Coordinate[coordList.size()];
	return coordList.toArray(coordinates);
}
 
Example #29
Source File: Schedule2Geojson.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Converts the stop facilities to points.
 */
private void convertStopFacilities() {
	for(TransitStopFacility stopFacility : schedule.getFacilities().values()) {
		Coord stopCoord = stopFacility.getCoord();

		Feature pf = GeojsonTools.createPointFeature(ct.transform(stopCoord));
		pf.setProperty("stopFacilityId", stopFacility.getId().toString());
		pf.setProperty("stopFacilityName", stopFacility.getName());
		pf.setProperty("stopFacilityPostAreaId", stopFacility.getStopAreaId());
		pf.setProperty("stopFacilityIsBlocking", stopFacility.getIsBlockingLane());

		if(stopFacility.getLinkId() != null) pf.setProperty("stopFacilityLinkId", stopFacility.getLinkId().toString());

		if(routesOnStopFacility.get(stopFacility) != null) {
			pf.setProperty("stopFacilityTransitRoutes", CollectionUtils.idSetToString(routesOnStopFacility.get(stopFacility)));
		}
		stopFacilityFeatures.add(pf);

		// convert stop ref links (not written to combined file)
		if(stopFacility.getLinkId() != null && this.network != null) {
			Link refLink = network.getLinks().get(stopFacility.getLinkId());

			List<Coord> coords = new ArrayList<>();
			coords.add(this.ct.transform(refLink.getFromNode().getCoord()));
			coords.add(this.ct.transform(refLink.getToNode().getCoord()));

			Feature lf = GeojsonTools.createLineFeature(coords);
			lf.setProperty("id", stopFacility.getId().toString());
			lf.setProperty("name", stopFacility.getName());
			lf.setProperty("linkId", stopFacility.getLinkId().toString());
			lf.setProperty("postAreaId", stopFacility.getStopAreaId());
			lf.setProperty("isBlocking", stopFacility.getIsBlockingLane());
			stopRefLinks.add(lf);
		}
	}
}
 
Example #30
Source File: NetworkToolsTest.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void linkSequenceHasDuplicateLink() {
	List<Link> seq = new ArrayList<>();
	seq.add(getLink("XA"));
	seq.add(getLink("AB"));
	seq.add(getLink("BC"));
	seq.add(getLink("CD"));
	seq.add(getLink("DA"));
	seq.add(getLink("AB"));
	seq.add(getLink("BI"));
	seq.add(getLink("IH"));

	assertTrue(NetworkTools.linkSequenceHasDuplicateLink(seq));
}