Пример #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"));
  }
  private void createDemand() {

    Population pop = sc.getPopulation();
    PopulationFactory fact = pop.getFactory();

    for (int i = 1; i <= 400; i++) {

      Person p = fact.createPerson(Id.createPersonId(i));
      Plan plan = fact.createPlan();
      p.addPlan(plan);
      Leg leg = fact.createLeg(TransportMode.car);
      Activity home;
      Activity work;

      if (i % 2 == 0) { // o --d1
        home = fact.createActivityFromCoord("o1", lo.getCoord());
        home.setEndTime(7 * 3600 + i);
        work = fact.createActivityFromCoord("d1", ld1.getCoord());
      } else /*if(i%2==0)*/ { // o --d2
        home = fact.createActivityFromCoord("o1", lo.getCoord());
        home.setEndTime(7 * 3600 + i);
        work = fact.createActivityFromCoord("d2", ld2.getCoord());
      }
      plan.addActivity(home);
      plan.addLeg(leg);
      plan.addActivity(work);
      pop.addPerson(p);
    }
    new PopulationWriter(pop).write(outputDir + "/input/input_plans.xml.gz");
  }
Пример #3
0
 @Override
 public void notifyIterationStarts(IterationStartsEvent event) {
   Population pop = event.getControler().getScenario().getPopulation();
   for (Person p : pop.getPersons().values()) {
     PersonUtils.setAge(p, 100);
   }
 }
Пример #4
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;
 }
Пример #5
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"));
  }
Пример #6
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"));
  }
 @Override
 public void startPlans(final Population plans, final BufferedWriter out) throws IOException {
   out.write("<population");
   if (plans.getName() != null) {
     out.write(" desc=\"" + plans.getName() + "\"");
   }
   out.write(">\n\n");
 }
Пример #8
0
 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;
 }
Пример #9
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);
  }
Пример #10
0
  public void testRouteLinkFilter() {
    loadConfig(null); // used to set the default dtd-location
    Population population = getTestPopulation();

    TestAlgorithm tester = new TestAlgorithm();

    RouteLinkFilter linkFilter = new RouteLinkFilter(tester);
    linkFilter.addLink(Id.create(15, Link.class));

    SelectedPlanFilter selectedPlanFilter = new SelectedPlanFilter(linkFilter);
    selectedPlanFilter.run(population);
    assertEquals(3, population.getPersons().size());
    assertEquals(2, linkFilter.getCount());
  }
Пример #11
0
  private Population getTestPopulation() {
    Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Network network = scenario.getNetwork();
    new MatsimNetworkReader(scenario.getNetwork()).readFile("test/scenarios/equil/network.xml");

    Link link1 = network.getLinks().get(Id.create(1, Link.class));
    Link link20 = network.getLinks().get(Id.create(20, Link.class));

    Population population = scenario.getPopulation();

    Person person;
    PlanImpl plan;
    LegImpl leg;
    NetworkRoute route;

    person = PopulationUtils.createPerson(Id.create("1", Person.class));
    plan = PersonUtils.createAndAddPlan(person, true);
    ActivityImpl a = plan.createAndAddActivity("h", link1.getId());
    a.setEndTime(7.0 * 3600);
    leg = plan.createAndAddLeg(TransportMode.car);
    route = new LinkNetworkRouteImpl(link1.getId(), link20.getId());
    route.setLinkIds(link1.getId(), NetworkUtils.getLinkIds("6 15"), link20.getId());
    leg.setRoute(route);
    plan.createAndAddActivity("w", link20.getId());
    population.addPerson(person);

    person = PopulationUtils.createPerson(Id.create("2", Person.class));
    plan = PersonUtils.createAndAddPlan(person, true);
    ActivityImpl a2 = plan.createAndAddActivity("h", link1.getId());
    a2.setEndTime(7.0 * 3600 + 5.0 * 60);
    leg = plan.createAndAddLeg(TransportMode.car);
    route = new LinkNetworkRouteImpl(link1.getId(), link20.getId());
    route.setLinkIds(link1.getId(), NetworkUtils.getLinkIds("6 15"), link20.getId());
    leg.setRoute(route);
    plan.createAndAddActivity("w", link20.getId());
    population.addPerson(person);

    person = PopulationUtils.createPerson(Id.create("3", Person.class));
    plan = PersonUtils.createAndAddPlan(person, true);
    ActivityImpl a3 = plan.createAndAddActivity("h", link1.getId());
    a3.setEndTime(7.0 * 3600 + 10.0 * 60);
    leg = plan.createAndAddLeg(TransportMode.car);
    route = new LinkNetworkRouteImpl(link1.getId(), link20.getId());
    route.setLinkIds(link1.getId(), NetworkUtils.getLinkIds("5 14"), link20.getId());
    leg.setRoute(route);
    plan.createAndAddActivity("w", link20.getId());
    population.addPerson(person);

    return population;
  }
Пример #12
0
  @Override
  public Collection<ReplanningGroup> identifyGroups(final Population population) {
    final List<ReplanningGroup> groups = new ArrayList<ReplanningGroup>();
    final Map<Id, Person> persons = new LinkedHashMap<Id, Person>(population.getPersons());

    int countGroups = 0;
    int countPersonsExplicit = 0;
    for (Collection<Id<Person>> groupIds : groupsInfo) {
      final ReplanningGroup g = new ReplanningGroup();
      countGroups++;

      for (Id<Person> id : groupIds) {
        countPersonsExplicit++;
        final Person p = persons.remove(id);
        if (p == null) {
          if (population.getPersons().containsKey(id)) {
            throw new RuntimeException(
                "person with id " + id + " was found pertaining to several groups");
          }
          throw new RuntimeException(
              "no person with id "
                  + id
                  + " in population "
                  + population
                  + " of size "
                  + population.getPersons().size());
        }
        g.addPerson(p);
      }

      groups.add(g);
    }
    log.info(countPersonsExplicit + " were allocated to " + countGroups + " groups.");

    // persons not allocated to any group are "grouped" alone
    int countPersonsImplicit = 0;
    for (Person p : persons.values()) {
      final ReplanningGroup g = new ReplanningGroup();
      g.addPerson(p);
      groups.add(g);
      countPersonsImplicit++;
    }
    log.info(
        countPersonsImplicit
            + " were not explicitly allocated to any group, and were put in one-person groups");

    return groups;
  }
Пример #13
0
  public void plans2Shape(Population population, String outputFile) {

    SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
    typeBuilder.setName("shape");
    typeBuilder.add("geometry", Point.class);
    typeBuilder.add("id", String.class);
    typeBuilder.add("actType", String.class);
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(typeBuilder.buildFeatureType());

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

    for (Person person : population.getPersons().values()) {

      for (PlanElement pe : person.getSelectedPlan().getPlanElements()) {

        if (pe instanceof Activity) {

          Activity act = (Activity) pe;
          Coord coord = act.getCoord();

          SimpleFeature feature =
              builder.buildFeature(
                  null,
                  new Object[] {
                    new GeometryFactory().createPoint(new Coordinate(coord.getX(), coord.getY())),
                    person.getId().toString(),
                    act.getType()
                  });
          features.add(feature);
        }
      }
    }

    ShapeFileWriter.writeGeometries(features, outputFile);
  }
Пример #14
0
 @Override
 public void handleEvent(PersonStuckEvent event) {
   Double startWaitingTime = agentsWaitingData.get(event.getPersonId());
   if (startWaitingTime != null) {
     int legs = 0, currentLeg = agentsCurrentLeg.get(event.getPersonId());
     PLAN_ELEMENTS:
     for (PlanElement planElement :
         population.getPersons().get(event.getPersonId()).getSelectedPlan().getPlanElements())
       if (planElement instanceof Leg) {
         if (currentLeg == legs) {
           String[] leg = (((Leg) planElement).getRoute()).getRouteDescription().split(SEPARATOR);
           WaitTimeData data =
               waitTimes
                   .get(
                       new Tuple<Id<TransitLine>, Id<TransitRoute>>(
                           Id.create(leg[2], TransitLine.class),
                           Id.create(leg[3], TransitRoute.class)))
                   .get(Id.create(leg[1], TransitStopFacility.class));
           if (data != null)
             data.addWaitTime(
                 (int) (startWaitingTime / timeSlot), event.getTime() - startWaitingTime);
           agentsWaitingData.remove(event.getPersonId());
           break PLAN_ELEMENTS;
         } else legs++;
       }
   }
 }
Пример #15
0
 private static void dropDepTimes(Population population) {
   for (Person pers : population.getPersons().values()) {
     for (Plan p : pers.getPlans()) {
       ((Activity) p.getPlanElements().get(0)).setEndTime(0);
     }
   }
 }
  // based on:
  // playground.wrashid.parkingSearch.withindayFW.controllers.kti.HUPCControllerKTIzh.getHouseHoldIncomeCantonZH
  public static DoubleValueHashMap<Id> getHouseHoldIncomeCantonZH(Population population) {
    DoubleValueHashMap<Id> houseHoldIncome = new DoubleValueHashMap<Id>();

    for (Id<Person> personId : population.getPersons().keySet()) {
      double rand = MatsimRandom.getRandom().nextDouble();
      if (rand < 0.032) {
        houseHoldIncome.put(personId, 1000 + MatsimRandom.getRandom().nextDouble() * 1000);
      } else if (rand < 0.206) {
        houseHoldIncome.put(personId, 2000 + MatsimRandom.getRandom().nextDouble() * 2000);
      } else if (rand < 0.471) {
        houseHoldIncome.put(personId, 4000 + MatsimRandom.getRandom().nextDouble() * 2000);
      } else if (rand < 0.674) {
        houseHoldIncome.put(personId, 6000 + MatsimRandom.getRandom().nextDouble() * 2000);
      } else if (rand < 0.803) {
        houseHoldIncome.put(personId, 8000 + MatsimRandom.getRandom().nextDouble() * 2000);
      } else if (rand < 0.885) {
        houseHoldIncome.put(personId, 10000 + MatsimRandom.getRandom().nextDouble() * 2000);
      } else if (rand < 0.927) {
        houseHoldIncome.put(personId, 12000 + MatsimRandom.getRandom().nextDouble() * 2000);
      } else if (rand < 0.952) {
        houseHoldIncome.put(personId, 14000 + MatsimRandom.getRandom().nextDouble() * 2000);
      } else {
        houseHoldIncome.put(personId, 16000 + MatsimRandom.getRandom().nextDouble() * 16000);
      }
    }

    return houseHoldIncome;
  }
Пример #17
0
  public void filterMode(final String fromFile, final String toFile, final String mode) {

    Population pop =
        ((MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig()))
            .getPopulation();

    log.info("reading plans from file: " + fromFile);
    new MatsimPopulationReader(new PseudoScenario(this.scenario, pop)).readFile(fromFile);

    log.info("filter plans with " + mode + "-legs");
    new PlansFilterByLegMode(mode, FilterType.keepAllPlansWithMode).run(pop);
    log.info("# persons remaining: " + pop.getPersons().size());

    log.info("writing plans to file: " + toFile);
    new PopulationWriter(pop, this.scenario.getNetwork()).write(toFile);
  }
Пример #18
0
 private void reviewActivities(String noHomeFileLocation, Population population)
     throws FileNotFoundException {
   PrintWriter writer = new PrintWriter(noHomeFileLocation);
   int noHome = 0;
   for (Entry<Id<Person>, List<String>> activityChain : activityChains.entrySet()) {
     if (!activityChain.getKey().toString().contains("pt_")) {
       String lastActivity = activityChain.getValue().get(activityChain.getValue().size() - 1);
       if (!lastActivity.contains("home")) {
         Id<Person> personId = activityChain.getKey();
         String plan = personId + ": ";
         for (PlanElement planElement :
             population.getPersons().get(personId).getSelectedPlan().getPlanElements())
           plan +=
               (planElement instanceof Activity
                       ? ((Activity) planElement).getType()
                       : ((Leg) planElement).getMode()
                           + (((Leg) planElement).getMode().equals("pt")
                               ? "(" + (((Leg) planElement).getRoute()).getRouteDescription() + ")"
                               : ""))
                   + "   ";
         writer.println(plan);
         String chain = activityChain.getKey() + ": ";
         for (String activity : activityChain.getValue()) chain += activity + "   ";
         writer.println(chain);
         noHome++;
       }
     }
   }
   writer.close();
   System.out.println("No home: " + noHome);
 }
Пример #19
0
  /**
   * @param args
   * @throws IOException
   * @throws FileNotFoundException
   */
  public static void main(String[] args) throws FileNotFoundException, IOException {
    Config config = Gbl.createConfig(new String[] {args[0]});
    ScenarioLoaderImpl loader = new ScenarioLoaderImpl(config);
    loader.loadScenario();
    ScenarioImpl data = loader.getScenario();
    Population population = data.getPopulation();

    Collection<Person> persons2 = new HashSet<Person>();
    double xmin = 678000;
    double ymin = 243000;
    double xmax = 687000;
    double ymax = 254000;
    for (Person p : population.getPersons().values()) {
      Coord c = ((PlanImpl) p.getSelectedPlan()).getFirstActivity().getCoord();
      if ((c.getX() >= xmin) && (c.getX() <= xmax) && (c.getY() >= ymin) && (c.getY() <= ymax))
        persons2.add(p);
    }

    TDoubleDoubleHashMap hist = new TDoubleDoubleHashMap();
    double binsize = 1000;
    int count = 0;
    for (Person p1 : population.getPersons().values()) {
      persons2.remove(p1);
      for (Person p2 : persons2) {
        Coord c1 = ((PlanImpl) p1.getSelectedPlan()).getFirstActivity().getCoord();
        Coord c2 = ((PlanImpl) p2.getSelectedPlan()).getFirstActivity().getCoord();
        double d = CoordUtils.calcDistance(c1, c2);
        double bin = Math.floor(d / binsize);
        double val = hist.get(bin);
        val++;
        hist.put(bin, val);
      }
      count++;
      if (count % 1000 == 0) {
        System.out.println(
            String.format(
                "Processed %1$s of %2$s persons. (%3$s )",
                count,
                population.getPersons().size(),
                count / (double) population.getPersons().size()));
      }
    }

    Distribution.writeHistogram(hist, args[1]);
  }
  /**
   * Handles each person of the given <code>population</code> with a AbstractPersonAlgorithm
   * provided by <code>algoProvider</code>, using up to <code>numberOfThreads</code> threads to
   * speed things up. This method will request a new instance of the AbstractPersonAlgorithm for
   * each thread it allocates, thus enabling the parallel use of non-thread-safe algorithms. For
   * thread-safe algorithms, {@link #run(Population, int, AbstractPersonAlgorithm)} may be an easier
   * method to use.
   *
   * @param population
   * @param numberOfThreads
   * @param algoProvider
   */
  public static void run(
      final Population population,
      final int numberOfThreads,
      final PersonAlgorithmProvider algoProvider) {
    int numOfThreads =
        Math.max(
            numberOfThreads,
            1); // it should be at least 1 here; we allow 0 in other places for "no threads"
    PersonAlgoThread[] algoThreads = new PersonAlgoThread[numOfThreads];
    Thread[] threads = new Thread[numOfThreads];
    String name = null;
    Counter counter = null;

    final AtomicBoolean hadException = new AtomicBoolean(false);
    final ExceptionHandler uncaughtExceptionHandler = new ExceptionHandler(hadException);

    // setup threads
    for (int i = 0; i < numOfThreads; i++) {
      PersonAlgorithm algo = algoProvider.getPersonAlgorithm();
      if (i == 0) {
        name = algo.getClass().getSimpleName();
        counter = new Counter("[" + name + "] handled person # ");
      }
      PersonAlgoThread algothread = new PersonAlgoThread(algo, counter);
      Thread thread = new Thread(algothread, name + "." + i);
      thread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
      threads[i] = thread;
      algoThreads[i] = algothread;
    }

    // distribute workload between threads, as long as threads are not yet started, so we don't need
    // synchronized data structures
    int i = 0;
    for (Person person : population.getPersons().values()) {
      algoThreads[i % numOfThreads].handlePerson(person);
      i++;
    }

    // start the threads
    for (Thread thread : threads) {
      thread.start();
    }

    // wait for the threads to finish
    try {
      for (Thread thread : threads) {
        thread.join();
      }
      counter.printCounter();
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
    if (hadException.get()) {
      throw new RuntimeException(
          "Exception while processing persons. Cannot guarantee that all persons have been fully processed.");
    }
  }
Пример #21
0
  /** @param args */
  public static void main(String[] args) {
    MutableScenario scenario =
        (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Network net = scenario.getNetwork();
    MatsimIo.loadNetwork(DgPaths.IVTCHNET, scenario);
    Population plansCmcf = MatsimIo.loadPlans(cmcfPlansFile, net);
    Population plans = MatsimIo.loadPlans(plansFile, net);
    for (Person p : plans.getPersons().values()) {
      Plan pl = p.getSelectedPlan();
      Leg l = ((PlanImpl) pl).getNextLeg(((PlanImpl) pl).getFirstActivity());
      Plan plcmcf = plansCmcf.getPersons().get(p.getId()).getSelectedPlan();
      Leg lcmcf = ((PlanImpl) plcmcf).getNextLeg(((PlanImpl) plcmcf).getFirstActivity());
      l.setRoute(lcmcf.getRoute());
    }
    MatsimIo.writePlans(plans, net, outPlansFile);

    log.info("done");
  }
Пример #22
0
  public static Set<Coord> getCoords(Population population) {
    Set<Coord> coords = new HashSet<Coord>();

    for (Person person : population.getPersons().values()) {
      Plan plan = person.getPlans().get(0);
      Activity act = (Activity) plan.getPlanElements().get(0);
      Coord c = act.getCoord();
      coords.add(c);
    }

    return coords;
  }
Пример #23
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);
  }
Пример #24
0
  @Test
  public void testPopulationAttributesIO() {
    final Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig());

    population.getAttributes().putAttribute("type", "candidates");
    population.getAttributes().putAttribute("number", 2);

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

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

    Assert.assertEquals(
        "Unexpected numeric attribute in " + readScenario.getPopulation().getAttributes(),
        population.getAttributes().getAttribute("number"),
        readScenario.getPopulation().getAttributes().getAttribute("number"));

    Assert.assertEquals(
        "Unexpected String attribute in " + readScenario.getPopulation().getAttributes(),
        population.getAttributes().getAttribute("type"),
        readScenario.getPopulation().getAttributes().getAttribute("type"));
  }
Пример #25
0
 private static void createPopulation(Scenario sc, int destination) {
   Population pop = sc.getPopulation();
   pop.getPersons().clear();
   PopulationFactory fac = pop.getFactory();
   double t = 0;
   for (int i = 0; i < NR_AGENTS / 2; i++) {
     Person pers = fac.createPerson(Id.create("b" + i, Person.class));
     Plan plan = fac.createPlan();
     pers.addPlan(plan);
     Activity act0;
     act0 = fac.createActivityFromLinkId("origin", Id.create("0", Link.class));
     act0.setEndTime(t);
     plan.addActivity(act0);
     Leg leg = fac.createLeg("walkct");
     plan.addLeg(leg);
     Activity act1 =
         fac.createActivityFromLinkId("destination", Id.create(destination, Link.class));
     plan.addActivity(act1);
     pop.addPerson(pers);
   }
   //		for (int i = NR_AGENTS / 2; i < NR_AGENTS; i++) {
   //			Person pers = fac.createPerson(Id.create("b" + i, Person.class));
   //			Plan plan = fac.createPlan();
   //			pers.addPlan(plan);
   //			Activity act0;
   //			act0 = fac.createActivityFromLinkId("origin",
   //					Id.create(destination + 1, Link.class));
   //			act0.setEndTime(t);
   //			plan.addActivity(act0);
   //			Leg leg = fac.createLeg("walkct");
   //			plan.addLeg(leg);
   //			Activity act1 = fac.createActivityFromLinkId("destination",
   //					Id.create(1, Link.class));
   //			plan.addActivity(act1);
   //			pop.addPerson(pers);
   //		}
 }
Пример #26
0
  public static void main(String[] args) {

    /*Create scenario and load population*/
    Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    log.info("Reading population...");
    new PopulationReader(scenario).readFile(inputPopulationFile);
    Population population = ((MutableScenario) scenario).getPopulation();

    ArrayList<Id> personsForRemoval = new ArrayList<Id>();
    System.out.println("Number of persons: " + population.getPersons().size());
    for (Id personId : population.getPersons().keySet()) {
      Plan plan = population.getPersons().get(personId).getSelectedPlan();
      boolean ptPerson = false;

      /*Check if person used Pt in the last selected plan*/
      for (PlanElement planElement : plan.getPlanElements()) {
        if (planElement instanceof Leg) {
          Leg leg = (Leg) planElement;
          if (leg.getMode().equals("pt") || leg.getMode().equals("transit_walk")) {
            ptPerson = true;
          }
        }
      }

      /*If person didn't use PT, add it to removal List, otherwise clear all plans and keep only selected PT Plan*/
      if (ptPerson) {
        population.getPersons().get(personId).getPlans().clear();
        population.getPersons().get(personId).addPlan(plan);
      } else {
        personsForRemoval.add(personId);
      }
    }

    /*Remove all persons without PT*/
    for (Id personId : personsForRemoval) {
      population.getPersons().remove(personId);
    }

    /*Write out new population file*/
    System.out.println("New number of persons: " + population.getPersons().size());
    new PopulationWriter(scenario.getPopulation(), scenario.getNetwork())
        .write(outputPopulationFile);
  }
Пример #27
0
  public void run(String plansFilePath, String networkFilePath) throws IOException {
    populationReader.readFile(plansFilePath);
    networkReader.readFile(networkFilePath);
    double distanceCar = 0.0;
    int countC = 0;
    double distanceBike = 0.0;
    int countB = 0;
    double distanceWalk = 0.0;
    int countW = 0;
    double distancePt = 0.0;
    int countPt = 0;
    int count = 0;
    Population pop = scenario.getPopulation();
    for (Person p : pop.getPersons().values()) {
      Leg previousLeg = null;
      for (PlanElement pe : p.getSelectedPlan().getPlanElements()) {

        if (pe instanceof Leg) {
          previousLeg = (Leg) pe;
          /*if (previousActivity.getType() == "shopgrocery") {
          	if (previousLeg.getMode() == "car") {
          		distanceCar += previousLeg.getTravelTime();
          		countC++;
          		count++;
          	}
          	else if (previousLeg.getMode() == "bike") {
          		distanceBike += previousLeg.getTravelTime();
          		countB++;
          		count++;
          	}
          	else if (previousLeg.getMode() == "walk") {
          		distanceWalk += previousLeg.getTravelTime();
          		countW++;
          		count++;
          	}
          	else if (previousLeg.getMode() == "pt") {
          		distancePt += previousLeg.getTravelTime();
          		countPt++;
          		count++;
          	}
          }*/

        } else if (pe instanceof Activity) {

          // if (((Activity) pe).getType().equals( "shopgrocery" )) {
          if (previousLeg != null) {
            if (previousLeg.getMode().equals("car")) {
              distanceCar += previousLeg.getTravelTime();
              countC++;
              count++;
            } else if (previousLeg.getMode().equals("bike")) {
              distanceBike += previousLeg.getTravelTime();
              countB++;
              count++;
            } else if (previousLeg.getMode().equals("walk")) {
              distanceWalk += previousLeg.getTravelTime();
              countW++;
              count++;
            } else if (previousLeg.getMode().equals("pt")) {
              distancePt += previousLeg.getTravelTime();
              countPt++;
              count++;
            }
          }
        }
      }
    }
    System.out.println((distanceCar + distanceBike + distanceWalk + distancePt) / count);
    System.out.println(distanceCar / (double) countC);
    System.out.println(distanceBike / (double) countB);
    System.out.println(distanceWalk / (double) countW);
    System.out.println(distancePt / (double) countPt);
  }
Пример #28
0
  public static void main(String[] args) {

    /*
     * We enter coordinates in the WGS84 reference system, but we want them to appear in the population file
     * projected to UTM33N, because we also generated the network in UTM33N.
     */
    CoordinateTransformation ct =
        TransformationFactory.getCoordinateTransformation(
            TransformationFactory.WGS84, TransformationFactory.WGS84_UTM33N);

    /*
     * First, create a new Config and a new Scenario.
     */
    Config config = ConfigUtils.createConfig();
    Scenario sc = ScenarioUtils.createScenario(config);

    /*
     * Pick the Network and the Population out of the Scenario for convenience.
     */
    Network network = sc.getNetwork();
    Population population = sc.getPopulation();

    /*
     * Pick the PopulationFactory out of the Population for convenience.
     * It contains methods to create new Population items.
     */
    PopulationFactory populationFactory = population.getFactory();

    /*
     * Create a Person designated "1" and add it to the Population.
     */

    long key = 1;
    for (long i = 1; i <= 5000; i++) {
      key = i;
      Person person = populationFactory.createPerson(Id.createPersonId(key));
      population.addPerson(person);

      /*
       * Create a Plan for the Person
       */
      Plan plan = populationFactory.createPlan();

      /*
       * Create a "home" Activity for the Person. In order to have the Person end its day at the same location,
       * we keep the home coordinates for later use (see below).
       * Note that we use the CoordinateTransformation created above.
       */
      Coord homeCoordinates = new Coord(686661.13571, 4827510.51845);
      Activity activity1 = populationFactory.createActivityFromCoord("home", homeCoordinates);
      activity1.setEndTime(
          21600
              + i * 0.72); // leave at 6 o'clock, one vehicle entering after other in a short while
      // so that there is no peak at one second
      // activity1.setEndTime(21600);
      plan.addActivity(activity1); // add the Activity to the Plan

      /*
       * Create a Leg. A Leg initially hasn't got many attributes. It just says that a car will be used.
       */
      plan.addLeg(populationFactory.createLeg("car"));

      /*
       * Create a "work" Activity, at a different location.
       */
      Activity activity2 =
          populationFactory.createActivityFromCoord("work", new Coord(689426.65361, 4826700.65288));
      activity2.setEndTime(57600); // leave at 4 p.m.
      plan.addActivity(activity2);
      System.out.println("Last Departure Time: " + claculateTime(activity1.getEndTime()));

      /*
       * Create another car Leg.
       */
      person.addPlan(plan);
    }

    for (long i = 1; i <= 5000; i++) {
      key = i + 5000;
      Person person = populationFactory.createPerson(Id.createPersonId(key));
      population.addPerson(person);
      Plan plan = populationFactory.createPlan();
      Coord homeCoordinates = new Coord(686661.13571, 4826063.88649);
      Activity activity1 = populationFactory.createActivityFromCoord("home", homeCoordinates);
      activity1.setEndTime(21600 + i * 1); // leave at 6 o'clock
      // activity1.setEndTime(21600);
      plan.addActivity(activity1); // add the Activity to the Plan
      plan.addLeg(populationFactory.createLeg("car"));
      Activity activity2 =
          populationFactory.createActivityFromCoord("work", new Coord(689426.65361, 4826700.65288));
      activity2.setEndTime(57600); // leave at 4 p.m.
      plan.addActivity(activity2);
      System.out.println("Last Departure Time: " + claculateTime(activity1.getEndTime()));
      person.addPlan(plan);
    }

    /*
     * Write the population (of 1 Person) to a file.
     */
    MatsimWriter popWriter =
        new org.matsim.api.core.v01.population.PopulationWriter(population, network);
    popWriter.write("H:\\Mike Work\\input\\population.xml");
  }
Пример #29
0
  /** @param args */
  public static void main(String[] args) {
    String basePath = "H:/data/experiments/ARTEMIS/output/run2/";
    String plansFile = basePath + "output_plans.xml.gz";
    String networkFile = basePath + "output_network.xml.gz";
    String facilititiesPath = basePath + "output_facilities.xml.gz";
    MutableScenario scenario =
        (MutableScenario) GeneralLib.readScenario(plansFile, networkFile, facilititiesPath);

    int nuberTripsWorkRelated = 0;
    int numberOfTripsShopAndLeisureRelated = 0;

    Population population = scenario.getPopulation();

    for (Person person : population.getPersons().values()) {
      Plan plan = person.getSelectedPlan();

      Activity prevAct = null;
      Leg prevLeg = null;

      for (PlanElement pe : plan.getPlanElements()) {
        if (pe instanceof Activity) {
          Activity activity = (Activity) pe;
          if (prevLeg != null && prevLeg.getMode().equalsIgnoreCase("car")) {

            // a) COMING FROM OC TO C FOR WORK
            if (!isInsideCordon(prevAct) && isInsideCordon(activity)) {
              if (equalsActType(activity, "work")) {
                nuberTripsWorkRelated++;
              }
            }

            // b)LEAVING C FROM WORK TO OC
            if (isInsideCordon(prevAct) && !isInsideCordon(activity)) {
              if (equalsActType(prevAct, "work")) {
                nuberTripsWorkRelated++;
              }
            }

            // c)COMING FROM C TO C FOR WORK
            if (isInsideCordon(prevAct) && isInsideCordon(activity)) {
              if (equalsActType(activity, "work")) {
                nuberTripsWorkRelated++;
              }
            }

            // d) LEAVING C FROM WORK TO C
            if (isInsideCordon(prevAct) && isInsideCordon(activity)) {
              if (equalsActType(prevAct, "work")) {
                nuberTripsWorkRelated++;
              }
            }

            // e) COMING FROM OC TO C FOR ACT (shop/leisure)
            if (!isInsideCordon(prevAct) && isInsideCordon(activity)) {
              if (equalsActType(activity, "shop") || equalsActType(activity, "leisure")) {
                numberOfTripsShopAndLeisureRelated++;
              }
            }

            // f) COMING FROM C TO C FOR ACT
            if (isInsideCordon(prevAct) && isInsideCordon(activity)) {
              if (equalsActType(activity, "shop") || equalsActType(activity, "leisure")) {
                numberOfTripsShopAndLeisureRelated++;
              }
            }
          }

          prevAct = activity;
        }

        if (pe instanceof Leg) {
          prevLeg = (Leg) pe;
        }
      }
    }

    System.out.println("nuberTripsWorkRelated:" + nuberTripsWorkRelated);
    System.out.println("numberOfTripsShopAndLeisureRelated:" + numberOfTripsShopAndLeisureRelated);
  }
Пример #30
0
  void readPersonsFromHouseholds(
      Population population, ActivityFacilitiesImpl facilities, double fraction) {
    log.fatal("does not work; see javadoc of class.  Aborting ..." + this);
    System.exit(-1);
    try {
      BufferedReader reader =
          IOUtils.getBufferedReader(Matsim4Urbansim.PATH_TO_OPUS_MATSIM + "tmp/households.tab");

      String header = reader.readLine();
      Map<String, Integer> idxFromKey = Utils.createIdxFromKey(header, null);

      String line = reader.readLine();
      while (line != null) {
        String[] parts = line.split("[\t\n]+");

        if (Math.random() > fraction) {
          line = reader.readLine(); // next line
          continue;
        }

        int idx = idxFromKey.get("persons:i4");
        int nPersons = Integer.parseInt(parts[idx]);

        idx = idxFromKey.get("workers:i4");
        int nWorkers = Integer.parseInt(parts[idx]);

        idx = idxFromKey.get("household_id:i4");
        Id<HH> hhId = Id.create(parts[idx], HH.class);

        idx = idxFromKey.get("grid_id:i4");
        Id<Location> homeGridId = Id.create(parts[idx], Location.class);
        ActivityFacility homeLocation =
            facilities.getFacilities().get(Id.create(homeGridId, ActivityFacility.class));
        if (homeLocation == null) {
          log.warn("no home location; hhId: " + hhId.toString());
          line = reader.readLine(); // next line
          continue;
        }
        Coord homeCoord = homeLocation.getCoord();

        // generate persons only after it's clear that they have a home location:
        for (int ii = 0; ii < nPersons; ii++) {
          Id<Person> personId = Id.create(personCnt, Person.class);
          Person person = PersonImpl.createPerson(personId);
          personCnt++;
          if (personCnt > 10) {
            log.error("hack");
            return;
          }

          population.addPerson(person);

          PlanImpl plan = PersonUtils.createAndAddPlan(person, true);
          Utils.makeHomePlan(plan, homeCoord);

          if (ii < nWorkers) {
            PersonUtils.setEmployed(person, Boolean.TRUE);
          } else {
            PersonUtils.setEmployed(person, Boolean.FALSE);
          }
        }
        line = reader.readLine(); // next line
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      System.exit(-1);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }