Exemple #1
0
  /**
   * Used this routine for MeisterEtAl_Heureka_2008 paper, plot of number of deps, arrs by activity
   * type to visualize the time distribution from microcensus.
   */
  public static void analyseInitialTimes(Config config) {

    MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario(config);
    // initialize scenario with events from a given events file
    // - network
    logger.info("Reading network xml file...");
    new MatsimNetworkReader(scenario).readFile(scenario.getConfig().network().getInputFile());
    logger.info("Reading network xml file...done.");
    // - population
    PersonAlgorithm pa = new PersonAnalyseTimesByActivityType(TIME_BIN_SIZE);
    ArrayList<PersonAlgorithm> plansAlgos = new ArrayList<PersonAlgorithm>();
    plansAlgos.add(pa);

    PopulationImpl matsimAgentPopulation = (PopulationImpl) scenario.getPopulation();
    matsimAgentPopulation.setIsStreaming(true);
    PopulationReader plansReader = new MatsimPopulationReader(scenario);
    plansReader.readFile(scenario.getConfig().plans().getInputFile());
    matsimAgentPopulation.printPlansCount();
    int[][] numDeps = ((PersonAnalyseTimesByActivityType) pa).getNumDeps();
    MyRuns.writeAnArray(numDeps, "output/deptimes.txt");
    int[][] numArrs = ((PersonAnalyseTimesByActivityType) pa).getNumArrs();
    MyRuns.writeAnArray(numArrs, "output/arrtimes.txt");
    int[][] numTraveling = ((PersonAnalyseTimesByActivityType) pa).getNumTraveling();
    MyRuns.writeAnArray(numTraveling, "output/traveling.txt");
  }
  public static void main(String[] args) {
    MutableScenario s = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    s.getConfig().transit().setUseTransit(true);
    s.getConfig().scenario().setUseVehicles(true);

    Vehicles v = s.getTransitVehicles();
    TransitSchedule ts = s.getTransitSchedule();
    PopulationImpl p = (PopulationImpl) s.getPopulation();

    new MatsimNetworkReader(s).readFile(NETWORK);
    new VehicleReaderV1(v).readFile(VEHICLES);
    new TransitScheduleReader(s).readFile(SCHEDULE);
    log.info("build transit router...");
    TransitRouterConfig tRConfig =
        new TransitRouterConfig(
            s.getConfig().planCalcScore(),
            s.getConfig().plansCalcRoute(),
            s.getConfig().transitRouter(),
            s.getConfig().vspExperimental());

    TransitRouterImpl router = new TransitRouterImpl(tRConfig, ts);

    PtRouter ptR = new PtRouter(router);

    p.setIsStreaming(true);
    p.addAlgorithm(ptR);

    log.info("start processing persons...");
    new MatsimPopulationReader(s).readFile(PLANS);

    ptR.close();
  }
  public static void main(String[] args) {
    MutableScenario scenario =
        (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Network network = scenario.getNetwork();
    new MatsimNetworkReader(scenario).readFile("../../input/network.xml");

    TravelTimeCalculator ttc =
        new TravelTimeCalculator(
            network, 60, 30 * 3600, scenario.getConfig().travelTimeCalculator());
    LeastCostPathTree st =
        new LeastCostPathTree(
            ttc.getLinkTravelTimes(),
            new RandomizingTimeDistanceTravelDisutility.Builder(TransportMode.car)
                .createTravelDisutility(
                    ttc.getLinkTravelTimes(), scenario.getConfig().planCalcScore()));
    Node origin = network.getNodes().get(Id.create(1, Node.class));
    st.calculate(network, origin, 8 * 3600);
    Map<Id<Node>, NodeData> tree = st.getTree();
    for (Map.Entry<Id<Node>, NodeData> e : tree.entrySet()) {
      Id<Node> id = e.getKey();
      NodeData d = e.getValue();
      if (d.getPrevNodeId() != null) {
        System.out.println(id + "\t" + d.getTime() + "\t" + d.getCost() + "\t" + d.getPrevNodeId());
      } else {
        System.out.println(id + "\t" + d.getTime() + "\t" + d.getCost() + "\t" + "0");
      }
    }
  }
Exemple #4
0
  /*
   * Reads the population from the plans file.
   */
  @Deprecated // use centralized infrastructure
  public static Scenario readScenario(
      String plansFile, String networkFile, String facilititiesPath) {
    MutableScenario sc = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());

    sc.getConfig().setParam("plans", "inputPlansFile", plansFile);
    sc.getConfig().setParam("network", "inputNetworkFile", networkFile);
    sc.getConfig().setParam("facilities", "inputFacilitiesFile", facilititiesPath);

    ScenarioUtils.loadScenario(sc);

    return sc;
  }
  public InternalControler(
      MutableScenario scenario,
      double fare,
      boolean calculate_inVehicleTimeDelayEffects,
      boolean calculate_waitingTimeDelayEffects,
      boolean calculate_capacityDelayEffects,
      boolean marginalCostPricingPt,
      boolean calculate_carCongestionEffects,
      boolean marginalCostPricingCar) {

    this.calculate_inVehicleTimeDelayEffects = calculate_inVehicleTimeDelayEffects;
    this.calculate_waitingTimeDelayEffects = calculate_waitingTimeDelayEffects;
    this.calculate_capacityDelayEffects = calculate_capacityDelayEffects;
    this.marginalCostPricingPt = marginalCostPricingPt;
    this.calculate_carCongestionEffects = calculate_carCongestionEffects;
    this.marginalCostPricingCar = marginalCostPricingCar;
    this.scenario = scenario;
    this.fare = fare;

    this.CONSTANT_PT =
        scenario.getConfig().planCalcScore().getModes().get(TransportMode.pt).getConstant();
    log.info("Pt constant set to " + this.CONSTANT_PT);

    //		this.LATE_ARRIVAL = -1. * this.PERFORMING * 2.; // coming early (which is the opportunity
    // costs of time) multiplied by 3 --> multiplying by 2 (see Hollander 2006)

  }
  public static void runEventsProcessing(Properties properties) {
    boolean isTransit = false;
    MutableScenario scenario =
        (MutableScenario)
            ScenarioUtils.createScenario(
                ConfigUtils.loadConfig(properties.get("configFile").toString()));
    scenario.getConfig().transit().setUseTransit(true);
    if (!properties.get("transitScheduleFile").toString().equals("")) {
      new TransitScheduleReader(scenario)
          .readFile(properties.get("transitScheduleFile").toString());
      isTransit = true;
    }
    new MatsimNetworkReader(scenario).readFile(properties.get("networkFile").toString());

    EventsManager eventsManager = EventsUtils.createEventsManager();
    EventsToTravelDiaries test;
    // if(linkTrafficComponent.isSelected()){
    // test = new EventsToPlanElements(
    // scenario.getTransitSchedule(), scenario.getNetwork(),
    // scenario.getConfig(),new File(postgresPropertiesComponent.getText())
    // ,tableSuffixComponent.getText());
    // }else{
    if (isTransit) {
      test =
          new EventsToTravelDiaries(
              scenario.getTransitSchedule(), scenario.getNetwork(), scenario.getConfig());

    } else {
      test = new EventsToTravelDiaries(scenario);
    }
    // }
    eventsManager.addHandler(test);
    new MatsimEventsReader(eventsManager).readFile(properties.get("eventsFile").toString());

    try {

      test.writeSimulationResultsToTabSeparated(
          properties.get("outputPath").toString(), properties.get("tableSuffix").toString());

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    System.out.println("Number of stuck vehicles/passengers: " + test.getStuck());
  }
Exemple #7
0
 private void loadScenario() {
   Config config = scenario.getConfig();
   config.transit().setUseTransit(true);
   config.scenario().setUseVehicles(true);
   config.transit().setTransitScheduleFile(scheduleFile);
   config.transit().setVehiclesFile(vehiclesFile);
   config.network().setInputFile(networkFile);
   ScenarioUtils.loadScenario(scenario);
 }
Exemple #8
0
  /*
   * Reads the network from the network file.
   */
  @Deprecated // use centralized infrastructure
  public static Network readNetwork(String networkFile) {
    MutableScenario sc = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());

    sc.getConfig().setParam("network", "inputNetworkFile", networkFile);

    ScenarioUtils.loadScenario(sc);

    return sc.getNetwork();
  }
 private static Population getPopulationTypesTransitLine(Scenario scenario, String[] args) {
   scenario.getConfig().transit().setUseTransit(true);
   (new TransitScheduleReader(scenario)).readFile(args[4]);
   TransitLine line =
       scenario.getTransitSchedule().getTransitLines().get(Id.create(args[5], TransitLine.class));
   MutableScenario sc = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());
   Population population = PopulationUtils.createPopulation(sc.getConfig(), sc.getNetwork());
   for (Person person : scenario.getPopulation().getPersons().values())
     if (isRelatedWithLine(person, line))
       population.addPerson(new PersonImplPops(person, Id.create(line.getId(), Population.class)));
     else population.addPerson(new PersonImplPops(person, PersonImplPops.DEFAULT_POP_ID));
   return population;
 }
Exemple #10
0
  /**
   * TODO: write test.
   *
   * @param persons
   * @param outputPlansFileName
   * @param network
   */
  public static void writePersons(
      Collection<? extends Person> persons,
      String outputPlansFileName,
      Network network,
      MutableScenario scenario) {
    PopulationWriter popWriter =
        new PopulationWriter(
            PopulationUtils.createPopulation(scenario.getConfig(), scenario.getNetwork()), network);
    popWriter.writeStartPlans(outputPlansFileName);

    for (Person person : persons) {
      popWriter.writePerson(person);
    }

    popWriter.writeEndPlans();
  }
Exemple #11
0
  void moveInitDemandToDifferentNetwork(final String[] args) {

    // read ivtch demand
    MutableScenario scenario =
        (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Config config = scenario.getConfig();
    MeisterkConfigGroup meisterkConfigGroup = new MeisterkConfigGroup();
    config.addModule(meisterkConfigGroup);
    ConfigReader reader = new ConfigReader(config);
    reader.readFile(args[0]);
    MatsimRandom.reset(config.global().getRandomSeed());

    ScenarioUtils.loadScenario(scenario);

    Population population = scenario.getPopulation();
    Network network = scenario.getNetwork();

    // remove links and routes
    PersonRemoveLinkAndRoute personRemoveLinkAndRoute = new PersonRemoveLinkAndRoute();
    personRemoveLinkAndRoute.run(population);

    // switch to new network in scenario

    // this is what I found ...
    //		ScenarioImpl scenario2 = (ScenarioImpl)
    // ScenarioUtils.createScenario(ConfigUtils.createConfig());
    //		new MatsimNetworkReader(scenario2).parse(config.getParam(MeisterkConfigGroup.GROUP_NAME,
    // "inputSecondNetworkFile"));
    //		scenario.setNetwork(scenario2.getNetwork());

    // ... but I think we can just give the existing scenario to the reader, so I am changing this.
    // There is so much commented out in this
    // code that it is probably no longer used anyways. kai, sep'15
    new MatsimNetworkReader(scenario)
        .parse(config.getParam(MeisterkConfigGroup.GROUP_NAME, "inputSecondNetworkFile"));

    // run XY2Links
    XY2Links xY2Links = new XY2Links();

    // write out new initial demand
    // new PopulationWriter(population,
    // network).write(null);//scenario.getConfig().plans().getOutputFile());

  }
Exemple #12
0
  void ktiPtRoutesPerformanceTest(final String[] args) {

    MutableScenario scenario =
        (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Config config = scenario.getConfig();
    KtiConfigGroup ktiConfigGroup = new KtiConfigGroup();
    config.addModule(ktiConfigGroup);
    ConfigReader reader = new ConfigReader(config);
    reader.readFile(args[0]);

    Network network = scenario.getNetwork();

    NodeImpl node = null;

    node = new NodeImpl(Id.create(1, Node.class));
    final double x = -824635.0;
    final double y = -799519.0;
    node.setCoord(new Coord(x, y));
    network.addNode(node);

    node = new NodeImpl(Id.create(2, Node.class));
    node.setCoord(new Coord(2732681.5, 2625289.25));
    network.addNode(node);

    PlansCalcRouteKtiInfo plansCalcRouteKtiInfo = new PlansCalcRouteKtiInfo(ktiConfigGroup);
    plansCalcRouteKtiInfo.prepare(network);

    int skip = 1;
    int max = 100000;
    for (int i = 0; i < max; i++) {
      String expectedRouteDescription = "kti=300614=6616=456.78=4258=8500301";
      KtiPtRoute testee = new KtiPtRoute(null, null, plansCalcRouteKtiInfo);
      testee.setRouteDescription(expectedRouteDescription);
      if (i == skip) {
        logger.info("Constructed " + i + " KtiPtRoute objects with processing route descriptions.");
        skip += max / 10;
      }
    }
    logger.info("Constructed " + max + " KtiPtRoute objects with processing route descriptions.");
  }
  public void run() {

    new MatsimNetworkReader(scenario).readFile(scenario.getConfig().network().getInputFile());
    new TransitScheduleReaderV1(scenario)
        .readFile(this.scenario.getConfig().transit().getTransitScheduleFile());
    Logger.getLogger(this.getClass())
        .fatal(
            "cannot say if the following should be vehicles or transit vehicles; aborting ... .  kai, feb'15");
    System.exit(-1);
    new VehicleReaderV1((scenario).getTransitVehicles())
        .readFile(this.scenario.getConfig().transit().getVehiclesFile());

    Controler controler = new Controler(this.scenario);
    controler
        .getConfig()
        .controler()
        .setOverwriteFileSetting(
            OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles);
    controler.addOverridingModule(new OTFVisFileWriterModule());
    controler.addControlerListener(
        new OptControlerListener(
            this.fare,
            this.scenario,
            this.calculate_inVehicleTimeDelayEffects,
            this.calculate_waitingTimeDelayEffects,
            this.calculate_capacityDelayEffects,
            this.marginalCostPricingPt,
            this.calculate_carCongestionEffects,
            this.marginalCostPricingCar));

    ControlerConfigGroup controlerConfGroup = controler.getConfig().controler();
    if (controlerConfGroup.getLastIteration() == 0) {
      controlerConfGroup.setWriteEventsInterval(1);
      controlerConfGroup.setWritePlansInterval(1);
    } else {
      controlerConfGroup.setWriteEventsInterval(controlerConfGroup.getLastIteration());
      controlerConfGroup.setWritePlansInterval(controlerConfGroup.getLastIteration());
    }

    PlanCalcScoreConfigGroup planCalcScoreConfigGroup = controler.getConfig().planCalcScore();
    planCalcScoreConfigGroup.setMarginalUtilityOfMoney(MARGINAL_UTILITY_OF_MONEY);
    planCalcScoreConfigGroup.setPerforming_utils_hr(PERFORMING);

    planCalcScoreConfigGroup.getModes().get(TransportMode.car).setConstant(CONSTANT_CAR);
    planCalcScoreConfigGroup
        .getModes()
        .get(TransportMode.car)
        .setMarginalUtilityOfTraveling(TRAVEL_CAR);
    planCalcScoreConfigGroup
        .getModes()
        .get(TransportMode.car)
        .setMonetaryDistanceRate(MONETARY_DISTANCE_COST_RATE_CAR);

    planCalcScoreConfigGroup.getModes().get(TransportMode.walk).setConstant(CONSTANT_WALK);
    planCalcScoreConfigGroup
        .getModes()
        .get(TransportMode.walk)
        .setMarginalUtilityOfTraveling(TRAVEL_WALK);
    planCalcScoreConfigGroup
        .getModes()
        .get(TransportMode.pt)
        .setMonetaryDistanceRate(MONETARY_DISTANCE_COST_RATE_PT);

    planCalcScoreConfigGroup.getModes().get(TransportMode.pt).setConstant(CONSTANT_PT);
    planCalcScoreConfigGroup
        .getModes()
        .get(TransportMode.pt)
        .setMarginalUtilityOfTraveling(TRAVEL_PT_IN_VEHICLE);
    planCalcScoreConfigGroup.setMarginalUtlOfWaitingPt_utils_hr(TRAVEL_PT_WAITING);
    planCalcScoreConfigGroup.setUtilityOfLineSwitch(LINE_SWITCH);

    planCalcScoreConfigGroup.setLateArrival_utils_hr(LATE_ARRIVAL);
    planCalcScoreConfigGroup.setEarlyDeparture_utils_hr(EARLY_DEPARTURE);
    planCalcScoreConfigGroup.setMarginalUtlOfWaiting_utils_hr(WAITING);

    OptimizationScoringFunctionFactory scoringfactory =
        new OptimizationScoringFunctionFactory(scenario, STUCK_SCORE);

    controler.setScoringFunctionFactory(scoringfactory);

    controler.getConfig().controler().setCreateGraphs(false);
    controler.run();
  }
Exemple #14
0
  public static void main(String[] args) throws IOException {

    final BufferedReader readLink = IOUtils.getBufferedReader(args[0]);
    MutableScenario scenario =
        (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    PopulationReader populationReader = new MatsimPopulationReader(scenario);
    MatsimNetworkReader networkReader = new MatsimNetworkReader(scenario.getNetwork());
    Config config = scenario.getConfig();
    final BufferedWriter outLink = IOUtils.getBufferedWriter(args[3]);

    scenario.getConfig().getModule("qsim").addParam("mainMode", "cs_fix_gas");

    int count = 0;
    networkReader.readFile(args[1]);
    populationReader.readFile(args[2]);

    Network network = scenario.getNetwork();
    String s = readLink.readLine();
    s = readLink.readLine();
    String previous = null;
    int counterrb = 0;
    int counterff = 0;
    double income = 0.0;
    boolean ff = false;
    boolean rb = false;
    while (s != null) {
      Leg lastLeg = null;
      String[] arr = s.split("\t");

      double startTime = Double.parseDouble(arr[2]);
      double endTime = Double.parseDouble(arr[3]);
      Id<Person> personId = Id.create(arr[0], Person.class);

      if (previous == null || !previous.equals(arr[0])) {
        counterrb = 0;
        counterff = 0;
      }

      if (arr[1].contains("c")) {
        rb = true;
        ff = false;
      } else {
        rb = false;
        ff = true;
      }

      if (rb) {

        Person p = scenario.getPopulation().getPersons().get(personId);
        boolean cs = false;
        double distance = 0.0;
        int c = 0;
        for (PlanElement pe : p.getSelectedPlan().getPlanElements()) {

          if (pe instanceof Activity) {
            if (c == counterrb) {
              if (((Activity) pe).getType().equals("cs_interaction")
                  && ((Activity) pe).getLinkId().toString().equals(arr[4])
                  && !cs) {
                cs = true;
              } else if (((Activity) pe).getType().equals("cs_interaction")
                  && ((Activity) pe).getLinkId().toString().equals(arr[4])
                  && cs
                  && lastLeg.getMode().equals("cs_fix_gas")) {

                cs = false;
                counterrb += 2;
                // write the distance here
                outLink.write(arr[0]);
                outLink.write(" ");
                outLink.write(arr[1]);
                outLink.write(" ");
                outLink.write(arr[2]);
                outLink.write(" ");
                outLink.write(arr[3]);
                outLink.write(" ");
                outLink.write(Double.toString(distance));
                outLink.newLine();
                break;
              }
            }

          } else if (pe instanceof Leg) {
            lastLeg = (Leg) pe;
            if (c < counterrb) {
              if (((Leg) pe).getMode().equals("cs_walk")) {
                c++;
              }
            } else if (cs) {

              if (((Leg) pe).getMode().equals("cs_fix_gas")) {

                Route r = ((Leg) pe).getRoute();
                GenericRouteImpl rg = (GenericRouteImpl) r;
                String grr = rg.getRouteDescription();

                String[] arr1 = grr.split("\\s");

                for (int i = 0; i < arr1.length; i++) {

                  distance += network.getLinks().get(Id.create(arr1[i], Link.class)).getLength();
                }
              }
            }
          }
        }
      }
      // else {
      /*
      	Person p = scenario.getPopulation().getPersons().get(personId);
      	double distance = 0.0;

      	for(PlanElement pe:p.getSelectedPlan().getPlanElements()) {
      		int c = 0;

      		if (pe instanceof Leg) {
      				lastLeg = (Leg) pe;
      				if (c < counterff) {
      					if (((Leg) pe).getMode().equals("cs_flex_gas")) {
      						c++;

      					}
      				}
      				else if (((Leg) pe).getMode().equals("cs_flex_gas")) {

      						Route r = ((Leg) pe).getRoute();
      						GenericRouteImpl rg = (GenericRouteImpl) r;
      						String grr = rg.getRouteDescription();
      						System.out.println(grr);
      						if (grr == null) {
      							System.out.println("bla");
      							counterff++;
      							break;
      						}
      						String[] arr1 = grr.split("\\s");

      						for (int i = 0; i < arr1.length; i++) {

      							distance += network.getLinks().get(Id.create(arr1[i])).getLength();
      						}

      						//write here the distance
      						outLink.write(arr[0]);
      						outLink.write(" ");
      						outLink.write(arr[1]);
      						outLink.write(" ");
      						outLink.write(arr[2]);
      						outLink.write(" ");
      						outLink.write(arr[3]);
      						outLink.write(" ");
      						outLink.write(Double.toString(distance));
      						outLink.newLine();
      						counterff++;
      						break;

      			}

      		}
      	}

      }*/

      previous = arr[0];
      s = readLink.readLine();
    }
    outLink.flush();
    outLink.close();
    System.out.println(income);
    System.out.println(count);
  }