public static void main(String[] args) {

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

    ObjectAttributes bla = new ObjectAttributes();

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

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

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

    ObjectAttributesXmlWriter betaWriter = new ObjectAttributesXmlWriter(bla);
    betaWriter.writeFile(args[3]);
  }
Esempio n. 2
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("");
  }
 public void printResults(CongestionAnalysisHandler congestionHandler, Scenario scenario) {
   System.out.println("isCaughtCongestionEvent: " + congestionHandler.isCaughtCongestionEvent());
   System.out.println("totalDelay: " + congestionHandler.getTotalDelay());
   for (Person person : scenario.getPopulation().getPersons().values()) {
     System.out.println("Person Id : " + person.getId());
     System.out.println(
         "causedDelay: "
             + congestionHandler.getPersonId2tripNumber2causedDelay().get(person.getId()));
     System.out.println(
         "affectedDelay: "
             + congestionHandler.getPersonId2tripNumber2affectedDelay().get(person.getId()));
   }
 }
Esempio n. 4
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);
  }
Esempio n. 5
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;
 }
Esempio n. 6
0
  private void createOneTransitTrucker(
      int i, Coord origin, Coord destination, String mode, String fromToPrefix) {
    Id<Person> personId = Id.createPersonId(fromToPrefix + i);
    Person person = scenario.getPopulation().getFactory().createPerson(personId);

    Plan plan = scenario.getPopulation().getFactory().createPlan();

    Activity cargo = scenario.getPopulation().getFactory().createActivityFromCoord("cargo", origin);
    int rand = random.nextInt(18 * 60 * 60) + 1;
    cargo.setEndTime(rand);
    plan.addActivity(cargo);

    Leg outboundTrip = scenario.getPopulation().getFactory().createLeg(mode);
    plan.addLeg(outboundTrip);

    Activity cargod =
        scenario.getPopulation().getFactory().createActivityFromCoord("cargoD", destination);
    cargod.setMaximumDuration(3600);
    plan.addActivity(cargod);
    Leg inBundTrip = scenario.getPopulation().getFactory().createLeg(mode);
    plan.addLeg(inBundTrip);

    Activity cargo2 =
        scenario.getPopulation().getFactory().createActivityFromCoord("cargo", origin);
    plan.addActivity(cargo2);

    person.addPlan(plan);
    scenario
        .getPopulation()
        .getPersonAttributes()
        .putAttribute(person.getId().toString(), "subpopulation", "noRep");
    scenario.getPopulation().addPerson(person);
  }
Esempio n. 7
0
  private static void getPersonsWithNegativeScores() {

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

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

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

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

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

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

    try {

      for (Person person : plansWithNegativeScores) {

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

        writer.newLine();
      }

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

    } catch (IOException e) {

      e.printStackTrace();
    }
  }
Esempio n. 8
0
  private void createOneVWTrucker(
      int i, Coord origin, Coord destination, String mode, String fromToPrefix) {
    Id<Person> personId = Id.createPersonId(fromToPrefix + i);
    Person person = scenario.getPopulation().getFactory().createPerson(personId);

    Plan plan = scenario.getPopulation().getFactory().createPlan();

    Activity source =
        scenario.getPopulation().getFactory().createActivityFromCoord("source", origin);
    double rand = random.nextDouble() * 18 * 60 * 60;
    source.setEndTime(rand);
    plan.addActivity(source);

    Leg outboundTrip = scenario.getPopulation().getFactory().createLeg(mode);
    plan.addLeg(outboundTrip);

    Activity delivery =
        scenario.getPopulation().getFactory().createActivityFromCoord("delivery", destination);
    delivery.setMaximumDuration(3600);
    plan.addActivity(delivery);

    Leg inboundTrip = scenario.getPopulation().getFactory().createLeg(mode);
    plan.addLeg(inboundTrip);
    Activity source2 =
        scenario.getPopulation().getFactory().createActivityFromCoord("source", origin);
    plan.addActivity(source2);

    person.addPlan(plan);
    scenario
        .getPopulation()
        .getPersonAttributes()
        .putAttribute(person.getId().toString(), "subpopulation", "noRep");

    scenario.getPopulation().addPerson(person);
  }
Esempio n. 9
0
  public double getParkingWalkBeta(Person person, double activityDurationInSeconds) {
    Id personId = person.getId();
    Parser parser = null;
    if (!parkingWalkBetaCache.containsKey(personId)) {
      Parser pTmp = new Parser(parkingWalkBeta);
      PersonImpl persImpl = (PersonImpl) person;

      int isMale = 1;
      if (persImpl.getSex() != null) {
        isMale = !persImpl.getSex().contains("f") ? 1 : 0;
      }

      pTmp.setVariable("isMale", isMale);

      int age = persImpl.getAge();

      pTmp.setVariable("ageInYears", age);
      parkingWalkBetaCache.put(personId, pTmp);
    }
    parser = parkingWalkBetaCache.get(personId);

    parser.setVariable("activityDurationInSeconds", activityDurationInSeconds);

    double result = 0;

    try {
      result = parser.parse();
    } catch (SyntaxException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return result;
  }
 private static void startPerson(final Person p, final BufferedWriter out) throws IOException {
   out.write("\t<person id=\"");
   out.write(p.getId().toString());
   out.write("\"");
   if (p != null) {
     Person person = p;
     if (PersonUtils.getSex(person) != null) {
       out.write(" sex=\"");
       out.write(PersonUtils.getSex(person));
       out.write("\"");
     }
     if (PersonUtils.getAge(person) != null) {
       out.write(" age=\"");
       out.write(Integer.toString(PersonUtils.getAge(person)));
       out.write("\"");
     }
     if (PersonUtils.getLicense(person) != null) {
       out.write(" license=\"");
       out.write(PersonUtils.getLicense(person));
       out.write("\"");
     }
     if (PersonUtils.getCarAvail(person) != null) {
       out.write(" car_avail=\"");
       out.write(PersonUtils.getCarAvail(person));
       out.write("\"");
     }
     if (PersonUtils.isEmployed(person) != null) {
       out.write(" employed=\"");
       out.write((PersonUtils.isEmployed(person) ? "yes" : "no"));
       out.write("\"");
     }
   }
   out.write(">\n");
 }
  // calculate generalized travel costs
  @Override
  public double getLinkTravelDisutility(
      final Link link, final double time, final Person person, final Vehicle vehicle) {
    Household household = this.personHouseholdMapping.getHousehold(person.getId());
    Income income = household.getIncome();
    double incomePerDay;
    if (income.getIncomePeriod().equals(IncomePeriod.year)) {
      // assumption: 240 working days per year
      incomePerDay = income.getIncome() / 240;
    } else {
      throw new UnsupportedOperationException("Can't calculate income per day");
    }

    double betaCost = betaIncomeCar / incomePerDay;
    double distance = link.getLength();
    double distanceCost = this.distanceCostFactor * distance;

    double travelTime = this.timeCalculator.getLinkTravelTime(link, time, person, vehicle);

    double generalizedDistanceCost = betaCost * distanceCost;
    double generalizedTravelTimeCost = this.betaTravelTime * travelTime;

    if (this.distanceCostFactor == 0.0) {
      return generalizedTravelTimeCost;
    }

    double generalizedTravelCost = generalizedDistanceCost + generalizedTravelTimeCost;
    return generalizedTravelCost;
  }
Esempio n. 12
0
  public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub

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

    final BufferedWriter outLinkrb = IOUtils.getBufferedWriter(args[2]);
    final BufferedWriter outLinkff = IOUtils.getBufferedWriter(args[3]);

    for (Person p : scenario.getPopulation().getPersons().values()) {
      boolean rb = false;
      boolean ff = false;
      Person pImpl = p;
      Plan plan = p.getSelectedPlan();

      for (PlanElement pe : plan.getPlanElements()) {

        if (pe instanceof Leg) {

          if (((Leg) pe).getMode().equals("cs_fix_gas") && !rb) {
            outLinkrb.write(p.getId().toString() + " ");
            outLinkrb.write(Integer.toString(PersonUtils.getAge(pImpl)) + " ");
            outLinkrb.write(PersonUtils.getSex(pImpl) + " ");
            outLinkrb.write(PersonUtils.getCarAvail(pImpl));
            outLinkrb.newLine();
            rb = true;

          } else if (((Leg) pe).getMode().equals("cs_flex_gas") && !ff) {
            outLinkff.write(p.getId().toString() + " ");
            outLinkff.write(Integer.toString(PersonUtils.getAge(pImpl)) + " ");
            outLinkff.write(PersonUtils.getSex(pImpl) + " ");
            outLinkff.write(PersonUtils.getCarAvail(pImpl));
            outLinkff.newLine();
            ff = true;
          }
        }
      }
    }
    outLinkrb.flush();
    outLinkrb.close();
    outLinkff.flush();
    outLinkff.close();
  }
Esempio n. 13
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());
     }
   }
 }
Esempio n. 14
0
 // does not matter which distribution is chosen here
 private void assignKValuesPersons() {
   for (Person p : this.scenario.getPopulation().getPersons().values()) {
     this.personsKValues.putAttribute(p.getId().toString(), "k", rnd.getUniform(1.0));
   }
   // write person k values
   ObjectAttributesXmlWriter attributesWriter = new ObjectAttributesXmlWriter(this.personsKValues);
   attributesWriter.writeFile(config.controler().getOutputDirectory() + pkValuesFile);
 }
Esempio n. 15
0
  /**
   * Setting up the simulation {@link Scenario}, using a given {@link Config}. In the scenario setup
   * each network link is given both {@code car} and {@code commercial} as mode. Also, each person
   * is assigned a vehicle, which is based on the Gauteng Freeway Improvement Project (GFIP) vehicle
   * toll classes. the following vehicle types are available.
   *
   * <ul>
   *   <li>{@code A2}: Light delivery vehicle with length 7.0m, maximum velocity of 100km/h, and
   *       accounting for 80% of all commercial vehicles;
   *   <li>{@code B}: Short heavy vehicles with length 12.0m, maximum velocity of 90km/h, and
   *       accounting for 15% of all commercial vehicles; and
   *   <li>{@code C}: Long heavy vehicles with length 20.0m, maximum velocity of 90km/h, and
   *       accounting for the remaining 5% of all commercial vehicles.
   * </ul>
   *
   * These vehicle classes are randomly sampled and assigned to the individuals. No cognisance is
   * given to intra- and inter-area traffic (based on the activity chain structure). This
   * <i><b>should</b></i> be refined.
   *
   * @param config typically the {@link Config} resulting from calling the method {@link
   *     #setupConfig(String, Machine)}.
   * @return a scenario in which the network has the necessary {@code commercial} mode; and each
   *     agent has a vehicle with a particular commercial vehicle class.
   */
  public static Scenario setupScenario(Config config) {
    Scenario sc = ScenarioUtils.loadScenario(config);

    /* Ensure that all links take 'commercial' as mode. */
    LOG.warn("Ensuring all links take 'commercial' as mode...");
    Collection<String> modesCollection = Arrays.asList("car", "commercial");
    Set<String> modesSet = new HashSet<>(modesCollection);
    for (Link link : sc.getNetwork().getLinks().values()) {
      link.setAllowedModes(modesSet);
    }
    LOG.warn("Done adding 'commercial' modes.");

    /* Add all VehicleTypes. */
    Vehicles vehicles = sc.getVehicles();
    for (VehicleTypeSA vt : VehicleTypeSA.values()) {
      vehicles.addVehicleType(vt.getVehicleType());
    }

    MatsimRandom.reset(2015093001l);
    for (Person person : sc.getPopulation().getPersons().values()) {
      /* Randomly sample a vehicle type for each person. */
      VehicleType vehicleType = null;
      double r = MatsimRandom.getRandom().nextDouble();
      if (r <= 0.8) {
        vehicleType = VehicleTypeSA.A2.getVehicleType();
      } else if (r <= 0.95) {
        vehicleType = VehicleTypeSA.B.getVehicleType();
      } else {
        vehicleType = VehicleTypeSA.C.getVehicleType();
      }

      Vehicle truck =
          VehicleUtils.getFactory()
              .createVehicle(Id.create(person.getId(), Vehicle.class), vehicleType);
      vehicles.addVehicle(truck);

      /* Link the vehicle type to the person's attributes. */
      sc.getPopulation()
          .getPersonAttributes()
          .putAttribute(person.getId().toString(), "vehicleType", vehicleType.getId().toString());
    }

    return sc;
  }
Esempio n. 16
0
 /**
  * copy the person and the selected plan of the person
  *
  * @param person
  * @return
  */
 public static Person copyPerson(Person person) {
   Person newPerson = PersonImpl.createPerson(person.getId());
   PlanImpl newPlan = new PlanImpl();
   newPlan.copyFrom(person.getSelectedPlan());
   newPlan.setPerson(newPerson);
   newPerson.addPlan(newPlan);
   newPerson.setSelectedPlan(newPlan);
   PersonUtils.removeUnselectedPlans(newPerson);
   return newPerson;
 }
 @Override
 public final void notifyArrivalOnLinkByNonNetworkMode(final Id<Link> linkId) {
   this.currentLinkId = linkId;
   double distance = ((Leg) getCurrentPlanElement()).getRoute().getDistance();
   this.simulation
       .getEventsManager()
       .processEvent(
           new TeleportationArrivalEvent(
               this.simulation.getSimTimer().getTimeOfDay(), person.getId(), distance));
 }
Esempio n. 18
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;
 }
Esempio n. 19
0
  // TODO: in controller, add income to person
  public double getParkingCostBeta(Person person) {
    Id personId = person.getId();
    if (!parkingCostBetaCache.containsKey(personId)) {
      parkingCostBetaParser.setVariable("income", income.get(personId));
      try {
        parkingCostBetaCache.put(personId, parkingCostBetaParser.parse());
      } catch (SyntaxException e) {
        e.printStackTrace();
        DebugLib.stopSystemAndReportInconsistency();
      }
    }

    return parkingCostBetaCache.get(personId);
  }
Esempio n. 20
0
 @Override
 public void run(Person person) {
   Integer p_id = Integer.valueOf(person.getId().toString());
   Coord coord = persons.getPerson(p_id).getHousehold().getCoord();
   ActivityFacility f = this.homeFacQuadTree.get(coord.getX(), coord.getY());
   Plan plan = person.getSelectedPlan();
   for (PlanElement pe : plan.getPlanElements()) {
     if (pe instanceof ActivityImpl) {
       ActivityImpl act = (ActivityImpl) pe;
       if (H.equals(act.getType())) {
         act.setCoord(f.getCoord());
       }
     }
   }
 }
  public static void main(String[] args) {

    String dataPath = "/Volumes/DATA 1 (WD 2 TB)/SimMethanaOutput_120215/";
    String populationFile =
        "/Volumes/DATA 1 (WD 2 TB)/SimMethanaOutput_120215/w8-18_homo/output_plans.xml.gz";
    String individualSelectedScoreFile =
        "/Volumes/DATA 1 (WD 2 TB)/SimMethanaOutput_120215/w8-18_homo/individualSelectedBenefits";

    File directory = new File(dataPath);
    File[] fList = directory.listFiles();

    for (File file : fList) {
      if (file.isDirectory()) {
        HashMap<String, String> scoreMap = new HashMap<String, String>();
        MutableScenario scenario =
            (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());

        System.out.println(file.getAbsolutePath());
        populationFile = file.getAbsolutePath() + "/output_plans.xml.gz";
        individualSelectedScoreFile = file.getAbsolutePath() + "/individualSelectedBenefits.csv";

        new PopulationReaderMatsimV5(scenario).readFile(populationFile);
        System.out.println("   Population size: " + scenario.getPopulation().getPersons().size());

        // Read selected plan score
        System.out.println("   Reading population from: " + populationFile);
        for (Person person : scenario.getPopulation().getPersons().values()) {
          scoreMap.put(person.getId().toString(), person.getSelectedPlan().getScore().toString());
        }

        System.out.println("   Map size: " + scoreMap.size());
        // Write selected plan scores;
        System.out.println(
            "   Writting individial selected plan scores to: " + individualSelectedScoreFile);
        Writer writer = new Writer();
        writer.creteFile(individualSelectedScoreFile);

        for (String personId : scoreMap.keySet()) {
          writer.writeLine(personId + "," + scoreMap.get(personId));
        }

        writer.close();
      }
    }

    System.out.println("Done!");
  }
Esempio n. 22
0
 // Static methods
 public static BasePersonImpl getBasePerson(
     boolean fixedTypes,
     String[] types,
     Person person,
     TripRouter tripRouter,
     ActivityFacilities facilities) {
   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));
   PlanImpl plan = (PlanImpl) person.getSelectedPlan();
   newPerson.addPlan(plan);
   BasePlanImpl.createBasePlan(fixedTypes, types, newPerson, plan, tripRouter, facilities);
   return newPerson;
 }
Esempio n. 23
0
    @Override
    public void run(Person person) {

      Plan selectedPlan = person.getSelectedPlan();

      ArrayList<String> modeChain = new ArrayList<String>();
      for (PlanElement pe : selectedPlan.getPlanElements()) {
        if (pe instanceof Leg) {
          Leg leg = (Leg) pe;
          modeChain.add(leg.getMode());
        }
      }
      String[] candidate = new String[modeChain.size()];
      candidate = modeChain.toArray(candidate);

      MeisterkConfigGroup meisterkConfigGroup = new MeisterkConfigGroup();

      boolean isFeasible =
          PlanAnalyzeTourModeChoiceSet.isModeChainFeasible(
              selectedPlan,
              candidate,
              meisterkConfigGroup.getChainBasedModes(),
              PlanomatConfigGroup.TripStructureAnalysisLayerOption.facility,
              this.facilities,
              this.network);

      if (!isFeasible) {

        logger.info("Agent id: " + person.getId());

        for (PlanElement pe : selectedPlan.getPlanElements()) {

          if (pe instanceof Activity) {
            Activity act = (Activity) pe;
            logger.info("\t" + act.getFacilityId());
          }

          if (pe instanceof Leg) {
            Leg leg = (Leg) pe;
            modeChain.add(leg.getMode());
            logger.info("\t" + leg.getMode());
          }
        }
        this.numInfeasiblePlans++;
      }
    }
Esempio n. 24
0
 @Override
 public void run(Person person) {
   try {
     Plan plan = person.getSelectedPlan();
     this.transitLegsRemover.run(plan);
     //				for (Plan plan : person.getPlans()) {
     Activity prevAct = null;
     for (PlanElement pe : plan.getPlanElements()) {
       if (pe instanceof Activity) {
         Activity act = (Activity) pe;
         if (prevAct != null) {
           List<Leg> legs =
               router.calcRoute(
                   new FakeFacility(prevAct.getCoord()),
                   new FakeFacility(act.getCoord()),
                   act.getStartTime(),
                   person);
           out.write(
               person.getId()
                   + " "
                   + prevAct.getCoord()
                   + " -> "
                   + act.getCoord()
                   + " @ "
                   + Time.writeTime(act.getStartTime())
                   + " :\n");
           if (legs != null) {
             for (Leg l : legs) {
               out.write("  " + l.getMode());
               if (l.getRoute() instanceof ExperimentalTransitRoute) {
                 ExperimentalTransitRoute r = (ExperimentalTransitRoute) l.getRoute();
                 out.write(" " + r.getRouteDescription());
               }
               out.write("\n");
             }
           }
         }
         prevAct = act;
       }
     }
     //				}
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
  @Override
  public double getLinkTravelDisutility(Link link, double time, Person person, Vehicle vehicle) {

    double randomizedTimeDistanceDisutilityForLink =
        this.randomizedTimeDistanceTravelDisutility.getLinkTravelDisutility(
            link, time, person, vehicle);

    double logNormalRnd = 1.;
    if (sigma != 0.) {
      logNormalRnd = (double) person.getCustomAttributes().get("logNormalRnd");
    }

    double linkExpectedTollDisutility =
        calculateExpectedTollDisutility(link.getId(), time, person.getId());
    double randomizedTollDisutility = linkExpectedTollDisutility * logNormalRnd;

    return randomizedTimeDistanceDisutilityForLink + randomizedTollDisutility;
  }
Esempio n. 26
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");
  }
Esempio n. 27
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    MutableScenario scenario1 =
        (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    PopulationReader populationReader1 = new MatsimPopulationReader(scenario1);
    MatsimNetworkReader networkReader1 = new MatsimNetworkReader(scenario1);
    networkReader1.readFile(args[0]);
    populationReader1.readFile(args[1]);

    MutableScenario scenario2 =
        (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    PopulationReader populationReader2 = new MatsimPopulationReader(scenario2);
    MatsimNetworkReader networkReader2 = new MatsimNetworkReader(scenario2);
    networkReader2.readFile(args[0]);
    populationReader2.readFile(args[2]);

    int car = 0;
    int pt = 0;
    int walk = 0;
    int bike = 0;
    for (Person p : scenario2.getPopulation().getPersons().values()) {

      for (PlanElement pe :
          scenario1
              .getPopulation()
              .getPersons()
              .get(p.getId())
              .getSelectedPlan()
              .getPlanElements()) {

        if (pe instanceof Leg) {

          if (((Leg) pe).getMode().equals("car")) car++;
          else if (((Leg) pe).getMode().equals("pt")) pt++;
          else if (((Leg) pe).getMode().equals("walk")) walk++;
          else if (((Leg) pe).getMode().equals("bike")) bike++;
        }
      }
    }

    System.out.println(car + " " + pt + " " + bike + " " + walk);
  }
  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");
  }
  private Person findPerson(int index, Map<Id, Person> addedMembers, Object[] potentialMembers) {

    boolean notFound = true;

    while (notFound) {

      int randomInt = MatsimRandom.getRandom().nextInt(potentialMembers.length);
      Person p = (Person) potentialMembers[randomInt];

      if (!addedMembers.containsKey(p.getId())) {

        switch (index) {
          case 0:
            if (18 <= PersonUtils.getAge(p) && PersonUtils.getAge(p) <= 24) {

              addedMembers.put(p.getId(), p);
              notFound = false;
            }
          case 1:
            if (25 <= PersonUtils.getAge(p) && PersonUtils.getAge(p) <= 34) {

              addedMembers.put(p.getId(), p);
              notFound = false;
            }
          case 2:
            if (35 <= PersonUtils.getAge(p) && PersonUtils.getAge(p) <= 44) {

              addedMembers.put(p.getId(), p);
              notFound = false;
            }
          case 3:
            if (45 <= PersonUtils.getAge(p) && PersonUtils.getAge(p) <= 54) {

              addedMembers.put(p.getId(), p);
              notFound = false;
            }
          case 4:
            if (55 <= PersonUtils.getAge(p) && PersonUtils.getAge(p) <= 64) {

              addedMembers.put(p.getId(), p);
              notFound = false;
            }
        }
      }
    }

    return null;
  }
Esempio n. 30
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");
  }