Exemplo n.º 1
0
  @Override
  public void run(final Person person) {
    // if (Integer.parseInt(person.getId().toString()) < 1000000000) {
    this.person = person;
    for (Plan pl : person.getPlans()) {
      run(pl);
    }
    person.getPlans().clear();

    for (PlanImpl copyPlan : copyPlans) {
      person.addPlan(copyPlan);
    }
    copyPlans.clear();
    // }
    pw.writePerson(person);
  }
Exemplo n.º 2
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);
     }
   }
 }
 @Override
 public void writePerson(final Person person, final BufferedWriter out) throws IOException {
   PopulationWriterHandlerImplV5.startPerson(person, out);
   for (Plan plan : person.getPlans()) {
     PopulationWriterHandlerImplV5.startPlan(plan, out);
     // act/leg
     for (PlanElement pe : plan.getPlanElements()) {
       if (pe instanceof Activity) {
         Activity act = (Activity) pe;
         this.writeAct(act, out);
       } else if (pe instanceof Leg) {
         Leg leg = (Leg) pe;
         PopulationWriterHandlerImplV5.startLeg(leg, out);
         // route
         Route route = leg.getRoute();
         if (route != null) {
           PopulationWriterHandlerImplV5.startRoute(route, out);
           PopulationWriterHandlerImplV5.endRoute(out);
         }
         PopulationWriterHandlerImplV5.endLeg(out);
       }
     }
     PopulationWriterHandlerImplV5.endPlan(out);
   }
   PopulationWriterHandlerImplV5.endPerson(out);
   this.writeSeparator(out);
   out.flush();
 }
Exemplo n.º 4
0
  @Test
  public void testNumberOfSelectedJointPlans() throws Exception {
    final JointPlans jointPlans = new JointPlans();
    final GroupPlanStrategy strategy =
        new GroupPlanStrategy(
            new HighestScoreSumSelector(new EmptyIncompatiblePlansIdentifierFactory()));
    strategy.addStrategyModule(new JointStructureInvertingModule(jointPlans.getFactory()));

    final ReplanningGroup group = createTestGroup(jointPlans);
    strategy.run(createContext(), jointPlans, Arrays.asList(group));

    int countSelectedJoint = 0;
    int countSelectedIndiv = 0;
    for (Person person : group.getPersons()) {
      for (Plan plan : person.getPlans()) {
        if (plan.isSelected() && jointPlans.getJointPlan(plan) != null) {
          countSelectedJoint++;
        }
        if (plan.isSelected() && jointPlans.getJointPlan(plan) == null) {
          countSelectedIndiv++;
        }
      }
    }

    assertEquals(
        "wrong number of selected plans in joint plans",
        N_INITIALLY_INDIV_PLANS,
        countSelectedJoint);
    assertEquals(
        "wrong number of selected plans in individual plans",
        N_INITIALLY_JOINT_PLANS,
        countSelectedIndiv);
  }
Exemplo n.º 5
0
  @Test
  public void testNewPlanIsSelected() throws Exception {
    final JointPlans jointPlans = new JointPlans();
    final GroupPlanStrategy strategy =
        new GroupPlanStrategy(
            new HighestScoreSumSelector(new EmptyIncompatiblePlansIdentifierFactory()));
    strategy.addStrategyModule(new JointStructureInvertingModule(jointPlans.getFactory()));

    final List<Plan> selectedPlans = new ArrayList<Plan>();
    final ReplanningGroup group = createTestGroup(jointPlans);
    for (Person p : group.getPersons()) {
      selectedPlans.add(p.getSelectedPlan());
    }

    strategy.run(createContext(), jointPlans, Arrays.asList(group));
    for (Person person : group.getPersons()) {
      for (Plan plan : person.getPlans()) {
        if (plan.isSelected()) {
          // new plan: selection status inverted
          assertFalse("old plan still selected", selectedPlans.contains(plan));
        } else {
          assertTrue("old plan still selected", selectedPlans.contains(plan));
        }
      }
    }
  }
Exemplo n.º 6
0
  @Override
  public void notifyIterationStarts(IterationStartsEvent event) {
    int evCount = 0;
    int cvCount = 0;
    int newKeysAdded = 0;
    int existingKeyUsed = 0;
    int numberOfPlansRemovedFromHM = 0;
    HashSet<Plan> allCurrentPlans = new HashSet<Plan>();
    for (Person person : event.getServices().getScenario().getPopulation().getPersons().values()) {

      if (person.getId().toString().equalsIgnoreCase("111106347")) {
        System.out.println();
      }

      if (hasCarLeg(person.getSelectedPlan())) {
        if (!hasElectricVehicle.containsKey(person.getSelectedPlan())) {
          hasElectricVehicle.put(person.getSelectedPlan(), MatsimRandom.getRandom().nextBoolean());
          newKeysAdded++;
        } else {
          existingKeyUsed++;
        }

        if (hasElectricVehicle.get(person.getSelectedPlan())) {
          evCount++;
          personHasElectricVehicle.put(person.getId(), true);
        } else {
          cvCount++;
          personHasElectricVehicle.put(person.getId(), false);
        }

        for (Plan plan : person.getPlans()) {
          allCurrentPlans.add(plan);
        }
      }
    }

    LinkedList<Plan> removePlans = new LinkedList<Plan>();
    for (Plan plan : hasElectricVehicle.keySet()) {
      if (!allCurrentPlans.contains(plan)) {
        removePlans.add(plan);
      }
    }

    for (Plan plan1 : removePlans) {
      hasElectricVehicle.remove(plan1);
      numberOfPlansRemovedFromHM++;
    }

    log.info("iteration: " + event.getIteration());

    log.info("numberOfPlansRemovedFromHM: " + numberOfPlansRemovedFromHM);
    log.info("evCount: " + evCount);
    log.info("cvCount: " + cvCount);
    log.info("hasElectricVehicle.size(): " + hasElectricVehicle.size());
    log.info("newKeysAdded: " + newKeysAdded);
    log.info("existingKeyUsed: " + existingKeyUsed);
    log.info("");
  }
  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");
  }
Exemplo n.º 8
0
 public static BasePersonImpl convertToBasePerson(Person person) {
   BasePersonImpl newPerson = new BasePersonImpl(person.getId());
   PersonUtils.setAge(newPerson, PersonUtils.getAge(person));
   PersonUtils.setCarAvail(newPerson, PersonUtils.getCarAvail(person));
   PersonUtils.setEmployed(newPerson, PersonUtils.isEmployed(person));
   PersonUtils.setLicence(newPerson, PersonUtils.getLicense(person));
   PersonUtils.setSex(newPerson, PersonUtils.getSex(person));
   for (Plan plan : person.getPlans()) if (!PersonUtils.isSelected(plan)) newPerson.addPlan(plan);
   BasePlanImpl.convertToBasePlan(newPerson, person.getSelectedPlan());
   return newPerson;
 }
Exemplo n.º 9
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;
  }
Exemplo n.º 10
0
 private void replaceSptByPtp() {
   for (Id<Person> pid : this.teleportPtUsers) {
     Person p = scenario.getPopulation().getPersons().get(pid);
     for (Plan plan : p.getPlans()) {
       for (PlanElement pe : plan.getPlanElements()) {
         if (pe instanceof Leg) {
           Leg leg = (Leg) pe;
           if (leg.getMode().equals("pt")) {
             leg.setMode("tpt");
           }
         }
       }
     }
   }
 }
Exemplo n.º 11
0
  private void replaceDoubtfulLegsByOtherMode() {
    for (Person p : scenario.getPopulation().getPersons().values()) {
      for (Plan plan : p.getPlans()) {

        Leg lastleg = null;
        Activity lastActivity = null;
        boolean personb = random.nextBoolean();
        for (PlanElement pe : plan.getPlanElements()) {
          if (pe instanceof Activity) {
            if (lastActivity == null) {
              lastActivity = (Activity) pe;
            } else {
              Coord lastCoord;
              if (lastActivity.getCoord() != null) {
                lastCoord = lastActivity.getCoord();
              } else {
                Link lastLink = scenario.getNetwork().getLinks().get(lastActivity.getLinkId());
                lastCoord = lastLink.getCoord();
              }
              Coord currentCoord;
              if (((Activity) pe).getCoord() != null) {
                currentCoord = ((Activity) pe).getCoord();
              } else {
                currentCoord =
                    scenario.getNetwork().getLinks().get(((Activity) pe).getLinkId()).getCoord();
              }

              double distance = CoordUtils.calcDistance(lastCoord, currentCoord);

              if (distance > 3000 && lastleg.getMode().equals("walk")) {
                lastleg.setMode("pt");
              } else if (distance > 20000 && lastleg.getMode().equals("bike")) {
                lastleg.setMode("pt");
              } else if (distance < 2000 && (lastleg.getMode().equals("pt"))) {
                if (personb == true) lastleg.setMode("walk");
                else lastleg.setMode("bike");
              }

              lastActivity = (Activity) pe;
            }

          } else if (pe instanceof Leg) {
            lastleg = (Leg) pe;
          }
        }
      }
    }
  }
Exemplo n.º 12
0
 void createAgentGroupNearTransitstrops(
     Scenario scenario, double distance, String transitScheduleFile) {
   new TransitScheduleReader(scenario).readFile(transitScheduleFile);
   for (Person p : scenario.getPopulation().getPersons().values()) {
     if (scenario
             .getPopulation()
             .getPersonAttributes()
             .getAttribute(p.getId().toString(), "subpopulation")
         != null) {
       return;
     }
     ArrayList<Boolean> isIt = new ArrayList<>();
     for (Plan plan : p.getPlans()) {
       for (PlanElement pe : plan.getPlanElements()) {
         if (pe instanceof Activity) {
           boolean setAct = false;
           Coord ac = ((Activity) pe).getCoord();
           for (TransitStopFacility stop :
               scenario.getTransitSchedule().getFacilities().values()) {
             double dist = CoordUtils.calcDistance(stop.getCoord(), ac);
             if (dist <= distance) {
               setAct = true;
               break;
             }
           }
           isIt.add(setAct);
         }
       }
     }
     boolean truth = true;
     for (Boolean t : isIt) {
       if (!t) truth = false;
     }
     if (truth) {
       scenario
           .getPopulation()
           .getPersonAttributes()
           .putAttribute(p.getId().toString(), "subpopulation", "schedulePt");
     } else {
       scenario
           .getPopulation()
           .getPersonAttributes()
           .putAttribute(p.getId().toString(), "subpopulation", "teleportPt");
       this.teleportPtUsers.add(p.getId());
     }
   }
 }
 @Override
 public boolean judge(final Person person) {
   for (Plan plan : person.getPlans()) {
     for (int i = 1, n = plan.getPlanElements().size(); i < n; i += 2) {
       Leg leg = (Leg) plan.getPlanElements().get(i);
       if (leg.getRoute() == null) {
         if (judgeByBeeline(
             (Activity) plan.getPlanElements().get(i - 1),
             (Activity) plan.getPlanElements().get(i + 1))) {
           return true;
         }
       } else if (leg.getRoute() instanceof NetworkRoute) {
         List<Id<Link>> linkIds = ((NetworkRoute) leg.getRoute()).getLinkIds();
         if (linkIds.size() == 0) {
           if (judgeByBeeline(
               (Activity) plan.getPlanElements().get(i - 1),
               (Activity) plan.getPlanElements().get(i + 1))) {
             return true;
           }
         } else {
           for (Id<Link> link : linkIds) {
             if (this.areaOfInterest.containsKey(link)) {
               return true;
             }
           }
           // test departure link
           Id<Link> linkId = ((Activity) plan.getPlanElements().get(i - 1)).getLinkId();
           if ((linkId != null) && (this.areaOfInterest.containsKey(linkId))) {
             return true;
           }
           // test arrival link
           linkId = ((Activity) plan.getPlanElements().get(i + 1)).getLinkId();
           if ((linkId != null) && (this.areaOfInterest.containsKey(linkId))) {
             return true;
           }
         }
       } else { // leg.getRoute() instanceof GenericRoute
         if (judgeByBeeline(
             (Activity) plan.getPlanElements().get(i - 1),
             (Activity) plan.getPlanElements().get(i + 1))) {
           return true;
         }
       }
     }
   }
   return false;
 }
Exemplo n.º 14
0
  private static void removeActs(String networkFile, String popFile) {
    String popOutFile = popFile + "_removedTransitActs.xml.gz";
    TransitActsRemover remover = new TransitActsRemover();

    Scenario sc = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new MatsimNetworkReader(sc.getNetwork()).readFile(networkFile);
    new PopulationReader(sc).readFile(popFile);

    for (Person person : sc.getPopulation().getPersons().values()) {
      for (Plan plan : person.getPlans()) {
        remover.run(plan);
      }
    }

    PopulationWriter popWriter = new PopulationWriter(sc.getPopulation(), sc.getNetwork());
    popWriter.write(popOutFile);
  }
Exemplo n.º 15
0
 private static boolean isRelatedWithLine(Person person, TransitLine line) {
   ExperimentalTransitRouteFactory factory = new ExperimentalTransitRouteFactory();
   for (Plan plan : person.getPlans())
     for (PlanElement planElement : plan.getPlanElements())
       if (planElement instanceof Leg && ((Leg) planElement).getRoute() instanceof Route) {
         Route origRoute = ((Leg) planElement).getRoute();
         ExperimentalTransitRoute route =
             (ExperimentalTransitRoute)
                 factory.createRoute(origRoute.getStartLinkId(), origRoute.getEndLinkId());
         route.setStartLinkId(origRoute.getStartLinkId());
         route.setEndLinkId(origRoute.getEndLinkId());
         route.setRouteDescription(origRoute.getRouteDescription());
         for (TransitRoute transitRoute : line.getRoutes().values())
           for (TransitRouteStop stop : transitRoute.getStops())
             if (stop.getStopFacility().getId().equals(route.getAccessStopId())
                 || stop.getStopFacility().getId().equals(route.getEgressStopId())) return true;
       }
   return false;
 }
Exemplo n.º 16
0
 /** Why? dg 09-2013 */
 private void createExperimentalTransitRoutes(Scenario sc) {
   for (Person person : sc.getPopulation().getPersons().values()) {
     for (Plan plan : person.getPlans()) {
       for (PlanElement pe : plan.getPlanElements()) {
         if (pe instanceof Leg) {
           Leg leg = (Leg) pe;
           if (leg.getMode().equals("pt")) {
             GenericRoute route = (GenericRoute) leg.getRoute();
             ExperimentalTransitRoute tr =
                 (ExperimentalTransitRoute)
                     new ExperimentalTransitRouteFactory().createRoute(null, null);
             leg.setRoute(tr);
             tr.setRouteDescription(
                 route.getStartLinkId(), route.getRouteDescription(), route.getEndLinkId());
             tr.setDistance(route.getDistance());
           }
         }
       }
     }
   }
 }
Exemplo n.º 17
0
  /**
   * Tests that the travel times are correctly calculated during the simulation.
   *
   * @author mrieser
   */
  @Test
  public void testTravelTimeCalculation() {
    Config config = this.utils.loadConfig(null);
    Fixture f = new Fixture(config);

    /* Create 2 persons driving from link 1 to link 3, both starting at the
     * same time at 7am.  */
    Population population = f.scenario.getPopulation();
    PopulationFactory factory = population.getFactory();
    Person person1 = null;

    person1 = factory.createPerson(Id.create("1", Person.class));
    Plan plan1 = factory.createPlan();
    person1.addPlan(plan1);
    Activity a1 = factory.createActivityFromLinkId("h", f.link1.getId());
    a1.setEndTime(7.0 * 3600);
    plan1.addActivity(a1);
    Leg leg1 = factory.createLeg(TransportMode.car);
    plan1.addLeg(leg1);
    NetworkRoute route1 =
        ((PopulationFactoryImpl) f.scenario.getPopulation().getFactory())
            .createRoute(NetworkRoute.class, f.link1.getId(), f.link3.getId());
    leg1.setRoute(route1);
    ArrayList<Id<Link>> linkIds = new ArrayList<Id<Link>>();
    linkIds.add(f.link2.getId());
    route1.setLinkIds(f.link1.getId(), linkIds, f.link3.getId());
    plan1.addActivity(factory.createActivityFromLinkId("h", f.link3.getId()));
    population.addPerson(person1);

    Person person2 = factory.createPerson(Id.create("2", Person.class));
    Plan plan2 = factory.createPlan();
    person2.addPlan(plan2);
    Activity a2 = factory.createActivityFromLinkId("h", f.link1.getId());
    a2.setEndTime(7.0 * 3600);
    plan2.addActivity(a2);
    Leg leg2 = factory.createLeg(TransportMode.car);
    plan2.addLeg(leg2);
    NetworkRoute route2 =
        ((PopulationFactoryImpl) f.scenario.getPopulation().getFactory())
            .createRoute(NetworkRoute.class, f.link1.getId(), f.link3.getId());
    leg2.setRoute(route2);
    route2.setLinkIds(f.link1.getId(), linkIds, f.link3.getId());
    plan2.addActivity(factory.createActivityFromLinkId("h", f.link3.getId()));
    population.addPerson(person2);

    // Complete the configuration for our test case
    // - set scoring parameters
    ActivityParams actParams = new ActivityParams("h");
    actParams.setTypicalDuration(8 * 3600);
    actParams.setPriority(1.0);
    config.planCalcScore().addActivityParams(actParams);
    // - define iterations
    config.controler().setLastIteration(0);
    // - make sure we don't use threads, as they are not deterministic
    config.global().setNumberOfThreads(0);

    // Now run the simulation
    Controler controler = new Controler(f.scenario);
    controler.getConfig().controler().setCreateGraphs(false);
    controler.getConfig().controler().setWriteEventsInterval(0);
    controler.setDumpDataAtEnd(false);
    controler.run();

    // test if we got the right result
    // the actual result is 151sec, not 150, as each vehicle "loses" 1sec in the buffer
    assertEquals(
        "TravelTimeCalculator has wrong result",
        151.0,
        controler.getLinkTravelTimes().getLinkTravelTime(f.link2, 7 * 3600, null, null),
        0.0);

    // now test that the ReRoute-Strategy also knows about these travel times...
    config.controler().setLastIteration(1);
    ConfigGroup strategyParams = config.getModule("strategy");
    strategyParams.addParam("maxAgentPlanMemorySize", "4");
    strategyParams.addParam("ModuleProbability_1", "1.0");
    strategyParams.addParam("Module_1", "ReRoute");
    // Run the simulation again
    controler = new Controler(f.scenario);
    controler.getConfig().controler().setCreateGraphs(false);
    controler
        .getConfig()
        .controler()
        .setOverwriteFileSetting(
            OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles);
    controler.getConfig().controler().setWriteEventsInterval(0);
    controler.run();

    // test that the plans have the correct times
    assertEquals(
        "ReRoute seems to have wrong travel times.",
        151.0,
        ((Leg) (person1.getPlans().get(1).getPlanElements().get(1))).getTravelTime(),
        0.0);
  }
Exemplo n.º 18
0
  public Scenario filterScenarioToSurveyRespondents() {
    LOG.info("Filtering scenario to households having completed the diary...");
    Scenario newSc = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    int membersAccountedFor = 0;
    int membersUnaccountedFor = 0;

    for (Id<Household> hhId : sc.getHouseholds().getHouseholds().keySet()) {
      /* Check if household completed the travel diary. */
      Object check =
          this.sc
              .getHouseholds()
              .getHouseholdAttributes()
              .getAttribute(hhId.toString(), "completedDiary");
      if (check instanceof String) {
        String sCheck = (String) check;
        if (sCheck.equalsIgnoreCase("Yes")) {
          /* Copy the household to the new scenario. */
          newSc
              .getHouseholds()
              .getHouseholds()
              .put(hhId, this.sc.getHouseholds().getHouseholds().get(hhId));

          /* Copy the household attributes to the new households. */
          for (String attr : getHouseholdAttributes()) {
            Object o =
                this.sc
                    .getHouseholds()
                    .getHouseholdAttributes()
                    .getAttribute(hhId.toString(), attr);
            newSc.getHouseholds().getHouseholdAttributes().putAttribute(hhId.toString(), attr, o);
          }

          /* Get the reported number of household members. */
          Object oMembers =
              this.sc
                  .getHouseholds()
                  .getHouseholdAttributes()
                  .getAttribute(hhId.toString(), "householdSize");
          int members = 0;
          if (oMembers instanceof Integer) {
            members = (Integer) oMembers;
          }

          /* Check for, and copy all the household members. */
          for (int i = 1; i <= members; i++) {
            Id<Person> pId = Id.createPersonId(hhId.toString() + "_" + i);
            if (!this.sc.getPopulation().getPersons().containsKey(pId)) {
              LOG.warn(
                  "Household "
                      + hhId.toString()
                      + " reported "
                      + members
                      + " members; cannot find "
                      + pId.toString());
              membersUnaccountedFor++;
            } else {
              /* Link the person to the household. */
              newSc.getHouseholds().getHouseholds().get(hhId).getMemberIds().add(pId);

              /* Copy the person, whether they have a plan or not. */
              newSc.getPopulation().addPerson(this.sc.getPopulation().getPersons().get(pId));

              /* Copy all the person's attributes. */
              for (String attr : getPersonAttributes()) {
                Object o =
                    this.sc
                        .getPopulation()
                        .getPersonAttributes()
                        .getAttribute(pId.toString(), attr);
                newSc.getPopulation().getPersonAttributes().putAttribute(pId.toString(), attr, o);
              }

              membersAccountedFor++;
            }
          }
        } else {
          /* Ignore the household. */
        }
      }
    }
    LOG.info("Done filtering scenario.");
    LOG.warn("Number of household members accounted for: " + membersAccountedFor);
    LOG.warn("Number of household members unaccounted for: " + membersUnaccountedFor);

    /* Check the number of members with and without plans. */
    int withPlans = 0;
    int withoutPlans = 0;
    for (Person p : newSc.getPopulation().getPersons().values()) {
      if (p.getPlans().size() == 0) {
        withoutPlans++;
      } else {
        withPlans++;
      }
    }
    LOG.info("   Number of persons with plans: " + withoutPlans);
    LOG.info("Number of persons without plans: " + withPlans);

    return newSc;
  }
  public void testTransitRouteCopy() {
    Config config = super.loadConfig(null);
    config.scenario().setUseTransit(true);
    config.scenario().setUseVehicles(true);
    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(config);

    Id<Node> nodeId1 = Id.create("1", Node.class);
    Id<Node> nodeId2 = Id.create("2", Node.class);
    Id<Node> nodeId3 = Id.create("3", Node.class);
    Id<Link> linkId1 = Id.create("1", Link.class);
    Id<Link> linkId2 = Id.create("2", Link.class);

    // build network
    Network network = scenario.getNetwork();
    NetworkFactory nBuilder = network.getFactory();
    Node node1 = nBuilder.createNode(nodeId1, scenario.createCoord(0, 0));
    Node node2 = nBuilder.createNode(nodeId2, scenario.createCoord(1000, 0));
    Node node3 = nBuilder.createNode(nodeId3, scenario.createCoord(2000, 0));
    network.addNode(node1);
    network.addNode(node2);
    network.addNode(node3);
    Link link1 = nBuilder.createLink(linkId1, node1, node2);
    Link link2 = nBuilder.createLink(linkId2, node2, node3);
    network.addLink(link1);
    network.addLink(link2);

    // build schedule
    TransitSchedule schedule = scenario.getTransitSchedule();
    TransitScheduleFactory sBuilder = schedule.getFactory();

    TransitStopFacility stopF1 =
        sBuilder.createTransitStopFacility(
            Id.create("1", TransitStopFacility.class), scenario.createCoord(1000.0, 0), false);
    TransitStopFacility stopF2 =
        sBuilder.createTransitStopFacility(
            Id.create("2", TransitStopFacility.class), scenario.createCoord(2000.0, 0), false);
    stopF1.setLinkId(link1.getId());
    stopF2.setLinkId(link2.getId());
    schedule.addStopFacility(stopF1);
    schedule.addStopFacility(stopF2);

    TransitLine tLine1 = sBuilder.createTransitLine(Id.create("1", TransitLine.class));

    TransitRouteStop stop1 = sBuilder.createTransitRouteStop(stopF1, 0, 0);
    TransitRouteStop stop2 = sBuilder.createTransitRouteStop(stopF2, 100, 100);
    ArrayList<TransitRouteStop> stops = new ArrayList<TransitRouteStop>();
    stops.add(stop1);
    stops.add(stop2);

    NetworkRoute netRoute = new LinkNetworkRouteImpl(link1.getId(), link2.getId());
    netRoute.setLinkIds(link1.getId(), Collections.<Id<Link>>emptyList(), link2.getId());
    TransitRoute tRoute1 =
        sBuilder.createTransitRoute(Id.create("1", TransitRoute.class), netRoute, stops, "bus");

    tRoute1.addDeparture(sBuilder.createDeparture(Id.create("1", Departure.class), 7.0 * 3600));
    tLine1.addRoute(tRoute1);
    schedule.addTransitLine(tLine1);

    // build vehicles
    new CreateVehiclesForSchedule(schedule, scenario.getVehicles()).run();

    // build population
    Population population = scenario.getPopulation();
    PopulationFactory pBuilder = population.getFactory();
    Person person1 = pBuilder.createPerson(Id.create("1", Person.class));
    Plan plan = pBuilder.createPlan();
    Activity homeAct = pBuilder.createActivityFromLinkId("h", linkId1);
    homeAct.setEndTime(7.0 * 3600);
    plan.addActivity(homeAct);
    Leg leg = pBuilder.createLeg(TransportMode.pt);
    ExperimentalTransitRoute tRoute = new ExperimentalTransitRoute(stopF1, tLine1, tRoute1, stopF2);
    leg.setRoute(tRoute);
    plan.addLeg(leg);
    plan.addActivity(pBuilder.createActivityFromLinkId("w", linkId2));
    person1.addPlan(plan);
    population.addPerson(person1);

    // prepare config
    config.controler().setFirstIteration(0);
    config.controler().setLastIteration(1);

    ActivityParams params = new ActivityParams("h");
    params.setTypicalDuration(16.0 * 3600);
    config.planCalcScore().addActivityParams(params);
    params = new ActivityParams("w");
    params.setTypicalDuration(8.0 * 3600);
    config.planCalcScore().addActivityParams(params);

    StrategySettings tam = new StrategySettings(Id.create(1, StrategySettings.class));
    tam.setStrategyName("TimeAllocationMutator");
    tam.setWeight(1.0);
    config.strategy().addStrategySettings(tam);

    // run
    Controler controler = new Controler(scenario);
    controler.getConfig().controler().setWriteEventsInterval(0);
    controler.setCreateGraphs(false);
    controler.run();

    // checks
    assertEquals(1, population.getPersons().size());
    assertEquals(2, person1.getPlans().size());
    assertEquals(
        ExperimentalTransitRoute.class,
        ((Leg) person1.getPlans().get(0).getPlanElements().get(1)).getRoute().getClass());
    assertEquals(
        ExperimentalTransitRoute.class,
        ((Leg) person1.getPlans().get(1).getPlanElements().get(1)).getRoute().getClass());
  }
Exemplo n.º 20
0
  /**
   * @param args
   * @throws FactoryException
   */
  public static void main(String[] args) throws FactoryException {
    String popFile = args[0];
    String facFile = args[1];
    String netFile = args[2];
    int n = Integer.parseInt(args[3]);
    String outDir = args[4];

    Logger logger = Logger.getLogger(DemoScenario.class);

    MathTransform transform = CRS.findMathTransform(CRSUtils.getCRS(31467), CRSUtils.getCRS(3857));

    Config config = ConfigUtils.createConfig();
    Scenario scenario = ScenarioUtils.createScenario(config);
    /*
     * remove foreign persons and extract subsample
     */
    logger.info("Loading persons...");
    MatsimPopulationReader pReader = new MatsimPopulationReader(scenario);
    pReader.readFile(popFile);
    logger.info("Done.");

    logger.info("Removing foreign persons...");
    Set<Id<Person>> remove = new HashSet<>();
    for (Id<Person> id : scenario.getPopulation().getPersons().keySet()) {
      if (id.toString().startsWith("foreign")) {
        remove.add(id);
      }
    }

    int cnt = 0;
    for (Id<Person> id : remove) {
      if (scenario.getPopulation().getPersons().remove(id) != null) {
        cnt++;
      }
    }
    logger.info(String.format("Done. Removed %s foreign persons.", cnt));

    logger.info("Drawing population subsample...");
    List<Person> persons = new ArrayList<>(scenario.getPopulation().getPersons().values());
    Collections.shuffle(persons);
    Population population = PopulationUtils.createPopulation(config);
    cnt = 0;
    for (int i = 0; i < n; i++) {
      population.addPerson(persons.get(i));
    }
    logger.info("Done.");

    logger.info("Bluring activity end times...");
    Random random = new XORShiftRandom();
    for (Person person : population.getPersons().values()) {
      for (Plan plan : person.getPlans()) {
        for (int i = 0; i < plan.getPlanElements().size(); i += 2) {
          Activity act = (Activity) plan.getPlanElements().get(i);
          double endTim = act.getEndTime() - 15 * 60 + (random.nextDouble() * 30 * 60);
          act.setEndTime(endTim);
          double startTim = act.getStartTime() - 15 * 60 + (random.nextDouble() * 30 * 60);
          act.setStartTime(startTim);
        }
      }
    }
    logger.info("Done.");

    logger.info("Writing population...");
    PopulationWriter pWriter = new PopulationWriter(population);
    pWriter.write(String.format("%s/plans.xml.gz", outDir));
    logger.info("Done.");
    /*
     * filter only used facilities
     */
    logger.info("Loading facilities...");
    MatsimFacilitiesReader fReader = new MatsimFacilitiesReader(scenario);
    fReader.readFile(facFile);
    logger.info("Done.");

    logger.info("Removing unsused facilities...");
    Set<Id<ActivityFacility>> unused =
        new HashSet<>(scenario.getActivityFacilities().getFacilities().keySet());
    for (Person person : population.getPersons().values()) {
      for (Plan plan : person.getPlans()) {
        for (int i = 0; i < plan.getPlanElements().size(); i += 2) {
          Activity act = (Activity) plan.getPlanElements().get(i);
          unused.remove(act.getFacilityId());
        }
      }
    }
    logger.info("Done.");

    logger.info("Transforming facility coordinates...");
    for (ActivityFacility fac : scenario.getActivityFacilities().getFacilities().values()) {
      double[] points = new double[] {fac.getCoord().getX(), fac.getCoord().getY()};
      try {
        transform.transform(points, 0, points, 0, 1);
      } catch (TransformException e) {
        e.printStackTrace();
      }

      ((ActivityFacilityImpl) fac).setCoord(new Coord(points[0], points[1]));
    }
    logger.info("Done.");

    logger.info("Writing facilities...");
    FacilitiesWriter fWrtier = new FacilitiesWriter(scenario.getActivityFacilities());
    fWrtier.write(String.format("%s/facilities.xml.gz", outDir));
    logger.info("Done.");
    /*
     * clean network from foreign links
     */
    logger.info("Loading network...");
    MatsimNetworkReader nReader = new MatsimNetworkReader(scenario);
    nReader.readFile(netFile);
    logger.info("Done.");

    logger.info("Removing foreign links...");
    Set<Id<Link>> linksRemove = new HashSet<>();
    for (Id<Link> id : scenario.getNetwork().getLinks().keySet()) {
      if (id.toString().contains(".l")) {
        linksRemove.add(id);
      }
    }

    for (Id<Link> id : linksRemove) {
      scenario.getNetwork().removeLink(id);
    }
    logger.info("Done.");

    logger.info("Removing foreign nodes...");
    Set<Id<Node>> nodesRemove = new HashSet<>();
    for (Id<Node> id : scenario.getNetwork().getNodes().keySet()) {
      if (id.toString().contains(".n")) {
        nodesRemove.add(id);
      }
    }

    for (Id<Node> id : nodesRemove) {
      scenario.getNetwork().removeNode(id);
    }
    logger.info("Done.");

    logger.info("Transforming node coordinates...");
    for (Node node : scenario.getNetwork().getNodes().values()) {
      double[] points = new double[] {node.getCoord().getX(), node.getCoord().getY()};
      try {
        transform.transform(points, 0, points, 0, 1);
      } catch (TransformException e) {
        e.printStackTrace();
      }

      ((NodeImpl) node).setCoord(new Coord(points[0], points[1]));
    }
    logger.info("Done.");

    logger.info("Writing network...");
    NetworkWriter nWriter = new NetworkWriter(scenario.getNetwork());
    nWriter.write(String.format("%s/network.xml.gz", outDir));
    logger.info("Done.");
  }
Exemplo n.º 21
0
  @Override
  public void run() {
    List<SocialVertex> egos = stateService.get();
    /*
     * get new and old plans
     */
    List<Plan> newState = new ArrayList<Plan>(egos.size());
    List<Plan> oldState = new ArrayList<Plan>(egos.size());

    for (SocialVertex ego : egos) {
      Person person = ego.getPerson().getPerson();
      if (person.getPlans().get(0).isSelected()) {
        newState.add(person.getPlans().get(0));
        oldState.add(person.getPlans().get(1));
      } else {
        newState.add(person.getPlans().get(1));
        oldState.add(person.getPlans().get(0));
      }
    }
    /*
     * get scores
     */
    double newScore = 0;
    for (int i = 0; i < newState.size(); i++) newScore += newState.get(i).getScore();

    double oldScore = 0;
    for (int i = 0; i < oldState.size(); i++) oldScore += oldState.get(i).getScore();
    /*
     * calculate transition probability
     */
    double delta = oldScore - newScore;
    double pi = 1 / (1 + Math.exp(delta));

    //		piSum += pi;
    /*
     * accept/reject
     */
    List<Plan> remove = null;
    if (random.nextDouble() < pi) {
      /*
       * accept state
       */
      remove = oldState;
      //			acceptedStates++;
      accept = true;
    } else {
      /*
       * reject state
       */
      remove = newState;
      accept = false;
    }
    /*
     * remove plans
     */
    for (int i = 0; i < remove.size(); i++) {
      Plan plan = remove.get(i);
      Person person = plan.getPerson();
      person.getPlans().remove(plan);
      person.setSelectedPlan(person.getPlans().get(0));
    }
  }
Exemplo n.º 22
0
 @Override
 public List<? extends Plan> getPlans() {
   return delegate.getPlans();
 }
Exemplo n.º 23
0
  public void run() throws IOException {

    /*
     * LOAD CONFIGURATION AND SCENARIO
     */
    final Config config = ConfigUtils.loadConfig(this.configFileName);
    final Scenario scenario = ScenarioUtils.loadScenario(config);
    scenario.getPopulation().getPersons().clear();

    /*
     * OVERLOAD POPULATION
     */
    final MatsimPopulationReader popReader = new MatsimPopulationReader(scenario);
    popReader.readFile(this.populationFileName);
    this.population = scenario.getPopulation();

    /*
     * PREPARE WRITING
     */
    final PrintWriter matlabWriter = new PrintWriter(this.matlabFileName);

    /*
     * ITERATE THROUGH POPULATION AND WRITE OUT PROPERTIES
     */
    for (Person person : this.population.getPersons().values()) {

      final Activity home = this.firstActivity(person, "h");
      final Activity work = this.firstActivity(person, "w");

      this.computeTravelStatistics(person);

      matlabWriter.print(person.getId() + ",");
      if (home != null) {
        matlabWriter.print(home.getCoord().getX() + ",");
        matlabWriter.print(home.getCoord().getY() + ",");
      } else {
        matlabWriter.print("NaN,NaN,");
      }

      if (work != null) {
        matlabWriter.print(work.getCoord().getX() + ",");
        matlabWriter.print(work.getCoord().getY() + ",");
      } else {
        matlabWriter.print("NaN,NaN,");
      }
      matlabWriter.print((work != null) ? "1," : "0,");
      if (person.getPlans() == null) {
        matlabWriter.print("0,");
      } else {
        matlabWriter.print(person.getPlans().size() + ",");
      }

      if (person.getSelectedPlan() == null || person.getSelectedPlan().getScore() == null) {
        matlabWriter.print("NaN,");
      } else {
        matlabWriter.print(person.getSelectedPlan().getScore() + ",");
      }

      if (person.getSelectedPlan() == null) {
        matlabWriter.print("NaN,NaN");
      } else {
        matlabWriter.print(this.totalTime + ",");
        matlabWriter.print(this.totalDist);
      }
      matlabWriter.println();
    }

    /*
     * FINALIZE WRITING
     */
    matlabWriter.flush();
    matlabWriter.close();
  }