org.matsim.api.core.v01.Scenario Java Examples

The following examples show how to use org.matsim.api.core.v01.Scenario. 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: TestScenario.java    From amodeus with 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 #2
Source File: Preparer.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
public Preparer(File workingDirectory) throws IOException {
    // Static.setup();

    /** amodeus options */
    scenOpt = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault());

    /** MATSim config */
    config = ConfigUtils.loadConfig(scenOpt.getPreparerConfigName());
    Scenario scenario = ScenarioUtils.loadScenario(config);

    /** adaption of MATSim network, e.g., radius cutting */
    Network network = scenario.getNetwork();
    this.network = NetworkPreparer.run(network, scenOpt);

    /** adaption of MATSim population, e.g., radius cutting */
    this.population = scenario.getPopulation();
}
 
Example #3
Source File: WaitingTimeTest.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
static Controler createController(AmodeusConfigGroup avConfigGroup) {
    Config config = ConfigUtils.createConfig(avConfigGroup, new DvrpConfigGroup());
    Scenario scenario = TestScenarioGenerator.generateWithAVLegs(config);

    PlanCalcScoreConfigGroup.ModeParams modeParams = config.planCalcScore().getOrCreateModeParams(AmodeusModeConfig.DEFAULT_MODE);
    modeParams.setMonetaryDistanceRate(0.0);
    modeParams.setMarginalUtilityOfTraveling(8.86);
    modeParams.setConstant(0.0);

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

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

    return controler;
}
 
Example #4
Source File: KMeansVirtualNetworkCreatorTest.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
@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
Source File: TestScenarioGenerator.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
static public Scenario generate(Config config) {
    config.controler().setOutputDirectory(outputDir + "/output");

    config.controler().setLastIteration(0);
    config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists);
    config.controler().setWriteEventsInterval(-1);
    config.controler().setWritePlansInterval(-1);
    config.controler().setWriteSnapshotsInterval(-1);
    config.controler().setCreateGraphs(false);
    config.controler().setDumpDataAtEnd(false);
    config.qsim().setEndTime(duration * 2);
    config.planCalcScore().getOrCreateScoringParameters(null).getOrCreateActivityParams("activity").setScoringThisActivityAtAll(false);
    config.qsim().setSimStarttimeInterpretation(StarttimeInterpretation.onlyUseStarttime);

    Random random = new Random(randomSeed);
    Scenario scenario = ScenarioUtils.createScenario(config);

    generateNetwork(scenario.getNetwork());
    generatePopulation(scenario.getPopulation(), scenario.getNetwork(), random);

    return scenario;
}
 
Example #6
Source File: CreateFleetVehicles.java    From matsim-maas with GNU General Public License v2.0 6 votes vote down vote up
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 #7
Source File: RunTest.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testMultiOD() {
    AmodeusConfigGroup avConfigGroup = new AmodeusConfigGroup();

    AmodeusModeConfig operatorConfig = new AmodeusModeConfig(AmodeusModeConfig.DEFAULT_MODE);
    operatorConfig.getDispatcherConfig().setType(MultiODHeuristic.TYPE);
    operatorConfig.getGeneratorConfig().setNumberOfVehicles(100);
    operatorConfig.getPricingConfig().setPricePerKm(0.48);
    operatorConfig.getPricingConfig().setSpatialBillingInterval(1000.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);

    PlanCalcScoreConfigGroup.ModeParams modeParams = config.planCalcScore().getOrCreateModeParams(AmodeusModeConfig.DEFAULT_MODE); // Refactor av
    modeParams.setMonetaryDistanceRate(0.0);
    modeParams.setMarginalUtilityOfTraveling(8.86);
    modeParams.setConstant(0.0);

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

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

    TestScenarioAnalyzer analyzer = new TestScenarioAnalyzer();
    controler.addOverridingModule(analyzer);

    controler.run();

    Assert.assertEquals(0, analyzer.numberOfDepartures - analyzer.numberOfArrivals);
}
 
Example #8
Source File: ScheduleTools.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Transforms a MATSim Transit Schedule file. Overwrites the file.
 */
public static void transformScheduleFile(String scheduleFile, String fromCoordinateSystem, String toCoordinateSystem) {
	log.info("... Transformig schedule from " + fromCoordinateSystem + " to " + toCoordinateSystem);
	final Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
	new TransitScheduleReader(fromCoordinateSystem, toCoordinateSystem, scenario).readFile(scheduleFile);
	TransitSchedule schedule = scenario.getTransitSchedule();
	new TransitScheduleWriter(schedule).writeFile(scheduleFile);
}
 
Example #9
Source File: SocketPreparer.java    From amod with GNU General Public License v2.0 5 votes vote down vote up
/** loads scenario preparer in the {@link File} workingDirectory
 * 
 * @param workingDirectory
 * @throws MalformedURLException
 * @throws Exception */
public SocketPreparer(File workingDirectory) throws MalformedURLException, Exception {
    Static.setup();

    /** amodeus options */
    scenOpt = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault());

    /** MATSim config */
    // configMatsim = ConfigUtils.loadConfig(scenOpt.getPreparerConfigName());
    AmodeusConfigGroup avConfigGroup = new AmodeusConfigGroup();
    config = ConfigUtils.loadConfig(scenOpt.getPreparerConfigName(), avConfigGroup);

    Scenario scenario = ScenarioUtils.loadScenario(config);
    GeneratorConfig genConfig = avConfigGroup.getModes().values().iterator().next().getGeneratorConfig();
    numRt = genConfig.getNumberOfVehicles();
    System.out.println("socketPrep NumberOfVehicles=" + numRt);

    /** adaption of MATSim network, e.g., radius cutting */
    Network network = scenario.getNetwork();
    this.network = NetworkPreparer.run(network, scenOpt);

    /** adaption of MATSim population, e.g., radius cutting */
    population = scenario.getPopulation();

    LocationSpec locationSpec = scenOpt.getLocationSpec();
    ReferenceFrame referenceFrame = locationSpec.referenceFrame();
    this.db = MatsimAmodeusDatabase.initialize(network, referenceFrame);
}
 
Example #10
Source File: RunDrtTest.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testAmodeusDrt() {
    Config config = ConfigUtils.createConfig(new MultiModeDrtConfigGroup(), new DvrpConfigGroup(), new AmodeusConfigGroup());
    Scenario scenario = TestScenarioGenerator.generateWithAVLegs(config);
    run(config, scenario, true);

    // Currently, Amodeus does not know where to put the auto-generated ScenarioOptions file.
    // We can make this a config option for AmodeusConfigGroup.
    FileUtils.deleteQuietly(new File("AmodeusOptions.properties"));
}
 
Example #11
Source File: AVPickupDropoffTest.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testWaitEmptyForPerson() {
    AmodeusConfigGroup config = TestScenario.createConfig();
    Scenario scenario = TestScenario.createScenario(config, Arrays.asList(new TestRequest(0.0, 100.0)));

    TestScenario.ArrivalListener listener = new TestScenario.ArrivalListener();
    Controler controller = TestScenario.createController(scenario, listener, 1);
    controller.run();

    Assert.assertEquals(1, listener.times.size());
    Assert.assertEquals(1014.0 + 100.0, listener.times.get(0), 1e-3);
}
 
Example #12
Source File: TestScenarioGenerator.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
static public Scenario generateWithAVLegs(Config config) {
    Scenario scenario = generate(config);

    scenario.getPopulation().getPersons().values().forEach(person -> {
        person.getSelectedPlan().getPlanElements().stream().filter(Leg.class::isInstance).forEach(leg -> ((Leg) leg).setMode(AmodeusModeConfig.DEFAULT_MODE)); // Refactor av
    });

    return scenario;
}
 
Example #13
Source File: RunTest.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testBasicSetup() {
    // CONFIG PART

    Config config = ConfigUtils.createConfig(new DvrpConfigGroup(), new AmodeusConfigGroup());

    // Add Amodeus mode
    AmodeusModeConfig modeConfig = new AmodeusModeConfig("av");
    modeConfig.getDispatcherConfig().setType("GlobalBipartiteMatchingDispatcher");
    AmodeusConfigGroup.get(config).addMode(modeConfig);

    config.planCalcScore().getOrCreateModeParams("av");

    // DVRP adjustments
    config.qsim().setSimStarttimeInterpretation(StarttimeInterpretation.onlyUseStarttime);

    // SCENARIO PART

    // Generates a scenario with "av" legs
    Scenario scenario = TestScenarioGenerator.generateWithAVLegs(config);

    // CONTROLLER PART
    Controler controller = new Controler(scenario);

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

    controller.addOverridingQSimModule(new AmodeusQSimModule());
    controller.configureQSimComponents(AmodeusQSimModule.activateModes(AmodeusConfigGroup.get(controller.getConfig())));

    // Some analysis listener for testing
    TestScenarioAnalyzer analyzer = new TestScenarioAnalyzer();
    controller.addOverridingModule(analyzer);

    controller.run();

    Assert.assertEquals(0, analyzer.numberOfDepartures - analyzer.numberOfArrivals);
    Assert.assertEquals(100, analyzer.numberOfDepartures);
}
 
Example #14
Source File: RunTest.java    From amodeus with 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 #15
Source File: LPTimeInvariantTest.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() throws IOException {
    System.out.println(LPTimeInvariant.class.getName());
    // copy scenario data into main directory
    File scenarioDirectory = new File(Locate.repoFolder(LPTimeInvariantTest.class, "amodeus"), "resources/testScenario");
    System.out.println("scenarioDirectory: " + scenarioDirectory);
    File workingDirectory = MultiFileTools.getDefaultWorkingDirectory();
    GlobalAssert.that(workingDirectory.isDirectory());
    TestFileHandling.copyScnearioToMainDirectory(scenarioDirectory.getAbsolutePath(), workingDirectory.getAbsolutePath());

    /* input data */
    scenarioOptions = new ScenarioOptions(scenarioDirectory, ScenarioOptionsBase.getDefault());
    File configFile = new File(scenarioOptions.getPreparerConfigName());
    System.out.println("configFile: " + configFile.getAbsolutePath());
    AmodeusConfigGroup avCg = new AmodeusConfigGroup();
    Config config = ConfigUtils.loadConfig(configFile.getAbsolutePath(), avCg);
    GeneratorConfig genConfig = avCg.getModes().values().iterator().next().getGeneratorConfig();
    int numRt = genConfig.getNumberOfVehicles();
    endTime = (int) config.qsim().getEndTime().seconds();
    Scenario scenario = ScenarioUtils.loadScenario(config);
    network = scenario.getNetwork();
    population = scenario.getPopulation();

    // create 2 node virtual network
    scenarioOptions.setProperty(ScenarioOptionsBase.NUMVNODESIDENTIFIER, "2");
    VirtualNetworkCreator virtualNetworkCreator = scenarioOptions.getVirtualNetworkCreator();
    virtualNetwork2 = virtualNetworkCreator.create(network, population, scenarioOptions, numRt, endTime);

    // create 3 node virtual network
    scenarioOptions.setProperty(ScenarioOptionsBase.NUMVNODESIDENTIFIER, "3");
    virtualNetworkCreator = scenarioOptions.getVirtualNetworkCreator();
    virtualNetwork3 = virtualNetworkCreator.create(network, population, scenarioOptions, numRt, endTime);
}
 
Example #16
Source File: TrafficDataModule.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
@Provides
@Singleton
public QNetworkFactory provideCustomConfigurableQNetworkFactory(EventsManager events, Scenario scenario, //
        TaxiTrafficData trafficData) {
    ConfigurableQNetworkFactory factory = new ConfigurableQNetworkFactory(events, scenario);
    LinkSpeedCalculator linkSpeedCalculator = new AmodeusLinkSpeedCalculator(trafficData);
    factory.setLinkSpeedCalculator(linkSpeedCalculator);
    return factory;
}
 
Example #17
Source File: RequestTest.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
@BeforeClass
public static void setup() throws IOException {

    /* input data */
    File scenarioDirectory = new File(Locate.repoFolder(RequestTest.class, "amodeus"), "resources/testScenario");
    ScenarioOptions scenarioOptions = new ScenarioOptions(scenarioDirectory, ScenarioOptionsBase.getDefault());
    File configFile = new File(scenarioOptions.getPreparerConfigName());
    Config config = ConfigUtils.loadConfig(configFile.getAbsolutePath());
    Scenario scenario = ScenarioUtils.loadScenario(config);
    network = scenario.getNetwork();

    link0 = (Link) network.getLinks().values().toArray()[0];
    link1 = (Link) network.getLinks().values().toArray()[1];
    link2 = (Link) network.getLinks().values().toArray()[2];
}
 
Example #18
Source File: LPEmptyTest.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() throws IOException {
    System.out.println(LPTimeInvariant.class.getName());
    // copy scenario data into main directory
    File scenarioDirectory = new File(Locate.repoFolder(LPEmptyTest.class, "amodeus"), "resources/testScenario");
    System.out.println("scenarioDirectory: " + scenarioDirectory);
    File workingDirectory = MultiFileTools.getDefaultWorkingDirectory();
    GlobalAssert.that(workingDirectory.isDirectory());
    TestFileHandling.copyScnearioToMainDirectory(scenarioDirectory.getAbsolutePath(), workingDirectory.getAbsolutePath());

    /* input data */
    scenarioOptions = new ScenarioOptions(scenarioDirectory, ScenarioOptionsBase.getDefault());
    File configFile = new File(scenarioOptions.getPreparerConfigName());
    System.out.println("configFile: " + configFile.getAbsolutePath());
    AmodeusConfigGroup avCg = new AmodeusConfigGroup();
    Config config = ConfigUtils.loadConfig(configFile.getAbsolutePath(), avCg);
    GeneratorConfig genConfig = avCg.getModes().values().iterator().next().getGeneratorConfig();
    int numRt = genConfig.getNumberOfVehicles();
    endTime = (int) config.qsim().getEndTime().seconds();
    Scenario scenario = ScenarioUtils.loadScenario(config);
    network = scenario.getNetwork();
    population = scenario.getPopulation();

    // create 2 node virtual network
    scenarioOptions.setProperty(ScenarioOptionsBase.NUMVNODESIDENTIFIER, "2");
    VirtualNetworkCreator virtualNetworkCreator = scenarioOptions.getVirtualNetworkCreator();
    virtualNetwork2 = virtualNetworkCreator.create(network, population, scenarioOptions, numRt, endTime);

    // create 3 node virtual network
    scenarioOptions.setProperty(ScenarioOptionsBase.NUMVNODESIDENTIFIER, "3");
    virtualNetworkCreator = scenarioOptions.getVirtualNetworkCreator();
    virtualNetwork3 = virtualNetworkCreator.create(network, population, scenarioOptions, numRt, endTime);
}
 
Example #19
Source File: LPMinFlowTest.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
@BeforeClass
public static void setup() throws IOException {
    System.out.println(LPTimeInvariant.class.getName());
    /** input data */
    File scenarioDirectory = new File(Locate.repoFolder(LPMinFlowTest.class, "amodeus"), "resources/testScenario");
    System.out.println("scenarioDirectory: " + scenarioDirectory.getAbsolutePath());
    scenarioOptions = new ScenarioOptions(scenarioDirectory, ScenarioOptionsBase.getDefault());
    File configFile = new File(scenarioOptions.getPreparerConfigName());
    System.out.println("configFile: " + configFile.getAbsolutePath());
    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 = scenario.getNetwork();
    population = scenario.getPopulation();

    // create 2 node virtual network
    scenarioOptions.setProperty(ScenarioOptionsBase.NUMVNODESIDENTIFIER, "2");
    VirtualNetworkCreator virtualNetworkCreator = scenarioOptions.getVirtualNetworkCreator();
    virtualNetwork2 = virtualNetworkCreator.create(network, population, scenarioOptions, numRt, endTime);

    // create 3 node virtual network
    scenarioOptions.setProperty(ScenarioOptionsBase.NUMVNODESIDENTIFIER, "3");
    virtualNetworkCreator = scenarioOptions.getVirtualNetworkCreator();
    virtualNetwork3 = virtualNetworkCreator.create(network, population, scenarioOptions, numRt, endTime);

    // create 3 node virtual network incomplete
    scenarioOptions.setProperty(ScenarioOptionsBase.COMPLETEGRAPHIDENTIFIER, "false");
    virtualNetworkCreator = scenarioOptions.getVirtualNetworkCreator();
    virtualNetwork3incomplete = virtualNetworkCreator.create(network, population, scenarioOptions, numRt, endTime);
}
 
Example #20
Source File: PopulationToolsTestVN2.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
@BeforeClass
public static void setup() throws IOException {
    // copy scenario data into main directory
    File scenarioDirectory = new File(Locate.repoFolder(PopulationToolsTestVN2.class, "amodeus"), "resources/testScenario");
    File workingDirectory = MultiFileTools.getDefaultWorkingDirectory();
    GlobalAssert.that(workingDirectory.exists());
    TestFileHandling.copyScnearioToMainDirectory(scenarioDirectory.getAbsolutePath(), workingDirectory.getAbsolutePath());

    /* input data */
    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();
    endTime = (int) config.qsim().getEndTime().seconds();
    Scenario scenario = ScenarioUtils.loadScenario(config);
    network = scenario.getNetwork();
    population = scenario.getPopulation();

    // create 2 node virtual network
    scenarioOptions.setProperty(ScenarioOptionsBase.NUMVNODESIDENTIFIER, "2");
    VirtualNetworkCreator virtualNetworkCreator = scenarioOptions.getVirtualNetworkCreator();
    virtualNetwork2 = virtualNetworkCreator.create(network, population, scenarioOptions, numRt, endTime);

    Link node0 = (Link) virtualNetwork2.getVirtualNode(0).getLinks().toArray()[0];
    Link node1 = (Link) virtualNetwork2.getVirtualNode(1).getLinks().toArray()[0];

    requestsSingle3.add(new Request(10, node0, node1));
    requests3.add(new Request(0, node0, node1));
    requests3.add(new Request(3600, node1, node0));
    requests3.add(new Request(30 * 3600 - 1, node1, node0));
    requests3.add(new Request(3600, node0, node0));
}
 
Example #21
Source File: VehicleToVSGeneratorTester.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
@BeforeClass
public static void setup() throws IOException {

    /** input data */
    File scenarioDirectory = new File(Locate.repoFolder(VehicleToVSGenerator.class, "amodeus"), "resources/testScenario");
    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 = scenario.getNetwork();
    population = scenario.getPopulation();
    scenarioOptions.setProperty(ScenarioOptionsBase.NUMVNODESIDENTIFIER, "3");
    VirtualNetworkCreator virtualNetworkCreator = scenarioOptions.getVirtualNetworkCreator();
    virtualNetwork = virtualNetworkCreator.create(network, population, scenarioOptions, numRt, endTime);

    /** creating dummy config with 10 vehicles */
    operatorConfig = new AmodeusModeConfig(AmodeusModeConfig.DEFAULT_MODE);

    GeneratorConfig avGeneratorConfig = operatorConfig.getGeneratorConfig();
    avGeneratorConfig.setType("strategy");
    avGeneratorConfig.setNumberOfVehicles(10);

    travelData000 = new StaticTravelData(virtualNetwork.getvNetworkID(), Array.zeros(3, 3, 3), Array.zeros(3, 3, 3), Array.zeros(3, 3, 3), Array.zeros(3), "", endTime);
    travelData123 = new StaticTravelData(virtualNetwork.getvNetworkID(), Array.zeros(3, 3, 3), Array.zeros(3, 3, 3), Array.zeros(3, 3, 3), Tensors.vector(1, 2, 3), "",
            endTime);
    travelData334 = new StaticTravelData(virtualNetwork.getvNetworkID(), Array.zeros(3, 3, 3), Array.zeros(3, 3, 3), Array.zeros(3, 3, 3), Tensors.vector(3, 3, 4), "",
            endTime);
}
 
Example #22
Source File: MATSimVirtualNetworkTravelDataTest.java    From amodeus with GNU General Public License v2.0 4 votes vote down vote up
private static Controler prepare() throws IOException {
    File scenarioDirectory = new File(Locate.repoFolder(StandardMATSimScenarioTest.class, "amodeus"), "resources/testScenario");
    File workingDirectory = MultiFileTools.getDefaultWorkingDirectory();
    GlobalAssert.that(workingDirectory.isDirectory());
    TestFileHandling.copyScnearioToMainDirectory(scenarioDirectory.getAbsolutePath(), workingDirectory.getAbsolutePath());

    StaticHelper.setup();
    MatsimRandom.reset();

    // Set up
    Config config = ConfigUtils.createConfig(new AmodeusConfigGroup(), new DvrpConfigGroup());
    Scenario scenario = TestScenarioGenerator.generateWithAVLegs(config);

    ScenarioOptions simOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault());
    LocationSpec locationSpec = simOptions.getLocationSpec();
    ReferenceFrame referenceFrame = locationSpec.referenceFrame();
    MatsimAmodeusDatabase db = MatsimAmodeusDatabase.initialize(scenario.getNetwork(), referenceFrame);

    PlanCalcScoreConfigGroup.ModeParams modeParams = config.planCalcScore().getOrCreateModeParams(AmodeusModeConfig.DEFAULT_MODE);
    modeParams.setMonetaryDistanceRate(0.0);
    modeParams.setMarginalUtilityOfTraveling(8.86);
    modeParams.setConstant(0.0);

    // Config

    AmodeusConfigGroup avConfig = AmodeusConfigGroup.get(config);

    AmodeusModeConfig operatorConfig = new AmodeusModeConfig(AmodeusModeConfig.DEFAULT_MODE);
    avConfig.addMode(operatorConfig);

    GeneratorConfig generatorConfig = operatorConfig.getGeneratorConfig();
    generatorConfig.setType("VehicleToVSGenerator");
    generatorConfig.setNumberOfVehicles(100);

    // Choose a dispatcher
    DispatcherConfig dispatcherConfig = operatorConfig.getDispatcherConfig();
    dispatcherConfig.addParam("infoLinePeriod", "3600");
    dispatcherConfig.setType("FeedforwardFluidicRebalancingPolicy");

    // Make sure that we do not need the SimulationObjectCompiler
    dispatcherConfig.addParam("publishPeriod", "-1");

    // Set up stuff for TravelData (but we'll generate it on the fly)
    LPOptions lpOptions = new LPOptions(simOptions.getWorkingDirectory(), LPOptionsBase.getDefault());
    lpOptions.setProperty(LPOptionsBase.LPSOLVER, "timeInvariant");
    lpOptions.saveAndOverwriteLPOptions();

    // Set up paths
    operatorConfig.getDispatcherConfig().setVirtualNetworkPath("generatedVirtualNetwork");
    operatorConfig.getDispatcherConfig().setTravelDataPath("generatedTravelData");

    // Controller
    Controler controller = new Controler(scenario);
    AmodeusConfigurator.configureController(controller, db, simOptions);

    // Run
    return controller;
}
 
Example #23
Source File: TestServer.java    From amodeus with 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 #24
Source File: ScheduleTools.java    From pt2matsim with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @return an empty transit schedule.
 */
public static TransitSchedule createSchedule() {
	Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
	return scenario.getTransitSchedule();
}
 
Example #25
Source File: ScheduleTools.java    From pt2matsim with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @return the transitSchedule from scheduleFile.
 */
public static TransitSchedule readTransitSchedule(String fileName) {
	Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
	new TransitScheduleReader(scenario).readFile(fileName);
	return scenario.getTransitSchedule();
}
 
Example #26
Source File: ScenarioParameters.java    From amodeus with GNU General Public License v2.0 4 votes vote down vote up
public ScenarioParameters(ScenarioOptions scenOptions) {
    System.out.println("scenOptions.getSimulationConfigName: " + scenOptions.getSimulationConfigName());

    AmodeusConfigGroup avConfigGroup = new AmodeusConfigGroup();
    Config config = ConfigUtils.loadConfig(scenOptions.getSimulationConfigName(), avConfigGroup);

    // TODO: This assumes that there is only one mode registered for Amodeus. There are two ways to go
    // forward. Either we need to put in a check somewhere that when Amodeus is used with ScenarioOptions
    // that there is really only one mode registered. Alternatives are to make he ScenarioOptions multimodal
    // or to put all ScenarioOptions into the AmodeusModeConfig. This will happen anyways (for the MATSim
    // users, but I would keep a fallback to the ScenarioOptions file anyways).
    AmodeusModeConfig operatorConfig = avConfigGroup.getModes().values().iterator().next();
    DispatcherConfig dispatcherConfig = operatorConfig.getDispatcherConfig();
    SafeConfig safeConfig = SafeConfig.wrap(dispatcherConfig);
    GeneratorConfig generatorConfig = operatorConfig.getGeneratorConfig();

    redispatchPeriod = safeConfig.getInteger(DISPATCHPERIODSTRING, UNDEFINED_INT);
    rebalancingPeriod = safeConfig.getInteger(REBALANCINGPERIODSTRING, UNDEFINED_INT);
    dispatcher = dispatcherConfig.getType();
    vehicleGenerator = generatorConfig.getType();
    Scenario scenario = ScenarioUtils.loadScenario(config);

    distanceHeuristic = safeConfig.getString(DISTANCEHEURISTICSTRING, UNDEFINED_STRING);
    populationSize = scenario.getPopulation().getPersons().values().size();
    virtualNetworkCreator = scenOptions.getString(ScenarioOptionsBase.VIRTUALNETWORKCREATORIDENTIFIER);

    Network network = scenario.getNetwork();
    if (Objects.isNull(network.getName()))
        networkName = "no network name found in network.xml";
    else
        networkName = network.getName();

    VirtualNetwork<Link> virtualNetwork = null;
    try {
        virtualNetwork = VirtualNetworkGet.readDefault(network, scenOptions);
    } catch (IOException e) {
        System.err.println("INFO not able to load virtual network for report");
        e.printStackTrace();
    }

    virtualNodesCount = Objects.isNull(virtualNetwork) //
            ? UNDEFINED_INT
            : virtualNetwork.getvNodesCount();

    iterations = config.controler().getLastIteration();

}
 
Example #27
Source File: SocketServer.java    From amod with 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());

}
 
Example #28
Source File: RunDrtTest.java    From amodeus with GNU General Public License v2.0 4 votes vote down vote up
static public void run(Config config, Scenario scenario, boolean useAmodeus) {
    // CONFIG PART

    // Set up MATSim configuration to be compatible with DRT
    config.plans().setHandlingOfPlansWithoutRoutingMode(HandlingOfPlansWithoutRoutingMode.useMainModeIdentifier);
    config.qsim().setStartTime(0.0);
    config.qsim().setSimStarttimeInterpretation(StarttimeInterpretation.onlyUseStarttime);

    config.qsim().setNumberOfThreads(1);

    // Set up missing scoring parameters
    config.planCalcScore().getOrCreateModeParams(DRT_MODE);

    // Set up DRT mode
    DrtConfigGroup drtModeConfig = new DrtConfigGroup();
    drtModeConfig.setMode(DRT_MODE);

    drtModeConfig.setMaxTravelTimeBeta(600.0);
    drtModeConfig.setMaxTravelTimeAlpha(1.4);
    drtModeConfig.setMaxWaitTime(600.0);
    drtModeConfig.setStopDuration(60);
    drtModeConfig.setRejectRequestIfMaxWaitOrTravelTimeViolated(true);
    drtModeConfig.setOperationalScheme(OperationalScheme.door2door);

    MultiModeDrtConfigGroup drtConfig = MultiModeDrtConfigGroup.get(config);
    drtConfig.addParameterSet(drtModeConfig);
    DrtConfigs.adjustDrtConfig(drtModeConfig, config.planCalcScore(), config.plansCalcRoute());

    // Create a fleet on the fly
    String vehiclesFile = new File("test_data/drt_vehicles.xml.gz").getAbsolutePath();
    drtModeConfig.setVehiclesFile(vehiclesFile);
    createFleet(vehiclesFile, 100, scenario.getNetwork());

    // Set up DVRP
    DvrpConfigGroup dvrpConfig = DvrpConfigGroup.get(config);
    dvrpConfig.setTravelTimeEstimationAlpha(1.0);
    dvrpConfig.setTravelTimeEstimationBeta(900);

    // SCENARIO PART
    scenario.getPopulation().getFactory().getRouteFactories().setRouteFactory(DrtRoute.class, new DrtRouteFactory());

    // CONTROLLER PART
    Controler controller = new Controler(scenario);

    // Add DVRP and activate modes
    controller.addOverridingModule(new DvrpModule());
    controller.configureQSimComponents(DvrpQSimComponents.activateModes(drtModeConfig.getMode()));

    if (!useAmodeus) {
        // No Amodeus, so we use standard MultiModeDrtModule
        controller.addOverridingModule(new MultiModeDrtModule());
    } else {
        // Add DRT, but NOT with MultiModeDrtModule, but with MultiModeDrtModuleForAmodeus
        // because right now we remove DRT's analysis components as they are not compatible yet
        controller.addOverridingModule(new MultiModeDrtModuleForAmodeus());
    }

    // Here we start overriding things of DRT with Amodeus
    if (useAmodeus) {

        // This is a per-mode config, which usually is contained in a AmodeusConfigGroup,
        // here we only use it to set up a small portion of Amodeus (the dispatching part),
        // and not scoring, waiting times, etc.
        AmodeusModeConfig amodeusModeConfig = new AmodeusModeConfig(drtModeConfig.getMode());

        // We can choose the dispatcher and set additional options. Note that some dispatchers
        // rely heavily on GLPK. You need to install it and then tell JAVA where to find it
        // via -Djava.library.path=/path/to/glpk/lib/jni on the command line.
        amodeusModeConfig.getDispatcherConfig().setType("FeedforwardFluidicRebalancingPolicy");

        // Change, for instance, to "GlobalBipartiteMatchingDispatcher" if you want to
        // test without GLPK!

        // Disable Amodeus-specific output (e.g., for the viewer)
        amodeusModeConfig.getDispatcherConfig().setPublishPeriod(0);

        // Path where to generate or read a VirtualNetwork and TravelData for rebalancing.
        // Note that not all dispatchers need this.
        amodeusModeConfig.getDispatcherConfig().setVirtualNetworkPath(new File("test_data/virtualNetwork").getAbsolutePath());
        amodeusModeConfig.getDispatcherConfig().setTravelDataPath(new File("test_data/travelData").getAbsolutePath());

        // Add a subset of Amodeus modules which usually would be added automatically
        // in the upper-level AmodeusModule.
        controller.addOverridingModule(new VirtualNetworkModeModule(amodeusModeConfig));
        controller.addOverridingModule(new AmodeusModule());

        // Add overriding modules for the Drt <-> Amodeus integration, which override some
        // components of DRT. Later on, we would only override DrtOptimizer, but we are
        // not there yet, because Amodeus internally still works with AmodeusStayTask, etc.
        // and does not understand DrtStayTask, etc.
        controller.addOverridingModule(new AmodeusDrtModule(amodeusModeConfig));
        controller.addOverridingQSimModule(new AmodeusDrtQSimModule(drtModeConfig.getMode()));
    }

    controller.run();
}
 
Example #29
Source File: AmodeusConfigurator.java    From amodeus with GNU General Public License v2.0 4 votes vote down vote up
/** Configures a MATSim scenario for use with AMoDeus */
static public void configureScenario(Scenario scenario) {
    scenario.getPopulation().getFactory().getRouteFactories().setRouteFactory(AmodeusRoute.class, new AmodeusRouteFactory());
}
 
Example #30
Source File: RunDrtTest.java    From amodeus with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testDefaultDrt() {
    Config config = ConfigUtils.createConfig(new MultiModeDrtConfigGroup(), new DvrpConfigGroup());
    Scenario scenario = TestScenarioGenerator.generateWithAVLegs(config);
    run(config, scenario, false);
}