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

The following examples show how to use org.matsim.api.core.v01.population.Population. 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
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 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
public void testSimple() throws Exception {
    File workingDirectory = MultiFileTools.getDefaultWorkingDirectory();

    /** download a scenario */
    File scenarioDirectory = //
            new File(Locate.repoFolder(ScenarioExecutionTest.class, "amodeus"), "resources/testScenario");
    GlobalAssert.that(workingDirectory.isDirectory());
    TestFileHandling.copyScnearioToMainDirectory(scenarioDirectory.getAbsolutePath(), //
            workingDirectory.getAbsolutePath());

    /** prepare a scenario */
    Preparer preparer = new Preparer(workingDirectory);
    Population population = preparer.population;

    PopulationCutter populationCutter = preparer.scenOpt.getPopulationCutter();
    populationCutter.cut(population, preparer.network, preparer.config);

    /** reduce the number of legs */
    int numReqDes = 3000;
    long seed = 1234;
    TheRequestApocalypse.reducesThe(population).toNoMoreThan(numReqDes, seed);

    /** ensure testing worked correctly */
    assertEquals(numReqDes, (int) LegCount.of(population, AmodeusModeConfig.DEFAULT_MODE));
}
 
Example 4
@BeforeClass
public static void setup() throws IOException {

    /* input data */
    File scenarioDirectory = new File(Locate.repoFolder(KMeansVirtualNetworkCreatorTest.class, "amodeus"), "resources/testScenario");
    ScenarioOptions scenarioOptions = new ScenarioOptions(scenarioDirectory, ScenarioOptionsBase.getDefault());
    File configFile = new File(scenarioOptions.getPreparerConfigName());

    AmodeusConfigGroup avCg = new AmodeusConfigGroup();
    Config config = ConfigUtils.loadConfig(configFile.getAbsolutePath(), avCg);
    GeneratorConfig genConfig = avCg.getModes().values().iterator().next().getGeneratorConfig();
    int numRt = genConfig.getNumberOfVehicles();
    int endTime = (int) config.qsim().getEndTime().seconds();
    Scenario scenario = ScenarioUtils.loadScenario(config);
    Network network = scenario.getNetwork();
    Population population = scenario.getPopulation();
    numVNodes = scenarioOptions.getNumVirtualNodes();
    VirtualNetworkCreator virtualNetworkCreator = scenarioOptions.getVirtualNetworkCreator();

    /* generate nCreations networks */
    for (int i = 0; i < nCreations; ++i)
        virtualNetworks.add(virtualNetworkCreator.create(network, population, scenarioOptions, numRt, endTime));
}
 
Example 5
public static VirtualNetwork<Link> createVirtualNetwork(Population population, Network network, int numVNodes, //
        boolean completeGraph) {
    @SuppressWarnings("unchecked")
    Collection<Link> elements = (Collection<Link>) network.getLinks().values();
    Map<Node, Set<Link>> uElements = NodeAdjacencyMap.of(network);

    /** generating centroids on a ring */
    List<Link> centroids = getRingCentroids(network, numVNodes);

    /** create the virtual network using the centroidvirtualNetworkCreator */
    CentroidVirtualNetworkCreator<Link, Node> vnc = new CentroidVirtualNetworkCreator<>(//
            elements, centroids, TensorLocation::of, NetworkCreatorUtils::linkToID, uElements, completeGraph);
    return vnc.getVirtualNetwork();
}
 
Example 6
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 7
@Override
public void process(Population population) {
    PopulationRemove.outsideNetwork(population, network);
    System.out.println("population size after removing all people outside the network: " + population.getPersons().size());
    // TODO @clruch why is this here? check and remove tODO big tODO massive tODO
    PopulationTimeInterval.removeOutside(population, endTime);
    System.out.println("population size after removing all people outside the time interval: " + population.getPersons().size());
}
 
Example 8
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 9
Source Project: amodeus   Source File: AmodeusParkingModule.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Provides
@Singleton
public ParkingCapacity provideAVSpatialCapacity(Network network, Population population) {
    try {
        ParkingCapacityGenerator generator = scenarioOptions.getParkingCapacityGenerator();
        parkingCapacity = generator.generate(network, population, scenarioOptions);
        return parkingCapacity;
    } catch (Exception exception) {
        System.err.println("Unable to load parking capacity for all links, returning null.");
        exception.printStackTrace();
    }
    return null;
}
 
Example 10
@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 11
static private VirtualNetwork<Link> provideVirtualNetworkFromConfig(InstanceGetter getter) {
    try {
        ScenarioOptions scenarioOptions = getter.get(ScenarioOptions.class);
        Config config = getter.get(Config.class);
        Population population = getter.get(Population.class);

        AmodeusModeConfig modeConfig = getter.getModal(AmodeusModeConfig.class);
        DispatcherConfig dispatcherConfig = modeConfig.getDispatcherConfig();
        Network network = getter.getModal(Network.class);

        URL virtualNetworkUrl = ConfigGroup.getInputFileURL(config.getContext(), dispatcherConfig.getVirtualNetworkPath());
        File virtualNetworkFile = new File(virtualNetworkUrl.getPath());

        if (!virtualNetworkFile.exists() || dispatcherConfig.getRegenerateVirtualNetwork()) {
            logger.info(String.format("Regenerating VirtualNetwork for mode '%s' at '%s'", modeConfig.getMode(), virtualNetworkFile));
            logger.info("Currently we use information from ScenarioOptions for that. Later on this should be moved to a specific config module.");
            logger.info(String.format("Using VirtualNetworkCreator: %s", scenarioOptions.getVirtualNetworkCreator().getClass().getSimpleName()));

            int numberOfVehicles = modeConfig.getGeneratorConfig().getNumberOfVehicles();
            VirtualNetwork<Link> virtualNetwork = scenarioOptions.getVirtualNetworkCreator().create(network, population, scenarioOptions, numberOfVehicles, //
                    (int) config.qsim().getEndTime().seconds());

            VirtualNetworkIO.toByte(virtualNetworkFile, virtualNetwork);
        }

        logger.info(String.format("Loading VirtualNetwork for operator '%s' from '%s'", modeConfig.getMode(), virtualNetworkFile));
        return VirtualNetworkGet.readFile(network, virtualNetworkFile);
    } catch (IOException | ClassNotFoundException | DataFormatException e) {
        throw new RuntimeException(e);
    }
}
 
Example 12
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 13
@Override
public AmodeusGenerator createGenerator(InstanceGetter inject) {
    AmodeusModeConfig modeConfig = inject.getModal(AmodeusModeConfig.class);
    Network network = inject.getModal(Network.class);

    Population population = inject.get(Population.class);
    ActivityFacilities facilities = inject.get(ActivityFacilities.class);

    GeneratorConfig generatorConfig = modeConfig.getGeneratorConfig();
    int capacity = generatorConfig.getCapacity();
    int randomSeed = Integer.parseInt(generatorConfig.getParams().getOrDefault("randomSeed", "1234"));

    return new PopulationDensityGenerator(modeConfig.getMode(), generatorConfig.getNumberOfVehicles(), network, population, facilities, randomSeed, capacity);
}
 
Example 14
@Test
public void testA_Preparer() throws Exception {
    System.out.print("Preparer Test:\t");

    // run scenario preparer
    TestPreparer testPreparer = TestPreparer.run(testServer.getWorkingDirectory());

    // creation of files
    File preparedPopulationFile = new File("preparedPopulation.xml");
    assertTrue(preparedPopulationFile.isFile());

    File preparedNetworkFile = new File("preparedNetwork.xml");
    assertTrue(preparedNetworkFile.isFile());

    File config = new File("config.xml");
    assertTrue(config.isFile());

    // consistency of network (here no cutting)
    Network originalNetwork = NetworkLoader.fromConfigFile(testServer.getConfigFile());
    Network preparedNetwork = testPreparer.getPreparedNetwork();
    GlobalAssert.that(Objects.nonNull(originalNetwork));
    GlobalAssert.that(Objects.nonNull(preparedNetwork));
    assertEquals(preparedNetwork.getNodes().size(), originalNetwork.getNodes().size());
    assertEquals(preparedNetwork.getLinks().size(), originalNetwork.getLinks().size());

    // consistency of population
    Population population = testPreparer.getPreparedPopulation();
    assertEquals(250, population.getPersons().size());
}
 
Example 15
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 16
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 17
Source Project: amodeus   Source File: TheApocalypse.java    License: GNU General Public License v2.0 4 votes vote down vote up
public static TheApocalypse reducesThe(Population population) {
    return new TheApocalypse(population);
}
 
Example 18
Source Project: amodeus   Source File: TheApocalypse.java    License: GNU General Public License v2.0 4 votes vote down vote up
private TheApocalypse(Population population) {
    this.population = population;
}
 
Example 19
Source Project: amodeus   Source File: TheRequestApocalypse.java    License: GNU General Public License v2.0 4 votes vote down vote up
public static TheRequestApocalypse reducesThe(Population population) {
    return new TheRequestApocalypse(population);
}
 
Example 20
Source Project: amodeus   Source File: TheRequestApocalypse.java    License: GNU General Public License v2.0 4 votes vote down vote up
private TheRequestApocalypse(Population population) {
    this.population = population;
}
 
Example 21
/** assigns totSpaces randomly chosen links from the network a parking space, there may
 * be multiple parking spaces per link */
public ParkingCapacityUniformRandom(Network network, Population population, //
        long totSpaces, Random random) {
    super(network, population, totSpaces, random);
}
 
Example 22
@Override
protected Collection<? extends Link> getLinks(Network network, Population population) {
    return network.getLinks().values();
}
 
Example 23
/** assigns totSpaces randomly chosen links from the network a parking space, there may
 * be multiple parking spaces per link */
public ParkingCapacityAbstractUniform(Network network, Population population, long totSpaces, Random random) {
    fillUsingLinks(getLinks(network, population), totSpaces, random);
}
 
Example 24
/** assigns totSpaces randomly chosen links from the network a parking space, there may
 * be multiple parking spaces per link */
public ParkingCapacityUniformRandomPopulationZone(Network network, Population population, //
        long totSpaces, Random random) {
    super(network, population, totSpaces, random);
}
 
Example 25
Source Project: amodeus   Source File: TestPreparer.java    License: GNU General Public License v2.0 4 votes vote down vote up
public Population getPreparedPopulation() {
    return populationPrepared;
}
 
Example 26
Source Project: amodeus   Source File: TestServer.java    License: GNU General Public License v2.0 4 votes vote down vote up
public void simulate() throws Exception {
    boolean waitForClients = scenarioOptions.getBoolean("waitForClients");
    StaticHelper.setup();

    LocationSpec locationSpec = scenarioOptions.getLocationSpec();

    ReferenceFrame referenceFrame = locationSpec.referenceFrame();

    // open server port for clients to connect to
    SimulationServer.INSTANCE.startAcceptingNonBlocking();
    SimulationServer.INSTANCE.setWaitForClients(waitForClients);

    // load MATSim configs - including av.xml where dispatcher is selected.
    System.out.println("loading config file " + configFile.getAbsoluteFile());

    GlobalAssert.that(configFile.exists()); // Test whether the config file
    // directory exists

    DvrpConfigGroup dvrpConfigGroup = new DvrpConfigGroup();
    dvrpConfigGroup.setTravelTimeEstimationAlpha(0.05);
    Config config = ConfigUtils.loadConfig(configFile.toString(), new AmodeusConfigGroup(), dvrpConfigGroup);
    config.planCalcScore().addActivityParams(new PlanCalcScoreConfigGroup.ActivityParams("activity"));

    config.qsim().setStartTime(0.0);
    config.qsim().setSimStarttimeInterpretation(StarttimeInterpretation.onlyUseStarttime);

    for (ActivityParams activityParams : config.planCalcScore().getActivityParams())
        // TODO @sebhoerl fix this to meaningful values, remove, or add comment
        // this was added because there are sometimes problems, is there a more elegant option?
        activityParams.setTypicalDuration(3600.0);

    String outputdirectory = config.controler().getOutputDirectory();
    System.out.println("outputdirectory = " + outputdirectory);

    // load scenario for simulation
    Scenario scenario = ScenarioUtils.loadScenario(config);
    Network network = scenario.getNetwork();
    Population population = scenario.getPopulation();
    GlobalAssert.that(Objects.nonNull(network) && Objects.nonNull(population));

    MatsimAmodeusDatabase db = MatsimAmodeusDatabase.initialize(network, referenceFrame);
    Controler controller = new Controler(scenario);
    AmodeusConfigurator.configureController(controller, db, scenarioOptions);

    // run simulation
    controller.run();

    // close port for visualization
    SimulationServer.INSTANCE.stopAccepting();

    Analysis analysis = Analysis.setup(scenarioOptions, new File(workingDirectory, "output/001"), network, db);
    analysis.addAnalysisExport(ate);
    analysis.addAnalysisExport(new RoboTaxiHistoriesExportFromEvents(network, config));
    analysis.addAnalysisExport(new RequestHistoriesExportFromEvents(network, config));
    analysis.run();
}
 
Example 27
Source Project: amodeus   Source File: WaitingTimeTest.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testAttributeWaitingTime() {
    AmodeusConfigGroup config = createConfig();
    AmodeusModeConfig operatorConfig = config.getModes().get(AmodeusModeConfig.DEFAULT_MODE);

    operatorConfig.getWaitingTimeEstimationConfig().setDefaultWaitingTime(123.0);
    operatorConfig.getWaitingTimeEstimationConfig().setConstantWaitingTimeLinkAttribute("avWaitingTime");

    Controler controller = createController(config);

    Link link = controller.getScenario().getNetwork().getLinks().get(Id.createLinkId("8:9_9:9"));
    link.getAttributes().putAttribute("avWaitingTime", 456.0);

    controller.run();

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

    int numberOfRoutes = 0;
    int numberOfSpecialRoutes = 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();

                if (Id.createLinkId("8:9_9:9").equals(route.getStartLinkId())) {
                    Assert.assertEquals(route.getWaitingTime().seconds(), 456.0, 1e-2);
                    numberOfSpecialRoutes++;
                } else {
                    Assert.assertEquals(route.getWaitingTime().seconds(), 123.0, 1e-2);
                }

                numberOfRoutes++;
            }
        }
    }

    Assert.assertEquals(100, numberOfRoutes);
    Assert.assertEquals(2, numberOfSpecialRoutes);
}
 
Example 28
Source Project: amodeus   Source File: WaitingTimeTest.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testDynamicWaitingTime() {
    AmodeusConfigGroup config = createConfig();
    AmodeusModeConfig operatorConfig = config.getModes().get(AmodeusModeConfig.DEFAULT_MODE);

    operatorConfig.getWaitingTimeEstimationConfig().setDefaultWaitingTime(123.0);
    operatorConfig.getWaitingTimeEstimationConfig().setConstantWaitingTimeLinkAttribute("avWaitingTime");
    operatorConfig.getWaitingTimeEstimationConfig().setEstimationLinkAttribute("avGroup");
    operatorConfig.getWaitingTimeEstimationConfig().setEstimationAlpha(0.7);

    Controler controller = createController(config);

    Link link = controller.getScenario().getNetwork().getLinks().get(Id.createLinkId("8:9_9:9"));
    link.getAttributes().putAttribute("avWaitingTime", 456.0);

    int index = 0;
    for (Link _link : controller.getScenario().getNetwork().getLinks().values()) {
        _link.getAttributes().putAttribute("avGroup", index++);
    }

    controller.getConfig().controler().setLastIteration(2);

    StrategySettings strategy = new StrategySettings();
    strategy.setStrategyName("ReRoute");
    strategy.setWeight(1.0);
    controller.getConfig().strategy().addStrategySettings(strategy);

    List<Double> waitingTimes = new LinkedList<>();

    controller.addControlerListener(new IterationEndsListener() {
        @Override
        public void notifyIterationEnds(IterationEndsEvent event) {
            Population population = event.getServices().getScenario().getPopulation();
            Person person = population.getPersons().get(Id.createPersonId(17));
            Plan plan = person.getSelectedPlan();

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

                    if (Id.createLinkId("8:9_9:9").equals(route.getStartLinkId())) {
                        waitingTimes.add(route.getWaitingTime().seconds());
                    }
                }
            }
        }
    });

    controller.run();

    Assert.assertEquals(456.0, waitingTimes.get(0), 1e-3);
    Assert.assertEquals(144.5, waitingTimes.get(1), 1e-3);
    Assert.assertEquals(51.05, waitingTimes.get(2), 1e-3);
}
 
Example 29
Source Project: amodeus   Source File: WaitingTimeTest.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testDynamicWaitingTimeWithoutConstantAttribute() {
    AmodeusConfigGroup config = createConfig();
    AmodeusModeConfig operatorConfig = config.getModes().get(AmodeusModeConfig.DEFAULT_MODE);

    operatorConfig.getWaitingTimeEstimationConfig().setDefaultWaitingTime(123.0);
    operatorConfig.getWaitingTimeEstimationConfig().setEstimationLinkAttribute("avGroup");
    operatorConfig.getWaitingTimeEstimationConfig().setEstimationAlpha(0.7);

    Controler controller = createController(config);

    Link link = controller.getScenario().getNetwork().getLinks().get(Id.createLinkId("8:9_9:9"));
    link.getAttributes().putAttribute("avWaitingTime", 456.0);

    int index = 0;
    for (Link _link : controller.getScenario().getNetwork().getLinks().values()) {
        _link.getAttributes().putAttribute("avGroup", index++);
    }

    controller.getConfig().controler().setLastIteration(2);

    StrategySettings strategy = new StrategySettings();
    strategy.setStrategyName("ReRoute");
    strategy.setWeight(1.0);
    controller.getConfig().strategy().addStrategySettings(strategy);

    List<Double> waitingTimes = new LinkedList<>();

    controller.addControlerListener(new IterationEndsListener() {
        @Override
        public void notifyIterationEnds(IterationEndsEvent event) {
            Population population = event.getServices().getScenario().getPopulation();
            Person person = population.getPersons().get(Id.createPersonId(17));
            Plan plan = person.getSelectedPlan();

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

                    if (Id.createLinkId("8:9_9:9").equals(route.getStartLinkId())) {
                        waitingTimes.add(route.getWaitingTime().seconds());
                    }
                }
            }
        }
    });

    controller.run();

    Assert.assertEquals(123.0, waitingTimes.get(0), 1e-3);
    Assert.assertEquals(44.6, waitingTimes.get(1), 1e-3);
    Assert.assertEquals(21.08, waitingTimes.get(2), 1e-3);
}
 
Example 30
Source Project: amod   Source File: SocketServer.java    License: GNU General Public License v2.0 4 votes vote down vote up
/** runs a simulation run using input data from Amodeus.properties, av.xml and MATSim config.xml
 * 
 * @throws MalformedURLException
 * @throws Exception */

public void simulate(StringSocket stringSocket, int numReqTot, //
        File workingDirectory) throws MalformedURLException, Exception {
    Static.setup();
    /** working directory and options */
    scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault());

    /** set to true in order to make server wait for at least 1 client, for
     * instance viewer client, for fals the ScenarioServer starts the simulation
     * immediately */
    boolean waitForClients = scenarioOptions.getBoolean("waitForClients");
    configFile = new File(scenarioOptions.getSimulationConfigName());
    /** geographic information */
    LocationSpec locationSpec = scenarioOptions.getLocationSpec();
    referenceFrame = locationSpec.referenceFrame();

    /** open server port for clients to connect to */
    SimulationServer.INSTANCE.startAcceptingNonBlocking();
    SimulationServer.INSTANCE.setWaitForClients(waitForClients);

    /** load MATSim configs - including av.xml configurations, load routing packages */
    GlobalAssert.that(configFile.exists());
    DvrpConfigGroup dvrpConfigGroup = new DvrpConfigGroup();
    dvrpConfigGroup.setTravelTimeEstimationAlpha(0.05);
    Config config = ConfigUtils.loadConfig(configFile.toString(), new AmodeusConfigGroup(), dvrpConfigGroup);
    config.planCalcScore().addActivityParams(new ActivityParams("activity"));
    // TODO @Sebastian fix this to meaningful values, remove, or add comment
    // this was added because there are sometimes problems, is there a more elegant option?
    for (ActivityParams activityParams : config.planCalcScore().getActivityParams()) {
        activityParams.setTypicalDuration(3600.0);
    }

    /** load MATSim scenario for simulation */
    Scenario scenario = ScenarioUtils.loadScenario(config);
    AddCoordinatesToActivities.run(scenario);
    network = scenario.getNetwork();
    Population population = scenario.getPopulation();
    GlobalAssert.that(Objects.nonNull(network));
    GlobalAssert.that(Objects.nonNull(population));

    Objects.requireNonNull(network);
    MatsimAmodeusDatabase db = MatsimAmodeusDatabase.initialize(network, referenceFrame);
    Controler controller = new Controler(scenario);
    AmodeusConfigurator.configureController(controller, db, scenarioOptions);

    /** try to load link speed data and use for speed adaption in network */
    try {
        File linkSpeedDataFile = new File(scenarioOptions.getLinkSpeedDataName());
        System.out.println(linkSpeedDataFile.toString());
        LinkSpeedDataContainer lsData = LinkSpeedUtils.loadLinkSpeedData(linkSpeedDataFile);
        controller.addOverridingQSimModule(new TrafficDataModule(lsData));
    } catch (Exception exception) {
        System.err.println("Unable to load linkspeed data, freeflow speeds will be used in the simulation.");
        exception.printStackTrace();
    }

    controller.addOverridingModule(new SocketModule(stringSocket, numReqTot));

    /** Custom router that ensures same network speeds as taxis in original data set. */
    controller.addOverridingModule(new AbstractModule() {
        @Override
        public void install() {
            bind(TaxiTravelTimeRouter.Factory.class);
            AmodeusUtils.bindRouterFactory(binder(), TaxiTravelTimeRouter.class.getSimpleName()).to(TaxiTravelTimeRouter.Factory.class);
        }
    });

    /** adding the dispatcher to receive and process string fleet commands */
    controller.addOverridingModule(new AbstractModule() {
        @Override
        public void install() {
            AmodeusUtils.registerDispatcherFactory(binder(), "SocketDispatcherHost", SocketDispatcherHost.Factory.class);
        }
    });

    /** adding an initial vehicle placer */
    controller.addOverridingModule(new AbstractModule() {
        @Override
        public void install() {
            AmodeusUtils.bindGeneratorFactory(binder(), RandomDensityGenerator.class.getSimpleName()).//
            to(RandomDensityGenerator.Factory.class);
        }
    });

    /** run simulation */
    controller.run();

    /** close port for visualizaiton */
    SimulationServer.INSTANCE.stopAccepting();

    /** perform analysis of simulation */
    /** output directory for saving results */
    outputDirectory = new File(config.controler().getOutputDirectory());

}