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

The following examples show how to use org.matsim.api.core.v01.Id. 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
private void run() {

		Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
		new MatsimNetworkReader(scenario.getNetwork()).readFile(networkFile.toString());
		final int[] i = {0};
		Stream<DvrpVehicleSpecification> vehicleSpecificationStream = scenario.getNetwork().getLinks().entrySet().stream()
				.filter(entry -> entry.getValue().getAllowedModes().contains(TransportMode.car)) // drt can only start on links with Transport mode 'car'
				.sorted((e1, e2) -> (random.nextInt(2) - 1)) // shuffle links
				.limit(numberOfVehicles) // select the first *numberOfVehicles* links
				.map(entry -> ImmutableDvrpVehicleSpecification.newBuilder()
						.id(Id.create("drt_" + i[0]++, DvrpVehicle.class))
						.startLinkId(entry.getKey())
						.capacity(seatsPerVehicle)
						.serviceBeginTime(operationStartTime)
						.serviceEndTime(operationEndTime)
						.build());

		new FleetWriter(vehicleSpecificationStream).write(outputFile.toString());
	}
 
Example 2
@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 3
Source Project: amodeus   Source File: TestScenario.java    License: GNU General Public License v2.0 6 votes vote down vote up
static public Controler createController(Scenario scenario, EventHandler handler, int vehicleCapacity) {
    Controler controller = new Controler(scenario);

    controller.addOverridingModule(new DvrpModule());
    controller.addOverridingModule(new DvrpTravelTimeModule());
    controller.addOverridingModule(new AmodeusModule());

    controller.addOverridingModule(new AbstractModule() {
        @Override
        public void install() {
            AmodeusUtils.registerGeneratorFactory(binder(), "Single", SingleVehicleGeneratorFactory.class);
            addEventHandlerBinding().toInstance(handler);
        }

        @Provides
        public SingleVehicleGeneratorFactory provideFactory() {
            return new SingleVehicleGeneratorFactory(vehicleCapacity, Id.createLinkId("link1"));
        }
    });

    controller.addOverridingQSimModule(new AmodeusQSimModule());

    controller.configureQSimComponents(AmodeusQSimModule.activateModes(scenario.getConfig()));

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

        /** select one of the 10 random links for placement */
        int elemRand = MatsimRandom.getRandom().nextInt(randomLinks.size());
        Link linkSel = randomLinks.stream().skip(elemRand).findFirst().get();

        LOGGER.info("car placed at link " + linkSel);

        Id<DvrpVehicle> id = AmodeusIdentifiers.createVehicleId(operatorConfig.getMode(), generatedVehicles);

        vehicles.add(ImmutableDvrpVehicleSpecification.newBuilder() //
                .id(id) //
                .serviceBeginTime(0.0) //
                .serviceEndTime(Double.POSITIVE_INFINITY) //
                .capacity(capacity) //
                .startLinkId(linkSel.getId()) //
                .build());
    }
    return vehicles;
}
 
Example 6
Source Project: pt2matsim   Source File: ScheduleTools.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Add mode "pt" to any link of the network that is
 * passed by any transitRoute of the schedule.
 */
public static void addPTModeToNetwork(TransitSchedule schedule, Network network) {
	log.info("... Adding mode \"pt\" to all links with public transit");

	Map<Id<Link>, ? extends Link> networkLinks = network.getLinks();
	Set<Id<Link>> transitLinkIds = new HashSet<>();

	for(TransitLine line : schedule.getTransitLines().values()) {
		for(TransitRoute transitRoute : line.getRoutes().values()) {
			if(transitRoute.getRoute() != null) {
				transitLinkIds.addAll(getTransitRouteLinkIds(transitRoute));
			}
		}
	}

	for(Id<Link> transitLinkId : transitLinkIds) {
		Link transitLink = networkLinks.get(transitLinkId);
		if(!transitLink.getAllowedModes().contains(TransportMode.pt)) {
			Set<String> modes = new HashSet<>(transitLink.getAllowedModes());
			modes.add(TransportMode.pt);
			transitLink.setAllowedModes(modes);
		}
	}
}
 
Example 7
/**
 * - Changes the referenced link of a stopfacility. Effectively creates a new child stop facility.
 * ["changeRefLink"] [StopFacilityId] [newlinkId]
 * ["changeRefLink"] [TransitLineId] [TransitRouteId] [ParentId] [newlinkId]
 * ["changeRefLink"] ["allTransitRoutesOnLink"] [linkId] [ParentId] [newlinkId]
 */
@Test
public void changeRefLink() {
	TransitSchedule schedule = initSchedule();
	Network network = NetworkToolsTest.initNetwork();

	String[] cmd = new String[]{ScheduleEditor.CHANGE_REF_LINK, ScheduleEditor.ALL_TRANSIT_ROUTES_ON_LINK, "XA", "stop3.link:XA", "XB"};

	new BasicScheduleEditor(schedule, network).executeCmdLine(cmd);

	List<Id<Link>> linkIds = ScheduleTools.getTransitRouteLinkIds(schedule.getTransitLines().get(LINE_B).getRoutes().get(ROUTE_B));

	List<Id<Link>> linkIdsExpected = new ArrayList<>();
	linkIdsExpected.add(Id.createLinkId("EW"));
	linkIdsExpected.add(Id.createLinkId("WD"));
	linkIdsExpected.add(Id.createLinkId("DA"));
	linkIdsExpected.add(Id.createLinkId("AX"));
	linkIdsExpected.add(Id.createLinkId("XB"));
	linkIdsExpected.add(Id.createLinkId("BA"));
	linkIdsExpected.add(Id.createLinkId("AH"));
	linkIdsExpected.add(Id.createLinkId("HZ"));
	linkIdsExpected.add(Id.createLinkId("ZI"));
	linkIdsExpected.add(Id.createLinkId("IB"));

	Assert.assertEquals(linkIdsExpected, linkIds);
}
 
Example 8
@Override
public void handleEvent(LinkEnterEvent event) {
    if (AmodeusIdentifiers.isValid(event.getVehicleId())) {
        double distance = linkFinder.getDistance(event.getLinkId());

        for (Id<Person> passengerId : passengers.getPassengerIds(event.getVehicleId())) {
            PassengerRideItem ride = currentRides.get(passengerId);

            if (ride == null) {
                throw new IllegalStateException("Found vehicle enter link without departure");
            }

            ride.distance += distance;
        }
    }
}
 
Example 9
@Override
public void handleEvent(PersonDepartureEvent event) {
    if (AmodeusIdentifiers.isValid(event.getPersonId())) {
        String mode = AmodeusIdentifiers.getMode(event.getPersonId());
        Id<Vehicle> vehicleId = Id.createVehicleId(event.getPersonId());

        VehicleMovementItem movement = new VehicleMovementItem();
        movements.add(movement);

        movement.mode = mode;
        movement.vehicleId = vehicleId;

        movement.originLink = linkFinder.getLink(event.getLinkId());
        movement.departureTime = event.getTime();

        currentMovements.put(vehicleId, movement);
    }
}
 
Example 10
Source Project: pt2matsim   Source File: ScheduleCleaner.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Removes vehicles that are not used in the schedule
 */
public static void cleanVehicles(TransitSchedule schedule, Vehicles vehicles) {
	log.info("Removing not used vehicles...");
	int removed = 0;
	final Set<Id<Vehicle>> usedVehicles = new HashSet<>();
	for(TransitLine transitLine : schedule.getTransitLines().values()) {
		for(TransitRoute transitRoute : transitLine.getRoutes().values()) {
			for(Departure departure : transitRoute.getDepartures().values()) {
				usedVehicles.add(departure.getVehicleId());
			}
		}
	}
	for(Id<Vehicle> vehicleId : new HashSet<>(vehicles.getVehicles().keySet())) {
		if(!usedVehicles.contains(vehicleId)) {
			vehicles.removeVehicle(vehicleId);
			removed++;
		}
	}
	log.info(removed + " vehicles removed");
}
 
Example 11
public AmodeusPickupActivity(PassengerEngine passengerEngine, DynAgent driver, DvrpVehicle vehicle, Map<Id<Request>, PassengerRequest> requests, double expectedEndTime,
        double durationPerPassenger) {
    super(ACTIVITY_TYPE);

    this.expectedEndTime = expectedEndTime;
    this.durationPerPassenger = durationPerPassenger;

    this.passengerEngine = passengerEngine;
    this.driver = driver;

    this.requests = requests;

    if (requests.size() > vehicle.getCapacity()) {
        throw new IllegalStateException("Number of requests exceeds number of seats");
    }
}
 
Example 12
Source Project: pt2matsim   Source File: ScheduleCleaner.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Removes all minimal transfer times from not used transit stops. Modifies the schedule.
 *
 * @param schedule the schedule in which the minimal transfer times should be removed
 */
public static void removeNotUsedMinimalTransferTimes(TransitSchedule schedule) {
	log.info("... Removing not used minimal transfer times");

	Set<Id<TransitStopFacility>> usedStopFacilitiesId = schedule.getFacilities().keySet();

	MinimalTransferTimes transferTimes = schedule.getMinimalTransferTimes();
	MinimalTransferTimes.MinimalTransferTimesIterator iterator = transferTimes.iterator();

	int removed = 0;

	while(iterator.hasNext()) {
		iterator.next();
		if(!usedStopFacilitiesId.contains(iterator.getFromStopId()) || !usedStopFacilitiesId.contains(iterator.getToStopId())) {
			transferTimes.remove(iterator.getFromStopId(), iterator.getToStopId());
			removed += 1;
		}
	}
	log.info("    " + removed + " not used minimal transfer times facilities removed");
}
 
Example 13
Source Project: pt2matsim   Source File: ScheduleTools.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a vehicle type with id and parameters of defaultVehicleType. Used to create different default
 * vehicle types for schedules which can later changed manually in vehicles.xml
 */
public static VehicleType createDefaultVehicleType(String id, String defaultVehicleType) {
	String defVehType = defaultVehicleType.toUpperCase().replace(" ", "_");
	VehiclesFactory vf = VehicleUtils.createVehiclesContainer().getFactory();
	Id<VehicleType> vTypeId = Id.create(id, VehicleType.class);

	// using default values for vehicle type
	VehicleTypeDefaults.Type defaultValues = VehicleTypeDefaults.Type.OTHER;
	try {
		defaultValues = VehicleTypeDefaults.Type.valueOf(defVehType);
	} catch (IllegalArgumentException e) {
		log.warn("Vehicle category '" + defVehType + "' is unknown. Falling back to generic OTHER and adding to schedule.");
	}

	VehicleType vehicleType = vf.createVehicleType(vTypeId);
	vehicleType.setLength(defaultValues.length);
	vehicleType.setWidth(defaultValues.width);
	vehicleType.setAccessTime(defaultValues.accessTime);
	vehicleType.setEgressTime(defaultValues.egressTime);
	vehicleType.setDoorOperationMode(defaultValues.doorOperation);
	vehicleType.setPcuEquivalents(defaultValues.pcuEquivalents);

	VehicleCapacity capacity = vf.createVehicleCapacity();
	capacity.setSeats(defaultValues.capacitySeats);
	capacity.setStandingRoom(defaultValues.capacityStanding);
	vehicleType.setCapacity(capacity);

	return vehicleType;
}
 
Example 14
Source Project: amodeus   Source File: IDGenerator.java    License: GNU General Public License v2.0 5 votes vote down vote up
public IDGenerator(Population populationExisting) {
    this.usedIDs = populationExisting.getPersons().keySet();

    // find largest integer used in IDs
    largestInteger = usedIDs.stream().map(Id::toString).map(this::extractLargestInt) //
            .filter(OptionalInt::isPresent).mapToInt(OptionalInt::getAsInt).max().orElse(1);
}
 
Example 15
Source Project: pt2matsim   Source File: ShapeToolsTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Before
public void prepare() {
	Map<Id<RouteShape>, RouteShape> shapes = initShapes();
	this.shapeA1 = shapes.get(Id.create("A1", RouteShape.class));
	this.shapeA2 = shapes.get(Id.create("A2", RouteShape.class));
	this.shapeB = shapes.get(Id.create("B", RouteShape.class));
}
 
Example 16
/**
 * This constructor is only used to set dummy stops
 */
public PseudoRouteStopImpl(String id) {
	if(id.equals(PseudoGraphImpl.SOURCE)) {
		this.id = Id.create(PseudoGraphImpl.SOURCE, PseudoRouteStop.class);
		this.travelCostToSource = 0;
	} else {
		this.id = Id.create(PseudoGraphImpl.DESTINATION, PseudoRouteStop.class);
	}

	previous = null;

	this.linkId = null;

	// stop facility values
	this.coord = null;
	this.parentStopFacilityId = null;
	this.isBlockingLane = false;
	this.facilityName = null;
	this.stopAreaId = null;

	// route stop values
	this.departureOffset = 0.0;
	this.arrivalOffset = 0.0;
	this.awaitDepartureTime = false;

	// link value
	this.linkCandidate = null;
}
 
Example 17
Source Project: amodeus   Source File: Warmstarter.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void setNewMatching(List<Id<DvrpVehicle>> actTaxi, List<PassengerRequest> actRequest) {
    Id<DvrpVehicle> tmpTaxi = null;
    PassengerRequest tmpReq = null;
    int tmpTaxiId = UNASSIGNED;
    int last = UNASSIGNED;
    // List<Integer> taxiIDmatched = new ArrayList<>();
    // List<Integer> reqIDmatched = new ArrayList<>();

    for (int i = 0; i < lastTaxis.size(); i++) {
        tmpTaxi = lastTaxis.get(i);
        last = lastMatching[i];
        if (last >= lastRequests.size()) {
            continue;
        }
        tmpReq = lastRequests.get(last);
        if (!actTaxi.contains(tmpTaxi) || !actRequest.contains(tmpReq))
            continue; // Request is gone or taxi is gone or was matched to dummy job
        for (int j = 0; j < actTaxi.size(); j++) { // Find position of taxi in vector
            if (actTaxi.get(j).equals(tmpTaxi)) {
                tmpTaxiId = j;
                break;
            }
        }
        for (int j = 0; j < actRequest.size(); j++) {
            if (actRequest.get(j).equals(tmpReq)) {
                // taxiIDmatched.add(tmpTaxiId);
                // reqIDmatched.add(j);
                newMatching[tmpTaxiId] = j; // Find position of corresp request in vector
                break;
            }
        }
    }
    lastRequests = actRequest; // For next warmstart
    lastTaxis = actTaxi;
}
 
Example 18
Source Project: pt2matsim   Source File: GtfsFeedImplTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void compareShapes() {
	feed.transform(TransformationFactory.CH1903_LV03_Plus);
	for(Map.Entry<Id<RouteShape>, RouteShape> entry : ShapeToolsTest.initShapes().entrySet()) {
		RouteShape feedShape = feed.getShapes().get(entry.getKey());
		for(Map.Entry<Integer, Coord> coordEntry : entry.getValue().getCoordsSorted().entrySet()) {
			Assert.assertEquals(coordEntry.getValue(), feedShape.getCoordsSorted().get(coordEntry.getKey()));
		}
	}
}
 
Example 19
/**
 * @return the TransitRoute of the schedule based on transit line and transit route as strings
 */
private TransitRoute getTransitRoute(String transitLineStr, String transitRouteStr) {
	TransitLine transitLine = schedule.getTransitLines().get(Id.create(transitLineStr, TransitLine.class));
	if(transitLine == null) {
		throw new IllegalArgumentException("TransitLine " + transitLineStr + " not found!");
	}
	Id<TransitRoute> transitRouteId = Id.create(transitRouteStr, TransitRoute.class);
	if(!transitLine.getRoutes().containsKey(transitRouteId)) {
		throw new IllegalArgumentException("TransitRoute " + transitRouteStr + " not found in Transitline " + transitLineStr + "!");
	}
	return transitLine.getRoutes().get(transitRouteId);
}
 
Example 20
Source Project: amodeus   Source File: LinkWaitingTimeData.java    License: GNU General Public License v2.0 5 votes vote down vote up
public double getWaitingTime(Id<Link> linkId, double defaultWaitingTime) {
    if (isEmpty) {
        return defaultWaitingTime;
    }

    return waitingTimes.getOrDefault(linkId, defaultWaitingTime);
}
 
Example 21
/**
 * creates a new stop facility and adds it to the schedule
 */
public TransitStopFacility createStopFacility(Id<TransitStopFacility> facilityId, Coord coord, String name, Id<Link> linkId) {
	TransitStopFacility newTransitStopFacility = scheduleFactory.createTransitStopFacility(facilityId, coord, false);
	newTransitStopFacility.setName(name);
	newTransitStopFacility.setLinkId(linkId);
	return newTransitStopFacility;
}
 
Example 22
Source Project: amodeus   Source File: DynamicWaitingTime.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void registerWaitingTime(double time, double waitingTime, Id<Link> linkId) {
    int groupIndex = linkGroupDefinition.getGroup(linkId);
    int timeIndex = getTimeIndex(time);

    if (groupIndex != -1) {
        cumulativeValues[groupIndex][timeIndex] += waitingTime;
        observationCounts[groupIndex][timeIndex] += 1;
    }
}
 
Example 23
Source Project: pt2matsim   Source File: PTMapperTools.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static Id<Link> createArtificialLinkId(LinkCandidate fromLinkCandidate, LinkCandidate toLinkCandidate) {
	if(fromLinkCandidate.isLoopLink()) {
		return Id.createLinkId(PublicTransitMappingStrings.PREFIX_ARTIFICIAL + fromLinkCandidate.getStop().getStopFacility().getId() + "_" + toLinkCandidate.getLink().getId());
	} else if(toLinkCandidate.isLoopLink()) {
		return Id.createLinkId(PublicTransitMappingStrings.PREFIX_ARTIFICIAL + fromLinkCandidate.getLink().getId() + "_" + toLinkCandidate.getStop().getStopFacility().getId());
	} else {
		return Id.createLinkId(PublicTransitMappingStrings.PREFIX_ARTIFICIAL + fromLinkCandidate.getLink().getId() + "_" + toLinkCandidate.getLink().getId());
	}
}
 
Example 24
Source Project: amodeus   Source File: LinkGroupDefinition.java    License: GNU General Public License v2.0 5 votes vote down vote up
public Collection<Id<Link>> getLinkIds(int index) {
    if (index > maximumIndex) {
        throw new IllegalAccessError();
    }

    Set<Id<Link>> linkIds = new HashSet<>();

    for (Map.Entry<Id<Link>, Integer> entry : indices.entrySet()) {
        if (entry.getValue() == index) {
            linkIds.add(entry.getKey());
        }
    }

    return linkIds;
}
 
Example 25
public void writeToFile(Path outputPath) throws IOException {
	try (BufferedWriter writer = Files.newBufferedWriter(outputPath)) {
		writer.write("LinkId" + SEPARATOR + "Geometry\n");
		for (Entry<Id<Link>, LinkDefinition> entry : linkDefinitions.entrySet()) {
			Optional<String> wkt = toWkt(entry.getValue());
			if (wkt.isPresent()) {
				writer.write(String.format("%s%s\"%s\"\n", entry.getKey(), SEPARATOR, wkt.get()));
			}
		}
	}
}
 
Example 26
/**
 * Replaces a stop facility with another one in the given route. Both ids must exist.
 */
public void replaceStopFacilityInRoute(TransitLine transitLine, TransitRoute transitRoute, Id<TransitStopFacility> toReplaceId, Id<TransitStopFacility> replaceWithId) {
	TransitStopFacility toReplace = schedule.getFacilities().get(toReplaceId);
	TransitStopFacility replaceWith = schedule.getFacilities().get(replaceWithId);

	if(toReplace == null) {
		throw new IllegalArgumentException("StopFacility " + toReplaceId + " not found in schedule!");
	} else if(replaceWith == null) {
		throw new IllegalArgumentException("StopFacility " + replaceWithId + " not found in schedule!");
	}
	replaceStopFacilityInRoute(transitLine, transitRoute, toReplace, replaceWith);
}
 
Example 27
/**
 * Adds a child stop facility for the given refLink, creates
 * a new one if needed.
 * @param refLinkId the id of the ref link
 * @return the childStopFacility
 */
public TransitStopFacility getChildStopFacility(Id<Link> refLinkId) {
	Id<TransitStopFacility> newChildStopId = ScheduleTools.createChildStopFacilityId(id, refLinkId.toString());
	TransitStopFacility newChildStopFacilty = schedule.getFacilities().get(newChildStopId);
	if(newChildStopFacilty == null) {
		newChildStopFacilty = createStopFacility(newChildStopId, this.coord, this.name, refLinkId);
		newChildStopFacilty.setLinkId(refLinkId);
		newChildStopFacilty.setStopAreaId(Id.create(this.id, TransitStopArea.class));
		schedule.addStopFacility(newChildStopFacilty);
	}
	children.put(newChildStopFacilty.getLinkId(), newChildStopFacilty);
	return newChildStopFacilty;
}
 
Example 28
Source Project: amodeus   Source File: PassengerTracker.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void removePassenger(Id<Vehicle> vehicleId, Id<Person> passengerId) {
    ensurePassengers(vehicleId);

    if (!passengers.get(vehicleId).remove(passengerId)) {
        throw new IllegalStateException(String.format("Passenger '%s' is not in vehicle '%s'", passengerId, vehicleId));
    }
}
 
Example 29
Source Project: pt2matsim   Source File: PTMapperTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void noTransportModeAssignment() {
	PublicTransitMappingConfigGroup noTMAConfig = new PublicTransitMappingConfigGroup();
	noTMAConfig.getModesToKeepOnCleanUp().add("car");
	noTMAConfig.setNumOfThreads(2);
	noTMAConfig.setNLinkThreshold(4);
	noTMAConfig.setMaxLinkCandidateDistance(999.0);
	noTMAConfig.setCandidateDistanceMultiplier(1.0);

	TransitSchedule schedule2 = ScheduleToolsTest.initUnmappedSchedule();
	Network network2 = NetworkToolsTest.initNetwork();

	new PTMapper(schedule2, network2).run(noTMAConfig);

	// only artificial links
	for(TransitLine transitLine : schedule2.getTransitLines().values()) {
		for(TransitRoute transitRoute : transitLine.getRoutes().values()) {
			List<Id<Link>> linkIds = ScheduleTools.getTransitRouteLinkIds(transitRoute);
			for(Id<Link> linkId : linkIds) {
				Assert.assertTrue(linkId.toString().contains("pt_"));
			}
		}
	}
	// only artificial stop links
	for(TransitStopFacility transitStopFacility : schedule2.getFacilities().values()) {
		Assert.assertTrue(transitStopFacility.getLinkId().toString().contains("pt_"));
	}
}
 
Example 30
Source Project: pt2matsim   Source File: GtfsConverterTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void combineRoutes() {
	TransitSchedule test = ScheduleTools.createSchedule();
	TransitScheduleFactory f = test.getFactory();
	Id<TransitLine> lineId = Id.create("L", TransitLine.class);
	TransitLine line = f.createTransitLine(lineId);
	test.addTransitLine(line);

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

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

	Assert.assertEquals(3, line.getRoutes().size());
	// only routes with identical stop sequence (1, 2, 3) and departure sequence (2, 3) are combined.
	gtfsConverter.combineTransitRoutes(test);
	Assert.assertEquals(2, line.getRoutes().size());
}