Java Code Examples for org.matsim.api.core.v01.population.Person

The following examples show how to use org.matsim.api.core.v01.population.Person. 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 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 2
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 3
Source Project: amodeus   Source File: CompatibilityModule.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void notifyStartup(StartupEvent event) {
    boolean anyWarnings = false;
    for (Person person : event.getServices().getScenario().getPopulation().getPersons().values()) {
        boolean skip = false;
        for (Plan plan : person.getPlans()) {
            if (skip)
                break;
            for (PlanElement element : plan.getPlanElements()) {
                if (skip)
                    break;
                if (element instanceof Activity) {
                    Activity activity = (Activity) element;
                    if (activity.getCoord() == null) {
                        logger.error(String.format("Agent '%s' has activity without coordiantes", person.getId()));
                        anyWarnings = true;
                        skip = true;
                    }
                }
            }
        }
    }
    if (anyWarnings)
        throw new RuntimeException(//
                "Since the last update of Amodeus it is necessary that each activity in a MATSim popuatlion" //
                        + " has a coordinate and not only a link ID to determine its location. You can either modify the way" //
                        + " you generate your population or use the AddCoordinatesToActivities tool to automatically " //
                        + "assign to each activity the coordinate of the currently associated link.");
}
 
Example 4
Source Project: amodeus   Source File: TheApocalypse.java    License: GNU General Public License v2.0 5 votes vote down vote up
public TheApocalypse toNoMoreThan(int maxPrs, long seed) {
    List<Id<Person>> list = new ArrayList<>(population.getPersons().keySet());
    Collections.shuffle(list, new Random(seed));
    final int sizeAnte = list.size();
    list.stream() //
            .limit(Math.max(0, sizeAnte - maxPrs)) //
            .forEach(population::removePerson);
    final int sizePost = population.getPersons().size();
    GlobalAssert.that(sizePost <= maxPrs);
    return this;
}
 
Example 5
Source Project: amodeus   Source File: IDGenerator.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** @return new ID which is not yet in set usedIDs */
public Id<Person> generateUnusedID() {
    largestInteger++;
    String newIDs = idName + String.format(format, largestInteger);
    Id<Person> newId = Id.create(newIDs, Person.class);
    usedIDs.add(newId);
    return newId;
}
 
Example 6
Source Project: amodeus   Source File: NetworkCreatorUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** @param population
 * @param network
 * @return double of length m,2 with m datapoints and their x,y coordinate where datapoits represent all
 *         Activities of agents in population. */
public static double[][] fromPopulation(Population population, Network network) {
    // FOR ALL activities find positions, record in list and store in array
    List<double[]> dataList = new ArrayList<>();

    for (Person person : population.getPersons().values())
        for (Plan plan : person.getPlans())
            for (PlanElement planElement : plan.getPlanElements())
                if (planElement instanceof Activity) {
                    Activity activity = (Activity) planElement;
                    if (!TripStructureUtils.isStageActivityType(activity.getType())) {
                        Link link = network.getLinks().getOrDefault(activity.getLinkId(), null);
                        if (Objects.nonNull(link)) {
                            double x = link.getCoord().getX();
                            double y = link.getCoord().getY();
                            dataList.add(new double[] { x, y });
                        } else {
                            LOGGER.warn(String.format("Link '%s' not found for agent '%s'. Either the link does not exist or has invalid modes?",
                                    activity.getLinkId().toString(), person.getId().toString()));
                        }
                    }
                }

    // final double data[][] = new double[dataList.size()][2];
    // for (int i = 0; i < dataList.size(); ++i) {
    // data[i][0] = dataList.get(i)[0];
    // data[i][1] = dataList.get(i)[1];
    // }
    // return data;
    return dataList.toArray(new double[dataList.size()][2]);
}
 
Example 7
Source Project: amodeus   Source File: TheRequestApocalypse.java    License: GNU General Public License v2.0 5 votes vote down vote up
public TheRequestApocalypse toNoMoreThan(int maxRequests, long seed) {
    final long legCount = LegCount.of(population, AmodeusModeConfig.DEFAULT_MODE);
    GlobalAssert.that(maxRequests <= legCount);
    if (legCount == maxRequests)
        return this;

    /** shuffle list of {@link Person}s */
    List<Person> list = new ArrayList<>(population.getPersons().values());
    Collections.shuffle(list, new Random(seed));
    Iterator<Person> iterator = list.iterator();

    // skip all persons that should completely remain in the population
    Person person = iterator.next();
    int totReq = 0;
    long req = LegCount.of(person, AmodeusModeConfig.DEFAULT_MODE);
    while (totReq + req <= maxRequests) {
        totReq += req;
        person = iterator.next();
        req = LegCount.of(person, AmodeusModeConfig.DEFAULT_MODE);
    }

    // create new person if needed to fill requests
    int split = maxRequests - totReq;
    if (split != 0) {
        Person splitPerson = SplitUp.of(population, person, split, AmodeusModeConfig.DEFAULT_MODE);
        req = LegCount.of(splitPerson, AmodeusModeConfig.DEFAULT_MODE);
        totReq += req;
        GlobalAssert.that(totReq == maxRequests);
        population.addPerson(splitPerson);
    }

    // remove all remaining persons
    iterator.forEachRemaining(p -> population.removePerson(p.getId()));
    population.removePerson(person.getId());
    GlobalAssert.that(LegCount.of(population, AmodeusModeConfig.DEFAULT_MODE) == maxRequests);
    return this;
}
 
Example 8
Source Project: amodeus   Source File: LSDataTravelTime.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public double getLinkTravelTime(Link link, double time, Person person, Vehicle vehicle) {
    double speed = link.getFreespeed();
    LinkSpeedTimeSeries timeSeries = lsData.get(link);
    if (Objects.nonNull(timeSeries))
        speed = timeSeries.getSpeedsFloor((int) time);
    return link.getLength() / speed;
}
 
Example 9
@Override
protected Collection<? extends Link> getLinks(Network network, Population population) {
    HashSet<Link> populatedLinks = new HashSet<>();
    for (Person person : population.getPersons().values())
        for (Plan plan : person.getPlans())
            for (PlanElement planElement : plan.getPlanElements())
                if (planElement instanceof Activity) {
                    Activity activity = (Activity) planElement;
                    populatedLinks.add(network.getLinks().get(activity.getLinkId()));
                }
    return populatedLinks;
}
 
Example 10
@Override
public Future<Path> calcLeastCostPath(Node fromNode, Node toNode, double starttime, Person person, Vehicle vehicle) {
    Future<Path> future = executor.submit(() -> {
        LeastCostPathCalculator calculator = calculators.take();
        Path path = calculator.calcLeastCostPath(fromNode, toNode, starttime, person, vehicle);
        calculators.put(calculator);
        return path;
    });

    // futures.add(future);
    return future;
}
 
Example 11
Source Project: amodeus   Source File: PassengerTracker.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void addPassenger(Id<Vehicle> vehicleId, Id<Person> passengerId) {
    ensurePassengers(vehicleId);

    if (!passengers.get(vehicleId).add(passengerId)) {
        throw new IllegalStateException(String.format("Passenger '%s' is already in vehicle '%s'", passengerId, vehicleId));
    }
}
 
Example 12
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 13
public AmodeusModalScoringParameters getScoringParameters(Person person) {
    String subpopulation = PopulationUtils.getSubpopulation(person);
    ScoringParameters scoringParameters = delegate.getScoringParameters(person);

    if (!parameters.containsKey(subpopulation)) {
        parameters.put(subpopulation, new AmodeusModalScoringParameters(subpopulation, amodeusConfig, scoringParameters));
    }

    return parameters.get(subpopulation);
}
 
Example 14
Source Project: amodeus   Source File: AmodeusRequestEvent.java    License: GNU General Public License v2.0 5 votes vote down vote up
private AmodeusRequestEvent(double time, Id<Person> personId, String mode, Optional<Double> expectedDistance, OptionalTime expectedTravelTime, Optional<Double> expectedPrice,
        OptionalTime expectedWaitingTime) {
    super(time);

    this.personId = personId;
    this.mode = mode;

    this.expectedDistance = expectedDistance;
    this.expectedTravelTime = expectedTravelTime;
    this.expectedPrice = expectedPrice;
    this.expectedWaitingTime = expectedWaitingTime;
}
 
Example 15
Source Project: amodeus   Source File: AmodeusRequest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public AmodeusRequest(Id<Request> id, Id<Person> passengerId, Link pickupLink, Link dropoffLink, double submissionTime, String mode, AmodeusRoute route) {
    this.id = id;
    this.passengerId = passengerId;
    this.pickupLink = pickupLink;
    this.dropoffLink = dropoffLink;
    this.submissionTime = submissionTime;
    this.mode = mode;
    this.route = route;
}
 
Example 16
Source Project: amodeus   Source File: RunTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testStuckScoring() {
    AmodeusConfigGroup avConfigGroup = new AmodeusConfigGroup();

    AmodeusModeConfig operatorConfig = new AmodeusModeConfig(AmodeusModeConfig.DEFAULT_MODE);
    operatorConfig.getGeneratorConfig().setNumberOfVehicles(0);
    avConfigGroup.addMode(operatorConfig);

    AmodeusScoringConfig scoringParams = operatorConfig.getScoringParameters(null);
    scoringParams.setMarginalUtilityOfWaitingTime(-0.84);

    Config config = ConfigUtils.createConfig(avConfigGroup, new DvrpConfigGroup());
    Scenario scenario = TestScenarioGenerator.generateWithAVLegs(config);
    config.planCalcScore().getOrCreateModeParams(AmodeusModeConfig.DEFAULT_MODE); // Refactor av

    Controler controler = new Controler(scenario);
    controler.addOverridingModule(new DvrpModule());
    controler.addOverridingModule(new AmodeusModule());
    controler.addOverridingQSimModule(new AmodeusQSimModule());

    controler.configureQSimComponents(AmodeusQSimModule.activateModes(avConfigGroup));

    controler.run();

    for (Person person : scenario.getPopulation().getPersons().values()) {
        Assert.assertEquals(-1000.0, person.getSelectedPlan().getScore(), 1e-6);
    }
}
 
Example 17
static private void generatePopulation(Population population, Network network, Random random) {
    PopulationFactory populationFactory = population.getFactory();

    List<Id<Link>> linkIds = network.getLinks().values().stream().map(link -> link.getId()).collect(Collectors.toList());

    for (int k = 0; k < populationSize; k++) {
        Person person = populationFactory.createPerson(Id.createPersonId(k));
        population.addPerson(person);

        Id<Link> originId = linkIds.get(random.nextInt(linkIds.size()));
        Id<Link> destinationId = linkIds.get(random.nextInt(linkIds.size()));
        double departureTime = random.nextDouble() * duration * 0.5;

        Plan plan = populationFactory.createPlan();
        person.addPlan(plan);

        Activity originActivity = populationFactory.createActivityFromLinkId("activity", originId);
        originActivity.setEndTime(departureTime);
        originActivity.setCoord(network.getLinks().get(originId).getCoord());
        plan.addActivity(originActivity);

        plan.addLeg(populationFactory.createLeg(defaultMode));

        Activity destinationActivity = populationFactory.createActivityFromLinkId("activity", destinationId);
        destinationActivity.setCoord(network.getLinks().get(destinationId).getCoord());
        plan.addActivity(destinationActivity);
    }
}
 
Example 18
Source Project: amodeus   Source File: WaitingTimeTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testConstantWaitingTime() {
    AmodeusConfigGroup config = createConfig();
    AmodeusModeConfig operatorConfig = config.getModes().get(AmodeusModeConfig.DEFAULT_MODE);

    operatorConfig.getWaitingTimeEstimationConfig().setDefaultWaitingTime(123.0);

    Controler controller = createController(config);
    controller.run();

    Population population = controller.getScenario().getPopulation();

    int numberOfRoutes = 0;

    for (Person person : population.getPersons().values()) {
        Plan plan = person.getSelectedPlan();

        for (PlanElement element : plan.getPlanElements()) {
            if (element instanceof Leg) {
                Leg leg = (Leg) element;
                AmodeusRoute route = (AmodeusRoute) leg.getRoute();

                Assert.assertEquals(route.getWaitingTime().seconds(), 123.0, 1e-2);
                numberOfRoutes++;
            }
        }
    }

    Assert.assertEquals(100, numberOfRoutes);
}
 
Example 19
private RebalanceVehicleEvent(double time, Id<Person> agentId, Id<Link> linkId) {
    super(time);

    this.personId = agentId;
    this.linkId = linkId;
}
 
Example 20
@Override
public Id<Person> getPersonId() {
    return personId;
}
 
Example 21
Source Project: amodeus   Source File: DefaultAStarLMRouter.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public Future<Path> calcLeastCostPath(Node fromNode, Node toNode, double starttime, //
        Person person, Vehicle vehicle) {
    return delegate.calcLeastCostPath(fromNode, toNode, starttime, person, vehicle);
}
 
Example 22
Source Project: amodeus   Source File: TaxiTravelTimeRouter.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public Future<Path> calcLeastCostPath(Node fromNode, Node toNode, double starttime, Person person, Vehicle vehicle) {
    return delegate.calcLeastCostPath(fromNode, toNode, starttime, person, vehicle);
}
 
Example 23
@Override
public Future<Path> calcLeastCostPath(Node fromNode, Node toNode, double starttime, Person person, Vehicle vehicle) {
    return ConcurrentUtils.constantFuture(delegate.calcLeastCostPath(fromNode, toNode, starttime, person, vehicle));
}
 
Example 24
Source Project: amodeus   Source File: PassengerTracker.java    License: GNU General Public License v2.0 4 votes vote down vote up
public boolean hasPassenger(Id<Vehicle> vehicleId, Id<Person> passengerId) {
    ensurePassengers(vehicleId);
    return passengers.get(vehicleId).contains(passengerId);
}
 
Example 25
Source Project: amodeus   Source File: PassengerTracker.java    License: GNU General Public License v2.0 4 votes vote down vote up
public Collection<Id<Person>> getPassengerIds(Id<Vehicle> vehicleId) {
    ensurePassengers(vehicleId);
    return passengers.get(vehicleId);
}
 
Example 26
Source Project: amodeus   Source File: PassengerTracker.java    License: GNU General Public License v2.0 4 votes vote down vote up
public void clear() {
    for (Set<Id<Person>> passengerList : passengers.values()) {
        passengerList.clear();
    }
}
 
Example 27
@Override
public ScoringFunction createNewScoringFunction(Person person) {
    SumScoringFunction scoringFunction = (SumScoringFunction) delegate.createNewScoringFunction(person);
    scoringFunction.addScoringFunction(new AmodeusScoringFunction(modes, parameters.getScoringParameters(person)));
    return scoringFunction;
}
 
Example 28
Source Project: amodeus   Source File: AmodeusRequestEvent.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public Id<Person> getPersonId() {
    return personId;
}
 
Example 29
Source Project: amodeus   Source File: AmodeusRequest.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public Id<Person> getPassengerId() {
    return passengerId;
}
 
Example 30
@Override
public PassengerRequest createRequest(Id<Request> id, Id<Person> passengerId, Route route, Link pickupLink, Link dropoffLink, double departureTime, double submissionTime) {
    return new AmodeusRequest(id, passengerId, pickupLink, dropoffLink, submissionTime, mode, (AmodeusRoute) route);
}