21 package org.matsim.core.population;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.PipedInputStream;
26 import java.io.PipedOutputStream;
27 import java.io.UncheckedIOException;
28 import java.util.ArrayList;
29 import java.util.Collections;
30 import java.util.Iterator;
31 import java.util.List;
33 import java.util.Random;
34 import java.util.SortedMap;
35 import java.util.TreeMap;
37 import org.apache.logging.log4j.LogManager;
38 import org.apache.logging.log4j.Logger;
143 throw new IllegalArgumentException(
"The type \"" + networkRouteType +
"\" is not a supported type for network routes.");
146 return new PopulationImpl(
new PopulationFactoryImpl(routeFactory));
150 return new UnmodifiableLeg(leg);
157 if (pe instanceof
Leg) {
158 ((Leg) pe).setRoute(null);
163 static class UnmodifiableLeg
implements Leg {
164 private final Leg delegate;
166 public UnmodifiableLeg(
Leg leg) {
171 public String getMode() {
172 return this.delegate.
getMode();
176 public void setMode(String mode) {
177 throw new UnsupportedOperationException();
181 public String getRoutingMode() {
186 public void setRoutingMode(String routingMode) {
187 throw new UnsupportedOperationException();
191 public Route getRoute() {
197 public void setRoute(
Route route) {
198 throw new UnsupportedOperationException();
207 public void setDepartureTime(
double seconds) {
208 throw new UnsupportedOperationException();
212 public void setDepartureTimeUndefined() {
213 throw new UnsupportedOperationException();
222 public void setTravelTime(
double seconds) {
223 throw new UnsupportedOperationException();
227 public void setTravelTimeUndefined() {
228 throw new UnsupportedOperationException();
232 public String toString() {
233 return this.delegate.toString();
244 return new UnmodifiableActivity(act);
247 static class UnmodifiableActivity
implements Activity {
250 public UnmodifiableActivity(
Activity act) {
260 public void setEndTime(
double seconds) {
261 throw new UnsupportedOperationException();
265 public void setEndTimeUndefined() {
266 throw new UnsupportedOperationException();
270 public String getType() {
271 return this.delegate.
getType();
275 public void setType(String type) {
276 throw new UnsupportedOperationException();
280 public Coord getCoord() {
290 public void setStartTime(
double seconds) {
291 throw new UnsupportedOperationException();
295 public void setStartTimeUndefined() {
296 throw new UnsupportedOperationException();
305 public void setMaximumDuration(
double seconds) {
306 throw new UnsupportedOperationException();
310 public void setMaximumDurationUndefined() {
311 throw new UnsupportedOperationException();
325 public String toString() {
326 return this.delegate.toString();
330 public void setLinkId(
Id<Link> id) {
331 throw new UnsupportedOperationException();
336 throw new UnsupportedOperationException();
340 public void setCoord(
Coord coord) {
356 return new UnmodifiablePlan(plan);
359 static class UnmodifiablePlan
implements Plan {
360 private final Plan delegate;
361 private final List<PlanElement> unmodifiablePlanElements;
363 public UnmodifiablePlan(
Plan plan) {
364 this.delegate = plan;
365 List<PlanElement> tmp =
new ArrayList<>();
369 }
else if (pe instanceof
Leg) {
373 this.unmodifiablePlanElements = Collections.unmodifiableList(tmp);
377 public void addActivity(
Activity act) {
378 throw new UnsupportedOperationException();
382 public String getType() {
387 public void setType(String type) {
388 throw new UnsupportedOperationException();
393 return this.delegate.
getId();
397 public void setPlanId(
Id<Plan> planId) {
398 throw new UnsupportedOperationException();
402 public int getIterationCreated() {
407 public void setIterationCreated(
int iteration) {
408 throw new UnsupportedOperationException();
412 public String getPlanMutator() {
417 public void setPlanMutator(String planMutator) {
418 throw new UnsupportedOperationException();
422 public void addLeg(
Leg leg) {
423 throw new UnsupportedOperationException();
427 public Map<String, Object> getCustomAttributes() {
432 public Person getPerson() {
437 public List<PlanElement> getPlanElements() {
438 return this.unmodifiablePlanElements;
442 public Double getScore() {
447 public void setPerson(
Person person) {
448 throw new UnsupportedOperationException();
452 public void setScore(Double score) {
453 throw new UnsupportedOperationException();
467 return new TreeMap<>(population.
getPersons());
476 if (map instanceof SortedMap)
return;
478 Map<Id<Person>,
Person> treeMap =
new TreeMap<>(map);
491 return linkIdFromActivity;
494 if (facility == null || facility.
getLinkId() == null) {
495 if (facility == null) {
496 if (missingFacilityCnt < 10) {
497 log.warn(
"we have a facility ID for an activity, but can't find the facility; this should not really happen. Falling back on link ID.");
498 missingFacilityCnt++;
499 if (missingFacilityCnt == 10) {
506 return linkIdFromActivity;
559 double sameModeReward,
double sameRouteReward) {
571 Iterator<Leg> it1 = legs1.iterator();
572 Iterator<Leg> it2 = legs2.iterator();
573 for (; it1.hasNext() && it2.hasNext(); ) {
574 Leg leg1 = it1.next();
575 Leg leg2 = it2.next();
577 simil += sameModeReward;
589 nr1 = (NetworkRoute) route1;
591 simil += sameModeReward;
597 if (route2 instanceof NetworkRoute) {
598 nr2 = (NetworkRoute) route2;
600 simil += sameModeReward;
613 public static double calculateSimilarity(List<Activity> activities1, List<Activity> activities2,
double sameActivityTypePenalty,
614 double sameActivityLocationPenalty,
double actTimeParameter) {
626 Iterator<Activity> it1 = activities1.iterator();
627 Iterator<Activity> it2 = activities2.iterator();
628 for (; it1.hasNext() && it2.hasNext(); ) {
634 simil += sameActivityTypePenalty;
639 simil += sameActivityLocationPenalty;
650 simil += actTimeParameter * Math.exp(-delta / (300 / Math.log(2)));
677 }
catch (IOException e) {
678 throw new UncheckedIOException(e);
690 final PipedInputStream in =
new PipedInputStream();
691 final PipedOutputStream out =
new PipedOutputStream(in);
698 }
catch (UncheckedIOException e) {
707 }
catch (IOException e) {
708 throw new UncheckedIOException(e);
714 int indexOfLastCarLegOfDay = -1;
715 for (
int i = planElements.size() - 1; i >= 0; i--) {
716 if (planElements.get(i) instanceof
Leg leg) {
718 indexOfLastCarLegOfDay = i;
725 for (
int i = indexOfLastCarLegOfDay + 1; i < planElements.size(); i++) {
726 if (planElements.get(i) instanceof
Activity act) {
735 int indexOfFirstCarLegOfDay = -1;
736 for (
int i = 0; i < planElements.size(); i++) {
737 if (planElements.get(i) instanceof
Leg leg) {
739 indexOfFirstCarLegOfDay = i;
745 for (
int i = indexOfFirstCarLegOfDay - 1; i >= 0; i--) {
746 if (planElements.get(i) instanceof
Activity act) {
755 for (
int i = 0; i < planElements.size(); i++) {
756 if (planElements.get(i) instanceof
Leg leg) {
828 if (activity instanceof InteractionActivity) {
869 if (plan.getPlanElements().size() == 0) {
870 throw new IllegalStateException(
"The order of 'acts'/'legs' is wrong in some way while trying to create a 'leg'.");
875 Activity act =
new ActivityImpl(type);
903 public static void copyFromTo(
final Plan in,
final Plan out,
final boolean withInteractionActivities) {
914 if (withInteractionActivities && (pe instanceof InteractionActivity )) {
919 }
else if (pe instanceof
Leg) {
922 throw new IllegalArgumentException(
"unrecognized plan element type discovered");
1011 if ((pe instanceof
Leg) || (pe instanceof
Activity)) {
1019 throw new IllegalArgumentException(
"Method call only valid with a Leg or Act instance as parameter!");
1055 if ((index % 2 == 0) || (index < 1) || (index >= plan.
getPlanElements().size() - 1)) {
1056 log.warn(plan +
"[index=" + index +
" is wrong. nothing removed]");
1072 if ((index % 2 != 0) || (index < 0) || (index > plan.
getPlanElements().size() - 1)) {
1073 log.warn(plan +
"[index=" + index +
" is wrong. nothing removed]");
1075 log.warn(plan +
"[index=" + index +
" only one act. nothing removed]");
1111 if (!(o instanceof
Leg)) {
1112 throw new IllegalArgumentException(
"Position to insert leg and act is not valid (act instead of leg at position).");
1115 throw new IllegalArgumentException(
"Position to insert leg and act is not valid.");
1122 if (person instanceof PersonImpl) {
1123 ((PersonImpl) person).changeId(
id);
1130 log.info(
" person # " + population.
getPersons().size());
1144 if (facility == null) {
1145 throw new RuntimeException(
"facility ID given but not in facilities container");
1163 if (facilityId != null) {
1180 return new Coord(fromCoord.
getX() + rel * (toCoord.
getX() - fromCoord.
getX()), fromCoord.
getY() + rel * (toCoord.
getY() - fromCoord.
getY()));
1185 log.info(
"population size before downsampling=" + pop.
getPersons().size());
1186 pop.
getPersons().values().removeIf(person -> rnd.nextDouble() >= sample);
1187 log.info(
"population size after downsampling=" + pop.
getPersons().size());
1219 if (person == null) {
1251 if (person == null) {
1256 return (String) person.
getAttributes().getAttribute(SUBPOPULATION_ATTRIBUTE_NAME);
1270 log.info(
"adding scenario element for allpersons container");
1281 if (person == null) {
1282 if (tryStdCnt > 0) {
1284 log.info(
"personId=" + personId +
" not in allPersons; trying standard population container ...");
1285 if (tryStdCnt == 0) {
1291 if (person == null) {
1292 log.info(
"unable to find person for personId=" + personId +
"; will return null");
1328 personRouteChecker::run
OptionalTime getEndTime()
static Activity createAndAddActivity(Plan plan, String type)
Map< Id< ActivityFacility >, ? extends ActivityFacility > getFacilities()
static void removeSubpopulation(Person person)
static Activity getPreviousActivity(Plan plan, Leg leg)
static String getRoutingMode(Leg leg)
Attributes getAttributes()
Activity createActivityFromActivityFacilityId(String actType, Id< ActivityFacility > activityFacilityId)
OptionalTime getMaximumDuration()
OptionalTime getStartTime()
static Activity createActivityFromCoord(String type, Coord coord)
static Activity createInteractionActivity(Activity act)
static boolean isEqual(InputStream first, InputStream second)
static Activity getNextActivity(Plan plan, Leg leg)
static final PopulationFactory populationFactory
static void assertIf(boolean flag)
static final String MediumCompressedNetworkRoute
static void insertVehicleTypesIntoPersonAttributes(Person person, Map< String, Id< VehicleType >> modeToVehicleType)
Map< String, Object > getCustomAttributes()
static boolean equalPopulation(final Population s1, final Population s2)
void setTravelTimeUndefined()
void ifDefinedOrElse(DoubleConsumer action, Runnable undefinedAction)
void setRouteFactory(final Class<? extends Route > routeClass, final RouteFactory factory)
static void insertLegAct(Plan plan, int pos, Leg leg, Activity act)
static void removePersonAttributes(Person person, Population population)
static boolean comparePopulations(Population population1, Population population2)
static void printPlansCount(StreamingPopulationReader reader)
Leg createLeg(String legMode)
static Population readPopulation(String filename)
static Activity getFirstActivityAfterLastCarLegOfDay(Plan plan)
static List< Activity > getActivities(final Plan plan, final StageActivityHandling stageActivityHandling)
static void removeActivity(Plan plan, int index)
static Activity createAndAddActivityFromCoord(Plan plan, String type, Coord coord)
static List< Leg > getLegs(Plan plan)
void addScenarioElement(String name, Object o)
static Person findPerson(Id< Person > personId, Scenario scenario)
void setLinkId(final Id< Link > id)
Activity createActivityFromLinkId(String actType, Id< Link > linkId)
static Object removePersonAttribute(Person person, String key)
static Coord computeCoordFromActivity(Activity act, ActivityFacilities facs, Config config)
static void insertVehicleIdsIntoPersonAttributes(Person person, Map< String, Id< Vehicle >> modeToVehicle)
static< T extends Attributable > void copyAttributesFromTo(T from, T to)
static Random getLocalInstance()
void addLeg(final Leg leg)
static Activity createActivityFromLinkId(String type, Id< Link > linkId)
static Activity createInteractionActivityFromCoordAndLinkId(String type, Coord coord, Id< Link > linkId)
final void setPopulation(Population population)
static Activity createAndAddActivityFromFacilityId(Plan plan, String type, Id< ActivityFacility > facilityId)
static int getActLegIndex(Plan plan, PlanElement pe)
static Activity convertInteractionToStandardActivity(Activity activity)
static Plan createPlan(Person person)
static MutableScenario createMutableScenario(final Config config)
static void copyFromTo(Activity act, Activity newAct)
static void changePersonId(Person person, Id< Person > id)
static final String CompressedNetworkRoute
static Population createPopulation(PlansConfigGroup plansConfigGroup, Network network)
OptionalTime getDepartureTime()
void setPerson(Person person)
static final String FUTURE_SUPPRESSED
Map< Id< Person >,? extends Person > getPersons()
Object getScenarioElement(String name)
static Leg createAndAddLeg(Plan plan, String mode)
static Id< Link > computeLinkIdFromActivity(Activity act, ActivityFacilities facs, Config config)
static void removeLeg(Plan plan, int index)
Activity createInteractionActivityFromActivityFacilityId(String actType, Id< ActivityFacility > activityFacilityId)
static void putPersonAttribute(HasPlansAndId<?, ?> person, String key, Object value)
static Leg getNextLeg(Plan plan, Activity act)
static void insertVehicleTypesIntoPersonAttributes(Person person, Map< String, Id< VehicleType >> modeToVehicleType)
static Activity createInteractionActivityFromCoord(String type, Coord coord)
void setMode(String mode)
static void copyFromTo(final Plan in, final Plan out)
void setDepartureTimeUndefined()
static double calculateSimilarity(List< Activity > activities1, List< Activity > activities2, double sameActivityTypePenalty, double sameActivityLocationPenalty, double actTimeParameter)
void setType(final String type)
static final String LinkNetworkRoute
static void setRoutingMode(Leg leg, String mode)
static Activity createActivityFromFacilityId(String type, Id< ActivityFacility > facilityId)
static void printPlansCount(Population population)
static Activity createInteractionActivityFromFacilityId(String type, Id< ActivityFacility > facilityId)
static final String SUBPOPULATION_ATTRIBUTE_NAME
static Object getPersonAttribute(HasPlansAndId<?, ?> person, String key)
Population getPopulation()
static void insertVehicleIdsIntoPersonAttributes(Person person, Map< String, Id< Vehicle >> modeToVehicle)
static Population createPopulation(Config config)
static String getSubpopulation(HasPlansAndId<?, ?> person)
static InputStream openPopulationInputStream(final Population s1)
void write(final String filename)
static Population getOrCreateAllpersons(Scenario scenario)
static void sampleDown(Population pop, double sample)
void setRoute(Route route)
void addActivity(final Activity act)
static Leg createLeg(String transportMode)
List< PlanElement > getPlanElements()
static double calculateSimilarity(List< Leg > legs1, List< Leg > legs2, Network network, double sameModeReward, double sameRouteReward)
final PlansConfigGroup plans()
static void readPopulation(Population population, String filename)
boolean equals(final Object other)
static SortedMap< Id< Person >, Person > getSortedPersons(final Population population)
void setScore(Double score)
static void assertNotNull(Object obj)
static Leg createLeg(Leg leg)
static Population createPopulation(Config config, Network network)
Activity createInteractionActivityFromCoord(String actType, Coord coord)
static void copyFromTo(final Plan in, final Plan out, final boolean withInteractionActivities)
Map< Id< Link >, ? extends Link > getLinks()
static Activity createInteractionActivityFromLinkId(String type, Id< Link > linkId)
static Activity createActivityFromCoordAndLinkId(String type, Coord coord, Id< Link > linkId)
static void checkRouteModeAndReset(Population population, Network network)
static Id< Link > decideOnLinkIdForActivity(Activity act, Scenario sc)
OptionalTime getTravelTime()
static List< Activity > getActivities(Plan plan, StageActivityHandling stageActivityHandling)
Id< ActivityFacility > getFacilityId()
static Activity createAndAddActivityFromLinkId(Plan plan, String type, Id< Link > linkId)
static final String HeavyCompressedNetworkRoute
static String createStageActivityType(String mode)
static Coord computeCoordFromActivity(Activity act, ActivityFacilities facs, Network network, Config config)
final void readFile(final String filename)
Activity createActivityFromCoord(String actType, Coord coord)
ActivityFacilities getActivityFacilities()
static Coord decideOnCoordForActivity(Activity act, Scenario sc)
static void putSubpopulation(HasPlansAndId<?, ?> person, String subpopulation)
String getNetworkRouteType()
Activity createInteractionActivityFromLinkId(String actType, Id< Link > linkId)
static Activity createActivity(Activity act)
PopulationFactory getFactory()
double getRelativePositionOfEntryExitOnLink()
void setCoord(Coord coord)
static double calculateCoverage(NetworkRoute route1, NetworkRoute route2, Network network)
void setType(final String type)
static Leg getPreviousLeg(Plan plan, Activity act)
static Activity createStageActivityFromCoordLinkIdAndModePrefix(final Coord interactionCoord, final Id< Link > interactionLink, String modePrefix)
static Activity getLastActivity(Plan plan)
static void copyFromTo(Leg in, Leg out)
static Activity getFirstActivityOfDayBeforeDepartingWithCar(Plan plan)
void setFacilityId(final Id< ActivityFacility > id)
int getIterationCreated()
final GlobalConfigGroup global()
static Plan unmodifiablePlan(Plan plan)
static PopulationFactory getFactory()
Object removeAttribute(final String attribute)
static void verifyCreateLeg(Plan plan)
static Activity getFirstActivity(Plan plan)
static List< Leg > getLegs(final Plan plan)
static void writePopulation(Population population, String filename)
static void sortPersons(final Population population)
static Activity unmodifiableActivity(Activity act)
static boolean hasCarLeg(Plan plan)
static Leg unmodifiableLeg(Leg leg)
static Config createConfig(final String context)
static int missingFacilityCnt
static void resetRoutes(final Plan plan)