Exemplo n.º 1
1
  @Test
  public void testLegAttributesIO() {
    final Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig());

    final Person person = population.getFactory().createPerson(Id.createPersonId("Donald Trump"));
    population.addPerson(person);

    final Plan plan = population.getFactory().createPlan();
    person.addPlan(plan);
    final Leg leg = population.getFactory().createLeg("SUV");
    plan.addActivity(
        population.getFactory().createActivityFromLinkId("speech", Id.createLinkId(1)));
    plan.addLeg(leg);
    plan.addActivity(population.getFactory().createActivityFromLinkId("tweet", Id.createLinkId(2)));

    leg.getAttributes().putAttribute("mpg", 0.000001d);

    final String file = utils.getOutputDirectory() + "/population.xml";
    new PopulationWriter(population).writeV6(file);

    final Scenario readScenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new PopulationReader(readScenario).readFile(file);

    final Person readPerson =
        readScenario.getPopulation().getPersons().get(Id.createPersonId("Donald Trump"));
    final Leg readLeg = (Leg) readPerson.getSelectedPlan().getPlanElements().get(1);

    Assert.assertEquals(
        "Unexpected Double attribute in " + readLeg.getAttributes(),
        leg.getAttributes().getAttribute("mpg"),
        readLeg.getAttributes().getAttribute("mpg"));
  }
Exemplo n.º 2
0
  @Test
  public void testCoord3dIO() {
    final Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig());

    final Person person = population.getFactory().createPerson(Id.createPersonId("Donald Trump"));
    population.addPerson(person);

    final Plan plan = population.getFactory().createPlan();
    person.addPlan(plan);
    plan.addActivity(population.getFactory().createActivityFromCoord("speech", new Coord(0, 0)));
    plan.addActivity(
        population.getFactory().createActivityFromCoord("tweet", new Coord(0, 0, -100)));

    final String file = utils.getOutputDirectory() + "/population.xml";
    new PopulationWriter(population).writeV6(file);

    final Scenario readScenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new PopulationReader(readScenario).readFile(file);

    final Person readPerson =
        readScenario.getPopulation().getPersons().get(Id.createPersonId("Donald Trump"));
    final Activity readSpeach = (Activity) readPerson.getSelectedPlan().getPlanElements().get(0);
    final Activity readTweet = (Activity) readPerson.getSelectedPlan().getPlanElements().get(1);

    Assert.assertFalse(
        "did not expect Z value in " + readSpeach.getCoord(), readSpeach.getCoord().hasZ());

    Assert.assertTrue("did expect T value in " + readTweet.getCoord(), readTweet.getCoord().hasZ());

    Assert.assertEquals(
        "unexpected Z value in " + readTweet.getCoord(),
        -100,
        readTweet.getCoord().getZ(),
        MatsimTestUtils.EPSILON);
  }
Exemplo n.º 3
0
  @Test
  public void testPersonAttributesIO() {
    final Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig());

    final Person person = population.getFactory().createPerson(Id.createPersonId("Donald Trump"));
    population.addPerson(person);

    person.getAttributes().putAttribute("brain", false);
    person.getAttributes().putAttribute("party", "republican");

    final String file = utils.getOutputDirectory() + "/population.xml";
    new PopulationWriter(population).writeV6(file);

    final Scenario readScenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new PopulationReader(readScenario).readFile(file);

    final Person readPerson =
        readScenario.getPopulation().getPersons().get(Id.createPersonId("Donald Trump"));

    Assert.assertEquals(
        "Unexpected boolean attribute in " + readPerson.getAttributes(),
        person.getAttributes().getAttribute("brain"),
        readPerson.getAttributes().getAttribute("brain"));

    Assert.assertEquals(
        "Unexpected String attribute in " + readPerson.getAttributes(),
        person.getAttributes().getAttribute("party"),
        readPerson.getAttributes().getAttribute("party"));
  }
Exemplo n.º 4
0
  @Test
  public void testActivityAttributesIO() {
    final Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig());

    final Person person = population.getFactory().createPerson(Id.createPersonId("Donald Trump"));
    population.addPerson(person);

    final Plan plan = population.getFactory().createPlan();
    person.addPlan(plan);
    final Activity act = population.getFactory().createActivityFromCoord("speech", new Coord(0, 0));
    plan.addActivity(act);

    act.getAttributes().putAttribute("makes sense", false);
    act.getAttributes().putAttribute("length", 1895L);

    final String file = utils.getOutputDirectory() + "/population.xml";
    new PopulationWriter(population).writeV6(file);

    final Scenario readScenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new PopulationReader(readScenario).readFile(file);

    final Person readPerson =
        readScenario.getPopulation().getPersons().get(Id.createPersonId("Donald Trump"));
    final Activity readAct = (Activity) readPerson.getSelectedPlan().getPlanElements().get(0);

    Assert.assertEquals(
        "Unexpected boolean attribute in " + readAct.getAttributes(),
        act.getAttributes().getAttribute("makes sense"),
        readAct.getAttributes().getAttribute("makes sense"));

    Assert.assertEquals(
        "Unexpected Long attribute in " + readAct.getAttributes(),
        act.getAttributes().getAttribute("length"),
        readAct.getAttributes().getAttribute("length"));
  }
Exemplo n.º 5
0
  @Test
  public void testEmptyPersonAttributesIO() {
    final Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig());

    final Person person = population.getFactory().createPerson(Id.createPersonId("Donald Trump"));
    population.addPerson(person);

    final String file = utils.getOutputDirectory() + "/population.xml";
    new PopulationWriter(population).writeV6(file);

    // just check everything works without attributes (dtd validation etc)
    final Scenario readScenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new PopulationReader(readScenario).readFile(file);
  }
 public static void main(String[] args) {
   Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
   new MatsimNetworkReader(scenario)
       .readFile("../../../shared-svn/projects/vw_rufbus/scenario/input/networkptcc.xml");
   int pop = 1000;
   Random rand = MatsimRandom.getRandom();
   for (int i = 0; i < pop; i++) {
     int hx = 603906 - 1500 + rand.nextInt(3000);
     int hy = 5791651 - 1500 + rand.nextInt(3000);
     Coord home = new Coord(hx, hy);
     int wx = 621155 - 1500 + rand.nextInt(3000);
     int wy = 5810010 - 1500 + rand.nextInt(3000);
     Coord work = new Coord(wx, wy);
     Person p = createPerson(scenario, home, work, i);
     scenario.getPopulation().addPerson(p);
   }
   for (int i = 1000; i < pop * 2; i++) {
     int hx = 603906 - 1500 + rand.nextInt(3000);
     int hy = 5791651 - 1500 + rand.nextInt(3000);
     int wx = 621155 - 1500 + rand.nextInt(3000);
     int wy = 5810010 - 1500 + rand.nextInt(3000);
     Coord work = new Coord(hx, hy);
     Coord home = new Coord(wx, wy);
     Person p = createPerson(scenario, home, work, i);
     scenario.getPopulation().addPerson(p);
   }
   new PopulationWriter(scenario.getPopulation(), scenario.getNetwork())
       .write("../../../shared-svn/projects/vw_rufbus/scenario/input/taxibuspassengers.xml");
 }
Exemplo n.º 7
0
  public static void main(final String[] args) {

    String zoneMappingFilename =
        "/Volumes/Data/projects/sviDosierungsanlagen/scenarios/kreuzlingen/l41_ZoneNo_TAZ_mapping.csv";
    String networkFilename =
        "/Volumes/Data/projects/sviDosierungsanlagen/scenarios/kreuzlingen/matsim/network.cleaned.xml";
    String vehTrajectoryFilename = "/Users/cello/Desktop/VehTrajectory.dat";

    Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new MatsimNetworkReader(scenario.getNetwork()).readFile(networkFilename);

    ZoneIdToIndexMapping zoneMapping = new ZoneIdToIndexMapping();
    new ZoneIdToIndexMappingReader(zoneMapping).readFile(zoneMappingFilename);

    DynamicTravelTimeMatrix matrix = new DynamicTravelTimeMatrix(600, 30 * 3600.0);
    //		new VehicleTrajectoriesReader(new CalculateTravelTimeMatrixFromVehTrajectories(matrix),
    // zoneMapping).readFile(vehTrajectoryFilename);

    TravelTimeCalculator ttcalc =
        new TravelTimeCalculator(
            scenario.getNetwork(), scenario.getConfig().travelTimeCalculator());
    new VehicleTrajectoriesReader(
            new CalculateLinkTravelTimesFromVehTrajectories(ttcalc, scenario.getNetwork()),
            zoneMapping)
        .readFile(vehTrajectoryFilename);
    matrix.dump();
  }
Exemplo n.º 8
0
  /** @param args */
  public static void main(String[] args) {

    String input = args[0];
    String output = args[1];

    /* Read the network. */
    Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new MatsimNetworkReader(scenario.getNetwork()).readFile(input);

    /* Transform each node. */
    CoordinateTransformation ct =
        TransformationFactory.getCoordinateTransformation(
            TransformationFactory.WGS84, "EPSG:25832");
    //		CoordinateTransformation ct =
    // TransformationFactory.getCoordinateTransformation(TransformationFactory.WGS84,TransformationFactory.DHDN_GK4);

    //		CoordinateTransformation ct =
    // TransformationFactory.getCoordinateTransformation("EPSG:25832",TransformationFactory.WGS84);
    //		CoordinateTransformation ct =
    // TransformationFactory.getCoordinateTransformation(TransformationFactory.DHDN_GK4,TransformationFactory.WGS84);

    for (Node node : scenario.getNetwork().getNodes().values()) {
      ((Node) node).setCoord(ct.transform(node.getCoord()));
    }

    /* Write the resulting network. */
    new NetworkWriter(scenario.getNetwork()).write(output);
  }
  public static void main(String[] args) {

    MutableScenario scenario =
        (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    MatsimReader populationReader = new PopulationReader(scenario);
    MatsimNetworkReader networkReader = new MatsimNetworkReader(scenario.getNetwork());
    networkReader.readFile(args[1]);
    populationReader.readFile(args[2]);

    ObjectAttributes bla = new ObjectAttributes();

    new ObjectAttributesXmlReader(bla).readFile(args[0]);

    for (Person p : scenario.getPopulation().getPersons().values()) {
      String act = "home";
      if (bla.getAttribute(p.getId().toString(), "earliestEndTime_leisure") != null)
        act = act + ",leisure";
      //	if (bla.getAttribute(p.getId().toString(), "earliestEndTime_work") != null)
      //		act = act + ",work";
      if (bla.getAttribute(p.getId().toString(), "earliestEndTime_shop") != null)
        act = act + ",shop";
      //	if (bla.getAttribute(p.getId().toString(), "earliestEndTime_education") != null)
      //		act = act + ",education";

      bla.putAttribute(p.getId().toString(), "activities", act);
    }

    ObjectAttributesXmlWriter betaWriter = new ObjectAttributesXmlWriter(bla);
    betaWriter.writeFile(args[3]);
  }
Exemplo n.º 10
0
  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();
  }
Exemplo n.º 11
0
  private Scenario loadAndPrepareScenario() {
    //		String netfile = utils.getClassInputDirectory() + "output_network.xml";
    String popfile = utils.getClassInputDirectory() + "output_plans.xml";
    Config config = ConfigUtils.createConfig();
    //		config.network().setInputFile(netfile);
    config.plans().setInputFile(popfile);

    {
      ModeRoutingParams params = new ModeRoutingParams();
      params.setMode("pt");
      config.plansCalcRoute().addModeRoutingParams(params);
    }
    {
      ModeRoutingParams params = new ModeRoutingParams();
      params.setMode("transit_walk");
      config.plansCalcRoute().addModeRoutingParams(params);
    }
    {
      ModeRoutingParams params = new ModeRoutingParams();
      params.setMode("train");
      config.plansCalcRoute().addModeRoutingParams(params);
    }

    Scenario sc = ScenarioUtils.loadScenario(config);
    createExperimentalTransitRoutes(sc);

    return sc;
  }
Exemplo n.º 12
0
  public void analyzeModeChainFeasibility(Config config) {

    MutableScenario scenario =
        (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());

    // initialize scenario with events from a given events file
    // - network
    logger.info("Reading network xml file...");
    Network network = scenario.getNetwork();
    new MatsimNetworkReader(scenario).readFile(config.network().getInputFile());
    logger.info("Reading network xml file...done.");

    // - facilities
    logger.info("Reading facilities xml file...");
    ActivityFacilities facilities = scenario.getActivityFacilities();
    new MatsimFacilitiesReader(scenario).parse(config.facilities().getInputFile());
    logger.info("Reading facilities xml file...");

    // - population
    PersonAnalyzeModeChainFeasibility pa =
        new PersonAnalyzeModeChainFeasibility(facilities, network);
    ArrayList<PersonAlgorithm> plansAlgos = new ArrayList<PersonAlgorithm>();
    plansAlgos.add(pa);

    PopulationImpl matsimAgentPopulation = (PopulationImpl) scenario.getPopulation();
    matsimAgentPopulation.setIsStreaming(true);
    matsimAgentPopulation.addAlgorithm(pa);
    PopulationReader plansReader = new MatsimPopulationReader(scenario);
    plansReader.readFile(config.plans().getInputFile());

    logger.info("Number of selected plans which are infeasible: " + pa.getNumInfeasiblePlans());
  }
Exemplo n.º 13
0
  /**
   * When not using PT but using a multimodal network, car should not be routed on links restricted
   * to pt modes, such as railways.
   */
  @Test
  public void testRestrictedNetworkNoPt() throws Exception {
    Config config = ConfigUtils.createConfig();
    config.transit().setUseTransit(false);

    testRestrictedNetwork(config);
  }
Exemplo n.º 14
0
  public static void main(String[] args) {
    Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Scenario scenario2 = ScenarioUtils.createScenario(ConfigUtils.createConfig());

    new MatsimNetworkReader(scenario.getNetwork())
        .readFile(
            "C:/Users/Joschka/Documents/shared-svn/projects/vw_rufbus/scenario/network/versions/network_trainonly.xml");
    new MatsimNetworkReader(scenario2.getNetwork())
        .readFile(
            "C:/Users/Joschka/Documents/shared-svn/projects/vw_rufbus/scenario/network/pt/braunschweig/bs-network.xml");
    MergeNetworks.merge(scenario.getNetwork(), "", scenario2.getNetwork());

    new NetworkWriter(scenario.getNetwork())
        .write(
            "C:/Users/Joschka/Documents/shared-svn/projects/vw_rufbus/scenario/network/versions/networkpt-feb.xml");
  }
Exemplo n.º 15
0
  public static void main(String[] args) throws IOException {

    Config c = ConfigUtils.createConfig();
    ConfigUtils.loadConfig(c, RAW_INPUT + "output_config.xml.gz");

    Scenario sc = ScenarioUtils.createScenario(c);
    //		Network net = sc.getNetwork();
    new MatsimNetworkReader(sc.getNetwork()).readFile(RAW_INPUT + "/output_network.xml.gz");
    new PopulationReader(sc).readFile(RAW_INPUT + "output_plans.xml.gz");
    //		dropDepTimes(sc.getPopulation());

    c.controler().setOutputDirectory(NEW_DIR + "output/");
    c.network().setInputFile(NEW_DIR + "input/network.xml.gz");
    c.plans().setInputFile(NEW_DIR + "input/population.xml.gz");

    new NetworkWriter(sc.getNetwork()).write(c.network().getInputFile());
    new PopulationWriter(sc.getPopulation(), sc.getNetwork()).write(c.plans().getInputFile());
    new ConfigWriter(c).write(NEW_DIR + "input/config.xml");

    c.controler().setLastIteration(0);

    Controler cntr = new Controler(sc);
    cntr.getConfig()
        .controler()
        .setOverwriteFileSetting(
            OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles);
    cntr.run();

    Analyzer.main(
        new String[] {
          NEW_DIR + "/output/ITERS/it.0/0.events.xml.gz",
          "/Users/laemmel/arbeit/papers/2015/TRBwFZJ/hybridsim_trb2016/analysis/runagain-vehicles_plot_data"
        });
  }
Exemplo n.º 16
0
  /** @param args */
  public static void main(final String[] args) {
    // final String netFilename = "./test/yu/ivtch/input/network.xml";
    final String netFilename = "../data/ivtch/input/network.xml";
    // final String netFilename = "./test/yu/equil_test/equil_net.xml";
    // final String plansFilename = "../runs/run264/100.plans.xml.gz";
    final String plansFilename = "../data/ivtch/carPt_opt_run266/ITERS/it.100/100.plans.xml.gz";
    // final String plansFilename =
    // "./test/yu/equil_test/output/100.plans.xml.gz";
    // final String outFilename = "./output/legsCount.txt.gz";
    // final String outFilename =
    // "../data/ivtch/carPt_opt_run266/legsCount.txt";

    Gbl.startMeasurement();

    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new MatsimNetworkReader(scenario).readFile(netFilename);

    Population population = scenario.getPopulation();

    System.out.println("-->reading plansfile: " + plansFilename);
    new MatsimPopulationReader(scenario).readFile(plansFilename);

    CarIllegal cl = new CarIllegal();
    cl.run(population);

    System.out.println("--> Done!\n-->There is " + cl.getCount() + " illeagel drivers!");
    Gbl.printElapsedTime();
    System.exit(0);
  }
Exemplo n.º 17
0
  @Override
  public void run() {
    String eventsFile1 = "output/ITERS/it.10/10.events.xml.gz";
    String eventsFile2 = "outputBridgeClosed/ITERS/it.20/20.events.xml.gz";
    EventsManager before = EventsUtils.createEventsManager();
    EventsManager after = EventsUtils.createEventsManager();

    String network = "output/output_network.xml.gz";
    MutableScenario scenario =
        (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new MatsimNetworkReader(scenario).readFile(network);

    for (Entry<Id<Link>, ? extends Link> entry : scenario.getNetwork().getLinks().entrySet()) {
      linkDeltas.put(entry.getKey(), new AnalysisLink());
    }

    before.addHandler(new Before());
    after.addHandler(new After());

    new MatsimEventsReader(before).readFile(eventsFile1);
    new MatsimEventsReader(after).readFile(eventsFile2);

    initFeatureType();

    ArrayList<SimpleFeature> features = new ArrayList<SimpleFeature>();
    for (Entry<Id<Link>, ? extends Link> entry : scenario.getNetwork().getLinks().entrySet()) {
      features.add(getFeature(entry.getValue()));
    }

    ShapeFileWriter.writeGeometries(features, "output/delta-network");
  }
Exemplo n.º 18
0
  private static void getPersonsWithNegativeScores() {

    String plansFile = runPath + "output/output_plans.xml.gz";

    Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new MatsimPopulationReader(scenario).parse(plansFile);

    Set<Person> plansWithNegativeScores = new HashSet<Person>();

    for (Person person : scenario.getPopulation().getPersons().values()) {

      if (person.getSelectedPlan().getScore() < 0) {

        plansWithNegativeScores.add(person);
      }
    }
    BufferedWriter writer = IOUtils.getBufferedWriter(analysisPath + "negativeScores.txt");

    try {

      for (Person person : plansWithNegativeScores) {

        writer.write(person.getId().toString() + "\t" + person.getSelectedPlan().getScore());

        writer.newLine();
      }

      writer.flush();
      writer.close();

    } catch (IOException e) {

      e.printStackTrace();
    }
  }
Exemplo n.º 19
0
  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();
  }
Exemplo n.º 20
0
  private void testReinput(final boolean isReflective) {
    final SocialNetwork output = generateRandomSocialNetwork(isReflective);
    final String path = utils.getOutputDirectory() + "/sn.xml";

    new SocialNetworkWriter(output).write(path);

    final Scenario sc = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new SocialNetworkReader(sc).readFile(path);

    final SocialNetwork input = (SocialNetwork) sc.getScenarioElement(SocialNetwork.ELEMENT_NAME);

    Assert.assertEquals("unexpected reflectiveness", output.isReflective(), input.isReflective());

    Assert.assertEquals(
        "unexpected number of egos", output.getEgos().size(), input.getEgos().size());

    Assert.assertEquals("different ego ids", output.getEgos(), input.getEgos());

    final Counter c = new Counter("Test alters of ego # ");
    for (Id ego : output.getEgos()) {
      c.incCounter();
      final Set<Id<Person>> expectedAlters = output.getAlters(ego);
      final Set<Id<Person>> actualAlters = input.getAlters(ego);

      Assert.assertEquals(
          "unexpected number of alters for ego " + ego, expectedAlters.size(), actualAlters.size());

      Assert.assertEquals("unexpected alters for ego " + ego, expectedAlters, actualAlters);
    }

    Assert.assertEquals("different metadata", output.getMetadata(), input.getMetadata());

    c.printCounter();
  }
Exemplo n.º 21
0
  /** @param args */
  public static void main(String[] args) {
    String //
        // netFilename = "../matsim/test/scenarios/chessboard/network.xml", //
        // popFilename = "../matsim/test/scenarios/chessboard/plans.xml", //
        facilitiesFilename = "../matsim/test/scenarios/chessboard/facilities.xml", //
        facilitiesTxtFilename = "../matsimTests/locationChoice/chessboard/facilities.txt";

    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    // new MatsimNetworkReader(scenario).readFile(netFilename);
    new MatsimFacilitiesReader((ScenarioImpl) scenario).readFile(facilitiesFilename);

    SimpleWriter writer = new SimpleWriter(facilitiesTxtFilename);
    writer.writeln("Id\tx\ty\tacts\tcapacities");

    ActivityFacilities facilities = scenario.getActivityFacilities();
    for (ActivityFacility facility : facilities.getFacilities().values()) {
      Coord coord = facility.getCoord();
      writer.write(facility.getId() + "\t" + coord.getX() + "\t" + coord.getY() + "\t");

      Map<String, ? extends ActivityOption> activityOptions = facility.getActivityOptions();
      // acts
      writer.write(activityOptions.keySet());
      // capacities
      for (ActivityOption activityOption : activityOptions.values()) {
        writer.write("\t" + activityOption.getCapacity());
      }
      writer.writeln();
      writer.flush();
    }

    writer.close();
  }
Exemplo n.º 22
0
  public void convertTransitSchedule(String file) {

    Config config = ConfigUtils.createConfig();
    config.scenario().setUseTransit(true);
    config.scenario().setUseVehicles(true);
    Scenario scenario = ScenarioUtils.createScenario(config);

    TransitScheduleReader ts = new TransitScheduleReader(scenario);
    ts.readFile(file);

    PointFeatureFactory.Builder builder = new PointFeatureFactory.Builder();
    builder.setName("nodes");
    builder.addAttribute("id", String.class);
    PointFeatureFactory factory = builder.create();

    List<SimpleFeature> features = new ArrayList<SimpleFeature>();

    for (TransitStopFacility stop : scenario.getTransitSchedule().getFacilities().values()) {
      features.add(factory.createPoint(MGC.coord2Coordinate(stop.getCoord())));
    }

    ShapeFileWriter.writeGeometries(
        features,
        "C:/Users/Daniel/Documents/work/shared-svn/studies/countries/cl/Kai_und_Daniel/Visualisierungen/stops.shp");
  }
Exemplo n.º 23
0
  public MeanQueueLengthCalculator() throws Exception {
    scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new MatsimNetworkReader(scenario).readFile(networkFile);

    linkInfos = new HashMap<Id, LinkInfo>();

    counts = new HashMap<Id, AtomicInteger>();
    sumCountsPerHour = new HashMap<Id, AtomicInteger>();
    meanCounts = new HashMap<Id, double[]>();

    for (Link link : scenario.getNetwork().getLinks().values()) {
      linkInfos.put(link.getId(), new LinkInfo(link.getId()));

      counts.put(link.getId(), new AtomicInteger());
      sumCountsPerHour.put(link.getId(), new AtomicInteger());
      meanCounts.put(link.getId(), new double[hours]);
    }

    log.info("start reading events file...");
    EventsManager eventsManager = (EventsManager) EventsUtils.createEventsManager();
    eventsManager.addHandler(this);

    MatsimEventsReader eventsReader = new MatsimEventsReader(eventsManager);
    eventsReader.readFile(eventsFile);
    log.info("done.");

    for (LinkInfo linkInfo : linkInfos.values()) {
      getLinkStatistic(linkInfo);
    }

    log.info("start writing file...");
    writeFile();
    log.info("done.");
  }
Exemplo n.º 24
0
  public static void main(final String[] args) {
    Gbl.startMeasurement();

    final String netFilename = "../schweiz-ivtch-SVN/baseCase/network/ivtch-osm.xml";
    final String plansFilename = "../runs-svn/run684/it.1000/1000.plans.xml.gz";
    String outputFilename = "../matsimTests/run684/DailyEnRouteTime/";
    String tollFilename = "../matsimTests/toll/KantonZurichToll.xml";

    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new MatsimNetworkReader(scenario).readFile(netFilename);

    Population population = scenario.getPopulation();

    //        ConfigUtils.addOrGetModule(scenario.getConfig(), RoadPricingConfigGroup.GROUP_NAME,
    // RoadPricingConfigGroup.class).setUseRoadpricing(true);
    RoadPricingReaderXMLv1 tollReader =
        new RoadPricingReaderXMLv1(
            (RoadPricingSchemeImpl) scenario.getScenarioElement(RoadPricingScheme.ELEMENT_NAME));
    tollReader.parse(tollFilename);

    DailyEnRouteTime ert =
        new DailyEnRouteTime(
            (RoadPricingScheme) scenario.getScenarioElement(RoadPricingScheme.ELEMENT_NAME));

    System.out.println("-->reading plansfile: " + plansFilename);
    new MatsimPopulationReader(scenario).readFile(plansFilename);

    ert.run(population);
    ert.write(outputFilename);

    System.out.println("--> Done!");
    Gbl.printElapsedTime();
    System.exit(0);
  }
Exemplo n.º 25
0
  @Test
  public void testGetNearest() {

    Scenario s = ScenarioUtils.createScenario(ConfigUtils.createConfig());

    LinkQuadTree qt = new LinkQuadTree(0, 0, 2000, 2000);
    Link foo = createLink(s, 100, 200, 800, 500);
    Link bar = createLink(s, 400, 300, 500, 400);
    Link fbr = createLink(s, 800, 1400, 1400, 800);
    Link a = createLink(s, 1100, 1100, 1200, 1200);
    Link b = createLink(s, 1100, 1100, 1200, 1100);
    Link c = createLink(s, 1200, 1200, 1200, 1100);
    qt.put(foo);
    qt.put(bar);
    qt.put(fbr);
    qt.put(a);
    qt.put(b);
    qt.put(c);

    Assert.assertEquals(foo, qt.getNearest(200, 200));
    Assert.assertEquals(foo, qt.getNearest(300, 300));
    Assert.assertEquals(bar, qt.getNearest(390, 300));
    Assert.assertEquals(fbr, qt.getNearest(1000, 1100));
    Assert.assertEquals(foo, qt.getNearest(-50, -50));
    Assert.assertEquals(a, qt.getNearest(1105, 1104));
    Assert.assertEquals(a, qt.getNearest(1105, 1103));
    Assert.assertEquals(b, qt.getNearest(1105, 1102));
    Assert.assertEquals(b, qt.getNearest(1105, 1101));
    Assert.assertEquals(c, qt.getNearest(1205, 1101));
  }
Exemplo n.º 26
0
  public boolean loadNetFromOSM(final String path, final String crs) {
    // REVISAR UTM33N a UTM19N
    //        String UTM19N_PROJCS =
    // "PROJCS[\"WGS_1984_UTM_Zone_19N\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"latitude_of_origin\",0],PARAMETER[\"central_meridian\",-69],PARAMETER[\"scale_factor\",0.9996],PARAMETER[\"false_easting\",500000],PARAMETER[\"false_northing\",0],UNIT[\"Meter\",1]]";
    //	String crs = UTM19N_PROJCS; // the coordinate reference system to be used.

    this.crs = crs;
    String osm = path;

    Scenario sc = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Network net = sc.getNetwork();

    CoordinateTransformation ct =
        TransformationFactory.getCoordinateTransformation(TransformationFactory.WGS84, crs);

    OsmNetworkReader onr = new OsmNetworkReader(net, ct); // constructs a new openstreetmap reader
    try {
      onr.parse(osm); // starts the conversion from osm to matsim
    } catch (UncheckedIOException e) {
      e.printStackTrace();
      return false;
    }
    // at this point we already have a matsim network...
    new NetworkCleaner()
        .run(net); // but may be there are isolated (not connected) links. The network cleaner
    // removes those links
    board.setNetwork((NetworkImpl) net);
    board.repaint();
    return true;
  }
Exemplo n.º 27
0
  @Test
  public void testGetNearest_longNear_smallFarAway() {

    /*
     * Test the following constellation:
     *
     *                 (1)---(2)
     *    (3)---------------------------------(4)
     *
     *                     X
     *
     *
     *
     * nodes 1 and 2 are closer to X, but link 3-4 is actually closer
     *
     */

    Scenario s = ScenarioUtils.createScenario(ConfigUtils.createConfig());

    LinkQuadTree qt = new LinkQuadTree(0, 0, 2000, 2000);
    Link a = createLink(s, 500, 200, 700, 200);
    Link b = createLink(s, 100, 100, 900, 100);
    qt.put(a);
    qt.put(b);

    Assert.assertEquals(b, qt.getNearest(600, 0));
    Assert.assertEquals(a, qt.getNearest(600, 210));
    Assert.assertEquals(
        b, qt.getNearest(300, 210)); // outside of segment (1)-(2), thus (3)-(4) is closer
    Assert.assertEquals(a, qt.getNearest(400, 210)); // distance to (1) is smaller than to (3)-(4)
  }
Exemplo n.º 28
0
  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");
      }
    }
  }
Exemplo n.º 29
0
 public Population geographicallyFilterPopulation(
     final Population origPopulation, final ObjectAttributes personAttributes) {
   Population filteredPopulation = PopulationUtils.createPopulation(ConfigUtils.createConfig());
   Counter counter = new Counter(" person # ");
   boolean actInArea;
   for (Person p : origPopulation.getPersons().values()) {
     counter.incCounter();
     if (p.getSelectedPlan() != null) {
       actInArea = false;
       for (PlanElement pe : p.getSelectedPlan().getPlanElements()) {
         if (!actInArea && pe instanceof ActivityImpl) {
           ActivityImpl act = (ActivityImpl) pe;
           if (inArea(act.getCoord())) {
             actInArea = true;
           }
         }
       }
       if (actInArea) {
         filteredPopulation.addPerson(p);
         filteredAgents.put(p.getId(), p);
       } else {
         personAttributes.removeAllAttributes(p.toString());
       }
     }
   }
   return filteredPopulation;
 }
Exemplo n.º 30
0
  public static void main(String args[]) throws IOException {
    String netFile = args[0];
    String zoneFile = args[1];
    String zoneIdKey = args[2];
    int nThreads = Integer.parseInt(args[3]);
    String out = args[4];

    Config config = ConfigUtils.createConfig();
    Scenario scenario = ScenarioUtils.createScenario(config);

    logger.info("Loading network...");
    MatsimNetworkReader reader = new MatsimNetworkReader(scenario.getNetwork());
    reader.parse(netFile);

    logger.info("Loading zones...");
    ZoneCollection zones = ZoneGeoJsonIO.readFromGeoJSON(zoneFile, zoneIdKey);

    TTMatrixGenerator generator = new TTMatrixGenerator();
    NumericMatrix m = generator.generate(scenario.getNetwork(), zones, zoneIdKey, nThreads);

    logger.info("Writing zones...");
    NumericMatrixXMLWriter writer = new NumericMatrixXMLWriter();
    writer.write(m, out);
    logger.info("Done.");
  }