Пример #1
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;
          }
        }
      }
    }
  }
  @Override
  public void handleAgentLeg(AgentWithParking aem) {
    Id personId = aem.getPerson().getId();

    boolean endOfLegReached = aem.endOfLegReached();

    if (endOfLegReached) {
      if (!parkingFound.contains(personId)) {
        parkingFound.add(personId);

        DebugLib.traceAgent(personId);

        Activity nextAct =
            (Activity)
                aem.getPerson()
                    .getSelectedPlan()
                    .getPlanElements()
                    .get(aem.getPlanElementIndex() + 3);

        Id parkingId =
            AgentWithParking.parkingManager.getFreePrivateParking(
                nextAct.getFacilityId(), nextAct.getType());

        if (isInvalidParking(aem, parkingId)) {
          parkingId =
              AgentWithParking.parkingManager.getClosestParkingFacilityNotOnLink(
                  nextAct.getCoord(), aem.getInvalidLinkForParking());
        }

        parkVehicleAndLogSearchTime(aem, personId, parkingId);
      }
    } else {
      super.handleAgentLeg(aem);
    }
  }
Пример #3
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);
  }
Пример #4
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);
   }
 }
  private boolean judgeByBeeline(final Activity fromAct, final Activity toAct) {
    if (this.aoiCenter == null) {
      // we cannot use the bee-line decision if we don't know the alternative aoi-center
      return false;
    }
    Coord fromCoord = fromAct.getCoord();
    Coord toCoord = toAct.getCoord();

    if (fromCoord == null) {
      fromCoord = this.network.getLinks().get(fromAct.getLinkId()).getCoord();
    }
    if (toCoord == null) {
      toCoord = this.network.getLinks().get(toAct.getLinkId()).getCoord();
    }

    return (CoordUtils.distancePointLinesegment(fromCoord, toCoord, this.aoiCenter)
        <= this.aoiRadius);
  }
Пример #6
0
  private void enrichPlanByReturnLegAndActivity(Activity last, Plan plan, String mode, int maxDur) {

    double lastEnd = 0.0;
    if (last.getEndTime() != Time.UNDEFINED_TIME) {
      lastEnd = last.getEndTime();
    }
    String newMode = enrichPlanBySingleLegAndActivity(last.getCoord(), plan, mode, maxDur, true);
    Leg returnTrip = scenario.getPopulation().getFactory().createLeg(newMode);
    plan.addLeg(returnTrip);
    Activity home =
        scenario
            .getPopulation()
            .getFactory()
            .createActivityFromCoord(last.getType(), last.getCoord());
    if (lastEnd != 0.0) {
      home.setEndTime(lastEnd);
    }
    plan.addActivity(home);
  }
 private void writeAct(final Activity act, final BufferedWriter out) throws IOException {
   out.write("\t\t\t<act type=\"");
   out.write(act.getType());
   out.write("\"");
   if (act.getLinkId() != null) {
     out.write(" link=\"");
     out.write(act.getLinkId().toString());
     out.write("\"");
   }
   if (act.getFacilityId() != null) {
     out.write(" facility=\"");
     out.write(act.getFacilityId().toString());
     out.write("\"");
   }
   if (act.getCoord() != null) {
     final Coord coord = coordinateTransformation.transform(act.getCoord());
     out.write(" x=\"");
     out.write(Double.toString(coord.getX()));
     out.write("\" y=\"");
     out.write(Double.toString(coord.getY()));
     out.write("\"");
   }
   if (act.getStartTime() != Time.UNDEFINED_TIME) {
     out.write(" start_time=\"");
     out.write(Time.writeTime(act.getStartTime()));
     out.write("\"");
   }
   if (act != null) {
     Activity a = act;
     if (a.getMaximumDuration() != Time.UNDEFINED_TIME) {
       out.write(" max_dur=\"");
       out.write(Time.writeTime(a.getMaximumDuration()));
       out.write("\"");
     }
   }
   if (act.getEndTime() != Time.UNDEFINED_TIME) {
     out.write(" end_time=\"");
     out.write(Time.writeTime(act.getEndTime()));
     out.write("\"");
   }
   out.write(" />\n");
 }
Пример #8
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;
  }
Пример #9
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);
  }
Пример #10
0
 public static boolean isInsideCordon(Activity act) {
   return isInsideCordon(act.getCoord());
 }
Пример #11
0
  public static final QuadTree<PersonPrimaryActivity> createPersonPrimaryActivityQuadTree(
      Controler controler) {
    int i;
    double minx = (1.0D / 0.0D);
    double miny = (1.0D / 0.0D);
    double maxx = (-1.0D / 0.0D);
    double maxy = (-1.0D / 0.0D);

    for (ActivityFacility f :
        controler.getScenario().getActivityFacilities().getFacilities().values()) {
      if (f.getCoord().getX() < minx) minx = f.getCoord().getX();
      if (f.getCoord().getY() < miny) miny = f.getCoord().getY();
      if (f.getCoord().getX() > maxx) maxx = f.getCoord().getX();
      if (f.getCoord().getY() <= maxy) continue;
      maxy = f.getCoord().getY();
    }
    minx -= 1.0D;
    miny -= 1.0D;
    maxx += 1.0D;
    maxy += 1.0D;
    QuadTree<PersonPrimaryActivity> personPrimaryActivityQuadTree =
        new QuadTree<PersonPrimaryActivity>(minx, miny, maxx, maxy);
    i = 0;
    for (Person p : controler.getScenario().getPopulation().getPersons().values()) {
      int primaryActivityCount = 0;
      boolean hasHome = false;
      boolean hasWork = false;
      boolean hasEducation = false;
      // boolean hasShop = false;

      if (p.getSelectedPlan().getPlanElements().toString().contains("type=shopgrocery")) {
        for (PlanElement pe : p.getSelectedPlan().getPlanElements()) {
          if (pe instanceof Activity) {
            Coord c;
            Id<Link> activityLink;
            int ppaId;
            PersonPrimaryActivity ppa;
            Activity act = (Activity) pe;

            if (act.getType().equals("home")) {
              if (!(hasHome)) {
                c =
                    ((ActivityFacility)
                            controler
                                .getScenario()
                                .getActivityFacilities()
                                .getFacilities()
                                .get(act.getFacilityId()))
                        .getCoord();
                activityLink =
                    (NetworkUtils.getNearestLink(
                            ((NetworkImpl) controler.getScenario().getNetwork()), act.getCoord()))
                        .getId();
                // activityLink =
                // (IdImpl)((ActivityFacility)controler.getFacilities().getFacilities().get(act.getFacilityId())).getLinkId();
                ppaId = Integer.parseInt(p.getId().toString()) * 10 + primaryActivityCount;
                ppa = new PersonPrimaryActivity(act.getType(), ppaId, p.getId(), activityLink);
                personPrimaryActivityQuadTree.put(c.getX(), c.getY(), ppa);

                hasHome = true;
                ++primaryActivityCount;
              }
            } else if (act.getType().equals("work")) {
              if (!(hasWork)) {
                c =
                    ((ActivityFacility)
                            controler
                                .getScenario()
                                .getActivityFacilities()
                                .getFacilities()
                                .get(act.getFacilityId()))
                        .getCoord();
                activityLink =
                    ((ActivityFacility)
                            controler
                                .getScenario()
                                .getActivityFacilities()
                                .getFacilities()
                                .get(act.getFacilityId()))
                        .getLinkId();
                ppaId = Integer.parseInt(p.getId().toString()) * 10 + primaryActivityCount;
                ppa = new PersonPrimaryActivity(act.getType(), ppaId, p.getId(), activityLink);
                personPrimaryActivityQuadTree.put(c.getX(), c.getY(), ppa);

                hasWork = true;
                ++primaryActivityCount;
              }
            } else {
              if ((!(act.getType().equals("education"))) || (hasEducation)) continue;
              c =
                  ((ActivityFacility)
                          controler
                              .getScenario()
                              .getActivityFacilities()
                              .getFacilities()
                              .get(act.getFacilityId()))
                      .getCoord();
              activityLink =
                  ((ActivityFacility)
                          controler
                              .getScenario()
                              .getActivityFacilities()
                              .getFacilities()
                              .get(act.getFacilityId()))
                      .getLinkId();
              log.info("Act Link " + activityLink);
              ppaId = Integer.parseInt(p.getId().toString()) * 10 + primaryActivityCount;
              ppa = new PersonPrimaryActivity(act.getType(), ppaId, p.getId(), activityLink);
              personPrimaryActivityQuadTree.put(c.getX(), c.getY(), ppa);

              hasEducation = true;
              ++primaryActivityCount;
            }
          }
        }

        i += primaryActivityCount;
      }

      // log.info("Global Primary activity count = " + i);
    }

    return personPrimaryActivityQuadTree;
  }
Пример #12
0
  public void cleanUpScenario(Scenario sc) {
    LOG.info("Cleaning up scenario...");
    /* TODO Still need to figure out what cleaning up must happen. */

    /* Search for location-less activities, and sample its locations from
     * the kernel density estimates. */
    LOG.info("Sampling locations for those without known zones...");
    int locationsFixed = 0;
    int knownLocations = 0;
    for (Person person : sc.getPopulation().getPersons().values()) {
      Plan plan = person.getSelectedPlan();
      if (plan != null) {
        for (PlanElement pe : plan.getPlanElements()) {
          if (pe instanceof Activity) {
            Activity act = (Activity) pe;
            Coord coord = act.getCoord();
            if (coord.getX() == 0.0 || coord.getY() == 0.0) {
              ((ActivityImpl) act).setCoord(sampleActivityLocation(act.getType()));
              locationsFixed++;
            } else {
              knownLocations++;
            }
          }
        }
      }
    }
    LOG.info("Number of known locations: " + knownLocations);
    LOG.info("Number of locations fixed: " + locationsFixed);
    LOG.info("Done sampling locations.");

    /* Ensure each activity, except the last, has both a start and end time. */
    LOG.info("Ensure each activity has an end time...");
    for (Person person : sc.getPopulation().getPersons().values()) {
      Plan plan = person.getSelectedPlan();
      if (plan != null) {
        List<PlanElement> list = plan.getPlanElements();
        for (int i = 0; i < list.size() - 2; i += 2) {
          PlanElement pe = list.get(i);
          if (pe instanceof Activity) {
            Activity act = (Activity) pe;
            double endTime = act.getEndTime();
            if (endTime < 0.0) {
              double legStart = ((Leg) list.get(i + 1)).getDepartureTime();
              act.setEndTime(legStart);
            }
          } else {
            LOG.warn("Every second PlanElement should be of type 'Activity'.");
          }
        }
      }
    }
    LOG.info("Done fixing activity end times.");

    /* Ensure that the home location/coordinate for all members in the
     * household are the same for all their "h" activities. */
    LOG.info("Fix home locations for each household member. ");
    int homeLocationsFixed = 0;
    int nonTravellers = 0;
    for (Household hh : sc.getHouseholds().getHouseholds().values()) {
      Object o =
          sc.getHouseholds()
              .getHouseholdAttributes()
              .getAttribute(hh.getId().toString(), "transportZone");
      if (o instanceof String) {
        String zoneId = (String) o;
        Coord homeCoord = null;
        if (zoneId != null && !zoneId.equalsIgnoreCase("")) {
          /* There is known home zone. */
          Point p = this.zoneMap.get(zoneId).sampleRandomInteriorPoint();
          homeCoord = CoordUtils.createCoord(p.getX(), p.getY());
        } else {
          /* There is no transport zone. */
          homeCoord = sampleActivityLocation("h");
        }

        /* Now assign the home coordinate to ALL home activities for
         * all members of the household. */
        for (Id<Person> id : hh.getMemberIds()) {
          Person person = sc.getPopulation().getPersons().get(id);
          Plan plan = person.getSelectedPlan();
          if (plan != null) {
            for (PlanElement pe : person.getSelectedPlan().getPlanElements()) {
              if (pe instanceof ActivityImpl) {
                ActivityImpl act = (ActivityImpl) pe;
                if (act.getType().equalsIgnoreCase("h")) {
                  act.setCoord(homeCoord);
                  homeLocationsFixed++;
                }
              }
            }
          } else {
            /* The member does not have ANY plan. We 'fix' this by
             * adding aPlan with a single home-based activity for
             * which not times are specified. */
            Plan stayHomePlan = sc.getPopulation().getFactory().createPlan();
            Activity act = sc.getPopulation().getFactory().createActivityFromCoord("h", homeCoord);
            stayHomePlan.addActivity(act);
            person.addPlan(stayHomePlan);
            nonTravellers++;
          }
        }
      }
    }
    LOG.info("Total number of home locations fixed: " + homeLocationsFixed);
    LOG.info("      Total number of non-travellers: " + nonTravellers);
    LOG.info("Done fixing home locations.");

    /* TODO Check what to do with those household members that are not
     * travelling. Are they just given a single 'h' activities, and
     * left at that? */

    /* Look for erroneous activity times that can/should be fixed in
     * the raw travel diary input data. This will typically include very
     * long activity times or leg durations. */
    LOG.info("Checking leg durations:");
    int remainingLegOddities = 0;
    double legDurationThreshold = Time.parseTime("03:00:00");
    for (Person p : sc.getPopulation().getPersons().values()) {
      Plan plan = p.getSelectedPlan();
      if (plan != null) {
        for (PlanElement pe : plan.getPlanElements()) {
          if (pe instanceof Leg) {
            double duration = ((Leg) pe).getTravelTime();
            if (duration < 0 || duration > legDurationThreshold) {
              LOG.warn(
                  " -> Odd leg duration: "
                      + p.getId().toString()
                      + " ("
                      + Time.writeTime(duration)
                      + ")");
              remainingLegOddities++;
            }
          }
        }
      }
    }
    LOG.info("Done checking leg durations. (" + remainingLegOddities + " remain)");

    /* Parse the activity duration times in an effort to pick up
     * erroneous travel time data that results in negative activity
     * durations. Then fix in input data. */
    LOG.info("Checking activity durations (from leg times):");
    int remainingActivityOddities = 0;
    double activityDurationThreshold = Time.parseTime("16:00:00");
    for (Person p : sc.getPopulation().getPersons().values()) {
      Plan plan = p.getSelectedPlan();
      if (plan != null) {
        for (int i = 1; i < plan.getPlanElements().size() - 2; i += 2) {
          PlanElement pe1 = plan.getPlanElements().get(i);
          PlanElement pe2 = plan.getPlanElements().get(i + 2);
          if (pe1 instanceof Leg && pe2 instanceof Leg) {
            Leg l1 = (Leg) pe1;
            Leg l2 = (Leg) pe2;
            double act = l2.getDepartureTime() - (l1.getDepartureTime() + l1.getTravelTime());
            if (act < 0 || act > activityDurationThreshold) {
              LOG.warn(
                  " -> Odd activity duration: "
                      + p.getId().toString()
                      + " ("
                      + Time.writeTime(act)
                      + ")");
              remainingActivityOddities++;
            }
          } else {
            LOG.error("PlanElements not of type Leg!!");
            LOG.error("   pe1: " + pe1.getClass().toString());
            LOG.error("   pe2: " + pe2.getClass().toString());
          }
        }
      }
    }
    LOG.info("Done checking activity durations. (" + remainingActivityOddities + " remain)");

    /* TODO Fix plans for night workers. They typically start with 'h',
     * but should actually start with 'w'. */

    /* TODO Consider what to do with repeating activities, especially
     * consecutive home activities. */

    /* Convert all activity locations to a projected coordinate system. */
    LOG.info("Converting all activity locations to EPSG:3857...");
    CoordinateTransformation ct =
        TransformationFactory.getCoordinateTransformation("WGS84", "EPSG:3857");
    for (Person person : sc.getPopulation().getPersons().values()) {
      Plan plan = person.getSelectedPlan();
      if (plan != null) {
        for (PlanElement pe : plan.getPlanElements()) {
          if (pe instanceof Activity) {
            Activity act = (Activity) pe;
            ((ActivityImpl) act).setCoord(ct.transform(act.getCoord()));
          }
        }
      }
    }
    LOG.info("Done converting activity locations.");

    LOG.info("Done cleaning up scenario.");
  }
Пример #13
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();
  }