org.matsim.core.config.ConfigUtils Java Examples

The following examples show how to use org.matsim.core.config.ConfigUtils. 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: 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 #2
Source File: PT2MATSimExample.java    From pt2matsim with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 2. A MATSim network of the area is required. If no such network is already available,
 * the PT2MATSim package provides the possibility to use OSM-maps as data-input.
 *
 * Here as an example, the OSM-extract of the city centre of Waterloo, Canada, is converted.
 */
public static void createOsmConfigFile(String configFile) {
	// Create a default createOsmConfigFile-Config:
	CreateDefaultOsmConfig.main(new String[]{inter + "OsmConverterConfigDefault.xml"});

	// Open the createOsmConfigFile Config and set the parameters to the required values
	// (usually done manually by opening the config with a simple editor)
	Config osmConverterConfig = ConfigUtils.loadConfig(
			inter + "OsmConverterConfigDefault.xml",
			new OsmConverterConfigGroup());

	OsmConverterConfigGroup osmConfig = ConfigUtils.addOrGetModule(osmConverterConfig, OsmConverterConfigGroup.class);
	osmConfig.setOsmFile(input + "addison.osm.gz");
	osmConfig.setOutputCoordinateSystem(addisonCountyEPSG);
	osmConfig.setOutputNetworkFile(inter + "addison.xml.gz");

	// Save the createOsmConfigFile config (usually done manually)
	new ConfigWriter(osmConverterConfig).write(configFile);
}
 
Example #3
Source File: VideoGenerator.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        // load options
        ScenarioOptions scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault());
        Config config = ConfigUtils.loadConfig(scenarioOptions.getSimulationConfigName());
        final File outputSubDirectory = new File(config.controler().getOutputDirectory()).getAbsoluteFile();
        GlobalAssert.that(outputSubDirectory.isDirectory());

        ReferenceFrame referenceFrame = scenarioOptions.getLocationSpec().referenceFrame();
        /** reference frame needs to be set manually in IDSCOptions.properties file */

        Network network = NetworkLoader.fromNetworkFile(new File(config.network().getInputFile()));

        export(network, referenceFrame, scenarioOptions, outputSubDirectory);

        System.out.println("successfully finished video generation");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #4
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 #5
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 #6
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 #7
Source File: PT2MATSimExample.java    From pt2matsim with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 	3. The core of the PT2MATSim-package is the mapping process of the schedule to the network.
 *
 * 	Here as an example, the unmapped schedule of GrandRiverTransit (previously converted from GTFS) is mapped
 * 	to the converted OSM network of the Waterloo Area, Canada.
 */
public static void createMapperConfigFile(String configFile) {
	// Create a mapping config:
	CreateDefaultPTMapperConfig.main(new String[]{ inter + "MapperConfigDefault.xml"});
	// Open the mapping config and set the parameters to the required values
	// (usually done manually by opening the config with a simple editor)
	Config config = ConfigUtils.loadConfig(
			inter + "MapperConfigDefault.xml",
			PublicTransitMappingConfigGroup.createDefaultConfig());
	PublicTransitMappingConfigGroup ptmConfig = ConfigUtils.addOrGetModule(config, PublicTransitMappingConfigGroup.class);

	ptmConfig.setInputNetworkFile(inter + "addison.xml.gz");
	ptmConfig.setOutputNetworkFile(output + "addison_multimodalnetwork.xml.gz");
	ptmConfig.setOutputScheduleFile(output+ "addison_schedule.xml.gz");
	ptmConfig.setOutputStreetNetworkFile(output + "addison_streetnetwork.xml.gz");
	ptmConfig.setInputScheduleFile(inter + "schedule_unmapped.xml.gz");
	ptmConfig.setScheduleFreespeedModes(CollectionUtils.stringToSet("rail, light_rail"));
	// Save the mapping config
	// (usually done manually)
	new ConfigWriter(config).write(configFile);
}
 
Example #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: TestViewer.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
private TestViewer(File workingDirectory) throws IOException {
    // Static.setup();
    ScenarioOptions scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault());

    /** load options */
    Config config = ConfigUtils.loadConfig(scenarioOptions.getSimulationConfigName());
    System.out.println("MATSim config file: " + scenarioOptions.getSimulationConfigName());
    final File outputSubDirectory = new File(config.controler().getOutputDirectory()).getAbsoluteFile();
    if (!outputSubDirectory.isDirectory())
        throw new RuntimeException("output directory: " + outputSubDirectory.getAbsolutePath() + " not found.");
    System.out.println("outputSubDirectory=" + outputSubDirectory.getAbsolutePath());
    File outputDirectory = outputSubDirectory.getParentFile();
    System.out.println("showing simulation results from outputDirectory=" + outputDirectory);

    /** geographic information, .e.g., coordinate system */
    LocationSpec locationSpec = scenarioOptions.getLocationSpec();
    ReferenceFrame referenceFrame = locationSpec.referenceFrame();

    /** MATSim simulation network */
    Network network = NetworkLoader.fromConfigFile(new File(workingDirectory, scenarioOptions.getString("simuConfig")));
    System.out.println("INFO network loaded");
    System.out.println("INFO total links " + network.getLinks().size());
    System.out.println("INFO total nodes " + network.getNodes().size());

    /** initializing the viewer */
    MatsimAmodeusDatabase db = MatsimAmodeusDatabase.initialize(network, referenceFrame);
    amodeusComponent = AmodeusComponent.createDefault(db, workingDirectory);

    /** virtual network layer, should not cause problems if layer does not exist */
    amodeusComponent.virtualNetworkLayer.setVirtualNetwork(VirtualNetworkGet.readDefault(network, scenarioOptions));

    /** starting the viewer */
    viewerConfig = ViewerConfig.from(db, workingDirectory);
    System.out.println("Used viewer config: " + viewerConfig);
    AmodeusViewerFrame amodeusViewerFrame = new AmodeusViewerFrame(amodeusComponent, outputDirectory, network, scenarioOptions);
    amodeusViewerFrame.setDisplayPosition(viewerConfig.settings.coord, viewerConfig.settings.zoom);
    amodeusViewerFrame.jFrame.setSize(viewerConfig.settings.dimensions);
    amodeusViewerFrame.jFrame.setVisible(true);
}
 
Example #15
Source File: SharedTestServer.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void simulate() throws Exception {
    // change dispatcher
    Config config = ConfigUtils.loadConfig(scenarioOptions.getSimulationConfigName(), new DvrpConfigGroup(), new AmodeusConfigGroup());
    AmodeusConfigGroup.get(config).getModes().values()//
            .iterator().next().getDispatcherConfig().setType("TShareDispatcher");
    new ConfigWriter(config).write(scenarioOptions.getSimulationConfigName());
    super.simulate();
}
 
Example #16
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 #17
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 #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: 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 #20
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 #21
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 #22
Source File: RunDoorToDoorDrtExample.java    From matsim-maas with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {

		Config config = ConfigUtils.loadConfig(COTTBUS_DOOR2DOOR_CONFIG, new MultiModeDrtConfigGroup(),
				new DvrpConfigGroup(),
				new OTFVisConfigGroup(), new DrtFaresConfigGroup());
		run(config, false);
	}
 
Example #23
Source File: PublicTransitMapper.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Routes the unmapped MATSim Transit Schedule to the network using the file
 * paths specified in the config. Writes the resulting schedule and network to xml files.<p/>
 *
 * @see CreateDefaultPTMapperConfig
 *
 * @param configFile the PublicTransitMapping config file
 */
public static void run(String configFile) {
	// Load config, input schedule and input network
	Config configAll = ConfigUtils.loadConfig(configFile, new PublicTransitMappingConfigGroup());
	PublicTransitMappingConfigGroup config = ConfigUtils.addOrGetModule(configAll, PublicTransitMappingConfigGroup.class);
	TransitSchedule schedule = config.getInputScheduleFile() == null ? null : ScheduleTools.readTransitSchedule(config.getInputScheduleFile());
	Network network = config.getInputNetworkFile() == null ? null : NetworkTools.readNetwork(config.getInputNetworkFile());

	// Run PTMapper
	PTMapper.mapScheduleToNetwork(schedule, network, config);
	// or: new PTMapper(schedule, network).run(config);

	// Write the schedule and network to output files (if defined in config)
	if(config.getOutputNetworkFile() != null && config.getOutputScheduleFile() != null) {
		log.info("Writing schedule and network to file...");
		try {
			ScheduleTools.writeTransitSchedule(schedule, config.getOutputScheduleFile());
			NetworkTools.writeNetwork(network, config.getOutputNetworkFile());
		} catch (Exception e) {
			log.error("Cannot write to output directory!");
		}
		if(config.getOutputStreetNetworkFile() != null) {
			NetworkTools.writeNetwork(NetworkTools.createFilteredNetworkByLinkMode(network, Collections.singleton(TransportMode.car)), config.getOutputStreetNetworkFile());
		}
	} else {
		log.info("No output paths defined, schedule and network are not written to files.");
	}
}
 
Example #24
Source File: RunStopBasedDrtExample.java    From matsim-maas with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {

		Config config = ConfigUtils.loadConfig("scenarios/cottbus/drtconfig_stopbased.xml",
				new MultiModeDrtConfigGroup(), new DvrpConfigGroup(),
                new OTFVisConfigGroup(), new DrtFaresConfigGroup());
        run(config, false);
    }
 
Example #25
Source File: CreateDefaultPTMapperConfig.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a default publicTransitMapping config file.
 * @param args [0] default config filename
 */
public static void main(final String[] args) {
	if(args.length < 1) {
		throw new IllegalArgumentException("Config file name as argument needed");
	}

	Config config = ConfigUtils.createConfig();

	config.addModule(PublicTransitMappingConfigGroup.createDefaultConfig());

	Set<String> toRemove = config.getModules().keySet().stream().filter(module -> !module.equals(PublicTransitMappingConfigGroup.GROUP_NAME)).collect(Collectors.toSet());
	toRemove.forEach(config::removeModule);

	new ConfigWriter(config).write(args[0]);
}
 
Example #26
Source File: RunTaxiExample.java    From matsim-maas with GNU General Public License v2.0 5 votes vote down vote up
public static void run(String configFile, boolean otfvis, int lastIteration) {
	// load config
	Config config = ConfigUtils.loadConfig(configFile, new MultiModeTaxiConfigGroup(), new DvrpConfigGroup(),
			new OTFVisConfigGroup());
	config.controler().setLastIteration(lastIteration);

	TaxiControlerCreator.createControler(config, otfvis).run();
}
 
Example #27
Source File: PreroutingTest.java    From amodeus with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testPreRouting() {
    AmodeusConfigGroup avConfigGroup = new AmodeusConfigGroup();

    AmodeusModeConfig operatorConfig = new AmodeusModeConfig(AmodeusModeConfig.DEFAULT_MODE);
    operatorConfig.setPredictRouteTravelTime(true);
    operatorConfig.getGeneratorConfig().setNumberOfVehicles(100);
    avConfigGroup.addMode(operatorConfig);

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

    operatorConfig.getPricingConfig().setPricePerKm(1.0);

    Config config = ConfigUtils.createConfig(avConfigGroup, new DvrpConfigGroup());
    Scenario scenario = TestScenarioGenerator.generateWithAVLegs(config);

    config.plansCalcRoute().setRoutingRandomness(0.0);

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

    StrategySettings strategySettings = new StrategySettings();
    strategySettings.setStrategyName("KeepLastSelected");
    strategySettings.setWeight(1.0);
    config.strategy().addStrategySettings(strategySettings);

    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()) {
        Plan plan = person.getSelectedPlan();

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

                Assert.assertTrue(route.getTravelTime().isDefined() && Double.isFinite(route.getTravelTime().seconds()));
                Assert.assertTrue(route.getExpectedDistance().isPresent());
                Assert.assertTrue(route.getWaitingTime().isDefined());
                Assert.assertTrue(route.getPrice().isPresent());
                Assert.assertTrue(route.getPrice().get() > 0.0);
            }
        }
    }
}
 
Example #28
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 #29
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 #30
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());

}