@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"));
  }
Example #2
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;
  }
  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();
  }
Example #4
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.");
  }
  private void createScenario() {
    this.initIds();
    Config config = ConfigUtils.createConfig();
    config.qsim().setUseLanes(true);
    ConfigUtils.addOrGetModule(
            config, SignalSystemsConfigGroup.GROUPNAME, SignalSystemsConfigGroup.class)
        .setUseSignalSystems(true);
    Scenario scenario = ScenarioUtils.loadScenario(config);

    // network
    Network net = this.createNetwork(scenario);
    this.writeMatsimNetwork(net, networkOutfile);
    log.info("network written to " + networkOutfile);
    // lanes
    createLanes((MutableScenario) scenario);
    LaneDefinitionsWriter20 laneWriter = new LaneDefinitionsWriter20(scenario.getLanes());
    laneWriter.write(lanesOutfile);
    log.info("lanes written to " + lanesOutfile);
    // signals
    SignalsData signalsData = (SignalsData) scenario.getScenarioElement(SignalsData.ELEMENT_NAME);
    createSignalSystemsAndGroups(signalsData);
    createSignalControl(signalsData);

    SignalsScenarioWriter signalsWriter = new SignalsScenarioWriter();
    signalsWriter.setSignalSystemsOutputFilename(signalSystemsOutfile);
    signalsWriter.setSignalGroupsOutputFilename(signalGroupsOutfile);
    signalsWriter.setSignalControlOutputFilename(signalControlOutfileBC);
    signalsWriter.writeSignalsData(signalsData);
  }
Example #6
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");
  }
  private OneWayCarsharingRDWithParkingStation findClosestAvailableOWCar(Id<Link> linkId) {

    // find the closest available car in the quad tree(?) reserve it (make it unavailable)
    // if no cars within certain radius return null
    Link link = scenario.getNetwork().getLinks().get(linkId);
    double distanceSearch =
        Double.parseDouble(
            scenario
                .getConfig()
                .getModule("OneWayCarsharing")
                .getParams()
                .get("searchDistanceOneWayCarsharing"));

    Collection<OneWayCarsharingRDWithParkingStation> location =
        this.carSharingVehicles
            .getOneWayVehicles()
            .getQuadTree()
            .getDisk(link.getCoord().getX(), link.getCoord().getY(), distanceSearch);
    if (location.isEmpty()) return null;

    OneWayCarsharingRDWithParkingStation closest = null;
    for (OneWayCarsharingRDWithParkingStation station : location) {
      if (CoordUtils.calcEuclideanDistance(link.getCoord(), station.getLink().getCoord())
              < distanceSearch
          && station.getNumberOfVehicles() > 0) {
        closest = station;
        distanceSearch =
            CoordUtils.calcEuclideanDistance(link.getCoord(), station.getLink().getCoord());
      }
    }
    // owvehiclesLocation.removeVehicle(closest.getLink());
    return closest;
  }
  @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"));
  }
 @Override
 public PlanStrategy createPlanStrategy(Scenario scenario, EventsManager eventsManager) {
   PlanStrategy strategy =
       new PlanStrategyImpl(
           new PathSizeLogitSelector(scenario.getConfig().planCalcScore(), scenario.getNetwork()));
   return strategy;
 }
Example #10
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();
    }
  }
  /** @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) throws Exception {
    Config config = ConfigUtils.loadConfig(configFile, new EmissionsConfigGroup());

    Scenario scenario = ScenarioUtils.loadScenario(config);

    // following is only for backward compatibility in which vehicle description is null;
    // for the new scenarios, setting vehicle description should be preferred.; Amit, sep 2016.
    EmissionsConfigGroup ecg =
        (EmissionsConfigGroup) scenario.getConfig().getModule(EmissionsConfigGroup.GROUP_NAME);
    ecg.setUsingVehicleTypeIdAsVehicleDescription(true);

    EmissionModule emissionModule = new EmissionModule(scenario);
    emissionModule.createLookupTables();
    emissionModule.createEmissionHandler();

    EventsManager eventsManager = EventsUtils.createEventsManager();
    eventsManager.addHandler(emissionModule.getWarmEmissionHandler());
    eventsManager.addHandler(emissionModule.getColdEmissionHandler());

    EventWriterXML emissionEventWriter = new EventWriterXML(emissionEventOutputFile);
    emissionModule.getEmissionEventsManager().addHandler(emissionEventWriter);

    MatsimEventsReader matsimEventsReader = new MatsimEventsReader(eventsManager);
    matsimEventsReader.readFile(eventsFile);

    emissionEventWriter.closeFile();

    emissionModule.writeEmissionInformation(emissionEventOutputFile);
  }
Example #13
0
  /**
   * Tests the setup with a traffic light that shows all the time green in the 0th iteration. After
   * the mobsim is run the signal settings are changed thus in the 1st iteration the signal should
   * be red in sec [0,99] and green in [100,2000]
   */
  @Test
  public void testModifySignalControlDataOnsetOffset() {
    // configure and load standard scenario
    Fixture fixture = new Fixture();
    Scenario scenario = fixture.createAndLoadTestScenario(false);
    scenario.getConfig().controler().setFirstIteration(0);
    scenario.getConfig().controler().setLastIteration(1);
    scenario.getConfig().controler().setOutputDirectory(testUtils.getOutputDirectory());

    Controler controler = new Controler(scenario);
    controler.getConfig().controler().setCreateGraphs(false);
    controler.addControlerListener(
        new AfterMobsimListener() {

          @Override
          public void notifyAfterMobsim(AfterMobsimEvent event) {
            Scenario scenario = event.getServices().getScenario();
            int dropping = 0;
            int onset = 100;
            for (SignalSystemControllerData intersectionSignal :
                ((SignalsData) scenario.getScenarioElement(SignalsData.ELEMENT_NAME))
                    .getSignalControlData()
                    .getSignalSystemControllerDataBySystemId()
                    .values()) {

              for (SignalPlanData plan : intersectionSignal.getSignalPlanData().values()) {
                plan.setCycleTime(2000);
                for (SignalGroupSettingsData data :
                    plan.getSignalGroupSettingsDataByGroupId().values()) {
                  data.setDropping(dropping);
                  data.setOnset(onset);
                }
              }
            }
          }
        });

    controler.addControlerListener(
        new IterationStartsListener() {

          @Override
          public void notifyIterationStarts(IterationStartsEvent event) {
            event.getServices().getEvents().addHandler(new EventsLogger());

            TestLink2EnterEventHandler enterHandler = new TestLink2EnterEventHandler();
            if (0 == event.getIteration()) {
              enterHandler.link2EnterTime = 38.0;
            }

            if (1 == event.getIteration()) {
              enterHandler.link2EnterTime = 100.0;
              SignalGroupStateChangedEventHandler signalsHandler0 =
                  new TestSignalGroupStateChangedHandler();
              event.getServices().getEvents().addHandler(signalsHandler0);
            }
          }
        });

    controler.run();
  }
Example #14
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();
  }
Example #15
0
  private void initWithinDayReplanning(Scenario scenario) {
    TravelDisutility travelDisutility =
        withinDayControlerListener
            .getTravelDisutilityFactory()
            .createTravelDisutility(
                withinDayControlerListener.getTravelTimeCollector(),
                scenario.getConfig().planCalcScore());
    RoutingContext routingContext =
        new RoutingContextImpl(
            travelDisutility, withinDayControlerListener.getTravelTimeCollector());

    LeaveLinkIdentifierFactory duringLegIdentifierFactory =
        new LeaveLinkIdentifierFactory(
            withinDayControlerListener.getLinkReplanningMap(),
            withinDayControlerListener.getMobsimDataProvider());

    StuckAgentsFilterFactory stuckAgentsFilterFactory =
        new StuckAgentsFilterFactory(withinDayControlerListener, scenario.getNetwork());
    duringLegIdentifierFactory.addAgentFilterFactory(stuckAgentsFilterFactory);

    CurrentLegMicroReplannerFactory duringLegReplannerFactory =
        new CurrentLegMicroReplannerFactory(
            scenario,
            withinDayControlerListener.getWithinDayEngine(),
            withinDayControlerListener.getWithinDayTripRouterFactory(),
            routingContext,
            this.controler);
    duringLegReplannerFactory.addIdentifier(duringLegIdentifierFactory.createIdentifier());

    withinDayControlerListener
        .getWithinDayEngine()
        .addDuringLegReplannerFactory(duringLegReplannerFactory);
  }
  public void parse(String inputfolder) {
    /* Check that the given folder ends with a '/'. */
    inputfolder = inputfolder + (inputfolder.endsWith("/") ? "" : "/");

    /* Read population. */
    LOG.info("Reading population...");
    PopulationReaderMatsimV5 pr = new PopulationReaderMatsimV5(this.sc);
    pr.parse(inputfolder + "population.xml.gz");

    /* Read population attributes. */
    LOG.info("Reading person attributes...");
    ObjectAttributesXmlReader oar1 =
        new ObjectAttributesXmlReader(this.sc.getPopulation().getPersonAttributes());
    oar1.putAttributeConverter(IncomeImpl.class, new SAIncomeConverter());
    oar1.parse(inputfolder + "populationAttributes.xml.gz");

    /* Read households */
    LOG.info("Reading households...");
    HouseholdsReaderV10 hhr = new HouseholdsReaderV10(this.sc.getHouseholds());
    hhr.parse(inputfolder + "households.xml.gz");

    /* Read household attributes. */
    LOG.info("Reading household attributes...");
    ObjectAttributesXmlReader oar2 =
        new ObjectAttributesXmlReader(this.sc.getHouseholds().getHouseholdAttributes());
    oar2.putAttributeConverter(IncomeImpl.class, new SAIncomeConverter());
    oar2.putAttributeConverter(CoordImpl.class, new CoordConverter());
    oar2.parse(inputfolder + "householdAttributes.xml.gz");

    LOG.info("================================================================");
    LOG.info("Population size: " + sc.getPopulation().getPersons().size());
    LOG.info("Number of households: " + sc.getHouseholds().getHouseholds().size());
    LOG.info("================================================================");
  }
 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");
 }
 public DCScoringFunctionFactory(
     Scenario scenario, DestinationChoiceBestResponseContext lcContext) {
   super(scenario.getConfig().planCalcScore(), scenario.getNetwork());
   this.scenario = scenario;
   this.lcContext = lcContext;
   log.info("creating DCScoringFunctionFactory");
 }
  @Override
  public ScoringFunction createNewScoringFunction(Person person) {
    SumScoringFunction scoringFunctionAccumulator = new SumScoringFunction();

    SumScoringFunction.BasicScoring scoringFunction;
    if (usingConfigParamsForScoring) {
      scoringFunction = new DCActivityWOFacilitiesScoringFunction(person, this.lcContext);
      scoringFunctionAccumulator.addScoringFunction(
          new CharyparNagelActivityScoring(this.lcContext.getParams()));
      // forgetting the previous line (which we did at some point) is not picked up by any test
      // within the locationchoice contrib. kai, oct'14
    } else {
      scoringFunction = new DCActivityScoringFunction(person.getSelectedPlan(), this.lcContext);
    }
    scoringFunctionAccumulator.addScoringFunction(scoringFunction);
    scoringFunctionAccumulator.addScoringFunction(
        new CharyparNagelLegScoring(
            CharyparNagelScoringParameters.getBuilder(scenario.getConfig().planCalcScore())
                .create(),
            scenario.getNetwork()));
    scoringFunctionAccumulator.addScoringFunction(
        new CharyparNagelAgentStuckScoring(
            CharyparNagelScoringParameters.getBuilder(scenario.getConfig().planCalcScore())
                .create()));
    return scoringFunctionAccumulator;
  }
Example #20
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"));
  }
Example #21
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"
        });
  }
Example #22
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);
  }
Example #23
0
  /** @param args */
  public static void main(String[] args) {
    Header.printHeader(SurveyParser.class.toString(), args);

    SurveyParser sp = new SurveyParser(args[0], Integer.parseInt(args[1]));
    sp.parsePersons(args[2]);
    sp.parseHouseholds(args[3]);
    sp.parseDerivedHouseholdAssets(args[4]);
    sp.parseDiaryTrips(args[5]);

    sp.writePopulation(args[6], sp.getScenario());

    Scenario surveySc = sp.filterScenarioToSurveyRespondents();
    sp.cleanUpScenario(surveySc);
    sp.writePopulation(args[7], surveySc);

    /* Finish off with some basic population statistics. */
    LOG.info("---------------------------------------");
    LOG.info(" Number of households: " + surveySc.getHouseholds().getHouseholds().size());
    LOG.info("    Number of persons: " + surveySc.getPopulation().getPersons().size());
    LOG.info("---------------------------------------");
    PopulationUtils.printActivityStatistics(
        args[7] + (args[7].endsWith("/") ? "" : "/") + "population.xml.gz");

    /* Some arbitrary checks. Remove once done. */
    LOG.info("              Number of observed zones: " + sp.zoneMap.size());
    LOG.info("  Number of unknown activity locations: " + numberOfUnknownActivityLocations);
    LOG.info("Number of (fixable) activity locations: " + numberOfFixableActivityLocations);

    Header.printFooter();
  }
 public EventsToTravelDiaries(Scenario scenario) {
   this.network = scenario.getNetwork();
   isTransitScenario = scenario.getConfig().transit().isUseTransit();
   if (isTransitScenario) {
     this.transitSchedule = scenario.getTransitSchedule();
     this.walkSpeed = new TransitRouterConfig(scenario.getConfig()).getBeelineWalkSpeed();
   }
 }
Example #25
0
  public static void main(String[] args) {

    // Dummy MATSim scenario including dummy network
    Config conf = ConfigUtils.createConfig();
    conf.global().setCoordinateSystem("EPSG:3395");
    Scenario sc = ScenarioUtils.createScenario(conf);
    //		Sim2DConfig conf2d = Sim2DConfigUtils.createConfig();
    //		Sim2DScenario sc2d = Sim2DScenarioUtils.createSim2dScenario(conf2d);
    //		sc.addScenarioElement(Sim2DScenario.ELEMENT_NAME,sc2d);
    Network net = sc.getNetwork();
    NetworkFactory fac = net.getFactory();
    Node n0 = fac.createNode(Id.create("0", Node.class), new Coord(minX, minY));
    Node n1 = fac.createNode(Id.create("1", Node.class), new Coord(minX, maxY));
    Node n2 = fac.createNode(Id.create("2", Node.class), new Coord(maxX, maxY));
    Node n3 = fac.createNode(Id.create("3", Node.class), new Coord(maxX, minY));
    net.addNode(n0);
    net.addNode(n1);
    net.addNode(n2);
    net.addNode(n3);

    // visualization stuff
    EventsManager em = new EventsManagerImpl();
    EventBasedVisDebuggerEngine vis = new EventBasedVisDebuggerEngine(sc);
    em.addHandler(vis);

    // routing algorithm - for now standard Dijkstra could be replaced by A*  in future
    Dijkstra d = new Dijkstra(env);

    // dummy data
    int number = 20;
    for (double time = 0; time <= 1000; time++) {
      List<XYVxVyEventImpl> events = createDummyData(MatsimRandom.getRandom().nextInt(21), time);

      List<TwoDObject> objs = new ArrayList<TwoDObject>();
      for (XYVxVyEventImpl e : events) {
        em.processEvent(e); // needed for visualization
        objs.add(e);
      }

      System.out.println("");
      LinearQuadTreeLD quad = new LinearQuadTreeLD(objs, env, em);

      // routing
      List<Quad> fromL = quad.query(new Envelope(0, 0.1, 0, 0.1));
      Quad from = fromL.get(0);
      List<Quad> toL = quad.query(new Envelope(19.9, 20, 19.9, 20));
      Quad to = toL.get(0);
      LinkedList<Quad> path = d.computeShortestPath(quad, from, to);
      path.addFirst(from);
      draw(path, em);
      //			to.getEnvelope().get
      try {
        Thread.sleep(2000); // to slow it down a bit
      } catch (InterruptedException e1) {
        e1.printStackTrace();
      }
    }
  }
Example #26
0
  /** @param args */
  public static void main(String[] args) {

    Config config = ConfigUtils.createConfig();

    config.controler().setLastIteration(0);
    config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists);
    Collection<String> sf = new ArrayList<>();
    sf.add("otfvis");
    config.controler().setSnapshotFormat(sf);
    config.controler().setWriteSnapshotsInterval(1);

    config.qsim().setStartTime(0);
    config.qsim().setSimStarttimeInterpretation(StarttimeInterpretation.onlyUseStarttime);
    config.qsim().setEndTime(10. * 3600.);
    config.qsim().setSimEndtimeInterpretation(EndtimeInterpretation.onlyUseEndtime);

    config.qsim().setNumberOfThreads(1);

    config.qsim().setSnapshotPeriod(1);

    OTFVisConfigGroup otfconf =
        ConfigUtils.addOrGetModule(config, OTFVisConfigGroup.GROUP_NAME, OTFVisConfigGroup.class);
    otfconf.setColoringScheme(ColoringScheme.byId);

    Scenario scenario = ScenarioUtils.createScenario(config);

    Network net = scenario.getNetwork();
    NetworkFactory nf = net.getFactory();
    Node node1 = nf.createNode(Id.createNodeId(1), new Coord(0., 0.));
    net.addNode(node1);
    Node node2 = nf.createNode(Id.createNodeId(2), new Coord(LEN * 7.5, 0.));
    net.addNode(node2);
    Node node3 = nf.createNode(Id.createNodeId(3), new Coord(0., -LEN * 7.5));
    net.addNode(node3);
    Node node4 = nf.createNode(Id.createNodeId(4), new Coord(0., LEN * 7.5));
    net.addNode(node4);
    Link link = nf.createLink(Id.createLinkId("1-2"), node1, node2);
    link.setLength(LEN * 7.5);
    net.addLink(link);
    //		Link link2 = nf.createLink(Id.createLinkId("1-3"), node1, node3) ;
    //		link.setLength( LEN*7.5 );
    //		net.addLink( link2 ) ;

    Controler controler = new Controler(scenario);

    controler.addOverridingModule(
        new AbstractModule() {
          @Override
          public void install() {
            bind(QNetworkFactory.class).to(MyQNetworkFactory.class);
          }
        });

    controler.addOverridingModule(new OTFVisLiveModule());
    controler.addOverridingModule(new OTFVisFileWriterModule());

    controler.run();
  }
  public static void main(String[] args) {
    String path = "./ihop2/matsim-input/config.xml";
    Config config = ConfigUtils.loadConfig(path);
    final Scenario scenario = ScenarioUtils.loadScenario(config);
    Controler controler = new Controler(scenario);
    double samplesize = config.qsim().getStorageCapFactor();
    String outputRoot = "./ihop2/matsim-output/output";
    //		LogToOutputSaver.setOutputDirectory(outputRoot);

    double departureTime = 8. * 60 * 60;

    // Changing vehicle and road capacity according to sample size
    PTCapacityAdjusmentPerSample capadjuster = new PTCapacityAdjusmentPerSample();
    capadjuster.adjustStoarageAndFlowCapacity(scenario, samplesize);

    //		controler.getConfig().qsim().setInflowConstraint(InflowConstraint.maxflowFromFdiag);
    //		controler.getConfig().qsim().setTrafficDynamics(TrafficDynamics.withHoles);

    Network network = scenario.getNetwork();
    TransitSchedule schedule = scenario.getTransitSchedule();
    new CreatePseudoNetwork(schedule, network, "tr_").createNetwork();
    //		NetworkWriter networkWriter =  new NetworkWriter(network);
    //		networkWriter.write("/home/saleem/input/PseudoNetwork.xml");
    //		networkWriter.write("H:\\Matsim\\Stockholm
    // Scenario\\teleportation\\input\\PseudoNetwork.xml");
    //		controler.addControlerListener(new FareControlListener());
    //		controler.setScoringFunctionFactory(new ScoringFunctionFactory() {
    //			@Inject CharyparNagelScoringParametersForPerson parameters;
    //			@Override
    //			public ScoringFunction createNewScoringFunction(Person person) {
    //				final CharyparNagelScoringParameters params = parameters.getScoringParameters( person );
    //				SumScoringFunction sumScoringFunction = new SumScoringFunction();
    //				sumScoringFunction.addScoringFunction(new CharyparNagelActivityScoring( params ));
    //				sumScoringFunction.addScoringFunction(new StockholmLegScoring( person, params ,
    // scenario.getNetwork()));
    //				sumScoringFunction.addScoringFunction(new StockholmMoneyScoring(person, params ));
    //				sumScoringFunction.addScoringFunction(new CharyparNagelAgentStuckScoring( params ));
    //				return sumScoringFunction;			}
    //		});
    //		controler.addControlerListener(new FareControlListener());
    controler.run();

    TransitRouter trouter =
        controler.getInjector().getBinding(TransitRouter.class).getProvider().get();
    createStopsFile(scenario.getTransitSchedule().getFacilities(), outputRoot + "ptStops.csv", ",");
    //
    //		// The locationFacilitiesMap is passed twice: Once for origins and once for destinations.
    //		// In other uses the two maps may be different -- thus the duplication here.
    new ThreadedMatrixCreator(
        scenario,
        scenario.getTransitSchedule().getFacilities(),
        scenario.getTransitSchedule().getFacilities(),
        departureTime,
        outputRoot,
        " ",
        1,
        trouter);
  }
 private Link createLink(Scenario s, double fromX, double fromY, double toX, double toY) {
   NetworkFactory nf = s.getNetwork().getFactory();
   Coord fc = s.createCoord(fromX, fromY);
   Coord tc = s.createCoord(toX, toY);
   return nf.createLink(
       Id.create(fc.toString() + "-" + tc.toString(), Link.class),
       nf.createNode(Id.create(fc.toString(), Node.class), fc),
       nf.createNode(Id.create(tc.toString(), Node.class), tc));
 }
 @Inject
 public Cache(final Scenario scenario) {
   this(
       scenario.getNetwork(),
       ConfigUtils.addOrGetModule(
           scenario.getConfig(),
           LazyScheduleBasedMatrixConfigGroup.GROUP_NAME,
           LazyScheduleBasedMatrixConfigGroup.class));
 }
  // Create external Facilities that are used by transit traffic agents.
  private static void createExternalFacilities(Scenario scenario, Set<Id<Node>> externalNodes) {

    ActivityFacilities activityFacilities = scenario.getActivityFacilities();
    ActivityFacilitiesFactory factory = activityFacilities.getFactory();

    /*
     * We check for all OutLinks of all external nodes if they already host a facility. If not,
     * a new facility with a tta ActivityOption will be created and added.
     */
    for (Id<Node> id : externalNodes) {
      Node externalNode = scenario.getNetwork().getNodes().get(id);

      for (Link externalLink : externalNode.getOutLinks().values()) {
        ActivityFacility facility = activityFacilities.getFacilities().get(externalLink.getId());

        // if already a facility exists we have nothing left to do
        if (facility != null) continue;

        /*
         * No Facility exists at that link therefore we create and add a new one.
         */
        double fromX = externalLink.getFromNode().getCoord().getX();
        double fromY = externalLink.getFromNode().getCoord().getY();
        double toX = externalLink.getToNode().getCoord().getX();
        double toY = externalLink.getToNode().getCoord().getY();

        double dX = toX - fromX;
        double dY = toY - fromY;

        double length = Math.sqrt(Math.pow(dX, 2) + Math.pow(dY, 2));

        double centerX = externalLink.getCoord().getX();
        double centerY = externalLink.getCoord().getY();

        /*
         * Unit vector that directs with an angle of 90° away from the link.
         */
        double unitVectorX = dY / length;
        double unitVectorY = -dX / length;

        Coord coord = new Coord(centerX + unitVectorX, centerY + unitVectorY);

        facility =
            activityFacilities
                .getFactory()
                .createActivityFacility(
                    Id.create(externalLink.getId().toString(), ActivityFacility.class), coord);
        activityFacilities.addActivityFacility(facility);
        ((ActivityFacilityImpl) facility).setLinkId(externalLink.getId());

        ActivityOption activityOption = factory.createActivityOption(ttaActivityType);
        activityOption.addOpeningTime(new OpeningTimeImpl(0 * 3600, 24 * 3600));
        activityOption.setCapacity(capacity);
        facility.addActivityOption(activityOption);
      }
    }
  }