private void assignDistanceBinsPerPerson(DesiredDurationPerson desiredDurationPerson) { Id personId = desiredDurationPerson.getPersonId(); PlanImpl plan = (PlanImpl) this.plans.getPersons().get(personId).getSelectedPlan(); List<? extends PlanElement> actslegs = plan.getPlanElements(); for (int j = 0; j < actslegs.size(); j = j + 2) { final Activity act = (Activity) actslegs.get(j); if (act.getType().startsWith("leisure")) { final LegImpl leg = (LegImpl) actslegs.get(j + 1); if (leg.getMode().equals(this.mode)) { int randomDistance = (int) Math.round( this.distanceBins.getRandomDistance( desiredDurationPerson.planContainsLeisurePriorToWork())); String newActType = act.getType() + "_" + randomDistance; act.setType(newActType); // minimum duration is 30 min! -> else division by zero while scoring plan.getPerson() .getDesires() .putActivityDuration( newActType, Math.max(30 * 60, desiredDurationPerson.getDuration())); // for plot this.durationDistanceBins.addVal(desiredDurationPerson.getDuration(), randomDistance); } } } }
private Collection<FolderType> getActivities() throws IOException { // this.networkLinkStyle = this.styleFactory.createDefaultNetworkLinkStyle(); // this.networkNodeStyle = this.styleFactory.createDefaultColoredNodeStyle(); HashMap<String, FolderType> folderTypes = new HashMap<String, FolderType>(); for (Activity act : this.activityList) { if (folderTypes.get(act.getType()) == null) { FolderType linkFolder = this.kmlObjectFactory.createFolderType(); linkFolder.setName(act.getType() + " activities"); folderTypes.put(act.getType(), linkFolder); } AbstractFeatureType abstractFeature = this.networkFeatureFactory.createActFeature( act, this.styleFactory.createDefaultColoredNodeStyle(act.getType())); folderTypes .get(act.getType()) .getAbstractFeatureGroup() .add(this.kmlObjectFactory.createPlacemark((PlacemarkType) abstractFeature)); } return folderTypes.values(); }
private void updateWalkTimeTmpVariables( String legMod, Id personId, Plan executedPlan, int planElementIndex, double valueA, double valueB) { if (isPlanElementDuringDay(personId, planElementIndex)) { if (legMod.equals(TransportMode.walk)) { Activity previousAct = (Activity) executedPlan.getPlanElements().get(planElementIndex - 1); Leg previousLeg = (Leg) executedPlan.getPlanElements().get(planElementIndex - 2); if (previousAct.getType().equalsIgnoreCase("parking") && previousLeg.getMode().equals(TransportMode.car)) { firstParkingWalkTmp.put(personId, valueA); } Activity nextAct = (Activity) executedPlan.getPlanElements().get(planElementIndex + 1); Leg nextLeg = (Leg) executedPlan.getPlanElements().get(planElementIndex + 2); if (nextAct.getType().equalsIgnoreCase("parking") && nextLeg.getMode().equals(TransportMode.car)) { secondParkingWalkTmp.put(personId, valueB); } } } }
private Activity firstActivity(final Person person, final String type) { final Plan plan = person.getSelectedPlan(); if (plan == null) { return null; } for (PlanElement element : plan.getPlanElements()) { if (element instanceof Activity) { final Activity act = (Activity) element; if (act.getType() != null && act.getType().startsWith(type)) { return act; } } } return null; }
protected void handleAct(final double time) { Activity act = (Activity) this.plan.getPlanElements().get(this.index); if (this.index == 0) { this.firstActTime = time; } else if (this.index == this.lastActIndex) { String lastActType = act.getType(); if (lastActType.equals(((Activity) this.plan.getPlanElements().get(0)).getType())) { // the first Act and the last Act have the same type this.score += calcActScore(this.lastTime, this.firstActTime + 24 * 3600, act); // SCENARIO_DURATION } else { if (scoreActs) { log.warn( "The first and the last activity do not have the same type. The correctness of the scoring function can thus not be guaranteed."); // score first activity Activity firstAct = (Activity) this.plan.getPlanElements().get(0); this.score += calcActScore(0.0, this.firstActTime, firstAct); // score last activity this.score += calcActScore(this.lastTime, 24 * 3600, act); // SCENARIO_DURATION } } } else { this.score += calcActScore(this.lastTime, time, act); } this.index++; }
private void handleActivity(EventsToScore eventsToScore, Fixture f, Activity activity) { eventsToScore.handleEvent( new ActivityStartEvent( activity.getStartTime(), f.person.getId(), activity.getLinkId(), activity.getFacilityId(), activity.getType())); eventsToScore.handleEvent( new ActivityEndEvent( activity.getEndTime(), f.person.getId(), activity.getLinkId(), activity.getFacilityId(), activity.getType())); }
@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); } }
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); }
protected double[] getOpeningInterval(final Activity act) { ActivityUtilityParameters params = utilParams.get(act.getType()); if (params == null) { throw new IllegalArgumentException( "acttype \"" + act.getType() + "\" is not known in utility parameters."); } double openingTime = params.getOpeningTime(); double closingTime = params.getClosingTime(); // openInterval has two values // openInterval[0] will be the opening time // openInterval[1] will be the closing time double[] openInterval = new double[] {openingTime, closingTime}; return openInterval; }
public double getDestinationScore( Activity act, double fVar, int activityIndex, Id<Person> personId) { double score = 0.0; if (this.scaleEpsilon.isFlexibleType(act.getType())) { /* * The following will not work if activities are inserted or removed during replanning (e.g. ptInteractionActivities). kai/mz, oct'14 */ int actIndex = 2 * activityIndex; // "2": retrofitting; this used to be the PlanElementIndex. One // could probably remove the "2", // but then the test fail because this is equivalent to a different random seed. So more // diligent checking would be needed. if (fVar < 0.0) fVar = this.scaleEpsilon.getEpsilonFactor(act.getType()); score += (fVar * this.getEpsilonAlternative(act.getFacilityId(), personId, actIndex)); score += this.getAttributesScore(act.getFacilityId(), personId); } return score; }
private void initializeActivity(Activity act) { this.state = MobsimAgent.State.ACTIVITY; double now = this.getMobsim().getSimTimer().getTimeOfDay(); this.simulation .getEventsManager() .processEvent( new ActivityStartEvent( now, this.getId(), this.currentLinkId, act.getFacilityId(), act.getType())); /* schedule a departure if either duration or endtime is set of the activity. * Otherwise, the agent will just stay at this activity for ever... */ calculateAndSetDepartureTime(act); }
@Override public final void endActivityAndComputeNextState(final double now) { Activity act = (Activity) this.getPlanElements().get(this.currentPlanElementIndex); this.simulation .getEventsManager() .processEvent( new ActivityEndEvent( now, this.getPerson().getId(), act.getLinkId(), act.getFacilityId(), act.getType())); advancePlan(now); }
@Override protected double[] getOpeningInterval(Activity act) { // openInterval has two values // openInterval[0] will be the opening time // openInterval[1] will be the closing time double[] openInterval = new double[] {Time.UNDEFINED_TIME, Time.UNDEFINED_TIME}; boolean foundAct = false; ActivityFacility facility = this.facilities.getFacilities().get(act.getFacilityId()); Iterator<String> facilityActTypeIterator = facility.getActivityOptions().keySet().iterator(); String facilityActType = null; Set<OpeningTime> opentimes = null; while (facilityActTypeIterator.hasNext() && !foundAct) { facilityActType = facilityActTypeIterator.next(); if (act.getType().equals(facilityActType)) { foundAct = true; // choose appropriate opentime: // either wed or wkday // if none is given, use undefined opentimes opentimes = facility.getActivityOptions().get(facilityActType).getOpeningTimes(); if (opentimes != null && opentimes.size() > 0) { // ignoring lunch breaks with the following procedure: // if there is only one wed/wkday open time interval, use it // if there are two or more, use the earliest start time and the latest end time openInterval[0] = Double.MAX_VALUE; openInterval[1] = Double.MIN_VALUE; for (OpeningTime opentime : opentimes) { openInterval[0] = Math.min(openInterval[0], opentime.getStartTime()); openInterval[1] = Math.max(openInterval[1], opentime.getEndTime()); } } } } if (!foundAct) { return new double[] {0, Double.MAX_VALUE}; } return openInterval; }
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"); }
/** @param args */ public static void main(String[] args) { Header.printHeader(checkShoppingTypes.class.toString(), args); Scenario sc = ScenarioUtils.createScenario(ConfigUtils.createConfig()); MatsimReader pr = new PopulationReader(sc); pr.readFile(args[0]); int s1 = 0; int s2 = 0; int s3 = 0; int s4 = 0; int s5 = 0; for (Id id : sc.getPopulation().getPersons().keySet()) { Plan plan = sc.getPopulation().getPersons().get(id).getSelectedPlan(); for (PlanElement pe : plan.getPlanElements()) { if (pe instanceof Activity) { Activity act = (Activity) pe; String s = act.getType(); if (s.equalsIgnoreCase("s1")) { s1++; } else if (s.equalsIgnoreCase("s2")) { s2++; } else if (s.equalsIgnoreCase("s3")) { s3++; } else if (s.equalsIgnoreCase("s4")) { s4++; } else if (s.equalsIgnoreCase("s5")) { s5++; } } } } LOG.info(" s1: " + s1); LOG.info(" s2: " + s2); LOG.info(" s3: " + s3); LOG.info(" s4: " + s4); LOG.info(" s5: " + s5); Header.printFooter(); }
private static boolean equalsActType(Activity act, String type) { return act.getType().startsWith(type); }
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; }
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."); }
public void run(String plansFilePath, String networkFilePath) { MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig()); MatsimReader populationReader = new PopulationReader(scenario); MatsimNetworkReader networkReader = new MatsimNetworkReader(scenario.getNetwork()); networkReader.readFile(networkFilePath); populationReader.readFile(plansFilePath); int countE = 0; int countW = 0; int countS = 0; int countL = 0; int countH = 0; int count = 0; int work = 0; boolean cs = false; int number = 0; for (Person p : scenario.getPopulation().getPersons().values()) { ArrayList<Activity> c = new ArrayList<Activity>(); Activity a = null; cs = false; for (PlanElement pe : p.getSelectedPlan().getPlanElements()) { if (pe instanceof Activity) { a = (Activity) pe; } else if (pe instanceof Leg) { if (a.getType().startsWith("home")) { if (((Leg) pe).getMode().equals("walk_rb")) number++; // startWork = true; } } if (pe instanceof Leg) { if ((((Leg) pe).getMode().equals("twowaycarsharing")) || ((Leg) pe).getMode().equals("walk_rb")) { cs = true; } else cs = false; } else if (pe instanceof Activity) { if (cs) { if (((Activity) pe).getType().startsWith("work")) { if (!c.isEmpty()) work++; else { } countW++; // time += (((Activity) pe).getMaximumDuration()); c.add((Activity) pe); count++; } else if (((Activity) pe).getType().startsWith("education")) { countE++; count++; } else if (((Activity) pe).getType().startsWith("shop")) { countS++; count++; } else if (((Activity) pe).getType().startsWith("leisure")) { countL++; count++; } else if (((Activity) pe).getType().startsWith("home")) { countH++; count++; } } } } } System.out.println(work); System.out.println(number); System.out.println((double) countS / count * 100.0); System.out.println((double) countW / count * 100.0); System.out.println((double) countE / count * 100.0); System.out.println((double) countL / count * 100.0); System.out.println((double) countH / count * 100.0); System.out.println(count); System.out.println((double) countS / count); // new PopulationWriter(scenario.getPopulation(), // scenario.getNetwork()).writeFileV4(outputFilePath + "/plans_1p.xml"); }
protected double calcActScore( final double arrivalTime, final double departureTime, final Activity act) { ActivityUtilityParameters params = utilParams.get(act.getType()); if (params == null) { throw new IllegalArgumentException( "acttype \"" + act.getType() + "\" is not known in utility parameters."); } double tmpScore = 0.0; /* Calculate the times the agent actually performs the * activity. The facility must be open for the agent to * perform the activity. If it's closed, but the agent is * there, the agent must wait instead of performing the * activity (until it opens). * * Interval during which * Relationship between times: activity is performed: * * O________C A~~D ( 0 <= C <= A <= D ) D...D (not performed) * A~~D O________C ( A <= D <= O <= C ) D...D (not performed) * O__A+++++C~~D ( O <= A <= C <= D ) A...C * O__A++D__C ( O <= A <= D <= C ) A...D * A~~O++++++++C~~D ( A <= O <= C <= D ) O...C * A~~O+++++D__C ( A <= O <= D <= C ) O...D * * Legend: * A = arrivalTime (when agent gets to the facility) * D = departureTime (when agent leaves the facility) * O = openingTime (when facility opens) * C = closingTime (when facility closes) * + = agent performs activity * ~ = agent waits (agent at facility, but not performing activity) * _ = facility open, but agent not there * * assume O <= C * assume A <= D */ double[] openingInterval = this.getOpeningInterval(act); double openingTime = openingInterval[0]; double closingTime = openingInterval[1]; double activityStart = arrivalTime; double activityEnd = departureTime; if ((openingTime >= 0) && (arrivalTime < openingTime)) { activityStart = openingTime; } if ((closingTime >= 0) && (closingTime < departureTime)) { activityEnd = closingTime; } if ((openingTime >= 0) && (closingTime >= 0) && ((openingTime > departureTime) || (closingTime < arrivalTime))) { // agent could not perform action activityStart = departureTime; activityEnd = departureTime; } double duration = activityEnd - activityStart; // disutility if too early if (arrivalTime < activityStart) { // agent arrives to early, has to wait tmpScore += marginalUtilityOfWaiting * (activityStart - arrivalTime); } // disutility if too late double latestStartTime = params.getLatestStartTime(); if ((latestStartTime >= 0) && (activityStart > latestStartTime)) { tmpScore += marginalUtilityOfLateArrival * (activityStart - latestStartTime); } // utility of performing an action, duration is >= 1, thus log is no problem double typicalDuration = params.getTypicalDuration(); if (duration > 0) { double utilPerf = marginalUtilityOfPerforming * typicalDuration * Math.log((duration / 3600.0) / params.getZeroUtilityDuration_h()); double utilWait = marginalUtilityOfWaiting * duration; tmpScore += Math.max(0, Math.max(utilPerf, utilWait)); } else { tmpScore += 2 * marginalUtilityOfLateArrival * Math.abs(duration); } // disutility if stopping too early double earliestEndTime = params.getEarliestEndTime(); if ((earliestEndTime >= 0) && (activityEnd < earliestEndTime)) { tmpScore += marginalUtilityOfEarlyDeparture * (earliestEndTime - activityEnd); } // disutility if going to away to late if (activityEnd < departureTime) { tmpScore += marginalUtilityOfWaiting * (departureTime - activityEnd); } // disutility if duration was too short double minimalDuration = params.getMinimalDuration(); if ((minimalDuration >= 0) && (duration < minimalDuration)) { tmpScore += marginalUtilityOfEarlyDeparture * (minimalDuration - duration); } return tmpScore; }