public static void main(final String[] args) {
    OutputDirectoryLogging.catchLogEntries();
    final String configFile = args[0];

    // read the config with our special parameters
    // Note that you need scoring parameters converted
    // from the KTI config by something like
    // playground.thibautd.scripts.KtiToSimiliKtiConfig
    final Config config = ConfigUtils.createConfig();
    config.addModule(new KtiPtConfigGroup());
    config.addModule(new KtiLikeScoringConfigGroup());
    ConfigUtils.loadConfig(config, configFile);

    // just make sure the scenario is loaded
    // Controler accepts a config, but if the Scenario is not
    // fully loaded when creating the routing module, we may get into
    // troubles later...
    final Scenario scenario = ScenarioUtils.loadScenario(config);
    final Controler controler = new Controler(scenario);
    controler.setTripRouterFactory(new KtiTripRouterFactory(scenario));
    controler.setScoringFunctionFactory(
        new KtiLikeActivitiesScoringFunctionFactory(
            new StageActivityTypesImpl(PtConstants.TRANSIT_ACTIVITY_TYPE),
            (KtiLikeScoringConfigGroup) config.getModule(KtiLikeScoringConfigGroup.GROUP_NAME),
            config.planCalcScore(),
            scenario));

    // we're done!
    controler.run();
  }
  public static void main(final String[] args) {
    final String configFile = args[0];

    // This allows to get a log file containing the log messages happening
    // before controler init.
    OutputDirectoryLogging.catchLogEntries();

    // This is the location choice MultiNodeDijkstra.
    // Suppress all log messages of level below error --- to avoid spaming the config
    // file with zillions of "not route found" messages.
    Logger.getLogger(org.matsim.core.router.MultiNodeDijkstra.class)
        .setLevel(Level.ERROR); // this is location choice
    Logger.getLogger(org.matsim.pt.router.MultiNodeDijkstra.class).setLevel(Level.ERROR);

    final Config config =
        ConfigUtils.loadConfig(
            configFile,
            // this adds a new config group, used by the specific scoring function
            // we use
            new KtiLikeScoringConfigGroup(),
            new DestinationChoiceConfigGroup());

    // This is currently needed for location choice: initializing
    // the location choice writes K-values files to the output directory, which:
    // - fails if the directory does not exist
    // - makes the controler crash latter if the unsafe setOverwriteFiles( true )
    // is not called.
    // This ensures that we get safety with location choice working as expected,
    // before we sort this out and definitely kick out setOverwriteFiles.
    createEmptyDirectoryOrFailIfExists(config.controler().getOutputDirectory());
    final Scenario scenario = ScenarioUtils.loadScenario(config);

    final Controler controler = new Controler(scenario);
    controler
        .getConfig()
        .controler()
        .setOverwriteFileSetting(
            true
                ? OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles
                : OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists);

    connectFacilitiesWithNetwork(controler);

    initializeLocationChoice(controler);

    // We use a specific scoring function, that uses individual preferences
    // for activity durations.
    controler.setScoringFunctionFactory(
        new MATSim2010ScoringFunctionFactory(
            controler.getScenario(),
            new StageActivityTypesImpl(PtConstants.TRANSIT_ACTIVITY_TYPE)));

    controler.run();
  }
  public static void main(final String[] args) {
    final String configFile = args[0];

    // This allows to get a log file containing the log messages happening
    // before controler init.
    OutputDirectoryLogging.catchLogEntries();

    // This is the location choice MultiNodeDijkstra.
    // Suppress all log messages of level below error --- to avoid spaming the config
    // file with zillions of "not route found" messages.
    Logger.getLogger(org.matsim.core.router.MultiNodeDijkstra.class)
        .setLevel(Level.ERROR); // this is location choice
    Logger.getLogger(org.matsim.pt.router.MultiNodeDijkstra.class).setLevel(Level.ERROR);

    final Config config =
        ConfigUtils.loadConfig(
            configFile,
            // this adds a new config group, used by the specific scoring function
            // we use

            new KtiLikeScoringConfigGroup());

    // This is currently needed for location choice: initializing
    // the location choice writes K-values files to the output directory, which:
    // - fails if the directory does not exist
    // - makes the controler crash latter if the unsafe setOverwriteFiles( true )
    // is not called.
    // This ensures that we get safety with location choice working as expected,
    // before we sort this out and definitely kick out setOverwriteFiles.
    createEmptyDirectoryOrFailIfExists(config.controler().getOutputDirectory());

    OneWayCarsharingRDConfigGroup configGroup = new OneWayCarsharingRDConfigGroup();
    config.addModule(configGroup);

    FreeFloatingConfigGroup configGroupff = new FreeFloatingConfigGroup();
    config.addModule(configGroupff);

    TwoWayCSConfigGroup configGrouptw = new TwoWayCSConfigGroup();
    config.addModule(configGrouptw);

    AllCSModesConfigGroup configGroupAll = new AllCSModesConfigGroup();
    config.addModule(configGroupAll);

    final Scenario scenario = ScenarioUtils.loadScenario(config);

    final Controler controler = new Controler(scenario);
    controler
        .getConfig()
        .controler()
        .setOverwriteFileSetting(
            true
                ? OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles
                : OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists);

    Set<String> modes = new TreeSet<String>();
    modes.add("freefloating");
    modes.add("twowaycarsharing");
    modes.add("onewaycarsharing");
    modes.add("car");
    modes.add("walk");
    modes.add("pt");
    modes.add("bike");
    TripsAnalyzer tripsAnalyzer =
        new TripsAnalyzer(
            controler.getConfig().getParam("controler", "outputDirectory") + "/tripsFile",
            controler.getConfig().getParam("controler", "outputDirectory") + "/durationsFile",
            controler.getConfig().getParam("controler", "outputDirectory") + "/distancesFile",
            modes,
            true,
            controler.getScenario().getNetwork());

    controler.addControlerListener(tripsAnalyzer);

    controler.addControlerListener(
        new AllCSModesTestListener(
            controler,
            Integer.parseInt(
                controler.getConfig().getModule("AllCSModes").getValue("statsWriterFrequency"))));

    controler.addOverridingModule(
        new AbstractModule() {
          @Override
          public void install() {
            bindMobsim().toProvider(AllCSModesQsimFactory.class);
          }
        });

    controler.addOverridingModule(
        new AbstractModule() {

          @Override
          public void install() {

            addRoutingModuleBinding("twowaycarsharing").toInstance(new TwoWayCSRoutingModule());
            addRoutingModuleBinding("freefloating").toInstance(new FreeFloatingRoutingModule());
            addRoutingModuleBinding("onewaycarsharing")
                .toInstance(new OneWayCarsharingRDRoutingModule());

            bind(MainModeIdentifier.class)
                .toInstance(
                    new MainModeIdentifier() {

                      final MainModeIdentifier defaultModeIdentifier = new MainModeIdentifierImpl();

                      @Override
                      public String identifyMainMode(List<? extends PlanElement> tripElements) {

                        for (PlanElement pe : tripElements) {
                          if (pe instanceof Leg
                              && ((Leg) pe).getMode().equals("twowaycarsharing")) {
                            return "twowaycarsharing";
                          } else if (pe instanceof Leg
                              && ((Leg) pe).getMode().equals("onewaycarsharing")) {
                            return "onewaycarsharing";
                          } else if (pe instanceof Leg
                              && ((Leg) pe).getMode().equals("freefloating")) {
                            return "freefloating";
                          }
                        }
                        // if the trip doesn't contain a carsharing leg,
                        // fall back to the default identification method.
                        return defaultModeIdentifier.identifyMainMode(tripElements);
                      }
                    });
          }
        });

    connectFacilitiesWithNetwork(controler);

    initializeLocationChoice(controler);

    // We use a specific scoring function, that uses individual preferences
    // for activity durations.
    controler.setScoringFunctionFactory(
        new CarsharingMATSimLectureScoringFunctionFactory(
            controler.getScenario(),
            new StageActivityTypesImpl(PtConstants.TRANSIT_ACTIVITY_TYPE)));

    controler.run();
  }
  public static void main(String[] args) throws Exception {

    String baseDir = "../../../shared-svn/projects/cottbus/data/scenarios/cottbus_scenario/";
    String networkFile = baseDir + "network_wgs84_utm33n.xml.gz";
    boolean useLanduse = true;
    String populationOutputDirectory = baseDir + "cb_spn_gemeinde_nachfrage_landuse_ohneTagebau/";

    //		String shapesOutputDirectory = populationOutputDirectory + "shapes_all_modes/";
    String shapesOutputDirectory = populationOutputDirectory + "shapes/";

    //		String populationOutputFile = populationOutputDirectory +
    // "commuter_population_wgs84_utm33n.xml.gz";
    String populationOutputFile =
        populationOutputDirectory + "commuter_population_wgs84_utm33n_car_only.xml.gz";
    OutputDirectoryLogging.initLoggingWithOutputDirectory(populationOutputDirectory);

    File shapes = new File(shapesOutputDirectory);
    if (!shapes.exists()) {
      shapes.mkdir();
    }

    Config config1 = ConfigUtils.createConfig();
    config1.network().setInputFile(networkFile);
    Scenario sc = ScenarioUtils.loadScenario(config1);

    CommuterDataReader cdr = new CommuterDataReader();
    cdr.addFilterRange(12071000);
    cdr.addFilter("12052000"); // 12052000 == cottbus stadt
    cdr.readFile(
        "../../../shared-svn/studies/countries/de/pendler_nach_gemeinden/brandenburg_einpendler.csv");
    //		cdr.getCommuterRelations().add(new CommuterDataElement("12052000", "12052000", 1000));

    String gemeindenBrandenburgShapeFile =
        "../../../shared-svn/studies/countries/de/brandenburg_gemeinde_kreisgrenzen/gemeinden/dlm_gemeinden.shp";
    ShapeFileReader gemeindenReader = new ShapeFileReader();
    Collection<SimpleFeature> gemeindenFeatures =
        gemeindenReader.readFileAndInitialize(gemeindenBrandenburgShapeFile);

    CommuterDemandWriter cdw =
        new CommuterDemandWriter(
            gemeindenFeatures,
            gemeindenReader.getCoordinateSystem(),
            cdr.getCommuterRelations(),
            MGC.getCRS(TransformationFactory.WGS84_UTM33N));
    // landuse
    if (useLanduse) {
      DgLanduseReader landuseReader = new DgLanduseReader();
      Tuple<Collection<SimpleFeature>, CoordinateReferenceSystem> homeLanduse =
          landuseReader.readLanduseDataHome();
      Tuple<Collection<SimpleFeature>, CoordinateReferenceSystem> workLanduse =
          landuseReader.readLanduseDataWork();
      cdw.addLanduse("home", homeLanduse);
      cdw.addLanduse("work", workLanduse);
    }
    //
    //		cdw.setScalefactor(1.0); // all modes
    cdw.setScalefactor(0.55); // car mode share
    //		cdw.setScalefactor(0.1); //testing

    cdw.computeDemand(sc);
    PopulationWriter populationWriter = new PopulationWriter(sc.getPopulation(), sc.getNetwork());
    populationWriter.write(populationOutputFile);
    log.info("population written to " + populationOutputFile);

    // write some test output
    Config config = ConfigUtils.createConfig();
    config.network().setInputFile(networkFile);
    config.plans().setInputFile(populationOutputFile);
    Scenario baseScenario = ScenarioUtils.loadScenario(config);

    String shapeFilename = shapesOutputDirectory + "commuter_population_home.shp";
    new DgPopulation2ShapeWriter(
            baseScenario.getPopulation(), MGC.getCRS(TransformationFactory.WGS84_UTM33N))
        .write("home", shapeFilename, MGC.getCRS(TransformationFactory.WGS84_UTM33N));
    shapeFilename = shapesOutputDirectory + "commuter_population_work.shp";
    new DgPopulation2ShapeWriter(
            baseScenario.getPopulation(), MGC.getCRS(TransformationFactory.WGS84_UTM33N))
        .write("work", shapeFilename, MGC.getCRS(TransformationFactory.WGS84_UTM33N));

    log.info("done!");
    OutputDirectoryLogging.closeOutputDirLogging();
  }
  private void run() {

    OutputDirectoryLogging.catchLogEntries();
    try {
      OutputDirectoryLogging.initLoggingWithOutputDirectory(outputDirectory);
    } catch (IOException e1) {
      e1.printStackTrace();
    }

    Config config = ConfigUtils.createConfig();
    config.network().setInputFile(runDirectory + "output_network.xml.gz");
    config.plans().setInputFile(runDirectory + "output_plans.xml.gz");
    config.controler().setOutputDirectory(runDirectory);
    config.controler().setLastIteration(lastIteration);

    // ################################

    GridParameters gridParameters = new GridParameters();
    gridParameters.setReceiverPointGap(receiverPointGap);

    //		// Berlin Coordinates: Area around the city center of Berlin (Tiergarten)
    //		double xMin = 4590855.;
    //		double yMin = 5819679.;
    //		double xMax = 4594202.;
    //		double yMax = 5821736.;

    // Berlin Coordinates: Area around the Tempelhofer Feld 4591900,5813265 : 4600279,5818768
    double xMin = 4591900.;
    double yMin = 5813265.;
    double xMax = 4600279.;
    double yMax = 5818768.;

    // Berlin Coordinates: Area of Berlin
    //		double xMin = 4573258.;
    //		double yMin = 5801225.;
    //		double xMax = 4620323.;
    //		double yMax = 5839639.;

    //		// Berlin Coordinates: Manteuffelstrasse
    //		double xMin = 4595288.82;
    //		double yMin = 5817859.97;
    //		double xMax = 4598267.52;
    //		double yMax = 5820953.98;

    gridParameters.setReceiverPointsGridMinX(xMin);
    gridParameters.setReceiverPointsGridMinY(yMin);
    gridParameters.setReceiverPointsGridMaxX(xMax);
    gridParameters.setReceiverPointsGridMaxY(yMax);

    //		 Berlin Activity Types
    //		String[] consideredActivitiesForDamages = {"home", "work", "educ_primary", "educ_secondary",
    // "educ_higher", "kiga"};
    //		String[] consideredActivitiesForDamages = {"home"};
    //		String[] consideredActivitiesForDamages = {"work"};
    //		String[] consideredActivitiesForDamages = {"educ_primary", "educ_secondary", "educ_higher",
    // "kiga"};
    //		String[] consideredActivitiesForDamages = {"leisure"};
    //		String[] consideredActivitiesForDamages = {"home", "educ_primary", "educ_secondary",
    // "educ_higher", "kiga"};
    //
    //	gridParameters.setConsideredActivitiesForSpatialFunctionality(consideredActivitiesForDamages);

    //		String[] consideredActivitiesForReceiverPointGrid = {"home", "work", "educ_primary",
    // "educ_secondary", "educ_higher", "kiga"};
    //		String[] consideredActivitiesForReceiverPointGrid = {"home", "work", "educ_primary",
    // "educ_secondary", "educ_higher", "kiga", "leisure"};
    //
    //	gridParameters.setConsideredActivitiesForReceiverPointGrid(consideredActivitiesForReceiverPointGrid);

    // ################################

    NoiseParameters noiseParameters = new NoiseParameters();
    noiseParameters.setUseActualSpeedLevel(false);
    noiseParameters.setAllowForSpeedsOutsideTheValidRange(false);
    noiseParameters.setScaleFactor(10.);
    noiseParameters.setComputePopulationUnits(false);
    noiseParameters.setComputeNoiseDamages(false);
    noiseParameters.setInternalizeNoiseDamages(false);
    noiseParameters.setComputeCausingAgents(false);
    noiseParameters.setThrowNoiseEventsAffected(false);
    noiseParameters.setThrowNoiseEventsCaused(false);

    Set<String> hgvIdPrefixes = new HashSet<String>();
    hgvIdPrefixes.add("lkw");
    noiseParameters.setHgvIdPrefixes(hgvIdPrefixes);

    //		Set<String> busIdPrefixes = new HashSet<String>();
    //		busIdPrefixes.add("-B-");
    //		noiseParameters.setBusIdPrefixes(busIdPrefixes);

    //		 Berlin Tunnel Link IDs
    Set<Id<Link>> tunnelLinkIDs = new HashSet<Id<Link>>();
    tunnelLinkIDs.add(Id.create("108041", Link.class));
    tunnelLinkIDs.add(Id.create("108142", Link.class));
    tunnelLinkIDs.add(Id.create("108970", Link.class));
    tunnelLinkIDs.add(Id.create("109085", Link.class));
    tunnelLinkIDs.add(Id.create("109757", Link.class));
    tunnelLinkIDs.add(Id.create("109919", Link.class));
    tunnelLinkIDs.add(Id.create("110060", Link.class));
    tunnelLinkIDs.add(Id.create("110226", Link.class));
    tunnelLinkIDs.add(Id.create("110164", Link.class));
    tunnelLinkIDs.add(Id.create("110399", Link.class));
    tunnelLinkIDs.add(Id.create("96503", Link.class));
    tunnelLinkIDs.add(Id.create("110389", Link.class));
    tunnelLinkIDs.add(Id.create("110116", Link.class));
    tunnelLinkIDs.add(Id.create("110355", Link.class));
    tunnelLinkIDs.add(Id.create("92604", Link.class));
    tunnelLinkIDs.add(Id.create("92603", Link.class));
    tunnelLinkIDs.add(Id.create("25651", Link.class));
    tunnelLinkIDs.add(Id.create("25654", Link.class));
    tunnelLinkIDs.add(Id.create("112540", Link.class));
    tunnelLinkIDs.add(Id.create("112556", Link.class));
    tunnelLinkIDs.add(Id.create("5052", Link.class));
    tunnelLinkIDs.add(Id.create("5053", Link.class));
    tunnelLinkIDs.add(Id.create("5380", Link.class));
    tunnelLinkIDs.add(Id.create("5381", Link.class));
    tunnelLinkIDs.add(Id.create("106309", Link.class));
    tunnelLinkIDs.add(Id.create("106308", Link.class));
    tunnelLinkIDs.add(Id.create("26103", Link.class));
    tunnelLinkIDs.add(Id.create("26102", Link.class));
    tunnelLinkIDs.add(Id.create("4376", Link.class));
    tunnelLinkIDs.add(Id.create("4377", Link.class));
    tunnelLinkIDs.add(Id.create("106353", Link.class));
    tunnelLinkIDs.add(Id.create("106352", Link.class));
    tunnelLinkIDs.add(Id.create("103793", Link.class));
    tunnelLinkIDs.add(Id.create("103792", Link.class));
    tunnelLinkIDs.add(Id.create("26106", Link.class));
    tunnelLinkIDs.add(Id.create("26107", Link.class));
    tunnelLinkIDs.add(Id.create("4580", Link.class));
    tunnelLinkIDs.add(Id.create("4581", Link.class));
    tunnelLinkIDs.add(Id.create("4988", Link.class));
    tunnelLinkIDs.add(Id.create("4989", Link.class));
    tunnelLinkIDs.add(Id.create("73496", Link.class));
    tunnelLinkIDs.add(Id.create("73497", Link.class));
    noiseParameters.setTunnelLinkIDs(tunnelLinkIDs);

    log.info("Loading scenario...");
    Scenario scenario = ScenarioUtils.loadScenario(config);
    log.info("Loading scenario... Done.");

    String outputFilePath =
        outputDirectory + "analysis_it." + config.controler().getLastIteration() + "/";
    File file = new File(outputFilePath);
    file.mkdirs();

    NoiseContext noiseContext = new NoiseContext(scenario, gridParameters, noiseParameters);
    noiseContext.initialize();
    NoiseWriter.writeReceiverPoints(noiseContext, outputFilePath + "/receiverPoints/");

    EventsManager events = EventsUtils.createEventsManager();

    NoiseTimeTracker timeTracker = new NoiseTimeTracker(noiseContext, events, outputFilePath);
    events.addHandler(timeTracker);

    if (noiseContext.getNoiseParams().isUseActualSpeedLevel()) {
      LinkSpeedCalculation linkSpeedCalculator = new LinkSpeedCalculation(noiseContext);
      events.addHandler(linkSpeedCalculator);
    }

    EventWriterXML eventWriter = null;
    if (noiseContext.getNoiseParams().isThrowNoiseEventsAffected()
        || noiseContext.getNoiseParams().isThrowNoiseEventsCaused()) {
      eventWriter =
          new EventWriterXML(
              outputFilePath
                  + config.controler().getLastIteration()
                  + ".events_NoiseImmission_Offline.xml.gz");
      events.addHandler(eventWriter);
    }

    if (noiseContext.getNoiseParams().isComputePopulationUnits()) {
      PersonActivityTracker actTracker = new PersonActivityTracker(noiseContext);
      events.addHandler(actTracker);
    }

    log.info("Reading events file...");
    MatsimEventsReader reader = new MatsimEventsReader(events);
    reader.readFile(
        runDirectory
            + "ITERS/it."
            + config.controler().getLastIteration()
            + "/"
            + config.controler().getLastIteration()
            + ".events.xml.gz");
    log.info("Reading events file... Done.");

    timeTracker.computeFinalTimeIntervals();

    if (noiseContext.getNoiseParams().isThrowNoiseEventsAffected()
        || noiseContext.getNoiseParams().isThrowNoiseEventsCaused()) {
      eventWriter.closeFile();
    }
    log.info("Noise calculation completed.");

    log.info("Processing the noise immissions...");
    ProcessNoiseImmissions process =
        new ProcessNoiseImmissions(
            outputFilePath + "immissions/",
            outputFilePath + "receiverPoints/receiverPoints.csv",
            receiverPointGap);
    process.run();
  }