Ejemplo n.º 1
0
  @Test
  public final void testSelectPlan() {
    Scenario sc = this.loadAndPrepareScenario();
    Set<String> mainModes = new HashSet<String>();
    mainModes.add("pt");
    mainModes.add("train");

    // Two plans with exactly same structure but a big difference in the scores
    PathSizeLogitSelector psls = new PathSizeLogitSelector(1, 2, mainModes);
    Plan plan =
        psls.selectPlan(sc.getPopulation().getPersons().get(Id.create("555555", Person.class)));
    System.out.println(plan);
    Assert.assertNotNull(plan);
    Assert.assertEquals(10.0, plan.getScore(), MatsimTestUtils.EPSILON);

    // Two plans with exactly same structure no difference in the scores
    psls = new PathSizeLogitSelector(50, 2, mainModes);
    plan = psls.selectPlan(sc.getPopulation().getPersons().get(Id.create("666666", Person.class)));
    System.out.println(plan);
    Assert.assertNotNull(plan); // can't test more both are exactly equal

    // Two exactly equal plans (structure + score) with a third pt plan that is not similar and
    // worse
    plan = psls.selectPlan(sc.getPopulation().getPersons().get(Id.create("777777", Person.class)));
    System.out.println(plan);
    Assert.assertNotNull(plan);
    Leg leg = (Leg) plan.getPlanElements().get(3);
    Assert.assertEquals(
        "PT1===TXL===TXL_MUC_SBA===TXL_MUC_SBA23===MUC",
        ((GenericRoute) leg.getRoute()).getRouteDescription());

    // Two equal pt plans and one train plan
    plan = psls.selectPlan(sc.getPopulation().getPersons().get(Id.create("888888", Person.class)));
    System.out.println(plan);
    Assert.assertNotNull(plan);
    leg = (Leg) plan.getPlanElements().get(3);
    Assert.assertEquals(
        "PT1===TXL===TXL_MUC_SBA===TXL_MUC_SBA23===MUC",
        ((GenericRoute) leg.getRoute()).getRouteDescription());

    // Two equal train plans and one pt plan with less score
    psls = new PathSizeLogitSelector(20, 2, mainModes);
    plan = psls.selectPlan(sc.getPopulation().getPersons().get(Id.create("999999", Person.class)));
    System.out.println(plan);
    Assert.assertNotNull(plan);
    leg = (Leg) plan.getPlanElements().get(1);
    Assert.assertEquals("train", leg.getMode());

    // Same as last test but with lest ps logit beta
    psls = new PathSizeLogitSelector(10, 2, mainModes);
    plan = psls.selectPlan(sc.getPopulation().getPersons().get(Id.create("999999", Person.class)));
    System.out.println(plan);
    Assert.assertNotNull(plan);
    leg = (Leg) plan.getPlanElements().get(1);
    Assert.assertEquals("transit_walk", leg.getMode());
  }
 private static void startPlan(final Plan plan, final BufferedWriter out) throws IOException {
   out.write("\t\t<plan");
   if (plan.getScore() != null) {
     out.write(" score=\"");
     out.write(plan.getScore().toString());
     out.write("\"");
   }
   if (PersonUtils.isSelected(plan)) out.write(" selected=\"yes\"");
   else out.write(" selected=\"no\"");
   if (plan != null) {
     Plan p = plan;
     if ((p.getType() != null)) {
       out.write(" type=\"");
       out.write(p.getType());
       out.write("\"");
     }
   }
   out.write(">\n");
 }
  private void run() {
    for (Person p : this.scenario.getPopulation().getPersons().values()) {

      if (Integer.parseInt(p.getId().toString()) > this.analysisPopulationOffset) continue;

      PlanImpl plan = (PlanImpl) p.getSelectedPlan();

      // find best plan
      double bestPlanScore = -999.0;
      int bestIndex = 0;
      int cnt = 0;
      for (Plan planTmp : p.getPlans()) {
        if (planTmp.getScore() > bestPlanScore) {
          bestPlanScore = planTmp.getScore();
          bestIndex = cnt;
        }
        cnt++;
      }
      plan = (PlanImpl) p.getPlans().get(bestIndex);
      for (PlanElement pe : plan.getPlanElements()) {
        if (pe instanceof Activity) {

          if (((Activity) pe).getType().startsWith("s")
              || ((Activity) pe).getType().startsWith("l")) {
            double distance =
                CoordUtils.calcDistance(
                    ((Activity) pe).getCoord(),
                    plan.getPreviousActivity(plan.getPreviousLeg((Activity) pe)).getCoord());
            if (((Activity) pe).getType().startsWith("s")) {
              this.shopBins.addVal(distance, 1.0);
            } else if (((Activity) pe).getType().startsWith("l")) {
              this.leisureBins.addVal(distance, 1.0);
            }
          }
        }
      }
    }
    this.shopBins.plotBinnedDistribution(
        this.outPath + this.shopBins.getInterval() + "_", "#", "m");
    this.leisureBins.plotBinnedDistribution(
        this.outPath + this.leisureBins.getInterval() + "_", "#", "m");
  }
Ejemplo n.º 4
0
  private void doAnalysis() {
    MutableScenario scenario =
        (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Network net = scenario.getNetwork();
    MatsimNetworkReader netReader = new MatsimNetworkReader(scenario.getNetwork());
    netReader.readFile(NETWORK);
    //		Gbl.getWorld().setNetworkLayer(net);
    //		Gbl.getWorld().complete();

    Scenario scenario1 = new ScenarioBuilder(ConfigUtils.createConfig()).setNetwork(net).build();
    Population plans = scenario1.getPopulation();
    new MatsimPopulationReader(scenario1).readFile(PLANS);

    Scenario scenario2 = new ScenarioBuilder(ConfigUtils.createConfig()).setNetwork(net).build();
    Population plans2 = scenario2.getPopulation();
    new MatsimPopulationReader(scenario2).readFile(PLANS2);

    Logger.getLogger(PlanScoreAnalysis.class).info("plans read");
    try {
      PlanScoreAnalysisTableWriter writer = new PlanScoreAnalysisTableWriter(OUTFILETXT);

      this.createOGCTypes();

      //			Collection<Feature> features = new ArrayList<Feature>(plans.getPersons()
      //					.size());

      Plan plan;
      double score1, score2;
      Coord loc;
      Id id;
      for (Person person : plans.getPersons().values()) {
        plan = person.getSelectedPlan();
        id = person.getId();
        score1 = plan.getScore().doubleValue();
        score2 = plans2.getPersons().get(id).getSelectedPlan().getScore().doubleValue();
        loc = ((ActivityImpl) plan.getPlanElements().get(0)).getCoord();
        writer.addLine(
            id.toString(),
            Double.toString(loc.getX()),
            Double.toString(loc.getY()),
            Double.toString(score1),
            Double.toString(score2));
        this.counter++;
        //				features.add(this.createHomeFeature(score1, loc, id));
        if (this.counter % this.nextMsg == 0) {
          this.nextMsg *= 2;
          Logger.getLogger(PlanScoreAnalysis.class).info("plans: " + this.counter);
        }
      }
      writer.close();
      //			this.writeShapeFile(features, OUTFILE);
    } catch (IOException e) {
      e.printStackTrace();
    } /*catch (FactoryException e) {
      	e.printStackTrace();
      } catch (SchemaException e) {
      	e.printStackTrace();
      }*/

    Logger.getLogger(PlanScoreAnalysis.class).info("completed analysis of plans");
  }
  @Override
  public Plan selectPlan(HasPlansAndId<Plan, Person> person) {

    // hashmap that returns "Integer" count for given plans type:
    HashMap<String, Integer> typeCounts = new HashMap<String, Integer>();

    // count how many plans per type an agent has:
    for (Plan plan : person.getPlans()) {
      if (!StayHomePlan.isAStayHomePlan(plan)) {
        /* stayHomePlan is isolated */
        Integer cnt = typeCounts.get(((PlanImpl) plan).getType());
        if (cnt == null) {
          typeCounts.put(((PlanImpl) plan).getType(), Integer.valueOf(1));
        } else {
          typeCounts.put(((PlanImpl) plan).getType(), Integer.valueOf(cnt.intValue() + 1));
        }
      }
    }

    Plan worst = null;
    double worstScore = Double.POSITIVE_INFINITY;
    for (Plan plan : person.getPlans()) {
      if (!StayHomePlan.isAStayHomePlan(plan)) {
        /* stayHomePlan is isolated */
        // if we have more than one plan of the same type:
        if (typeCounts.get(((PlanImpl) plan).getType()).intValue() > 1) {

          // if there is a plan without score:
          if (plan.getScore() == null) {
            // say that the plan without score now is the "worst":
            worst = plan;

            // make sure that this one remains the selected plan:
            worstScore = Double.NEGATIVE_INFINITY;

            // otherwise do the usual logic to find the plan with
            // the
            // minimum score:
          } else if (plan.getScore().doubleValue() < worstScore) {
            worst = plan;
            worstScore = plan.getScore().doubleValue();
          }
        }

        // (otherwise we just keep "worst=null")
      }
    }

    if (worst == null) {
      // there is exactly one plan, or we have of each plan-type exactly
      // one.
      // select the one with worst score globally
      for (Plan plan : person.getPlans()) {
        if (plan.getScore() == null) {
          return plan;
        }
        if (plan.getScore().doubleValue() < worstScore) {
          worst = plan;
          worstScore = plan.getScore().doubleValue();
        }
      }
    }
    return worst;
  }
  @Override
  public void notifyShutdown(ShutdownEvent event) {
    Scenario newScenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Population newPopulation = newScenario.getPopulation();
    MoneyEventHandler moneyHandler = choiceGenerationControler.getMoneyEventHandler();
    CrowdingPsimHandler crowdingPsimHandler = choiceGenerationControler.getCrowdingPsimHandler();

    for (Id<Person> personId : population.getPersons().keySet()) {

      Id<Person> orgPersonId = Id.create(personId.toString().split("_")[0], Person.class);

      Double monetaryPayments = moneyHandler.getPersonId2amount().get(personId);
      if (monetaryPayments == null) {
        monetaryPayments = 0.0;
      }

      Plan planToAdd = null;
      if (personId.toString().contains("_")) {
        planToAdd = population.getPersons().get(personId).getSelectedPlan();
        planToAdd.getCustomAttributes().put("toll", monetaryPayments.toString());
        if (crowdingPsimHandler.getPerson2crowdingDisutility().containsKey(personId)) {
          planToAdd.setScore(
              planToAdd.getScore()
                  + crowdingPsimHandler.getPerson2crowdingDisutility().get(personId));
        }
      } else {
        planToAdd = initialPlans.get(personId);
        // planToAdd.getCustomAttributes().put("toll", monetaryPayments.toString());
      }

      if (newPopulation.getPersons().containsKey(orgPersonId)) {
        newPopulation.getPersons().get(orgPersonId).addPlan(planToAdd);
      } else {
        Person newPerson = newPopulation.getFactory().createPerson(orgPersonId);
        newPerson.addPlan(planToAdd);
        newPopulation.addPerson(newPerson);
      }
    }

    /*Write score table to SQL*/
    Integer relativeOutputDirectory =
        event.getServices().getConfig().controler().getOutputDirectory().split("/").length;

    String tableName = schema + ".scores_";
    String tableSuffix =
        event
            .getServices()
            .getConfig()
            .controler()
            .getOutputDirectory()
            .split("/")[relativeOutputDirectory - 1];
    tableSuffix = tableSuffix.replaceAll("\\.0x", "x");
    tableSuffix = tableSuffix.replaceAll("-", "_");
    tableSuffix = tableSuffix.replaceAll("\\.5", "5");
    tableSuffix = tableSuffix.replaceAll("\\.1", "1");
    tableSuffix = tableSuffix.replaceAll("\\.0", "0");
    tableName = tableName + tableSuffix;

    IndividualScoreFromPopulationSQLWriter sqlWriter =
        new IndividualScoreFromPopulationSQLWriter(event.getServices().getConfig(), newPopulation);
    sqlWriter.writeToDatabase(connectionPropertiesPath, schema, tableName);

    new PopulationWriter(newScenario.getPopulation())
        .write(
            choiceGenerationControler.getControler().getConfig().controler().getOutputDirectory()
                + "/output_plansJoin.xml");
  }