From b24d01bff651500b1377d538c6304d644f0d5360 Mon Sep 17 00:00:00 2001 From: Kai Nagel Date: Mon, 12 Feb 2024 15:35:50 +0100 Subject: [PATCH 001/101] changes --- .../PC2/GeneralParkingModule.java | 50 ++---- .../PC2/infrastructure/PC2Parking.java | 2 +- .../PC2/infrastructure/PublicParking.java | 22 +-- .../PC2/scoring/ParkingScore.java | 4 +- .../PC2/scoring/ParkingScoreManager.java | 2 +- .../simulation/ParkingChoiceSimulation.java | 77 +++++---- .../PC2/simulation/ParkingInfrastructure.java | 18 +-- .../ParkingInfrastructureManager.java | 148 +++++++++--------- 8 files changed, 152 insertions(+), 171 deletions(-) diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/GeneralParkingModule.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/GeneralParkingModule.java index 29b225d5397..3a85713682c 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/GeneralParkingModule.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/GeneralParkingModule.java @@ -13,59 +13,31 @@ public class GeneralParkingModule implements StartupListener, BeforeMobsimListen private final Controler controler; private ParkingScore parkingScoreManager; -// public final ParkingScore getParkingScoreManager() { -// return parkingScoreManager; -// } - - public final void setParkingScoreManager(ParkingScore parkingScoreManager) { - this.parkingScoreManager = parkingScoreManager; - } - private ParkingInfrastructure parkingInfrastructureManager; private ParkingChoiceSimulation parkingChoiceSimulation; public GeneralParkingModule(Controler controler){ this.controler = controler ; - controler.addControlerListener(this); } - - @Override - public void notifyStartup(StartupEvent event) { + + @Override public void notifyStartup(StartupEvent event) { parkingChoiceSimulation = new ParkingChoiceSimulation(controler.getScenario(), parkingInfrastructureManager); controler.getEvents().addHandler( parkingChoiceSimulation ); -// controler.addControlerListener(parkingSimulation); - // was not doing anything there. kai, jul'15 } -// public final ParkingInfrastructure getParkingInfrastructure() { -// return parkingInfrastructureManager; -// } - - public final void setParkingInfrastructurManager(ParkingInfrastructure parkingInfrastructureManager) { - this.parkingInfrastructureManager = parkingInfrastructureManager; + @Override public void notifyBeforeMobsim(BeforeMobsimEvent event) { + parkingScoreManager.notifyBeforeMobsim(); + parkingInfrastructureManager.notifyBeforeMobsim(); + parkingChoiceSimulation.notifyBeforeMobsim(); } -// @Deprecated -// // lower level objects may keep back pointers to higher level objects if they have to, but we prefer that they do not provide them -// // as a service. kai, apr'15 -// public final Controler getControler() { -// return controler; -// } - - @Override - public void notifyBeforeMobsim(BeforeMobsimEvent event) { - parkingScoreManager.prepareForNewIteration(); - parkingInfrastructureManager.reset(); - parkingChoiceSimulation.prepareForNewIteration(); + public final void setParkingScoreManager(ParkingScore parkingScoreManager) { + this.parkingScoreManager = parkingScoreManager; } -// protected final ParkingInfrastructure getParkingInfrastructureManager() { -// return parkingInfrastructureManager; -// } -// -// protected final ParkingChoiceSimulation getParkingSimulation() { -// return parkingSimulation; -// } + public final void setParkingInfrastructurManager(ParkingInfrastructure parkingInfrastructureManager) { + this.parkingInfrastructureManager = parkingInfrastructureManager; + } } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/infrastructure/PC2Parking.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/infrastructure/PC2Parking.java index d0fdfda187d..0e2a9bc2cbb 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/infrastructure/PC2Parking.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/infrastructure/PC2Parking.java @@ -26,7 +26,7 @@ public interface PC2Parking { public Id getId(); - public int getMaximumParkingCapacity(); +// public int getMaximumParkingCapacity(); public int getAvailableParkingCapacity(); diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/infrastructure/PublicParking.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/infrastructure/PublicParking.java index 28a18a2dce8..93256534074 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/infrastructure/PublicParking.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/infrastructure/PublicParking.java @@ -25,12 +25,12 @@ public class PublicParking implements PC2Parking { - private Id id = null; - private int capacity =0; + private final Id id; + private final int capacity; private int availableParking=0; private Coord coord=null; private ParkingCostModel parkingCostModel=null; - private String groupName; + private final String groupName; public PublicParking(Id id, int capacity, Coord coord, ParkingCostModel parkingCostModel, String groupName){ this.id=id; @@ -56,14 +56,14 @@ public Coord getCoordinate(){ return coord; } - public boolean isParkingAvailable(){ - return availableParking>0; - } - - @Override - public int getMaximumParkingCapacity(){ - return capacity; - } +// public boolean isParkingAvailable(){ +// return availableParking>0; +// } +// +// @Override +// public int getMaximumParkingCapacity(){ +// return capacity; +// } @Override public int getAvailableParkingCapacity(){ diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScore.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScore.java index 1eed79efbf2..a6a36fadc7f 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScore.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScore.java @@ -18,7 +18,7 @@ public interface ParkingScore { void addScore(Id id, double incValue); - void prepareForNewIteration(); + void notifyBeforeMobsim(); double getParkingScoreScalingFactor(); @@ -34,4 +34,4 @@ public interface ParkingScore { void setRandomErrorTermManger(RandomErrorTermManager randomErrorTermManager); -} \ No newline at end of file +} diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScoreManager.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScoreManager.java index 49fd0109768..abc90d45b94 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScoreManager.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScoreManager.java @@ -108,7 +108,7 @@ public synchronized void addScore(Id id, double incValue) { } @Override - public synchronized void prepareForNewIteration() { + public synchronized void notifyBeforeMobsim() { scores = new DoubleValueHashMap<>(); } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingChoiceSimulation.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingChoiceSimulation.java index 29bc9b7c65b..db2a710a0a8 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingChoiceSimulation.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingChoiceSimulation.java @@ -46,11 +46,9 @@ public final class ParkingChoiceSimulation implements PersonDepartureEventHandler, PersonArrivalEventHandler, ActivityEndEventHandler { - - private final ParkingInfrastructure parkingInfrastructureManager; private final Scenario scenario; - private IntegerValueHashMap> currentPlanElementIndex; + private IntegerValueHashMap> currentPlanElementIndices; private HashMap, ParkingOperationRequestAttributes> parkingOperationRequestAttributes; private DoubleValueHashMap> firstDepartureTimeOfDay; @@ -61,7 +59,7 @@ public ParkingChoiceSimulation(Scenario scenario, ParkingInfrastructure parkingI @Override public void handleEvent(ActivityEndEvent event) { - currentPlanElementIndex.increment(event.getPersonId()); + currentPlanElementIndices.increment(event.getPersonId() ); } @Override @@ -76,25 +74,37 @@ public void handleEvent(PersonDepartureEvent event) { } if (isFirstCarDepartureOfDay(event.getPersonId())) { - // (special case, think about it later) + // for the first departure of the day, we do not know when the parking actually started. The scoring is, in + // consequence, not done here, but done when _starting_ the _last_ parking of the day (see there). + // (yy what happens if the agent arrives by car but departs by some other mode, or the other way round? Can happen in particular if there is an additional home stop during the day.) ParkingOperationRequestAttributes parkingAttributes = new ParkingOperationRequestAttributes(); parkingAttributes.personId = event.getPersonId(); - // this is a trick to get the correct departure time + + // for the time being, we memorize a parking record with arrival time zero. This is corrected later, at the last arrival of the day. parkingAttributes.arrivalTime = 0; parkingAttributes.parkingDurationInSeconds = GeneralLib.getIntervalDuration(0, event.getTime()); parkingInfrastructureManager.personCarDepartureEvent(parkingAttributes); } else { + // parking has just ended: + + // finalize the corresponding record: ParkingOperationRequestAttributes parkingAttributes = parkingOperationRequestAttributes.get(event.getPersonId()); parkingAttributes.parkingDurationInSeconds = GeneralLib.getIntervalDuration(parkingAttributes.arrivalTime, event.getTime()); + + // hedge against a special case: if (parkingAttributes.parkingDurationInSeconds == 24 * 3600) { // (yyyy no idea what this is and why. kai, jul'15) + // (Presumably, the code is such that it cannot handle a parking duration of zero. Presumably, a parking + // duration of zero cannot happen, and therefore this is ok. However, if someone parks for exactly 24 hours, + // then this is at some point mapped back to zero, and then it may happen. kai, feb'24) parkingAttributes.parkingDurationInSeconds = 1; // not zero, because this might lead to NaN } - PC2Parking parking = parkingInfrastructureManager.personCarDepartureEvent(parkingAttributes); - parkingInfrastructureManager.scoreParkingOperation(parkingAttributes, parking); + // score the parking: + final PC2Parking parking = parkingInfrastructureManager.personCarDepartureEvent( parkingAttributes ); + parkingInfrastructureManager.scoreParkingOperation(parkingAttributes, parking ); } } @@ -106,7 +116,7 @@ public void handleEvent(PersonArrivalEvent event) { if (event.getLegMode().equalsIgnoreCase(TransportMode.car) && !event.getPersonId().toString().contains("pt") && isNotTransitAgent(event.getPersonId())) { // (exclude some cases (in a brittle way, i.e. based on IDs)) - // I think that this just packages some information together into the parkingAttributes: + // Generate most of the parking record (departure time will be added later): ParkingOperationRequestAttributes parkingAttributes = new ParkingOperationRequestAttributes(); { Link link = scenario.getNetwork().getLinks().get( event.getLinkId() ); @@ -120,9 +130,13 @@ public void handleEvent(PersonArrivalEvent event) { } if (isLastCarLegOfDay(personId)) { - // (special case, think about it later) - + // if this is the last arrival of the day, the parking record is already there, since it was generated at the first + // departure. However, the duration is not correct since at that time the arrival time was not known. + // (yy It looks to me that the arrivalTime remains at 0. why?) parkingAttributes.parkingDurationInSeconds = GeneralLib.getIntervalDuration(event.getTime(), firstDepartureTimeOfDay.get(personId)); + + // scoring of this special case is done further down, see there + } else { Activity activityBeforeNextCarLeg = getActivityBeforeNextCarLeg(personId); @@ -130,19 +144,19 @@ public void handleEvent(PersonArrivalEvent event) { double parkingDuration=0; if (endTime==Double.NEGATIVE_INFINITY || endTime==Double.POSITIVE_INFINITY){ - // (I think that this _can_ happen, especially in context of within-day replanning, if departure time is unknown. (*)) + // (in general, we take the (parking) end time from above. Sometimes, this end time does not have a useful value, in which case the current - // try to estimate parking duration + // try to estimate parking duration: Person person = scenario.getPopulation().getPersons().get(personId); List planElements = person.getSelectedPlan().getPlanElements(); - for (int i = currentPlanElementIndex.get(personId); i < planElements.size(); i++) { - if (planElements.get(i) instanceof Activity) { - parkingDuration+= ((Activity)planElements.get(i)).getMaximumDuration().seconds(); + for ( int ii = currentPlanElementIndices.get(personId ) ; ii < planElements.size(); ii++) { + if (planElements.get(ii) instanceof Activity) { + parkingDuration+= ((Activity)planElements.get(ii)).getMaximumDuration().seconds(); } - if (planElements.get(i) == activityBeforeNextCarLeg) { + if (planElements.get(ii) == activityBeforeNextCarLeg) { endTime=event.getTime()+parkingDuration; break; } @@ -150,15 +164,16 @@ public void handleEvent(PersonArrivalEvent event) { } parkingAttributes.parkingDurationInSeconds = GeneralLib.getIntervalDuration(event.getTime(), endTime); - // (This is the _estimated_ parking duration, since we are at arrival. This is needed to define the "best" parking + // (This is the _estimated_ parking duration, since we are at arrival, and in this special case we did not have the + // corresponding activity end time. This is needed to define the "best" parking // location ... cf. short-term/long-term parking at airports. Could rename the attributed into "expected...", but we // have seen at other places in the code that such attributes may change their interpretation based on context so will // not do this here.) } - parkingAttributes.legIndex = currentPlanElementIndex.get(personId); + parkingAttributes.legIndex = currentPlanElementIndices.get(personId ); - PC2Parking parking = parkingInfrastructureManager.parkVehicle(parkingAttributes); + final PC2Parking parking = parkingInfrastructureManager.parkVehicle(parkingAttributes); // to me this looks like first the agent arrives at his/her activity. And then the negative parking score is added after the // fact, however without consuming time. I.e. there is no physics. kai, jul'15 @@ -171,15 +186,11 @@ public void handleEvent(PersonArrivalEvent event) { } - currentPlanElementIndex.increment(personId); + currentPlanElementIndices.increment(personId ); } - private boolean isNotTransitAgent(Id persondId) { - return (Integer.parseInt(persondId.toString())< 1000000000); - } - - public void prepareForNewIteration() { - currentPlanElementIndex = new IntegerValueHashMap<>(); + public void notifyBeforeMobsim() { + currentPlanElementIndices = new IntegerValueHashMap<>(); parkingOperationRequestAttributes = new HashMap<>(); firstDepartureTimeOfDay = new DoubleValueHashMap<>(); @@ -215,6 +226,10 @@ public void prepareForNewIteration() { // === only private helper functions below this line === + private boolean isNotTransitAgent(Id persondId) { + return (Integer.parseInt(persondId.toString())< 1000000000); + } + private boolean isFirstCarDepartureOfDay(Id personId) { Person person = scenario.getPopulation().getPersons().get(personId); @@ -223,7 +238,7 @@ private boolean isFirstCarDepartureOfDay(Id personId) { } List planElements = person.getSelectedPlan().getPlanElements(); - for (int i = currentPlanElementIndex.get(personId) - 1; i >= 0; i--) { + for ( int i = currentPlanElementIndices.get(personId ) - 1 ; i >= 0; i--) { if (planElements.get(i) instanceof Leg) { Leg leg = (Leg) planElements.get(i); @@ -240,7 +255,7 @@ private boolean isFirstCarDepartureOfDay(Id personId) { private boolean isLastCarLegOfDay(Id personId) { Person person = scenario.getPopulation().getPersons().get(personId); List planElements = person.getSelectedPlan().getPlanElements(); - for (int i = currentPlanElementIndex.get(personId) + 1; i < planElements.size(); i++) { + for ( int i = currentPlanElementIndices.get(personId ) + 1 ; i < planElements.size(); i++) { if (planElements.get(i) instanceof Leg) { Leg Leg = (Leg) planElements.get(i); @@ -257,7 +272,7 @@ private Activity getActivityBeforeNextCarLeg(Id personId) { Person person = scenario.getPopulation().getPersons().get(personId); List planElements = person.getSelectedPlan().getPlanElements(); int indexOfNextCarLeg = -1; - for (int i = currentPlanElementIndex.get(personId) + 1; i < planElements.size(); i++) { + for ( int i = currentPlanElementIndices.get(personId ) + 1 ; i < planElements.size(); i++) { if (planElements.get(i) instanceof Leg) { Leg Leg = (Leg) planElements.get(i); @@ -281,7 +296,7 @@ private Activity getActivityBeforeNextCarLeg(Id personId) { private Activity getNextActivity(Id personId) { Person person = scenario.getPopulation().getPersons().get(personId); List planElements = person.getSelectedPlan().getPlanElements(); - for (int i = currentPlanElementIndex.get(personId); i < planElements.size(); i++) { + for ( int i = currentPlanElementIndices.get(personId ) ; i < planElements.size(); i++) { if (planElements.get(i) instanceof Activity) { return (Activity) planElements.get(i); } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingInfrastructure.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingInfrastructure.java index d2b170ce801..c4ed7484a32 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingInfrastructure.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingInfrastructure.java @@ -17,18 +17,18 @@ public interface ParkingInfrastructure { void setPublicParkings(LinkedList publicParkings); - void setRentableParking(LinkedList rentableParkings); +// void setRentableParking(LinkedList rentableParkings); - void setPrivateParkingRestrictedToFacilities(LinkedList ppRestrictedToFacilities); +// void setPrivateParkingRestrictedToFacilities(LinkedList ppRestrictedToFacilities); - void reset(); + void notifyBeforeMobsim(); - PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, String groupName); +// PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, String groupName); - void logArrivalEventAtTimeZero(PC2Parking parking); +// void logArrivalEventAtTimeZero(PC2Parking parking); - PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, String groupName, Id personId, - double parkingDurationInSeconds, double arrivalTime); +// PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, String groupName, Id personId, +// double parkingDurationInSeconds, double arrivalTime); // TODO: make this method abstract // when person/vehicleId is clearly distinct, then I can change this to @@ -42,7 +42,7 @@ PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, St void unParkVehicle(PC2Parking parking, double departureTime, Id personId); - ParkingScore getParkingScoreManager(); +// ParkingScore getParkingScoreManager(); EventsManager getEventsManager(); @@ -52,4 +52,4 @@ PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, St void setAllParkings(HashMap, PC2Parking> allParkings); -} \ No newline at end of file +} diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingInfrastructureManager.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingInfrastructureManager.java index 72d6250a771..65c1cf8367f 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingInfrastructureManager.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingInfrastructureManager.java @@ -119,27 +119,27 @@ public static void addParkingToQuadTree(QuadTree quadTree, PC2Parkin quadTree.put(parking.getCoordinate().getX(), parking.getCoordinate().getY(), parking); } - @Override - public synchronized void setRentableParking(LinkedList rentableParkings) { - for (RentableParking pp : rentableParkings) { - rentablePrivateParking.put(pp.getOwnerId(), pp); - getAllParkings().put(pp.getId(), pp); - } - } - - @Override - public synchronized void setPrivateParkingRestrictedToFacilities( - LinkedList ppRestrictedToFacilities) { - for (PPRestrictedToFacilities pp : ppRestrictedToFacilities) { - for (Id facilityId : pp.getFacilityIds()) { - privateParkingsRestrictedToFacilities.put(facilityId, pp); - getAllParkings().put(pp.getId(), pp); - } - } - } +// @Override +// public synchronized void setRentableParking(LinkedList rentableParkings) { +// for (RentableParking pp : rentableParkings) { +// rentablePrivateParking.put(pp.getOwnerId(), pp); +// getAllParkings().put(pp.getId(), pp); +// } +// } +// +// @Override +// public synchronized void setPrivateParkingRestrictedToFacilities( +// LinkedList ppRestrictedToFacilities) { +// for (PPRestrictedToFacilities pp : ppRestrictedToFacilities) { +// for (Id facilityId : pp.getFacilityIds()) { +// privateParkingsRestrictedToFacilities.put(facilityId, pp); +// getAllParkings().put(pp.getId(), pp); +// } +// } +// } @Override - public synchronized void reset() { + public synchronized void notifyBeforeMobsim() { parkedVehicles.clear(); for (PC2Parking parking : getAllParkings().values()) { @@ -174,45 +174,45 @@ private synchronized QuadTree getPublicParkingQuadTree() { return publicParkingsQuadTree; } - @Override - public synchronized PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, - String groupName) { - PC2Parking parking = null; - if (groupName == null) { - parking = publicParkingsQuadTree.getClosest(destCoordinate.getX(), destCoordinate.getY()); - } else { - QuadTree quadTree = publicParkingGroupQuadTrees.get(groupName); - parking = quadTree.getClosest(destCoordinate.getX(), destCoordinate.getY()); - - if (parking == null) { - throw new Error("system is in inconsistent state: " + - "not enough parking available for parkingGroupName:" + groupName); - } - } - parkVehicle(parking); - - return parking; - } - - @Override - public synchronized void logArrivalEventAtTimeZero(PC2Parking parking) { - eventsManager.processEvent(new ParkingArrivalEvent(0, parking.getId(), null, null, 0)); - } - - @Override - public synchronized PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, String groupName, - Id personId, double parkingDurationInSeconds, double arrivalTime) { - PC2Parking parking = parkAtClosestPublicParkingNonPersonalVehicle(destCoordinate, groupName); - - double walkScore = parkingScoreManager.calcWalkScore(destCoordinate, parking, personId, - parkingDurationInSeconds); - parkingScoreManager.addScore(personId, walkScore); - - eventsManager.processEvent( - new ParkingArrivalEvent(arrivalTime, parking.getId(), personId, destCoordinate, walkScore)); - - return parking; - } +// @Override +// public synchronized PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, +// String groupName) { +// PC2Parking parking = null; +// if (groupName == null) { +// parking = publicParkingsQuadTree.getClosest(destCoordinate.getX(), destCoordinate.getY()); +// } else { +// QuadTree quadTree = publicParkingGroupQuadTrees.get(groupName); +// parking = quadTree.getClosest(destCoordinate.getX(), destCoordinate.getY()); +// +// if (parking == null) { +// throw new Error("system is in inconsistent state: " + +// "not enough parking available for parkingGroupName:" + groupName); +// } +// } +// parkVehicle(parking); +// +// return parking; +// } + +// @Override +// public synchronized void logArrivalEventAtTimeZero(PC2Parking parking) { +// eventsManager.processEvent(new ParkingArrivalEvent(0, parking.getId(), null, null, 0)); +// } +// +// @Override +// public synchronized PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, String groupName, +// Id personId, double parkingDurationInSeconds, double arrivalTime) { +// PC2Parking parking = parkAtClosestPublicParkingNonPersonalVehicle(destCoordinate, groupName); +// +// double walkScore = parkingScoreManager.calcWalkScore(destCoordinate, parking, personId, +// parkingDurationInSeconds); +// parkingScoreManager.addScore(personId, walkScore); +// +// eventsManager.processEvent( +// new ParkingArrivalEvent(arrivalTime, parking.getId(), personId, destCoordinate, walkScore)); +// +// return parking; +// } // TODO: make this method abstract // when person/vehicleId is clearly distinct, then I can change this to @@ -227,8 +227,7 @@ public synchronized PC2Parking parkVehicle(ParkingOperationRequestAttributes par boolean parkingFound = false; // first search for parking at selected facility: - for (PPRestrictedToFacilities pp : privateParkingsRestrictedToFacilities - .get(parkingOperationRequestAttributes.facilityId)) { + for (PPRestrictedToFacilities pp : privateParkingsRestrictedToFacilities.get(parkingOperationRequestAttributes.facilityId)) { if (pp.getAvailableParkingCapacity() > 0) { // this tells the parking lot to decrease the number of @@ -248,7 +247,7 @@ public synchronized PC2Parking parkVehicle(ParkingOperationRequestAttributes par if (!parkingFound) { Collection collection = getFilteredCollection(parkingOperationRequestAttributes, distance); - while (collection.size() == 0) { + while ( collection.isEmpty() ) { distance *= 2; collection = getFilteredCollection(parkingOperationRequestAttributes, distance); @@ -278,8 +277,7 @@ public synchronized PC2Parking parkVehicle(ParkingOperationRequestAttributes par selectedParking = poll.getKey(); if (rentablePrivateParking.containsKey(parkingOperationRequestAttributes.personId)) { - RentableParking rentableParking = rentablePrivateParking - .get(parkingOperationRequestAttributes.personId); + RentableParking rentableParking = rentablePrivateParking.get(parkingOperationRequestAttributes.personId); if (rentableParking.getAvailableParkingCapacity() > 0) { @@ -508,16 +506,12 @@ public synchronized void unParkVehicle(PC2Parking parking, double departureTime, if (!(parking instanceof PrivateParking)) { addParkingToQuadTree(publicParkingsQuadTree, parking); addParkingToQuadTree(publicParkingGroupQuadTrees.get(parking.getGroupName()), parking); - // I could speculate that full parking lots are removed from the - // quad tree, and it is re-added as soon - // as space becomes available. But this is not commented, and it - // also does not look like it would work in that way. - // kai, jul'15 - // No, actually I now think that it works. When - // remainingCapacity==0, then the parking is removed from the - // list, and - // when (again) ==1, it is re-inserted. In addition, it is - // re-inserted in reset. + + // I could speculate that full parking lots are removed from the quad tree, and it is re-added as soon as space + // becomes available. But this is not commented, and it also does not look like it would work in that way. kai, jul'15 + + // No, actually I now think that it works. When remainingCapacity==0, then the parking is removed from the list, and + // when (again) ==1, it is re-inserted. In addition, it is re-inserted in reset. } } @@ -528,10 +522,10 @@ public synchronized void unParkVehicle(PC2Parking parking, double departureTime, eventsManager.processEvent(new ParkingDepartureEvent(departureTime, parking.getId(), personId)); } - @Override - public synchronized ParkingScore getParkingScoreManager() { - return parkingScoreManager; - } +// @Override +// public synchronized ParkingScore getParkingScoreManager() { +// return parkingScoreManager; +// } @Override public synchronized EventsManager getEventsManager() { From 0282b8a11d18a9994baae47431588c32a2bd01b8 Mon Sep 17 00:00:00 2001 From: nkuehnel Date: Thu, 27 Jun 2024 13:19:57 +0200 Subject: [PATCH 002/101] add router binding for complex request unscheduling --- .../contrib/drt/prebooking/PrebookingModeQSimModule.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingModeQSimModule.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingModeQSimModule.java index badbb8624f5..e1ec52ac877 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingModeQSimModule.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingModeQSimModule.java @@ -22,7 +22,9 @@ import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.mobsim.framework.MobsimTimer; import org.matsim.core.mobsim.qsim.QSim; +import org.matsim.core.router.speedy.SpeedyALTFactory; import org.matsim.core.router.util.LeastCostPathCalculator; +import org.matsim.core.router.util.TravelDisutility; import org.matsim.core.router.util.TravelTime; public class PrebookingModeQSimModule extends AbstractDvrpModeQSimModule { @@ -97,6 +99,10 @@ protected void configureQSim() { bindModal(RequestUnscheduler.class).to(modalKey(SimpleRequestUnscheduler.class)); break; case Routing: + bindModal(LeastCostPathCalculator.class).toProvider(modalProvider(getter -> + new SpeedyALTFactory().createPathCalculator(getter.getModal(Network.class), + getter.getModal(TravelDisutility.class), getter.getModal(TravelTime.class) + ))); bindModal(RequestUnscheduler.class).to(modalKey(ComplexRequestUnscheduler.class)); break; default: From 4c5782121460f4617aec4508b8c6c7a6d903ed56 Mon Sep 17 00:00:00 2001 From: nkuehnel Date: Thu, 27 Jun 2024 13:43:27 +0200 Subject: [PATCH 003/101] use time as disutility --- .../contrib/drt/prebooking/PrebookingModeQSimModule.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingModeQSimModule.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingModeQSimModule.java index e1ec52ac877..19274c3fd8b 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingModeQSimModule.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingModeQSimModule.java @@ -17,6 +17,7 @@ import org.matsim.contrib.dvrp.fleet.DvrpVehicleLookup; import org.matsim.contrib.dvrp.optimizer.VrpOptimizer; import org.matsim.contrib.dvrp.passenger.*; +import org.matsim.contrib.dvrp.router.TimeAsTravelDisutility; import org.matsim.contrib.dvrp.run.AbstractDvrpModeQSimModule; import org.matsim.contrib.dvrp.schedule.ScheduleTimingUpdater; import org.matsim.core.api.experimental.events.EventsManager; @@ -101,7 +102,7 @@ protected void configureQSim() { case Routing: bindModal(LeastCostPathCalculator.class).toProvider(modalProvider(getter -> new SpeedyALTFactory().createPathCalculator(getter.getModal(Network.class), - getter.getModal(TravelDisutility.class), getter.getModal(TravelTime.class) + new TimeAsTravelDisutility(getter.getModal(TravelTime.class)), getter.getModal(TravelTime.class) ))); bindModal(RequestUnscheduler.class).to(modalKey(ComplexRequestUnscheduler.class)); break; From 2054bbacfde4d957ddbddbd858271eb4ab759c91 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 27 Jun 2024 14:37:07 +0000 Subject: [PATCH 004/101] Bump junit.version from 5.10.2 to 5.10.3 Bumps `junit.version` from 5.10.2 to 5.10.3. Updates `org.junit.jupiter:junit-jupiter-engine` from 5.10.2 to 5.10.3 - [Release notes](https://github.com/junit-team/junit5/releases) - [Commits](https://github.com/junit-team/junit5/compare/r5.10.2...r5.10.3) Updates `org.junit.jupiter:junit-jupiter` from 5.10.2 to 5.10.3 - [Release notes](https://github.com/junit-team/junit5/releases) - [Commits](https://github.com/junit-team/junit5/compare/r5.10.2...r5.10.3) --- updated-dependencies: - dependency-name: org.junit.jupiter:junit-jupiter-engine dependency-type: direct:development update-type: version-update:semver-patch - dependency-name: org.junit.jupiter:junit-jupiter dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 70842b4e875..0a677e59c8b 100644 --- a/pom.xml +++ b/pom.xml @@ -37,7 +37,7 @@ 7.0.0 2.17.1 2.5.0 - 5.10.2 + 5.10.3 From 126ffcd5ee636446c709c964d74c557292ce2337 Mon Sep 17 00:00:00 2001 From: rakow Date: Thu, 27 Jun 2024 20:36:22 +0200 Subject: [PATCH 005/101] norm subgroups to 1 (#3346) --- .../org/matsim/application/CommandRunner.java | 2 +- .../analysis/population/TripByGroupAnalysis.java | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/contribs/application/src/main/java/org/matsim/application/CommandRunner.java b/contribs/application/src/main/java/org/matsim/application/CommandRunner.java index b55fc548a56..ea0af2e6dd2 100644 --- a/contribs/application/src/main/java/org/matsim/application/CommandRunner.java +++ b/contribs/application/src/main/java/org/matsim/application/CommandRunner.java @@ -108,7 +108,7 @@ private void runCommand(Class clazz, Path input) thr MATSimAppCommand command = clazz.getDeclaredConstructor().newInstance(); String[] args = this.args.get(clazz); args = ArrayUtils.addAll(args, createArgs(clazz, args, input)); - log.info("Running {} with arguments: {}", clazz, Arrays.toString(args)); + log.info("Running {} with arguments: {}", clazz, String.join(" ", args)); command.execute(args); } diff --git a/contribs/application/src/main/java/org/matsim/application/analysis/population/TripByGroupAnalysis.java b/contribs/application/src/main/java/org/matsim/application/analysis/population/TripByGroupAnalysis.java index 47edfec0824..b63a58f5ed8 100644 --- a/contribs/application/src/main/java/org/matsim/application/analysis/population/TripByGroupAnalysis.java +++ b/contribs/application/src/main/java/org/matsim/application/analysis/population/TripByGroupAnalysis.java @@ -81,6 +81,22 @@ final class TripByGroupAnalysis { } } + // Norm shares per instance of each group to sum of 1 + for (Group group : this.groups) { + + String norm = group.columns.get(0); + if (group.columns.size() > 1) + throw new UnsupportedOperationException("Multiple columns not supported yet"); + + Table df = group.data; + for (String label : df.stringColumn(norm).asSet()) { + DoubleColumn dist_group = df.doubleColumn("share"); + Selection sel = df.stringColumn(norm).isEqualTo(label); + double total = dist_group.where(sel).sum(); + if (total > 0) + dist_group.set(sel, dist_group.divide(total)); + } + } } } From b49541f8f4b1f9bcdb444120d2fdf076a6bff9c4 Mon Sep 17 00:00:00 2001 From: nkuehnel Date: Fri, 28 Jun 2024 12:52:54 +0200 Subject: [PATCH 006/101] add test integration test case for complex unscheduler --- .../ComplexRequestUnscheduler.java | 22 +++++-- .../drt/prebooking/AbandonAndCancelTest.java | 65 +++++++++++++++++++ .../drt/prebooking/PrebookingTest.java | 13 +++- 3 files changed, 91 insertions(+), 9 deletions(-) diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/unscheduler/ComplexRequestUnscheduler.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/unscheduler/ComplexRequestUnscheduler.java index 4fb0cae5339..ca25cb41cbf 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/unscheduler/ComplexRequestUnscheduler.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/unscheduler/ComplexRequestUnscheduler.java @@ -65,7 +65,7 @@ public void unscheduleRequest(double now, Id vehicleId, Id DvrpVehicle vehicle = vehicleLookup.lookupVehicle(vehicleId); VehicleEntry vEntry = vehicleEntryFactory.create(vehicle, now); - Waypoint.Stop pickupStop = null; + Waypoint pickupStop = null; Waypoint.Stop dropoffStop = null; DrtStopTask pickupStopTask = null; @@ -89,6 +89,15 @@ public void unscheduleRequest(double now, Id vehicleId, Id } } + if(pickupStopTask == null) { + if(vEntry.start.task.orElseThrow() instanceof DrtStopTask stopTask) { + if(stopTask.getPickupRequests().containsKey(requestId)) { + pickupStopTask = stopTask; + pickupStop = vEntry.start; + } + } + } + Verify.verifyNotNull(pickupStopTask, "Could not find request that I'm supposed to unschedule"); Verify.verifyNotNull(dropoffStopTask, "Could not find request that I'm supposed to unschedule"); Verify.verifyNotNull(pickupStop); @@ -103,12 +112,13 @@ public void unscheduleRequest(double now, Id vehicleId, Id // removed the pickup and the StopAction will handle the situation // - or we found a stop, then it is not started yet and we can remove it - boolean removePickup = pickupStopTask.getPickupRequests().size() == 0 - && pickupStopTask.getDropoffRequests().size() == 0; - boolean removeDropoff = dropoffStopTask.getPickupRequests().size() == 0 - && dropoffStopTask.getDropoffRequests().size() == 0; + boolean removePickup = pickupStopTask.getPickupRequests().isEmpty() + && pickupStopTask.getDropoffRequests().isEmpty() + && pickupStop instanceof Waypoint.Stop; + boolean removeDropoff = dropoffStopTask.getPickupRequests().isEmpty() + && dropoffStopTask.getDropoffRequests().isEmpty(); - Replacement pickupReplacement = removePickup ? findReplacement(vEntry, pickupStop) : null; + Replacement pickupReplacement = removePickup ? findReplacement(vEntry, (Waypoint.Stop) pickupStop) : null; Replacement dropoffReplacement = removeDropoff ? findReplacement(vEntry, dropoffStop) : null; if (pickupReplacement != null && dropoffReplacement != null) { diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/AbandonAndCancelTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/AbandonAndCancelTest.java index 61241d7c293..ca3f22dd46f 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/AbandonAndCancelTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/AbandonAndCancelTest.java @@ -265,4 +265,69 @@ public void notifyMobsimBeforeSimStep(MobsimBeforeSimStepEvent e) { assertTrue(requestInfo.rejected); } } + + @Test + void cancelLateWithComplexUnschedulerTest() { + /* + * One person requests to depart at 2000 and also is there at 2000. Another + * person asks also to depart at 2000, but only arrives at 4000, i.e. the person + * has 1000s delay. + * + * In this test we manually cancel the second request at 3000.0 (so after + * departure of the first agent). + */ + + PrebookingTestEnvironment environment = new PrebookingTestEnvironment(utils) // + .addVehicle("vehicle", 1, 1) // + .addRequest("personOk", 0, 0, 5, 5, 2000.0, 0.0, 2000.0) // + .addRequest("personLate", 0, 0, 5, 5, 4000.0, 0.0, 2000.0) // + .configure(600.0, 1.3, 600.0, 60.0) // + .endTime(10.0 * 3600.0); + + Controler controller = environment.build(); + PrebookingParams prebookingParams = new PrebookingParams(); + prebookingParams.unschedulingMode = PrebookingParams.UnschedulingMode.Routing; + PrebookingTest.installPrebooking(controller, prebookingParams); + + controller.addOverridingQSimModule(new AbstractDvrpModeQSimModule("drt") { + @Override + protected void configureQSim() { + addModalQSimComponentBinding().toProvider(modalProvider(getter -> { + PrebookingManager prebookingManager = getter.getModal(PrebookingManager.class); + QSim qsim = getter.get(QSim.class); + + return new MobsimBeforeSimStepListener() { + @Override + public void notifyMobsimBeforeSimStep(MobsimBeforeSimStepEvent e) { + if (e.getSimulationTime() == 3000.0) { + PlanAgent planAgent = (PlanAgent) qsim.getAgents() + .get(Id.createPersonId("personLate")); + + Leg leg = TripStructureUtils.getLegs(planAgent.getCurrentPlan()).get(1); + + prebookingManager.cancel(leg); + } + } + }; + })); + } + }); + + controller.run(); + + { + RequestInfo requestInfo = environment.getRequestInfo().get("personOk"); + assertEquals(0.0, requestInfo.submissionTime, 1e-3); + assertEquals(2061.0, requestInfo.pickupTime, 1e-3); + assertEquals(3212.0, requestInfo.dropoffTime, 1e-3); // still waited quite a bit + } + + { + RequestInfo requestInfo = environment.getRequestInfo().get("personLate"); + assertEquals(0.0, requestInfo.submissionTimes.get(0), 1e-3); + // agent tries a non-prebooked request upon arrival + assertEquals(4000.0, requestInfo.submissionTimes.get(1), 1e-3); + assertTrue(requestInfo.rejected); + } + } } diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/PrebookingTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/PrebookingTest.java index 8a2f236a7b0..4809a205c8a 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/PrebookingTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/PrebookingTest.java @@ -12,7 +12,6 @@ import org.matsim.contrib.drt.stops.StaticPassengerStopDurationProvider; import org.matsim.contrib.dvrp.fleet.DvrpVehicle; import org.matsim.contrib.dvrp.run.AbstractDvrpModeModule; -import org.matsim.contrib.dvrp.run.AbstractDvrpModeQSimModule; import org.matsim.core.controler.Controler; import org.matsim.testcases.MatsimTestUtils; @@ -57,12 +56,20 @@ void withoutPrebookedRequests() { } static PrebookingParams installPrebooking(Controler controller) { - return installPrebooking(controller, true); + return installPrebooking(controller, true, new PrebookingParams()); + } + + static PrebookingParams installPrebooking(Controler controller, PrebookingParams prebookingParams) { + return installPrebooking(controller, true, prebookingParams); } static PrebookingParams installPrebooking(Controler controller, boolean installLogic) { + return installPrebooking(controller, installLogic, new PrebookingParams()); + } + + static PrebookingParams installPrebooking(Controler controller, boolean installLogic, PrebookingParams prebookingParams) { DrtConfigGroup drtConfig = DrtConfigGroup.getSingleModeDrtConfig(controller.getConfig()); - drtConfig.addParameterSet(new PrebookingParams()); + drtConfig.addParameterSet(prebookingParams); if (installLogic) { AttributeBasedPrebookingLogic.install(controller, drtConfig); From e38801634c640e8529f5d86bd8268ae9efe5d257 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 28 Jun 2024 14:45:37 +0000 Subject: [PATCH 007/101] Bump io.grpc:grpc-all from 1.64.0 to 1.65.0 Bumps [io.grpc:grpc-all](https://github.com/grpc/grpc-java) from 1.64.0 to 1.65.0. - [Release notes](https://github.com/grpc/grpc-java/releases) - [Commits](https://github.com/grpc/grpc-java/compare/v1.64.0...v1.65.0) --- updated-dependencies: - dependency-name: io.grpc:grpc-all dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- contribs/hybridsim/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contribs/hybridsim/pom.xml b/contribs/hybridsim/pom.xml index a94a59e4058..940af6cbe34 100644 --- a/contribs/hybridsim/pom.xml +++ b/contribs/hybridsim/pom.xml @@ -11,7 +11,7 @@ 4.27.1 - 1.64.0 + 1.65.0 From 3702bb5bf43e869094e639fe6d8e26f020b944bd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 30 Jun 2024 14:30:40 +0000 Subject: [PATCH 008/101] Bump com.google.protobuf:protobuf-java from 4.27.1 to 4.27.2 Bumps [com.google.protobuf:protobuf-java](https://github.com/protocolbuffers/protobuf) from 4.27.1 to 4.27.2. - [Release notes](https://github.com/protocolbuffers/protobuf/releases) - [Changelog](https://github.com/protocolbuffers/protobuf/blob/main/protobuf_release.bzl) - [Commits](https://github.com/protocolbuffers/protobuf/commits) --- updated-dependencies: - dependency-name: com.google.protobuf:protobuf-java dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- contribs/hybridsim/pom.xml | 2 +- contribs/protobuf/pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/contribs/hybridsim/pom.xml b/contribs/hybridsim/pom.xml index 940af6cbe34..5917f032e3e 100644 --- a/contribs/hybridsim/pom.xml +++ b/contribs/hybridsim/pom.xml @@ -10,7 +10,7 @@ hybridsim - 4.27.1 + 4.27.2 1.65.0 diff --git a/contribs/protobuf/pom.xml b/contribs/protobuf/pom.xml index b93c87b1246..a2c8a4ef62b 100644 --- a/contribs/protobuf/pom.xml +++ b/contribs/protobuf/pom.xml @@ -11,7 +11,7 @@ protobuf - 4.27.1 + 4.27.2 From d6c43d9b6fa2c17d9fb6ccf85df084fcda721c1d Mon Sep 17 00:00:00 2001 From: marecabo <23156476+marecabo@users.noreply.github.com> Date: Tue, 2 Jul 2024 12:51:11 +0200 Subject: [PATCH 009/101] Split CalculateSkimMatrices.prepareAndCalculateNetworkMatrices() to allow for custom travel times objects --- .../analysis/skims/CalculateSkimMatrices.java | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/CalculateSkimMatrices.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/CalculateSkimMatrices.java index f65f15224ac..78875ce775c 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/CalculateSkimMatrices.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/CalculateSkimMatrices.java @@ -39,6 +39,9 @@ import java.util.function.BiPredicate; import java.util.function.Predicate; import java.util.function.ToDoubleFunction; + +import javax.annotation.Nullable; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.geotools.api.feature.simple.SimpleFeature; @@ -350,8 +353,8 @@ public final FloatMatrix calculateBeelineMatrix() { return BeelineDistanceMatrix.calculateBeelineDistanceMatrix(this.coordsPerZone.keySet(), coordsPerZone, numberOfThreads); } - public final void calculateAndWriteNetworkMatrices(String networkFilename, String eventsFilename, double[] times, Config config, String outputPrefix, Predicate xy2linksPredicate) - throws IOException { + public final void calculateAndWriteNetworkMatrices(String networkFilename, @Nullable String eventsFilename, + double[] times, Config config, String outputPrefix, Predicate xy2linksPredicate) throws IOException { String prefix = outputPrefix == null ? "" : outputPrefix; var netIndicators = prepareAndCalculateNetworkMatrices(networkFilename, eventsFilename, times, config, xy2linksPredicate); writeNetworkMatricesAsCSV(netIndicators, prefix); @@ -363,7 +366,8 @@ public final void writeNetworkMatricesAsCSV(NetworkIndicators netIndicat FloatMatrixIO.writeAsCSV(netIndicators.distanceMatrix, outputDirectory + "/" + prefix + CAR_DISTANCES_FILENAME); } - public final NetworkIndicators prepareAndCalculateNetworkMatrices(String networkFilename, String eventsFilename, double[] times, Config config, Predicate xy2linksPredicate) { + public final NetworkIndicators prepareAndCalculateNetworkMatrices(String networkFilename, + @Nullable String eventsFilename, double[] times, Config config, Predicate xy2linksPredicate) { Scenario scenario = ScenarioUtils.createScenario(config); log.info("loading network from " + networkFilename); new MatsimNetworkReader(scenario.getNetwork()).readFile(networkFilename); @@ -382,11 +386,16 @@ public final NetworkIndicators prepareAndCalculateNetworkMatrices(String log.info("No events specified. Travel Times will be calculated with free speed travel times."); } + return prepareAndCalculateNetworkMatrices(scenario.getNetwork(), tt, times, config, xy2linksPredicate); + } + + public final NetworkIndicators prepareAndCalculateNetworkMatrices(Network network, TravelTime tt, + double[] times, Config config, Predicate xy2linksPredicate) { TravelDisutility td = new OnlyTimeDependentTravelDisutility(tt); log.info("extracting car-only network"); final Network carNetwork = NetworkUtils.createNetwork(config); - new TransportModeNetworkFilter(scenario.getNetwork()).filter(carNetwork, Collections.singleton(TransportMode.car)); + new TransportModeNetworkFilter(network).filter(carNetwork, Collections.singleton(TransportMode.car)); log.info("filter car-only network for assigning links to locations"); final Network xy2linksNetwork = extractXy2LinksNetwork(carNetwork, xy2linksPredicate, config); From 8dfc8c3eddeef26191b3791169d9958bdec29bef Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 2 Jul 2024 14:34:23 +0000 Subject: [PATCH 010/101] Bump org.checkerframework:checker-qual from 3.44.0 to 3.45.0 Bumps [org.checkerframework:checker-qual](https://github.com/typetools/checker-framework) from 3.44.0 to 3.45.0. - [Release notes](https://github.com/typetools/checker-framework/releases) - [Changelog](https://github.com/typetools/checker-framework/blob/master/docs/CHANGELOG.md) - [Commits](https://github.com/typetools/checker-framework/compare/checker-framework-3.44.0...checker-framework-3.45.0) --- updated-dependencies: - dependency-name: org.checkerframework:checker-qual dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 0a677e59c8b..2df319d6476 100644 --- a/pom.xml +++ b/pom.xml @@ -296,7 +296,7 @@ org.checkerframework checker-qual - 3.44.0 + 3.45.0 From 8313a4d5518158da26b7d60a079d9823f04b8237 Mon Sep 17 00:00:00 2001 From: steffenaxer <26229392+steffenaxer@users.noreply.github.com> Date: Wed, 3 Jul 2024 20:31:43 +0200 Subject: [PATCH 011/101] Switch to DrtWithExtensionsConfigGroup --- .../DrtOperationsControlerCreator.java | 3 +- .../DrtWithOperationsConfigGroup.java | 31 ------------------- .../EDrtOperationsControlerCreator.java | 3 +- .../run/ShiftEDrtModeOptimizerQSimModule.java | 4 +-- .../OperationFacilitiesModeModule.java | 6 ++-- .../shifts/run/ShiftDrtModeModule.java | 4 +-- .../run/ShiftDrtModeOptimizerQSimModule.java | 4 +-- .../extension/fiss/RunFissDrtScenarioIT.java | 6 ++-- .../eshifts/run/RunEShiftDrtScenarioIT.java | 7 +++-- .../run/RunMultiHubShiftDrtScenarioIT.java | 6 ++-- .../shifts/run/RunShiftDrtScenarioIT.java | 6 ++-- 11 files changed, 26 insertions(+), 54 deletions(-) delete mode 100644 contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtWithOperationsConfigGroup.java diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtOperationsControlerCreator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtOperationsControlerCreator.java index 9a1772ca184..835cc77e9e2 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtOperationsControlerCreator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtOperationsControlerCreator.java @@ -1,5 +1,6 @@ package org.matsim.contrib.drt.extension.operations; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilitiesModeModule; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilitiesQSimModule; import org.matsim.contrib.drt.extension.operations.shifts.analysis.efficiency.DrtShiftEfficiencyModeModule; @@ -33,7 +34,7 @@ public static Controler createControler(Config config, boolean otfvis) { for (DrtConfigGroup drtCfg : multiModeDrtConfig.getModalElements()) { controler.addOverridingModule(new ShiftDrtModeModule(drtCfg)); controler.addOverridingQSimModule(new DrtModeQSimModule(drtCfg, new ShiftDrtModeOptimizerQSimModule(drtCfg))); - controler.addOverridingModule(new OperationFacilitiesModeModule((DrtWithOperationsConfigGroup) drtCfg)); + controler.addOverridingModule(new OperationFacilitiesModeModule((DrtWithExtensionsConfigGroup) drtCfg)); controler.addOverridingQSimModule(new OperationFacilitiesQSimModule(drtCfg)); controler.addOverridingModule(new DrtShiftEfficiencyModeModule(drtCfg)); } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtWithOperationsConfigGroup.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtWithOperationsConfigGroup.java deleted file mode 100644 index d33e6c74c2e..00000000000 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtWithOperationsConfigGroup.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2022 MOIA GmbH - All Rights Reserved - * - * You may use, distribute and modify this code under the terms - * of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, - * or (at your option) any later version. - */ -package org.matsim.contrib.drt.extension.operations; - -import jakarta.validation.constraints.NotNull; -import org.matsim.contrib.drt.run.DrtConfigGroup; - -/** - * @author mdziakowski / MOIA - */ -public class DrtWithOperationsConfigGroup extends DrtConfigGroup { - - @NotNull - private DrtOperationsParams drtOperationsParams; - - public DrtWithOperationsConfigGroup() { - addDefinition(DrtOperationsParams.SET_NAME, DrtOperationsParams::new, - () -> drtOperationsParams, - params -> drtOperationsParams = (DrtOperationsParams)params); - } - - public DrtOperationsParams getDrtOperationsParams() { - return drtOperationsParams; - } -} diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/EDrtOperationsControlerCreator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/EDrtOperationsControlerCreator.java index c0b78a1a5bb..da76f73772d 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/EDrtOperationsControlerCreator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/EDrtOperationsControlerCreator.java @@ -1,5 +1,6 @@ package org.matsim.contrib.drt.extension.operations; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.edrt.run.EDrtControlerCreator; import org.matsim.contrib.drt.extension.operations.eshifts.charging.ShiftOperatingVehicleProvider; import org.matsim.contrib.drt.extension.operations.eshifts.fleet.EvShiftDvrpFleetQSimModule; @@ -33,7 +34,7 @@ public static Controler createControler(Config config, boolean otfvis) { controler.addOverridingQSimModule(new DrtModeQSimModule(drtCfg, new ShiftDrtModeOptimizerQSimModule(drtCfg))); controler.addOverridingQSimModule(new ShiftEDrtModeOptimizerQSimModule(drtCfg)); controler.addOverridingQSimModule(new EvShiftDvrpFleetQSimModule(drtCfg.getMode())); - controler.addOverridingModule(new OperationFacilitiesModeModule((DrtWithOperationsConfigGroup) drtCfg)); + controler.addOverridingModule(new OperationFacilitiesModeModule((DrtWithExtensionsConfigGroup) drtCfg)); controler.addOverridingQSimModule(new OperationFacilitiesQSimModule(drtCfg)); controler.addOverridingModule(new DrtShiftEfficiencyModeModule(drtCfg)); } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/run/ShiftEDrtModeOptimizerQSimModule.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/run/ShiftEDrtModeOptimizerQSimModule.java index afbf606fc1d..ab4bf41c938 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/run/ShiftEDrtModeOptimizerQSimModule.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/run/ShiftEDrtModeOptimizerQSimModule.java @@ -2,12 +2,12 @@ import com.google.inject.Singleton; import org.matsim.api.core.v01.network.Network; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.edrt.EDrtActionCreator; import org.matsim.contrib.drt.extension.edrt.optimizer.EDrtVehicleDataEntryFactory; import org.matsim.contrib.drt.extension.edrt.schedule.EDrtTaskFactoryImpl; import org.matsim.contrib.drt.extension.edrt.scheduler.EmptyVehicleChargingScheduler; import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; -import org.matsim.contrib.drt.extension.operations.DrtWithOperationsConfigGroup; import org.matsim.contrib.drt.extension.operations.eshifts.dispatcher.EDrtAssignShiftToVehicleLogic; import org.matsim.contrib.drt.extension.operations.eshifts.dispatcher.EDrtShiftDispatcherImpl; import org.matsim.contrib.drt.extension.operations.eshifts.dispatcher.EDrtShiftStartLogic; @@ -53,7 +53,7 @@ public class ShiftEDrtModeOptimizerQSimModule extends AbstractDvrpModeQSimModule public ShiftEDrtModeOptimizerQSimModule(DrtConfigGroup drtCfg) { super(drtCfg.getMode()); - this.drtOperationsParams = ((DrtWithOperationsConfigGroup) drtCfg).getDrtOperationsParams(); + this.drtOperationsParams = ((DrtWithExtensionsConfigGroup) drtCfg).getDrtOperationsParams().orElseThrow(); this.drtCfg = drtCfg; } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/OperationFacilitiesModeModule.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/OperationFacilitiesModeModule.java index 15276252c50..e178fc0a69d 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/OperationFacilitiesModeModule.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/OperationFacilitiesModeModule.java @@ -1,6 +1,6 @@ package org.matsim.contrib.drt.extension.operations.operationFacilities; -import org.matsim.contrib.drt.extension.operations.DrtWithOperationsConfigGroup; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.operations.shifts.io.OperationFacilitiesReader; import org.matsim.contrib.dvrp.run.AbstractDvrpModeModule; @@ -8,9 +8,9 @@ public class OperationFacilitiesModeModule extends AbstractDvrpModeModule { private final OperationFacilitiesParams operationFacilitiesParams; - public OperationFacilitiesModeModule(DrtWithOperationsConfigGroup drtCfg) { + public OperationFacilitiesModeModule(DrtWithExtensionsConfigGroup drtCfg) { super(drtCfg.getMode()); - this.operationFacilitiesParams = drtCfg.getDrtOperationsParams().getOperationFacilitiesParams().orElseThrow(); + this.operationFacilitiesParams = drtCfg.getDrtOperationsParams().orElseThrow().getOperationFacilitiesParams().orElseThrow(); } @Override diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeModule.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeModule.java index 91e324456d1..7df2d885723 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeModule.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeModule.java @@ -6,8 +6,8 @@ import com.google.inject.Singleton; import com.google.inject.TypeLiteral; import org.matsim.api.core.v01.population.Population; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; -import org.matsim.contrib.drt.extension.operations.DrtWithOperationsConfigGroup; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilitiesSpecification; import org.matsim.contrib.drt.extension.operations.shifts.analysis.*; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; @@ -52,7 +52,7 @@ public class ShiftDrtModeModule extends AbstractDvrpModeModule { public ShiftDrtModeModule(DrtConfigGroup drtCfg) { super(drtCfg.getMode()); this.drtConfigGroup = drtCfg; - this.drtOperationsParams = ((DrtWithOperationsConfigGroup) drtCfg).getDrtOperationsParams(); + this.drtOperationsParams = ((DrtWithExtensionsConfigGroup) drtCfg).getDrtOperationsParams().orElseThrow(); } private static final Comparator taskTypeComparator = Comparator.comparing((Task.TaskType type) -> { diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeOptimizerQSimModule.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeOptimizerQSimModule.java index a10c6e409e3..a6398faf3b3 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeOptimizerQSimModule.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeOptimizerQSimModule.java @@ -4,8 +4,8 @@ import com.google.inject.Singleton; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Network; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; -import org.matsim.contrib.drt.extension.operations.DrtWithOperationsConfigGroup; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilities; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilityFinder; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; @@ -70,7 +70,7 @@ public class ShiftDrtModeOptimizerQSimModule extends AbstractDvrpModeQSimModule public ShiftDrtModeOptimizerQSimModule(DrtConfigGroup drtCfg) { super(drtCfg.getMode()); this.drtCfg = drtCfg; - this.drtOperationsParams = ((DrtWithOperationsConfigGroup) drtCfg).getDrtOperationsParams(); + this.drtOperationsParams = ((DrtWithExtensionsConfigGroup) drtCfg).getDrtOperationsParams().orElseThrow(); } @Override diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java index 3ae153f665a..2da1b30b225 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java @@ -7,9 +7,9 @@ import org.matsim.api.core.v01.events.handler.LinkLeaveEventHandler; import org.matsim.contrib.common.zones.systems.grid.square.SquareGridZoneSystemParams; import org.matsim.contrib.drt.analysis.zonal.DrtZoneSystemParams; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.operations.DrtOperationsControlerCreator; import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; -import org.matsim.contrib.drt.extension.operations.DrtWithOperationsConfigGroup; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilitiesParams; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; import org.matsim.contrib.drt.optimizer.constraints.DefaultDrtOptimizationConstraintsSet; @@ -42,7 +42,7 @@ public class RunFissDrtScenarioIT { @Test void test() { - MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithOperationsConfigGroup::new); + MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithExtensionsConfigGroup::new); String fleetFile = "holzkirchenFleet.xml"; String plansFile = "holzkirchenPlans_car_drt.xml.gz"; @@ -50,7 +50,7 @@ void test() { String opFacilitiesFile = "holzkirchenOperationFacilities.xml"; String shiftsFile = "holzkirchenShifts.xml"; - DrtWithOperationsConfigGroup drtWithShiftsConfigGroup = (DrtWithOperationsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); + DrtWithExtensionsConfigGroup drtWithShiftsConfigGroup = (DrtWithExtensionsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); DrtConfigGroup drtConfigGroup = drtWithShiftsConfigGroup; drtConfigGroup.mode = TransportMode.drt; diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/eshifts/run/RunEShiftDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/eshifts/run/RunEShiftDrtScenarioIT.java index 3b5d9830c29..a137d932fe5 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/eshifts/run/RunEShiftDrtScenarioIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/eshifts/run/RunEShiftDrtScenarioIT.java @@ -4,8 +4,9 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.contrib.common.zones.systems.grid.square.SquareGridZoneSystemParams; import org.matsim.contrib.drt.analysis.zonal.DrtZoneSystemParams; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; -import org.matsim.contrib.drt.extension.operations.DrtWithOperationsConfigGroup; + import org.matsim.contrib.drt.extension.operations.EDrtOperationsControlerCreator; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilitiesParams; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; @@ -43,7 +44,7 @@ public class RunEShiftDrtScenarioIT { @Test void test() { - MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithOperationsConfigGroup::new); + MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithExtensionsConfigGroup::new); String fleetFile = "holzkirchenFleet.xml"; String plansFile = "holzkirchenPlans.xml.gz"; @@ -53,7 +54,7 @@ void test() { String chargersFile = "holzkirchenChargers.xml"; String evsFile = "holzkirchenElectricFleet.xml"; - DrtWithOperationsConfigGroup drtWithShiftsConfigGroup = (DrtWithOperationsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); + DrtWithExtensionsConfigGroup drtWithShiftsConfigGroup = (DrtWithExtensionsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); DrtConfigGroup drtConfigGroup = drtWithShiftsConfigGroup; drtConfigGroup.mode = TransportMode.drt; diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunMultiHubShiftDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunMultiHubShiftDrtScenarioIT.java index 6f08a46d3c7..b481b20898f 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunMultiHubShiftDrtScenarioIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunMultiHubShiftDrtScenarioIT.java @@ -4,8 +4,8 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.contrib.common.zones.systems.grid.square.SquareGridZoneSystemParams; import org.matsim.contrib.drt.analysis.zonal.DrtZoneSystemParams; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.operations.DrtOperationsControlerCreator; -import org.matsim.contrib.drt.extension.operations.DrtWithOperationsConfigGroup; import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilitiesParams; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; @@ -34,7 +34,7 @@ public class RunMultiHubShiftDrtScenarioIT { @Test void test() { - MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithOperationsConfigGroup::new); + MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithExtensionsConfigGroup::new); String fleetFile = "holzkirchenMultiHubFleet.xml"; String plansFile = "holzkirchenPlans.xml.gz"; @@ -42,7 +42,7 @@ void test() { String opFacilitiesFile = "holzkirchenMultiHubOperationFacilities.xml"; String shiftsFile = "holzkirchenMultiHubShifts.xml"; - DrtWithOperationsConfigGroup drtWithShiftsConfigGroup = (DrtWithOperationsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); + DrtWithExtensionsConfigGroup drtWithShiftsConfigGroup = (DrtWithExtensionsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); DrtConfigGroup drtConfigGroup = drtWithShiftsConfigGroup; drtConfigGroup.mode = TransportMode.drt; diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunShiftDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunShiftDrtScenarioIT.java index 1b866a314d2..acfc878a000 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunShiftDrtScenarioIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunShiftDrtScenarioIT.java @@ -4,9 +4,9 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.contrib.common.zones.systems.grid.square.SquareGridZoneSystemParams; import org.matsim.contrib.drt.analysis.zonal.DrtZoneSystemParams; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.operations.DrtOperationsControlerCreator; import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; -import org.matsim.contrib.drt.extension.operations.DrtWithOperationsConfigGroup; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilitiesParams; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; import org.matsim.contrib.drt.optimizer.constraints.DefaultDrtOptimizationConstraintsSet; @@ -36,7 +36,7 @@ public class RunShiftDrtScenarioIT { @Test void test() { - MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithOperationsConfigGroup::new); + MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithExtensionsConfigGroup::new); String fleetFile = "holzkirchenFleet.xml"; String plansFile = "holzkirchenPlans.xml.gz"; @@ -44,7 +44,7 @@ void test() { String opFacilitiesFile = "holzkirchenOperationFacilities.xml"; String shiftsFile = "holzkirchenShifts.xml"; - DrtWithOperationsConfigGroup drtWithShiftsConfigGroup = (DrtWithOperationsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); + DrtWithExtensionsConfigGroup drtWithShiftsConfigGroup = (DrtWithExtensionsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); drtWithShiftsConfigGroup.mode = TransportMode.drt; DefaultDrtOptimizationConstraintsSet defaultConstraintsSet = From 64c4bd54e5f4707ae36b91f38c5e06153d78aaf8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 4 Jul 2024 06:50:53 +0000 Subject: [PATCH 012/101] Bump org.apache.poi:poi-ooxml from 5.2.5 to 5.3.0 Bumps org.apache.poi:poi-ooxml from 5.2.5 to 5.3.0. --- updated-dependencies: - dependency-name: org.apache.poi:poi-ooxml dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- contribs/vsp/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contribs/vsp/pom.xml b/contribs/vsp/pom.xml index fe92d90b3a5..b2bf9fb3a41 100644 --- a/contribs/vsp/pom.xml +++ b/contribs/vsp/pom.xml @@ -150,7 +150,7 @@ org.apache.poi poi-ooxml - 5.2.5 + 5.3.0 From 56f586865d656f065050713de5a39bbcebae07c0 Mon Sep 17 00:00:00 2001 From: u229351 Date: Thu, 4 Jul 2024 13:56:02 +0200 Subject: [PATCH 013/101] reworked CreatePseudoNetwork with loop-links to avoid duplicating stops --- .../matsim/pt/utils/CreatePseudoNetwork.java | 124 +++++++----------- 1 file changed, 48 insertions(+), 76 deletions(-) diff --git a/matsim/src/main/java/org/matsim/pt/utils/CreatePseudoNetwork.java b/matsim/src/main/java/org/matsim/pt/utils/CreatePseudoNetwork.java index cae2eaf0f43..eb9f7f04235 100644 --- a/matsim/src/main/java/org/matsim/pt/utils/CreatePseudoNetwork.java +++ b/matsim/src/main/java/org/matsim/pt/utils/CreatePseudoNetwork.java @@ -29,28 +29,33 @@ import java.util.Set; import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; +import org.matsim.api.core.v01.network.NetworkWriter; import org.matsim.api.core.v01.network.Node; +import org.matsim.core.config.ConfigUtils; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.population.routes.RouteUtils; +import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.collections.Tuple; import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.pt.transitSchedule.api.TransitLine; import org.matsim.pt.transitSchedule.api.TransitRoute; import org.matsim.pt.transitSchedule.api.TransitRouteStop; import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.pt.transitSchedule.api.TransitStopArea; +import org.matsim.pt.transitSchedule.api.TransitScheduleReader; +import org.matsim.pt.transitSchedule.api.TransitScheduleWriter; import org.matsim.pt.transitSchedule.api.TransitStopFacility; /** * Builds a network where transit vehicles can drive along and assigns the correct - * links to the transit stop facilities and routes of transit lines. As each transit - * stop facility can only be connected to at most one link, the algorithm is forced - * to duplicated transit stop facilities in certain cases to build the network. + * links to the transit stop facilities and routes of transit lines. Each stop facility + * is assigned to a loop link, located in a node with the same coordinates as the stop. + * The stop facility ID is used for node and link IDs. * - * @author mrieser + * @author mrieser, davibicudo */ public class CreatePseudoNetwork { @@ -59,14 +64,9 @@ public class CreatePseudoNetwork { private final String prefix; private final double linkFreeSpeed; private final double linkCapacity; - - private final Map, Link> links = new HashMap, Link>(); - private final Map, TransitStopFacility> stopFacilities = new HashMap, TransitStopFacility>(); - private final Map nodes = new HashMap(); - private final Map> facilityCopies = new HashMap>(); - - private long linkIdCounter = 0; + private final Map, Link> links = new HashMap<>(); + private final Map nodes = new HashMap<>(); private final Set transitModes = Collections.singleton(TransportMode.pt); @@ -77,8 +77,8 @@ public CreatePseudoNetwork(final TransitSchedule schedule, final Network network this.linkFreeSpeed = 100.0 / 3.6; this.linkCapacity = 100000.0; } - - public CreatePseudoNetwork(final TransitSchedule schedule, final Network network, final String networkIdPrefix, + + public CreatePseudoNetwork(final TransitSchedule schedule, final Network network, final String networkIdPrefix, final double linkFreeSpeed, final double linkCapacity) { this.schedule = schedule; this.network = network; @@ -89,24 +89,27 @@ public CreatePseudoNetwork(final TransitSchedule schedule, final Network network public void createNetwork() { - List> toBeRemoved = new LinkedList>(); + createStopNodesAndLoopLinks(); + List> toBeRemoved = new LinkedList<>(); for (TransitLine tLine : this.schedule.getTransitLines().values()) { for (TransitRoute tRoute : tLine.getRoutes().values()) { - ArrayList> routeLinks = new ArrayList>(); + ArrayList> routeLinks = new ArrayList<>(); TransitRouteStop prevStop = null; for (TransitRouteStop stop : tRoute.getStops()) { - Link link = getNetworkLink(prevStop, stop); - routeLinks.add(link.getId()); + if (prevStop != null) { + Link link = getNetworkLink(prevStop, stop); + routeLinks.add(link.getId()); + } prevStop = stop; } - if (routeLinks.size() > 0) { - NetworkRoute route = RouteUtils.createNetworkRoute(routeLinks ); + if (!routeLinks.isEmpty()) { + NetworkRoute route = RouteUtils.createNetworkRoute(routeLinks); tRoute.setRoute(route); } else { System.err.println("Line " + tLine.getId() + " route " + tRoute.getId() + " has less than two stops. Removing this route from schedule."); - toBeRemoved.add(new Tuple(tLine, tRoute)); + toBeRemoved.add(new Tuple<>(tLine, tRoute)); } } } @@ -116,64 +119,40 @@ public void createNetwork() { } } + private void createStopNodesAndLoopLinks() { + for (TransitStopFacility stop : this.schedule.getFacilities().values()) { + Node node = this.network.getFactory().createNode(Id.createNodeId(this.prefix + stop.getId()), stop.getCoord()); + this.network.addNode(node); + this.nodes.put(stop, node); + + Link loopLink = this.network.getFactory().createLink(Id.createLinkId (this.prefix + stop.getId()), node, node); + stop.setLinkId(loopLink.getId()); + this.network.addLink(loopLink); + Tuple connection = new Tuple<>(node, node); + this.links.put(connection, loopLink); + } + } + private Link getNetworkLink(final TransitRouteStop fromStop, final TransitRouteStop toStop) { - TransitStopFacility fromFacility = (fromStop == null) ? toStop.getStopFacility() : fromStop.getStopFacility(); + TransitStopFacility fromFacility = fromStop.getStopFacility(); TransitStopFacility toFacility = toStop.getStopFacility(); Node fromNode = this.nodes.get(fromFacility); - if (fromNode == null) { - fromNode = this.network.getFactory().createNode(Id.create(this.prefix + toFacility.getId(), Node.class), fromFacility.getCoord()); - this.network.addNode(fromNode); - this.nodes.put(toFacility, fromNode); - } - Node toNode = this.nodes.get(toFacility); - if (toNode == null) { - toNode = this.network.getFactory().createNode(Id.create(this.prefix + toFacility.getId(), Node.class), toFacility.getCoord()); - this.network.addNode(toNode); - this.nodes.put(toFacility, toNode); - } - Tuple connection = new Tuple(fromNode, toNode); + Tuple connection = new Tuple<>(fromNode, toNode); Link link = this.links.get(connection); - if (link == null) { - link = createAndAddLink(fromNode, toNode, connection); - - if (toFacility.getLinkId() == null) { - toFacility.setLinkId(link.getId()); - this.stopFacilities.put(connection, toFacility); - } else { - List copies = this.facilityCopies.get(toFacility); - if (copies == null) { - copies = new ArrayList(); - this.facilityCopies.put(toFacility, copies); - } - Id newId = Id.create(toFacility.getId().toString() + "." + Integer.toString(copies.size() + 1), TransitStopFacility.class); - TransitStopFacility newFacility = this.schedule.getFactory().createTransitStopFacility(newId, toFacility.getCoord(), toFacility.getIsBlockingLane()); - newFacility.setStopAreaId(Id.create(toFacility.getId(), TransitStopArea.class)); - newFacility.setLinkId(link.getId()); - newFacility.setName(toFacility.getName()); - copies.add(newFacility); - this.nodes.put(newFacility, toNode); - this.schedule.addStopFacility(newFacility); - toStop.setStopFacility(newFacility); - this.stopFacilities.put(connection, newFacility); - } - } else { - toStop.setStopFacility(this.stopFacilities.get(connection)); - } - return link; + return link == null ? createAndAddLink(connection) : link; } - private Link createAndAddLink(Node fromNode, Node toNode, - Tuple connection) { + private Link createAndAddLink(Tuple connection) { + Node fromNode = connection.getFirst(); + Node toNode = connection.getSecond(); Link link; - link = this.network.getFactory().createLink(Id.create(this.prefix + this.linkIdCounter++, Link.class), fromNode, toNode); - if (fromNode == toNode) { - link.setLength(50); - } else { - link.setLength(CoordUtils.calcEuclideanDistance(fromNode.getCoord(), toNode.getCoord())); - } + link = this.network.getFactory().createLink(Id.createLinkId(this.prefix + fromNode.getId() + "-" + toNode.getId()), fromNode, + toNode); + link.setLength(CoordUtils.calcEuclideanDistance(fromNode.getCoord(), toNode.getCoord())); + link.setFreespeed(linkFreeSpeed); link.setCapacity(linkCapacity); link.setNumberOfLanes(1); @@ -183,11 +162,4 @@ private Link createAndAddLink(Node fromNode, Node toNode, return link; } - public Link getLinkBetweenStops(final TransitStopFacility fromStop, final TransitStopFacility toStop) { - Node fromNode = this.nodes.get(fromStop); - Node toNode = this.nodes.get(toStop); - Tuple connection = new Tuple(fromNode, toNode); - return this.links.get(connection); - } - } From 8ddacdf344c2a6067f66b2886afda1d767c7b0eb Mon Sep 17 00:00:00 2001 From: frievoe97 <44405087+frievoe97@users.noreply.github.com> Date: Thu, 4 Jul 2024 20:15:15 +0200 Subject: [PATCH 014/101] Trip facet dashboard (#3350) * implement dropdown facets on the trip dashboard * implement dropdown facets on the trip dashboard * added backgroundColor attribute and restyled text seperators * set backgroundcolor on all plots --------- Co-authored-by: rakow --- .../simwrapper/dashboard/TripDashboard.java | 17 ++++++++++++----- .../java/org/matsim/simwrapper/viz/Viz.java | 1 + 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/TripDashboard.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/TripDashboard.java index 7ca920bfa12..28078cbd24b 100644 --- a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/TripDashboard.java +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/TripDashboard.java @@ -1,5 +1,6 @@ package org.matsim.simwrapper.dashboard; +import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.application.analysis.population.TripAnalysis; @@ -308,8 +309,9 @@ public void configure(Header header, Layout layout) { private void createChoiceTab(Layout layout, String[] args) { layout.row("choice-intro", "Mode Choice").el(TextBlock.class, (viz, data) -> { - viz.title = "Information"; + viz.backgroundColor = "transparent"; viz.content = """ + ### **Information** Note that these metrics are based on a single run and may have limited interpretability. For a more robust evaluation, consider running multiple simulations with different seeds and use metrics that consider probabilities as well. (log-likelihood, Brier score, etc.) For policy cases, these metrics do not have any meaning. They are solely for the base-case. @@ -371,7 +373,14 @@ private void createGroupedTab(Layout layout, String[] args) { for (String cat : Objects.requireNonNull(categories, "Categories not set")) { - layout.row("category_" + cat, "By Groups") + layout.row("category_header_" + cat, "By Groups") + + .el(TextBlock.class, (viz, data) -> { + viz.content = "## **" + StringUtils.capitalize(cat) + "**"; + viz.backgroundColor = "transparent"; + }); + + layout.row("category_1_" + cat, "By Groups") .el(Plotly.class, (viz, data) -> { viz.title = "Mode share"; @@ -399,8 +408,7 @@ private void createGroupedTab(Layout layout, String[] args) { }); - /* - TODO: This part needs some more work in simwrapper and is not yet ready + layout.row("category_2_" + cat, "By Groups") .el(Plotly.class, (viz, data) -> { viz.title = "Modal distance distribution"; @@ -433,7 +441,6 @@ private void createGroupedTab(Layout layout, String[] args) { .build(), ds); }); - */ } } diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/Viz.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/Viz.java index c943984bf24..04a4a4ecc3e 100644 --- a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/Viz.java +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/Viz.java @@ -17,6 +17,7 @@ public abstract class Viz { public String description; public Double height; public Double width; + public String backgroundColor; protected Viz(String type) { this.type = type; From 041381ac0c3d09c1e79b778e646a819b24f7f6c8 Mon Sep 17 00:00:00 2001 From: Ricardo Ewert Date: Mon, 8 Jul 2024 13:38:25 +0200 Subject: [PATCH 015/101] adjust rounding --- .../matsim/freightDemandGeneration/DemandReaderFromCSV.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java index 126eff63188..6d313f82d21 100644 --- a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java +++ b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java @@ -1086,7 +1086,7 @@ private static int calculateDemandForThisLink(int demandToDistribute, int number } else { roundingError = roundingError + ((double) demandForThisLink - ((double) demandToDistribute / (double) numberOfJobs)); - if (roundingError > 1) { + if (roundingError >= 1) { demandForThisLink = demandForThisLink - 1; roundingError = roundingError - 1; } @@ -1113,7 +1113,7 @@ private static int calculateDemandBasedOnLinkLength(int countOfLinks, int distri .ceil(link.getLength() / sumOfPossibleLinkLength * (double) demandToDistribute); roundingError = roundingError + ((double) demandForThisLink - (link.getLength() / sumOfPossibleLinkLength * (double) demandToDistribute)); - if (roundingError > 1) { + if (roundingError >= 1) { demandForThisLink = demandForThisLink - 1; roundingError = roundingError - 1; } From c52cbed47b02aeb41dd7d54bbd8930a30b32442a Mon Sep 17 00:00:00 2001 From: Ricardo Ewert Date: Mon, 8 Jul 2024 13:41:35 +0200 Subject: [PATCH 016/101] exclude case --- .../org/matsim/freightDemandGeneration/DemandReaderFromCSV.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java index 6d313f82d21..aaca1a0dafb 100644 --- a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java +++ b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java @@ -1265,7 +1265,7 @@ private static HashMap, Link> findAllPossibleLinks(Scenario scenario, crsTransformationNetworkAndShape); if (!possibleLinks.containsKey(newPossibleLink.getId())) possibleLinks.put(newPossibleLink.getId(), newPossibleLink); - if (nearestLinkPerPerson.size() == possiblePersons.size()) + if (!possiblePersons.isEmpty() && nearestLinkPerPerson.size() == possiblePersons.size()) break; } } From cdc625df8c7369fa2b79d163f15ba61ef0142a66 Mon Sep 17 00:00:00 2001 From: frievoe97 <44405087+frievoe97@users.noreply.github.com> Date: Mon, 8 Jul 2024 14:37:36 +0200 Subject: [PATCH 017/101] Drt dashboard typo fix (#3360) * added tooltip for gridmap/emissionsDashboard * fix typo in drt dashboard --------- Co-authored-by: rakow --- .../contrib/drt/extension/dashboards/DrtDashboard.java | 8 ++++---- .../matsim/simwrapper/dashboard/EmissionsDashboard.java | 2 ++ .../src/main/java/org/matsim/simwrapper/viz/GridMap.java | 6 ++++++ 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtDashboard.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtDashboard.java index a62f46a1ebc..6131d9f0edd 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtDashboard.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtDashboard.java @@ -159,7 +159,7 @@ public void configure(Header header, Layout layout) { viz.description = "Number of rides (customers) is displayed in bars, wait statistics in lines"; Plotly.DataSet waitStats = viz.addDataset(data.output("*_waitStats_" + drtConfigGroup.mode + ".csv")); - Plotly.DataSet rejections = viz.addDataset(data.output("*drt_rejections_perTimeBin_" + drtConfigGroup.mode + ".csv")); + Plotly.DataSet rejections = viz.addDataset(data.output("*drt_rejections_perTimeBin_" + drtConfigGroup.mode + ".csv")); viz.layout = tech.tablesaw.plotly.components.Layout.builder() .xAxis(Axis.builder().title("Time Bin").build()) @@ -244,7 +244,7 @@ public void configure(Header header, Layout layout) { viz.layout = tech.tablesaw.plotly.components.Layout.builder() .xAxis(Axis.builder().title("Iteration").build()) - .yAxis(Axis.builder().title("Wait Time [s]").build()) + .yAxis(Axis.builder().title("Number of Rides").build()) .barMode(tech.tablesaw.plotly.components.Layout.BarMode.STACK) .build(); @@ -272,12 +272,12 @@ public void configure(Header header, Layout layout) { viz.description = ""; viz.dataset = data.output("*customer_stats_" + drtConfigGroup.mode + ".csv"); viz.x = "iteration"; - viz.columns = List.of("wait_average","wait_median", "wait_p95"); + viz.columns = List.of("wait_average", "wait_median", "wait_p95"); viz.legendName = List.of("Average", "Median", "95th Percentile"); viz.xAxisName = "Iteration"; viz.yAxisName = "Waiting Time [s]"; }) - ; + ; layout.row("Demand And Travel Time Statistics per iteration") .el(Plotly.class, (viz, data) -> { diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/EmissionsDashboard.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/EmissionsDashboard.java index b4c044fbe99..b12052b7c7a 100644 --- a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/EmissionsDashboard.java +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/EmissionsDashboard.java @@ -55,6 +55,7 @@ public void configure(Header header, Layout layout) { layout.row("second") .el(GridMap.class, (viz, data) -> { viz.title = "CO₂ Emissions"; + viz.unit = "CO₂ [g]"; viz.description = "per day"; viz.height = 12.; viz.cellSize = 100; @@ -70,6 +71,7 @@ public void configure(Header header, Layout layout) { layout.row("third") .el(GridMap.class, (viz, data) -> { viz.title = "CO₂ Emissions"; + viz.unit = "CO₂ [g]"; viz.description = "per hour"; viz.height = 12.; viz.cellSize = 100; diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/GridMap.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/GridMap.java index 08e19a3bd37..190c6f3a083 100644 --- a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/GridMap.java +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/GridMap.java @@ -9,6 +9,12 @@ */ public class GridMap extends Viz { + /** + * The unit of the values. + */ + @JsonProperty(required = false) + public String unit; + /** * The center of the map. */ From e07615e6d59a1b04e670199ac05afdb0167126ba Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 8 Jul 2024 14:21:14 +0000 Subject: [PATCH 018/101] Bump com.fasterxml.jackson:jackson-bom from 2.17.1 to 2.17.2 Bumps [com.fasterxml.jackson:jackson-bom](https://github.com/FasterXML/jackson-bom) from 2.17.1 to 2.17.2. - [Commits](https://github.com/FasterXML/jackson-bom/compare/jackson-bom-2.17.1...jackson-bom-2.17.2) --- updated-dependencies: - dependency-name: com.fasterxml.jackson:jackson-bom dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 2df319d6476..cb137bfeb6a 100644 --- a/pom.xml +++ b/pom.xml @@ -35,7 +35,7 @@ 0.49.2 1.19.0 7.0.0 - 2.17.1 + 2.17.2 2.5.0 5.10.3 From 613c0390b24a1a70d7ef318e1cc5d569ad8173f5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 9 Jul 2024 14:07:28 +0000 Subject: [PATCH 019/101] Bump net.bytebuddy:byte-buddy from 1.14.17 to 1.14.18 Bumps [net.bytebuddy:byte-buddy](https://github.com/raphw/byte-buddy) from 1.14.17 to 1.14.18. - [Release notes](https://github.com/raphw/byte-buddy/releases) - [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md) - [Commits](https://github.com/raphw/byte-buddy/compare/byte-buddy-1.14.17...byte-buddy-1.14.18) --- updated-dependencies: - dependency-name: net.bytebuddy:byte-buddy dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index cb137bfeb6a..3f370ac8530 100644 --- a/pom.xml +++ b/pom.xml @@ -358,7 +358,7 @@ net.bytebuddy byte-buddy - 1.14.17 + 1.14.18 test From a639335fd092e7573b5a1ac7742e0d57388d3735 Mon Sep 17 00:00:00 2001 From: Ricardo Ewert Date: Tue, 9 Jul 2024 16:57:07 +0200 Subject: [PATCH 020/101] set networkMode based on vehicleTypes --- .../SmallScaleCommercialTrafficUtils.java | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java index f180308e69e..25026ad424d 100644 --- a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java +++ b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java @@ -195,13 +195,9 @@ static void createPlansBasedOnCarrierPlans(Scenario scenario, String smallScaleC Carrier relatedCarrier = CarriersUtils.addOrGetCarriers(scenario).getCarriers() .get(Id.create(carrierName, Carrier.class)); String subpopulation = relatedCarrier.getAttributes().getAttribute("subpopulation").toString(); - final String mode; - if (subpopulation.contains("commercialPersonTraffic")) - mode = "car"; - else if (subpopulation.contains("goodsTraffic")) - mode = "freight"; - else - mode = relatedCarrier.getAttributes().getAttribute("networkMode").toString(); + Id vehicleId = Id.createVehicleId(person.getId().toString()); + String mode = allVehicles.getVehicles().get(vehicleId).getType().getNetworkMode(); + List tourElements = person.getSelectedPlan().getPlanElements(); double tourStartTime = 0; for (PlanElement tourElement : tourElements) { @@ -241,8 +237,6 @@ else if (subpopulation.contains("goodsTraffic")) newPerson.getAttributes().putAttribute("tourStartArea", relatedCarrier.getAttributes().getAttribute("tourStartArea")); - Id vehicleId = Id.createVehicleId(person.getId().toString()); - VehicleUtils.insertVehicleIdsIntoPersonAttributes(newPerson, Map.of(mode, vehicleId)); VehicleUtils.insertVehicleTypesIntoPersonAttributes(newPerson, Map.of(mode, allVehicles.getVehicles().get(vehicleId).getType().getId())); From cd4a87048c5f11d174a658565364c3a08e9cdb6a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 10 Jul 2024 14:38:44 +0000 Subject: [PATCH 021/101] Bump org.assertj:assertj-core from 3.26.0 to 3.26.3 Bumps [org.assertj:assertj-core](https://github.com/assertj/assertj) from 3.26.0 to 3.26.3. - [Release notes](https://github.com/assertj/assertj/releases) - [Commits](https://github.com/assertj/assertj/compare/assertj-build-3.26.0...assertj-build-3.26.3) --- updated-dependencies: - dependency-name: org.assertj:assertj-core dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index cb137bfeb6a..be0292d3dcb 100644 --- a/pom.xml +++ b/pom.xml @@ -314,7 +314,7 @@ org.assertj assertj-core - 3.26.0 + 3.26.3 test From 61b02bc959402ac201ad73c27292136a66bb161d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=B6rl?= Date: Thu, 11 Jul 2024 09:05:12 +0200 Subject: [PATCH 022/101] chore: clean up MinimalTransferTimes (#3365) --- .../transitSchedule/MinimalTransferTimesImpl.java | 13 ------------- .../transitSchedule/api/MinimalTransferTimes.java | 4 ---- 2 files changed, 17 deletions(-) diff --git a/matsim/src/main/java/org/matsim/pt/transitSchedule/MinimalTransferTimesImpl.java b/matsim/src/main/java/org/matsim/pt/transitSchedule/MinimalTransferTimesImpl.java index c78b1b1687e..f8e5bf92d9f 100644 --- a/matsim/src/main/java/org/matsim/pt/transitSchedule/MinimalTransferTimesImpl.java +++ b/matsim/src/main/java/org/matsim/pt/transitSchedule/MinimalTransferTimesImpl.java @@ -19,11 +19,9 @@ package org.matsim.pt.transitSchedule; -import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; -import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.matsim.api.core.v01.Id; @@ -166,15 +164,4 @@ public double getSeconds() { throw new NoSuchElementException(); } } - - @Override - public Set> getCandidates(Id fromStop) { - var inner = minimalTransferTimes.get(fromStop); - - if (inner == null) { - return Collections.emptySet(); - } - - return inner.keySet(); - } } diff --git a/matsim/src/main/java/org/matsim/pt/transitSchedule/api/MinimalTransferTimes.java b/matsim/src/main/java/org/matsim/pt/transitSchedule/api/MinimalTransferTimes.java index c567093f865..72819f5cf70 100644 --- a/matsim/src/main/java/org/matsim/pt/transitSchedule/api/MinimalTransferTimes.java +++ b/matsim/src/main/java/org/matsim/pt/transitSchedule/api/MinimalTransferTimes.java @@ -19,8 +19,6 @@ package org.matsim.pt.transitSchedule.api; -import java.util.Set; - import org.matsim.api.core.v01.Id; /** @@ -68,8 +66,6 @@ public interface MinimalTransferTimes { * @return the previously set minimal transfer time, or Double.NaN if none was set. */ double remove(Id fromStop, Id toStop); - - Set> getCandidates(Id fromStop); /** * @return an iterator to iterate over all minimal transfer times set. From 79c9523c82b1c681b001f4accbb6ab4748a4d164 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=B6rl?= Date: Thu, 11 Jul 2024 09:46:24 +0200 Subject: [PATCH 023/101] chore: cleanup adaptive transfers (#3366) * chore: cleanup adaptvie transfers * make final --- .../config/SwissRailRaptorConfigGroup.java | 2 +- .../routing/pt/raptor/RaptorStaticConfig.java | 4 ++-- .../pt/raptor/SwissRailRaptorCore.java | 24 ++++++++++++++----- .../pt/raptor/SwissRailRaptorData.java | 10 ++++---- 4 files changed, 25 insertions(+), 15 deletions(-) diff --git a/matsim/src/main/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroup.java b/matsim/src/main/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroup.java index c5376acc84b..8bf362f1b2c 100644 --- a/matsim/src/main/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroup.java +++ b/matsim/src/main/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroup.java @@ -65,7 +65,7 @@ public class SwissRailRaptorConfigGroup extends ReflectiveConfigGroup { private static final String PARAM_INTERMODAL_LEG_ONLYHANDLING = "intermodalLegOnlyHandling"; private static final String PARAM_INTERMODAL_LEG_ONLYHANDLING_DESC = "Define how routes containing only intermodal legs are handled: Useful options: alllow, avoid, forbid"; private static final String PARAM_TRANSFER_CALCULATION = "transferCalculation"; - private static final String PARAM_TRANFER_CALCULATION_DESC = "Defines whether all potential transfers are precomputed at the beginning of the simulation (Initial) or whether they are constructed on-demand (Cached). The former incurs potentially long up-front caclulations, but quicker routing. The latter avoids any initial computation, but may require longer routing time."; + private static final String PARAM_TRANFER_CALCULATION_DESC = "Defines whether all potential transfers are precomputed at the beginning of the simulation (Initial) or whether they are constructed on-demand when needed (Adaptive). The former incurs potentially long up-front caclulations, but quicker routing. The latter avoids any initial computation, but may require longer routing time."; private boolean useRangeQuery = false; private boolean useIntermodality = false; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorStaticConfig.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorStaticConfig.java index 8f49f121ab2..5e71b1170ce 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorStaticConfig.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorStaticConfig.java @@ -61,11 +61,11 @@ public enum RaptorTransferCalculation { Initial, /** - * Use this option if you want the algorithm to calculate transfers on demand, + * Use this option if you want the algorithm to calculate transfers adaptively on demand, * which avoids any simulation start-up time but may increase the routing time * itself. */ - Cached + Adaptive } diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorCore.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorCore.java index 3778eebfaea..d6c059897d8 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorCore.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorCore.java @@ -22,6 +22,7 @@ import ch.sbb.matsim.config.SwissRailRaptorConfigGroup; import ch.sbb.matsim.routing.pt.raptor.OccupancyData.DepartureData; import ch.sbb.matsim.routing.pt.raptor.RaptorInVehicleCostCalculator.RouteSegmentIterator; +import ch.sbb.matsim.routing.pt.raptor.RaptorStaticConfig.RaptorTransferCalculation; import ch.sbb.matsim.routing.pt.raptor.SwissRailRaptor.RaptorObserver; import ch.sbb.matsim.routing.pt.raptor.SwissRailRaptorData.CachingTransferProvider; import ch.sbb.matsim.routing.pt.raptor.SwissRailRaptorData.RRoute; @@ -70,6 +71,7 @@ public class SwissRailRaptorCore { private final PathElement[] tmpArrivalPathPerStop; // only used to ensure parallel update private final BitSet tmpImprovedStops; // only used to ensure parallel update private final boolean useCapacityConstraints; + private final boolean useAdaptiveTransferCalculation; private final RaptorInVehicleCostCalculator inVehicleCostCalculator; private final RaptorTransferCostCalculator transferCostCalculator; private final RouteSegmentIteratorImpl routeSegmentIterator; @@ -90,6 +92,7 @@ public class SwissRailRaptorCore { this.tmpArrivalPathPerStop = new PathElement[this.data.countStops]; this.tmpImprovedStops = new BitSet(this.data.countStops); this.useCapacityConstraints = this.data.config.isUseCapacityConstraints(); + this.useAdaptiveTransferCalculation = this.data.config.getTransferCalculation().equals(RaptorTransferCalculation.Adaptive); this.inVehicleCostCalculator = inVehicleCostCalculator; this.transferCostCalculator = transferCostCalculator; this.routeSegmentIterator = new RouteSegmentIteratorImpl(this.data); @@ -827,12 +830,21 @@ private void handleTransfers(boolean strict, RaptorParameters raptorParams, Cach } RRouteStop fromRouteStop = fromPE.toRouteStop; // this is the route stop we arrive with least cost at stop - // obtain on-demand transfers if applicable (will return null if transfers are calculated initially) - RTransfer[] transfers = this.data.calculateTransfers(fromRouteStop); - - int firstTransferIndex = transfers == null ? fromRouteStop.indexFirstTransfer : 0; - int lastTransferIndex = transfers == null ? firstTransferIndex + fromRouteStop.countTransfers : transfers.length; - transfers = transfers == null ? this.data.transfers : transfers; + final int firstTransferIndex; + final int lastTransferIndex; + final RTransfer[] transfers; + + if (!useAdaptiveTransferCalculation) { + // efficient lookup from the precomputed transfer candidates + transfers = this.data.transfers; + firstTransferIndex = fromRouteStop.indexFirstTransfer; + lastTransferIndex = firstTransferIndex + fromRouteStop.countTransfers; + } else { + // more costly calculation and caching of transfer canddiates + transfers = this.data.calculateTransfers(fromRouteStop); + firstTransferIndex = 0; + lastTransferIndex = transfers.length; + } for (int transferIndex = firstTransferIndex; transferIndex < lastTransferIndex; transferIndex++) { RTransfer transfer = transfers[transferIndex]; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorData.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorData.java index 7ec137e6096..a02b58c7b35 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorData.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorData.java @@ -245,15 +245,17 @@ public static SwissRailRaptorData create(TransitSchedule schedule, @Nullable Veh } } - // if cached transfer calculation is used, build a map for quick lookup of minimal transfer times + // if adaptive transfer calculation is used, build a map for quick lookup of and collection of minimal transfer times IdMap> staticTransferTimes = null; - if (staticConfig.getTransferCalculation().equals(RaptorTransferCalculation.Cached)) { + if (staticConfig.getTransferCalculation().equals(RaptorTransferCalculation.Adaptive)) { staticTransferTimes = new IdMap<>(TransitStopFacility.class); MinimalTransferTimes.MinimalTransferTimesIterator iterator = schedule.getMinimalTransferTimes().iterator(); while (iterator.hasNext()) { iterator.next(); + // we only put the predefined transfer times here, the location-based ones will be calculated + // adaptively during routing staticTransferTimes.computeIfAbsent(iterator.getFromStopId(), id -> new HashMap<>()) .put(schedule.getFacilities().get(iterator.getToStopId()), iterator.getSeconds()); } @@ -649,10 +651,6 @@ public Transfer get() { } RTransfer[] calculateTransfers(RRouteStop fromRouteStop) { - if (config.getTransferCalculation().equals(RaptorTransferCalculation.Initial)) { - return null; - } - // We tested this in a parallel set-up and things seem to work as they are // implemented. The routing threads will access the cache as read-only an // retrieve the cached stop connections. It can happen that two of them try to From d0f310a31bd8e56d8c5b7d775d225e3506ce095e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 11 Jul 2024 14:13:55 +0000 Subject: [PATCH 024/101] Bump org.apache.maven.plugins:maven-failsafe-plugin from 3.3.0 to 3.3.1 Bumps [org.apache.maven.plugins:maven-failsafe-plugin](https://github.com/apache/maven-surefire) from 3.3.0 to 3.3.1. - [Release notes](https://github.com/apache/maven-surefire/releases) - [Commits](https://github.com/apache/maven-surefire/compare/surefire-3.3.0...surefire-3.3.1) --- updated-dependencies: - dependency-name: org.apache.maven.plugins:maven-failsafe-plugin dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 3c4e8870bf5..3f97fb8c5d3 100644 --- a/pom.xml +++ b/pom.xml @@ -425,7 +425,7 @@ org.apache.maven.plugins maven-failsafe-plugin - 3.3.0 + 3.3.1 org.apache.maven.plugins From bad4be00dd3831b287ea1a89227acc1425a214e0 Mon Sep 17 00:00:00 2001 From: Ricardo Ewert Date: Fri, 12 Jul 2024 12:06:58 +0200 Subject: [PATCH 025/101] add missing case of enum --- .../freightDemandGeneration/FreightDemandGeneration.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGeneration.java b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGeneration.java index 76dda11fc9b..09ba9e75623 100644 --- a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGeneration.java +++ b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGeneration.java @@ -381,6 +381,13 @@ private void createDemand(DemandGenerationOptions selectedDemandGenerationOption */ FreightDemandGenerationUtils.preparePopulation(population, sampleSizeInputPopulation, upSamplePopulationTo, "changeDemandOnLocation"); + case noPopulationSampling -> + /* + * If the demand sample is equal to the population sample, the demand is created + * based on the given population and the set input population sampleSize + */ + FreightDemandGenerationUtils.preparePopulation(population, sampleSizeInputPopulation, + sampleSizeInputPopulation, "noPopulationSampling"); default -> throw new RuntimeException("No valid sampling option selected!"); } switch (selectedPopulationOption) { From 9cf945d06fefd99255e8d7e3d1a32b93e9fa7f25 Mon Sep 17 00:00:00 2001 From: Ricardo Ewert Date: Fri, 12 Jul 2024 12:42:34 +0200 Subject: [PATCH 026/101] add functionality to split jobs --- .../DemandReaderFromCSV.java | 117 ++++++++++++------ 1 file changed, 79 insertions(+), 38 deletions(-) diff --git a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java index aaca1a0dafb..02ae5072583 100644 --- a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java +++ b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java @@ -667,18 +667,25 @@ else if (samplingOption.equals("changeDemandOnLocation")) { int demandForThisLink = calculateDemandBasedOnLinkLength(countOfLinks, distributedDemand, demandToDistribute, possibleLinksForService.size(), sumOfPossibleLinkLength, link); countOfLinks++; - double serviceTime = newDemandInformationElement.getFirstJobElementTimePerUnit() - * demandForThisLink; - Id idNewService = Id.create( + Carrier thisCarrier = CarriersUtils.getCarriers(scenario).getCarriers() + .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)); + int numberOfJobsForDemand = calculateNumberOfJobsForDemand(thisCarrier, demandForThisLink); + for (int i = 0; i < numberOfJobsForDemand; i++) { + int singleDemandForThisLink = demandForThisLink / numberOfJobsForDemand; + if (i == numberOfJobsForDemand - 1) + singleDemandForThisLink = demandForThisLink - (numberOfJobsForDemand - 1) * singleDemandForThisLink; + double serviceTime = newDemandInformationElement.getFirstJobElementTimePerUnit() + * singleDemandForThisLink; + Id idNewService = Id.create( createJobId(scenario, newDemandInformationElement, link.getId(), null), CarrierService.class); - if (demandToDistribute > 0 && demandForThisLink > 0) { - CarrierService thisService = CarrierService.Builder.newInstance(idNewService, link.getId()) - .setCapacityDemand(demandForThisLink).setServiceDuration(serviceTime) + if (demandToDistribute > 0 && singleDemandForThisLink > 0) { + CarrierService thisService = CarrierService.Builder.newInstance(idNewService, link.getId()) + .setCapacityDemand(singleDemandForThisLink).setServiceDuration(serviceTime) .setServiceStartTimeWindow(newDemandInformationElement.getFirstJobElementTimeWindow()) .build(); - CarriersUtils.getCarriers(scenario).getCarriers().values().iterator().next().getServices() - .put(thisService.getId(), thisService); + thisCarrier.getServices().put(thisService.getId(), thisService); + } } distributedDemand = distributedDemand + demandForThisLink; } @@ -705,24 +712,31 @@ else if (samplingOption.equals("changeDemandOnLocation")) { .skip(rand.nextInt(usedServiceLocations.size() - 1)).findFirst().get())); } int demandForThisLink = calculateDemandForThisLink(demandToDistribute, numberOfJobs, distributedDemand, i); + Carrier thisCarrier = CarriersUtils.getCarriers(scenario).getCarriers() + .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)); + int numberOfJobsForDemand = calculateNumberOfJobsForDemand(thisCarrier, demandForThisLink); + for (int j = 0; j < numberOfJobsForDemand; j++) { + int singleDemandForThisLink = demandForThisLink / numberOfJobsForDemand; + if (j == numberOfJobsForDemand - 1) + singleDemandForThisLink = demandForThisLink - (numberOfJobsForDemand - 1) * singleDemandForThisLink; + double serviceTime; + if (singleDemandForThisLink == 0) + serviceTime = newDemandInformationElement.getFirstJobElementTimePerUnit(); + else + serviceTime = newDemandInformationElement.getFirstJobElementTimePerUnit() * demandForThisLink; + usedServiceLocations.add(link.getId().toString()); - double serviceTime; - if (demandToDistribute == 0) - serviceTime = newDemandInformationElement.getFirstJobElementTimePerUnit(); - else - serviceTime = newDemandInformationElement.getFirstJobElementTimePerUnit() * demandForThisLink; - usedServiceLocations.add(link.getId().toString()); - - Id idNewService = Id.create( + Id idNewService = Id.create( createJobId(scenario, newDemandInformationElement, link.getId(), null), CarrierService.class); - if ((demandToDistribute > 0 && demandForThisLink > 0) || demandToDistribute == 0) { - CarrierService thisService = CarrierService.Builder.newInstance(idNewService, link.getId()) - .setCapacityDemand(demandForThisLink).setServiceDuration(serviceTime) + if ((demandToDistribute > 0 && singleDemandForThisLink > 0) || demandToDistribute == 0) { + CarrierService thisService = CarrierService.Builder.newInstance(idNewService, link.getId()) + .setCapacityDemand(singleDemandForThisLink).setServiceDuration(serviceTime) .setServiceStartTimeWindow(newDemandInformationElement.getFirstJobElementTimeWindow()) .build(); - CarriersUtils.getCarriers(scenario).getCarriers() + CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)).getServices() .put(thisService.getId(), thisService); + } } distributedDemand = distributedDemand + demandForThisLink; } @@ -1007,29 +1021,56 @@ else if (numberOfPickupLocations != null) { private static void createSingleShipment(Scenario scenario, DemandInformationElement newDemandInformationElement, Link linkPickup, Link linkDelivery, int demandForThisLink) { - Id idNewShipment = Id.create(createJobId(scenario, newDemandInformationElement, - linkPickup.getId(), linkDelivery.getId()), CarrierShipment.class); + Carrier thisCarrier = CarriersUtils.getCarriers(scenario).getCarriers() + .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)); + int numberOfJobsForDemand = calculateNumberOfJobsForDemand(thisCarrier, demandForThisLink); TimeWindow timeWindowPickup = newDemandInformationElement.getFirstJobElementTimeWindow(); TimeWindow timeWindowDelivery = newDemandInformationElement.getSecondJobElementTimeWindow(); - double serviceTimePickup; - double serviceTimeDelivery; - if (demandForThisLink == 0) { - serviceTimePickup = newDemandInformationElement.getFirstJobElementTimePerUnit(); - serviceTimeDelivery = newDemandInformationElement.getSecondJobElementTimePerUnit(); - } else { - serviceTimePickup = newDemandInformationElement.getFirstJobElementTimePerUnit() * demandForThisLink; - serviceTimeDelivery = newDemandInformationElement.getSecondJobElementTimePerUnit() * demandForThisLink; + for (int i = 0; i < numberOfJobsForDemand; i++) { + Id idNewShipment = Id.create(createJobId(scenario, newDemandInformationElement, + linkPickup.getId(), linkDelivery.getId()), CarrierShipment.class); + double serviceTimePickup; + double serviceTimeDelivery; + int singleDemandForThisLink = Math.round ((float) demandForThisLink / numberOfJobsForDemand); + if (i == numberOfJobsForDemand - 1) + singleDemandForThisLink = demandForThisLink - (numberOfJobsForDemand - 1) * singleDemandForThisLink; + if (singleDemandForThisLink == 0) { + serviceTimePickup = newDemandInformationElement.getFirstJobElementTimePerUnit(); + serviceTimeDelivery = newDemandInformationElement.getSecondJobElementTimePerUnit(); + } else { + serviceTimePickup = newDemandInformationElement.getFirstJobElementTimePerUnit() * singleDemandForThisLink; + serviceTimeDelivery = newDemandInformationElement.getSecondJobElementTimePerUnit() * singleDemandForThisLink; + } + CarrierShipment thisShipment = CarrierShipment.Builder + .newInstance(idNewShipment, linkPickup.getId(), linkDelivery.getId(), singleDemandForThisLink) + .setPickupServiceTime(serviceTimePickup).setPickupTimeWindow(timeWindowPickup) + .setDeliveryServiceTime(serviceTimeDelivery).setDeliveryTimeWindow(timeWindowDelivery) + .build(); + thisCarrier.getShipments().put(thisShipment.getId(), thisShipment); + } + } + + /** + * Method calculates the number of jobs for a demand on one link based on the largest vehicle capacity of the carrier. + * + * @param thisCarrier the carrier of a job + * @param demandForThisLink Demand for this link + * @return Number of jobs for this demand + */ + private static int calculateNumberOfJobsForDemand(Carrier thisCarrier, int demandForThisLink) { + double largestVehicleCapacity = 0; + for (CarrierVehicle vehicle : thisCarrier.getCarrierCapabilities().getCarrierVehicles().values()) { + if (vehicle.getType().getCapacity().getOther() > largestVehicleCapacity) { + largestVehicleCapacity = vehicle.getType().getCapacity().getOther(); + } + } + if (demandForThisLink > largestVehicleCapacity) { + log.info("Demand {} is larger than the largest vehicle capacity ({}). Splitting demand into multiple jobs.", demandForThisLink, largestVehicleCapacity); + return (int) Math.ceil((double) demandForThisLink / largestVehicleCapacity); } - CarrierShipment thisShipment = CarrierShipment.Builder - .newInstance(idNewShipment, linkPickup.getId(), linkDelivery.getId(), demandForThisLink) - .setPickupServiceTime(serviceTimePickup).setPickupTimeWindow(timeWindowPickup) - .setDeliveryServiceTime(serviceTimeDelivery).setDeliveryTimeWindow(timeWindowDelivery) - .build(); - CarriersUtils.getCarriers(scenario).getCarriers() - .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)).getShipments() - .put(thisShipment.getId(), thisShipment); + return 1; } /** From c157c29b1d281eafb06c982f5ca9478e1c0dc7da Mon Sep 17 00:00:00 2001 From: Ricardo Ewert Date: Fri, 12 Jul 2024 12:54:53 +0200 Subject: [PATCH 027/101] use new methods --- .../GenerateSmallScaleCommercialTrafficDemand.java | 3 +-- .../SmallScaleCommercialTrafficUtils.java | 8 ++++---- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java index 026c853a5be..bfb86cc4e35 100644 --- a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java +++ b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java @@ -79,7 +79,6 @@ import picocli.CommandLine; import java.io.File; -import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDate; @@ -660,7 +659,7 @@ private void createCarriers(Scenario scenario, TripDistributionMatrix odMatrix, } // find a start category with existing employees in this zone Collections.shuffle(startCategory, rnd); - String selectedStartCategory = startCategory.get(0); + String selectedStartCategory = startCategory.getFirst(); for (int count = 1; resultingDataPerZone.get(startZone).getDouble(selectedStartCategory) == 0; count++) { if (count <= startCategory.size()) selectedStartCategory = startCategory.get(rnd.nextInt(startCategory.size())); diff --git a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java index 25026ad424d..08fbd7565e5 100644 --- a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java +++ b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java @@ -79,7 +79,7 @@ public class SmallScaleCommercialTrafficUtils { public static Index getIndexZones(Path shapeFileZonePath, String shapeCRS, String shapeFileZoneNameColumn) { ShpOptions shpZones = new ShpOptions(shapeFileZonePath, shapeCRS, StandardCharsets.UTF_8); - if (shpZones.readFeatures().iterator().next().getAttribute(shapeFileZoneNameColumn) == null) + if (shpZones.readFeatures().getFirst().getAttribute(shapeFileZoneNameColumn) == null) throw new NullPointerException("The column '" + shapeFileZoneNameColumn + "' does not exist in the zones shape file. Please check the input."); return shpZones.createIndex(shapeCRS, shapeFileZoneNameColumn); } @@ -94,7 +94,7 @@ public static Index getIndexZones(Path shapeFileZonePath, String shapeCRS, Strin */ public static Index getIndexLanduse(Path shapeFileLandusePath, String shapeCRS, String shapeFileLanduseTypeColumn) { ShpOptions shpLanduse = new ShpOptions(shapeFileLandusePath, shapeCRS, StandardCharsets.UTF_8); - if (shpLanduse.readFeatures().iterator().next().getAttribute(shapeFileLanduseTypeColumn) == null) + if (shpLanduse.readFeatures().getFirst().getAttribute(shapeFileLanduseTypeColumn) == null) throw new NullPointerException("The column '" + shapeFileLanduseTypeColumn + "' does not exist in the landuse shape file. Please check the input."); return shpLanduse.createIndex(shapeCRS, shapeFileLanduseTypeColumn); } @@ -109,7 +109,7 @@ public static Index getIndexLanduse(Path shapeFileLandusePath, String shapeCRS, */ public static Index getIndexBuildings(Path shapeFileBuildingsPath, String shapeCRS, String shapeFileBuildingTypeColumn) { ShpOptions shpBuildings = new ShpOptions(shapeFileBuildingsPath, shapeCRS, StandardCharsets.UTF_8); - if (shpBuildings.readFeatures().iterator().next().getAttribute(shapeFileBuildingTypeColumn) == null) + if (shpBuildings.readFeatures().getFirst().getAttribute(shapeFileBuildingTypeColumn) == null) throw new NullPointerException("The column '" + shapeFileBuildingTypeColumn + "' does not exist in the building shape file. Please check the input."); return shpBuildings.createIndex(shapeCRS, shapeFileBuildingTypeColumn); @@ -125,7 +125,7 @@ public static Index getIndexBuildings(Path shapeFileBuildingsPath, String shapeC */ public static Index getIndexRegions(Path shapeFileRegionsPath, String shapeCRS, String regionsShapeRegionColumn) { ShpOptions shpRegions = new ShpOptions(shapeFileRegionsPath, shapeCRS, StandardCharsets.UTF_8); - if (shpRegions.readFeatures().iterator().next().getAttribute(regionsShapeRegionColumn) == null) + if (shpRegions.readFeatures().getFirst().getAttribute(regionsShapeRegionColumn) == null) throw new NullPointerException("The column '" + regionsShapeRegionColumn + "' does not exist in the region shape file. Please check the input."); return shpRegions.createIndex(shapeCRS, regionsShapeRegionColumn); } From 346b6e70b2b41f3550a1556d2d84c2ef7c87604d Mon Sep 17 00:00:00 2001 From: Ricardo Ewert Date: Fri, 12 Jul 2024 12:55:36 +0200 Subject: [PATCH 028/101] update activity creation --- .../SmallScaleCommercialTrafficUtils.java | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java index 08fbd7565e5..72f029ab072 100644 --- a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java +++ b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java @@ -203,22 +203,21 @@ static void createPlansBasedOnCarrierPlans(Scenario scenario, String smallScaleC for (PlanElement tourElement : tourElements) { if (tourElement instanceof Activity activity) { - activity.setCoord( + Activity newActivity = PopulationUtils.createActivityFromCoord(activity.getType(), scenario.getNetwork().getLinks().get(activity.getLinkId()).getFromNode().getCoord()); if (activity.getType().equals("start")) { tourStartTime = activity.getEndTime().seconds(); - activity.setType("commercial_start"); + newActivity.setType("commercial_start"); } else - activity.setEndTimeUndefined(); + newActivity.setEndTimeUndefined(); if (activity.getType().equals("end")) { - activity.setStartTime(tourStartTime + 8 * 3600); - activity.setType("commercial_end"); + newActivity.setStartTime(tourStartTime + 8 * 3600); + newActivity.setType("commercial_end"); } - plan.addActivity(activity); + plan.addActivity(newActivity); } if (tourElement instanceof Leg) { - Leg legActivity = popFactory.createLeg(mode); - plan.addLeg(legActivity); + PopulationUtils.createAndAddLeg(plan, mode); } } From 5fd7bb213bb53aa9f6f8b6cf069b0ae741546e27 Mon Sep 17 00:00:00 2001 From: Ricardo Ewert Date: Fri, 12 Jul 2024 13:58:01 +0200 Subject: [PATCH 029/101] set activity time correctly --- .../SmallScaleCommercialTrafficUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java index 72f029ab072..3af4dc1fa7f 100644 --- a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java +++ b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java @@ -206,7 +206,7 @@ static void createPlansBasedOnCarrierPlans(Scenario scenario, String smallScaleC Activity newActivity = PopulationUtils.createActivityFromCoord(activity.getType(), scenario.getNetwork().getLinks().get(activity.getLinkId()).getFromNode().getCoord()); if (activity.getType().equals("start")) { - tourStartTime = activity.getEndTime().seconds(); + newActivity.setEndTime(activity.getEndTime().seconds()); newActivity.setType("commercial_start"); } else newActivity.setEndTimeUndefined(); From 683b731a5ba76b3a556d9469366dd0a05ef4d846 Mon Sep 17 00:00:00 2001 From: Ricardo Ewert Date: Sat, 13 Jul 2024 10:33:36 +0200 Subject: [PATCH 030/101] remove unneeded exception --- .../GenerateSmallScaleCommercialTrafficDemand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java index bfb86cc4e35..1b8a0b260e8 100644 --- a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java +++ b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java @@ -887,7 +887,7 @@ private Id findPossibleLink(String zone, String selectedCategory, List, Link>> filterLinksForZones(Scenario scenario, Index indexZones, Map>> facilitiesPerZone, - String shapeFileZoneNameColumn) throws URISyntaxException { + String shapeFileZoneNameColumn) { Map, Link>> linksPerZone = new HashMap<>(); log.info("Filtering and assign links to zones. This take some time..."); From 6f0721e561fd8bd34f52ca2bed6af21d8cdc49a2 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 15:35:02 +0200 Subject: [PATCH 031/101] change to parameterized log message --- .../carriers/CarrierPlanXmlParserV2.java | 2 +- .../carriers/CarrierPlanXmlParserV2_1.java | 2 +- .../carriers/CarrierPlanXmlReader.java | 12 +++--- .../carriers/CarrierPlanXmlWriterV2_1.java | 6 +-- .../carriers/CarrierVehicleTypeReader.java | 19 +++++----- .../org/matsim/freight/carriers/Carriers.java | 2 +- .../freight/carriers/CarriersUtils.java | 4 +- .../org/matsim/freight/carriers/Tour.java | 6 +-- .../carriers/controler/CarrierAgent.java | 2 +- .../controler/CarrierDriverAgent.java | 4 +- .../controler/FreightAgentSource.java | 6 +-- .../carriers/jsprit/MatsimJspritFactory.java | 38 +++++++++---------- .../usecases/analysis/CarrierScoreStats.java | 8 ++-- .../carriers/jsprit/FixedCostsTest.java | 2 +- 14 files changed, 54 insertions(+), 59 deletions(-) diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2.java index fb921395d19..a63697cfab4 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2.java @@ -306,7 +306,7 @@ public void startTag(String name, Attributes atts, Stack context) { // do nothing break ; default: - logger.warn("Unexpected value while reading in. This field will be ignored: " + name); + logger.warn("Unexpected value while reading in. This field will be ignored: {}", name); } } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2_1.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2_1.java index 862123d3201..8503eb4acad 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2_1.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2_1.java @@ -309,7 +309,7 @@ public void startTag(String name, Attributes atts, Stack context) { // do nothing break ; default: - logger.warn("Unexpected value while reading in. This field will be ignored: " + name); + logger.warn("Unexpected value while reading in. This field will be ignored: {}", name); } } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlReader.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlReader.java index 5019604572d..5155f5bdebc 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlReader.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlReader.java @@ -56,9 +56,9 @@ public void readFile( String filename ){ try { reader.readFile( filename ); } catch (Exception e) { - log.warn("### Exception found while trying to read CarrierPlan: Message: " + e.getMessage() + " ; cause: " + e.getCause() + " ; class " + e.getClass()); + log.warn("### Exception found while trying to read CarrierPlan: Message: {} ; cause: {} ; class {}", e.getMessage(), e.getCause(), e.getClass()); if (e.getCause().getMessage().contains("cvc-elt.1")) { // "Cannot find the declaration of element" -> exception comes most probably because no validation information was found - log.warn("read with validation = true failed. Try it again without validation... filename: " + filename); + log.warn("read with validation = true failed. Try it again without validation... filename: {}", filename); reader.setValidating(false); reader.readFile(filename); } else { //other problem: e.g. validation does not work, because of missing validation file. @@ -72,9 +72,9 @@ public void readURL( URL url ){ try { reader.readURL(url); } catch (Exception e) { - log.warn("### Exception found while trying to read CarrierPlan: Message: " + e.getMessage() + " ; cause: " + e.getCause() + " ; class " + e.getClass()); + log.warn("### Exception found while trying to read CarrierPlan: Message: {} ; cause: {} ; class {}", e.getMessage(), e.getCause(), e.getClass()); if (e.getCause().getMessage().contains("cvc-elt.1")) { // "Cannot find the declaration of element" -> exception comes most probably because no validation information was found - log.warn("read with validation = true failed. Try it again without validation... url: " + url.toString()); + log.warn("read with validation = true failed. Try it again without validation... url: {}", url.toString()); reader.setValidating(false); reader.readURL(url); } else { //other problem: e.g. validation does not work, because of missing validation file. @@ -89,7 +89,7 @@ public void readStream( InputStream inputStream ){ reader.setValidating(false); reader.parse(inputStream); } catch (Exception e) { - log.warn("### Exception found while trying to read CarrierPlan: Message: " + e.getMessage() + " ; cause: " + e.getCause() + " ; class " + e.getClass()); + log.warn("### Exception found while trying to read CarrierPlan: Message: {} ; cause: {} ; class {}", e.getMessage(), e.getCause(), e.getClass()); throw e; } } @@ -110,7 +110,7 @@ private static final class CarriersPlanReader extends MatsimXmlParser { public void startTag(final String name, final Attributes attributes, final Stack context) { if ( CARRIERS.equalsIgnoreCase( name ) ) { String str = attributes.getValue( "xsi:schemaLocation" ); - log.info("Found following schemeLocation in carriers definition file: " + str); + log.info("Found following schemeLocation in carriers definition file: {}", str); if (str == null){ log.warn("Carrier plans file does not contain a valid xsd header. Using CarrierPlanReaderV2."); delegate = new CarrierPlanXmlParserV2( carriers, carrierVehicleTypes ) ; diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1.java index 8b89b8f8216..88be7b7b866 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1.java @@ -283,8 +283,7 @@ else if (tourElement instanceof Tour.ShipmentBasedActivity act) { createTuple(SHIPMENT_ID, act.getShipment().getId().toString())), true ); if (!carrier.getShipments().containsKey(act.getShipment().getId())) { - logger.error("Shipment with id " + act.getShipment().getId().toString() + " is contained in the carriers plan, " + - "but not available in the list of shipments. Carrier with carrierId: " + carrier.getId()); + logger.error("Shipment with id {} is contained in the carriers plan, but not available in the list of shipments. Carrier with carrierId: {}", act.getShipment().getId().toString(), carrier.getId()); } } else if (tourElement instanceof Tour.ServiceActivity act) { @@ -293,8 +292,7 @@ else if (tourElement instanceof Tour.ServiceActivity act) { createTuple(SERVICE_ID, act.getService().getId().toString())), true ); if (!carrier.getServices().containsKey(act.getService().getId())) { - logger.error("service with id " + act.getService().getId().toString() + " is contained in the carriers plan, " + - "but not available in the list of services. Carrier with carrierId: " + carrier.getId()); + logger.error("service with id {} is contained in the carriers plan, but not available in the list of services. Carrier with carrierId: {}", act.getService().getId().toString(), carrier.getId()); } } } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeReader.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeReader.java index ce87229d7ee..f10e5fc9bd5 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeReader.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeReader.java @@ -60,9 +60,9 @@ public void readFile( String filename ){ reader.setValidating(true) ; reader.readFile( filename ); } catch (Exception e) { - log.warn("### Exception: Message=" + e.getMessage() + " ; cause=" + e.getCause() + " ; class=" + e.getClass()); + log.warn("### Exception: Message={} ; cause={} ; class={}", e.getMessage(), e.getCause(), e.getClass()); if (e.getCause().getMessage().contains("cvc-elt.1")) { // "Cannot find the declaration of element" -> exception comes most probably because no validation information was found - log.warn("read with validation = true failed. Try it again without validation. filename: " + filename); + log.warn("read with validation = true failed. Try it again without validation. filename: {}", filename); reader.setValidating(false); reader.readFile(filename); } else { //other problem: e.g. validation does not work, because of missing validation file. @@ -78,11 +78,11 @@ public void readURL( URL url ){ reader.setValidating(true) ; reader.readURL(url); } catch (Exception e) { - log.warn("### Exception: Message=" + e.getMessage() ); - log.warn("### Exception: Cause=" + e.getCause() ); - log.warn("### Exception: Class=" + e.getClass() ); + log.warn("### Exception: Message={}", e.getMessage()); + log.warn("### Exception: Cause={}", e.getCause()); + log.warn("### Exception: Class={}", e.getClass()); if (e.getCause().getMessage().contains("cvc-elt.1.a")) { // "Cannot find the declaration of element" -> exception comes most probably because no validation information was found - log.warn("read with validation = true failed. Try it again without validation... url: " + url.toString()); + log.warn("read with validation = true failed. Try it again without validation... url: {}", url.toString()); reader.setValidating(false); reader.readURL(url); } else { //other problem: e.g. validation does not work, because of missing validation file. @@ -97,7 +97,8 @@ public void readStream( InputStream inputStream ){ reader.setValidating(true) ; reader.parse( inputStream ) ; } catch (Exception e) - {log.warn("### Exception found while trying to read Carrier Vehicle Type: Message: " + e.getMessage() + " ; cause: " + e.getCause() + " ; class " + e.getClass()); + { + log.warn("### Exception found while trying to read Carrier Vehicle Type: Message: {} ; cause: {} ; class {}", e.getMessage(), e.getCause(), e.getClass()); if (e.getCause().getMessage().contains("cvc-elt.1.a")) { // "Cannot find the declaration of element" -> exception comes most probably because no validation information was found log.warn("read with validation = true failed. Try it again without validation... "); reader.setValidating(false); @@ -121,10 +122,10 @@ private static final class CarrierVehicleTypeParser extends MatsimXmlParser { @Override public void startTag(final String name, final Attributes attributes, final Stack context) { - log.debug("Reading start tag. name: " + name + " , attributes: " + attributes.toString() + " , context: " + context); + log.debug("Reading start tag. name: {} , attributes: {} , context: {}", name, attributes.toString(), context); if ( "vehicleTypes".equalsIgnoreCase( name ) ) { String str = attributes.getValue( "xsi:schemaLocation" ); - log.info("Found following schemeLocation in carriers definition file: " + str); + log.info("Found following schemeLocation in carriers definition file: {}", str); if (str == null){ log.warn( "No validation information found. Using ReaderV1." ); delegate = new CarrierVehicleTypeReaderV1( vehicleTypes ); diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/Carriers.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/Carriers.java index 8746def11e9..f13f0bc56ae 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/Carriers.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/Carriers.java @@ -63,7 +63,7 @@ public void addCarrier(Carrier carrier) { if(!carriers.containsKey(carrier.getId())){ carriers.put(carrier.getId(), carrier); } - else log.warn("carrier " + carrier.getId() + " already exists"); + else log.warn("carrier {} already exists", carrier.getId()); } } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java index 9b594c05f6b..1b9e7117c65 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java @@ -314,7 +314,7 @@ public static void loadCarriersAccordingToFreightConfig(Scenario scenario) { */ private static void copyShipments(Carrier carrierWS, Carrier carrier) { for (CarrierShipment carrierShipment : carrier.getShipments().values()) { - log.debug("Copy CarrierShipment: " + carrierShipment.toString()); + log.debug("Copy CarrierShipment: {}", carrierShipment.toString()); addShipment(carrierWS, carrierShipment); } } @@ -349,7 +349,7 @@ private static void createShipmentsFromServices(Carrier carrierWS, Carrier carri } } for (CarrierService carrierService : carrier.getServices().values()) { - log.debug("Converting CarrierService to CarrierShipment: " + carrierService.getId()); + log.debug("Converting CarrierService to CarrierShipment: {}", carrierService.getId()); CarrierShipment carrierShipment = CarrierShipment.Builder .newInstance(Id.create(carrierService.getId().toString(), CarrierShipment.class), depotServiceIsDeliveredFrom.get(carrierService.getId()), carrierService.getLocationLinkId(), diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/Tour.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/Tour.java index 9b0e9d91696..a6161bd2d11 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/Tour.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/Tour.java @@ -197,7 +197,7 @@ public Builder schedulePickupAtBeginning(CarrierShipment shipment) { */ public void schedulePickup(CarrierShipment shipment) { Gbl.assertNotNull(shipment); - logger.debug("Pickup to get scheduled: " + shipment); + logger.debug("Pickup to get scheduled: {}", shipment); boolean wasNew = openPickups.add(shipment); if (!wasNew) { throw new IllegalStateException("Trying to deliver something which was already picked up."); @@ -223,8 +223,8 @@ private void assertLastElementIsLeg() { */ public void scheduleDelivery(CarrierShipment shipment) { Gbl.assertNotNull(shipment); - logger.debug("Delivery to get scheduled: " + shipment); - logger.debug("OpenPickups: " + openPickups); + logger.debug("Delivery to get scheduled: {}", shipment); + logger.debug("OpenPickups: {}", openPickups); boolean wasOpen = openPickups.remove(shipment); if (!wasOpen) { throw new IllegalStateException("Trying to deliver something which was not picked up."); diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgent.java index d3e08e9afbb..88423d00a1f 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgent.java @@ -179,7 +179,7 @@ void scoreSelectedPlan() { } scoringFunction.finish(); final double score = scoringFunction.getScore(); - log.warn("score=" + score); + log.warn("score={}", score); carrier.getSelectedPlan().setScore( score ); } void handleEvent(Event event, Id driverId) { diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java index 5a0889c8dc2..7ee36e067a7 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java @@ -83,7 +83,7 @@ final class CarrierDriverAgent{ this.carrier = carrier; this.events = events; this.carrierEventCreators = carrierEventCreators; - log.debug( "creating CarrierDriverAgent with driverId=" + driverId ); + log.debug("creating CarrierDriverAgent with driverId={}", driverId); this.driverId = driverId; this.scheduledTour = tour; } @@ -163,7 +163,7 @@ private void handleEvent( ActivityEndEvent event ){ createAdditionalEvents( event, currentActivity, scheduledTour, driverId, planElementCounter ); - log.debug( "handling activity end event=" + event ); + log.debug("handling activity end event={}", event); if( CarrierConstants.START.equals( event.getActType() ) ){ planElementCounter += 1; return; diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightAgentSource.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightAgentSource.java index 0feadd08226..6b60f14d91b 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightAgentSource.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightAgentSource.java @@ -75,15 +75,15 @@ public final class FreightAgentSource implements AgentSource { Vehicle vehicle; if( CarriersUtils.getVehicle( freightDriverPlan ) == null ){ vehicle = VehicleUtils.getFactory().createVehicle( Id.create( agent.getId(), Vehicle.class ), VehicleUtils.createDefaultVehicleType() ); - log.warn( "vehicle for agent " + freightDriverPlan.getPerson().getId() + " is missing. set default vehicle where maxVelocity is solely defined by link.speed." ); + log.warn("vehicle for agent {} is missing. set default vehicle where maxVelocity is solely defined by link.speed.", freightDriverPlan.getPerson().getId()); } else if( CarriersUtils.getVehicle( freightDriverPlan ).getType() == null ){ vehicle = VehicleUtils.getFactory().createVehicle( Id.create( agent.getId(), Vehicle.class ), VehicleUtils.createDefaultVehicleType() ); - log.warn( "vehicleType for agent " + freightDriverPlan.getPerson().getId() + " is missing. set default vehicleType where maxVelocity is solely defined by link.speed." ); + log.warn("vehicleType for agent {} is missing. set default vehicleType where maxVelocity is solely defined by link.speed.", freightDriverPlan.getPerson().getId()); } else { vehicle = CarriersUtils.getVehicle( freightDriverPlan ); } - log.warn( "inserting vehicleId=" + vehicle.getId() + " into mobsim." ); + log.warn("inserting vehicleId={} into mobsim.", vehicle.getId()); qsim.addParkedVehicle( new QVehicleImpl( vehicle ), agent.getCurrentLinkId() ); // yyyyyy should rather use QVehicleFactory. kai, nov'18 diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java index 0b16a1dbbed..94115fa9a1d 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java @@ -318,7 +318,7 @@ static com.graphhopper.jsprit.core.problem.vehicle.VehicleType createJspritVehic final double vehicleCapacity = matsimVehicleType.getCapacity().getOther(); final int vehicleCapacityInt = (int) vehicleCapacity; if (vehicleCapacity - vehicleCapacityInt > 0) { - log.warn("vehicle capacity truncated to int: before=" + vehicleCapacity + "; after=" + vehicleCapacityInt); + log.warn("vehicle capacity truncated to int: before={}; after={}", vehicleCapacity, vehicleCapacityInt); // yyyyyy this implies that we would have fewer problems if we set vehicle // capacity in kg instead of in tons in our data model. kai, aug'19 } @@ -329,13 +329,13 @@ static com.graphhopper.jsprit.core.problem.vehicle.VehicleType createJspritVehic if (VehicleUtils.getCostsPerSecondInService(matsimVehicleType.getCostInformation()) != null) { jspritVehTypeBuilder.setCostPerServiceTime(VehicleUtils.getCostsPerSecondInService(matsimVehicleType.getCostInformation())); } else { - log.info("'costsPerSecondInService' is not set in VehicleType attributes. Will use the value of 'costsPerSecond' instead. VehicleTypeId: " + matsimVehicleType.getId()); + log.info("'costsPerSecondInService' is not set in VehicleType attributes. Will use the value of 'costsPerSecond' instead. VehicleTypeId: {}", matsimVehicleType.getId()); jspritVehTypeBuilder.setCostPerServiceTime(matsimVehicleType.getCostInformation().getCostsPerSecond()); } if (VehicleUtils.getCostsPerSecondWaiting(matsimVehicleType.getCostInformation()) != null) { jspritVehTypeBuilder.setCostPerWaitingTime(VehicleUtils.getCostsPerSecondWaiting(matsimVehicleType.getCostInformation())); } else { - log.info("'costsPerSecondWaiting' is not set in VehicleType attributes. Will use the value of 'costsPerSecond' instead. VehicleTypeId: " + matsimVehicleType.getId()); + log.info("'costsPerSecondWaiting' is not set in VehicleType attributes. Will use the value of 'costsPerSecond' instead. VehicleTypeId: {}", matsimVehicleType.getId()); jspritVehTypeBuilder.setCostPerWaitingTime(matsimVehicleType.getCostInformation().getCostsPerSecond()); } jspritVehTypeBuilder.setFixedCost(matsimVehicleType.getCostInformation().getFixedCosts()); @@ -369,22 +369,19 @@ static ScheduledTour createScheduledTour(VehicleRoute jspritRoute, Id tour matsimFreightTourBuilder.scheduleStart(Id.create(jspritRoute.getStart().getLocation().getId(), Link.class)); for (TourActivity act : tour.getActivities()) { if (act instanceof ServiceActivity || act instanceof PickupService) { - log.debug("Found ServiceActivity or PickupService : " + act.getName() + " at location " - + act.getLocation().getId() + " : " + act.getLocation().getCoordinate()); + log.debug("Found ServiceActivity or PickupService : {} at location {} : {}", act.getName(), act.getLocation().getId(), act.getLocation().getCoordinate()); Service job = (Service) ((JobActivity) act).getJob(); CarrierService carrierService = createCarrierService(job); matsimFreightTourBuilder.addLeg(new Tour.Leg()); matsimFreightTourBuilder.scheduleService(carrierService); } else if (act instanceof DeliverShipment) { - log.debug("Found DeliveryShipment: " + act.getName() + " at location " + act.getLocation().getId() - + " : " + act.getLocation().getCoordinate()); + log.debug("Found DeliveryShipment: {} at location {} : {}", act.getName(), act.getLocation().getId(), act.getLocation().getCoordinate()); Shipment job = (Shipment) ((JobActivity) act).getJob(); CarrierShipment carrierShipment = createCarrierShipment(job); matsimFreightTourBuilder.addLeg(new Tour.Leg()); matsimFreightTourBuilder.scheduleDelivery(carrierShipment); } else if (act instanceof PickupShipment) { - log.debug("Found PickupShipment: " + act.getName() + " at location " + act.getLocation().getId() + " : " - + act.getLocation().getCoordinate()); + log.debug("Found PickupShipment: {} at location {} : {}", act.getName(), act.getLocation().getId(), act.getLocation().getCoordinate()); Shipment job = (Shipment) ((JobActivity) act).getJob(); CarrierShipment carrierShipment = createCarrierShipment(job); matsimFreightTourBuilder.addLeg(new Tour.Leg()); @@ -445,13 +442,12 @@ public static VehicleRoute createRoute(ScheduledTour scheduledTour, VehicleRouti } } VehicleRoute jspritRoute = jspritRouteBuilder.build(); - log.debug("jsprit route: " + jspritRoute); - log.debug("start-location: " + jspritRoute.getStart().getLocation() + " endTime: " + jspritRoute.getDepartureTime() + "(" - + jspritRoute.getStart().getEndTime() + ")"); + log.debug("jsprit route: {}", jspritRoute); + log.debug("start-location: {} endTime: {}({})", jspritRoute.getStart().getLocation(), jspritRoute.getDepartureTime(), jspritRoute.getStart().getEndTime()); for (TourActivity act : jspritRoute.getActivities()) { - log.debug("act: " + act); + log.debug("act: {}", act); } - log.debug("end: " + jspritRoute.getEnd()); + log.debug("end: {}", jspritRoute.getEnd()); if (jspritRoute.getDepartureTime() != scheduledTour.getDeparture()) throw new AssertionError("departureTimes of both routes must be equal"); return jspritRoute; @@ -502,7 +498,7 @@ public static VehicleRoutingProblem createRoutingProblem(Carrier carrier, Networ + carrierVehicle.getId() + "][locationId=" + carrierVehicle.getLinkId() + "]"); coordinate = link.getCoord(); } else - log.warn("cannot find linkId " + carrierVehicle.getId()); + log.warn("cannot find linkId {}", carrierVehicle.getId()); Vehicle veh = createJspritVehicle(carrierVehicle, coordinate); if (veh.getEarliestDeparture() != carrierVehicle.getEarliestStartTime()) @@ -523,7 +519,7 @@ public static VehicleRoutingProblem createRoutingProblem(Carrier carrier, Networ if (link != null) { coordinate = link.getCoord(); } else - log.warn("cannot find linkId " + service.getLocationLinkId()); + log.warn("cannot find linkId {}", service.getLocationLinkId()); } vrpBuilder.addJob(createJspritService(service, coordinate)); } @@ -606,13 +602,13 @@ public static VehicleRoutingProblem.Builder createRoutingProblemBuilder(Carrier + carrierVehicle.getId() + "][locationId=" + carrierVehicle.getLinkId() + "]"); coordinate = link.getCoord(); } else - log.warn("cannot find linkId " + carrierVehicle.getId()); + log.warn("cannot find linkId {}", carrierVehicle.getId()); vrpBuilder.addVehicle(createJspritVehicle(carrierVehicle, coordinate)); } if (serviceInVrp) { for (CarrierService service : carrier.getServices().values()) { - log.debug("Handle CarrierService: " + service.toString()); + log.debug("Handle CarrierService: {}", service.toString()); Coord coordinate = null; if (network != null) { Link link = network.getLinks().get(service.getLocationLinkId()); @@ -628,7 +624,7 @@ public static VehicleRoutingProblem.Builder createRoutingProblemBuilder(Carrier if (shipmentInVrp) { for (CarrierShipment carrierShipment : carrier.getShipments().values()) { - log.debug("Handle CarrierShipment: " + carrierShipment.toString()); + log.debug("Handle CarrierShipment: {}", carrierShipment.toString()); Coord fromCoordinate = null; Coord toCoordinate = null; if (network != null) { @@ -637,7 +633,7 @@ public static VehicleRoutingProblem.Builder createRoutingProblemBuilder(Carrier if (fromLink != null && toLink != null) { // Shipment to be delivered from specified location to // specified location - log.debug("Shipment identified as Shipment: " + carrierShipment.getId().toString()); + log.debug("Shipment identified as Shipment: {}", carrierShipment.getId().toString()); fromCoordinate = fromLink.getCoord(); toCoordinate = toLink.getCoord(); } else @@ -735,7 +731,7 @@ public static VehicleRoutingAlgorithm loadOrCreateVehicleRoutingAlgorithm(Scenar final String vehicleRoutingAlgorithmFile = freightConfig.getVehicleRoutingAlgorithmFile(); if (vehicleRoutingAlgorithmFile != null && !vehicleRoutingAlgorithmFile.equals("")) { - log.info("Will read in VehicleRoutingAlgorithm from " + vehicleRoutingAlgorithmFile); + log.info("Will read in VehicleRoutingAlgorithm from {}", vehicleRoutingAlgorithmFile); URL vraURL; try { vraURL = IOUtils.extendUrl(scenario.getConfig().getContext(), vehicleRoutingAlgorithmFile); diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/CarrierScoreStats.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/CarrierScoreStats.java index dd289a49b1b..84556de1a14 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/CarrierScoreStats.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/CarrierScoreStats.java @@ -178,10 +178,10 @@ public void notifyIterationEnds(final IterationEndsEvent event) { nofAvgScores++; } } - log.info("-- avg. score of the executed plan of each agent: " + (sumExecutedScores / nofExecutedScores)); - log.info("-- avg. score of the worst plan of each agent: " + (sumScoreWorst / nofScoreWorst)); - log.info("-- avg. of the avg. plan score per agent: " + (sumAvgScores / nofAvgScores)); - log.info("-- avg. score of the best plan of each agent: " + (sumScoreBest / nofScoreBest)); + log.info("-- avg. score of the executed plan of each agent: {}", sumExecutedScores / nofExecutedScores); + log.info("-- avg. score of the worst plan of each agent: {}", sumScoreWorst / nofScoreWorst); + log.info("-- avg. of the avg. plan score per agent: {}", sumAvgScores / nofAvgScores); + log.info("-- avg. score of the best plan of each agent: {}", sumScoreBest / nofScoreBest); try { this.out.write(event.getIteration() + "\t" + (sumExecutedScores / nofExecutedScores) + "\t" + diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/FixedCostsTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/FixedCostsTest.java index 07ea6e5ac60..3b6ec115df5 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/FixedCostsTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/FixedCostsTest.java @@ -161,7 +161,7 @@ public void setUp() throws Exception { netBuilder.setTimeSliceWidth(86400) ; // !!!!, otherwise it will not do anything. for (Carrier carrier : carriers.getCarriers().values()) { - log.info("creating and solving VRP for carrier: " + carrier.getId().toString()); + log.info("creating and solving VRP for carrier: {}", carrier.getId().toString()); //Build VRP VehicleRoutingProblem.Builder vrpBuilder = MatsimJspritFactory.createRoutingProblemBuilder(carrier, network); vrpBuilder.setRoutingCost(netBasedCosts) ; From af5098efe971cf3bc24f5f1328ed376e0b44693d Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 15:36:33 +0200 Subject: [PATCH 032/101] delete empty test methods --- .../freight/carriers/jsprit/MatsimTransformerTest.java | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java index 991ef3eb236..23438d50fbc 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java @@ -401,11 +401,6 @@ private CarrierShipment getMatsimShipment(String id, String from, String to, int .setPickupServiceTime(15.0).setPickupTimeWindow(TimeWindow.newInstance(1.0, 5.0)).build(); } - @Test - void createVehicleRoutingProblemWithServices_isMadeCorrectly() { - // TODO create - } - @Test void createVehicleRoutingProblemBuilderWithServices_isMadeCorrectly() { Carrier carrier = createCarrierWithServices(); @@ -453,11 +448,6 @@ void createVehicleRoutingProblemBuilderWithServices_isMadeCorrectly() { assertEquals("i(3,9)", service2.getLocation().getId().toString()); } - @Test - void createVehicleRoutingProblemWithShipments_isMadeCorrectly() { - // TODO create - } - // @Disabled //Set to ignore due to not implemented functionality of Shipments in MatsimJspritFactory @Test void createVehicleRoutingProblemBuilderWithShipments_isMadeCorrectly() { From 6d14b2541dce8bc21c101aed18de04382dc9873f Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 15:36:44 +0200 Subject: [PATCH 033/101] remove unused import --- .../src/main/java/org/matsim/freight/carriers/CarriersUtils.java | 1 - 1 file changed, 1 deletion(-) diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java index 1b9e7117c65..143b5e20e22 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java @@ -47,7 +47,6 @@ import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.Collectors; public class CarriersUtils { From edda343ed3c1fce45c480536a281bfe0bf683263 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:10:24 +0200 Subject: [PATCH 034/101] fix unchecked assignment --- .../freight/carriers/jsprit/DistanceConstraintTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintTest.java index 16c42c7286c..a14b562fa6d 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintTest.java @@ -494,7 +494,7 @@ final void CarrierWithShipmentsMidSizeBatteryTest_Version5() throws ExecutionExc MatsimTestUtils.EPSILON, "Wrong maximum distance of the tour of this vehicleType"); - ArrayList distancesOfTours = new ArrayList(); + ArrayList distancesOfTours = new ArrayList<>(); for (ScheduledTour scheduledTour: carrierV5.getSelectedPlan().getScheduledTours()) { double distanceTour = 0.0; List elements = scheduledTour.getTour().getTourElements(); @@ -576,7 +576,7 @@ final void CarrierWithShipmentsLargeBatteryTest_Version6() throws ExecutionExcep MatsimTestUtils.EPSILON, "Wrong maximum distance of the tour of this vehicleType"); - ArrayList distancesOfTours = new ArrayList(); + ArrayList distancesOfTours = new ArrayList<>(); for (ScheduledTour scheduledTour: carrierV5.getSelectedPlan().getScheduledTours()) { double distanceTour = 0.0; List elements = scheduledTour.getTour().getTourElements(); From a1c3a771c5a511e360e091ea0ca87cae7d929689 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:12:38 +0200 Subject: [PATCH 035/101] remove redundant local variables --- .../freight/carriers/CarrierVehicleTypeTest.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeTest.java index 8ca8a5aae02..c91bc625fb9 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeTest.java @@ -59,14 +59,12 @@ public void setUp() throws Exception{ //Setting up a copy of the one above VehicleType newVehicleType1 = VehicleUtils.getFactory().createVehicleType( Id.create("medium2", VehicleType.class ) ); VehicleUtils.copyFromTo( mediumType, newVehicleType1 ); - VehicleType mediumType2 = newVehicleType1; - types.getVehicleTypes().put(mediumType2.getId(), mediumType2); + types.getVehicleTypes().put(newVehicleType1.getId(), newVehicleType1); //Setting up a smaller one based of the one above and changing all values. final Id smallTypeId = Id.create( "small", VehicleType.class ); - VehicleType newVehicleType = VehicleUtils.getFactory().createVehicleType( smallTypeId ); - VehicleUtils.copyFromTo( mediumType, newVehicleType ); - VehicleType smallType = newVehicleType ; + VehicleType smallType = VehicleUtils.getFactory().createVehicleType( smallTypeId ); + VehicleUtils.copyFromTo( mediumType, smallType ); { CostInformation costInformation = smallType.getCostInformation() ; costInformation.setFixedCost( 25. ); @@ -79,7 +77,7 @@ public void setUp() throws Exception{ capacity.setWeightInTons( 16 ) ; // VehicleType smallType = CarriersUtils.CarrierVehicleTypeBuilder.newInstance( smallTypeId, mediumType ) smallType.setDescription( "Small Vehicle" ).setMaximumVelocity( 10.0 ) ; - types.getVehicleTypes().put( smallType.getId(), smallType ); + types.getVehicleTypes().put( smallType.getId(), smallType); } } From 720a2d074a4cdbb34202c03cd4fb044ecf28cf50 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:14:33 +0200 Subject: [PATCH 036/101] minor code style update --- .../org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java index 94115fa9a1d..eae8060dde6 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java @@ -730,7 +730,7 @@ public static VehicleRoutingAlgorithm loadOrCreateVehicleRoutingAlgorithm(Scenar VehicleRoutingAlgorithm algorithm; final String vehicleRoutingAlgorithmFile = freightConfig.getVehicleRoutingAlgorithmFile(); - if (vehicleRoutingAlgorithmFile != null && !vehicleRoutingAlgorithmFile.equals("")) { + if (vehicleRoutingAlgorithmFile != null && !vehicleRoutingAlgorithmFile.isEmpty()) { log.info("Will read in VehicleRoutingAlgorithm from {}", vehicleRoutingAlgorithmFile); URL vraURL; try { From 7e45620fe95bc7cda0b7fa25bab17143b8c27300 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:17:54 +0200 Subject: [PATCH 037/101] remove not needed throw information --- .../org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java index be71e48b2ca..59f8416f6a2 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java @@ -36,7 +36,7 @@ public class CarrierReadWriteV2_1Test { private MatsimTestUtils utils = new MatsimTestUtils(); @Test - void readWriteTest() throws FileNotFoundException, IOException { + void readWriteTest() { Carriers carriers = new Carriers(Collections.emptyList()); CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); @@ -57,7 +57,7 @@ void readWriteTest() throws FileNotFoundException, IOException { @Test - void readWriteReadTest() throws FileNotFoundException, IOException { + void readWriteReadTest() { Carriers carriers = new Carriers(Collections.emptyList()); CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); From 8d310b4391761d65ddf7d5be4f70edff67eaf059 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:19:42 +0200 Subject: [PATCH 038/101] make things final --- .../java/org/matsim/freight/carriers/CarrierShipment.java | 6 +++--- .../org/matsim/freight/carriers/CarrierVehicleType.java | 2 +- .../carriers/events/CarrierTourStartEventCreator.java | 4 ++-- .../jsprit/NetworkBasedTransportCostsFactory.java | 8 ++++---- .../usecases/chessboard/FreightScenarioCreator.java | 2 +- .../usecases/chessboard/PassengerScenarioCreator.java | 2 +- .../mobsim/DistanceScoringFunctionFactoryForTests.java | 4 ++-- .../carriers/mobsim/ScoringFunctionFactoryForTests.java | 6 +++--- .../mobsim/TimeScoringFunctionFactoryForTests.java | 2 +- 9 files changed, 18 insertions(+), 18 deletions(-) diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierShipment.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierShipment.java index 1298f3eb5b2..9472ffaac91 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierShipment.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierShipment.java @@ -81,9 +81,9 @@ public static Builder newInstance(Id id, Id from, Id id; - Id from; - Id to; - int size; + final Id from; + final Id to; + final int size; TimeWindow pickTW = TimeWindow.newInstance(0.0, Integer.MAX_VALUE); TimeWindow delTW = TimeWindow.newInstance(0.0, Integer.MAX_VALUE); double pickServiceTime = 0.0; diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleType.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleType.java index 8f5a5ea31e7..16b7e92a03d 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleType.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleType.java @@ -50,7 +50,7 @@ private CarrierVehicleType(){} // do not instantiate * */ public static class Builder { - VehicleType delegate ; + final VehicleType delegate ; /** * Returns a new instance of builder initialized with the typeId. diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourStartEventCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourStartEventCreator.java index eb015551dd0..aacf3e6ef12 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourStartEventCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourStartEventCreator.java @@ -36,8 +36,8 @@ /*package-private*/ final class CarrierTourStartEventCreator implements CarrierEventCreator { - TreeMap, ActivityEndEvent> endEventMap = new TreeMap<>(); - TreeMap, PersonEntersVehicleEvent> personEntersVehicleEventMap = new TreeMap<>(); + final TreeMap, ActivityEndEvent> endEventMap = new TreeMap<>(); + final TreeMap, PersonEntersVehicleEvent> personEntersVehicleEventMap = new TreeMap<>(); @Override diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCostsFactory.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCostsFactory.java index 3fcc5ca9868..6a0be5414f0 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCostsFactory.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCostsFactory.java @@ -38,10 +38,10 @@ * @author steffenaxer */ public class NetworkBasedTransportCostsFactory implements VRPTransportCostsFactory { - Scenario scenario; - Carriers carriers; - Map travelTimes; - Config config; + final Scenario scenario; + final Carriers carriers; + final Map travelTimes; + final Config config; public NetworkBasedTransportCostsFactory(Scenario scenario, Carriers carriers, Map travelTimes, Config config) { this.scenario = scenario; diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/FreightScenarioCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/FreightScenarioCreator.java index be215bd0d7e..c258d01e703 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/FreightScenarioCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/FreightScenarioCreator.java @@ -47,7 +47,7 @@ final class FreightScenarioCreator { static int agentCounter = 1; - static Random random = new Random(Long.MAX_VALUE); + static final Random random = new Random(Long.MAX_VALUE); public static void main(String[] args) { diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/PassengerScenarioCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/PassengerScenarioCreator.java index e19d4b506bb..3a742ced5e6 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/PassengerScenarioCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/PassengerScenarioCreator.java @@ -43,7 +43,7 @@ final class PassengerScenarioCreator { static int agentCounter = 1; - static int nuOfAgentsPerHomeLink = 1; + static final int nuOfAgentsPerHomeLink = 1; public static void main(String[] args) { diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java index 121eb0c5616..685873ba8e0 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java @@ -154,7 +154,7 @@ static class DriverActScoring implements BasicScoring, ActivityScoring{ double startTimeOfEnd; - double amountPerHour = 20.0; + final double amountPerHour = 20.0; @Override public void startActivity(double time, Activity act) { @@ -192,7 +192,7 @@ public void reset() { static class NumberOfToursAward implements BasicScoring{ - private Carrier carrier; + private final Carrier carrier; public NumberOfToursAward(Carrier carrier) { super(); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java index 3bf4716a680..9f20c3189bf 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java @@ -136,7 +136,7 @@ static class DriverActScoring implements BasicScoring, ActivityScoring{ double startTimeOfEnd; - double amountPerHour = 20.0; + final double amountPerHour = 20.0; @Override public void startActivity(double time, Activity act) { @@ -174,7 +174,7 @@ public void reset() { static class NumberOfToursAward implements BasicScoring{ - private Carrier carrier; + private final Carrier carrier; public NumberOfToursAward(Carrier carrier) { super(); @@ -199,7 +199,7 @@ public void reset() { } - private Network network; + private final Network network; public ScoringFunctionFactoryForTests(Network network) { super(); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/TimeScoringFunctionFactoryForTests.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/TimeScoringFunctionFactoryForTests.java index ee8e1921ed7..65bd9951299 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/TimeScoringFunctionFactoryForTests.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/TimeScoringFunctionFactoryForTests.java @@ -200,7 +200,7 @@ public void reset() { static class NumberOfToursAward implements BasicScoring{ - private Carrier carrier; + private final Carrier carrier; public NumberOfToursAward(Carrier carrier) { super(); From 295ef5fd37be2ea8ab2c571f370f5d204666d59c Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:21:02 +0200 Subject: [PATCH 039/101] remove redundant final declaration --- .../usecases/chessboard/RunPassengerAlongWithCarriers.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerAlongWithCarriers.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerAlongWithCarriers.java index 36f76f30787..9d54c7299e1 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerAlongWithCarriers.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerAlongWithCarriers.java @@ -97,7 +97,7 @@ public void run() { } - public final Config prepareConfig() { + public Config prepareConfig() { Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(url, "config.xml")); config.controller().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles ); config.global().setRandomSeed(4177); @@ -105,7 +105,7 @@ public final Config prepareConfig() { return config; } - public final Scenario prepareScenario(Config config) { + public Scenario prepareScenario(Config config) { Gbl.assertNotNull( config ); Scenario scenario = ScenarioUtils.loadScenario(config); CarriersUtils.addOrGetCarriers(scenario); From e57b1389a97e104c9aa9bd346c3c5a2c46fff2e2 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:23:17 +0200 Subject: [PATCH 040/101] remove unnecessary 'throws' declarations --- .../carriers/CarrierPlanXmlWriterV2_1.java | 15 +++++++-------- .../carriers/CarrierPlanXmlReaderV2Test.java | 2 +- .../CarrierPlanXmlReaderV2WithDtdTest.java | 2 +- .../carriers/CarrierPlanXmlWriterV2Test.java | 2 +- .../carriers/CarrierPlanXmlWriterV2_1Test.java | 2 +- .../carriers/CarrierVehicleTypeLoaderTest.java | 2 +- .../freight/carriers/CarrierVehicleTypeTest.java | 2 +- .../freight/carriers/jsprit/FixedCostsTest.java | 2 +- .../carriers/utils/CarrierControlerUtilsTest.java | 2 +- 9 files changed, 15 insertions(+), 16 deletions(-) diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1.java index 88be7b7b866..92699982378 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1.java @@ -104,7 +104,7 @@ public void write(String filename) { } } - private void writeRootElement() throws UncheckedIOException, IOException { + private void writeRootElement() throws UncheckedIOException { List> atts = new ArrayList<>(); atts.add(createTuple(XMLNS, MatsimXmlWriter.MATSIM_NAMESPACE)); atts.add(createTuple(XMLNS + ":xsi", DEFAULTSCHEMANAMESPACELOCATION)); @@ -112,15 +112,14 @@ private void writeRootElement() throws UncheckedIOException, IOException { this.writeStartTag(CARRIERS, atts); } - private void startCarrier(Carrier carrier, BufferedWriter writer) - throws IOException { + private void startCarrier(Carrier carrier, BufferedWriter writer) { this.writeStartTag(CARRIER, List.of( createTuple(ID, carrier.getId().toString())), false, true ); attributesWriter.writeAttributes("\t\t", writer, carrier.getAttributes(), false); } - private void writeVehiclesAndTheirTypes(Carrier carrier)throws IOException { + private void writeVehiclesAndTheirTypes(Carrier carrier) { this.writeStartTag(CAPABILITIES, List.of( createTuple(FLEET_SIZE, carrier.getCarrierCapabilities().getFleetSize().toString()) )); @@ -142,7 +141,7 @@ private void writeVehiclesAndTheirTypes(Carrier carrier)throws IOException { this.writeEndTag(CAPABILITIES); } - private void writeShipments(Carrier carrier, BufferedWriter writer) throws IOException { + private void writeShipments(Carrier carrier, BufferedWriter writer) { if(carrier.getShipments().isEmpty()) return; this.writeStartTag(SHIPMENTS, null); for (CarrierShipment s : carrier.getShipments().values()) { @@ -173,7 +172,7 @@ private void writeShipment(CarrierShipment s, Id shipmentId, bo ); } - private void writeServices(Carrier carrier, BufferedWriter writer) throws IOException { + private void writeServices(Carrier carrier, BufferedWriter writer) { if(carrier.getServices().isEmpty()) return; this.writeStartTag(SERVICES, null); for (CarrierService s : carrier.getServices().values()) { @@ -306,11 +305,11 @@ else if (tourElement instanceof Tour.ServiceActivity act) { this.writeEndTag(PLANS); } - private void endCarrier() throws IOException { + private void endCarrier() { this.writeEndTag(CARRIER); } - private void writeEndElement() throws IOException { + private void writeEndElement() { this.writeEndTag(CARRIERS); } } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test.java index e5412431ca5..db0e3008d20 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test.java @@ -50,7 +50,7 @@ public class CarrierPlanXmlReaderV2Test { private Carrier testCarrier; @BeforeEach - public void setUp() throws Exception{ + public void setUp() { CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); new CarrierVehicleTypeReader( carrierVehicleTypes ).readFile( utils.getPackageInputDirectory() + "vehicleTypes_v2.xml" ); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest.java index 22d23f8eefe..cff37127033 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest.java @@ -43,7 +43,7 @@ public class CarrierPlanXmlReaderV2WithDtdTest { private Carrier testCarrier; @BeforeEach - public void setUp() throws Exception{ + public void setUp() { CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); new CarrierVehicleTypeReader( carrierVehicleTypes ).readFile( utils.getPackageInputDirectory() + "vehicleTypes_v2.xml" ); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java index 822b98269d6..d3703c241e9 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java @@ -43,7 +43,7 @@ public class CarrierPlanXmlWriterV2Test { private Carrier testCarrier; @BeforeEach - public void setUp() throws Exception{ + public void setUp() { CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); new CarrierVehicleTypeReader( carrierVehicleTypes ).readFile( this.testUtils.getPackageInputDirectory() + "vehicleTypes_v2.xml" ); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java index 7788b8895f5..4f7eb5773c9 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java @@ -43,7 +43,7 @@ public class CarrierPlanXmlWriterV2_1Test { private Carrier testCarrier; @BeforeEach - public void setUp() throws Exception{ + public void setUp() { CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); new CarrierVehicleTypeReader( carrierVehicleTypes ).readFile( this.testUtils.getPackageInputDirectory() + "vehicleTypes_v2.xml" ); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeLoaderTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeLoaderTest.java index df97a944c1d..97954bb151d 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeLoaderTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeLoaderTest.java @@ -40,7 +40,7 @@ public class CarrierVehicleTypeLoaderTest { private Carriers carriers; @BeforeEach - public void setUp() throws Exception{ + public void setUp() { types = new CarrierVehicleTypes(); new CarrierVehicleTypeReader(types).readFile(utils.getClassInputDirectory() + "vehicleTypes.xml"); carriers = new Carriers(); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeTest.java index c91bc625fb9..24328872de2 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeTest.java @@ -39,7 +39,7 @@ public class CarrierVehicleTypeTest { CarrierVehicleTypes types; @BeforeEach - public void setUp() throws Exception{ + public void setUp() { final Id vehicleTypeId = Id.create( "medium", VehicleType.class ); VehicleType mediumType = VehicleUtils.getFactory().createVehicleType( vehicleTypeId ); { diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/FixedCostsTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/FixedCostsTest.java index 3b6ec115df5..13433ede378 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/FixedCostsTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/FixedCostsTest.java @@ -65,7 +65,7 @@ public class FixedCostsTest { private final Carriers carriersPlannedAndRouted = new Carriers(); @BeforeEach - public void setUp() throws Exception { + public void setUp() { // Create carrier with services; service1 nearby the depot, service2 at the opposite side of the network CarrierService service1 = createMatsimService("Service1", "i(3,0)", 1); CarrierService service2 = createMatsimService("Service2", "i(9,9)R", 1); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsTest.java index 678b2727ff1..30ae050e289 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsTest.java @@ -443,7 +443,7 @@ void testRunJsprit_allInformationGiven(){ * This test should lead to an exception, because the NumberOfJspritIterations is not set for carriers. */ @Test - void testRunJsprit_NoOfJspritIterationsMissing() throws ExecutionException, InterruptedException { + void testRunJsprit_NoOfJspritIterationsMissing() { assertThrows(java.util.concurrent.ExecutionException.class, () -> { Config config = prepareConfig(); config.controller().setOutputDirectory(utils.getOutputDirectory()); From 72aa7ca0a4025c359d5eb254d5b57099d62ac5a6 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:24:47 +0200 Subject: [PATCH 041/101] simplify assertions --- .../jsprit/MatsimTransformerTest.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java index 23438d50fbc..4293663dd7a 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java @@ -133,8 +133,8 @@ void whenTransforming_matsimService2jspritService_isMadeCorrectly() { assertEquals(10.0, service.getTimeWindow().getStart(), 0.01); Service service2 = MatsimJspritFactory.createJspritService(carrierService, null); - assertTrue(service != service2); - assertTrue(service.equals(service2)); + assertNotSame(service, service2); + assertEquals(service, service2); } @Test @@ -153,8 +153,8 @@ void whenTransforming_jspritService2matsimService_isMadeCorrectly() { assertEquals(10.0, service.getServiceStartTimeWindow().getStart(), 0.01); CarrierService service2 = MatsimJspritFactory.createCarrierService(carrierService); - assertTrue(service != service2); - assertTrue(service.equals(service2)); + assertNotSame(service, service2); + assertEquals(service, service2); } @Test @@ -177,8 +177,8 @@ void whenTransforming_matsimShipment2jspritShipment_isMadeCorrectly() { assertEquals(50, shipment.getSize().get(0)); Shipment shipment2 = MatsimJspritFactory.createJspritShipment(carrierShipment); - assertTrue(shipment != shipment2); - assertTrue(shipment.equals(shipment2)); + assertNotSame(shipment, shipment2); + assertEquals(shipment, shipment2); } @Test @@ -205,8 +205,8 @@ void whenTransforming_jspritShipment2matsimShipment_isMadeCorrectly() { assertEquals(50, carrierShipment.getSize()); CarrierShipment carrierShipment2 = MatsimJspritFactory.createCarrierShipment(shipment); - assertTrue(carrierShipment != carrierShipment2); - assertTrue(carrierShipment.equals(carrierShipment2)); + assertNotSame(carrierShipment, carrierShipment2); + assertEquals(carrierShipment, carrierShipment2); } @Test @@ -431,7 +431,7 @@ void createVehicleRoutingProblemBuilderWithServices_isMadeCorrectly() { assertNotNull(jobS1); assertEquals("serviceId", jobS1.getId()); assertEquals(20, jobS1.getSize().get(0)); - assertTrue(jobS1 instanceof Service); + assertInstanceOf(Service.class, jobS1); Service service1 = (Service) jobS1; assertEquals(20, service1.getSize().get(0)); assertEquals(10.0, service1.getServiceDuration(), 0.0); @@ -441,7 +441,7 @@ void createVehicleRoutingProblemBuilderWithServices_isMadeCorrectly() { assertNotNull(jobS2); assertEquals("serviceId2", jobS2.getId()); assertEquals(10, jobS2.getSize().get(0)); - assertTrue(jobS2 instanceof Service); + assertInstanceOf(Service.class, jobS2); Service service2 = (Service) jobS2; assertEquals(10, service2.getSize().get(0)); assertEquals(20.0, service2.getServiceDuration(), 0.0); @@ -479,7 +479,7 @@ void createVehicleRoutingProblemBuilderWithShipments_isMadeCorrectly() { assertNotNull(jobS1); assertEquals("shipment1", jobS1.getId()); assertEquals(10, jobS1.getSize().get(0)); - assertTrue(jobS1 instanceof Shipment); + assertInstanceOf(Shipment.class, jobS1); Shipment shipment1 = (Shipment) jobS1; assertEquals(10, shipment1.getSize().get(0)); assertEquals("i(6,0)", shipment1.getPickupLocation().getId()); @@ -495,7 +495,7 @@ void createVehicleRoutingProblemBuilderWithShipments_isMadeCorrectly() { assertNotNull(jobS2); assertEquals("shipment2", jobS2.getId()); assertEquals(20, jobS2.getSize().get(0)); - assertTrue(jobS2 instanceof Shipment); + assertInstanceOf(Shipment.class, jobS2); Shipment shipment2 = (Shipment) jobS2; assertEquals(20, shipment2.getSize().get(0)); assertEquals("i(3,9)", shipment2.getDeliveryLocation().getId().toString()); From 154f91b853113de27bd5cf5132673a0c698de6da Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:27:12 +0200 Subject: [PATCH 042/101] cleanup Strings --- .../chessboard/CarrierScoringFunctionFactoryImpl.java | 2 +- .../freight/carriers/jsprit/MatsimTransformerTest.java | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/CarrierScoringFunctionFactoryImpl.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/CarrierScoringFunctionFactoryImpl.java index 6d137ce6f27..759b3da5890 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/CarrierScoringFunctionFactoryImpl.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/CarrierScoringFunctionFactoryImpl.java @@ -237,7 +237,7 @@ public void handleEvent(Event event) { CarrierVehicle carrierVehicle = CarriersUtils.getCarrierVehicle(carrier, ((LinkEnterEvent) event).getVehicleId()); if(carrierVehicle == null) throw new IllegalStateException("carrier vehicle missing"); double toll = roadPricing.getTollAmount(carrierVehicle.getType().getId(),network.getLinks().get(((LinkEnterEvent) event).getLinkId() ),event.getTime() ); - if(toll > 0.) System.out.println("bing: vehicle " + carrierVehicle.getId() + " paid toll " + toll + "" ); + if(toll > 0.) System.out.println("bing: vehicle " + carrierVehicle.getId() + " paid toll " + toll ); score += (-1) * toll; } } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java index 4293663dd7a..069acc42f38 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java @@ -418,7 +418,7 @@ void createVehicleRoutingProblemBuilderWithServices_isMadeCorrectly() { assertEquals("i(6,0)", vehicle.getStartLocation().getId()); assertEquals(10.0, vehicle.getEarliestDeparture(), 0.0); assertEquals(20.0, vehicle.getLatestArrival(), 0.0); - assertEquals("matsimType", vehicle.getType().getTypeId().toString()); + assertEquals("matsimType", vehicle.getType().getTypeId()); assertEquals(10.0, vehicle.getType().getVehicleCostParams().perDistanceUnit, 0.0); assertEquals(5.0, vehicle.getType().getVehicleCostParams().perTransportTimeUnit, 0.0); assertEquals(100.0, vehicle.getType().getVehicleCostParams().fix, 0.0); @@ -435,7 +435,7 @@ void createVehicleRoutingProblemBuilderWithServices_isMadeCorrectly() { Service service1 = (Service) jobS1; assertEquals(20, service1.getSize().get(0)); assertEquals(10.0, service1.getServiceDuration(), 0.0); - assertEquals("i(7,4)R", service1.getLocation().getId().toString()); + assertEquals("i(7,4)R", service1.getLocation().getId()); Job jobS2 = vrp.getJobs().get("serviceId2"); assertNotNull(jobS2); @@ -445,7 +445,7 @@ void createVehicleRoutingProblemBuilderWithServices_isMadeCorrectly() { Service service2 = (Service) jobS2; assertEquals(10, service2.getSize().get(0)); assertEquals(20.0, service2.getServiceDuration(), 0.0); - assertEquals("i(3,9)", service2.getLocation().getId().toString()); + assertEquals("i(3,9)", service2.getLocation().getId()); } // @Disabled //Set to ignore due to not implemented functionality of Shipments in MatsimJspritFactory @@ -466,7 +466,7 @@ void createVehicleRoutingProblemBuilderWithShipments_isMadeCorrectly() { assertEquals("i(6,0)", vehicle.getStartLocation().getId()); assertEquals(10.0, vehicle.getEarliestDeparture(), 0.0); assertEquals(20.0, vehicle.getLatestArrival(), 0.0); - assertEquals("matsimType", vehicle.getType().getTypeId().toString()); + assertEquals("matsimType", vehicle.getType().getTypeId()); assertEquals(10.0, vehicle.getType().getVehicleCostParams().perDistanceUnit, 0.0); assertEquals(5.0, vehicle.getType().getVehicleCostParams().perTransportTimeUnit, 0.0); assertEquals(100.0, vehicle.getType().getVehicleCostParams().fix, 0.0); @@ -498,7 +498,7 @@ void createVehicleRoutingProblemBuilderWithShipments_isMadeCorrectly() { assertInstanceOf(Shipment.class, jobS2); Shipment shipment2 = (Shipment) jobS2; assertEquals(20, shipment2.getSize().get(0)); - assertEquals("i(3,9)", shipment2.getDeliveryLocation().getId().toString()); + assertEquals("i(3,9)", shipment2.getDeliveryLocation().getId()); } private Carrier createCarrierWithServices() { From bbb1919f8ae3442d23a9c3c496948cf592edb78b Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:28:21 +0200 Subject: [PATCH 043/101] remove redundant casts --- .../matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java | 4 ++-- .../matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java | 4 ++-- .../matsim/freight/carriers/CarrierVehicleTypeReaderTest.java | 2 +- .../matsim/freight/carriers/jsprit/MatsimTransformerTest.java | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java index d3703c241e9..b6eda515ede 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java @@ -151,10 +151,10 @@ void test_CarrierHasAttributes(){ void test_ServicesAndShipmentsHaveAttributes(){ Object serviceCustomerAtt = testCarrier.getServices().get(Id.create("serv1",CarrierService.class)).getAttributes().getAttribute("customer"); assertNotNull(serviceCustomerAtt); - assertEquals("someRandomCustomer", (String) serviceCustomerAtt); + assertEquals("someRandomCustomer", serviceCustomerAtt); Object shipmentCustomerAtt = testCarrier.getShipments().get(Id.create("s1",CarrierShipment.class)).getAttributes().getAttribute("customer"); assertNotNull(shipmentCustomerAtt); - assertEquals("someRandomCustomer", (String) shipmentCustomerAtt); + assertEquals("someRandomCustomer", shipmentCustomerAtt); } } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java index 4f7eb5773c9..6f812da91d3 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java @@ -175,10 +175,10 @@ void test_CarrierHasAttributes(){ void test_ServicesAndShipmentsHaveAttributes(){ Object serviceCustomerAtt = testCarrier.getServices().get(Id.create("serv1",CarrierService.class)).getAttributes().getAttribute("customer"); assertNotNull(serviceCustomerAtt); - assertEquals("someRandomCustomer", (String) serviceCustomerAtt); + assertEquals("someRandomCustomer", serviceCustomerAtt); Object shipmentCustomerAtt = testCarrier.getShipments().get(Id.create("s1",CarrierShipment.class)).getAttributes().getAttribute("customer"); assertNotNull(shipmentCustomerAtt); - assertEquals("someRandomCustomer", (String) shipmentCustomerAtt); + assertEquals("someRandomCustomer", shipmentCustomerAtt); } @Test diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest.java index 2fe9b82dc26..3320fd5fcee 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest.java @@ -69,7 +69,7 @@ void test_whenReadingTypeMedium_itReadsDescriptionCorrectly(){ @Test void test_whenReadingTypeMedium_itReadsCapacityCorrectly(){ VehicleType medium = types.getVehicleTypes().get(Id.create("medium", org.matsim.vehicles.VehicleType.class ) ); - assertEquals(30., (double) medium.getCapacity().getOther(), Double.MIN_VALUE ); + assertEquals(30., medium.getCapacity().getOther(), Double.MIN_VALUE ); } @Test diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java index 069acc42f38..75b4f468da9 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java @@ -63,7 +63,7 @@ void whenTransforming_jSpritType2matsimType_itIsMadeCorrectly() { VehicleType matsimType = MatsimJspritFactory.createMatsimVehicleType(jspritType); assertNotNull(matsimType); assertEquals("myType", matsimType.getId().toString()); - assertEquals(50., (double) matsimType.getCapacity().getWeightInTons(), Double.MIN_VALUE); + assertEquals(50., matsimType.getCapacity().getWeightInTons(), Double.MIN_VALUE); assertEquals(10.0, matsimType.getCostInformation().getCostsPerMeter(), 0.01); assertEquals(5.0, matsimType.getCostInformation().getCostsPerSecond(), 0.01); assertEquals(100.0, matsimType.getCostInformation().getFixedCosts(), 0.01); From bc5fda2c3af7ab5610bfacf33116d0253a1ca0f2 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:29:51 +0200 Subject: [PATCH 044/101] code style update --- .../java/org/matsim/freight/carriers/CarriersUtils.java | 8 ++++---- .../freight/carriers/controler/CarrierDriverAgent.java | 2 +- .../freight/carriers/jsprit/DistanceConstraint.java | 2 +- .../freight/carriers/CarrierVehicleTypeReaderTest.java | 2 +- .../freight/carriers/utils/CarrierControlerUtilsIT.java | 4 ++-- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java index 143b5e20e22..de88f529862 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java @@ -236,10 +236,10 @@ public static Carriers createShipmentVRPCarrierFromServiceVRPSolution(Carriers c Carriers carriersWithShipments = new Carriers(); for (Carrier carrier : carriers.getCarriers().values()) { Carrier carrierWS = createCarrier(carrier.getId()); - if (carrier.getShipments().size() > 0) { + if (!carrier.getShipments().isEmpty()) { copyShipments(carrierWS, carrier); } - if (carrier.getServices().size() > 0) { + if (!carrier.getServices().isEmpty()) { createShipmentsFromServices(carrierWS, carrier); } carrierWS.setCarrierCapabilities(carrier.getCarrierCapabilities()); // vehicles and other carrierCapabilities @@ -512,7 +512,7 @@ private static void addSkill(Attributes attributes, String skill) { List skills = convertSkillsAttributeToList(attributes); if (!skills.contains(skill)) { String skillString; - if (skills.size() == 0) { + if (skills.isEmpty()) { skillString = skill; } else { skillString = attributes.getAttribute(ATTR_SKILLS) + "," + skill; @@ -555,7 +555,7 @@ private static List convertSkillsAttributeToList(Attributes attributes) } private static void setSkills(Attributes attributes, Set skills) { - if (skills.size() != 0) { + if (!skills.isEmpty()) { Iterator skillIterator = skills.iterator(); StringBuilder skillString = new StringBuilder(skillIterator.next()); while (skillIterator.hasNext()) { diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java index 7ee36e067a7..bc064a564f8 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java @@ -119,7 +119,7 @@ private void handleEvent( PersonArrivalEvent event ){ currentRoute = null; } else{ Id startLink; - if( currentRoute.size() != 0 ){ + if(!currentRoute.isEmpty()){ startLink = currentRoute.get( 0 ); } else{ startLink = event.getLinkId(); diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceConstraint.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceConstraint.java index 0d6c4725b97..904f329d034 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceConstraint.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceConstraint.java @@ -258,7 +258,7 @@ private double findMinimalAdditionalDistance(JobInsertionContext context, TourAc } // checks the distance if the delivery is the last activity before the end of // the tour - if (route.getTourActivities().getActivities().size() > 0) { + if (!route.getTourActivities().getActivities().isEmpty()) { TourActivity activityLastDelivery = route.getTourActivities().getActivities() .get(route.getTourActivities().getActivities().size() - 1); TourActivity activityEnd = route.getEnd(); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest.java index 3320fd5fcee..3a2f5a5648e 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest.java @@ -104,7 +104,7 @@ void readV2andWriteV2() { log.info("") ; log.info("now starting for real") ; log.info("") ; - String inFilename1 = utils.getClassInputDirectory() + "vehicleTypes_v2.xml";; + String inFilename1 = utils.getClassInputDirectory() + "vehicleTypes_v2.xml"; CarrierVehicleTypes types1 = new CarrierVehicleTypes(); new CarrierVehicleTypeReader( types1 ).readFile( inFilename1 ); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsIT.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsIT.java index a50b4c5430d..4b86789a97a 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsIT.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsIT.java @@ -87,8 +87,8 @@ public void setUp() { //Create vehicle for Carriers final Id vehTypeId = Id.create( "gridType", VehicleType.class ); - VehicleType carrierVehType = VehicleUtils.getFactory().createVehicleType( vehTypeId );; - EngineInformation engineInformation = carrierVehType.getEngineInformation() ; + VehicleType carrierVehType = VehicleUtils.getFactory().createVehicleType( vehTypeId ); + EngineInformation engineInformation = carrierVehType.getEngineInformation() ; engineInformation.setFuelType( FuelType.diesel ); engineInformation.setFuelConsumption( 0.015 ); VehicleCapacity capacity = carrierVehType.getCapacity() ; From 2814bc9186b950643be480823488a754eb945c09 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:30:40 +0200 Subject: [PATCH 045/101] cleanup imports --- .../org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java | 2 -- .../freight/carriers/utils/CarrierControlerUtilsTest.java | 1 - 2 files changed, 3 deletions(-) diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java index 59f8416f6a2..71d69e6d216 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java @@ -26,8 +26,6 @@ import org.matsim.freight.carriers.*; import org.matsim.testcases.MatsimTestUtils; -import java.io.FileNotFoundException; -import java.io.IOException; import java.util.Collections; public class CarrierReadWriteV2_1Test { diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsTest.java index 30ae050e289..ba52b1cfd00 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsTest.java @@ -58,7 +58,6 @@ import java.net.URL; import java.util.Collection; -import java.util.concurrent.ExecutionException; public class CarrierControlerUtilsTest { From 00beceb2408b12857654cfcf4585c7fdb65c4f3c Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:31:55 +0200 Subject: [PATCH 046/101] Java language: Replace explicit type with <> --- .../carriers/CarrierPlanXmlWriterV2Test.java | 10 +++++----- .../carriers/CarrierPlanXmlWriterV2_1Test.java | 16 ++++++++-------- .../carriers/jsprit/MatsimTransformerTest.java | 4 ++-- .../DistanceScoringFunctionFactoryForTests.java | 2 +- .../mobsim/ScoringFunctionFactoryForTests.java | 2 +- 5 files changed, 17 insertions(+), 17 deletions(-) diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java index b6eda515ede..ded1c47ee6f 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java @@ -104,7 +104,7 @@ void test_whenReadingCarrier_itSelectsPlansCorrectly(){ @Test void test_whenReadingPlans_nuOfToursIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); assertEquals(1, plans.get(0).getScheduledTours().size()); assertEquals(1, plans.get(1).getScheduledTours().size()); assertEquals(1, plans.get(2).getScheduledTours().size()); @@ -112,7 +112,7 @@ void test_whenReadingPlans_nuOfToursIsCorrect(){ @Test void test_whenReadingToursOfPlan1_nuOfActivitiesIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan1 = plans.get(0); ScheduledTour tour1 = plan1.getScheduledTours().iterator().next(); assertEquals(5,tour1.getTour().getTourElements().size()); @@ -120,7 +120,7 @@ void test_whenReadingToursOfPlan1_nuOfActivitiesIsCorrect(){ @Test void test_whenReadingToursOfPlan2_nuOfActivitiesIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan2 = plans.get(1); ScheduledTour tour1 = plan2.getScheduledTours().iterator().next(); assertEquals(9,tour1.getTour().getTourElements().size()); @@ -128,7 +128,7 @@ void test_whenReadingToursOfPlan2_nuOfActivitiesIsCorrect(){ @Test void test_whenReadingToursOfPlan3_nuOfActivitiesIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan3 = plans.get(2); ScheduledTour tour1 = plan3.getScheduledTours().iterator().next(); assertEquals(9,tour1.getTour().getTourElements().size()); @@ -136,7 +136,7 @@ void test_whenReadingToursOfPlan3_nuOfActivitiesIsCorrect(){ private boolean exactlyTheseVehiclesAreInVehicleCollection(List> asList, Collection carrierVehicles) { - List vehicles = new ArrayList(carrierVehicles); + List vehicles = new ArrayList<>(carrierVehicles); for(CarrierVehicle type : carrierVehicles) if(asList.contains(type.getId() )) vehicles.remove(type ); return vehicles.isEmpty(); } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java index 6f812da91d3..8b677f9d2d6 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java @@ -104,7 +104,7 @@ void test_whenReadingCarrier_itSelectsPlansCorrectly(){ @Test void test_whenReadingPlans_nuOfToursIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); assertEquals(1, plans.get(0).getScheduledTours().size()); assertEquals(1, plans.get(1).getScheduledTours().size()); assertEquals(1, plans.get(2).getScheduledTours().size()); @@ -112,7 +112,7 @@ void test_whenReadingPlans_nuOfToursIsCorrect(){ @Test void test_whenReadingToursOfPlan1_nuOfActivitiesIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan1 = plans.get(0); ScheduledTour tour1 = plan1.getScheduledTours().iterator().next(); assertEquals(5,tour1.getTour().getTourElements().size()); @@ -120,7 +120,7 @@ void test_whenReadingToursOfPlan1_nuOfActivitiesIsCorrect(){ @Test void test_whenReadingToursOfPlan2_nuOfActivitiesIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan2 = plans.get(1); ScheduledTour tour1 = plan2.getScheduledTours().iterator().next(); assertEquals(9,tour1.getTour().getTourElements().size()); @@ -128,7 +128,7 @@ void test_whenReadingToursOfPlan2_nuOfActivitiesIsCorrect(){ @Test void test_whenReadingToursOfPlan3_nuOfActivitiesIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan3 = plans.get(2); ScheduledTour tour1 = plan3.getScheduledTours().iterator().next(); assertEquals(9,tour1.getTour().getTourElements().size()); @@ -136,7 +136,7 @@ void test_whenReadingToursOfPlan3_nuOfActivitiesIsCorrect(){ @Test void test_whenReadingToursOfPlan1_SpritScoreIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan1 = plans.get(0); plan1.getAttributes().getAttribute("jspritScore"); assertEquals(Double.NaN, CarriersUtils.getJspritScore(plan1), testUtils.EPSILON); @@ -144,7 +144,7 @@ void test_whenReadingToursOfPlan1_SpritScoreIsCorrect(){ @Test void test_whenReadingToursOfPlan2_jSpritScoreIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan2 = plans.get(1); plan2.getAttributes().getAttribute("jspritScore"); assertEquals(80.0, CarriersUtils.getJspritScore(plan2), testUtils.EPSILON); @@ -152,7 +152,7 @@ void test_whenReadingToursOfPlan2_jSpritScoreIsCorrect(){ @Test void test_whenReadingToursOfPlan3_jSpritIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan3 = plans.get(2); plan3.getAttributes().getAttribute("jspritScore"); assertEquals(105.0, CarriersUtils.getJspritScore(plan3), testUtils.EPSILON); @@ -160,7 +160,7 @@ void test_whenReadingToursOfPlan3_jSpritIsCorrect(){ private boolean exactlyTheseVehiclesAreInVehicleCollection(List> asList, Collection carrierVehicles) { - List vehicles = new ArrayList(carrierVehicles); + List vehicles = new ArrayList<>(carrierVehicles); for(CarrierVehicle type : carrierVehicles) if(asList.contains(type.getId() )) vehicles.remove(type ); return vehicles.isEmpty(); } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java index 75b4f468da9..1d1e888ee7e 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java @@ -228,7 +228,7 @@ private VehicleRoutingProblem getVehicleRoutingProblem(ScheduledTour sTour) { } private Collection getJobsFrom(ScheduledTour sTour) { - Collection services = new ArrayList(); + Collection services = new ArrayList<>(); for (Tour.TourElement e : sTour.getTour().getTourElements()) { if (e instanceof Tour.TourActivity) { if (e instanceof Tour.ServiceActivity) { @@ -308,7 +308,7 @@ void whenTransforming_matsimScheduledTourWithServiceAct2vehicleRoute_secondActId @Test void whenTransforming_matsimPlan2vehicleRouteSolution_itIsMadeCorrectly() { - List sTours = new ArrayList(); + List sTours = new ArrayList<>(); ScheduledTour matsimTour = getMatsimTour("matsimVehicle"); sTours.add(matsimTour); ScheduledTour matsimTour1 = getMatsimTour("matsimVehicle1"); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java index 685873ba8e0..692721d41bd 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java @@ -62,7 +62,7 @@ public DriverLegScoring(Carrier carrier, Network network) { super(); this.network = network; this.carrier = carrier; - employedVehicles = new HashSet(); + employedVehicles = new HashSet<>(); } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java index 9f20c3189bf..0d5ef7f3df3 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java @@ -61,7 +61,7 @@ public DriverLegScoring(Carrier carrier, Network network) { super(); this.network = network; this.carrier = carrier; - employedVehicles = new HashSet(); + employedVehicles = new HashSet<>(); } From 93e62941d40f13a583d02a2c2c7afaa2b577eab7 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:32:51 +0200 Subject: [PATCH 047/101] Java language: use computeIfAbsent --- .../freight/carriers/usecases/analysis/LegHistogram.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/LegHistogram.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/LegHistogram.java index 1db193121ec..fff393eee93 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/LegHistogram.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/LegHistogram.java @@ -391,11 +391,8 @@ private int getBinIndex(final double time) { } private ModeData getDataForMode(final String legMode) { - ModeData modeData = this.data.get(legMode); - if (modeData == null) { - modeData = new ModeData(this.nofBins + 1); // +1 for all times out of our range - this.data.put(legMode, modeData); - } + // +1 for all times out of our range + ModeData modeData = this.data.computeIfAbsent(legMode, k -> new ModeData(this.nofBins + 1)); return modeData; } From b5d767f33c0fc68085288461b417081538e5dd07 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:35:53 +0200 Subject: [PATCH 048/101] Java language: use Double.hashCode(...) --- .../main/java/org/matsim/freight/carriers/TimeWindow.java | 6 ++---- .../freight/carriers/jsprit/NetworkBasedTransportCosts.java | 4 +--- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/TimeWindow.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/TimeWindow.java index 167dc424028..8c5e9fc0d25 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/TimeWindow.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/TimeWindow.java @@ -96,11 +96,9 @@ public boolean equals(Object o){ @Override public int hashCode(){ int result = 59; - long startLong = Double.doubleToLongBits(start); - int startHash = (int) (startLong^(startLong>>>32)); + int startHash = Double.hashCode(start); result = 31 * result + startHash; - long endLong = Double.doubleToLongBits(end); - int endHash = (int) (endLong^(endLong>>>32)); + int endHash = Double.hashCode(end); result = 31 * result + endHash; return result; } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCosts.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCosts.java index 6ae0c93d705..f332b84cb0b 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCosts.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCosts.java @@ -191,9 +191,7 @@ public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((from == null) ? 0 : from.hashCode()); - long temp; - temp = Double.doubleToLongBits(time); - result = prime * result + (int) (temp ^ (temp >>> 32)); + result = prime * result + Double.hashCode(time); result = prime * result + ((to == null) ? 0 : to.hashCode()); result = prime * result + ((vehicleType == null) ? 0 : vehicleType.hashCode()); return result; From 3c964b0a15978956b891480347824b0dc4825ab5 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:37:05 +0200 Subject: [PATCH 049/101] Java language: replace if by switch --- .../controler/CarrierDriverAgent.java | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java index bc064a564f8..21f4f131c36 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java @@ -91,18 +91,13 @@ final class CarrierDriverAgent{ void handleAnEvent(Event event){ // the event comes to here from CarrierAgent#handleEvent only for events concerning this driver - if( event instanceof PersonArrivalEvent ){ - handleEvent( (PersonArrivalEvent) event); - } else if( event instanceof PersonDepartureEvent ){ - handleEvent( (PersonDepartureEvent) event ); - } else if( event instanceof LinkEnterEvent ){ - handleEvent( (LinkEnterEvent) event ); - } else if( event instanceof ActivityEndEvent ){ - handleEvent( (ActivityEndEvent) event ); - } else if( event instanceof ActivityStartEvent ){ - handleEvent( (ActivityStartEvent) event ); - } else{ - createAdditionalEvents( event, null, scheduledTour, driverId, planElementCounter); + switch (event) { + case PersonArrivalEvent personArrivalEvent -> handleEvent(personArrivalEvent); + case PersonDepartureEvent personDepartureEvent -> handleEvent(personDepartureEvent); + case LinkEnterEvent linkEnterEvent -> handleEvent(linkEnterEvent); + case ActivityEndEvent activityEndEvent -> handleEvent(activityEndEvent); + case ActivityStartEvent activityStartEvent -> handleEvent(activityStartEvent); + case null, default -> createAdditionalEvents(event, null, scheduledTour, driverId, planElementCounter); } } From 967e0e84590a80ceb2c33a73c8308eef6d32965c Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:38:42 +0200 Subject: [PATCH 050/101] Java language: avoid raw use --- .../matsim/freight/carriers/jsprit/MatsimJspritFactory.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java index eae8060dde6..8710e50c7ba 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java @@ -32,6 +32,7 @@ import com.graphhopper.jsprit.core.problem.cost.VehicleRoutingActivityCosts; import com.graphhopper.jsprit.core.problem.cost.VehicleRoutingTransportCosts; import com.graphhopper.jsprit.core.problem.job.Service; +import com.graphhopper.jsprit.core.problem.job.Service.Builder; import com.graphhopper.jsprit.core.problem.job.Shipment; import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution; import com.graphhopper.jsprit.core.problem.solution.route.VehicleRoute; @@ -164,7 +165,7 @@ static Service createJspritService(CarrierService carrierService, Coord location } Location location = locationBuilder.build(); - Service.Builder serviceBuilder = Service.Builder.newInstance(carrierService.getId().toString()); + Builder serviceBuilder = Builder.newInstance(carrierService.getId().toString()); serviceBuilder.addSizeDimension(0, carrierService.getCapacityDemand()); serviceBuilder.setLocation(location).setServiceTime(carrierService.getServiceDuration()) .setTimeWindow(com.graphhopper.jsprit.core.problem.solution.route.activity.TimeWindow.newInstance( From 87e7f9993ec0a4567fd487402747aa3e19188d12 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:39:12 +0200 Subject: [PATCH 051/101] Java language: use text block --- .../FreightCarriersConfigGroupTest.java | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/FreightCarriersConfigGroupTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/FreightCarriersConfigGroupTest.java index 6113348707b..33a4d6736e8 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/FreightCarriersConfigGroupTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/FreightCarriersConfigGroupTest.java @@ -55,17 +55,18 @@ void test_configXmlCanBeParsed() { FreightCarriersConfigGroup freight = new FreightCarriersConfigGroup(); Config config = ConfigUtils.createConfig(freight); - String xml = "\n" + - "\n" + - "\n" + - " \t\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; + String xml = """ + + + + \t + + + + + + + """; InputStream is = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); From 6a1cc65d8f5176dc6b89c81846302a0f01308c92 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:39:57 +0200 Subject: [PATCH 052/101] Java language: use pattern variable --- ...DistanceConstraintFromVehiclesFileTest.java | 12 ++++-------- .../jsprit/DistanceConstraintTest.java | 18 ++++++------------ ...DistanceScoringFunctionFactoryForTests.java | 3 +-- .../mobsim/ScoringFunctionFactoryForTests.java | 3 +-- .../TimeScoringFunctionFactoryForTests.java | 3 +-- 5 files changed, 13 insertions(+), 26 deletions(-) diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintFromVehiclesFileTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintFromVehiclesFileTest.java index d7329adc924..43abc654497 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintFromVehiclesFileTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintFromVehiclesFileTest.java @@ -136,8 +136,7 @@ final void CarrierSmallBatteryTest_Version1() throws ExecutionException, Interru List elements = carrierV1.getSelectedPlan().getScheduledTours().iterator().next().getTour() .getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); @@ -214,8 +213,7 @@ final void CarrierLargeBatteryTest_Version2() throws ExecutionException, Interru List elements = carrierV2.getSelectedPlan().getScheduledTours().iterator().next().getTour() .getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); @@ -293,8 +291,7 @@ final void Carrier2SmallBatteryTest_Version3() throws ExecutionException, Interr double distanceTour = 0.0; List elements = scheduledTour.getTour().getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); @@ -380,8 +377,7 @@ final void CarrierWithAdditionalDieselVehicleTest_Version4() throws ExecutionExc double distanceTour = 0.0; List elements = scheduledTour.getTour().getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintTest.java index a14b562fa6d..50b8505cb70 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintTest.java @@ -143,8 +143,7 @@ final void CarrierSmallBatteryTest_Version1() throws ExecutionException, Interru List elements = carrierV1.getSelectedPlan().getScheduledTours().iterator().next().getTour() .getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); @@ -227,8 +226,7 @@ final void CarrierLargeBatteryTest_Version2() throws ExecutionException, Interru List elements = carrierV2.getSelectedPlan().getScheduledTours().iterator().next().getTour() .getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); @@ -315,8 +313,7 @@ final void Carrier2SmallBatteryTest_Version3() throws ExecutionException, Interr double distanceTour = 0.0; List elements = scheduledTour.getTour().getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); @@ -415,8 +412,7 @@ final void CarrierWithAdditionalDieselVehicleTest_Version4() throws ExecutionExc double distanceTour = 0.0; List elements = scheduledTour.getTour().getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); @@ -499,8 +495,7 @@ final void CarrierWithShipmentsMidSizeBatteryTest_Version5() throws ExecutionExc double distanceTour = 0.0; List elements = scheduledTour.getTour().getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); @@ -581,8 +576,7 @@ final void CarrierWithShipmentsLargeBatteryTest_Version6() throws ExecutionExcep double distanceTour = 0.0; List elements = scheduledTour.getTour().getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java index 692721d41bd..81ad7c6e577 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java @@ -94,8 +94,7 @@ public void startLeg(double time, Leg leg) { @Override public void endLeg(double time) { - if(currentLeg.getRoute() instanceof NetworkRoute){ - NetworkRoute nRoute = (NetworkRoute) currentLeg.getRoute(); + if(currentLeg.getRoute() instanceof NetworkRoute nRoute){ Id vehicleId = nRoute.getVehicleId(); CarrierVehicle vehicle = CarriersUtils.getCarrierVehicle(carrier, vehicleId); Gbl.assertNotNull(vehicle); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java index 0d5ef7f3df3..68dbf0bc7ab 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java @@ -93,8 +93,7 @@ public void startLeg(double time, Leg leg) { @Override public void endLeg(double time) { - if(currentLeg.getRoute() instanceof NetworkRoute){ - NetworkRoute nRoute = (NetworkRoute) currentLeg.getRoute(); + if(currentLeg.getRoute() instanceof NetworkRoute nRoute){ Id vehicleId = nRoute.getVehicleId(); CarrierVehicle vehicle = CarriersUtils.getCarrierVehicle(carrier, vehicleId); Gbl.assertNotNull(vehicle); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/TimeScoringFunctionFactoryForTests.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/TimeScoringFunctionFactoryForTests.java index 65bd9951299..a8cc127ba93 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/TimeScoringFunctionFactoryForTests.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/TimeScoringFunctionFactoryForTests.java @@ -94,8 +94,7 @@ public void startLeg(double time, Leg leg) { @Override public void endLeg(double time) { - if(currentLeg.getRoute() instanceof NetworkRoute){ - NetworkRoute nRoute = (NetworkRoute) currentLeg.getRoute(); + if(currentLeg.getRoute() instanceof NetworkRoute nRoute){ Id vehicleId = nRoute.getVehicleId(); CarrierVehicle vehicle = CarriersUtils.getCarrierVehicle(carrier, vehicleId); assert vehicle != null : "cannot find vehicle with id=" + vehicleId; From 128b9aab4c1ee558e166c45915f80236c880d0a3 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:41:47 +0200 Subject: [PATCH 053/101] Java language: use add/getFirst() --- .../org/matsim/freight/carriers/Tour.java | 4 ++-- .../controler/CarrierDriverAgent.java | 2 +- .../carriers/jsprit/DistanceConstraint.java | 20 +++++++++---------- .../carriers/CarrierPlanReaderV1Test.java | 2 +- .../carriers/CarrierPlanXmlReaderV2Test.java | 2 +- .../CarrierPlanXmlReaderV2WithDtdTest.java | 2 +- .../carriers/CarrierPlanXmlWriterV2Test.java | 2 +- .../CarrierPlanXmlWriterV2_1Test.java | 4 ++-- .../jsprit/MatsimTransformerTest.java | 2 +- 9 files changed, 20 insertions(+), 20 deletions(-) diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/Tour.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/Tour.java index a6161bd2d11..cb522e857fb 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/Tour.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/Tour.java @@ -163,7 +163,7 @@ public Leg createLeg(Route route, double dep_time, double transportTime) { @Deprecated public Builder insertLegAtBeginning(Leg leg) { Gbl.assertNotNull(leg); - tourElements.add(0,leg); + tourElements.addFirst(leg); return this; } @@ -183,7 +183,7 @@ public Builder schedulePickupAtBeginning(CarrierShipment shipment) { } // assertLastElementIsLeg(); Pickup pickup = createPickup(shipment); - tourElements.add(0, pickup); + tourElements.addFirst(pickup); // previousElementIsActivity = true; return this; } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java index 21f4f131c36..00233bbbf18 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java @@ -115,7 +115,7 @@ private void handleEvent( PersonArrivalEvent event ){ } else{ Id startLink; if(!currentRoute.isEmpty()){ - startLink = currentRoute.get( 0 ); + startLink = currentRoute.getFirst(); } else{ startLink = event.getLinkId(); } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceConstraint.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceConstraint.java index 904f329d034..068c70506cd 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceConstraint.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceConstraint.java @@ -142,14 +142,14 @@ private double calculateRouteDistanceWithAssociatedPickup(JobInsertionContext co if (positionOfRelatedPickup == 0 && context.getRoute().getActivities().isEmpty()) { context.getRoute().getStart().setLocation(context.getNewVehicle().getStartLocation()); context.getRoute().getEnd().setLocation(context.getNewVehicle().getEndLocation()); - routeDistance = getDistance(context.getAssociatedActivities().get(0), context.getRoute().getEnd(), + routeDistance = getDistance(context.getAssociatedActivities().getFirst(), context.getRoute().getEnd(), context.getNewVehicle(), context.getNewDepTime()); return routeDistance; } else if (positionOfRelatedPickup == 0 && !context.getRoute().getActivities().isEmpty()) { - routeDistance = getDistance(context.getAssociatedActivities().get(0), - context.getRoute().getActivities().get(0), context.getNewVehicle(), context.getNewDepTime()); + routeDistance = getDistance(context.getAssociatedActivities().getFirst(), + context.getRoute().getActivities().getFirst(), context.getNewVehicle(), context.getNewDepTime()); } else { - routeDistance = getDistance(context.getRoute().getStart(), context.getRoute().getActivities().get(0), + routeDistance = getDistance(context.getRoute().getStart(), context.getRoute().getActivities().getFirst(), context.getNewVehicle(), context.getNewDepTime()); } // adds distances between every tour activity and adds the associated pickup on @@ -157,8 +157,8 @@ private double calculateRouteDistanceWithAssociatedPickup(JobInsertionContext co while (context.getRoute().getTourActivities().getActivities().size() > (nextRouteActivity + 1)) { if (positionOfRelatedPickup == (nextRouteActivity + 1) && positionOfRelatedPickup != 0) { routeDistance = routeDistance + getDistance(context.getRoute().getActivities().get(nextRouteActivity), - context.getAssociatedActivities().get(0), context.getNewVehicle()); - routeDistance = routeDistance + getDistance(context.getAssociatedActivities().get(0), + context.getAssociatedActivities().getFirst(), context.getNewVehicle()); + routeDistance = routeDistance + getDistance(context.getAssociatedActivities().getFirst(), context.getRoute().getActivities().get(nextRouteActivity), context.getNewVehicle()); } else { routeDistance = routeDistance + getDistance(context.getRoute().getActivities().get(nextRouteActivity), @@ -168,8 +168,8 @@ private double calculateRouteDistanceWithAssociatedPickup(JobInsertionContext co } if (positionOfRelatedPickup == context.getRoute().getActivities().size()) { routeDistance = routeDistance + getDistance(context.getRoute().getActivities().get(nextRouteActivity), - context.getAssociatedActivities().get(0), context.getNewVehicle()); - routeDistance = routeDistance + getDistance(context.getAssociatedActivities().get(0), + context.getAssociatedActivities().getFirst(), context.getNewVehicle()); + routeDistance = routeDistance + getDistance(context.getAssociatedActivities().getFirst(), context.getRoute().getEnd(), context.getNewVehicle()); } else routeDistance = routeDistance + getDistance(context.getRoute().getActivities().get(nextRouteActivity), @@ -189,7 +189,7 @@ private double calculateRouteDistance(JobInsertionContext context, Vehicle newVe return realRouteDistance; int n = 0; realRouteDistance = getDistance(context.getRoute().getStart(), - context.getRoute().getTourActivities().getActivities().get(0), newVehicle); + context.getRoute().getTourActivities().getActivities().getFirst(), newVehicle); while (context.getRoute().getTourActivities().getActivities().size() > (n + 1)) { realRouteDistance = realRouteDistance + getDistance(context.getRoute().getTourActivities().getActivities().get(n), @@ -260,7 +260,7 @@ private double findMinimalAdditionalDistance(JobInsertionContext context, TourAc // the tour if (!route.getTourActivities().getActivities().isEmpty()) { TourActivity activityLastDelivery = route.getTourActivities().getActivities() - .get(route.getTourActivities().getActivities().size() - 1); + .getLast(); TourActivity activityEnd = route.getEnd(); double possibleAdditionalDistance = getDistance(activityLastDelivery, assignedDelivery, newVehicle) + getDistance(assignedDelivery, activityEnd, newVehicle) diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanReaderV1Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanReaderV1Test.java index 1be22630df2..38749fbabdf 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanReaderV1Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanReaderV1Test.java @@ -70,7 +70,7 @@ void testReaderReadsCorrectly() { Carrier carrier = carriers.getCarriers().values().iterator().next(); Assertions.assertEquals(1, carrier.getSelectedPlan().getScheduledTours().size()); Leg leg = (Leg) carrier.getSelectedPlan().getScheduledTours() - .iterator().next().getTour().getTourElements().get(0); + .iterator().next().getTour().getTourElements().getFirst(); NetworkRoute route = (NetworkRoute) leg.getRoute(); Assertions.assertEquals(3, route.getLinkIds().size()); Assertions.assertEquals("23", route.getStartLinkId().toString()); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test.java index db0e3008d20..0deffa73889 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test.java @@ -132,7 +132,7 @@ void test_whenReadingPlans_nuOfToursIsCorrect(){ @Test void test_whenReadingToursOfPlan1_nuOfActivitiesIsCorrect(){ List plans = new ArrayList<>(testCarrier.getPlans()); - CarrierPlan plan1 = plans.get(0); + CarrierPlan plan1 = plans.getFirst(); ScheduledTour tour1 = plan1.getScheduledTours().iterator().next(); Assertions.assertEquals(5,tour1.getTour().getTourElements().size()); } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest.java index cff37127033..fb12a37ff82 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest.java @@ -134,7 +134,7 @@ void test_whenReadingPlans_nuOfToursIsCorrect(){ @Disabled void test_whenReadingToursOfPlan1_nuOfActivitiesIsCorrect(){ List plans = new ArrayList<>(testCarrier.getPlans()); - CarrierPlan plan1 = plans.get(0); + CarrierPlan plan1 = plans.getFirst(); ScheduledTour tour1 = plan1.getScheduledTours().iterator().next(); Assertions.assertEquals(5,tour1.getTour().getTourElements().size()); } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java index ded1c47ee6f..46444ed07d3 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java @@ -113,7 +113,7 @@ void test_whenReadingPlans_nuOfToursIsCorrect(){ @Test void test_whenReadingToursOfPlan1_nuOfActivitiesIsCorrect(){ List plans = new ArrayList<>(testCarrier.getPlans()); - CarrierPlan plan1 = plans.get(0); + CarrierPlan plan1 = plans.getFirst(); ScheduledTour tour1 = plan1.getScheduledTours().iterator().next(); assertEquals(5,tour1.getTour().getTourElements().size()); } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java index 8b677f9d2d6..4ef1c22204e 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java @@ -113,7 +113,7 @@ void test_whenReadingPlans_nuOfToursIsCorrect(){ @Test void test_whenReadingToursOfPlan1_nuOfActivitiesIsCorrect(){ List plans = new ArrayList<>(testCarrier.getPlans()); - CarrierPlan plan1 = plans.get(0); + CarrierPlan plan1 = plans.getFirst(); ScheduledTour tour1 = plan1.getScheduledTours().iterator().next(); assertEquals(5,tour1.getTour().getTourElements().size()); } @@ -137,7 +137,7 @@ void test_whenReadingToursOfPlan3_nuOfActivitiesIsCorrect(){ @Test void test_whenReadingToursOfPlan1_SpritScoreIsCorrect(){ List plans = new ArrayList<>(testCarrier.getPlans()); - CarrierPlan plan1 = plans.get(0); + CarrierPlan plan1 = plans.getFirst(); plan1.getAttributes().getAttribute("jspritScore"); assertEquals(Double.NaN, CarriersUtils.getJspritScore(plan1), testUtils.EPSILON); } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java index 1d1e888ee7e..15f7a1a7c86 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java @@ -295,7 +295,7 @@ void whenTransforming_matsimScheduledTourWithServiceAct2vehicleRoute_firstActIdM ScheduledTour sTour = getMatsimServiceTour(); VehicleRoutingProblem vehicleRoutingProblem = getVehicleRoutingProblem(sTour); VehicleRoute route = MatsimJspritFactory.createRoute(sTour, vehicleRoutingProblem); - assertEquals("to1", route.getTourActivities().getActivities().get(0).getLocation().getId()); + assertEquals("to1", route.getTourActivities().getActivities().getFirst().getLocation().getId()); } @Test From ac78f5b49ee49a3c92e7eb30a20f8dccc1b39de7 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:43:48 +0200 Subject: [PATCH 054/101] Access to TestUtils.EPSILION --- .../freight/carriers/CarrierPlanXmlWriterV2_1Test.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java index 4ef1c22204e..e55f1d1aef7 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java @@ -139,7 +139,8 @@ void test_whenReadingToursOfPlan1_SpritScoreIsCorrect(){ List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan1 = plans.getFirst(); plan1.getAttributes().getAttribute("jspritScore"); - assertEquals(Double.NaN, CarriersUtils.getJspritScore(plan1), testUtils.EPSILON); + assertEquals(Double.NaN, CarriersUtils.getJspritScore(plan1), MatsimTestUtils.EPSILON); + assertEquals(Double.NaN, CarriersUtils.getJspritScore(plan1), MatsimTestUtils.EPSILON); } @Test @@ -147,7 +148,7 @@ void test_whenReadingToursOfPlan2_jSpritScoreIsCorrect(){ List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan2 = plans.get(1); plan2.getAttributes().getAttribute("jspritScore"); - assertEquals(80.0, CarriersUtils.getJspritScore(plan2), testUtils.EPSILON); + assertEquals(80.0, CarriersUtils.getJspritScore(plan2), MatsimTestUtils.EPSILON); } @Test @@ -155,7 +156,7 @@ void test_whenReadingToursOfPlan3_jSpritIsCorrect(){ List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan3 = plans.get(2); plan3.getAttributes().getAttribute("jspritScore"); - assertEquals(105.0, CarriersUtils.getJspritScore(plan3), testUtils.EPSILON); + assertEquals(105.0, CarriersUtils.getJspritScore(plan3), MatsimTestUtils.EPSILON); } From f59e4d698c527b6908735477fb45f311dbeb542d Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Tue, 16 Jul 2024 21:47:01 +0200 Subject: [PATCH 055/101] add not null assertion --- .../matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java index e55f1d1aef7..b3a12fdb60f 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java @@ -26,7 +26,6 @@ import org.junit.jupiter.api.extension.RegisterExtension; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.TransportMode; -import org.matsim.freight.carriers.*; import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.Vehicle; @@ -65,12 +64,15 @@ void test_whenReadingServices_nuOfServicesIsCorrect(){ void test_whenReadingCarrier_itReadsTypeIdsCorrectly(){ CarrierVehicle light = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("lightVehicle")); + assert light != null; assertEquals("light",light.getVehicleTypeId().toString()); CarrierVehicle medium = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("mediumVehicle")); + assert medium != null; assertEquals("medium",medium.getVehicleTypeId().toString()); CarrierVehicle heavy = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("heavyVehicle")); + assert heavy != null; assertEquals("heavy",heavy.getVehicleTypeId().toString()); } From af740e61e37e8e53875b99087b816ade330f904d Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Wed, 17 Jul 2024 13:35:39 +0200 Subject: [PATCH 056/101] remove one layer of "LSPs" --- .../main/resources/dtd/lspsDefinitions_v1.xsd | 230 +++++++++--------- 1 file changed, 112 insertions(+), 118 deletions(-) diff --git a/matsim/src/main/resources/dtd/lspsDefinitions_v1.xsd b/matsim/src/main/resources/dtd/lspsDefinitions_v1.xsd index a5a7d6ec747..32a03b4d072 100644 --- a/matsim/src/main/resources/dtd/lspsDefinitions_v1.xsd +++ b/matsim/src/main/resources/dtd/lspsDefinitions_v1.xsd @@ -7,129 +7,123 @@ - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 60368d2b9119f57a0fe493e7ca49231d209d0e9a Mon Sep 17 00:00:00 2001 From: nkuehnel Date: Fri, 19 Jul 2024 14:05:29 +0200 Subject: [PATCH 057/101] add prebooking support for drt shifts some minor shift cleanups possibility to assign requests to shifts that are assigned bot not started yet --- .../edrt/run/EDrtControlerCreator.java | 8 +- .../DrtOperationsControlerCreator.java | 21 +- .../EDrtOperationsControlerCreator.java | 18 +- .../EDrtAssignShiftToVehicleLogic.java | 6 +- .../dispatcher/EDrtShiftDispatcherImpl.java | 10 +- .../dispatcher/EDrtShiftStartLogic.java | 6 +- .../run/ShiftEDrtModeOptimizerQSimModule.java | 4 +- ...tayTask.java => EDrtWaitForShiftTask.java} | 10 +- .../schedule/ShiftEDrtActionCreator.java | 4 +- .../schedule/ShiftEDrtTaskFactoryImpl.java | 20 +- .../scheduler/EShiftTaskScheduler.java | 32 +- .../shifts/config/ShiftsParams.java | 14 +- .../dispatcher/DefaultShiftStartLogic.java | 6 +- .../dispatcher/DrtShiftDispatcherImpl.java | 37 +-- .../ShiftVehicleDataEntryFactory.java | 37 ++- .../ShiftInsertionCostCalculator.java | 17 +- .../shifts/run/ShiftDrtModeModule.java | 6 +- .../run/ShiftDrtModeOptimizerQSimModule.java | 4 +- .../schedule/ShiftDrtActionCreator.java | 2 +- .../ShiftDrtStayTaskEndTimeCalculator.java | 18 +- .../shifts/schedule/ShiftDrtTaskFactory.java | 4 +- .../schedule/ShiftDrtTaskFactoryImpl.java | 8 +- .../shifts/schedule/WaitForShiftStayTask.java | 29 -- .../shifts/schedule/WaitForShiftTask.java | 65 ++++ .../scheduler/ShiftDrtScheduleInquiry.java | 4 +- .../shifts/scheduler/ShiftTaskScheduler.java | 4 + .../scheduler/ShiftTaskSchedulerImpl.java | 32 +- .../run/RunPrebookingShiftDrtScenarioIT.java | 298 ++++++++++++++++++ .../contrib/drt/run/DrtControlerCreator.java | 17 +- 29 files changed, 590 insertions(+), 151 deletions(-) rename contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/{EDrtWaitForShiftStayTask.java => EDrtWaitForShiftTask.java} (69%) delete mode 100644 contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/WaitForShiftStayTask.java create mode 100644 contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/WaitForShiftTask.java create mode 100644 contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunPrebookingShiftDrtScenarioIT.java diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/run/EDrtControlerCreator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/run/EDrtControlerCreator.java index 1db60059c37..3d54738d88e 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/run/EDrtControlerCreator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/run/EDrtControlerCreator.java @@ -41,11 +41,13 @@ public class EDrtControlerCreator { public static Controler createControler(Config config, boolean otfvis) { - MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); - DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.scoring(), config.routing()); - Scenario scenario = DrtControlerCreator.createScenarioWithDrtRouteFactory(config); ScenarioUtils.loadScenario(scenario); + return createControler(config, scenario, otfvis); + } + public static Controler createControler(Config config, Scenario scenario, boolean otfvis) { + MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); + DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.scoring(), config.routing()); Controler controler = new Controler(scenario); controler.addOverridingModule(new MultiModeEDrtModule()); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtOperationsControlerCreator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtOperationsControlerCreator.java index 835cc77e9e2..ccc1576a348 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtOperationsControlerCreator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtOperationsControlerCreator.java @@ -1,5 +1,6 @@ package org.matsim.contrib.drt.extension.operations; +import org.matsim.api.core.v01.Scenario; import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilitiesModeModule; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilitiesQSimModule; @@ -27,10 +28,25 @@ public class DrtOperationsControlerCreator { * @return */ public static Controler createControler(Config config, boolean otfvis) { - MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); - Controler controler = DrtControlerCreator.createControler(config, otfvis); + return prepareController(config, controler); + } + + /** + * Creates a controller in one step. + * + * @param config + * @param scenario + * @param otfvis + * @return + */ + public static Controler createControler(Config config, Scenario scenario, boolean otfvis) { + Controler controler = DrtControlerCreator.createControler(config, scenario, otfvis); + return prepareController(config, controler); + } + private static Controler prepareController(Config config, Controler controler) { + MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); for (DrtConfigGroup drtCfg : multiModeDrtConfig.getModalElements()) { controler.addOverridingModule(new ShiftDrtModeModule(drtCfg)); controler.addOverridingQSimModule(new DrtModeQSimModule(drtCfg, new ShiftDrtModeOptimizerQSimModule(drtCfg))); @@ -40,7 +56,6 @@ public static Controler createControler(Config config, boolean otfvis) { } controler.configureQSimComponents(DvrpQSimComponents.activateAllModes(multiModeDrtConfig)); - return controler; } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/EDrtOperationsControlerCreator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/EDrtOperationsControlerCreator.java index da76f73772d..855cba7f143 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/EDrtOperationsControlerCreator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/EDrtOperationsControlerCreator.java @@ -1,5 +1,6 @@ package org.matsim.contrib.drt.extension.operations; +import org.matsim.api.core.v01.Scenario; import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.edrt.run.EDrtControlerCreator; import org.matsim.contrib.drt.extension.operations.eshifts.charging.ShiftOperatingVehicleProvider; @@ -24,11 +25,19 @@ public class EDrtOperationsControlerCreator { public static Controler createControler(Config config, boolean otfvis) { - - MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); - Controler controler = EDrtControlerCreator.createControler(config, otfvis); + prepareController(config, controler); + return controler; + } + + public static Controler createControler(Config config, Scenario scenario, boolean otfvis) { + Controler controler = EDrtControlerCreator.createControler(config, scenario, otfvis); + prepareController(config, controler); + return controler; + } + private static void prepareController(Config config, Controler controler) { + MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); for (DrtConfigGroup drtCfg : multiModeDrtConfig.getModalElements()) { controler.addOverridingModule(new ShiftDrtModeModule(drtCfg)); controler.addOverridingQSimModule(new DrtModeQSimModule(drtCfg, new ShiftDrtModeOptimizerQSimModule(drtCfg))); @@ -39,14 +48,11 @@ public static Controler createControler(Config config, boolean otfvis) { controler.addOverridingModule(new DrtShiftEfficiencyModeModule(drtCfg)); } - controler.addOverridingQSimModule(new AbstractQSimModule() { @Override protected void configureQSim() { this.bind(IdleDischargingHandler.VehicleProvider.class).to(ShiftOperatingVehicleProvider.class); } }); - - return controler; } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtAssignShiftToVehicleLogic.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtAssignShiftToVehicleLogic.java index 32f74d1196c..0c2d4fd79c8 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtAssignShiftToVehicleLogic.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtAssignShiftToVehicleLogic.java @@ -9,7 +9,7 @@ package org.matsim.contrib.drt.extension.operations.eshifts.dispatcher; import org.matsim.contrib.drt.extension.operations.eshifts.fleet.EvShiftDvrpVehicle; -import org.matsim.contrib.drt.extension.operations.eshifts.schedule.EDrtWaitForShiftStayTask; +import org.matsim.contrib.drt.extension.operations.eshifts.schedule.EDrtWaitForShiftTask; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; import org.matsim.contrib.drt.extension.operations.shifts.dispatcher.AssignShiftToVehicleLogic; import org.matsim.contrib.drt.extension.operations.shifts.fleet.ShiftDvrpVehicle; @@ -37,8 +37,8 @@ public boolean canAssignVehicleToShift(ShiftDvrpVehicle vehicle, DrtShift shift) // no, if charging if(vehicle.getSchedule().getStatus() == Schedule.ScheduleStatus.STARTED) { final Task currentTask = vehicle.getSchedule().getCurrentTask(); - if (currentTask instanceof EDrtWaitForShiftStayTask) { - if (((EDrtWaitForShiftStayTask) currentTask).getChargingTask() != null) { + if (currentTask instanceof EDrtWaitForShiftTask) { + if (((EDrtWaitForShiftTask) currentTask).getChargingTask() != null) { if (currentTask.getEndTime() > shift.getStartTime()) { return false; } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtShiftDispatcherImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtShiftDispatcherImpl.java index e18008e4ce5..ace6e8d66e0 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtShiftDispatcherImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtShiftDispatcherImpl.java @@ -3,7 +3,7 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.drt.extension.operations.eshifts.fleet.EvShiftDvrpVehicle; -import org.matsim.contrib.drt.extension.operations.eshifts.schedule.EDrtWaitForShiftStayTask; +import org.matsim.contrib.drt.extension.operations.eshifts.schedule.EDrtWaitForShiftTask; import org.matsim.contrib.drt.extension.operations.eshifts.scheduler.EShiftTaskScheduler; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; import org.matsim.contrib.drt.extension.operations.shifts.dispatcher.DrtShiftDispatcher; @@ -11,7 +11,7 @@ import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilities; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacility; import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftBreakTask; -import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftStayTask; +import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftTask; import org.matsim.contrib.dvrp.fleet.DvrpVehicle; import org.matsim.contrib.dvrp.fleet.Fleet; import org.matsim.contrib.dvrp.schedule.Schedule; @@ -96,8 +96,8 @@ private void checkChargingAtHub(double timeStep) { final ElectricVehicle electricVehicle = eShiftVehicle.getElectricVehicle(); if (electricVehicle.getBattery().getCharge() / electricVehicle.getBattery().getCapacity() < drtShiftParams.chargeAtHubThreshold) { final Task currentTask = eShiftVehicle.getSchedule().getCurrentTask(); - if (currentTask instanceof EDrtWaitForShiftStayTask - && ((EDrtWaitForShiftStayTask) currentTask).getChargingTask() == null) { + if (currentTask instanceof EDrtWaitForShiftTask + && ((EDrtWaitForShiftTask) currentTask).getChargingTask() == null) { Optional selectedCharger = chargerIds .stream() .map(id -> chargingInfrastructure.getChargers().get(id)) @@ -122,7 +122,7 @@ private void checkChargingAtHub(double timeStep) { .calcRemainingEnergyToCharge(electricVehicle); final double endTime = timeStep + waitTime + chargingTime; if (endTime < currentTask.getEndTime()) { - shiftTaskScheduler.chargeAtHub((WaitForShiftStayTask) currentTask, eShiftVehicle, + shiftTaskScheduler.chargeAtHub((WaitForShiftTask) currentTask, eShiftVehicle, electricVehicle, selectedChargerImpl, timeStep, endTime, energy); } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtShiftStartLogic.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtShiftStartLogic.java index ad3c83ca0f7..97ceadbb433 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtShiftStartLogic.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtShiftStartLogic.java @@ -8,7 +8,7 @@ */ package org.matsim.contrib.drt.extension.operations.eshifts.dispatcher; -import org.matsim.contrib.drt.extension.operations.eshifts.schedule.EDrtWaitForShiftStayTask; +import org.matsim.contrib.drt.extension.operations.eshifts.schedule.EDrtWaitForShiftTask; import org.matsim.contrib.drt.extension.operations.shifts.dispatcher.DrtShiftDispatcher; import org.matsim.contrib.drt.extension.operations.shifts.dispatcher.ShiftStartLogic; import org.matsim.contrib.dvrp.schedule.Schedule; @@ -29,9 +29,9 @@ public EDrtShiftStartLogic(ShiftStartLogic delegate) { public boolean shiftStarts(DrtShiftDispatcher.ShiftEntry shiftEntry) { Schedule schedule = shiftEntry.vehicle().getSchedule(); Task currentTask = schedule.getCurrentTask(); - if (currentTask instanceof EDrtWaitForShiftStayTask) { + if (currentTask instanceof EDrtWaitForShiftTask) { //check whether vehicle still needs to complete charging task - if(((EDrtWaitForShiftStayTask) currentTask).getChargingTask() == null) { + if(((EDrtWaitForShiftTask) currentTask).getChargingTask() == null) { return delegate.shiftStarts(shiftEntry); } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/run/ShiftEDrtModeOptimizerQSimModule.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/run/ShiftEDrtModeOptimizerQSimModule.java index ab4bf41c938..aefdfeb5e6c 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/run/ShiftEDrtModeOptimizerQSimModule.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/run/ShiftEDrtModeOptimizerQSimModule.java @@ -76,7 +76,9 @@ drtShiftParams, new EDrtShiftStartLogic(new DefaultShiftStartLogic()), new EDrtAssignShiftToVehicleLogic(new DefaultAssignShiftToVehicleLogic(drtShiftParams), drtShiftParams)), getter.getModal(Fleet.class)))).asEagerSingleton(); - bindModal(VehicleEntry.EntryFactory.class).toProvider(modalProvider(getter -> new ShiftVehicleDataEntryFactory(new EDrtVehicleDataEntryFactory(0)))).asEagerSingleton(); + bindModal(VehicleEntry.EntryFactory.class).toProvider(modalProvider(getter -> + new ShiftVehicleDataEntryFactory(new EDrtVehicleDataEntryFactory(0), + drtShiftParams.considerUpcomingShiftsForInsertion))).asEagerSingleton(); bindModal(DrtTaskFactory.class).toProvider(modalProvider(getter -> new ShiftEDrtTaskFactoryImpl(new EDrtTaskFactoryImpl(), getter.getModal(OperationFacilities.class)))).in(Singleton.class); bindModal(ShiftDrtTaskFactory.class).toProvider(modalProvider(getter -> ((ShiftDrtTaskFactory) getter.getModal(DrtTaskFactory.class)))); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/EDrtWaitForShiftStayTask.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/EDrtWaitForShiftTask.java similarity index 69% rename from contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/EDrtWaitForShiftStayTask.java rename to contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/EDrtWaitForShiftTask.java index c60e0214f1d..546b4e6b770 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/EDrtWaitForShiftStayTask.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/EDrtWaitForShiftTask.java @@ -1,23 +1,23 @@ package org.matsim.contrib.drt.extension.operations.eshifts.schedule; import org.matsim.api.core.v01.network.Link; +import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftTask; import org.matsim.contrib.evrp.ChargingTask; import org.matsim.contrib.evrp.ETask; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacility; -import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftStayTask; /** * @author nkuehnel / MOIA */ -public class EDrtWaitForShiftStayTask extends WaitForShiftStayTask implements ETask { +public class EDrtWaitForShiftTask extends WaitForShiftTask implements ETask { private final double consumedEnergy; private final ChargingTask chargingTask; - public EDrtWaitForShiftStayTask(double beginTime, double endTime, Link link, - double consumedEnergy, OperationFacility facility, - ChargingTask chargingTask) { + public EDrtWaitForShiftTask(double beginTime, double endTime, Link link, + double consumedEnergy, OperationFacility facility, + ChargingTask chargingTask) { super(beginTime, endTime, link, facility); this.consumedEnergy = consumedEnergy; this.chargingTask = chargingTask; diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/ShiftEDrtActionCreator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/ShiftEDrtActionCreator.java index 4604771bed9..6092021974c 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/ShiftEDrtActionCreator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/ShiftEDrtActionCreator.java @@ -42,9 +42,9 @@ public DynAction createAction(DynAgent dynAgent, DvrpVehicle vehicle, double now task.initTaskTracker(new OfflineETaskTracker((EvDvrpVehicle) vehicle, timer)); DrtStopTask t = (DrtStopTask) task; return new ChargingChangeoverActivity(((EDrtShiftChangeoverTaskImpl) task).getChargingTask(), passengerHandler, dynAgent, t, t.getDropoffRequests(), t.getPickupRequests()); - } else if (task instanceof EDrtWaitForShiftStayTask && ((EDrtWaitForShiftStayTask) task).getChargingTask() != null) { + } else if (task instanceof EDrtWaitForShiftTask && ((EDrtWaitForShiftTask) task).getChargingTask() != null) { task.initTaskTracker(new OfflineETaskTracker((EvDvrpVehicle) vehicle, timer)); - return new ChargingWaitForShiftActivity(((EDrtWaitForShiftStayTask) task).getChargingTask()); + return new ChargingWaitForShiftActivity(((EDrtWaitForShiftTask) task).getChargingTask()); } DynAction dynAction = delegate.createAction(dynAgent, vehicle, now); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/ShiftEDrtTaskFactoryImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/ShiftEDrtTaskFactoryImpl.java index 5e0c085c1bb..b7c2657f1bf 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/ShiftEDrtTaskFactoryImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/ShiftEDrtTaskFactoryImpl.java @@ -9,7 +9,7 @@ import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftBreakTask; import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftChangeOverTask; import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftDrtTaskFactory; -import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftStayTask; +import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftTask; import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShift; import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftBreak; import org.matsim.contrib.drt.schedule.DrtDriveTask; @@ -69,14 +69,14 @@ public DefaultStayTask createInitialTask(DvrpVehicle vehicle, double beginTime, } catch (Throwable e) { throw new RuntimeException(e); } - WaitForShiftStayTask waitForShiftStayTask = createWaitForShiftStayTask(vehicle, vehicle.getServiceBeginTime(), vehicle.getServiceEndTime(), + WaitForShiftTask waitForShiftTask = createWaitForShiftStayTask(vehicle, vehicle.getServiceBeginTime(), vehicle.getServiceEndTime(), vehicle.getStartLink(), operationFacility); boolean success = operationFacility.register(vehicle.getId()); if (!success) { throw new RuntimeException(String.format("Cannot register vehicle %s at facility %s at start-up. Please check" + "facility capacity and initial fleet distribution.", vehicle.getId().toString(), operationFacility.getId().toString())); } - return waitForShiftStayTask; + return waitForShiftTask; } @Override @@ -92,16 +92,16 @@ public ShiftChangeOverTask createShiftChangeoverTask(DvrpVehicle vehicle, double } @Override - public WaitForShiftStayTask createWaitForShiftStayTask(DvrpVehicle vehicle, double beginTime, double endTime, Link link, - OperationFacility facility) { - return new EDrtWaitForShiftStayTask(beginTime, endTime, link, 0, facility, null); + public WaitForShiftTask createWaitForShiftStayTask(DvrpVehicle vehicle, double beginTime, double endTime, Link link, + OperationFacility facility) { + return new EDrtWaitForShiftTask(beginTime, endTime, link, 0, facility, null); } - public WaitForShiftStayTask createChargingWaitForShiftStayTask(DvrpVehicle vehicle, double beginTime, - double endTime, Link link, OperationFacility facility, - double totalEnergy, Charger charger) { + public WaitForShiftTask createChargingWaitForShiftStayTask(DvrpVehicle vehicle, double beginTime, + double endTime, Link link, OperationFacility facility, + double totalEnergy, Charger charger) { ChargingTask chargingTask = new ChargingTaskImpl(EDrtChargingTask.TYPE, beginTime, endTime, charger, ((EvDvrpVehicle)vehicle).getElectricVehicle(), totalEnergy); - return new EDrtWaitForShiftStayTask(beginTime, endTime, link, totalEnergy, facility, chargingTask); + return new EDrtWaitForShiftTask(beginTime, endTime, link, totalEnergy, facility, chargingTask); } public EDrtShiftBreakTaskImpl createChargingShiftBreakTask(DvrpVehicle vehicle, double beginTime, double endTime, Link link, diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/scheduler/EShiftTaskScheduler.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/scheduler/EShiftTaskScheduler.java index 7352f32c261..dc053728a40 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/scheduler/EShiftTaskScheduler.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/scheduler/EShiftTaskScheduler.java @@ -351,8 +351,8 @@ private void appendShiftChange(DvrpVehicle vehicle, DrtShift shift, OperationFac public void startShift(ShiftDvrpVehicle vehicle, double now, DrtShift shift) { Schedule schedule = vehicle.getSchedule(); StayTask stayTask = (StayTask) schedule.getCurrentTask(); - if (stayTask instanceof WaitForShiftStayTask) { - ((WaitForShiftStayTask) stayTask).getFacility().deregisterVehicle(vehicle.getId()); + if (stayTask instanceof WaitForShiftTask) { + ((WaitForShiftTask) stayTask).getFacility().deregisterVehicle(vehicle.getId()); stayTask.setEndTime(now); schedule.addTask(taskFactory.createStayTask(vehicle, now, shift.getEndTime(), stayTask.getLink())); } else { @@ -375,6 +375,24 @@ public boolean updateShiftChange(ShiftDvrpVehicle vehicle, Link link, DrtShift s return false; } + @Override + public void planAssignedShift(ShiftDvrpVehicle vehicle, double timeStep, DrtShift shift) { + Schedule schedule = vehicle.getSchedule(); + StayTask stayTask = (StayTask) schedule.getCurrentTask(); + if (stayTask instanceof WaitForShiftTask) { + stayTask.setEndTime(Math.max(timeStep, shift.getStartTime())); + } + } + + @Override + public void cancelAssignedShift(ShiftDvrpVehicle vehicle, double timeStep, DrtShift shift) { + Schedule schedule = vehicle.getSchedule(); + StayTask stayTask = (StayTask) schedule.getCurrentTask(); + if (stayTask instanceof WaitForShiftTask) { + stayTask.setEndTime(vehicle.getServiceEndTime()); + } + } + private void updateShiftChangeImpl(DvrpVehicle vehicle, VrpPathWithTravelData vrpPath, DrtShift shift, OperationFacility facility, Task lastTask) { Schedule schedule = vehicle.getSchedule(); @@ -413,19 +431,19 @@ private void updateShiftChangeImpl(DvrpVehicle vehicle, VrpPathWithTravelData vr vrpPath.getToLink(), facility)); } - public void chargeAtHub(WaitForShiftStayTask currentTask, ShiftDvrpVehicle vehicle, + public void chargeAtHub(WaitForShiftTask currentTask, ShiftDvrpVehicle vehicle, ElectricVehicle electricVehicle, Charger charger, double beginTime, double endTime, double energy) { final double initialEndTime = currentTask.getEndTime(); currentTask.setEndTime(beginTime); ((ChargingWithAssignmentLogic) charger.getLogic()).assignVehicle(electricVehicle); - final WaitForShiftStayTask chargingWaitForShiftStayTask = ((ShiftEDrtTaskFactoryImpl) taskFactory).createChargingWaitForShiftStayTask(vehicle, + final WaitForShiftTask chargingWaitForShiftTask = ((ShiftEDrtTaskFactoryImpl) taskFactory).createChargingWaitForShiftStayTask(vehicle, beginTime, endTime, currentTask.getLink(), currentTask.getFacility(), energy, charger); - final WaitForShiftStayTask waitForShiftStayTask = taskFactory.createWaitForShiftStayTask(vehicle, endTime, + final WaitForShiftTask waitForShiftTask = taskFactory.createWaitForShiftStayTask(vehicle, endTime, initialEndTime, currentTask.getLink(), currentTask.getFacility()); - vehicle.getSchedule().addTask(currentTask.getTaskIdx() + 1, chargingWaitForShiftStayTask); - vehicle.getSchedule().addTask(currentTask.getTaskIdx() + 2, waitForShiftStayTask); + vehicle.getSchedule().addTask(currentTask.getTaskIdx() + 1, chargingWaitForShiftTask); + vehicle.getSchedule().addTask(currentTask.getTaskIdx() + 2, waitForShiftTask); } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/config/ShiftsParams.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/config/ShiftsParams.java index 4d76cbddfc0..e61e5541896 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/config/ShiftsParams.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/config/ShiftsParams.java @@ -8,8 +8,8 @@ */ package org.matsim.contrib.drt.extension.operations.shifts.config; -import org.matsim.contrib.ev.infrastructure.ChargerSpecification; import org.matsim.contrib.common.util.ReflectiveConfigGroupWithConfigurableParameterSets; +import org.matsim.contrib.ev.infrastructure.ChargerSpecification; import org.matsim.core.config.ConfigGroup; import java.net.URL; @@ -43,7 +43,7 @@ public class ShiftsParams extends ReflectiveConfigGroupWithConfigurableParameter @Parameter @Comment("Time of shift end rescheduling (i.e. check whether shift should end" + - " at a different facillity) before end of shift in [seconds]") + " at a different facility) before end of shift in [seconds]") public double shiftEndRescheduleLookAhead = 1800; @Parameter @@ -53,7 +53,7 @@ public class ShiftsParams extends ReflectiveConfigGroupWithConfigurableParameter @Parameter @Comment("set to true if shifts can start and end at in field operational facilities," + - " false if changerover is only allowed at hubs") + " false if changeover is only allowed at hubs") public boolean allowInFieldChangeover = true; //electric shifts @@ -91,7 +91,13 @@ public class ShiftsParams extends ReflectiveConfigGroupWithConfigurableParameter @Comment("defines the logging interval in [seconds]") public double loggingInterval = 600; - public ShiftsParams() { + @Parameter + @Comment("Defines whether vehicles should be eligible for insertion when they have a shift assigned which has not yet started. " + + "Defaults to false. Should be set to true if used together with prebookings that are inserted before shift starts. " + + "In this case, make sure that 'shiftScheduleLookAhead' is larger than the prebboking slack.") + public boolean considerUpcomingShiftsForInsertion = false; + + public ShiftsParams() { super(SET_NAME); } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DefaultShiftStartLogic.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DefaultShiftStartLogic.java index cb9e5d76a9f..f2b006cbae7 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DefaultShiftStartLogic.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DefaultShiftStartLogic.java @@ -11,7 +11,7 @@ import com.google.common.base.Verify; import org.matsim.api.core.v01.Id; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacility; -import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftStayTask; +import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftTask; import org.matsim.contrib.dvrp.schedule.Schedule; import org.matsim.contrib.dvrp.schedule.Task; @@ -34,11 +34,11 @@ public boolean shiftStarts(DrtShiftDispatcher.ShiftEntry peek) { // current task is WaitForShiftTask Task currentTask = schedule.getCurrentTask(); - if(currentTask instanceof WaitForShiftStayTask) { + if(currentTask instanceof WaitForShiftTask) { //check if optional location requirement is met if(peek.shift().getOperationFacilityId().isPresent()) { Id operationFacilityId = peek.shift().getOperationFacilityId().get(); - Verify.verify((operationFacilityId.equals(((WaitForShiftStayTask) currentTask).getFacility().getId())), + Verify.verify((operationFacilityId.equals(((WaitForShiftTask) currentTask).getFacility().getId())), "Vehicle and shift start locations do not match."); } return true; diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java index c32b5d1b12b..7cfa4579612 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java @@ -152,28 +152,30 @@ private void checkBreaks() { } private void startShifts(double timeStep) { - // Start shifts final Iterator iterator = this.assignedShifts.iterator(); while (iterator.hasNext()) { - final ShiftEntry next = iterator.next(); - if (next.shift().getStartTime() > timeStep) { + final ShiftEntry assignedShiftEntry = iterator.next(); + if (assignedShiftEntry.shift().getStartTime() > timeStep) { + shiftTaskScheduler.planAssignedShift(assignedShiftEntry.vehicle(), timeStep, assignedShiftEntry.shift()); break; - } else if (next.shift().getEndTime() < timeStep) { - logger.warn("Too late to start shift " + next.shift().getId()); - next.vehicle().getShifts().remove(next.shift()); + } else if (assignedShiftEntry.shift().getEndTime() < timeStep) { + logger.warn("Too late to start shift " + assignedShiftEntry.shift().getId()); + assignedShiftEntry.vehicle().getShifts().remove(assignedShiftEntry.shift()); iterator.remove(); continue; } - if (shiftStartLogic.shiftStarts(next)) { - next.shift().start(); - shiftTaskScheduler.startShift(next.vehicle(), timeStep, next.shift()); - activeShifts.add(next); + if (shiftStartLogic.shiftStarts(assignedShiftEntry)) { + assignedShiftEntry.shift().start(); + shiftTaskScheduler.startShift(assignedShiftEntry.vehicle(), timeStep, assignedShiftEntry.shift()); + activeShifts.add(assignedShiftEntry); iterator.remove(); - logger.debug("Started shift " + next.shift()); - StayTask currentTask = (StayTask) next.vehicle().getSchedule().getCurrentTask(); - eventsManager.processEvent(new DrtShiftStartedEvent(timeStep, mode, next.shift().getId(), next.vehicle().getId(), + logger.debug("Started shift " + assignedShiftEntry.shift()); + StayTask currentTask = (StayTask) assignedShiftEntry.vehicle().getSchedule().getCurrentTask(); + eventsManager.processEvent(new DrtShiftStartedEvent(timeStep, mode, assignedShiftEntry.shift().getId(), assignedShiftEntry.vehicle().getId(), currentTask.getLink().getId())); + } else { + shiftTaskScheduler.planAssignedShift(assignedShiftEntry.vehicle(), timeStep, assignedShiftEntry.shift()); } } } @@ -264,6 +266,7 @@ private void assignShifts(double timeStep) { private void assignShiftToVehicle(DrtShift shift, ShiftDvrpVehicle vehicle) { Gbl.assertNotNull(vehicle); vehicle.addShift(shift); + shiftTaskScheduler.planAssignedShift(vehicle, timer.getTimeOfDay(), shift); assignedShifts.add(new ShiftEntry(shift, vehicle)); eventsManager.processEvent(new DrtShiftAssignedEvent(timer.getTimeOfDay(), mode, shift.getId(), vehicle.getId())); } @@ -438,7 +441,7 @@ private void scheduleShiftEnd(ShiftEntry endingShift) { private OperationFacility decideOnBreak(ShiftEntry activeShift) { if (activeShift.shift() != null) { - if (shiftNeedsBreak(activeShift.shift(), timer.getTimeOfDay())) { + if (hasSchedulableBreak(activeShift.shift(), timer.getTimeOfDay())) { final Schedule schedule = activeShift.vehicle().getSchedule(); Task currentTask = schedule.getCurrentTask(); Link lastLink; @@ -500,12 +503,10 @@ public void startBreak(ShiftDvrpVehicle vehicle, Id linkId) { } private boolean isSchedulable(DrtShift shift, double timeStep) { - return shift.getStartTime() <= timeStep + drtShiftParams.shiftScheduleLookAhead; // && shift.getEndTime() > timeStep; + return shift.getStartTime() <= timeStep + drtShiftParams.shiftScheduleLookAhead; } - - - private boolean shiftNeedsBreak(DrtShift shift, double timeStep) { + private boolean hasSchedulableBreak(DrtShift shift, double timeStep) { return shift.getBreak().isPresent() && shift.getBreak().get().getEarliestBreakStartTime() == timeStep && !shift.getBreak().get().isScheduled(); } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/ShiftVehicleDataEntryFactory.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/ShiftVehicleDataEntryFactory.java index 3262fe787fc..66a3470ddbe 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/ShiftVehicleDataEntryFactory.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/ShiftVehicleDataEntryFactory.java @@ -1,16 +1,11 @@ package org.matsim.contrib.drt.extension.operations.shifts.optimizer; -import com.google.inject.Provider; import org.matsim.contrib.drt.extension.operations.shifts.fleet.ShiftDvrpVehicle; -import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShift; import org.matsim.contrib.drt.extension.operations.shifts.schedule.OperationalStop; -import org.matsim.contrib.drt.optimizer.VehicleDataEntryFactoryImpl; +import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftTask; +import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShift; import org.matsim.contrib.drt.optimizer.VehicleEntry; -import org.matsim.contrib.drt.run.DrtConfigGroup; import org.matsim.contrib.dvrp.fleet.DvrpVehicle; -import org.matsim.core.config.Config; - -import jakarta.inject.Inject; /** * @author nkuehnel / MOIA @@ -19,10 +14,13 @@ public class ShiftVehicleDataEntryFactory implements VehicleEntry.EntryFactory { private final VehicleEntry.EntryFactory entryFactory; + private final boolean considerUpcomingShifts; + - public ShiftVehicleDataEntryFactory(VehicleEntry.EntryFactory delegate) { + public ShiftVehicleDataEntryFactory(VehicleEntry.EntryFactory delegate, boolean considerUpcomingShifts) { entryFactory = delegate; - } + this.considerUpcomingShifts = considerUpcomingShifts; + } @Override public VehicleEntry create(DvrpVehicle vehicle, double currentTime) { @@ -36,12 +34,21 @@ public VehicleEntry create(DvrpVehicle vehicle, double currentTime) { public boolean isEligibleForRequestInsertion(DvrpVehicle dvrpVehicle, double currentTime) { final DrtShift currentShift = ((ShiftDvrpVehicle) dvrpVehicle).getShifts().peek(); - if(currentShift == null || - currentTime > currentShift.getEndTime() || - !currentShift.isStarted() || - currentShift.isEnded()) { - return false; + + // no shift assigned + if (currentShift == null) { + return false; + } + + if(currentShift.isStarted()) { + if(currentTime > currentShift.getEndTime()) { + return false; + } + // do not insert into operational stops such as breaks + return !(dvrpVehicle.getSchedule().getCurrentTask() instanceof OperationalStop); + } else { + // upcoming shift assigned but not started yet. Only consider vehicles already waiting for shift start + return considerUpcomingShifts && dvrpVehicle.getSchedule().getCurrentTask() instanceof WaitForShiftTask; } - return !(dvrpVehicle.getSchedule().getCurrentTask() instanceof OperationalStop); } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/insertion/ShiftInsertionCostCalculator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/insertion/ShiftInsertionCostCalculator.java index db74fcd4d85..7055e4569be 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/insertion/ShiftInsertionCostCalculator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/insertion/ShiftInsertionCostCalculator.java @@ -1,5 +1,6 @@ package org.matsim.contrib.drt.extension.operations.shifts.optimizer.insertion; +import org.matsim.contrib.drt.extension.operations.shifts.fleet.ShiftDvrpVehicle; import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftBreakTask; import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftChangeOverTask; import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftBreak; @@ -32,19 +33,23 @@ public ShiftInsertionCostCalculator(MobsimTimer timer, @Override public double calculate(DrtRequest drtRequest, Insertion insertion, DetourTimeInfo detourTimeInfo) { - if (!checkShiftTimeConstraintsForScheduledRequests(insertion, - detourTimeInfo.pickupDetourInfo.pickupTimeLoss, detourTimeInfo.getTotalTimeLoss())) { + if (!checkShiftTimeConstraintsForScheduledRequests(insertion, detourTimeInfo)) { return INFEASIBLE_SOLUTION_COST; } return delegate.calculate(drtRequest, insertion, detourTimeInfo); } - boolean checkShiftTimeConstraintsForScheduledRequests(Insertion insertion, double pickupDetourTimeLoss, - double totalTimeLoss) { + boolean checkShiftTimeConstraintsForScheduledRequests(Insertion insertion, DetourTimeInfo detourTimeInfo) { VehicleEntry vEntry = insertion.vehicleEntry; final int pickupIdx = insertion.pickup.index; final int dropoffIdx = insertion.dropoff.index; + double shiftEndTime = ((ShiftDvrpVehicle) vEntry.vehicle).getShifts().peek().getEndTime(); + if(shiftEndTime < detourTimeInfo.dropoffDetourInfo.arrivalTime) { + // fast fail which also captures requests that are prebooked for times outside of the shift. + return false; + } + for (int s = 0; s < pickupIdx; s++) { Waypoint.Stop stop = vEntry.stops.get(s); if (stop.task instanceof ShiftChangeOverTask) { @@ -53,6 +58,8 @@ boolean checkShiftTimeConstraintsForScheduledRequests(Insertion insertion, doubl } } + double pickupDetourTimeLoss = detourTimeInfo.pickupDetourInfo.pickupTimeLoss; + // each existing stop has 2 time constraints: latestArrivalTime and latestDepartureTime (see: Waypoint.Stop) // we are looking only at the time constraints of the scheduled requests (the new request is checked separately) @@ -73,6 +80,8 @@ boolean checkShiftTimeConstraintsForScheduledRequests(Insertion insertion, doubl } } + double totalTimeLoss = detourTimeInfo.getTotalTimeLoss(); + // all stops after the new (potential) dropoff are delayed by totalTimeLoss // check if this delay satisfies the time constraints at these stops for (int s = dropoffIdx; s < vEntry.stops.size(); s++) { diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeModule.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeModule.java index 7df2d885723..8b52ca88951 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeModule.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeModule.java @@ -14,7 +14,7 @@ import org.matsim.contrib.drt.extension.operations.shifts.io.DrtShiftsReader; import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftBreakTaskImpl; import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftChangeoverTaskImpl; -import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftStayTask; +import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftTask; import org.matsim.contrib.drt.extension.operations.shifts.scheduler.ShiftTaskScheduler; import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftsSpecification; import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftsSpecificationImpl; @@ -57,7 +57,7 @@ public ShiftDrtModeModule(DrtConfigGroup drtCfg) { private static final Comparator taskTypeComparator = Comparator.comparing((Task.TaskType type) -> { //we want the following order on the plot: STAY, RELOCATE, other - if (type.equals(WaitForShiftStayTask.TYPE)) { + if (type.equals(WaitForShiftTask.TYPE)) { return "F"; } else if (type.equals(ShiftChangeoverTaskImpl.TYPE)) { return "E"; @@ -73,7 +73,7 @@ public ShiftDrtModeModule(DrtConfigGroup drtCfg) { }).reversed(); private static final Map taskTypePaints = ImmutableMap.of( - WaitForShiftStayTask.TYPE, Color.WHITE, + WaitForShiftTask.TYPE, Color.WHITE, ShiftChangeoverTaskImpl.TYPE, Color.GRAY, ShiftBreakTaskImpl.TYPE, Color.DARK_GRAY, DrtStayTask.TYPE, Color.LIGHT_GRAY); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeOptimizerQSimModule.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeOptimizerQSimModule.java index a6398faf3b3..a65de06b2c4 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeOptimizerQSimModule.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeOptimizerQSimModule.java @@ -124,7 +124,9 @@ shiftsParams, new DefaultShiftStartLogic(), new DefaultAssignShiftToVehicleLogic new DefaultInsertionCostCalculator(getter.getModal(CostCalculationStrategy.class), drtCfg.addOrGetDrtOptimizationConstraintsParams().addOrGetDefaultDrtOptimizationConstraintsSet())))); - bindModal(VehicleEntry.EntryFactory.class).toInstance(new ShiftVehicleDataEntryFactory(new VehicleDataEntryFactoryImpl())); + bindModal(VehicleEntry.EntryFactory.class).toInstance( + new ShiftVehicleDataEntryFactory(new VehicleDataEntryFactoryImpl(), shiftsParams.considerUpcomingShiftsForInsertion) + ); bindModal(DrtTaskFactory.class).toProvider(modalProvider(getter -> new ShiftDrtTaskFactoryImpl(new DrtTaskFactoryImpl(), getter.getModal(OperationFacilities.class)))); bindModal(ShiftDrtTaskFactory.class).toProvider(modalProvider(getter -> ((ShiftDrtTaskFactory) getter.getModal(DrtTaskFactory.class)))); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtActionCreator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtActionCreator.java index 0f65e1208f0..5deb47eba47 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtActionCreator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtActionCreator.java @@ -38,7 +38,7 @@ public DynAction createAction(DynAgent dynAgent, DvrpVehicle vehicle, double now DrtStopTask t = (DrtStopTask) task; return new DrtStopActivity(passengerHandler, dynAgent, t::getEndTime, t.getDropoffRequests(), t.getPickupRequests(), DRT_SHIFT_CHANGEOVER_NAME); - } else if (task instanceof WaitForShiftStayTask) { + } else if (task instanceof WaitForShiftTask) { return new IdleDynActivity(DRT_SHIFT_WAIT_FOR_SHIFT_NAME, task::getEndTime); } else { return dynActionCreator.createAction(dynAgent, vehicle, now); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtStayTaskEndTimeCalculator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtStayTaskEndTimeCalculator.java index ddeaf4ffb9e..546f0843673 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtStayTaskEndTimeCalculator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtStayTaskEndTimeCalculator.java @@ -1,8 +1,8 @@ package org.matsim.contrib.drt.extension.operations.shifts.schedule; +import com.google.common.base.Verify; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftBreak; import org.matsim.contrib.drt.schedule.DrtStayTaskEndTimeCalculator; @@ -31,17 +31,21 @@ public ShiftDrtStayTaskEndTimeCalculator(ShiftsParams drtShiftParams, DrtStayTas @Override public double calcNewEndTime(DvrpVehicle vehicle, StayTask task, double newBeginTime) { - if(task instanceof ShiftBreakTask) { + if (task instanceof WaitForShiftTask) { + Verify.verify(newBeginTime <= task.getEndTime(), "WaitForShiftTasks should not be delayed"); + return task.getEndTime(); + } + if (task instanceof ShiftBreakTask) { final DrtShiftBreak shiftBreak = ((ShiftBreakTask) task).getShiftBreak(); return newBeginTime + shiftBreak.getDuration(); - } else if(task instanceof ShiftChangeOverTask) { + } else if (task instanceof ShiftChangeOverTask) { return Math.max(newBeginTime, ((ShiftChangeOverTask) task).getShift().getEndTime()) + drtShiftParams.changeoverDuration; - } else if(DrtTaskBaseType.getBaseTypeOrElseThrow(task).equals(DrtTaskBaseType.STAY)) { + } else if (DrtTaskBaseType.getBaseTypeOrElseThrow(task).equals(DrtTaskBaseType.STAY)) { final List tasks = vehicle.getSchedule().getTasks(); final int taskIdx = tasks.indexOf(task); - if(tasks.size() > taskIdx+1) { - final Task nextTask = tasks.get(taskIdx +1); - if(nextTask instanceof ShiftChangeOverTask) { + if (tasks.size() > taskIdx + 1) { + final Task nextTask = tasks.get(taskIdx + 1); + if (nextTask instanceof ShiftChangeOverTask) { return Math.max(newBeginTime, ((ShiftChangeOverTask) nextTask).getShift().getEndTime()); } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtTaskFactory.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtTaskFactory.java index 9de610a8b84..eaaf5c371ef 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtTaskFactory.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtTaskFactory.java @@ -18,6 +18,6 @@ ShiftBreakTask createShiftBreakTask(DvrpVehicle vehicle, double beginTime, doubl ShiftChangeOverTask createShiftChangeoverTask(DvrpVehicle vehicle, double beginTime, double endTime, Link link, DrtShift shift, OperationFacility facility); - WaitForShiftStayTask createWaitForShiftStayTask(DvrpVehicle vehicle, double beginTime, double endTime, Link link, - OperationFacility facility); + WaitForShiftTask createWaitForShiftStayTask(DvrpVehicle vehicle, double beginTime, double endTime, Link link, + OperationFacility facility); } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtTaskFactoryImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtTaskFactoryImpl.java index 57460d2bee6..e59d40dbac6 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtTaskFactoryImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtTaskFactoryImpl.java @@ -58,9 +58,9 @@ public ShiftChangeOverTask createShiftChangeoverTask(DvrpVehicle vehicle, double } @Override - public WaitForShiftStayTask createWaitForShiftStayTask(DvrpVehicle vehicle, double beginTime, double endTime, - Link link, OperationFacility facility) { - return new WaitForShiftStayTask(beginTime, endTime, link, facility); + public WaitForShiftTask createWaitForShiftStayTask(DvrpVehicle vehicle, double beginTime, double endTime, + Link link, OperationFacility facility) { + return new WaitForShiftTask(beginTime, endTime, link, facility); } public DefaultStayTask createInitialTask(DvrpVehicle vehicle, double beginTime, double endTime, Link link) { @@ -71,7 +71,7 @@ public DefaultStayTask createInitialTask(DvrpVehicle vehicle, double beginTime, } catch (Throwable e) { throw new RuntimeException(e); } - WaitForShiftStayTask waitForShiftStayTask = createWaitForShiftStayTask(vehicle, vehicle.getServiceBeginTime(), vehicle.getServiceEndTime(), + WaitForShiftTask waitForShiftStayTask = createWaitForShiftStayTask(vehicle, vehicle.getServiceBeginTime(), vehicle.getServiceEndTime(), vehicle.getStartLink(), operationFacility); boolean success = operationFacility.register(vehicle.getId()); if (!success) { diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/WaitForShiftStayTask.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/WaitForShiftStayTask.java deleted file mode 100644 index 25556e16db7..00000000000 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/WaitForShiftStayTask.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.matsim.contrib.drt.extension.operations.shifts.schedule; - -import org.matsim.api.core.v01.network.Link; -import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacility; -import org.matsim.contrib.drt.schedule.DrtTaskType; -import org.matsim.contrib.dvrp.schedule.DefaultStayTask; - -import static org.matsim.contrib.drt.schedule.DrtTaskBaseType.STAY; - -/** - * @author nkuehnel / MOIA - */ -public class WaitForShiftStayTask extends DefaultStayTask implements OperationalStop { - - public static final DrtTaskType TYPE = new DrtTaskType("WAIT_FOR_SHIFT", STAY); - - private final OperationFacility facility; - - public WaitForShiftStayTask(double beginTime, double endTime, Link link, OperationFacility facility) { - super(TYPE, beginTime, endTime, link); - this.facility = facility; - } - - @Override - public OperationFacility getFacility() { - return facility; - } - -} diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/WaitForShiftTask.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/WaitForShiftTask.java new file mode 100644 index 00000000000..dcb0e9a1927 --- /dev/null +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/WaitForShiftTask.java @@ -0,0 +1,65 @@ +package org.matsim.contrib.drt.extension.operations.shifts.schedule; + +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.network.Link; +import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacility; +import org.matsim.contrib.drt.passenger.AcceptedDrtRequest; +import org.matsim.contrib.drt.schedule.DrtStopTask; +import org.matsim.contrib.drt.schedule.DrtTaskType; +import org.matsim.contrib.dvrp.optimizer.Request; +import org.matsim.contrib.dvrp.schedule.DefaultStayTask; + +import java.util.Collections; +import java.util.Map; + +import static org.matsim.contrib.drt.schedule.DrtTaskBaseType.STOP; + +/** + * @author nkuehnel / MOIA + */ +public class WaitForShiftTask extends DefaultStayTask implements DrtStopTask, OperationalStop { + + public static final DrtTaskType TYPE = new DrtTaskType("WAIT_FOR_SHIFT", STOP); + + private final OperationFacility facility; + + public WaitForShiftTask(double beginTime, double endTime, Link link, OperationFacility facility) { + super(TYPE, beginTime, endTime, link); + this.facility = facility; + } + + @Override + public OperationFacility getFacility() { + return facility; + } + + @Override + public Map, AcceptedDrtRequest> getDropoffRequests() { + return Collections.emptyMap(); + } + + @Override + public Map, AcceptedDrtRequest> getPickupRequests() { + return Collections.emptyMap(); + } + + @Override + public void addDropoffRequest(AcceptedDrtRequest request) { + throw new RuntimeException("Not supported"); + } + + @Override + public void addPickupRequest(AcceptedDrtRequest request) { + throw new RuntimeException("Not supported"); + } + + @Override + public void removePickupRequest(Id requestId) { + throw new RuntimeException("Not supported"); + } + + @Override + public void removeDropoffRequest(Id requestId) { + throw new RuntimeException("Not supported"); + } +} diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftDrtScheduleInquiry.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftDrtScheduleInquiry.java index 7fb582caea6..d598bb29b13 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftDrtScheduleInquiry.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftDrtScheduleInquiry.java @@ -2,13 +2,13 @@ import com.google.inject.Inject; import org.matsim.contrib.drt.extension.operations.shifts.fleet.ShiftDvrpVehicle; +import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftTask; import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShift; import org.matsim.contrib.drt.scheduler.DrtScheduleInquiry; import org.matsim.contrib.dvrp.fleet.DvrpVehicle; import org.matsim.contrib.dvrp.schedule.Schedule; import org.matsim.contrib.dvrp.schedule.ScheduleInquiry; import org.matsim.contrib.dvrp.schedule.Task; -import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftStayTask; import org.matsim.core.mobsim.framework.MobsimTimer; import static org.matsim.contrib.drt.schedule.DrtTaskBaseType.STAY; @@ -42,7 +42,7 @@ public boolean isIdle(DvrpVehicle vehicle) { } } Task currentTask = schedule.getCurrentTask(); - if(currentTask instanceof WaitForShiftStayTask) { + if(currentTask instanceof WaitForShiftTask) { return false; } return currentTask.getTaskIdx() == schedule.getTaskCount() - 1 diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskScheduler.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskScheduler.java index 2b9b3415d5c..dc8187c0fce 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskScheduler.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskScheduler.java @@ -23,4 +23,8 @@ public interface ShiftTaskScheduler { boolean updateShiftChange(ShiftDvrpVehicle vehicle, Link link, DrtShift shift, LinkTimePair start, OperationFacility facility, Task lastTask); + + void planAssignedShift(ShiftDvrpVehicle vehicle, double timeStep, DrtShift shift); + + void cancelAssignedShift(ShiftDvrpVehicle vehicle, double timeStep, DrtShift shift); } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskSchedulerImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskSchedulerImpl.java index d6d272371e9..0cb820990b2 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskSchedulerImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskSchedulerImpl.java @@ -18,10 +18,7 @@ import org.matsim.contrib.dvrp.fleet.Fleet; import org.matsim.contrib.dvrp.path.VrpPathWithTravelData; import org.matsim.contrib.dvrp.path.VrpPaths; -import org.matsim.contrib.dvrp.schedule.DriveTask; -import org.matsim.contrib.dvrp.schedule.Schedule; -import org.matsim.contrib.dvrp.schedule.StayTask; -import org.matsim.contrib.dvrp.schedule.Task; +import org.matsim.contrib.dvrp.schedule.*; import org.matsim.contrib.dvrp.tracker.OnlineDriveTaskTracker; import org.matsim.contrib.dvrp.util.LinkTimePair; import org.matsim.core.mobsim.framework.MobsimTimer; @@ -266,10 +263,13 @@ private void appendShiftChange(DvrpVehicle vehicle, DrtShift shift, OperationFac public void startShift(ShiftDvrpVehicle vehicle, double now, DrtShift shift) { Schedule schedule = vehicle.getSchedule(); StayTask stayTask = (StayTask) schedule.getCurrentTask(); - if (stayTask instanceof WaitForShiftStayTask) { - ((WaitForShiftStayTask) stayTask).getFacility().deregisterVehicle(vehicle.getId()); + if (stayTask instanceof WaitForShiftTask) { + ((WaitForShiftTask) stayTask).getFacility().deregisterVehicle(vehicle.getId()); stayTask.setEndTime(now); - schedule.addTask(taskFactory.createStayTask(vehicle, now, shift.getEndTime(), stayTask.getLink())); + if(Schedules.getLastTask(schedule).equals(stayTask)) { + //nothing planned yet. + schedule.addTask(taskFactory.createStayTask(vehicle, now, shift.getEndTime(), stayTask.getLink())); + } } else { throw new IllegalStateException("Vehicle cannot start shift during task:" + stayTask.getTaskType().name()); } @@ -291,6 +291,24 @@ public boolean updateShiftChange(ShiftDvrpVehicle vehicle, Link link, DrtShift s return false; } + @Override + public void planAssignedShift(ShiftDvrpVehicle vehicle, double timeStep, DrtShift shift) { + Schedule schedule = vehicle.getSchedule(); + StayTask stayTask = (StayTask) schedule.getCurrentTask(); + if (stayTask instanceof WaitForShiftTask) { + stayTask.setEndTime(Math.max(timeStep, shift.getStartTime())); + } + } + + @Override + public void cancelAssignedShift(ShiftDvrpVehicle vehicle, double timeStep, DrtShift shift) { + Schedule schedule = vehicle.getSchedule(); + StayTask stayTask = (StayTask) schedule.getCurrentTask(); + if (stayTask instanceof WaitForShiftTask) { + stayTask.setEndTime(vehicle.getServiceEndTime()); + } + } + private void updateShiftChangeImpl(DvrpVehicle vehicle, VrpPathWithTravelData vrpPath, DrtShift shift, OperationFacility facility, Task lastTask) { Schedule schedule = vehicle.getSchedule(); diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunPrebookingShiftDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunPrebookingShiftDrtScenarioIT.java new file mode 100644 index 00000000000..fa6ad3cb0ce --- /dev/null +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunPrebookingShiftDrtScenarioIT.java @@ -0,0 +1,298 @@ +package org.matsim.contrib.drt.extension.operations.shifts.run; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.matsim.api.core.v01.Coord; +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.Scenario; +import org.matsim.api.core.v01.TransportMode; +import org.matsim.api.core.v01.network.Network; +import org.matsim.api.core.v01.network.Node; +import org.matsim.api.core.v01.population.*; +import org.matsim.contrib.common.zones.systems.grid.square.SquareGridZoneSystemParams; +import org.matsim.contrib.drt.analysis.zonal.DrtZoneSystemParams; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; +import org.matsim.contrib.drt.extension.operations.DrtOperationsControlerCreator; +import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; +import org.matsim.contrib.drt.extension.operations.operationFacilities.*; +import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; +import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShift; +import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftSpecificationImpl; +import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftsSpecification; +import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftsSpecificationImpl; +import org.matsim.contrib.drt.optimizer.constraints.DefaultDrtOptimizationConstraintsSet; +import org.matsim.contrib.drt.optimizer.insertion.extensive.ExtensiveInsertionSearchParams; +import org.matsim.contrib.drt.optimizer.rebalancing.RebalancingParams; +import org.matsim.contrib.drt.optimizer.rebalancing.mincostflow.MinCostFlowRebalancingStrategyParams; +import org.matsim.contrib.drt.prebooking.PrebookingModeQSimModule; +import org.matsim.contrib.drt.prebooking.PrebookingParams; +import org.matsim.contrib.drt.prebooking.logic.AttributeBasedPrebookingLogic; +import org.matsim.contrib.drt.run.DrtConfigGroup; +import org.matsim.contrib.drt.run.DrtControlerCreator; +import org.matsim.contrib.drt.run.MultiModeDrtConfigGroup; +import org.matsim.contrib.dvrp.fleet.DvrpVehicle; +import org.matsim.contrib.dvrp.fleet.FleetSpecification; +import org.matsim.contrib.dvrp.fleet.FleetSpecificationImpl; +import org.matsim.contrib.dvrp.fleet.ImmutableDvrpVehicleSpecification; +import org.matsim.contrib.dvrp.passenger.PassengerRequestRejectedEventHandler; +import org.matsim.contrib.dvrp.run.AbstractDvrpModeModule; +import org.matsim.contrib.dvrp.run.DvrpConfigGroup; +import org.matsim.contrib.zone.skims.DvrpTravelTimeMatrixParams; +import org.matsim.core.config.Config; +import org.matsim.core.config.ConfigGroup; +import org.matsim.core.config.ConfigUtils; +import org.matsim.core.config.groups.QSimConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.controler.AbstractModule; +import org.matsim.core.controler.Controler; +import org.matsim.core.controler.OutputDirectoryHierarchy; +import org.matsim.core.network.NetworkUtils; +import org.matsim.core.population.PopulationUtils; +import org.matsim.core.utils.geometry.CoordUtils; + +import java.util.HashSet; +import java.util.Set; + + + +/** + * @author nkuehnel / MOIA + */ +public class RunPrebookingShiftDrtScenarioIT { + + + @Test + void test() { + + MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithExtensionsConfigGroup::new); + + DrtWithExtensionsConfigGroup drtWithShiftsConfigGroup = (DrtWithExtensionsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); + drtWithShiftsConfigGroup.mode = TransportMode.drt; + DefaultDrtOptimizationConstraintsSet defaultConstraintsSet = + (DefaultDrtOptimizationConstraintsSet) drtWithShiftsConfigGroup.addOrGetDrtOptimizationConstraintsParams() + .addOrGetDefaultDrtOptimizationConstraintsSet(); + drtWithShiftsConfigGroup.stopDuration = 30.; + defaultConstraintsSet.maxTravelTimeAlpha = 1.5; + defaultConstraintsSet.maxTravelTimeBeta = 10. * 60.; + defaultConstraintsSet.maxWaitTime = 600.; + defaultConstraintsSet.rejectRequestIfMaxWaitOrTravelTimeViolated = true; + defaultConstraintsSet.maxWalkDistance = 1000.; + drtWithShiftsConfigGroup.operationalScheme = DrtConfigGroup.OperationalScheme.door2door; + + drtWithShiftsConfigGroup.addParameterSet(new ExtensiveInsertionSearchParams()); + + ConfigGroup rebalancing = drtWithShiftsConfigGroup.createParameterSet("rebalancing"); + drtWithShiftsConfigGroup.addParameterSet(rebalancing); + ((RebalancingParams) rebalancing).interval = 600; + + MinCostFlowRebalancingStrategyParams strategyParams = new MinCostFlowRebalancingStrategyParams(); + strategyParams.targetAlpha = 0.3; + strategyParams.targetBeta = 0.3; + + drtWithShiftsConfigGroup.getRebalancingParams().get().addParameterSet(strategyParams); + + SquareGridZoneSystemParams zoneParams = new SquareGridZoneSystemParams(); + zoneParams.cellSize = 500.; + + DrtZoneSystemParams drtZoneSystemParams = new DrtZoneSystemParams(); + drtZoneSystemParams.addParameterSet(zoneParams); + drtWithShiftsConfigGroup.addParameterSet(drtZoneSystemParams); + + DvrpConfigGroup dvrpConfigGroup = new DvrpConfigGroup(); + DvrpTravelTimeMatrixParams matrixParams = dvrpConfigGroup.getTravelTimeMatrixParams(); + matrixParams.addParameterSet(zoneParams); + + multiModeDrtConfigGroup.addParameterSet(drtWithShiftsConfigGroup); + + final Config config = ConfigUtils.createConfig(multiModeDrtConfigGroup, + dvrpConfigGroup); + + Set modes = new HashSet<>(); + modes.add("drt"); + config.travelTimeCalculator().setAnalyzedModes(modes); + + ScoringConfigGroup.ModeParams scoreParams = new ScoringConfigGroup.ModeParams("drt"); + config.scoring().addModeParams(scoreParams); + ScoringConfigGroup.ModeParams scoreParams2 = new ScoringConfigGroup.ModeParams("walk"); + config.scoring().addModeParams(scoreParams2); + + final ScoringConfigGroup.ActivityParams start = new ScoringConfigGroup.ActivityParams("start"); + start.setScoringThisActivityAtAll(false); + final ScoringConfigGroup.ActivityParams end = new ScoringConfigGroup.ActivityParams("end"); + end.setScoringThisActivityAtAll(false); + + config.scoring().addActivityParams(start); + config.scoring().addActivityParams(end); + + config.qsim().setSimStarttimeInterpretation(QSimConfigGroup.StarttimeInterpretation.onlyUseStarttime); + config.qsim().setSimEndtimeInterpretation(QSimConfigGroup.EndtimeInterpretation.minOfEndtimeAndMobsimFinished); + + final ReplanningConfigGroup.StrategySettings stratSets = new ReplanningConfigGroup.StrategySettings(); + stratSets.setWeight(1); + stratSets.setStrategyName("ChangeExpBeta"); + config.replanning().addStrategySettings(stratSets); + + config.controller().setLastIteration(0); + config.controller().setWriteEventsInterval(1); + + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory("test/output/prebooking_shifts"); + + DrtOperationsParams operationsParams = (DrtOperationsParams) drtWithShiftsConfigGroup.createParameterSet(DrtOperationsParams.SET_NAME); + ShiftsParams shiftsParams = (ShiftsParams) operationsParams.createParameterSet(ShiftsParams.SET_NAME); + OperationFacilitiesParams operationFacilitiesParams = (OperationFacilitiesParams) operationsParams.createParameterSet(OperationFacilitiesParams.SET_NAME); + operationsParams.addParameterSet(shiftsParams); + operationsParams.addParameterSet(operationFacilitiesParams); + + shiftsParams.considerUpcomingShiftsForInsertion = true; + drtWithShiftsConfigGroup.addParameterSet(operationsParams); + + PrebookingParams prebookingParams = new PrebookingParams(); + prebookingParams.maximumPassengerDelay = 600; + prebookingParams.unschedulingMode = PrebookingParams.UnschedulingMode.Routing; + prebookingParams.scheduleWaitBeforeDrive = true; + drtWithShiftsConfigGroup.addParameterSet(prebookingParams); + + Scenario scenario = DrtControlerCreator.createScenarioWithDrtRouteFactory(config); + prepareNetwork(scenario); + preparePopulation(scenario); + + final Controler run = DrtOperationsControlerCreator.createControler(config, scenario, false); + prepareOperations(run, drtWithShiftsConfigGroup); + + run.addOverridingQSimModule(new PrebookingModeQSimModule(drtWithShiftsConfigGroup.getMode(), + prebookingParams)); + AttributeBasedPrebookingLogic.install(run, drtWithShiftsConfigGroup); + + Set> rejectedPersons = new HashSet<>(); + run.addOverridingModule(new AbstractModule() { + @Override + public void install() { + addEventHandlerBinding().toInstance((PassengerRequestRejectedEventHandler) event -> rejectedPersons.addAll(event.getPersonIds())); + } + }); + + run.run(); + + + Assertions.assertFalse(rejectedPersons.contains(Id.createPersonId(1))); + Assertions.assertTrue(rejectedPersons.contains(Id.createPersonId(2))); + Assertions.assertFalse(rejectedPersons.contains(Id.createPersonId(3))); + Assertions.assertTrue(rejectedPersons.contains(Id.createPersonId(4))); + } + + private void preparePopulation(Scenario scenario) { + Population population = scenario.getPopulation(); + PopulationFactory factory = PopulationUtils.getFactory(); + + //person 1 - prebooking submitted once shift is assigned (but not started) for time when shift should be active - ok + { + Person person = factory.createPerson(Id.createPersonId(1)); + Plan plan = factory.createPlan(); + Activity start = factory.createActivityFromLinkId("start", Id.createLinkId(1)); + start.setEndTime(5000); + start.getAttributes().putAttribute("prebooking:submissionTime" + "drt", 1800.); + start.getAttributes().putAttribute("prebooking:plannedDepartureTime" + "drt", 5000.); + plan.addActivity(start); + plan.addLeg(factory.createLeg("drt")); + plan.addActivity(factory.createActivityFromLinkId("end", Id.createLinkId(2))); + person.addPlan(plan); + population.addPerson(person); + } + + //person 2 - prebooking submitted before shift is assigned for time when shift should be active - rejected + { + Person person = factory.createPerson(Id.createPersonId(2)); + Plan plan = factory.createPlan(); + Activity start = factory.createActivityFromLinkId("start", Id.createLinkId(1)); + start.setEndTime(5000); + start.getAttributes().putAttribute("prebooking:submissionTime" + "drt", 900.); + start.getAttributes().putAttribute("prebooking:plannedDepartureTime" + "drt", 5000.); + plan.addActivity(start); + plan.addLeg(factory.createLeg("drt")); + plan.addActivity(factory.createActivityFromLinkId("end", Id.createLinkId(2))); + person.addPlan(plan); + population.addPerson(person); + } + + //person 3 - prebooking submitted during shift for time when shift should be active - ok + { + Person person = factory.createPerson(Id.createPersonId(3)); + Plan plan = factory.createPlan(); + Activity start = factory.createActivityFromLinkId("start", Id.createLinkId(1)); + start.setEndTime(5000); + start.getAttributes().putAttribute("prebooking:submissionTime" + "drt", 4000.); + start.getAttributes().putAttribute("prebooking:plannedDepartureTime" + "drt", 5000.); + plan.addActivity(start); + plan.addLeg(factory.createLeg("drt")); + plan.addActivity(factory.createActivityFromLinkId("end", Id.createLinkId(2))); + person.addPlan(plan); + population.addPerson(person); + } + + //person 4 - prebooking submitted during shift for time when shift should be ended - rejected + { + Person person = factory.createPerson(Id.createPersonId(4)); + Plan plan = factory.createPlan(); + Activity start = factory.createActivityFromLinkId("start", Id.createLinkId(1)); + start.setEndTime(8000); + start.getAttributes().putAttribute("prebooking:submissionTime" + "drt", 4000.); + start.getAttributes().putAttribute("prebooking:plannedDepartureTime" + "drt", 8000.); + plan.addActivity(start); + plan.addLeg(factory.createLeg("drt")); + plan.addActivity(factory.createActivityFromLinkId("end", Id.createLinkId(2))); + person.addPlan(plan); + population.addPerson(person); + } + } + + private static void prepareOperations(Controler run, DrtWithExtensionsConfigGroup drtWithShiftsConfigGroup) { + FleetSpecification fleetSpecification = new FleetSpecificationImpl(); + fleetSpecification.addVehicleSpecification(ImmutableDvrpVehicleSpecification.newBuilder() // + .id(Id.create("v1", DvrpVehicle.class)) // + .capacity(1) // + .serviceBeginTime(0.0) // + .serviceEndTime(24 * 3600) // + .startLinkId(Id.createLinkId(1)) // + .build()); + + OperationFacilitiesSpecification opFasSpecification = new OperationFacilitiesSpecificationImpl(); + opFasSpecification.addOperationFacilitySpecification(OperationFacilitySpecificationImpl + .newBuilder() + .capacity(1) + .type(OperationFacilityType.hub) + .coord(new Coord(1000, 1000)) + .linkId(Id.createLinkId(1)) + .id(Id.create(1, OperationFacility.class)) + .build()); + + DrtShiftsSpecification shiftsSpecification = new DrtShiftsSpecificationImpl(); + shiftsSpecification.addShiftSpecification(DrtShiftSpecificationImpl.newBuilder() + .start(3600) + .end(7200) + .id(Id.create(1, DrtShift.class)) + .operationFacility(Id.create(1, OperationFacility.class)) + .build() + ); + run.addOverridingModule(new AbstractDvrpModeModule(drtWithShiftsConfigGroup.getMode()) { + @Override + public void install() { + bindModal(FleetSpecification.class).toInstance(fleetSpecification); + bindModal(OperationFacilitiesSpecification.class).toInstance(opFasSpecification); + bindModal(DrtShiftsSpecification.class).toInstance(shiftsSpecification); + } + }); + + } + + private void prepareNetwork(Scenario scenario) { + Network network = scenario.getNetwork(); + Node node1 = NetworkUtils.createAndAddNode(network, Id.createNodeId(1), new Coord(0, 0)); + Node node2 = NetworkUtils.createAndAddNode(network, Id.createNodeId(2), new Coord(1000, 1000)); + + NetworkUtils.createAndAddLink(network, Id.createLinkId(1), node1, node2, CoordUtils.length(node2.getCoord()), 50 / 3.6, 100, 1, null, null); + NetworkUtils.createAndAddLink(network, Id.createLinkId(2), node2, node1, CoordUtils.length(node2.getCoord()), 50 / 3.6, 100, 1, null, null); + } + +} diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtControlerCreator.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtControlerCreator.java index ab438acc805..1b4435829f1 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtControlerCreator.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtControlerCreator.java @@ -60,11 +60,22 @@ public static Scenario createScenarioWithDrtRouteFactory(Config config) { * @return */ public static Controler createControler(Config config, boolean otfvis) { - MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); - DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.scoring(), config.routing()); - Scenario scenario = createScenarioWithDrtRouteFactory(config); ScenarioUtils.loadScenario(scenario); + return createControler(config, scenario, otfvis); + } + + /** + * Creates a controller in one step. + * + * @param config + * @param scenario + * @param otfvis + * @return + */ + public static Controler createControler(Config config, Scenario scenario, boolean otfvis) { + MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); + DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.scoring(), config.routing()); Controler controler = new Controler(scenario); controler.addOverridingModule(new DvrpModule()); From 4a5ad3fa7a3c1e41a442556ad524806d25bc9745 Mon Sep 17 00:00:00 2001 From: nkuehnel Date: Fri, 19 Jul 2024 15:05:48 +0200 Subject: [PATCH 058/101] cancel assigned shifts --- .../operations/shifts/dispatcher/DrtShiftDispatcherImpl.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java index 7cfa4579612..aeda75ba862 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java @@ -160,6 +160,7 @@ private void startShifts(double timeStep) { break; } else if (assignedShiftEntry.shift().getEndTime() < timeStep) { logger.warn("Too late to start shift " + assignedShiftEntry.shift().getId()); + shiftTaskScheduler.cancelAssignedShift(assignedShiftEntry.vehicle(), timeStep, assignedShiftEntry.shift()); assignedShiftEntry.vehicle().getShifts().remove(assignedShiftEntry.shift()); iterator.remove(); continue; @@ -185,7 +186,7 @@ private void assignShifts(double timeStep) { unscheduledShifts.removeIf(shift -> { if (shift.getStartTime() + drtShiftParams.maxUnscheduledShiftDelay < timeStep ) { logger.warn("Shift with ID " + shift.getId() + " could not be assigned and is being removed as start time is longer in the past than defined by maxUnscheduledShiftDelay."); - return true; + return true; } return false; }); From 7c2f4d213b8f0058a5d83a1048b0267e8cc7ae3e Mon Sep 17 00:00:00 2001 From: nkuehnel Date: Fri, 19 Jul 2024 17:35:38 +0200 Subject: [PATCH 059/101] add some documentation --- .../drt/extension/operations/README.md | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/README.md diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/README.md b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/README.md new file mode 100644 index 00000000000..9f7200cc257 --- /dev/null +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/README.md @@ -0,0 +1,72 @@ +# DRT Operations + +Provides functionality to realistically simulate operational aspects, +designed for, bot not limited to, non-autonomous services. + +Initially developed for MOIA GmbH + +If used, please cite: + +Felix Zwick, Nico Kuehnel, Sebastian Hörl. +Shifts in perspective: Operational aspects in (non-)autonomous +ride-pooling simulations. +Transportation Research Part A: Policy and Practice, +Volume 165, 2022, Pages 300-320. +https://doi.org/10.1016/j.tra.2022.09.001. + + +## Core features: + +- Operation facilities +- (Driver) shifts + + +The entry point for setting up a simulation are the specific control(l)er creators: +- DrtOperationsControlerCreator + - or +- EDrtOperationsControlerCreator + - in the electric vehicles case + +## Operation Facilities +Operation facilities are meant to represent hubs and in-field break locations. +The facilities have a capacity that cannot be exceeded and may be linked to +existing chargers via the id. + +(Driver) shifts may only start or end at operation facilities in the default setup. +Vehicles will route to operation facilities to end a shift or for scheduling a break. + +Operational facilities may be described with an xml file like this: +``` + + + + + + + + +``` + +## Shifts +Shifts define periods in which vehicles may be active serving passengers. +Shifts are dynamically assigned to vehicles. + +In autonomous settings, shifts may be used to model up- and down-time and/or cleaning +cycles. + +Shifts have a start and end time and can optionally have a break which is defined +by earliest start and latest end as well as a duration. Optionally, as operation +facility id may be defined to control the location of the start/end of the shift. + +Shifts may be described in an xml file likes this: +``` + + + + + + + + +``` + From 106766a42a240d268d02ba5bfb3536426b329b1b Mon Sep 17 00:00:00 2001 From: nkuehnel Date: Fri, 19 Jul 2024 17:37:06 +0200 Subject: [PATCH 060/101] shift drt maintenance --- .../dispatcher/DrtShiftDispatcherImpl.java | 68 +++++++++---------- .../scheduler/ShiftTaskSchedulerImpl.java | 6 +- 2 files changed, 37 insertions(+), 37 deletions(-) diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java index aeda75ba862..27bdeb5125d 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java @@ -140,12 +140,21 @@ private void checkBreaks() { for (ShiftEntry activeShift : activeShifts) { final DrtShift shift = activeShift.shift(); if (shift != null && shift.isStarted()) { - OperationFacility breakFacility = decideOnBreak(activeShift); - if (breakFacility != null) { - shiftTaskScheduler.relocateForBreak(activeShift.vehicle(), breakFacility, shift); - eventsManager.processEvent(new DrtShiftBreakScheduledEvent(timer.getTimeOfDay(), mode, shift.getId(), - activeShift.vehicle().getId(), breakFacility.getLinkId(), - shift.getBreak().orElseThrow().getScheduledLatestArrival())); + if (hasSchedulableBreak(shift, timer.getTimeOfDay())) { + Optional breakFacility = findBreakFacility(activeShift); + if (breakFacility.isPresent()) { + OperationFacility facility = breakFacility.get(); + if (facility.register(activeShift.vehicle().getId())) { + eventsManager.processEvent(new ShiftFacilityRegistrationEvent( + timer.getTimeOfDay(), mode, activeShift.vehicle().getId(), facility.getId())); + shiftTaskScheduler.relocateForBreak(activeShift.vehicle(), facility, shift); + eventsManager.processEvent(new DrtShiftBreakScheduledEvent(timer.getTimeOfDay(), mode, shift.getId(), + activeShift.vehicle().getId(), facility.getLinkId(), + shift.getBreak().orElseThrow().getScheduledLatestArrival())); + return; + } + } + throw new RuntimeException("Could not schedule break!"); } } } @@ -188,7 +197,7 @@ private void assignShifts(double timeStep) { logger.warn("Shift with ID " + shift.getId() + " could not be assigned and is being removed as start time is longer in the past than defined by maxUnscheduledShiftDelay."); return true; } - return false; + return false; }); // Assign shifts @@ -440,37 +449,28 @@ private void scheduleShiftEnd(ShiftEntry endingShift) { } } - private OperationFacility decideOnBreak(ShiftEntry activeShift) { + private Optional findBreakFacility(ShiftEntry activeShift) { if (activeShift.shift() != null) { - if (hasSchedulableBreak(activeShift.shift(), timer.getTimeOfDay())) { - final Schedule schedule = activeShift.vehicle().getSchedule(); - Task currentTask = schedule.getCurrentTask(); - Link lastLink; - if (currentTask instanceof DriveTask - && currentTask.getTaskType().equals(EmptyVehicleRelocator.RELOCATE_VEHICLE_TASK_TYPE) - && currentTask.equals(schedule.getTasks().get(schedule.getTaskCount()-2))) { - LinkTimePair start = ((OnlineDriveTaskTracker) currentTask.getTaskTracker()).getDiversionPoint(); - if(start != null) { - lastLink = start.link; - } else { - lastLink = ((DriveTask) currentTask).getPath().getToLink(); - } - } else { - lastLink = ((DrtStayTask) schedule.getTasks() - .get(schedule.getTaskCount() - 1)).getLink(); - } - final OperationFacility shiftBreakFacility = breakFacilityFinder.findFacility(lastLink.getCoord()); - if (shiftBreakFacility == null) { - throw new RuntimeException("Could not schedule break!"); - } - if (shiftBreakFacility.register(activeShift.vehicle().getId())) { - eventsManager.processEvent(new ShiftFacilityRegistrationEvent(timer.getTimeOfDay(), - mode, activeShift.vehicle().getId(), shiftBreakFacility.getId())); - return shiftBreakFacility; + final Schedule schedule = activeShift.vehicle().getSchedule(); + Task currentTask = schedule.getCurrentTask(); + Link lastLink; + if (currentTask instanceof DriveTask + && currentTask.getTaskType().equals(EmptyVehicleRelocator.RELOCATE_VEHICLE_TASK_TYPE) + && currentTask.equals(schedule.getTasks().get(schedule.getTaskCount()-2))) { + LinkTimePair start = ((OnlineDriveTaskTracker) currentTask.getTaskTracker()).getDiversionPoint(); + if(start != null) { + lastLink = start.link; + } else { + lastLink = ((DriveTask) currentTask).getPath().getToLink(); } + } else { + lastLink = ((DrtStayTask) schedule.getTasks() + .get(schedule.getTaskCount() - 1)).getLink(); } + final OperationFacility shiftBreakFacility = breakFacilityFinder.findFacility(lastLink.getCoord()); + return Optional.of(shiftBreakFacility); } - return null; + return Optional.empty(); } @Override diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskSchedulerImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskSchedulerImpl.java index 0cb820990b2..94b5c3d0fed 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskSchedulerImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskSchedulerImpl.java @@ -92,7 +92,7 @@ public void relocateForBreak(ShiftDvrpVehicle vehicle, OperationFacility breakFa double startTime = path.getArrivalTime(); double endTime = startTime + shift.getBreak().orElseThrow().getDuration(); - double latestDetourArrival = path.getDepartureTime() + path.getTravelTime() + 1.5; + double latestDetourArrival = path.getDepartureTime() + path.getTravelTime() * 1.5; relocateForBreakImpl(vehicle, startTime, endTime, latestDetourArrival, toLink, shift, breakFacility); } else { @@ -153,10 +153,10 @@ private void relocateForBreakImpl(ShiftDvrpVehicle vehicle, double startTime, do // append SHIFT_BREAK task DrtShiftBreak shiftBreak = shift.getBreak().orElseThrow(); - ShiftBreakTask dropoffStopTask = taskFactory.createShiftBreakTask(vehicle, startTime, + ShiftBreakTask shiftBreakTask = taskFactory.createShiftBreakTask(vehicle, startTime, endTime, link, shiftBreak, breakFacility); - schedule.addTask(dropoffStopTask); + schedule.addTask(shiftBreakTask); schedule.addTask(taskFactory.createStayTask(vehicle, endTime, shift.getEndTime(), link)); From c7a9904df8156dfc88481610bd909f2605f6aaff Mon Sep 17 00:00:00 2001 From: nkuehnel Date: Fri, 19 Jul 2024 17:55:32 +0200 Subject: [PATCH 061/101] some more drt shift maintenance --- ...stOperationFacilityWithCapacityFinder.java | 9 ++- .../OperationFacilityFinder.java | 6 +- .../dispatcher/DrtShiftDispatcherImpl.java | 78 +++++++++---------- 3 files changed, 46 insertions(+), 47 deletions(-) diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/NearestOperationFacilityWithCapacityFinder.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/NearestOperationFacilityWithCapacityFinder.java index 1df98354824..7d41752548e 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/NearestOperationFacilityWithCapacityFinder.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/NearestOperationFacilityWithCapacityFinder.java @@ -4,6 +4,7 @@ import org.matsim.contrib.common.util.DistanceUtils; import java.util.Comparator; +import java.util.Optional; import java.util.function.Predicate; /** @@ -21,7 +22,7 @@ public NearestOperationFacilityWithCapacityFinder(OperationFacilities operationF } @Override - public OperationFacility findFacilityOfType(Coord coord, OperationFacilityType type) { + public Optional findFacilityOfType(Coord coord, OperationFacilityType type) { Predicate filter; switch (type) { case hub: @@ -37,15 +38,15 @@ public OperationFacility findFacilityOfType(Coord coord, OperationFacilityType t .filter(filter) .filter(OperationFacility::hasCapacity) .min(Comparator.comparing( - f -> DistanceUtils.calculateSquaredDistance(coord, f.getCoord()))).orElse(null); + f -> DistanceUtils.calculateSquaredDistance(coord, f.getCoord()))); } @Override - public OperationFacility findFacility(Coord coord) { + public Optional findFacility(Coord coord) { return operationFacilities.getDrtOperationFacilities().values().stream() .filter(OperationFacility::hasCapacity) .min(Comparator.comparing( - f -> DistanceUtils.calculateSquaredDistance(coord, f.getCoord()))).orElse(null); + f -> DistanceUtils.calculateSquaredDistance(coord, f.getCoord()))); } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/OperationFacilityFinder.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/OperationFacilityFinder.java index 8262f5938f5..469f7f3703b 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/OperationFacilityFinder.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/OperationFacilityFinder.java @@ -2,12 +2,14 @@ import org.matsim.api.core.v01.Coord; +import java.util.Optional; + /** * @author nkuehnel / MOIA */ public interface OperationFacilityFinder { - OperationFacility findFacilityOfType(Coord coord, OperationFacilityType type); + Optional findFacilityOfType(Coord coord, OperationFacilityType type); - OperationFacility findFacility(Coord coord); + Optional findFacility(Coord coord); } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java index 27bdeb5125d..5d983e81f05 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java @@ -370,23 +370,25 @@ private void updateShiftEnd(ShiftEntry next) { } } - final OperationFacility shiftChangeFacility; + final Optional maybeFacility; if (drtShiftParams.allowInFieldChangeover) { - shiftChangeFacility = breakFacilityFinder.findFacility(start.link.getCoord()); + maybeFacility = breakFacilityFinder.findFacility(start.link.getCoord()); } else { - shiftChangeFacility = breakFacilityFinder.findFacilityOfType(start.link.getCoord(), + maybeFacility = breakFacilityFinder.findFacilityOfType(start.link.getCoord(), OperationFacilityType.hub); } - if (shiftChangeFacility != null && changeOverTask != null - && !(shiftChangeFacility.getId().equals(changeOverTask.getFacility().getId()))) { - if (shiftChangeFacility.hasCapacity()) { - if (shiftTaskScheduler.updateShiftChange(next.vehicle(), - network.getLinks().get(shiftChangeFacility.getLinkId()), next.shift(), start, - shiftChangeFacility, lastTask)) { - shiftChangeFacility.register(next.vehicle().getId()); - changeOverTask.getFacility().deregisterVehicle(next.vehicle().getId()); - eventsManager.processEvent(new ShiftFacilityRegistrationEvent(timer.getTimeOfDay(), - mode, next.vehicle().getId(), shiftChangeFacility.getId())); + if (maybeFacility.isPresent()) { + OperationFacility shiftChangeFacility = maybeFacility.get(); + if(changeOverTask != null && !(shiftChangeFacility.getId().equals(changeOverTask.getFacility().getId()))) { + if (shiftChangeFacility.hasCapacity()) { + if (shiftTaskScheduler.updateShiftChange(next.vehicle(), + network.getLinks().get(shiftChangeFacility.getLinkId()), next.shift(), start, + shiftChangeFacility, lastTask)) { + shiftChangeFacility.register(next.vehicle().getId()); + changeOverTask.getFacility().deregisterVehicle(next.vehicle().getId()); + eventsManager.processEvent(new ShiftFacilityRegistrationEvent(timer.getTimeOfDay(), + mode, next.vehicle().getId(), shiftChangeFacility.getId())); + } } } } @@ -436,41 +438,35 @@ private void scheduleShiftEnd(ShiftEntry endingShift) { if(shiftChangeoverFacility == null) { shiftChangeoverFacility = breakFacilityFinder.findFacilityOfType(coord, - OperationFacilityType.hub); + OperationFacilityType.hub).orElseThrow(() -> new RuntimeException("Could not find shift end location!")); } - if (shiftChangeoverFacility != null && shiftChangeoverFacility.register(endingShift.vehicle().getId())) { - shiftTaskScheduler.relocateForShiftChange(endingShift.vehicle(), - network.getLinks().get(shiftChangeoverFacility.getLinkId()), endingShift.shift(), shiftChangeoverFacility); - eventsManager.processEvent(new ShiftFacilityRegistrationEvent(timer.getTimeOfDay(), mode, endingShift.vehicle().getId(), - shiftChangeoverFacility.getId())); - } else { - throw new RuntimeException("Could not find shift end location!"); - } + Verify.verify(shiftChangeoverFacility.register(endingShift.vehicle().getId()), "Could not register vehicle at facility."); + + shiftTaskScheduler.relocateForShiftChange(endingShift.vehicle(), + network.getLinks().get(shiftChangeoverFacility.getLinkId()), endingShift.shift(), shiftChangeoverFacility); + eventsManager.processEvent(new ShiftFacilityRegistrationEvent(timer.getTimeOfDay(), mode, endingShift.vehicle().getId(), + shiftChangeoverFacility.getId())); } private Optional findBreakFacility(ShiftEntry activeShift) { - if (activeShift.shift() != null) { - final Schedule schedule = activeShift.vehicle().getSchedule(); - Task currentTask = schedule.getCurrentTask(); - Link lastLink; - if (currentTask instanceof DriveTask - && currentTask.getTaskType().equals(EmptyVehicleRelocator.RELOCATE_VEHICLE_TASK_TYPE) - && currentTask.equals(schedule.getTasks().get(schedule.getTaskCount()-2))) { - LinkTimePair start = ((OnlineDriveTaskTracker) currentTask.getTaskTracker()).getDiversionPoint(); - if(start != null) { - lastLink = start.link; - } else { - lastLink = ((DriveTask) currentTask).getPath().getToLink(); - } - } else { - lastLink = ((DrtStayTask) schedule.getTasks() - .get(schedule.getTaskCount() - 1)).getLink(); + final Schedule schedule = activeShift.vehicle().getSchedule(); + Task currentTask = schedule.getCurrentTask(); + Link lastLink; + if (currentTask instanceof DriveTask + && currentTask.getTaskType().equals(EmptyVehicleRelocator.RELOCATE_VEHICLE_TASK_TYPE) + && currentTask.equals(schedule.getTasks().get(schedule.getTaskCount()-2))) { + LinkTimePair start = ((OnlineDriveTaskTracker) currentTask.getTaskTracker()).getDiversionPoint(); + if(start != null) { + lastLink = start.link; + } else { + lastLink = ((DriveTask) currentTask).getPath().getToLink(); } - final OperationFacility shiftBreakFacility = breakFacilityFinder.findFacility(lastLink.getCoord()); - return Optional.of(shiftBreakFacility); + } else { + lastLink = ((DrtStayTask) schedule.getTasks() + .get(schedule.getTaskCount() - 1)).getLink(); } - return Optional.empty(); + return breakFacilityFinder.findFacility(lastLink.getCoord()); } @Override From 6dc04214fed5b5b2d8e09e84dea63c2ed47cd8c2 Mon Sep 17 00:00:00 2001 From: nkuehnel Date: Fri, 19 Jul 2024 19:30:22 +0200 Subject: [PATCH 062/101] consider break corridors for (pre)bookings --- .../ShiftInsertionCostCalculator.java | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/insertion/ShiftInsertionCostCalculator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/insertion/ShiftInsertionCostCalculator.java index 7055e4569be..d6b3c978146 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/insertion/ShiftInsertionCostCalculator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/insertion/ShiftInsertionCostCalculator.java @@ -3,6 +3,7 @@ import org.matsim.contrib.drt.extension.operations.shifts.fleet.ShiftDvrpVehicle; import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftBreakTask; import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftChangeOverTask; +import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShift; import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftBreak; import org.matsim.contrib.drt.optimizer.VehicleEntry; import org.matsim.contrib.drt.optimizer.Waypoint; @@ -44,7 +45,8 @@ boolean checkShiftTimeConstraintsForScheduledRequests(Insertion insertion, Detou final int pickupIdx = insertion.pickup.index; final int dropoffIdx = insertion.dropoff.index; - double shiftEndTime = ((ShiftDvrpVehicle) vEntry.vehicle).getShifts().peek().getEndTime(); + DrtShift currentShift = ((ShiftDvrpVehicle) vEntry.vehicle).getShifts().peek(); + double shiftEndTime = currentShift.getEndTime(); if(shiftEndTime < detourTimeInfo.dropoffDetourInfo.arrivalTime) { // fast fail which also captures requests that are prebooked for times outside of the shift. return false; @@ -118,6 +120,31 @@ boolean checkShiftTimeConstraintsForScheduledRequests(Insertion insertion, Detou return false; } } + + + // avoid shrinking break corridor too much (rather coarse for now) + if(currentShift.getBreak().isPresent()) { + DrtShiftBreak drtShiftBreak = currentShift.getBreak().get(); + if(!drtShiftBreak.isScheduled()) { + + + if(detourTimeInfo.dropoffDetourInfo.arrivalTime < drtShiftBreak.getEarliestBreakStartTime()) { + // insertion finished before break corridor + //ok + } else if(detourTimeInfo.pickupDetourInfo.departureTime > drtShiftBreak.getLatestBreakEndTime()) { + // insertion start after break corridor + //ok + } else { + double remainingTime = drtShiftBreak.getLatestBreakEndTime() - detourTimeInfo.dropoffDetourInfo.arrivalTime; + if (remainingTime < drtShiftBreak.getDuration()) { + // no meaningful break possible after insertion + // (there could still be enough time before a prebooking though) + return false; + } + } + } + } + return true; //all time constraints of all stops are satisfied } } From 6f8d84143ffc936023c51359d773ace983e8699a Mon Sep 17 00:00:00 2001 From: nkuehnel Date: Fri, 19 Jul 2024 19:30:40 +0200 Subject: [PATCH 063/101] consider break corridors for (pre)bookings --- .../run/RunPrebookingShiftDrtScenarioIT.java | 43 ++++++++++++++++--- 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunPrebookingShiftDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunPrebookingShiftDrtScenarioIT.java index fa6ad3cb0ce..5babef611b3 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunPrebookingShiftDrtScenarioIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunPrebookingShiftDrtScenarioIT.java @@ -16,10 +16,7 @@ import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; import org.matsim.contrib.drt.extension.operations.operationFacilities.*; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; -import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShift; -import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftSpecificationImpl; -import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftsSpecification; -import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftsSpecificationImpl; +import org.matsim.contrib.drt.extension.operations.shifts.shift.*; import org.matsim.contrib.drt.optimizer.constraints.DefaultDrtOptimizationConstraintsSet; import org.matsim.contrib.drt.optimizer.insertion.extensive.ExtensiveInsertionSearchParams; import org.matsim.contrib.drt.optimizer.rebalancing.RebalancingParams; @@ -146,6 +143,7 @@ void test() { operationsParams.addParameterSet(operationFacilitiesParams); shiftsParams.considerUpcomingShiftsForInsertion = true; + shiftsParams.shiftEndLookAhead = 900.; drtWithShiftsConfigGroup.addParameterSet(operationsParams); PrebookingParams prebookingParams = new PrebookingParams(); @@ -180,6 +178,8 @@ public void install() { Assertions.assertTrue(rejectedPersons.contains(Id.createPersonId(2))); Assertions.assertFalse(rejectedPersons.contains(Id.createPersonId(3))); Assertions.assertTrue(rejectedPersons.contains(Id.createPersonId(4))); + Assertions.assertFalse(rejectedPersons.contains(Id.createPersonId(5))); + Assertions.assertTrue(rejectedPersons.contains(Id.createPersonId(6))); } private void preparePopulation(Scenario scenario) { @@ -238,7 +238,37 @@ private void preparePopulation(Scenario scenario) { Activity start = factory.createActivityFromLinkId("start", Id.createLinkId(1)); start.setEndTime(8000); start.getAttributes().putAttribute("prebooking:submissionTime" + "drt", 4000.); - start.getAttributes().putAttribute("prebooking:plannedDepartureTime" + "drt", 8000.); + start.getAttributes().putAttribute("prebooking:plannedDepartureTime" + "drt", 11000.); + plan.addActivity(start); + plan.addLeg(factory.createLeg("drt")); + plan.addActivity(factory.createActivityFromLinkId("end", Id.createLinkId(2))); + person.addPlan(plan); + population.addPerson(person); + } + + //person 5 - prebooking submitted during shift for time which falls into break beginning of break corridor with enough remaining time - ok + { + Person person = factory.createPerson(Id.createPersonId(5)); + Plan plan = factory.createPlan(); + Activity start = factory.createActivityFromLinkId("start", Id.createLinkId(1)); + start.setEndTime(6000.); + start.getAttributes().putAttribute("prebooking:submissionTime" + "drt", 4000.); + start.getAttributes().putAttribute("prebooking:plannedDepartureTime" + "drt", 6000.); + plan.addActivity(start); + plan.addLeg(factory.createLeg("drt")); + plan.addActivity(factory.createActivityFromLinkId("end", Id.createLinkId(2))); + person.addPlan(plan); + population.addPerson(person); + } + + //person 6 - prebooking submitted during shift for time which would preclude meaningful break - rejected + { + Person person = factory.createPerson(Id.createPersonId(6)); + Plan plan = factory.createPlan(); + Activity start = factory.createActivityFromLinkId("start", Id.createLinkId(1)); + start.setEndTime(6500.); + start.getAttributes().putAttribute("prebooking:submissionTime" + "drt", 4000.); + start.getAttributes().putAttribute("prebooking:plannedDepartureTime" + "drt", 6500.); plan.addActivity(start); plan.addLeg(factory.createLeg("drt")); plan.addActivity(factory.createActivityFromLinkId("end", Id.createLinkId(2))); @@ -270,8 +300,9 @@ private static void prepareOperations(Controler run, DrtWithExtensionsConfigGrou DrtShiftsSpecification shiftsSpecification = new DrtShiftsSpecificationImpl(); shiftsSpecification.addShiftSpecification(DrtShiftSpecificationImpl.newBuilder() .start(3600) - .end(7200) + .end(10800) .id(Id.create(1, DrtShift.class)) + .shiftBreak(DrtShiftBreakSpecificationImpl.newBuilder().duration(600.).earliestStart(6000.).latestEnd(7000.).build()) .operationFacility(Id.create(1, OperationFacility.class)) .build() ); From ef5de1771ba18773455e8702e0c7c73241d39721 Mon Sep 17 00:00:00 2001 From: nkuehnel Date: Fri, 19 Jul 2024 19:31:04 +0200 Subject: [PATCH 064/101] clean up obsolete method --- .../operations/shifts/shift/DefaultShiftBreakImpl.java | 5 ----- .../drt/extension/operations/shifts/shift/DrtShiftBreak.java | 2 -- 2 files changed, 7 deletions(-) diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/shift/DefaultShiftBreakImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/shift/DefaultShiftBreakImpl.java index 07b094f3dc0..10f36a1d387 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/shift/DefaultShiftBreakImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/shift/DefaultShiftBreakImpl.java @@ -54,9 +54,4 @@ public boolean isScheduled() { public double getScheduledLatestArrival() { return latestArrivalTime; } - - @Override - public void reset() { - this.latestArrivalTime = UNSCHEDULED_ARRIVAL_TIME; - } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/shift/DrtShiftBreak.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/shift/DrtShiftBreak.java index 2009dcd02f6..86e5500401a 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/shift/DrtShiftBreak.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/shift/DrtShiftBreak.java @@ -16,6 +16,4 @@ public interface DrtShiftBreak { boolean isScheduled(); double getScheduledLatestArrival(); - - void reset(); } From 2d4f1d7f540fece86cdd7f5e544e6da30050d5a3 Mon Sep 17 00:00:00 2001 From: nkuehnel Date: Tue, 23 Jul 2024 10:59:16 +0200 Subject: [PATCH 065/101] update FISS test, reduce iterations to reduce runtime --- .../contrib/drt/extension/fiss/RunFissDrtScenarioIT.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java index 2da1b30b225..fc58f3b3b63 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java @@ -135,7 +135,7 @@ void test() { stratSets.setStrategyName("ChangeExpBeta"); config.replanning().addStrategySettings(stratSets); - config.controller().setLastIteration(2); + config.controller().setLastIteration(1); config.controller().setWriteEventsInterval(1); config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); @@ -184,7 +184,7 @@ public void install() { } run.run(); - Assertions.assertEquals(23817, linkCounter.getLinkLeaveCount()); + Assertions.assertEquals(20842, linkCounter.getLinkLeaveCount()); } static class LinkCounter implements LinkLeaveEventHandler { From f55bf9300deb756822267b3dbbd46c7a76331a39 Mon Sep 17 00:00:00 2001 From: nkuehnel Date: Tue, 23 Jul 2024 11:59:24 +0200 Subject: [PATCH 066/101] avoid abandoning prebooked requests twice in the same time step --- .../contrib/drt/prebooking/PrebookingStopActivity.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingStopActivity.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingStopActivity.java index 762c80500b1..fd81c1745f3 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingStopActivity.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingStopActivity.java @@ -73,14 +73,14 @@ public PrebookingStopActivity(PassengerHandler passengerHandler, DynAgent driver @Override protected boolean isLastStep(double now) { boolean dropoffsReady = updateDropoffRequests(now); - boolean pickupsReady = updatePickupRequests(now); + boolean pickupsReady = updatePickupRequests(now, false); return pickupsReady && dropoffsReady && now >= endTime.get(); } @Override protected void beforeFirstStep(double now) { initDropoffRequests(now); - updatePickupRequests(now); + updatePickupRequests(now, true); } private void initDropoffRequests(double now) { @@ -112,7 +112,7 @@ public int compareTo(QueuedRequest o) { } } - private boolean updatePickupRequests(double now) { + private boolean updatePickupRequests(double now, boolean isFirstStep) { var pickupIterator = pickupRequests.values().iterator(); while (pickupIterator.hasNext()) { @@ -125,7 +125,7 @@ private boolean updatePickupRequests(double now) { if (passengerHandler.notifyWaitForPassengers(this, this.driver, request.getId())) { // agent starts to enter queuePickup(request, now); - } else if (now > request.getEarliestStartTime()) { + } else if (now > request.getEarliestStartTime() && !isFirstStep) { if (abandonVoter.abandonRequest(now, vehicle, request)) { prebookingManager.abandon(request.getId()); } From f684d07f5e47b94e2662c5fea010950d081109ee Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 11:40:49 +0200 Subject: [PATCH 067/101] remove redundant suppression --- .../org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java | 1 - 1 file changed, 1 deletion(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java index f7107ece5f0..e64ef90be51 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java @@ -187,7 +187,6 @@ public DetailedVsAverageLookupBehavior getDetailedVsAverageLookupBehavior() { // =============== /** * @param hbefaTableConsistencyCheckingLevel -- {@value #HBEFA_TABLE_CONSISTENCY_CHECKING_LEVEL} - * @noinspection JavadocReference */ @StringSetter(HBEFA_TABLE_CONSISTENCY_CHECKING_LEVEL) public void setHbefaTableConsistencyCheckingLevel(HbefaTableConsistencyCheckingLevel hbefaTableConsistencyCheckingLevel) { From 95af12573ebfba5d8dba842e8758c73787ae5ad6 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 11:53:00 +0200 Subject: [PATCH 068/101] remove unused field --- .../contrib/emissions/TestHbefaColdEmissionFactorKey.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java index 13efc7bf890..2248230ae87 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java @@ -43,7 +43,6 @@ public class TestHbefaColdEmissionFactorKey { private Pollutant coldPollutant; private HbefaVehicleAttributes hbefaVehicleAttributes; private HbefaVehicleCategory hbefaVehCategory; - private boolean equalErr; private HbefaColdEmissionFactorKey normal; private void setUp(){ @@ -56,7 +55,6 @@ private void setUp(){ parkingTime = 5; coldPollutant = FC; hbefaVehCategory = HbefaVehicleCategory.PASSENGER_CAR; - equalErr = false; } From f7540709b02b20bbda3ed6a90d3af171f46f7289 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 11:57:19 +0200 Subject: [PATCH 069/101] internal renaming --- .../events/TestWarmEmissionEventImpl.java | 77 +++++++++---------- 1 file changed, 38 insertions(+), 39 deletions(-) diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java index 62691c3670f..2d378543e90 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java @@ -42,55 +42,54 @@ public class TestWarmEmissionEventImpl { - + private final Id vehicleId = Id.create("veh 1", Vehicle.class); private final Id linkId = Id.create("link 1", Link.class); - private final Double co = 20.; - private final Double c2 = 8.; - private final Double fc = 30.; - private final Double hc=4.; - private final Double nm=5.; - private final Double n2=6.; - private final Double nx=7.; - private final Double pm=8.; - private final Double so=1.6; -// private final Set pollutants = new HashSet<>(Arrays.asList(CO, CO2_TOTAL, FC, HC, NMHC, NOx, NO2,PM, SO2)); + private final Double co_value = 20.; + private final Double co2total_value = 8.; + private final Double fc_value = 30.; + private final Double hc_value =4.; + private final Double nmhc_value =5.; + private final Double no2_value =6.; + private final Double nox_value =7.; + private final Double pm_value =8.; + private final Double so2_value =1.6; private final Set pollutants = new HashSet<>( Arrays.asList( Pollutant.values() ) ); @Test final void testGetAttributesForCompleteEmissionMaps(){ //test normal functionality - + //create a normal event impl Map warmEmissionsMap = new HashMap<>(); - warmEmissionsMap.put(CO, co ); - warmEmissionsMap.put(CO2_TOTAL, c2 ); - warmEmissionsMap.put(FC, fc ); - warmEmissionsMap.put(HC, hc ); - warmEmissionsMap.put(NMHC, nm ); - warmEmissionsMap.put(NO2, n2 ); - warmEmissionsMap.put(NOx, nx ); - warmEmissionsMap.put(PM, pm ); - warmEmissionsMap.put(SO2, so ); + warmEmissionsMap.put(CO, co_value); + warmEmissionsMap.put(CO2_TOTAL, co2total_value); + warmEmissionsMap.put(FC, fc_value); + warmEmissionsMap.put(HC, hc_value); + warmEmissionsMap.put(NMHC, nmhc_value); + warmEmissionsMap.put(NO2, no2_value); + warmEmissionsMap.put(NOx, nox_value); + warmEmissionsMap.put(PM, pm_value); + warmEmissionsMap.put(SO2, so2_value); Map map = new LinkedHashMap<>(); warmEmissionsMap.forEach( (key,value) -> map.put( key, value ) ); // (this could be made more direct) WarmEmissionEvent we = new WarmEmissionEvent(0.0, linkId, vehicleId, map); - + Map weg = we.getAttributes(); - Assertions.assertEquals(Double.parseDouble(weg.get(CO.name())), co, MatsimTestUtils.EPSILON, "the CO value of this warm emission event was "+ Double.parseDouble(weg.get(CO.name()))+ "but should have been "+ co); - Assertions.assertEquals(Double.parseDouble(weg.get(CO2_TOTAL.name())), c2, MatsimTestUtils.EPSILON, "the CO2 value of this warm emission event was "+ Double.parseDouble(weg.get(CO2_TOTAL.name()))+ "but should have been "+ c2); - Assertions.assertEquals(Double.parseDouble(weg.get(FC.name())), fc, MatsimTestUtils.EPSILON, "the FC value of this warm emission event was "+ Double.parseDouble(weg.get(FC.name()))+ "but should have been "+ fc); - Assertions.assertEquals(Double.parseDouble(weg.get(HC.name())), hc, MatsimTestUtils.EPSILON, "the HC value of this warm emission event was "+ Double.parseDouble(weg.get(HC.name()))+ "but should have been "+ hc); - Assertions.assertEquals(Double.parseDouble(weg.get(NMHC.name())), nm, MatsimTestUtils.EPSILON, "the NMHC value of this warm emission event was "+ Double.parseDouble(weg.get(NMHC.name()))+ "but should have been "+ nm); - Assertions.assertEquals(Double.parseDouble(weg.get(NO2.name())), n2, MatsimTestUtils.EPSILON, "the NO2 value of this warm emission event was "+ Double.parseDouble(weg.get(NO2.name()))+ "but should have been "+ n2); - Assertions.assertEquals(Double.parseDouble(weg.get(NOx.name())), nx, MatsimTestUtils.EPSILON, "the NOx value of this warm emission event was "+ Double.parseDouble(weg.get(NOx.name()))+ "but should have been "+ nx); - Assertions.assertEquals(Double.parseDouble(weg.get(PM.name())), pm, MatsimTestUtils.EPSILON, "the PM value of this warm emission event was "+ Double.parseDouble(weg.get(PM.name()))+ "but should have been "+ pm); - Assertions.assertEquals(Double.parseDouble(weg.get(SO2.name())), so, MatsimTestUtils.EPSILON, "the SO2 value of this warm emission event was "+ Double.parseDouble(weg.get(SO2.name()))+ "but should have been "+ so); + Assertions.assertEquals(Double.parseDouble(weg.get(CO.name())), co_value, MatsimTestUtils.EPSILON, "the CO value of this warm emission event was "+ Double.parseDouble(weg.get(CO.name()))+ "but should have been "+ co_value); + Assertions.assertEquals(Double.parseDouble(weg.get(CO2_TOTAL.name())), co2total_value, MatsimTestUtils.EPSILON, "the CO2 value of this warm emission event was "+ Double.parseDouble(weg.get(CO2_TOTAL.name()))+ "but should have been "+ co2total_value); + Assertions.assertEquals(Double.parseDouble(weg.get(FC.name())), fc_value, MatsimTestUtils.EPSILON, "the FC value of this warm emission event was "+ Double.parseDouble(weg.get(FC.name()))+ "but should have been "+ fc_value); + Assertions.assertEquals(Double.parseDouble(weg.get(HC.name())), hc_value, MatsimTestUtils.EPSILON, "the HC value of this warm emission event was "+ Double.parseDouble(weg.get(HC.name()))+ "but should have been "+ hc_value); + Assertions.assertEquals(Double.parseDouble(weg.get(NMHC.name())), nmhc_value, MatsimTestUtils.EPSILON, "the NMHC value of this warm emission event was "+ Double.parseDouble(weg.get(NMHC.name()))+ "but should have been "+ nmhc_value); + Assertions.assertEquals(Double.parseDouble(weg.get(NO2.name())), no2_value, MatsimTestUtils.EPSILON, "the NO2 value of this warm emission event was "+ Double.parseDouble(weg.get(NO2.name()))+ "but should have been "+ no2_value); + Assertions.assertEquals(Double.parseDouble(weg.get(NOx.name())), nox_value, MatsimTestUtils.EPSILON, "the NOx value of this warm emission event was "+ Double.parseDouble(weg.get(NOx.name()))+ "but should have been "+ nox_value); + Assertions.assertEquals(Double.parseDouble(weg.get(PM.name())), pm_value, MatsimTestUtils.EPSILON, "the PM value of this warm emission event was "+ Double.parseDouble(weg.get(PM.name()))+ "but should have been "+ pm_value); + Assertions.assertEquals(Double.parseDouble(weg.get(SO2.name())), so2_value, MatsimTestUtils.EPSILON, "the SO2 value of this warm emission event was "+ Double.parseDouble(weg.get(SO2.name()))+ "but should have been "+ so2_value); } @Test @@ -98,12 +97,12 @@ final void testGetAttributesForIncompleteMaps(){ //the getAttributesMethod should // - return null if the emission map is empty // - throw NullPointerExceptions if the emission values are not set - // - throw NullPointerExceptions if no emission map is assigned - + // - throw NullPointerExceptions if no emission map is assigned + //empty map Map emptyMap = new HashMap<>(); WarmEmissionEvent emptyMapEvent = new WarmEmissionEvent(22., linkId, vehicleId, emptyMap); - + //values not set Map valuesNotSet = new HashMap<>(); valuesNotSet.put(CO, null); @@ -119,20 +118,20 @@ final void testGetAttributesForIncompleteMaps(){ // (this could be made more direct) WarmEmissionEvent valuesNotSetEvent = new WarmEmissionEvent(44., linkId, vehicleId, map); - + //no map WarmEmissionEvent noMap = new WarmEmissionEvent(23, linkId, vehicleId, null); - + int numberOfWarmPollutants = pollutants.size(); int valuesNotSetNullPointers =0, noMapNullPointers=0; - + for( Pollutant wpEnum : pollutants){ String wp=wpEnum.name(); //empty map Assertions.assertNull(emptyMapEvent.getAttributes().get(wp)); - + //values not set try{ valuesNotSetEvent.getAttributes().get(wp); @@ -140,7 +139,7 @@ final void testGetAttributesForIncompleteMaps(){ catch(NullPointerException e){ valuesNotSetNullPointers++; } - + //no map try{ noMap.getAttributes().get(wp); From 50daf7da200480f15eeee0d3b9ce86ca33a2df70 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:00:12 +0200 Subject: [PATCH 070/101] remove unnecessary toString() calls --- .../emissions/ColdEmissionAnalysisModule.java | 4 +-- .../TestColdEmissionAnalysisModuleCase1.java | 6 ++-- .../TestColdEmissionAnalysisModuleCase2.java | 22 ++++++------ .../TestColdEmissionAnalysisModuleCase3.java | 36 +++++++++---------- .../TestColdEmissionAnalysisModuleCase4.java | 30 ++++++++-------- .../TestColdEmissionAnalysisModuleCase6.java | 28 +++++++-------- .../TestHbefaColdEmissionFactorKey.java | 16 ++++----- .../emissions/TestHbefaVehicleAttributes.java | 12 +++---- .../TestHbefaWarmEmissionFactorKey.java | 36 +++++++++---------- .../analysis/EmissionGridAnalyzerTest.java | 18 +++++----- 10 files changed, 104 insertions(+), 104 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java index 45013b10201..4e058d47451 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java @@ -17,7 +17,7 @@ * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * - * + * * *********************************************************************** */ package org.matsim.contrib.emissions; @@ -420,7 +420,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple linkId = Id.create("linkId" + testCase1, Link.class); Id vehicleId = Id.create("vehicleId" + testCase1, Vehicle.class); Id vehicleTypeId = Id.create(testCase1.get(0) + ";" + testCase1.get(1) + ";" + testCase1.get(2) + ";" + testCase1.get(3), VehicleType.class); @@ -118,7 +118,7 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { final Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); - String message = "The expected emissions for " + testCase1.toString() + " are " + pollutants.size() * (Double) testCase1.get(4) + " but were " + sumOfEmissions; + String message = "The expected emissions for " + testCase1 + " are " + pollutants.size() * (Double) testCase1.get(4) + " but were " + sumOfEmissions; Assertions.assertEquals(pollutants.size() * (Double) testCase1.get(4), sumOfEmissions, MatsimTestUtils.EPSILON, message); } @@ -227,5 +227,5 @@ private static void putIntoHbefaColdTable( detailedHbefaColdTable.put(detColdKey, detColdFactor); } } - + } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java index c97de7d7ecd..ccf34b068bd 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java @@ -70,7 +70,7 @@ public class TestColdEmissionAnalysisModuleCase2 { // The material below was confused in the way that strings like "petrol" or "diesel" were given for the // size classes, and "<1,4L" or ">=2L" for the emissions concept. Tried to make it consistent, // but I don't know if it is still testing the original functionality. kai, jul'18 - + // first case: complete data - corresponding entry in average table private static final String petrol_technology = "petrol"; private static final String none_sizeClass = "average"; @@ -110,8 +110,8 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); - - String message = "The expected emissions for " + testCase2.toString() + " are " + pollutants.size() * (Double) testCase2.get( 4 ) + " but were " + sumOfEmissions; + + String message = "The expected emissions for " + testCase2 + " are " + pollutants.size() * (Double) testCase2.get( 4 ) + " but were " + sumOfEmissions; Assertions.assertEquals( pollutants.size() * (Double) testCase2.get( 4 ), sumOfEmissions, MatsimTestUtils.EPSILON, message ); } @@ -120,10 +120,10 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { private ColdEmissionAnalysisModule setUp() { Map avgHbefaColdTable = new HashMap<>(); Map detailedHbefaColdTable = new HashMap<>(); - + fillAveragesTable( avgHbefaColdTable ); fillDetailedTable( detailedHbefaColdTable ); - + EventsManager emissionEventManager = new HandlerToTestEmissionAnalysisModules(); EmissionsConfigGroup ecg = new EmissionsConfigGroup(); ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.usingVehicleTypeId ); @@ -133,7 +133,7 @@ private ColdEmissionAnalysisModule setUp() { return new ColdEmissionAnalysisModule( avgHbefaColdTable, detailedHbefaColdTable, ecg, pollutants, emissionEventManager ); } - + private static void fillDetailedTable( Map detailedHbefaColdTable ) { // create all needed and one unneeded entry for the detailed table { @@ -154,19 +154,19 @@ private static void fillDetailedTable( Map avgHbefaColdTable ) { // create all needed and one unneeded entry for the average table { // add passenger car entry "average;average;average": HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( "average", "average", "average" ) ; - + putIntoHbefaColdTable( avgHbefaColdTable, vehAtt, new HbefaColdEmissionFactor(averageAverageFactor), PASSENGER_CAR ); } { HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( petrol_technology, none_sizeClass, none_emConcept ); - + putIntoHbefaColdTable( avgHbefaColdTable, vehAtt, new HbefaColdEmissionFactor( averagePetrolFactor ), PASSENGER_CAR ); } { @@ -182,7 +182,7 @@ private static void fillAveragesTable( Map detailedHbefaColdTable, final HbefaVehicleAttributes vehAtt, final HbefaColdEmissionFactor detColdFactor, final HbefaVehicleCategory hbefaVehicleCategory ) { for ( Pollutant cp : pollutants ) { HbefaColdEmissionFactorKey detColdKey = new HbefaColdEmissionFactorKey(); @@ -194,5 +194,5 @@ private static void putIntoHbefaColdTable( final Map pollutants = new HashSet<>(Arrays.asList(Pollutant.values())); // strings for test cases - + // The material below was confused in the way that strings like "petrol" or "diesel" were given for the // size classes, and "<1,4L" or ">=2L" for the emissions concept. Tried to make it consistent, // but I don't know if it is still testing the original functionality. kai, jul'18 - + // first case: complete data - corresponding entry in average table private static final String petrol_technology = "petrol"; private static final String none_sizeClass = "average"; @@ -103,7 +103,7 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { // error when using the average entry. Collections.addAll( testCase3, "PASSENGER_CAR", diesel_technology, geq2l_sizeClass, PC_D_Euro_3_emConcept, detailedDieselFactor ); - logger.info("Running testcase: " + testCase3.toString()); + logger.info("Running testcase: " + testCase3); Id linkId = Id.create( "linkId" + testCase3 , Link.class ); Id vehicleId = Id.create( "vehicleId" + testCase3, Vehicle.class ); Id vehicleTypeId = Id.create( testCase3.get( 0 ) + ";" + testCase3.get( 1 ) + ";" + testCase3.get( 2 ) + ";" + testCase3.get( 3 ), VehicleType.class ); @@ -115,7 +115,7 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); - String message = "The expected emissions for " + testCase3.toString() + " are " + pollutants.size() * (Double) testCase3.get( 4 ) + " but were " + sumOfEmissions; + String message = "The expected emissions for " + testCase3 + " are " + pollutants.size() * (Double) testCase3.get( 4 ) + " but were " + sumOfEmissions; Assertions.assertEquals( pollutants.size() * (Double) testCase3.get( 4 ), sumOfEmissions, MatsimTestUtils.EPSILON, message ); @@ -124,10 +124,10 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { private ColdEmissionAnalysisModule setUp() { Map avgHbefaColdTable = new HashMap<>(); Map detailedHbefaColdTable = new HashMap<>(); - + fillAveragesTable( avgHbefaColdTable ); fillDetailedTable( detailedHbefaColdTable ); - + EventsManager emissionEventManager = new HandlerToTestEmissionAnalysisModules(); EmissionsConfigGroup ecg = new EmissionsConfigGroup(); ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.usingVehicleTypeId ); @@ -136,12 +136,12 @@ private ColdEmissionAnalysisModule setUp() { ecg.setDetailedVsAverageLookupBehavior(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); // return new ColdEmissionAnalysisModule( avgHbefaColdTable, detailedHbefaColdTable, ecg, pollutants, emissionEventManager ); - + } - + private static void fillDetailedTable( Map detailedHbefaColdTable ) { // create all needed and one unneeded entry for the detailed table - + { // add passenger car entry "petrol;<=1.4L;PC-P-Euro-1": HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( petrol_technology2, leq14l_sizeClass, PC_P_Euro_1_emConcept ); @@ -151,19 +151,19 @@ private static void fillDetailedTable( Map=2L;PC-D-Euro-3": HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( diesel_technology, geq2l_sizeClass, PC_D_Euro_3_emConcept ); - + putIntoHbefaColdTable( detailedHbefaColdTable, vehAtt, new HbefaColdEmissionFactor( detailedDieselFactor ), PASSENGER_CAR ); } { // add heavy goods vehicle entry "petrol;none;none": //(pre-existing comment: HEAVY_GOODS_VEHICLE;PC petrol;petrol;none should not be used --???) HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( petrol_technology, none_sizeClass, none_emConcept ); - + putIntoHbefaColdTable( detailedHbefaColdTable, vehAtt, new HbefaColdEmissionFactor( fakeFactor ), HEAVY_GOODS_VEHICLE ); } } - + private static void fillAveragesTable( Map avgHbefaColdTable ) { // create all needed and one unneeded entry for the average table @@ -171,30 +171,30 @@ private static void fillAveragesTable( Map detailedHbefaColdTable, final HbefaVehicleAttributes vehAtt, final HbefaColdEmissionFactor detColdFactor, final HbefaVehicleCategory hbefaVehicleCategory ) { for ( Pollutant cp : pollutants ) { HbefaColdEmissionFactorKey detColdKey = new HbefaColdEmissionFactorKey(); @@ -206,5 +206,5 @@ private static void putIntoHbefaColdTable( final Map pollutants = new HashSet<>(Arrays.asList(Pollutant.values())); // strings for test cases - + // The material below was confused in the way that strings like "petrol" or "diesel" were given for the // size classes, and "<1,4L" or ">=2L" for the emissions concept. Tried to make it consistent, // but I don't know if it is still testing the original functionality. kai, jul'18 - + // first case: complete data - corresponding entry in average table private static final String petrol_technology = "petrol"; private static final String none_sizeClass = "average"; @@ -84,7 +84,7 @@ public class TestColdEmissionAnalysisModuleCase4 { private static final String diesel_technology = "diesel"; private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - + // fifth case: cold emission factor not set // private static final String nullcase_emConcept = "nullCase"; // this testcase does not exist any more. kai, jul'18 @@ -113,11 +113,11 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { Collections.addAll( testCase4, "PASSENGER_CAR", "", "", "", averageAverageFactor ); - logger.info("Running testcase: " + testCase4.indexOf( 0 ) + " " + testCase4.toString()); + logger.info("Running testcase: " + testCase4.indexOf( 0 ) + " " + testCase4); Id linkId = Id.create( "linkId" + testCase4.indexOf( 0 ), Link.class ); Id vehicleId = Id.create( "vehicleId" + testCase4.indexOf( 0 ), Vehicle.class ); Id vehicleTypeId = Id.create( testCase4.get( 0 ) + ";" + testCase4.get( 1 ) + ";" + testCase4.get( 2 ) + ";" + testCase4.get( 3 ), VehicleType.class ); - + Vehicle vehicle = VehicleUtils.getFactory().createVehicle( vehicleId, VehicleUtils.getFactory().createVehicleType( vehicleTypeId ) ); logger.info("VehicleId: " + vehicle.getId().toString()); logger.info("VehicleTypeId: " + vehicle.getType().getId()); @@ -125,18 +125,18 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); - String message = "The expected emissions for " + testCase4.toString() + " are " + pollutants.size() * (Double) testCase4.get( 4 ) + " but were " + sumOfEmissions; + String message = "The expected emissions for " + testCase4 + " are " + pollutants.size() * (Double) testCase4.get( 4 ) + " but were " + sumOfEmissions; Assertions.assertEquals( pollutants.size() * (Double) testCase4.get( 4 ), sumOfEmissions, MatsimTestUtils.EPSILON, message ); - + } - + private ColdEmissionAnalysisModule setUp() { Map avgHbefaColdTable = new HashMap<>(); Map detailedHbefaColdTable = new HashMap<>(); - + fillAveragesTable( avgHbefaColdTable ); fillDetailedTable( detailedHbefaColdTable ); - + EventsManager emissionEventManager = new HandlerToTestEmissionAnalysisModules(); EmissionsConfigGroup ecg = new EmissionsConfigGroup(); @@ -146,10 +146,10 @@ private ColdEmissionAnalysisModule setUp() { ecg.setDetailedVsAverageLookupBehavior(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); return new ColdEmissionAnalysisModule( avgHbefaColdTable, detailedHbefaColdTable, ecg, pollutants, emissionEventManager ); } - + private static void fillDetailedTable( Map detailedHbefaColdTable ) { // create all needed and one unneeded entry for the detailed table - + { // add passenger car entry "petrol;<=1.4L;PC-P-Euro-1": HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( petrol_technology2, leq14l_sizeClass, PC_P_Euro_1_emConcept ); @@ -167,7 +167,7 @@ private static void fillDetailedTable( Map avgHbefaColdTable ) { // create all needed and one unneeded entry for the average table @@ -194,7 +194,7 @@ private static void fillAveragesTable( Map detailedHbefaColdTable, final HbefaVehicleAttributes vehAtt, final HbefaColdEmissionFactor detColdFactor, final HbefaVehicleCategory hbefaVehicleCategory ) { for ( Pollutant cp : pollutants ) { HbefaColdEmissionFactorKey detColdKey = new HbefaColdEmissionFactorKey(); @@ -206,5 +206,5 @@ private static void putIntoHbefaColdTable( final Map pollutants = new HashSet<>(Arrays.asList(Pollutant.values())); // strings for test cases - + // The material below was confused in the way that strings like "petrol" or "diesel" were given for the // size classes, and "<1,4L" or ">=2L" for the emissions concept. Tried to make it consistent, // but I don't know if it is still testing the original functionality. kai, jul'18 - + // case: complete data - corresponding entry in average table private static final String petrol_technology = "petrol"; private static final String none_sizeClass = "average"; @@ -82,7 +82,7 @@ public class TestColdEmissionAnalysisModuleCase6 { private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - + // emission factors for tables - no dublicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; @@ -108,11 +108,11 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { String heavygoodsvehicle = "HEAVY_GOODS_VEHICLE"; Collections.addAll( testCase6, heavygoodsvehicle, petrol_technology, none_sizeClass, none_emConcept, heavyGoodsFactor); - logger.info("Running testcase: " + testCase6 + " " +testCase6.toString()); + logger.info("Running testcase: " + testCase6 + " " + testCase6); Id linkId = Id.create( "linkId" + testCase6, Link.class ); Id vehicleId = Id.create( "vehicleId" + testCase6, Vehicle.class ); Id vehicleTypeId = Id.create( testCase6.get( 0 ) + ";" + testCase6.get( 1 ) + ";" + testCase6.get( 2 ) + ";" + testCase6.get( 3 ), VehicleType.class ); - + Vehicle vehicle = VehicleUtils.getFactory().createVehicle( vehicleId, VehicleUtils.getFactory().createVehicleType( vehicleTypeId ) ); logger.info("VehicleId: " + vehicle.getId().toString()); logger.info("VehicleTypeId: " + vehicle.getType().getId()); @@ -120,24 +120,24 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); - String message = "The expected emissions for " + testCase6.toString() + " are " + pollutants.size() * (Double) testCase6.get( 4 ) + " but were " + sumOfEmissions; + String message = "The expected emissions for " + testCase6 + " are " + pollutants.size() * (Double) testCase6.get( 4 ) + " but were " + sumOfEmissions; Assertions.assertEquals( pollutants.size() * (Double) testCase6.get( 4 ), sumOfEmissions, MatsimTestUtils.EPSILON, message ); } - + private ColdEmissionAnalysisModule setUp() { Map avgHbefaColdTable = new HashMap<>(); Map detailedHbefaColdTable = new HashMap<>(); - + fillAveragesTable( avgHbefaColdTable ); fillDetailedTable( detailedHbefaColdTable ); - + EventsManager emissionEventManager = new HandlerToTestEmissionAnalysisModules(); EmissionsConfigGroup ecg = new EmissionsConfigGroup(); ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.usingVehicleTypeId ); return new ColdEmissionAnalysisModule( avgHbefaColdTable, detailedHbefaColdTable, ecg, pollutants, emissionEventManager ); } - + private static void fillDetailedTable( Map detailedHbefaColdTable ) { // create all needed and one unneeded entry for the detailed table { @@ -160,7 +160,7 @@ private static void fillDetailedTable( Map avgHbefaColdTable ) { // create all needed and one unneeded entry for the average table @@ -184,11 +184,11 @@ private static void fillAveragesTable( Map detailedHbefaColdTable, final HbefaVehicleAttributes vehAtt, final HbefaColdEmissionFactor detColdFactor, final HbefaVehicleCategory hbefaVehicleCategory ) { for ( Pollutant cp : pollutants ) { HbefaColdEmissionFactorKey detColdKey = new HbefaColdEmissionFactorKey(); @@ -200,5 +200,5 @@ private static void putIntoHbefaColdTable( final Map return false // uncompleteData.equals(completeData) -> throw nullpointer // exception: if the vehicleAttributes are set to 'average' by default - + @Test final void testEqualsForIncompleteKeys_vehicleCategory() { // generate a complete HbefaWarmEmissionFactorKey: 'normal' @@ -167,7 +167,7 @@ final void testEqualsForIncompleteKeys_roadCategory() { equalErr = true; } - String message = "these two HbefaWarmEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noRoadCat.toString(); + String message = "these two HbefaWarmEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noRoadCat; String message2 = "this key should not be comparable since no road category is set"; Assertions.assertTrue(equalErr, message2); assertFalse(normal.equals(noRoadCat), message); @@ -213,7 +213,7 @@ final void testEqualsForIncompleteKeys_vehicleAttributes(){ // if no vehicle attributes are set manually they are set to 'average' by default // thus, the equals method should not throw nullpointer exceptions but return false or respectively true - // generate a complete HbefaWarmEmissionFactorKey: 'normal' + // generate a complete HbefaWarmEmissionFactorKey: 'normal' // and set some parameters setUp(); setToNormal(normal); @@ -232,7 +232,7 @@ final void testEqualsForIncompleteKeys_vehicleAttributes(){ equalErr = true; } - String message = "these two HbefaWarmEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noVehAtt.toString(); + String message = "these two HbefaWarmEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noVehAtt; assertFalse(noVehAtt.equals(normal), message); assertFalse(equalErr); // veh attributes are allowed to be not initiated @@ -247,13 +247,13 @@ final void testEqualsForIncompleteKeys_vehicleAttributes(){ hbefaVehicleAttributesAverage.setHbefaTechnology("average"); normal.setVehicleAttributes(hbefaVehicleAttributesAverage); - message = "these two HbefaWarmEmissionFactorKeys should be the same: " + normal.toString() + " and " + noVehAtt.toString(); + message = "these two HbefaWarmEmissionFactorKeys should be the same: " + normal.toString() + " and " + noVehAtt; Assertions.assertTrue(normal.equals(noVehAtt), message); Assertions.assertTrue(noVehAtt.equals(normal), message); } - + private void setToNormal(HbefaWarmEmissionFactorKey normal) { normal.setComponent(warmPollutant); normal.setRoadCategory(hbefaRoadCategory); @@ -261,10 +261,10 @@ private void setToNormal(HbefaWarmEmissionFactorKey normal) { normal.setVehicleAttributes(hbefaVehicleAttributes); normal.setVehicleCategory(hbefaVehicleCategory); } - - + + } - - + + diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzerTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzerTest.java index d9614bd3dea..e000400d4ca 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzerTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzerTest.java @@ -69,7 +69,7 @@ void process() { final Pollutant pollutant = HC; final double pollutionPerEvent = 1; - Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); Network network = TestUtils.createRandomNetwork(100, 1000, 1000); TestUtils.writeWarmEventsToFile(eventsFile, network, pollutant, pollutionPerEvent, 1, 99); @@ -95,7 +95,7 @@ void process_singleLinkWithOneEvent() { final Pollutant pollutant = CO; final double pollutionPerEvent = 1000; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); final Network network = NetworkUtils.createNetwork(); Node from = network.getFactory().createNode(Id.createNodeId("from"), new Coord(5, 5)); network.addNode(from); @@ -134,7 +134,7 @@ void process_singleLinkWithTwoEvents() { final Pollutant pollutant = CO; final double pollutionPerEvent = 1000; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); final Network network = NetworkUtils.createNetwork(); Node from = network.getFactory().createNode(Id.createNodeId("from"), new Coord(5, 5)); network.addNode(from); @@ -173,7 +173,7 @@ void process_twoLinksWithOneEventEach() { final Pollutant pollutant = CO; final double pollutionPerEvent = 1000; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); final Network network = NetworkUtils.createNetwork(); Node from = network.getFactory().createNode(Id.createNodeId("from"), new Coord(5, 5)); network.addNode(from); @@ -215,7 +215,7 @@ void process_twoLinksWithTwoEventsEach() { final Pollutant pollutant = NOx; final double pollutionPerEvent = 1000; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); final Network network = NetworkUtils.createNetwork(); Node from = network.getFactory().createNode(Id.createNodeId("from"), new Coord(5, 5)); network.addNode(from); @@ -255,7 +255,7 @@ void process_twoLinksWithTwoEventsEach() { void process_withBoundaries() { final double pollutionPerEvent = 1; - Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); Network network = TestUtils.createRandomNetwork(100, 1000, 1000); TestUtils.writeWarmEventsToFile(eventsFile, network, NOx, pollutionPerEvent, 1, 99); @@ -281,7 +281,7 @@ void processToJson() { final double pollutionPerEvent = 1; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); final Network network = TestUtils.createRandomNetwork(1, 1000, 1000); TestUtils.writeWarmEventsToFile(eventsFile, network, NO2, pollutionPerEvent, time, time + 3); @@ -302,8 +302,8 @@ void processToJsonFile() throws IOException { final double pollutionPerEvent = 1; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); - final Path jsonFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".json"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); + final Path jsonFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".json"); final Network network = TestUtils.createRandomNetwork(1, 1000, 1000); TestUtils.writeWarmEventsToFile(eventsFile, network, NO2, pollutionPerEvent, time, time + 3); From db06b2b081a66c0ae19241d66f946df3c3512075 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:00:32 +0200 Subject: [PATCH 071/101] remove unnecessary semicolon --- .../emissions/example/RunAverageEmissionToolOfflineExample.java | 2 +- .../example/RunDetailedEmissionToolOfflineExample.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java index bd1af3c2a90..5264f6d4b39 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java @@ -96,7 +96,7 @@ public void install(){ bind( EmissionModule.class ) ; // bind( OutputDirectoryHierarchy.class ); } - };; + }; com.google.inject.Injector injector = Injector.createInjector(config, module ); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java index 191766556c2..270b3bae7f2 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java @@ -89,7 +89,7 @@ public void install(){ bind( EventsManager.class ).toInstance( eventsManager ); bind( EmissionModule.class ) ; } - };; + }; com.google.inject.Injector injector = Injector.createInjector(config, module ); From 53a9a1f61e301aece4d0ed6fb4e53ae74b69de4c Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:02:12 +0200 Subject: [PATCH 072/101] inline and remove method --- .../RunDetailedEmissionToolOnlineExample.java | 24 ++++--------------- ...EmissionToolOnlineExampleIT_vehTypeV1.java | 4 +++- ...eExampleIT_vehTypeV1FallbackToAverage.java | 3 ++- ...EmissionToolOnlineExampleIT_vehTypeV2.java | 4 +++- ...eExampleIT_vehTypeV2FallbackToAverage.java | 3 ++- 5 files changed, 14 insertions(+), 24 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExample.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExample.java index 32708f736ea..d0518b73dc1 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExample.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExample.java @@ -29,8 +29,8 @@ import org.matsim.core.scenario.ScenarioUtils; /** - * - * After creating a config file with + * + * After creating a config file with * {@link CreateEmissionConfig CreateEmissionConfig} * this class runs a simulation and calculates emissions online. * Results are written into events file (including emission events) for some iterations (as specified by the config). @@ -55,23 +55,6 @@ public static Config prepareConfig( String[] args ) { return config; } - public static Scenario prepareScenario( Config config ) { - Scenario scenario = ScenarioUtils.loadScenario( config ); - - //load emissions config -// EmissionsConfigGroup emissionsConfigGroup = (EmissionsConfigGroup) config.getModules().get(EmissionsConfigGroup.GROUP_NAME); -// URL context = scenario.getConfig().getContext(); -// URL mappingFile = emissionsConfigGroup.getEmissionRoadTypeMappingFileURL(context); - - //add Hbefa mappings to the network -// HbefaRoadTypeMapping vhtm = VisumHbefaRoadTypeMapping.createVisumRoadTypeMapping(mappingFile); -// vhtm.addHbefaMappings(scenario.getNetwork()); - - // no need for the mapping file; hbefa mappings were directly written into the link attributes. ihab nov '18 - - return scenario ; - } - public static void run( Scenario scenario, AbstractModule... modules ) { Controler controler = new Controler(scenario); controler.addOverridingModule(new AbstractModule() { @@ -87,7 +70,8 @@ public void install() { } public static void main(String[] args) { Config config = prepareConfig( args ) ; - Scenario scenario = prepareScenario( config ) ; + + Scenario scenario = ScenarioUtils.loadScenario(config); run( scenario ) ; } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java index 1c16db00fa9..fbb83a35eb9 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java @@ -26,6 +26,7 @@ import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; +import org.matsim.core.scenario.ScenarioUtils; import org.matsim.testcases.MatsimTestUtils; /** @@ -58,7 +59,8 @@ final void testDetailed_vehTypeV1() { EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.fromVehicleTypeDescription ); emissionsConfig.setDetailedVsAverageLookupBehavior( EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort ); - Scenario scenario = onlineExample.prepareScenario( config ) ; + + Scenario scenario = ScenarioUtils.loadScenario(config); onlineExample.run( scenario ) ; } catch (Exception ee ) { gotAnException = true ; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1FallbackToAverage.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1FallbackToAverage.java index 8715b4525ed..21f6baf1404 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1FallbackToAverage.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1FallbackToAverage.java @@ -26,6 +26,7 @@ import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; +import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; import org.matsim.testcases.MatsimTestUtils; @@ -65,7 +66,7 @@ final void testDetailed_vehTypeV1_FallbackToAverage() { emissionsConfig.setAverageWarmEmissionFactorsFile( "../sample_41_EFA_HOT_vehcat_2020average.csv" ); emissionsConfig.setHbefaTableConsistencyCheckingLevel( EmissionsConfigGroup.HbefaTableConsistencyCheckingLevel.consistent ); - Scenario scenario = RunDetailedEmissionToolOnlineExample.prepareScenario( config ) ; + Scenario scenario = ScenarioUtils.loadScenario(config); RunDetailedEmissionToolOnlineExample.run( scenario ) ; } catch ( Exception ee ) { ee.printStackTrace(); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java index 95cbc87199b..18dd18a1be0 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java @@ -26,6 +26,7 @@ import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; +import org.matsim.core.scenario.ScenarioUtils; import org.matsim.testcases.MatsimTestUtils; /** @@ -51,7 +52,8 @@ final void testDetailed_vehTypeV2() { config.controller().setLastIteration( 1 ); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setDetailedVsAverageLookupBehavior( EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort ); - Scenario scenario = onlineExample.prepareScenario( config ) ; + + Scenario scenario = ScenarioUtils.loadScenario(config); onlineExample.run( scenario ) ; } catch (Exception ee ) { gotAnException = true ; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java index ef667425698..65f2c8a4850 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java @@ -27,6 +27,7 @@ import org.matsim.contrib.emissions.utils.EmissionsConfigGroup.DetailedVsAverageLookupBehavior; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; +import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; import org.matsim.testcases.MatsimTestUtils; @@ -60,7 +61,7 @@ final void testDetailed_vehTypeV2_FallbackToAverage() { emissionsConfig.setAverageWarmEmissionFactorsFile( "../sample_41_EFA_HOT_vehcat_2020average.csv" ); emissionsConfig.setHbefaTableConsistencyCheckingLevel( EmissionsConfigGroup.HbefaTableConsistencyCheckingLevel.consistent ); - Scenario scenario = RunDetailedEmissionToolOnlineExample.prepareScenario( config ) ; + Scenario scenario = ScenarioUtils.loadScenario(config); RunDetailedEmissionToolOnlineExample.run( scenario ) ; } catch ( Exception ee ) { ee.printStackTrace(); From f2eee3fe0a07540f257b47745642e248a68aa8e3 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:03:17 +0200 Subject: [PATCH 073/101] cleanup imports --- .../java/org/matsim/contrib/emissions/OsmHbefaMapping.java | 2 -- .../contrib/emissions/analysis/EmissionsByPollutant.java | 1 - .../matsim/contrib/emissions/events/ColdEmissionEvent.java | 2 -- .../org/matsim/contrib/emissions/events/EmissionEvent.java | 1 - .../matsim/contrib/emissions/events/WarmEmissionEvent.java | 2 -- .../contrib/emissions/TestColdEmissionAnalysisModule.java | 1 - .../contrib/emissions/TestWarmEmissionAnalysisModule.java | 2 -- .../emissions/TestWarmEmissionAnalysisModuleCase1.java | 4 ---- .../emissions/TestWarmEmissionAnalysisModuleCase2.java | 3 --- .../emissions/TestWarmEmissionAnalysisModuleCase3.java | 3 --- .../emissions/TestWarmEmissionAnalysisModuleCase4.java | 1 - .../emissions/TestWarmEmissionAnalysisModuleCase5.java | 3 --- .../TestWarmEmissionAnalysisModuleTrafficSituations.java | 5 ----- 13 files changed, 30 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java index 4938d75e993..2bb05ace764 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java @@ -22,13 +22,11 @@ package org.matsim.contrib.emissions; import com.google.inject.Provides; -import org.apache.commons.lang3.StringUtils; import org.matsim.api.core.v01.network.Link; import org.matsim.core.network.NetworkUtils; import java.util.Arrays; import java.util.HashMap; -import java.util.List; import java.util.Map; /** diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutant.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutant.java index 6b1eda64b73..167bc09caf8 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutant.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutant.java @@ -24,7 +24,6 @@ import org.matsim.contrib.emissions.Pollutant; -import java.util.HashMap; import java.util.Map; /** diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/ColdEmissionEvent.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/ColdEmissionEvent.java index e658817da12..fe184d1ce2b 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/ColdEmissionEvent.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/ColdEmissionEvent.java @@ -20,13 +20,11 @@ package org.matsim.contrib.emissions.events; import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.Pollutant; import org.matsim.vehicles.Vehicle; import java.util.Map; -import java.util.Map.Entry; /** diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEvent.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEvent.java index 32a5221e27c..ae7c9c59e2a 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEvent.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEvent.java @@ -23,7 +23,6 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.Event; -import org.matsim.api.core.v01.events.HasLinkId; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.Pollutant; import org.matsim.vehicles.Vehicle; diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/WarmEmissionEvent.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/WarmEmissionEvent.java index b0504f880ed..02eeb1daaf5 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/WarmEmissionEvent.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/WarmEmissionEvent.java @@ -20,13 +20,11 @@ package org.matsim.contrib.emissions.events; import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.Pollutant; import org.matsim.vehicles.Vehicle; import java.util.Map; -import java.util.Map.Entry; /** diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModule.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModule.java index d5d32b96239..2ed3110e4a9 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModule.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModule.java @@ -20,7 +20,6 @@ package org.matsim.contrib.emissions; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.matsim.api.core.v01.Id; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java index 30b456f1455..c8c39b2f3ad 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java @@ -20,10 +20,8 @@ package org.matsim.contrib.emissions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java index 2bc080b1bc3..9fd1234d3bb 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java @@ -21,11 +21,8 @@ package org.matsim.contrib.emissions; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; @@ -38,7 +35,6 @@ import org.matsim.vehicles.VehiclesFactory; import java.util.*; -import java.util.stream.Stream; import static org.matsim.contrib.emissions.Pollutant.CO2_TOTAL; import static org.matsim.contrib.emissions.TestWarmEmissionAnalysisModule.HBEFA_ROAD_CATEGORY; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase2.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase2.java index 8fb143e1821..101c410289d 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase2.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase2.java @@ -21,10 +21,8 @@ package org.matsim.contrib.emissions; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; @@ -37,7 +35,6 @@ import org.matsim.vehicles.VehiclesFactory; import java.util.*; -import java.util.stream.Stream; import static org.matsim.contrib.emissions.Pollutant.NMHC; import static org.matsim.contrib.emissions.TestWarmEmissionAnalysisModule.fillAverageTable; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase3.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase3.java index b9df5a7e9bf..4a8f8f5827b 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase3.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase3.java @@ -22,9 +22,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; @@ -37,7 +35,6 @@ import org.matsim.vehicles.VehiclesFactory; import java.util.*; -import java.util.stream.Stream; import static org.matsim.contrib.emissions.Pollutant.PM; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase4.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase4.java index 838573a0e35..f7a25a4d003 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase4.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase4.java @@ -23,7 +23,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.matsim.api.core.v01.Id; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase5.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase5.java index c1ba590dcfa..bbc1ce82970 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase5.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase5.java @@ -22,9 +22,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; @@ -37,7 +35,6 @@ import org.matsim.vehicles.VehiclesFactory; import java.util.*; -import java.util.stream.Stream; import static org.matsim.contrib.emissions.Pollutant.PM; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleTrafficSituations.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleTrafficSituations.java index 3289f013639..49f3a0494d9 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleTrafficSituations.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleTrafficSituations.java @@ -19,12 +19,8 @@ * *********************************************************************** */ import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Node; @@ -39,7 +35,6 @@ import org.matsim.vehicles.VehiclesFactory; import java.util.*; -import java.util.stream.Stream; import static org.matsim.contrib.emissions.HbefaTrafficSituation.*; import static org.matsim.contrib.emissions.Pollutant.NOx; From c104df247e178081090f05ab6ec733180ef12e46 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:07:06 +0200 Subject: [PATCH 074/101] simplification --- .../RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java | 5 ++--- .../RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java | 5 ++--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java index fbb83a35eb9..f52a038ddda 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java @@ -52,8 +52,7 @@ public class RunDetailedEmissionToolOnlineExampleIT_vehTypeV1 { final void testDetailed_vehTypeV1() { boolean gotAnException = false ; try { - RunDetailedEmissionToolOnlineExample onlineExample = new RunDetailedEmissionToolOnlineExample(); - Config config = onlineExample.prepareConfig( new String[]{"./scenarios/sampleScenario/testv2_Vehv1/config_detailed.xml"} ) ; + Config config = RunDetailedEmissionToolOnlineExample.prepareConfig( new String[]{"./scenarios/sampleScenario/testv2_Vehv1/config_detailed.xml"} ) ; config.controller().setOutputDirectory( utils.getOutputDirectory() ); config.controller().setLastIteration( 1 ); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); @@ -61,7 +60,7 @@ final void testDetailed_vehTypeV1() { emissionsConfig.setDetailedVsAverageLookupBehavior( EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort ); Scenario scenario = ScenarioUtils.loadScenario(config); - onlineExample.run( scenario ) ; + RunDetailedEmissionToolOnlineExample.run( scenario ) ; } catch (Exception ee ) { gotAnException = true ; } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java index 18dd18a1be0..1a28fb39bf2 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java @@ -46,15 +46,14 @@ public class RunDetailedEmissionToolOnlineExampleIT_vehTypeV2 { final void testDetailed_vehTypeV2() { boolean gotAnException = false ; try { - RunDetailedEmissionToolOnlineExample onlineExample = new RunDetailedEmissionToolOnlineExample(); - Config config = onlineExample.prepareConfig( new String[]{"./scenarios/sampleScenario/testv2_Vehv2/config_detailed.xml"} ) ; + Config config = RunDetailedEmissionToolOnlineExample.prepareConfig( new String[]{"./scenarios/sampleScenario/testv2_Vehv2/config_detailed.xml"} ) ; config.controller().setOutputDirectory( utils.getOutputDirectory() ); config.controller().setLastIteration( 1 ); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setDetailedVsAverageLookupBehavior( EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort ); Scenario scenario = ScenarioUtils.loadScenario(config); - onlineExample.run( scenario ) ; + RunDetailedEmissionToolOnlineExample.run( scenario ) ; } catch (Exception ee ) { gotAnException = true ; } From fdadeca47c31c24fea8e0b09829d35e76dbec938 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:09:56 +0200 Subject: [PATCH 075/101] make final, internal renaming --- .../contrib/emissions/OsmHbefaMapping.java | 16 ++++++++-------- .../emissions/events/EmissionEventsReader.java | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java index 2bb05ace764..1e1b72a08db 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java @@ -61,14 +61,14 @@ public class OsmHbefaMapping extends HbefaRoadTypeMapping { private final Map hbfeaMap = new HashMap<>(); static class Hbefa { - String name; - int min; - int max; + final String name; + final int min_speed; + final int max_speed; - Hbefa(String name, int min, int max) { + Hbefa(String name, int min_speed, int max) { this.name = name; - this.min = min; - this.max = max; + this.min_speed = min_speed; + this.max_speed = max; } } @@ -137,8 +137,8 @@ private String getHEBFAtype(String type, double speed) { if (!hbfeaMap.containsKey(type)) { throw new RuntimeException("'" + type + "' not in hbefa map"); } - int min_speed = hbfeaMap.get(type).min; - int max_speed = hbfeaMap.get(type).max; + int min_speed = hbfeaMap.get(type).min_speed; + int max_speed = hbfeaMap.get(type).max_speed; int clamped_speed = (int) Math.min(Math.max(min_speed, freeVelocity_kmh), max_speed); return "URB/" + hbfeaMap.get(type).name + "/" + clamped_speed; diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java index c9c21926ef9..1e54d1de5f6 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java @@ -40,7 +40,7 @@ public final class EmissionEventsReader implements MatsimReader { // leave this public so that external code can generate "standard" emission events. MATSIM-893 - private MatsimEventsReader delegate ; + private final MatsimEventsReader delegate ; public EmissionEventsReader( EventsManager events ){ this.delegate = new MatsimEventsReader(events); From 26cbfd4ca42dcfe16a3948485b56f159d9ab1701 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:15:09 +0200 Subject: [PATCH 076/101] replace 'if' by 'switch' --- .../events/EmissionEventsReader.java | 50 ++++++++++--------- 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java index 1e54d1de5f6..83bf51bc0f2 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java @@ -59,20 +59,21 @@ public EmissionEventsReader( EventsManager events ){ // the loop is necessary since we do now know which pollutants are in the event. for (Map.Entry entry : attributes.entrySet()) { - if( "time".equals( entry.getKey() ) ){ - time = Double.parseDouble( entry.getValue() ); - } else if( "type".equals( entry.getKey() ) ){ - // I don't think that we are doing anything here. kai, jan'19 - } else if( WarmEmissionEvent.ATTRIBUTE_LINK_ID.equals( entry.getKey() ) ){ - linkId = Id.createLinkId( entry.getValue() ); - } else if (WarmEmissionEvent.ATTRIBUTE_VEHICLE_ID.equals(entry.getKey())) { - vehicleId = Id.createVehicleId(entry.getValue()); - } else { - String pollutant = entry.getKey().equals("NOX") ? + switch (entry.getKey()) { + case "time" -> time = Double.parseDouble(entry.getValue()); + case "type" -> { + // I don't think that we are doing anything here. kai, jan'19 + } + case WarmEmissionEvent.ATTRIBUTE_LINK_ID -> linkId = Id.createLinkId(entry.getValue()); + case WarmEmissionEvent.ATTRIBUTE_VEHICLE_ID -> vehicleId = Id.createVehicleId(entry.getValue()); + case null, default -> { + String pollutant = entry.getKey().equals("NOX") ? "NOx" : entry.getKey(); // the previous versions would write NOX instead of NOx - Double value = Double.parseDouble(entry.getValue()); - warmEmissions.put(Pollutant.valueOf(pollutant), value); + + Double value = Double.parseDouble(entry.getValue()); + warmEmissions.put(Pollutant.valueOf(pollutant), value); + } } } @@ -91,20 +92,21 @@ public EmissionEventsReader( EventsManager events ){ // the loop is necessary since we do now know which pollutants are in the event. for (Map.Entry entry : attributes.entrySet()) { - if( "time".equals( entry.getKey() ) ){ - time = Double.parseDouble( entry.getValue() ); - } else if( "type".equals( entry.getKey() ) ){ - // do nothing - } else if( ColdEmissionEvent.ATTRIBUTE_LINK_ID.equals( entry.getKey() ) ){ - linkId = Id.createLinkId( entry.getValue() ); - } else if (ColdEmissionEvent.ATTRIBUTE_VEHICLE_ID.equals(entry.getKey())) { - vehicleId = Id.createVehicleId(entry.getValue()); - } else { - String pollutant = entry.getKey().equals("NOX") ? + switch (entry.getKey()) { + case "time" -> time = Double.parseDouble(entry.getValue()); + case "type" -> { + // do nothing + } + case ColdEmissionEvent.ATTRIBUTE_LINK_ID -> linkId = Id.createLinkId(entry.getValue()); + case ColdEmissionEvent.ATTRIBUTE_VEHICLE_ID -> vehicleId = Id.createVehicleId(entry.getValue()); + case null, default -> { + String pollutant = entry.getKey().equals("NOX") ? "NOx" : entry.getKey(); // the previous versions would write NOX instead of NOx - Double value = Double.parseDouble(entry.getValue()); - coldEmissions.put(Pollutant.valueOf(pollutant), value); + + Double value = Double.parseDouble(entry.getValue()); + coldEmissions.put(Pollutant.valueOf(pollutant), value); + } } } return new ColdEmissionEvent(time, linkId, vehicleId, coldEmissions); From 41af9a2c9846f91e40ff11eacb8caf6be349407e Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:15:58 +0200 Subject: [PATCH 077/101] simplification --- .../contrib/emissions/events/TestWarmEmissionEventImpl.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java index 2d378543e90..2244cb6dde7 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java @@ -74,9 +74,7 @@ final void testGetAttributesForCompleteEmissionMaps(){ warmEmissionsMap.put(PM, pm_value); warmEmissionsMap.put(SO2, so2_value); - Map map = new LinkedHashMap<>(); - warmEmissionsMap.forEach( (key,value) -> map.put( key, value ) ); - // (this could be made more direct) + Map map = new LinkedHashMap<>(warmEmissionsMap); WarmEmissionEvent we = new WarmEmissionEvent(0.0, linkId, vehicleId, map); @@ -114,7 +112,7 @@ final void testGetAttributesForIncompleteMaps(){ valuesNotSet.put(PM, null); Map map = new LinkedHashMap<>(); - valuesNotSet.forEach( (key,value) -> map.put( key, value ) ); + valuesNotSet.forEach(map::put); // (this could be made more direct) WarmEmissionEvent valuesNotSetEvent = new WarmEmissionEvent(44., linkId, vehicleId, map); From a3c5c2bfc41fd9939c3eda3f4bdb63c6688d826c Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:17:30 +0200 Subject: [PATCH 078/101] use enhanced 'switch' --- .../contrib/emissions/EmissionModule.java | 23 ++---- .../contrib/emissions/EmissionUtils.java | 73 +++++++------------ 2 files changed, 33 insertions(+), 63 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java index 196d7e77255..842075c1ba9 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java @@ -205,24 +205,17 @@ private void addPollutantsToMap(Set addTo, Set true; + default -> false; + }; } private boolean shouldCreateDetailedTables() { - switch (emissionConfigGroup.getDetailedVsAverageLookupBehavior()) { - case onlyTryDetailedElseAbort: - case tryDetailedThenTechnologyAverageElseAbort: - case tryDetailedThenTechnologyAverageThenAverageTable: - return true; - default: - return false; - } + return switch (emissionConfigGroup.getDetailedVsAverageLookupBehavior()) { + case onlyTryDetailedElseAbort, tryDetailedThenTechnologyAverageElseAbort, tryDetailedThenTechnologyAverageThenAverageTable -> true; + default -> false; + }; } private void createEmissionHandlers() { diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java index a24186833db..4b7ed17b902 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java @@ -97,7 +97,7 @@ public static Map, SortedMap> setNonCalculatedEmis for (Pollutant pollutant : pollutants) { emissionType2Value.put(pollutant, 0.0); } - } else { // person in map, but some emissions are not set; setting these to 0.0 + } else { // person in map, but some emissions are not set; setting these to 0.0 emissionType2Value = totalEmissions.get(personId); for (Pollutant pollutant : emissionType2Value.keySet()) { // else do nothing @@ -329,22 +329,15 @@ public static HbefaVehicleCategory mapString2HbefaVehicleCategory(String string) public static String mapHbefaVehicleCategory2String(HbefaVehicleCategory category) { - switch (category) { - case COACH: - return "coach"; - case HEAVY_GOODS_VEHICLE: - return "HGV"; - case LIGHT_COMMERCIAL_VEHICLE: - return "LCV"; - case MOTORCYCLE: - return "motorcycle"; - case PASSENGER_CAR: - return "pass. car"; - case URBAN_BUS: - return "urban bus"; - default: - throw new RuntimeException("Could not transform category to string: " + category); - } + return switch (category) { + case COACH -> "coach"; + case HEAVY_GOODS_VEHICLE -> "HGV"; + case LIGHT_COMMERCIAL_VEHICLE -> "LCV"; + case MOTORCYCLE -> "motorcycle"; + case PASSENGER_CAR -> "pass. car"; + case URBAN_BUS -> "urban bus"; + default -> throw new RuntimeException("Could not transform category to string: " + category); + }; } static Pollutant getPollutant( String pollutantString ){ @@ -353,37 +346,21 @@ static Pollutant getPollutant( String pollutantString ){ // setCo2TotalKeys( Set keys ) // as we have it, e.g., with network modes. kai, feb'20 - Pollutant pollutant; - switch( pollutantString ){ - case "CO2(total)": - pollutant = Pollutant.CO2_TOTAL; - break; - case "CO2(rep)": - pollutant = Pollutant.CO2_rep; - break; - case "PM2.5 (non-exhaust)": - pollutant = Pollutant.PM2_5_non_exhaust; - break; - case "PM2.5": - pollutant = Pollutant.PM2_5; - break; - case "PM (non-exhaust)": - pollutant = Pollutant.PM_non_exhaust; - break; - case "BC (exhaust)": - pollutant = Pollutant.BC_exhaust; - break; - case "BC (non-exhaust)": - pollutant = Pollutant.BC_non_exhaust; - break; - default: - pollutant = Pollutant.valueOf( pollutantString ); - // the Pollutant.valueOf(...) should fail if the incoming key is not consistent with what is available in the enum. Two possibilities: - // (1) it is a new pollutant. In that case, just add to the enum. - // (2) It is a different spelling of an already existing pollutant. In that case, see above. - // kai, jan'20 - } - return pollutant; + Pollutant pollutant = switch (pollutantString) { + case "CO2(total)" -> Pollutant.CO2_TOTAL; + case "CO2(rep)" -> Pollutant.CO2_rep; + case "PM2.5 (non-exhaust)" -> Pollutant.PM2_5_non_exhaust; + case "PM2.5" -> Pollutant.PM2_5; + case "PM (non-exhaust)" -> Pollutant.PM_non_exhaust; + case "BC (exhaust)" -> Pollutant.BC_exhaust; + case "BC (non-exhaust)" -> Pollutant.BC_non_exhaust; + default -> Pollutant.valueOf(pollutantString); + // the Pollutant.valueOf(...) should fail if the incoming key is not consistent with what is available in the enum. Two possibilities: + // (1) it is a new pollutant. In that case, just add to the enum. + // (2) It is a different spelling of an already existing pollutant. In that case, see above. + // kai, jan'20 + }; + return pollutant; } /** From 71c8509c9aa03531d390a7920366d5f9f3f7ff8c Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:18:23 +0200 Subject: [PATCH 079/101] simplification --- .../contrib/emissions/HbefaEmissionFactorKey.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaEmissionFactorKey.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaEmissionFactorKey.java index aa11fc55018..3ce7f9632e7 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaEmissionFactorKey.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaEmissionFactorKey.java @@ -66,13 +66,11 @@ public void setComponent(Pollutant component) { @Override public boolean equals(Object o) { if (this == o) return true; - if (!(o instanceof HbefaEmissionFactorKey)) return false; + if (!(o instanceof HbefaEmissionFactorKey efk)) return false; - var that = (HbefaEmissionFactorKey) o; - - if (vehicleCategory != that.getVehicleCategory()) return false; - if (!Objects.equals(vehicleAttributes, that.vehicleAttributes)) return false; - return Objects.equals(component, that.component); + if (vehicleCategory != efk.getVehicleCategory()) return false; + if (!Objects.equals(vehicleAttributes, efk.vehicleAttributes)) return false; + return Objects.equals(component, efk.component); } @Override From 174009f46f9de48c9699c44bd7c87e01e84e6ca9 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:18:42 +0200 Subject: [PATCH 080/101] use 'getFirst()' --- .../matsim/contrib/emissions/utils/EmissionWriter.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java index 7a5e1a1ada1..10ba02d6243 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java @@ -42,18 +42,18 @@ public final class EmissionWriter { // is this useful as a publicly available class? kai, jan'19 private static final Logger logger = LogManager.getLogger(EmissionWriter.class); - + public EmissionWriter(){ } - + public void writeHomeLocation2TotalEmissions( Population population, Map, SortedMap> totalEmissions, Collection pollutants, String outFile) { try{ - FileWriter fstream = new FileWriter(outFile); + FileWriter fstream = new FileWriter(outFile); BufferedWriter out = new BufferedWriter(fstream); out.append("personId \t xHome \t yHome \t"); for (String pollutant : pollutants){ @@ -64,7 +64,7 @@ public void writeHomeLocation2TotalEmissions( for(Person person: population.getPersons().values()){ Id personId = person.getId(); Plan plan = person.getSelectedPlan(); - Activity homeAct = (Activity) plan.getPlanElements().get(0); + Activity homeAct = (Activity) plan.getPlanElements().getFirst(); Coord homeCoord = homeAct.getCoord(); Double xHome = homeCoord.getX(); Double yHome = homeCoord.getY(); From ad74210055e7fc70a5c49478c6d44d18bd524fb3 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:19:23 +0200 Subject: [PATCH 081/101] javadoc: replace blank lines with '

' --- .../contrib/emissions/OsmHbefaMapping.java | 6 ++-- .../example/CreateEmissionConfig.java | 2 +- .../contrib/emissions/package-info.java | 12 +++---- .../TestColdEmissionsFallbackBehaviour.java | 30 ++++++++-------- .../TestWarmEmissionAnalysisModule.java | 6 ++-- .../TestWarmEmissionsFallbackBehaviour.java | 34 +++++++++---------- 6 files changed, 45 insertions(+), 45 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java index 1e1b72a08db..27da7acf1be 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java @@ -31,13 +31,13 @@ /** * Created by molloyj on 01.12.2017. - * + *

* * handled OSM road types: * motorway,trunk,primary,secondary, tertiary, unclassified,residential,service * motorway_link, trunk_link,primary_link, secondary_link * tertiary_link, living_street, pedestrian,track,road - * + *

* Hbefa categories and respective speeds * URB/MW-Nat./80 - 130 * URB/MW-City/60 - 110 @@ -46,7 +46,7 @@ * URB/Distr/50 - 80 * URB/Local/50 - 60 * URB/Access/30 - 50 - * + *

* Conversions from OSM to hbefa types * motorway;MW * primary;Trunk diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java index f50fc6a6d27..b0b73b6bd28 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java @@ -32,7 +32,7 @@ * * Creates a config file * with necessary emission input files for the {@link EmissionsConfigGroup EmissionsConfigGroup}. - * + *

* This config file is used by the {@link RunDetailedEmissionToolOfflineExample OfflineExample} and * the {@link RunDetailedEmissionToolOnlineExample OnlineExample} * diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/package-info.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/package-info.java index 95bfb7b8b85..2d954229c63 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/package-info.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/package-info.java @@ -14,7 +14,7 @@ * *

Export from HBEFA 3.x

* Currently, data from the HBEFA 3.x Microsoft Access database needs to be exported manually. - * + *

* Consequently, the following steps within HBEFA 3.x need still be done manually: *

    *
  • Install and open HBEFA 3.x
  • @@ -29,11 +29,11 @@ *
  • HOT EMISSION FACTORS: Choose "Individual TrafficSituations" > "Construct your own list" > "SelectAll" > "Return"
  • *
  • COLD START EXCESS EMISSION FACTORS: Tick this option and choose "Construct your own list" > select all "patterns" with average temperature, detailed parking time (0-1h .. >12h), and detailed distance (0-1km and 1-2km) > "Return"
  • *
  • Leave everything else as default
  • - *
+ * *
  • Enter "Name of parameter set" and press "Calculate"
  • *
  • Save the two generated tables using "Results" > "Export" to the desired location
  • * - * + * * All these emission factor files need to be converted into *.txt or *.csv with ";" as delimiter. * Their column headers should automatically match the parser definition * in the respective method of the {@link org.matsim.contrib.emissions.EmissionModule}. @@ -44,7 +44,7 @@ *
  • roadTypeMappingFile: This file needs to map road types in your network to HBEFA 3.x road types. * Update (June'2018) one can now directly add HBEFA road type to link attributes using {@link org.matsim.contrib.emissions.EmissionUtils#setHbefaRoadType(org.matsim.api.core.v01.network.Link, java.lang.String)} * or see {@link org.matsim.contrib.emissions.utils.EmissionsConfigGroup} for a detailed description. - * + * *
  • emissionVehicleFile: This data type is defined in the EmissionsConfigGroup, * see {@link org.matsim.contrib.emissions.utils.EmissionsConfigGroup}. The following information is surrounded by {@link org.matsim.contrib.emissions.EmissionUtils.EmissionSpecificationMarker}. It is described as "definition of a vehicle * for every person (who is allowed to choose a vehicle in the simulation): @@ -61,7 +61,7 @@ *
      * *

      Model description

      - * + * *

      Emissions

      * The main package contains classes and methods to handle the emission input data and create * maps to associate the emissions with corresponding vehicle types, speed, parking time, ...
      @@ -86,7 +86,7 @@ * a distance, which is driven after parking and, again, vehicle attributes. * The cold/warm emission factor keys are mapped to the values of cold/warm emissions, the cold/warm emission factors. *

      - * + * * @author benjamin, julia */ diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionsFallbackBehaviour.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionsFallbackBehaviour.java index cef4618571e..d4816287c55 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionsFallbackBehaviour.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionsFallbackBehaviour.java @@ -76,9 +76,9 @@ public class TestColdEmissionsFallbackBehaviour { // --------- DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort) ----------- /** * vehicles information is complete - * + *

      * LookupBehavior: onlyTryDetailedElseAbort - * + *

      * -> should calculate value */ @Test @@ -86,7 +86,7 @@ void testColdDetailedValueOnlyDetailed() { EmissionModule emissionModule = setUpScenario( DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort ); Map coldEmissions = emissionModule.getColdEmissionAnalysisModule() - .checkVehicleInfoAndCalculateWColdEmissions(vehicleFull.getType(), vehicleFull.getId(), link.getId(), + .checkVehicleInfoAndCalculateWColdEmissions(vehicleFull.getType(), vehicleFull.getId(), link.getId(), startTime, parkingDuration, distance); Assertions.assertEquals(emissionsFactorInGrammPerKilometer_Detailed, coldEmissions.get(Pollutant.CO2_TOTAL ), MatsimTestUtils.EPSILON ); @@ -97,7 +97,7 @@ void testColdDetailedValueOnlyDetailed() { * * vehicles information is complete but fully specified entry is NOT available in detailed table * LookupBehavior: onlyTryDetailedElseAbort - * + *

      * -> should abort --> RuntimeException */ @Test @@ -114,9 +114,9 @@ void testCold_DetailedElseAbort_ShouldAbort1() { /** * vehicles information is complete but fully specified entry is NOT available in detailed table * HbefaTechnology is also not in detailed table -> fall back to technology average is NOT possible as well. - * + *

      * LookupBehavior: onlyTryDetailedElseAbort - * + *

      * -> should abort --> RuntimeException */ @Test @@ -135,7 +135,7 @@ void testCold_DetailedElseAbort_ShouldAbort2() { /** * vehicles information is complete * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

      * -> do NOT fall back to technology average * ---> should calculate value from detailed value */ @@ -144,7 +144,7 @@ void testCold_DetailedThenTechnologyAverageElseAbort_FallbackNotNeeded() { EmissionModule emissionModule = setUpScenario( DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageElseAbort ); Map coldEmissions = emissionModule.getColdEmissionAnalysisModule() - .checkVehicleInfoAndCalculateWColdEmissions(vehicleFull.getType(), vehicleFull.getId(), link.getId(), + .checkVehicleInfoAndCalculateWColdEmissions(vehicleFull.getType(), vehicleFull.getId(), link.getId(), startTime, parkingDuration, distance); Assertions.assertEquals(emissionsFactorInGrammPerKilometer_Detailed, coldEmissions.get(Pollutant.CO2_TOTAL ), MatsimTestUtils.EPSILON ); @@ -154,7 +154,7 @@ void testCold_DetailedThenTechnologyAverageElseAbort_FallbackNotNeeded() { /** * vehicles information is complete but fully specified entry is NOT available in detailed table * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

      * -> do fall back to technology average * ---> should calculate value from technology average */ @@ -173,9 +173,9 @@ void testCold_DetailedThenTechnologyAverageElseAbort_FallbackToTechnologyAverage /** * vehicles information is complete but fully specified entry is NOT available in detailed table * HbefaTechnology is also not in detailed table -> fall back to technology average is NOT possible as well. - * + *

      * LookupBehavior: onlyTryDetailedElseAbort - * + *

      * -> should abort --> RuntimeException */ @Test @@ -193,7 +193,7 @@ void testCold_DetailedThenTechnologyAverageElseAbort_ShouldAbort() { /** * vehicles information is complete * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

      * -> do NOT fall back to technology average or average table * ---> should calculate value from detailed value */ @@ -212,7 +212,7 @@ void testCold_DetailedThenTechnologyAverageThenAverageTable_FallbackNotNeeded() /** * vehicles information is complete but fully specified entry is NOT available in detailed table * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

      * -> do fall back to technology average; do NOT fall back to average table * ---> should calculate value from technology average */ @@ -230,9 +230,9 @@ void testCold_DetailedThenTechnologyAverageThenAverageTable_FallbackToTechnology /** * vehicles information is complete but fully specified entry is NOT available in detailed table * HbefaTechnology is also not in detailed table -> fall back to technology average is NOT possible as well. - * + *

      * LookupBehavior: tryDetailedThenTechnologyAverageThenAverageTable - * + *

      * -> do fall back to average table * ---> should calculate value from average table */ diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java index c8c39b2f3ad..9d6fc109be9 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java @@ -47,7 +47,7 @@ /* * test for playground.vsp.emissions.WarmEmissionAnalysisModule - * + *

      * WarmEmissionAnalysisModule (weam) * public methods and corresponding tests: * weamParameter - testWarmEmissionAnalysisParameter @@ -60,12 +60,12 @@ * get free flow km counter - testCounters*() * get top go km couter - testCounters*() * get warm emission event counter - testCounters*() - * + *

      * private methods and corresponding tests: * rescale warm emissions - rescaleWarmEmissionsTest() * calculate warm emissions - implicitly tested * convert string 2 tuple - implicitly tested - * + *

      * in all cases the needed tables are created manually by the setUp() method * see test methods for details on the particular test cases **/ diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionsFallbackBehaviour.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionsFallbackBehaviour.java index 4d7d500299e..35f4c8c2c47 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionsFallbackBehaviour.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionsFallbackBehaviour.java @@ -60,12 +60,12 @@ public class TestWarmEmissionsFallbackBehaviour { private final Vehicle vehicleFallbackToAverageTable = generateVehicleForFallbackToAverageTable(); -// --------- DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort) ----------- +// --------- DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort) ----------- /** * vehicles information is complete - * + *

      * LookupBehavior: onlyTryDetailedElseAbort - * + *

      * -> should calculate value */ @Test @@ -84,7 +84,7 @@ void testWarmDetailedValueOnlyDetailed() { * * vehicles information is complete but fully specified entry is NOT available in detailed table * LookupBehavior: onlyTryDetailedElseAbort - * + *

      * -> should abort --> RuntimeException */ @Test @@ -100,9 +100,9 @@ void testWarm_DetailedElseAbort_ShouldAbort1() { /** * vehicles information is complete but fully specified entry is NOT available in detailed table * HbefaTechnology is also not in detailed table -> fall back to technology average is NOT possible as well. - * + *

      * LookupBehavior: onlyTryDetailedElseAbort - * + *

      * -> should abort --> RuntimeException */ @Test @@ -116,11 +116,11 @@ void testWarm_DetailedElseAbort_ShouldAbort2() { } -// --------- DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageElseAbort) ----------- +// --------- DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageElseAbort) ----------- /** * vehicles information is complete * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

      * -> do NOT fall back to technology average * ---> should calculate value from detailed value */ @@ -139,7 +139,7 @@ void testWarm_DetailedThenTechnologyAverageElseAbort_FallbackNotNeeded() { /** * vehicles information is complete but fully specified entry is NOT available in detailed table * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

      * -> do fall back to technology average * ---> should calculate value from technology average */ @@ -157,9 +157,9 @@ void testWarm_DetailedThenTechnologyAverageElseAbort_FallbackToTechnologyAverage /** * vehicles information is complete but fully specified entry is NOT available in detailed table * HbefaTechnology is also not in detailed table -> fall back to technology average is NOT possible as well. - * + *

      * LookupBehavior: onlyTryDetailedElseAbort - * + *

      * -> should abort --> RuntimeException */ @Test @@ -172,11 +172,11 @@ void testWarm_DetailedThenTechnologyAverageElseAbort_ShouldAbort() { }); } -// --------- DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable ----------- +// --------- DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable ----------- /** * vehicles information is complete * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

      * -> do NOT fall back to technology average or average table * ---> should calculate value from detailed value */ @@ -195,7 +195,7 @@ void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackNotNeeded() /** * vehicles information is complete but fully specified entry is NOT available in detailed table * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

      * -> do fall back to technology average; do NOT fall back to average table * ---> should calculate value from technology average */ @@ -213,9 +213,9 @@ void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackToTechnology /** * vehicles information is complete but fully specified entry is NOT available in detailed table * HbefaTechnology is also not in detailed table -> fall back to technology average is NOT possible as well. - * + *

      * LookupBehavior: tryDetailedThenTechnologyAverageThenAverageTable - * + *

      * -> do fall back to average table * ---> should calculate value from average table */ @@ -233,7 +233,7 @@ void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackToAverageTab -// ---------- setup and helper methods ------------- +// ---------- setup and helper methods ------------- /** * load and prepare the scenario, create the emissionsModule From fcd62efcdb66cb7f813f01ad8d7127b6c5a66303 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:20:06 +0200 Subject: [PATCH 082/101] javadoc: set link as a link --- .../contrib/emissions/analysis/FastEmissionGridAnalyzer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java index b036c3d9f72..5af1857ae90 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java @@ -54,7 +54,7 @@ public abstract class FastEmissionGridAnalyzer { * 2. The aggregated emissions for each link are rastered onto all the raster-cells covered by the link. * 3. In the smoothing step the emissions are blurred onto the surrounding raster-cells. *

      - * The blurring algorithm is a gaussian blur https://en.wikipedia.org/wiki/Gaussian_blur + * The blurring algorithm is a gaussian blur ... *

      * If only a certain area of the scenario is of interest for the analysis. The supplied network must be filtered beforehand. * The resulting raster's size depends on the bounding box of the supplied network. From 8de79dc8e089d5cd031eddcc324143fac40a630c Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:22:15 +0200 Subject: [PATCH 083/101] logging: use parameterized logging --- .../emissions/ColdEmissionAnalysisModule.java | 35 +++++++++--------- .../emissions/ColdEmissionHandler.java | 7 ++-- .../contrib/emissions/EmissionModule.java | 24 +++++-------- .../contrib/emissions/EmissionUtils.java | 4 +-- .../matsim/contrib/emissions/HbefaTables.java | 2 +- .../emissions/PositionEmissionsModule.java | 2 +- .../emissions/WarmEmissionAnalysisModule.java | 36 +++++++++---------- .../emissions/WarmEmissionHandler.java | 11 +++--- .../analysis/EmissionGridAnalyzer.java | 6 ++-- .../analysis/FastEmissionGridAnalyzer.java | 6 ++-- .../analysis/RawEmissionEventsReader.java | 2 +- .../emissions/utils/EmissionWriter.java | 2 +- .../emissions/utils/EmissionsConfigGroup.java | 8 ++--- .../TestColdEmissionAnalysisModuleCase1.java | 6 ++-- .../TestColdEmissionAnalysisModuleCase2.java | 4 +-- .../TestColdEmissionAnalysisModuleCase3.java | 6 ++-- .../TestColdEmissionAnalysisModuleCase4.java | 6 ++-- .../TestColdEmissionAnalysisModuleCase6.java | 6 ++-- .../TestHbefaWarmEmissionFactorKey.java | 4 +-- 19 files changed, 80 insertions(+), 97 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java index 4e058d47451..6793d6dcaa1 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java @@ -130,7 +130,7 @@ private Map calculateColdEmissions(Id vehicleId, dou final Map coldEmissionsOfEvent = new EnumMap<>( Pollutant.class ); - logger.debug("VehId: " + vehicleId + " ; Tuple.first = " +vehicleInformationTuple.getFirst()); + logger.debug("VehId: {} ; Tuple.first = {}", vehicleId, vehicleInformationTuple.getFirst()); // fallback vehicle types that we cannot or do not want to map onto a hbefa vehicle type: if ( vehicleInformationTuple.getFirst()==HbefaVehicleCategory.NON_HBEFA_VEHICLE ) { for ( Pollutant coldPollutant : coldPollutants) { @@ -218,8 +218,7 @@ private void changeVehCategory(HbefaColdEmissionFactorKey key, HbefaVehicleCateg // } if (vehInfoWarnHDVCnt < maxWarnCnt) { vehInfoWarnHDVCnt++; - logger.warn("Automagic changing of VehCategory is disabled. Please make sure that your table contains the " + - "necessary values for " + originVehCat.name()); + logger.warn("Automagic changing of VehCategory is disabled. Please make sure that your table contains the necessary values for {}", originVehCat.name()); if (vehInfoWarnHDVCnt == maxWarnCnt) logger.warn(Gbl.FUTURE_SUPPRESSED); } } @@ -241,7 +240,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple; average; average'"); logger.warn(Gbl.ONLYONCE); logger.warn(Gbl.FUTURE_SUPPRESSED); @@ -306,7 +305,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple; average; average" should, I think, just be entered as such. kai, feb'20 @@ -336,7 +335,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple; average; average'"); logger.warn(Gbl.ONLYONCE); logger.warn(Gbl.FUTURE_SUPPRESSED); @@ -370,7 +369,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple; average; average" should, I think, just be entered as such. kai, feb'20 @@ -387,7 +386,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple list = new ArrayList<>(this.avgHbefaColdTable.keySet()); list.sort(Comparator.comparing(HbefaColdEmissionFactorKey::toString)); for (HbefaColdEmissionFactorKey key : list) { diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionHandler.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionHandler.java index 74dfec02974..97eeee4956b 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionHandler.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionHandler.java @@ -17,7 +17,7 @@ * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * - * + * * *********************************************************************** */ package org.matsim.contrib.emissions; @@ -134,8 +134,7 @@ static void handleNullVehicleECG(Id vehicleId, EmissionsConfigGroup emi + " Aborting..." ); case ignore: if ( noVehWarnCnt < 10 ){ - logger.warn( - "No vehicle defined for id " + vehicleId + ". The vehicle will be ignored." ); + logger.warn("No vehicle defined for id {}. The vehicle will be ignored.", vehicleId); noVehWarnCnt++; if ( noVehWarnCnt == 10 ) logger.warn( Gbl.FUTURE_SUPPRESSED ); } @@ -201,7 +200,7 @@ public void handleEvent(VehicleEntersTrafficEvent event) { private void warnIfZeroLinkLength(Id linkId, double linkLength) { if (linkLength == 0.) { if (zeroLinkLengthWarnCnt == 0) { - logger.warn("Length of the link " + linkId + " is zero. No emissions will be estimated for this link. Make sure, this is intentional."); + logger.warn("Length of the link {} is zero. No emissions will be estimated for this link. Make sure, this is intentional.", linkId); logger.warn(Gbl.ONLYONCE); zeroLinkLengthWarnCnt++; } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java index 842075c1ba9..e7eaec3a17c 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java @@ -103,27 +103,19 @@ public EventsManager getEmissionEventsManager() { } public void writeEmissionInformation() { - logger.info("Warm emissions were not calculated for " + warmEmissionHandler.getLinkLeaveWarnCnt() + " of " + - warmEmissionHandler.getLinkLeaveCnt() + " link leave events (no corresponding link enter event)."); + logger.info("Warm emissions were not calculated for {} of {} link leave events (no corresponding link enter event).", warmEmissionHandler.getLinkLeaveWarnCnt(), warmEmissionHandler.getLinkLeaveCnt()); int noVehicleLeavesTrafficEmissions = warmEmissionHandler.getSameLinkTrafficLeaveWarnCnt() + warmEmissionHandler.getUnusualTrafficLeaveWarnCnt(); - logger.info("Warm emissions were not calculated for " + noVehicleLeavesTrafficEmissions + " of " + warmEmissionHandler.getTrafficLeaveCnt() + - " vehicle leaves traffic events (no corresponding link enter event)."); + logger.info("Warm emissions were not calculated for {} of {} vehicle leaves traffic events (no corresponding link enter event).", noVehicleLeavesTrafficEmissions, warmEmissionHandler.getTrafficLeaveCnt()); if ( warmEmissionHandler.getUnusualTrafficLeaveWarnCnt() > 0 ) { - logger.info(warmEmissionHandler.getUnusualTrafficLeaveWarnCnt() + " events occurred where the vehicle left traffic without entering ANY link " + - "(no warm emissions calculated). These events might need to be investigated."); } + logger.info("{} events occurred where the vehicle left traffic without entering ANY link (no warm emissions calculated). These events might need to be investigated.", warmEmissionHandler.getUnusualTrafficLeaveWarnCnt()); } WarmEmissionAnalysisModule wam = warmEmissionHandler.getWarmEmissionAnalysisModule(); - logger.info("Emission calculation based on `Free flow only' occured for " + wam.getFreeFlowOccurences() + " of " + - wam.getWarmEmissionEventCounter() + " warm emission events."); - logger.info("Emission calculation based on `Stop&Go only' occured for " + wam.getStopGoOccurences() + " of " + - wam.getWarmEmissionEventCounter() + " warm emission events."); - logger.info("Emission calculation based on `Fractions' occured for " + wam.getFractionOccurences() + " of " + - wam.getWarmEmissionEventCounter() + " warm emission events."); - logger.info("Free flow occured on " + wam.getFreeFlowKmCounter() + " km of total " + - wam.getKmCounter() + " km, where emissions were calculated."); - logger.info("Stop&Go occured on " + wam.getStopGoKmCounter() + " km of total " + - wam.getKmCounter() + " km, where emissions were calculated."); + logger.info("Emission calculation based on `Free flow only' occured for {} of {} warm emission events.", wam.getFreeFlowOccurences(), wam.getWarmEmissionEventCounter()); + logger.info("Emission calculation based on `Stop&Go only' occured for {} of {} warm emission events.", wam.getStopGoOccurences(), wam.getWarmEmissionEventCounter()); + logger.info("Emission calculation based on `Fractions' occured for {} of {} warm emission events.", wam.getFractionOccurences(), wam.getWarmEmissionEventCounter()); + logger.info("Free flow occured on {} km of total {} km, where emissions were calculated.", wam.getFreeFlowKmCounter(), wam.getKmCounter()); + logger.info("Stop&Go occured on {} km of total {} km, where emissions were calculated.", wam.getStopGoKmCounter(), wam.getKmCounter()); logger.info("Emission calculation terminated. Emission events can be found in regular events file."); } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java index 4b7ed17b902..e174e14192c 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java @@ -225,7 +225,7 @@ static Tuple convertVehicleDescrip EngineInformation engineInformation; // get information from where it used to be in previous versions and move to where it should be now: - logger.debug("emissionsConfigGroup.getHbefaVehicleDescriptionSource=" + emissionsConfigGroup.getHbefaVehicleDescriptionSource()); + logger.debug("emissionsConfigGroup.getHbefaVehicleDescriptionSource={}", emissionsConfigGroup.getHbefaVehicleDescriptionSource()); switch( emissionsConfigGroup.getHbefaVehicleDescriptionSource() ) { case usingVehicleTypeId: // (v1, hbefa vehicle description is in vehicle type id. Copy to where it is expected now) @@ -320,7 +320,7 @@ public static HbefaVehicleCategory mapString2HbefaVehicleCategory(String string) try{ hbefaVehicleCategory = HbefaVehicleCategory.valueOf(string); } catch (IllegalArgumentException e) { - logger.warn("Could not map String " + string + " to any HbefaVehicleCategory; please check syntax in hbefa input file."); + logger.warn("Could not map String {} to any HbefaVehicleCategory; please check syntax in hbefa input file.", string); throw new RuntimeException(); } } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaTables.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaTables.java index b3d23dedb82..f01d42bb0f7 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaTables.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaTables.java @@ -125,7 +125,7 @@ private static HbefaTrafficSituation mapString2HbefaTrafficSituation(String stri else if (string.endsWith("St+Go")) return HbefaTrafficSituation.STOPANDGO; else if (string.endsWith("St+Go2")) return HbefaTrafficSituation.STOPANDGO_HEAVY; else { - logger.warn("Could not map String " + string + " to any HbefaTrafficSituation; please check syntax in hbefa input file."); + logger.warn("Could not map String {} to any HbefaTrafficSituation; please check syntax in hbefa input file.", string); throw new RuntimeException(); } } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java index 4652c3d7339..1f6304d0ade 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java @@ -290,7 +290,7 @@ private void computeCombinedEmissionEvent(PositionEvent event) { eventsManager.processEvent(new PositionEmissionEvent(event, combinedEmissions, "combined")); } else { - log.warn("speed was too fast: " + speed + "m/s Current time: " + event.getTime() + " prev time: " + previousPosition.getTime() + " current linkId: " + event.getLinkId() + " prev linkId: " + previousPosition.getLinkId() + " agentId: " + event.getPersonId()); + log.warn("speed was too fast: {}m/s Current time: {} prev time: {} current linkId: {} prev linkId: {} agentId: {}", speed, event.getTime(), previousPosition.getTime(), event.getLinkId(), previousPosition.getLinkId(), event.getPersonId()); } } else { // if the vehicle hasn't moved, issue an event with 0 emissions. This way there is an event for every timestep diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java index ff055cf31fd..33b43c8a9e1 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java @@ -275,7 +275,7 @@ Map calculateWarmEmissions(double travelTime_sec, String road } if ((averageSpeed_kmh - freeVelocity_ms * 3.6) > 1.0){ if (ecg.getHandleHighAverageSpeeds()) { - logger.warn("averageSpeed was capped from " + averageSpeed_kmh + " to" + freeVelocity_ms * 3.6 ); + logger.warn("averageSpeed was capped from {} to{}", averageSpeed_kmh, freeVelocity_ms * 3.6); averageSpeed_kmh = freeVelocity_ms * 3.6; } else { throw new RuntimeException("Average speed has been calculated to be greater than free flow speed; this might produce negative warm emissions. Aborting..."); @@ -307,7 +307,7 @@ Map calculateWarmEmissions(double travelTime_sec, String road // compute emissions from stop-go fraction: efkey.setTrafficSituation(STOPANDGO); efStopGo_gpkm = getEf(vehicleInformationTuple, efkey).getFactor(); - logger.debug("pollutant=" + warmPollutant + "; efStopGo=" + efStopGo_gpkm); + logger.debug("pollutant={}; efStopGo={}", warmPollutant, efStopGo_gpkm); } @@ -316,7 +316,7 @@ Map calculateWarmEmissions(double travelTime_sec, String road // compute emissions for free-flow fraction: efkey.setTrafficSituation(FREEFLOW); efFreeFlow_gpkm = getEf(vehicleInformationTuple, efkey).getFactor(); - logger.debug("pollutant=" + warmPollutant + "; efFreeFlow=" + efFreeFlow_gpkm); + logger.debug("pollutant={}; efFreeFlow={}", warmPollutant, efFreeFlow_gpkm); } // sum them up: @@ -379,7 +379,7 @@ private HbefaWarmEmissionFactor getEf(Tuple; average; average'" ); logger.warn( Gbl.ONLYONCE ); logger.warn( Gbl.FUTURE_SUPPRESSED ); @@ -444,7 +444,7 @@ private HbefaWarmEmissionFactor getEf(Tuple; average; average" should, I think, just be entered as such. kai, feb'20 @@ -462,7 +462,7 @@ private HbefaWarmEmissionFactor getEf(Tuple; average; average'" ); logger.warn( Gbl.ONLYONCE ); logger.warn( Gbl.FUTURE_SUPPRESSED ); @@ -496,7 +496,7 @@ private HbefaWarmEmissionFactor getEf(Tuple; average; average" should, I think, just be entered as such. kai, feb'20 @@ -513,7 +513,7 @@ private HbefaWarmEmissionFactor getEf(Tuple list = new ArrayList<>( this.avgHbefaWarmTable.keySet() ); list.sort( Comparator.comparing( HbefaWarmEmissionFactorKey::toString ) ); for ( HbefaWarmEmissionFactorKey key : list ) { diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionHandler.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionHandler.java index 8213320fdff..03a57d63b17 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionHandler.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionHandler.java @@ -123,12 +123,10 @@ public void handleEvent(VehicleLeavesTrafficEvent event) { handleNullVehicle(vehicleId); } } else if ( this.vehicleEntersTrafficMap.containsKey( vehicleId ) ) { - logger.warn("At time " + event.getTime() + ", vehicle " + event.getVehicleId() + " enters and leaves traffic without" + - " having entered link " + event.getLinkId() + ". Thus, no emissions are calculated for travel along this link."); + logger.warn("At time {}, vehicle {} enters and leaves traffic without having entered link {}. Thus, no emissions are calculated for travel along this link.", event.getTime(), event.getVehicleId(), event.getLinkId()); sameLinkTrafficLeaveWarnCnt++; } else { - logger.warn("At time " + event.getTime() + ", vehicle " + event.getVehicleId() + " left traffic without entering traffic " + - "or ANY link. Thus, no emissions are calculated for this unusual event."); + logger.warn("At time {}, vehicle {} left traffic without entering traffic or ANY link. Thus, no emissions are calculated for this unusual event.", event.getTime(), event.getVehicleId()); unusualTrafficLeaveWarnCnt++; } } @@ -191,7 +189,7 @@ private void emissionsCalculation(Id vehicleId, Vehicle vehicle, Link l private boolean linkLengthIsZero( Id linkId, double linkLength) { if (linkLength == 0.) { if (zeroLinkLengthWarnCnt == 0) { - logger.warn("Length of the link " + linkId + " is zero. No emissions will be estimated for this link. Make sure that this is intentional."); + logger.warn("Length of the link {} is zero. No emissions will be estimated for this link. Make sure that this is intentional.", linkId); logger.warn(Gbl.ONLYONCE); zeroLinkLengthWarnCnt++; } @@ -211,8 +209,7 @@ private void handleNullVehicle(Id vehicleId) { + " Aborting..."); } else if (this.warmEmissionAnalysisModule.getEcg().getNonScenarioVehicles().equals(NonScenarioVehicles.ignore)) { if (noVehWarnCnt < 10) { - logger.warn( - "No vehicle defined for id " + vehicleId + ". The vehicle will be ignored."); + logger.warn("No vehicle defined for id {}. The vehicle will be ignored.", vehicleId); noVehWarnCnt++; if (noVehWarnCnt == 10) logger.warn(Gbl.FUTURE_SUPPRESSED); } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzer.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzer.java index 1454c799a48..65586e05d91 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzer.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzer.java @@ -106,7 +106,7 @@ public TimeBinMap>> process(String eventsFile) { logger.info("Starting grid computation..."); for (var bin : timeBinsWithEmissions.getTimeBins()) { - logger.info("creating grid for time bin with start time: " + bin.getStartTime()); + logger.info("creating grid for time bin with start time: {}", bin.getStartTime()); Grid> grid = writeAllLinksToGrid(bin.getValue()); result.getTimeBin(bin.getStartTime()).setValue(grid); } @@ -153,7 +153,7 @@ public Tuple processNextTimeBin() { if (!this.timeBins.hasNext()) throw new RuntimeException("processNextTimeBin() was called too many times"); TimeBinMap.TimeBin, EmissionsByPollutant>> nextBin = this.timeBins.next(); - logger.info("creating grid for time bin with start time: " + nextBin.getStartTime()); + logger.info("creating grid for time bin with start time: {}", nextBin.getStartTime()); Grid> grid = writeAllLinksToGrid(nextBin.getValue()); @@ -224,7 +224,7 @@ private Grid> writeAllLinksToGrid(Map, Emissions .forEach(entry -> { var count = counter.incrementAndGet(); if (count % 10000 == 0) - logger.info("processing: " + count * 100 / linksWithEmissions.keySet().size() + "% done"); + logger.info("processing: {}% done", count * 100 / linksWithEmissions.keySet().size()); if (network.getLinks().containsKey(entry.getKey()) && isWithinBounds(network.getLinks().get(entry.getKey()))) { processLink(network.getLinks().get(entry.getKey()), entry.getValue(), grid); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java index 5af1857ae90..fdff9835fa6 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java @@ -92,7 +92,7 @@ public static Map processEventsFile(final String eventsFile, logger.info("Start smoothing pollution."); return linkEmissionsByPollutant.entrySet().stream() .map(entry -> { - logger.info("Smoothing of: " + entry.getKey()); + logger.info("Smoothing of: {}", entry.getKey()); return Tuple.of(entry.getKey(), processLinkEmissions(entry.getValue(), network, cellSize, radius)); }) .collect(Collectors.toMap(Tuple::getFirst, Tuple::getSecond)); @@ -116,7 +116,7 @@ public static Map processHandlerEmissions(Map, Map

      { - logger.info("Smoothing of: " + entry.getKey()); + logger.info("Smoothing of: {}", entry.getKey()); return Tuple.of(entry.getKey(), processLinkEmissions(entry.getValue(), network, cellSize, radius)); }) .collect(Collectors.toMap(Tuple::getFirst, Tuple::getSecond)); @@ -192,7 +192,7 @@ public static Raster processLinkEmissions(final Map, Double> emissions, static Raster blur(Raster raster, int radius) { - logger.info("Creating Kernel with " + (radius * 2 + 1) + " taps"); + logger.info("Creating Kernel with {} taps", radius * 2 + 1); var kernel = createKernel(radius * 2 + 1); var result = new Raster(raster.getBounds(), raster.getCellSize()); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReader.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReader.java index ff962f67cff..283d144e0bb 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReader.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReader.java @@ -103,7 +103,7 @@ private void handleEmissionEvent(Attributes atts) { // give some feedback about progress var currentCount = eventsCounter.incrementAndGet(); if (currentCount % 500000 == 0) { - logger.info("Emission Event # " + numberFormat.format(currentCount)); + logger.info("Emission Event # {}", numberFormat.format(currentCount)); } } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java index 10ba02d6243..f402d16519f 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java @@ -83,7 +83,7 @@ public void writeHomeLocation2TotalEmissions( } //Close the output stream out.close(); - logger.info("Finished writing output to " + outFile); + logger.info("Finished writing output to {}", outFile); } catch (Exception e){ throw new RuntimeException(e); } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java index e64ef90be51..a5d366ae78f 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java @@ -317,12 +317,8 @@ public void setEmissionsComputationMethod(EmissionsComputationMethod emissionsCo @Override protected final void checkConsistency(Config config){ switch( this.emissionsComputationMethod ){ - case StopAndGoFraction -> log.info( "Please note that with setting of emissionsComputationMethod " + EmissionsComputationMethod.StopAndGoFraction + "" + - " the emission factors for both freeFlow and StopAndGo fractions are looked up independently and are " + - "therefore following the fallback behaviour set in " + DETAILED_VS_AVERAGE_LOOKUP_BEHAVIOR + - " independently. --> Depending on the input, it may be that e.g. for ff the detailed value is taken, while for the stopAndGo part " + - "a less detailed value is used, because the value with the same level of detail is missing." ); - case AverageSpeed -> log.warn( "This setting of emissionsComputationMethod. " + EmissionsComputationMethod.AverageSpeed + " is not covered by many test cases." ); + case StopAndGoFraction -> log.info("Please note that with setting of emissionsComputationMethod {} the emission factors for both freeFlow and StopAndGo fractions are looked up independently and are therefore following the fallback behaviour set in " + DETAILED_VS_AVERAGE_LOOKUP_BEHAVIOR + " independently. --> Depending on the input, it may be that e.g. for ff the detailed value is taken, while for the stopAndGo part a less detailed value is used, because the value with the same level of detail is missing.", EmissionsComputationMethod.StopAndGoFraction); + case AverageSpeed -> log.warn("This setting of emissionsComputationMethod. {} is not covered by many test cases.", EmissionsComputationMethod.AverageSpeed); default -> throw new IllegalStateException( "Unexpected value: " + this.emissionsComputationMethod ); } } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java index 07da985b0a3..3dc63ebde3a 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java @@ -107,13 +107,13 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { // first case: complete data // corresponding entry in average table Collections.addAll(testCase1, "PASSENGER_CAR", petrol_technology, none_sizeClass, none_emConcept, averagePetrolFactor); - logger.info("Running testcase:" + testCase1); + logger.info("Running testcase:{}", testCase1); Id linkId = Id.create("linkId" + testCase1, Link.class); Id vehicleId = Id.create("vehicleId" + testCase1, Vehicle.class); Id vehicleTypeId = Id.create(testCase1.get(0) + ";" + testCase1.get(1) + ";" + testCase1.get(2) + ";" + testCase1.get(3), VehicleType.class); Vehicle vehicle = VehicleUtils.getFactory().createVehicle(vehicleId, VehicleUtils.getFactory().createVehicleType(vehicleTypeId)); - logger.info("VehicleId: " + vehicle.getId().toString()); - logger.info("VehicleTypeId: " + vehicle.getType().getId()); + logger.info("VehicleId: {}", vehicle.getId().toString()); + logger.info("VehicleTypeId: {}", vehicle.getType().getId()); final Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java index ccf34b068bd..c5ce8831a6a 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java @@ -105,8 +105,8 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { Id vehicleId = Id.create( "vehicleId" + testCase2 , Vehicle.class ); Id vehicleTypeId = Id.create( testCase2.get( 0 ) + ";" + testCase2.get( 1 ) + ";" + testCase2.get( 2 ) + ";" + testCase2.get( 3 ), VehicleType.class ); Vehicle vehicle = VehicleUtils.getFactory().createVehicle( vehicleId, VehicleUtils.getFactory().createVehicleType( vehicleTypeId ) ); - logger.info("VehicleId: " + vehicle.getId().toString()); - logger.info("VehicleTypeId: " + vehicle.getType().getId()); + logger.info("VehicleId: {}", vehicle.getId().toString()); + logger.info("VehicleTypeId: {}", vehicle.getType().getId()); Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase3.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase3.java index fbebf02e2ce..52bee68cde3 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase3.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase3.java @@ -103,14 +103,14 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { // error when using the average entry. Collections.addAll( testCase3, "PASSENGER_CAR", diesel_technology, geq2l_sizeClass, PC_D_Euro_3_emConcept, detailedDieselFactor ); - logger.info("Running testcase: " + testCase3); + logger.info("Running testcase: {}", testCase3); Id linkId = Id.create( "linkId" + testCase3 , Link.class ); Id vehicleId = Id.create( "vehicleId" + testCase3, Vehicle.class ); Id vehicleTypeId = Id.create( testCase3.get( 0 ) + ";" + testCase3.get( 1 ) + ";" + testCase3.get( 2 ) + ";" + testCase3.get( 3 ), VehicleType.class ); Vehicle vehicle = VehicleUtils.getFactory().createVehicle( vehicleId, VehicleUtils.getFactory().createVehicleType( vehicleTypeId ) ); - logger.info("VehicleId: " + vehicle.getId().toString()); - logger.info("VehicleTypeId: " + vehicle.getType().getId()); + logger.info("VehicleId: {}", vehicle.getId().toString()); + logger.info("VehicleTypeId: {}", vehicle.getType().getId()); Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase4.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase4.java index c64e78372b8..021503fa903 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase4.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase4.java @@ -113,14 +113,14 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { Collections.addAll( testCase4, "PASSENGER_CAR", "", "", "", averageAverageFactor ); - logger.info("Running testcase: " + testCase4.indexOf( 0 ) + " " + testCase4); + logger.info("Running testcase: {} {}", testCase4.indexOf(0), testCase4); Id linkId = Id.create( "linkId" + testCase4.indexOf( 0 ), Link.class ); Id vehicleId = Id.create( "vehicleId" + testCase4.indexOf( 0 ), Vehicle.class ); Id vehicleTypeId = Id.create( testCase4.get( 0 ) + ";" + testCase4.get( 1 ) + ";" + testCase4.get( 2 ) + ";" + testCase4.get( 3 ), VehicleType.class ); Vehicle vehicle = VehicleUtils.getFactory().createVehicle( vehicleId, VehicleUtils.getFactory().createVehicleType( vehicleTypeId ) ); - logger.info("VehicleId: " + vehicle.getId().toString()); - logger.info("VehicleTypeId: " + vehicle.getType().getId()); + logger.info("VehicleId: {}", vehicle.getId().toString()); + logger.info("VehicleTypeId: {}", vehicle.getType().getId()); Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase6.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase6.java index d97ddf5162d..8013a55267b 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase6.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase6.java @@ -108,14 +108,14 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { String heavygoodsvehicle = "HEAVY_GOODS_VEHICLE"; Collections.addAll( testCase6, heavygoodsvehicle, petrol_technology, none_sizeClass, none_emConcept, heavyGoodsFactor); - logger.info("Running testcase: " + testCase6 + " " + testCase6); + logger.info("Running testcase: {} {}", testCase6, testCase6); Id linkId = Id.create( "linkId" + testCase6, Link.class ); Id vehicleId = Id.create( "vehicleId" + testCase6, Vehicle.class ); Id vehicleTypeId = Id.create( testCase6.get( 0 ) + ";" + testCase6.get( 1 ) + ";" + testCase6.get( 2 ) + ";" + testCase6.get( 3 ), VehicleType.class ); Vehicle vehicle = VehicleUtils.getFactory().createVehicle( vehicleId, VehicleUtils.getFactory().createVehicleType( vehicleTypeId ) ); - logger.info("VehicleId: " + vehicle.getId().toString()); - logger.info("VehicleTypeId: " + vehicle.getType().getId()); + logger.info("VehicleId: {}", vehicle.getId().toString()); + logger.info("VehicleTypeId: {}", vehicle.getType().getId()); Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java index 947e985d7b3..b9bc83aa597 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java @@ -121,8 +121,8 @@ final void testEqualsForIncompleteKeys_vehicleCategory() { noVehCat.setTrafficSituation(hbefaTrafficSituation); noVehCat.setVehicleAttributes(hbefaVehicleAttributes); - log.warn("normal=" + normal); - log.warn("noVehCat=" + noVehCat); + log.warn("normal={}", normal); + log.warn("noVehCat={}", noVehCat); var result = noVehCat.equals(normal); From f9ccc498b7f34c3b153346ead6117d362bd26ce6 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:25:25 +0200 Subject: [PATCH 084/101] add casting --- .../matsim/contrib/emissions/WarmEmissionAnalysisModule.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java index 33b43c8a9e1..3b59b10d5a9 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java @@ -593,8 +593,8 @@ private void incrementCountersFractional(double linkLength_km, double fractionSt freeFlowKmCounter += linkLength_km * (1-fractionStopGo); stopGoKmCounter += linkLength_km * fractionStopGo; - freeFlowCounter += 1-fractionStopGo; - stopGoCounter += fractionStopGo; + freeFlowCounter += (int) (1-fractionStopGo); + stopGoCounter += (int) fractionStopGo; fractionCounter += (fractionStopGo < 1.0 && fractionStopGo > 0.0) ? 1 : 0; } From 268f609aac1a1334e87e087041cb847d0808732a Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:26:53 +0200 Subject: [PATCH 085/101] simplification --- .../emissions/analysis/EmissionsByPollutantTest.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java index 635affd8832..208bd5e1328 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java @@ -25,8 +25,7 @@ void initialize() { Map emissions = EmissionUtilsTest.createEmissions(); - Map map = new LinkedHashMap<>(); - emissions.forEach( map::put ) ; + Map map = new LinkedHashMap<>(emissions); EmissionsByPollutant linkEmissions = new EmissionsByPollutant( map ) ; @@ -47,7 +46,7 @@ void addEmission() { final double expectedValue = emissions.get(pollutant) + valueToAdd; Map map = new LinkedHashMap<>(); - emissions.forEach( map::put ) ; + map.putAll(emissions); EmissionsByPollutant emissionsByPollutant = new EmissionsByPollutant(map); @@ -80,12 +79,12 @@ void addEmissions() { Map emissions = EmissionUtilsTest.createEmissions(); Map map = new LinkedHashMap<>(); - emissions.forEach( map::put ) ; + map.putAll(emissions); EmissionsByPollutant linkEmissions = new EmissionsByPollutant(map); Map map2 = new LinkedHashMap<>(); - emissions.forEach( map2::put ) ; + map2.putAll(emissions); linkEmissions.addEmissions(map2); From 44713d945e1320f1912c52040b01f2dcb6ab6973 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:27:48 +0200 Subject: [PATCH 086/101] use 'append()' calls --- .../org/matsim/contrib/emissions/utils/EmissionWriter.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java index f402d16519f..ce87ab17cb0 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java @@ -57,7 +57,7 @@ public void writeHomeLocation2TotalEmissions( BufferedWriter out = new BufferedWriter(fstream); out.append("personId \t xHome \t yHome \t"); for (String pollutant : pollutants){ - out.append(pollutant + "[g] \t"); + out.append(pollutant).append("[g] \t"); } out.append("\n"); @@ -69,12 +69,12 @@ public void writeHomeLocation2TotalEmissions( Double xHome = homeCoord.getX(); Double yHome = homeCoord.getY(); - out.append(personId + "\t" + xHome + "\t" + yHome + "\t"); + out.append(String.valueOf(personId)).append("\t").append(String.valueOf(xHome)).append("\t").append(String.valueOf(yHome)).append("\t"); Map emissionType2Value = totalEmissions.get(personId); for(String pollutant : pollutants){ if(emissionType2Value.get(pollutant) != null){ - out.append(emissionType2Value.get(pollutant) + "\t"); + out.append(String.valueOf(emissionType2Value.get(pollutant))).append("\t"); } else{ out.append("0.0" + "\t"); // TODO: do I still need this? } From 8fd0955d13b4feb87e3cfb479b9b6de48fb3f238 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:30:40 +0200 Subject: [PATCH 087/101] simplification by removing inaccessibly parts of if statements. --- .../contrib/emissions/example/CreateEmissionConfig.java | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java index b0b73b6bd28..ee492e3bb25 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java @@ -119,13 +119,7 @@ public static void main(String[] args) { // emission vehicles are now set in the default vehicle container config.vehicles().setVehiclesFile(emissionVehicleFile); - if ( (Boolean) false ==null ) { - ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.asEngineInformationAttributes ); - } else if ( false ) { - ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.usingVehicleTypeId ); - } else { - ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.fromVehicleTypeDescription ); - } + ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.fromVehicleTypeDescription ); ecg.setAverageWarmEmissionFactorsFile(averageFleetWarmEmissionFactorsFile); ecg.setAverageColdEmissionFactorsFile(averageFleetColdEmissionFactorsFile); From 1a8510d8421b8021c4f8998839d44fc80dd5ac60 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:34:01 +0200 Subject: [PATCH 088/101] remove duplicated setting of variable --- .../contrib/emissions/TestWarmEmissionAnalysisModule.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java index 9d6fc109be9..813cb15e28b 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java @@ -182,8 +182,6 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Ex excep = true; } Assertions.assertFalse(excep); - - excep=false; } @ParameterizedTest @@ -209,7 +207,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Ex }catch(Exception e){ excep = true; } - Assertions.assertTrue(excep); excep=false; + Assertions.assertTrue(excep); } @ParameterizedTest @@ -234,7 +232,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Ex }catch(Exception e){ excep = true; } - Assertions.assertTrue(excep); excep=false; + Assertions.assertTrue(excep); } @ParameterizedTest @@ -257,7 +255,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Ex }catch(Exception e){ excep = true; } - Assertions.assertTrue(excep); excep=false; + Assertions.assertTrue(excep); } From 3fa72e9774ef780074099e4bcb20d498c0fb0b1f Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:35:56 +0200 Subject: [PATCH 089/101] Simplify assertions --- .../TestHbefaColdEmissionFactorKey.java | 14 +++++++------- .../TestHbefaWarmEmissionFactorKey.java | 19 ++++++++++--------- .../emissions/utils/EmissionUtilsTest.java | 14 +++++++------- 3 files changed, 24 insertions(+), 23 deletions(-) diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java index e0181758ad3..d9475cdc817 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java @@ -126,7 +126,7 @@ final void testEqualsForIncompleteKeys_vehicleCategory(){ noVehCat.setVehicleAttributes(hbefaVehicleAttributes); String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal + " and " + noVehCat; - assertFalse(noVehCat.equals(normal), message); + assertNotEquals(noVehCat, normal, message); } @Test @@ -145,7 +145,7 @@ final void testEqualsForIncompleteKeys_pollutant(){ noColdPollutant.setVehicleAttributes(hbefaVehicleAttributes); String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noColdPollutant; - assertFalse(noColdPollutant.equals(normal), message); + assertNotEquals(noColdPollutant, normal, message); } @Test @@ -164,7 +164,7 @@ final void testEqualsForIncompleteKeys_parkingTime() { noParkingTime.setVehicleAttributes(hbefaVehicleAttributes); String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noParkingTime; - assertFalse(noParkingTime.equals(normal), message); + assertNotEquals(noParkingTime, normal, message); } @Test @@ -183,7 +183,7 @@ final void testEqualsForIncompleteKeys_distance() { noDistance.setVehicleAttributes(hbefaVehicleAttributes); String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noDistance; - assertFalse(noDistance.equals(normal), message); + assertNotEquals(noDistance, normal, message); } @Test @@ -198,7 +198,7 @@ final void testEqualsForIncompleteKeys_emptyKey() { HbefaColdEmissionFactorKey emptyKey = new HbefaColdEmissionFactorKey(); String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + emptyKey; - assertFalse(emptyKey.equals(normal), message); + assertNotEquals(emptyKey, normal, message); } @Test @@ -225,7 +225,7 @@ final void testEqualsForIncompleteKeys_VehicleAttributes(){ noVehAtt.setVehicleCategory(hbefaVehCategory); String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal + " and " + noVehAtt; - assertFalse(noVehAtt.equals(normal), message); + assertNotEquals(noVehAtt, normal, message); //set the vehicle attributes of the normal hbefaColdWmissionFactorKey to 'average' @@ -237,7 +237,7 @@ final void testEqualsForIncompleteKeys_VehicleAttributes(){ hbefaVehicleAttributesAverage.setHbefaTechnology("average"); normal.setVehicleAttributes(hbefaVehicleAttributesAverage); - Assertions.assertTrue(noVehAtt.equals(normal), message); + assertEquals(noVehAtt, normal, message); } } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java index b9bc83aa597..23ecb51b684 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java @@ -26,6 +26,7 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.matsim.contrib.emissions.Pollutant.CO; import static org.matsim.contrib.emissions.Pollutant.FC; @@ -80,8 +81,8 @@ final void testEqualsForCompleteKeys(){ compare.setVehicleCategory(hbefaVehicleCategory); String message = "these two objects should be the same but are not: " + normal.toString() + " and " + compare; - Assertions.assertTrue(normal.equals(compare), message); - Assertions.assertTrue(compare.equals(normal), message); + Assertions.assertEquals(normal, compare, message); + Assertions.assertEquals(compare, normal, message); //two unequal but complete objects HbefaWarmEmissionFactorKey different = new HbefaWarmEmissionFactorKey(); @@ -97,8 +98,8 @@ final void testEqualsForCompleteKeys(){ message = "these two objects should not be the same: " + normal.toString() + " and " + different; - assertFalse(different.equals(normal), message); - assertFalse(normal.equals(different), message); + assertNotEquals(different, normal, message); + assertNotEquals(normal, different, message); } // the following tests each compare a incomplete key to a complete key @@ -170,7 +171,7 @@ final void testEqualsForIncompleteKeys_roadCategory() { String message = "these two HbefaWarmEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noRoadCat; String message2 = "this key should not be comparable since no road category is set"; Assertions.assertTrue(equalErr, message2); - assertFalse(normal.equals(noRoadCat), message); + assertNotEquals(normal, noRoadCat, message); } @Test @@ -233,11 +234,11 @@ final void testEqualsForIncompleteKeys_vehicleAttributes(){ } String message = "these two HbefaWarmEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noVehAtt; - assertFalse(noVehAtt.equals(normal), message); + assertNotEquals(noVehAtt, normal, message); assertFalse(equalErr); // veh attributes are allowed to be not initiated // therefore this should not throw a nullpointer but return false - assertFalse(normal.equals(noVehAtt), message); + assertNotEquals(normal, noVehAtt, message); //set the vehicle attributes of the normal hbefacoldemissionfactorkey to 'average' //then noVehAtt is equal to normal @@ -248,8 +249,8 @@ final void testEqualsForIncompleteKeys_vehicleAttributes(){ normal.setVehicleAttributes(hbefaVehicleAttributesAverage); message = "these two HbefaWarmEmissionFactorKeys should be the same: " + normal.toString() + " and " + noVehAtt; - Assertions.assertTrue(normal.equals(noVehAtt), message); - Assertions.assertTrue(noVehAtt.equals(normal), message); + Assertions.assertEquals(normal, noVehAtt, message); + Assertions.assertEquals(noVehAtt, normal, message); } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java index 4f20dfbf78f..9d978f682e6 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java @@ -52,8 +52,8 @@ * missing data is not tested here * negative emission values are allowed * 1 test constructor - * 2 test sumUpEmissions - * 3 test sumUpEmissionPerId + * 2 test sumUpEmissions + * 3 test sumUpEmissionPerId * 4 test getTotalEmissions * 5 test SetNonCalculatedEmissionsForPopulation * - correct input - population does not match map of emissions - empty map of emissions @@ -430,7 +430,7 @@ final void testSetNonCalculatedEmissionsForPopulation_completeData(){ //check: all values for person 1 and 2 are not null or zero // and of type double for(Object id : finalMap.keySet()) { - Assertions.assertTrue(id instanceof Id); + Assertions.assertInstanceOf(Id.class, id); for (Object pollutant : finalMap.get(id).values()) { Assertions.assertSame(pollutant.getClass(), Double.class); Assertions.assertNotSame(0.0, pollutant); @@ -553,7 +553,7 @@ final void testSetNonCalculatedEmissionsForPopulation_nullEmissions(){ //test setNonCalculatedEmissionsForPopulation with 'null' // throw nullpointer exception setUpForNonCaculatedEmissions(); - + Id idp5 = Id.create("p5", Person.class); Person p5 = populationFactory.createPerson(idp5); pop.addPerson(p5); @@ -576,7 +576,7 @@ final void testSetNonCalculatedEmissionsForPopulation_emptyPopulation(){ // empty list should be returned setUpForNonCaculatedEmissions(); - //person 7 in totalEmissions but not in population + //person 7 in totalEmissions but not in population SortedMap p7Emissions = new TreeMap<>(); //complete list of all pollutants - missing data is not tested here p7Emissions.put( CO, .0 ); @@ -815,6 +815,6 @@ private void addLinksToNetwork(Scenario sc) { NetworkUtils.createAndAddLink(network, Id.create("link24", Link.class), node2, node4, 1000., 20., 3600, 2); NetworkUtils.createAndAddLink(network, Id.create("link34", Link.class), node3, node4, 1000., 20., 3600, 2); //w/o orig id and type } - + } - + From 04ad679817835d515dd0087d5ff0b7bdf9131b86 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:37:35 +0200 Subject: [PATCH 090/101] Simplify stream --- .../java/org/matsim/contrib/emissions/OsmHbefaMapping.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java index 27da7acf1be..f9de1d049b1 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java @@ -25,9 +25,9 @@ import org.matsim.api.core.v01.network.Link; import org.matsim.core.network.NetworkUtils; -import java.util.Arrays; import java.util.HashMap; import java.util.Map; +import java.util.stream.Stream; /** * Created by molloyj on 01.12.2017. @@ -123,8 +123,7 @@ private String getHEBFAtype(String type, double speed) { //sometimes link type is smth like 'motorway_link' or 'living_street' or 'primary|railway.tram'. We only care about the first part, here - int idx = Arrays.asList(type.indexOf('.'), type.indexOf('|'), type.indexOf('_'), type.indexOf(',')) - .stream() + int idx = Stream.of(type.indexOf('.'), type.indexOf('|'), type.indexOf('_'), type.indexOf(',')) .filter(i -> i>= 0) //if chrc is not in String indexOf returns -1 .min(Integer::compare) .orElse(type.length()); From ebec8854866de9e1719935073978d49699f23bff Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:39:26 +0200 Subject: [PATCH 091/101] avoid casting --- .../contrib/emissions/utils/EmissionUtilsTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java index 9d978f682e6..b4404ed0bfb 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java @@ -487,10 +487,10 @@ final void testSetNonCalculatedEmissionsForPopulation_missingMap() { Assertions.assertEquals(pop.getPersons().keySet().size(), finalMap.keySet().size(), message); //check: all values for the this person are zero and of type double - for (Object pollutant : finalMap.get(idp3).values()) { - Assertions.assertSame(pollutant.getClass(), Double.class); - Assertions.assertEquals(0.0, (Double) pollutant, MatsimTestUtils.EPSILON); - Assertions.assertNotNull(pollutant); + for (Double pollutantValues : finalMap.get(idp3).values()) { + Assertions.assertSame(pollutantValues.getClass(), Double.class); + Assertions.assertEquals(0.0, pollutantValues, MatsimTestUtils.EPSILON); + Assertions.assertNotNull(pollutantValues); } //check: all types of emissions appear for (Pollutant emission : pollsFromEU) { @@ -625,9 +625,9 @@ final void testSetNonCalculatedEmissionsForPopulation_emptyEmissionMap() { //check: all values for all persons are zero and of type double for (Id id : finalMap.keySet()) { - for (Object pollutant : finalMap.get(id).values()) { + for (Double pollutant : finalMap.get(id).values()) { Assertions.assertSame(pollutant.getClass(), Double.class); - Assertions.assertEquals(0.0, (Double) pollutant, MatsimTestUtils.EPSILON, "map of pollutants was missing. Therefore all values should be set to zero."); + Assertions.assertEquals(0.0, pollutant, MatsimTestUtils.EPSILON, "map of pollutants was missing. Therefore all values should be set to zero."); Assertions.assertNotNull(pollutant); } //check: alle types of emissions appear From 0319babf6c31692315fba83e87d6c09b446b594d Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:42:44 +0200 Subject: [PATCH 092/101] suppress warning --- .../main/java/org/matsim/contrib/emissions/EmissionModule.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java index e7eaec3a17c..7f06339b8f6 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java @@ -77,11 +77,13 @@ public EmissionModule(final Scenario scenario, final EventsManager eventsManager // Event handlers are now added to the event manager inside the respective Handlers, jm march '18 } + @SuppressWarnings("ClassEscapesDefinedScope") public WarmEmissionAnalysisModule getWarmEmissionAnalysisModule() { // makes sense to have this public for externalization computations. kai, jan'20 return this.warmEmissionHandler.getWarmEmissionAnalysisModule(); } + @SuppressWarnings("ClassEscapesDefinedScope") public ColdEmissionAnalysisModule getColdEmissionAnalysisModule() { // makes sense to have this public for externalization computations. kai, jan'20 return this.coldEmissionHandler.getColdEmissionAnalysisModule(); From 597faae3962568c0534f39ead771c6eaaed14362 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 12:52:24 +0200 Subject: [PATCH 093/101] fix some (language) grammar --- .../java/org/matsim/contrib/emissions/EmissionModule.java | 7 ++++--- .../java/org/matsim/contrib/emissions/OsmHbefaMapping.java | 2 +- .../matsim/contrib/emissions/PositionEmissionsModule.java | 4 ++-- .../contrib/emissions/analysis/EmissionGridAnalyzer.java | 4 ++-- .../emissions/analysis/FastEmissionGridAnalyzer.java | 4 ++-- .../emissions/analysis/RawEmissionEventsReader.java | 2 +- .../example/RunAverageEmissionToolOfflineExample.java | 2 +- .../example/RunDetailedEmissionToolOfflineExample.java | 2 +- .../emissions/TestColdEmissionAnalysisModuleCase1.java | 2 +- .../emissions/TestColdEmissionAnalysisModuleCase4.java | 2 +- .../emissions/TestColdEmissionAnalysisModuleCase6.java | 2 +- .../emissions/TestColdEmissionsFallbackBehaviour.java | 2 +- .../contrib/emissions/TestHbefaColdEmissionFactorKey.java | 2 +- .../contrib/emissions/TestHbefaWarmEmissionFactorKey.java | 2 +- .../contrib/emissions/TestWarmEmissionAnalysisModule.java | 6 +++--- .../emissions/TestWarmEmissionAnalysisModuleCase1.java | 6 +++--- .../emissions/analysis/EmissionsByPollutantTest.java | 2 +- .../emissions/analysis/RawEmissionEventsReaderTest.java | 2 +- .../example/RunDetailedEmissionToolOfflineExampleIT.java | 6 +++--- .../RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java | 4 ++-- .../RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java | 4 ++-- .../matsim/contrib/emissions/utils/EmissionUtilsTest.java | 2 +- 22 files changed, 36 insertions(+), 35 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java index 7f06339b8f6..8b7004be8d7 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java @@ -165,9 +165,10 @@ private void createLookupTables() { if (shouldCreateAverageTables()) { this.avgHbefaColdTable = HbefaTables.loadAverageCold(emissionConfigGroup.getAverageColdEmissionFactorsFileURL(scenario.getConfig().getContext())); addPollutantsToMap(coldPollutants, avgHbefaColdTable.keySet()); - // yy The naming and signature of the above should presumably be changed: (1) addPollutantsToX implies signature (pollutants, - // X). But it is actually the other way round (even if it does not read that way. (2) "coldPollutants" is not a Map. Since - // this is a private method, maybe one could also have a method "memorizeColdPollutants" and then not have coldPollutants as + // yy The naming and signature of the above should presumably be changed: + // (1) addPollutantsToX implies signature (pollutants,X). But it is actually the other way round (even if it does not read that way.) + // (2) "coldPollutants" is not a Map. + // Since this is a private method, maybe one could also have a method "memorizeColdPollutants" and then not have coldPollutants as // field. kai, dec'22 this.avgHbefaWarmTable = HbefaTables.loadAverageWarm(emissionConfigGroup.getAverageWarmEmissionFactorsFileURL(scenario.getConfig().getContext())); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java index f9de1d049b1..d09a01c2ed2 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java @@ -108,7 +108,7 @@ private String getHEBFAtype(String type, double speed) { /* * speed attributes are sometimes rounded beforehand. - * make sure the speed is a multiple of 10, as the HBEFA emission key factors are and otherwise we get problems later... + * make sure the speed is a multiple of 10, as the HBEFA emission key factors are, and otherwise we get problems later... */ freeVelocity_kmh = Math.round(freeVelocity_kmh/10.0) * 10; diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java index 1f6304d0ade..df0a7c1144c 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java @@ -111,7 +111,7 @@ Map calculateColdEmissions(Vehicle vehicle, double parkingDur } private Tuple getVehicleAttributes(Vehicle vehicle) { - // the following block fixes the vehicle types's emission information whenusing an old vehicle type format + // the following block fixes the vehicle type's emission information whenusing an old vehicle type format // the unit test I found uses an old format, so have it here. { String hbefaVehicleTypeDescription = EmissionUtils.getHbefaVehicleDescription(vehicle.getType(), emissionsConfigGroup); @@ -209,7 +209,7 @@ private void handlePositionEvent(PositionEvent event) { return; // only calculate emissions for cars if (!vehiclesInTraffic.containsKey(event.getVehicleId())) - return; // only collect positions if vehicle has entered traffic (if vehicle is wait2link its position is calculated but it hasn't entered traffic yet. + return; // only collect positions if vehicle has entered traffic (if vehicle is wait2link its position is calculated, but it hasn't entered traffic yet.) if (trajectories.containsKey(event.getVehicleId())) { computeCombinedEmissionEvent(event); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzer.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzer.java index 65586e05d91..42003c91ffb 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzer.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzer.java @@ -57,7 +57,7 @@ /** * This class may be used to collect emission events of some events file and assign those emissions to a grid structure. - * Additionally those emissions are divided into time bins + * Additionally, those emissions are divided into time bins */ public class EmissionGridAnalyzer { @@ -316,7 +316,7 @@ public Builder withTimeBinSize(double size) { /** * Sets the used grid type. Default is Square * - * @param type The grid type. Currently either Square or Hexagonal + * @param type The grid type. Currently, either Square or Hexagonal * @return {@link org.matsim.contrib.emissions.analysis.EmissionGridAnalyzer.Builder} */ public Builder withGridType(GridType type) { diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java index fdff9835fa6..ea6d8ea92cc 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java @@ -59,8 +59,8 @@ public abstract class FastEmissionGridAnalyzer { * If only a certain area of the scenario is of interest for the analysis. The supplied network must be filtered beforehand. * The resulting raster's size depends on the bounding box of the supplied network. *

      - * Note: The algorithm is not accurate at the edges of the raster. The kernel is cut of a the edges meaning that emissions - * are underestimated at the edges of the raster. I didn't bother to implement this correctly. Otherwise the overall + * Note: The algorithm is not accurate at the edges of the raster. The kernel is cut of the edges meaning that emissions + * are underestimated at the edges of the raster. I didn't bother to implement this correctly. Otherwise, the overall * amount of emissions doesn't change. * * @param eventsFile The events file which contains the emission events diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReader.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReader.java index 283d144e0bb..811c3d49181 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReader.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReader.java @@ -57,7 +57,7 @@ class RawEmissionEventsReader extends MatsimXmlParser { RawEmissionEventsReader(HandleEmissionEvent handler) { super(ValidationType.NO_VALIDATION); this.handler = handler; - // events don't have dtd. Therefore validation is not possible + // events don't have dtd. Therefore, validation is not possible this.setValidating(false); } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java index 5264f6d4b39..4361e146329 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java @@ -49,7 +49,7 @@ public final class RunAverageEmissionToolOfflineExample{ public static final String emissionEventsFilename = "emission.events.offline.xml.gz"; - // (remove dependency of one test/execution path from other. kai/ihab, nov'18) + // (remove dependency of one test/execution path from others. kai/ihab, nov'18) private Config config; diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java index 270b3bae7f2..cb999fd8d78 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java @@ -48,7 +48,7 @@ public final class RunDetailedEmissionToolOfflineExample{ // private static final String configFile = "./scenarios/sampleScenario/testv2_Vehv1/config_detailed.xml"; // private static final String eventsFile = "./scenarios/sampleScenario/5.events.xml.gz"; - // (remove dependency of one test/execution path from other. kai/ihab, nov'18) + // (remove dependency of one test/execution path from others. kai/ihab, nov'18) // private static final String emissionEventOutputFileName = "5.emission.events.offline.xml.gz"; private Config config; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java index 3dc63ebde3a..4e06d69ec20 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java @@ -135,7 +135,7 @@ private static ColdEmissionAnalysisModule setUp() { // This represents the previous behavior, which fallbacks to the average table, // if values are not found in the detailed table, kmt apr'20 - // This test seems to refer to an direct lookup in average table + // This test seems to refer to a direct lookup in average table ecg.setDetailedVsAverageLookupBehavior(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); return new ColdEmissionAnalysisModule(avgHbefaColdTable, detailedHbefaColdTable, ecg, pollutants, emissionEventManager); } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase4.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase4.java index 021503fa903..3f1b44dc470 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase4.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase4.java @@ -87,7 +87,7 @@ public class TestColdEmissionAnalysisModuleCase4 { // fifth case: cold emission factor not set // private static final String nullcase_emConcept = "nullCase"; - // this testcase does not exist any more. kai, jul'18 + // this testcase does not exist anymore. kai, jul'18 // emission factors for tables - no dublicates! private static final Double detailedPetrolFactor = 100.; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase6.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase6.java index 8013a55267b..117c56e7da8 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase6.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase6.java @@ -147,7 +147,7 @@ private static void fillDetailedTable( Map Should be used, since HGV shpuld be supported and not fallback to average any more, kmt apr'20. + //(pre-existing comment: HEAVY_GOODS_VEHICLE;PC petrol;petrol; --> Should be used, since HGV shpuld be supported and not fallback to average anymore, kmt apr'20.) HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( petrol_technology, none_sizeClass, none_emConcept ); putIntoHbefaColdTable( detailedHbefaColdTable, vehAtt, new HbefaColdEmissionFactor(heavyGoodsFactor), HEAVY_GOODS_VEHICLE ); } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionsFallbackBehaviour.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionsFallbackBehaviour.java index d4816287c55..f35050cc9e0 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionsFallbackBehaviour.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionsFallbackBehaviour.java @@ -65,7 +65,7 @@ public class TestColdEmissionsFallbackBehaviour { private static final Double parkingDuration = 1.; private static final int distance = 1; - //This are the expected values and extracted from "./scenarios/sampleScenario/sample_41_EFA_ColdStart_vehcat_2020average.csv" and + //These are the expected values and extracted from "./scenarios/sampleScenario/sample_41_EFA_ColdStart_vehcat_2020average.csv" and // "./scenarios/sampleScenario/sample_41_EFA_ColdStart_SubSegm_2020detailed.csv" //Both for AmbientConditionPattern 0-1h, 0-1km private final double emissionsFactorInGrammPerKilometer_Detailed = 3.337293625; //detailed table diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java index d9475cdc817..810c11e8d2c 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java @@ -104,7 +104,7 @@ final void testEqualsForCompleteKeys() { } } - // the following tests each compare a incomplete key to a complete key + // the following tests each compare an incomplete key to a complete key // wanted result: // completeData.equals(partialData) -> return false // uncompleteData.equals(completeData) -> throw nullpointer diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java index 23ecb51b684..df5cf8fd2d7 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java @@ -102,7 +102,7 @@ final void testEqualsForCompleteKeys(){ assertNotEquals(normal, different, message); } - // the following tests each compare a incomplete key to a complete key + // the following tests each compare an incomplete key to a complete key // wanted result: // completeData.equals(partialData) -> return false // uncompleteData.equals(completeData) -> throw nullpointer diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java index 813cb15e28b..ca302cd33ad 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java @@ -55,7 +55,7 @@ * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * get free flow occurences - testCounters*() * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get stop-go occurences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() * get top go km couter - testCounters*() @@ -102,7 +102,7 @@ public class TestWarmEmissionAnalysisModule { private final Double noeFreeSpeed = AVG_PASSENGER_CAR_SPEED_FF_KMH; - // case 6 - data in detailed table, stop go speed = free flow speed + // case 6 - data in detailed table, stop-go speed = free flow speed private final String sgffRoadCatgory = "URB_case7"; private final String sgffTechnology = "sg ff technology"; private final String sgffConcept = "sg ff concept"; @@ -265,7 +265,7 @@ void testCounters7(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp setUp(emissionsComputationMethod); emissionsModule.reset(); - // case 10 - data in detailed table, stop go speed > free flow speed + // case 10 - data in detailed table, stop-go speed > free flow speed Id tableVehicleId = Id.create("vehicle 8", Vehicle.class); double tableLinkLength= 30.*1000; Id tableVehicleTypeId = Id.create( diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java index 9fd1234d3bb..38330659906 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java @@ -61,7 +61,7 @@ * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * get free flow occurences - testCounters*() * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get stop-go occurences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() * get top go km couter - testCounters*() @@ -149,7 +149,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent1(E /* * this test method creates a mock link and mock vehicle (petrol technology) with a complete vehicleTypId --> detailed values are used - * the counters for all possible combinations of avg, stop go and free flow speed are tested + * the counters for all possible combinations of avg, stop-go and free flow speed are tested * for the cases: > s&g speed, vehicleId = Id.create("vehicle 1", Vehicle.class); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java index 208bd5e1328..114802a4de0 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java @@ -17,7 +17,7 @@ public class EmissionsByPollutantTest { // The EmissionsByPollutant potentially adds up the same emissions coming from cold and warm. Thus, this cannot be combined into the enum approach // without some thinking. kai, jan'20 - // Quite possibly, should just combine them into an enum "pollutant"?! There is, anyways, the JM map of those emissions that are actually present in the + // Quite possibly, should just combine them into an enum "pollutant"?! There is, anyway, the JM map of those emissions that are actually present in the // input file. kai, jan'20 @Test diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReaderTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReaderTest.java index 4592d26ec17..5495783715a 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReaderTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReaderTest.java @@ -22,7 +22,7 @@ public class RawEmissionEventsReaderTest { @Test void handleNonEventNode() { - // read in an xml file which doesn't have events. It will parse the whole file but will not handle any of the + // read in a xml file which doesn't have events. It will parse the whole file but will not handle any of the // parsed nodes var networkUrl = IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "network.xml"); new RawEmissionEventsReader((time, linkId, vehicleId, pollutant, value) -> { diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExampleIT.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExampleIT.java index e2ed6c54bba..09d0e9bc5b0 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExampleIT.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExampleIT.java @@ -42,7 +42,7 @@ public class RunDetailedEmissionToolOfflineExampleIT { * * */ - // Expecting RuntimeException, because requested values are only in average file. Without fallback it has to fail! + // Expecting RuntimeException, because requested values are only in average file. Without fallback, it has to fail! // @Test(expected=RuntimeException.class) @Test final void testDetailed_vehTypeV1() { @@ -67,7 +67,7 @@ final void testDetailed_vehTypeV1() { Assertions.assertTrue( gotAnException ); } - // Expecting RuntimeException, because requested values are only in average file. Without fallback it has to fail! + // Expecting RuntimeException, because requested values are only in average file. Without fallback, it has to fail! // @Test(expected=RuntimeException.class) @Test final void testDetailed_vehTypeV2() { @@ -91,7 +91,7 @@ final void testDetailed_vehTypeV2() { Assertions.assertTrue( gotAnException ); } - // Expecting RuntimeException, because requested values are only in average file. Without fallback it has to fail! + // Expecting RuntimeException, because requested values are only in average file. Without fallback, it has to fail! // @Test(expected=RuntimeException.class) @Test final void testDetailed_vehTypeV2_HBEFA4() { diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java index f52a038ddda..892803c548e 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java @@ -46,8 +46,8 @@ public class RunDetailedEmissionToolOnlineExampleIT_vehTypeV1 { * This is by now (feb'20) the default. Setting it here for the tests explicitly * * */ -// @Test(expected=RuntimeException.class) // Expecting RuntimeException, because requested values are only in average file. Without fallback it has to fail! - @Disabled //Ignore this test, because the thrown exception during events handling does not always leads to an abort of the Simulation ->> Maybe a problem in @link{ParallelEventsManagerImpl.class}? +// @Test(expected=RuntimeException.class) // Expecting RuntimeException, because requested values are only in average file. Without fallback, it has to fail! + @Disabled //Ignore this test, because the thrown exception during events handling does not always lead to an abort of the Simulation ->> Maybe a problem in @link{ParallelEventsManagerImpl.class}? @Test final void testDetailed_vehTypeV1() { boolean gotAnException = false ; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java index 1a28fb39bf2..d6e33fc37f1 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java @@ -40,8 +40,8 @@ public class RunDetailedEmissionToolOnlineExampleIT_vehTypeV2 { * Test method for {@link RunDetailedEmissionToolOnlineExample#main(String[])}. */ -// @Test(expected=RuntimeException.class) // Expecting RuntimeException, because requested values are only in average file. Without fallback it has to fail! - @Disabled //Ignore this test, because the thrown exception during events handling does not always leads to an abort of the Simulation ->> Maybe a problem in @link{ParallelEventsManagerImpl.class}? +// @Test(expected=RuntimeException.class) // Expecting RuntimeException, because requested values are only in average file. Without fallback, it has to fail! + @Disabled //Ignore this test, because the thrown exception during events handling does not always lead to an abort of the Simulation ->> Maybe a problem in @link{ParallelEventsManagerImpl.class}? @Test final void testDetailed_vehTypeV2() { boolean gotAnException = false ; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java index b4404ed0bfb..121aabefc72 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java @@ -486,7 +486,7 @@ final void testSetNonCalculatedEmissionsForPopulation_missingMap() { message = "the calculated map should contain " + pop.getPersons().size() + " person(s) but contains " + finalMap.keySet().size() + "person(s)."; Assertions.assertEquals(pop.getPersons().keySet().size(), finalMap.keySet().size(), message); - //check: all values for the this person are zero and of type double + //check: all values for this person are zero and of type double for (Double pollutantValues : finalMap.get(idp3).values()) { Assertions.assertSame(pollutantValues.getClass(), Double.class); Assertions.assertEquals(0.0, pollutantValues, MatsimTestUtils.EPSILON); From d08aec145ba347da2737ef85c9f0ccf9bb455f22 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 13:48:50 +0200 Subject: [PATCH 094/101] fix some typos --- .../emissions/ColdEmissionAnalysisModule.java | 2 +- .../contrib/emissions/EmissionModule.java | 10 +++--- .../emissions/HbefaRoadTypeMapping.java | 4 +-- .../contrib/emissions/OsmHbefaMapping.java | 2 +- .../matsim/contrib/emissions/Pollutant.java | 6 ++-- .../emissions/PositionEmissionsModule.java | 10 +++--- .../emissions/VisumHbefaRoadTypeMapping.java | 2 +- .../emissions/VspHbefaRoadTypeMapping.java | 2 +- .../emissions/WarmEmissionAnalysisModule.java | 12 +++---- .../analysis/FastEmissionGridAnalyzer.java | 2 +- .../emissions/utils/EmissionsConfigGroup.java | 2 +- .../emissions/OsmHbefaMappingTest.java | 22 ++++++------- .../TestColdEmissionAnalysisModule.java | 2 +- .../TestColdEmissionAnalysisModuleCase1.java | 2 +- .../TestColdEmissionAnalysisModuleCase2.java | 2 +- .../TestColdEmissionAnalysisModuleCase3.java | 2 +- .../TestColdEmissionAnalysisModuleCase4.java | 2 +- .../TestColdEmissionAnalysisModuleCase6.java | 8 ++--- .../TestWarmEmissionAnalysisModule.java | 10 +++--- .../TestWarmEmissionAnalysisModuleCase1.java | 18 +++++------ .../TestWarmEmissionAnalysisModuleCase2.java | 32 +++++++++---------- .../TestWarmEmissionAnalysisModuleCase3.java | 24 +++++++------- .../TestWarmEmissionAnalysisModuleCase4.java | 20 ++++++------ .../TestWarmEmissionAnalysisModuleCase5.java | 12 +++---- ...issionAnalysisModuleTrafficSituations.java | 4 +-- .../TestWarmEmissionsFallbackBehaviour.java | 18 +++++------ .../VspHbefaRoadTypeMappingTest.java | 4 +-- .../analysis/EmissionGridAnalyzerTest.java | 4 +-- .../analysis/RawEmissionEventsReaderTest.java | 2 +- .../emissions/utils/EmissionUtilsTest.java | 6 ++-- 30 files changed, 124 insertions(+), 124 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java index 6793d6dcaa1..bc201e3761c 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java @@ -206,7 +206,7 @@ private Map calculateColdEmissions(Id vehicleId, dou * @param originVehCat * @param targetvehCat */ - //TODO Mabe make the behaviour settable by an enum? -> keep some kind of backwards capability or just return a 0.0 as it is for motorcycle? + //TODO Maybe make the behaviour settable by an enum? -> keep some kind of backwards capability or just return a 0.0 as it is for motorcycle? private void changeVehCategory(HbefaColdEmissionFactorKey key, HbefaVehicleCategory originVehCat, HbefaVehicleCategory targetvehCat) { // key.setVehicleCategory(targetvehCat); // if (vehInfoWarnHDVCnt < maxWarnCnt) { diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java index 8b7004be8d7..39e58239d09 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java @@ -113,11 +113,11 @@ public void writeEmissionInformation() { WarmEmissionAnalysisModule wam = warmEmissionHandler.getWarmEmissionAnalysisModule(); - logger.info("Emission calculation based on `Free flow only' occured for {} of {} warm emission events.", wam.getFreeFlowOccurences(), wam.getWarmEmissionEventCounter()); - logger.info("Emission calculation based on `Stop&Go only' occured for {} of {} warm emission events.", wam.getStopGoOccurences(), wam.getWarmEmissionEventCounter()); - logger.info("Emission calculation based on `Fractions' occured for {} of {} warm emission events.", wam.getFractionOccurences(), wam.getWarmEmissionEventCounter()); - logger.info("Free flow occured on {} km of total {} km, where emissions were calculated.", wam.getFreeFlowKmCounter(), wam.getKmCounter()); - logger.info("Stop&Go occured on {} km of total {} km, where emissions were calculated.", wam.getStopGoKmCounter(), wam.getKmCounter()); + logger.info("Emission calculation based on `Free flow only' occurred for {} of {} warm emission events.", wam.getFreeFlowOccurences(), wam.getWarmEmissionEventCounter()); + logger.info("Emission calculation based on `Stop&Go only' occurred for {} of {} warm emission events.", wam.getStopGoOccurences(), wam.getWarmEmissionEventCounter()); + logger.info("Emission calculation based on `Fractions' occurred for {} of {} warm emission events.", wam.getFractionOccurences(), wam.getWarmEmissionEventCounter()); + logger.info("Free flow occurred on {} km of total {} km, where emissions were calculated.", wam.getFreeFlowKmCounter(), wam.getKmCounter()); + logger.info("Stop&Go occurred on {} km of total {} km, where emissions were calculated.", wam.getStopGoKmCounter(), wam.getKmCounter()); logger.info("Emission calculation terminated. Emission events can be found in regular events file."); } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaRoadTypeMapping.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaRoadTypeMapping.java index bca754b259d..5074b708db5 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaRoadTypeMapping.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaRoadTypeMapping.java @@ -33,11 +33,11 @@ public void addHbefaMappings(Network network) { network.getLinks().values().parallelStream() .forEach(link -> { - String hbefaString = determineHebfaType(link); + String hbefaString = determineHbefaType(link); EmissionUtils.setHbefaRoadType(link, hbefaString); }); } - protected abstract String determineHebfaType(Link link); + protected abstract String determineHbefaType(Link link); } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java index d09a01c2ed2..ccce2492711 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java @@ -94,7 +94,7 @@ private void put(String s, Hbefa hbefa) { } @Override - public String determineHebfaType(Link link) { + public String determineHbefaType(Link link) { String roadType = NetworkUtils.getHighwayType(link); double allowedSpeed = NetworkUtils.getAllowedSpeed(link); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/Pollutant.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/Pollutant.java index 7e0f815d747..2db4b9607e9 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/Pollutant.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/Pollutant.java @@ -33,11 +33,11 @@ public enum Pollutant{ NMHC, // non-methane hydro carbons NOx, // nitrogen oxide NO2, // provided as g/km, but based on %-values of NOx - PM, // = PM10 --> particulate matterof size below 10μm, i.e. equivalent to PM10. unit = g/km + PM, // = PM10 --> particulate matter of size below 10μm, i.e. equivalent to PM10. unit = g/km SO2, //sulphur dioxide FC_MJ, // fuel consumption in MJ/km - CO2_rep, // CO2(reported): = carbon dioxide “reported”, i.e. withoutthe biofuel share in the fuel -> input for CO2e calculation - CO2e, // CO2 equivalents (WTW basis), CO2 equivalents contain CO2, CH4 and N2O, i.e. the relevant greenhouse gases from thetransport sector,multiplied with their respective 100-year Global Warming Potentials and summed up. + CO2_rep, // CO2(reported): = carbon dioxide “reported”, i.e. without the biofuel share in the fuel -> input for CO2e calculation + CO2e, // CO2 equivalents (WTW basis), CO2 equivalents contain CO2, CH4 and N2O, i.e. the relevant greenhouse gases from the transport sector, multiplied with their respective 100-year Global Warming Potentials and summed up. PM2_5, // particle mass for particles < 2.5 µm. unit = g/km PM2_5_non_exhaust, // tire wear! PM_non_exhaust, // PM10 from non-exhaust sources(e.g. road, tyre wear) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java index df0a7c1144c..d43d1f941e2 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java @@ -111,7 +111,7 @@ Map calculateColdEmissions(Vehicle vehicle, double parkingDur } private Tuple getVehicleAttributes(Vehicle vehicle) { - // the following block fixes the vehicle type's emission information whenusing an old vehicle type format + // the following block fixes the vehicle type's emission information when using an old vehicle type format // the unit test I found uses an old format, so have it here. { String hbefaVehicleTypeDescription = EmissionUtils.getHbefaVehicleDescription(vehicle.getType(), emissionsConfigGroup); @@ -223,23 +223,23 @@ private void handlePositionEvent(PositionEvent event) { private Map computeColdEmissions(PositionEvent event, Vehicle vehicle, double distanceToLastPosition) { - // we remember the vehicles which are currently emmitting cold emissions if not stored here return nothing + // we remember the vehicles which are currently emitting cold emissions if not stored here return nothing if (!vehiclesEmittingColdEmissions.contains(vehicle.getId())) return emissionCalculator.getEmptyColdEmissions(); double distance = calculateTravelledDistance(event); // this model assumes vehicles to emmit cold emissions for the first 2000m of a trip remove a vehicle from - // the list of emmiting vehicles if the current trajectory is longer than 2000m + // the list of emitting vehicles if the current trajectory is longer than 2000m if (distance > 2000) { vehiclesEmittingColdEmissions.remove(vehicle.getId()); return emissionCalculator.getEmptyColdEmissions(); } - // HBEFA assumes a constantly decreasing ammount of cold emissions depending on the distance travelled + // HBEFA assumes a constantly decreasing amount of cold emissions depending on the distance travelled // the underlying emission module simplifies this into two steps. Between 0-1km and 1-2km. We use the same // classes here because we don't want to rewrite all the stuff. The cold emission module computes emissions - // for 1000m. We take these as is and muliply with distanceToLastPosition / 1000. This way we have the fraction + // for 1000m. We take these as is and multiply with distanceToLastPosition / 1000. This way we have the fraction // of cold emissions for the distance travelled during the last time step janek oct' 2021 int distanceClass = distance <= 1000 ? 1 : 2; diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VisumHbefaRoadTypeMapping.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VisumHbefaRoadTypeMapping.java index e822003f09f..1fce8b282cb 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VisumHbefaRoadTypeMapping.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VisumHbefaRoadTypeMapping.java @@ -46,7 +46,7 @@ private VisumHbefaRoadTypeMapping() { } @Override - public String determineHebfaType(Link link) { + public String determineHbefaType(Link link) { String roadType = NetworkUtils.getType(link); return mapping.get(roadType); } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMapping.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMapping.java index 12fb81ea572..8a990e6d5ab 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMapping.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMapping.java @@ -13,7 +13,7 @@ public VspHbefaRoadTypeMapping() { } @Override - protected String determineHebfaType(Link link) { + protected String determineHbefaType(Link link) { var freespeed = link.getFreespeed() <= 13.888889 ? link.getFreespeed() * 2 : link.getFreespeed(); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java index 3b59b10d5a9..9da932e67a5 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java @@ -104,7 +104,7 @@ public WarmEmissionAnalysisModule( // The following tests if the detailed table is consistent, i.e. if there exist all combinations of entries. There used to be some test // cases where this was deliberately not the case, implying that this was assumed as plausible also for studies. This is now forbidding it. // If this causes too many problems, we could insert a switch (or attach it to the fallback behavior switch). kai, feb'20 - // Eventually vehicle category and vehicle attribute should be alligned in order to make the allCombinations setting useful + // Eventually vehicle category and vehicle attribute should be aligned in order to make the allCombinations setting useful // see discussion in https://github.com/matsim-org/matsim-libs/issues/1226 kturner, nov'20 Set roadCategories = new HashSet<>(); Set trafficSituations = EnumSet.noneOf(HbefaTrafficSituation.class); @@ -149,7 +149,7 @@ public WarmEmissionAnalysisModule( // conditions exist for a certain lookup. So we could still have some road categories, vehicle categories or vehicle attributes // where some detailed values exist and others don't. So the thing to check would be if for each existing // roadCategory x vehicleCategory x vehicleAttribute x pollutant - // there is a freeflow and a stopgo entry. Maybe something like this here: + // there is a freeflow and a stop-go entry. Maybe something like this here: Set freeflowSet = new HashSet<>(); Set stopgoSet = new HashSet<>(); for (HbefaWarmEmissionFactorKey key : detailedHbefaWarmTable.keySet()) { @@ -334,7 +334,7 @@ Map calculateWarmEmissions(double travelTime_sec, String road } // update counters: - // yy I don't now what this is good for; I would base downstream analysis rather on events. kai, jan'20 + // yy I don't know what this is good for; I would base downstream analysis rather on events. kai, jan'20 if (ecg.getEmissionsComputationMethod() == StopAndGoFraction) { incrementCountersFractional( linkLength_m / 1000, fractionStopGo ); } @@ -556,7 +556,7 @@ private HbefaTrafficSituation getTrafficSituation(HbefaWarmEmissionFactorKey efk HbefaRoadVehicleCategoryKey hbefaRoadVehicleCategoryKey = new HbefaRoadVehicleCategoryKey(efkey); Map trafficSpeeds = this.hbefaRoadTrafficSpeeds.get(hbefaRoadVehicleCategoryKey); - //TODO: Hier die Berechunung einfügen, die die trafficSpeedTabelle entsprechend aus den Werten erstellt? + //TODO: Hier die Berechnung einfügen, die die trafficSpeedTabelle entsprechend aus den Werten erstellt? //Frage Laufzeit: Einmal berechnen ha if (trafficSpeeds == null || !trafficSpeeds.containsKey(FREEFLOW)) { @@ -576,7 +576,7 @@ private HbefaTrafficSituation getTrafficSituation(HbefaWarmEmissionFactorKey efk trafficSituation = STOPANDGO; } } - /*FIXME The following lines should be added to account for the HBEFA 4.1's additiona traffic situation, + /*FIXME The following lines should be added to account for the HBEFA 4.1's additional traffic situation, but it currently causes a test failure (jwj, Nov'20) */ // if (trafficSpeeds.containsKey(STOPANDGO_HEAVY) && averageSpeed_kmh <= trafficSpeeds.get(STOPANDGO_HEAVY)) { // if (averageSpeed_kmh != trafficSpeeds.get(FREEFLOW)) { //handle case testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent6 @@ -626,7 +626,7 @@ private void incrementCountersAverage(HbefaTrafficSituation hbefaTrafficSituatio } } - //------ These (occurrences) seem do be used only for logging statements and tests. KMT/GR Jul'20 + //------ These (occurrences) seem to be used only for logging statements and tests. KMT/GR Jul'20 /*package-private*/ int getFreeFlowOccurences() { return freeFlowCounter; } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java index ea6d8ea92cc..347fe2bb3eb 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java @@ -279,7 +279,7 @@ static Raster rasterizeNetwork(Network network, Map, Double> emissions, * Rasterizes links into squares. Uses Bresenham's line drawing algorithm, which is supposed to be fast * Maybe the result is too chunky, but it'll do as a first try * - * @param link Matsim network link + * @param link MATSim network link * @return number of cells the link is rastered to */ private static int rasterizeLink(Link link, double value, Raster raster) { diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java index a5d366ae78f..cc958dc1a04 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java @@ -82,7 +82,7 @@ public enum HbefaTableConsistencyCheckingLevel { allCombinations, consistent, no private static final String EMISSION_FACTORS_COLD_FILE_DETAILED_CMT = "file with HBEFA detailed cold emission factors"; private static final String HBEFA_TABLE_CONSISTENCY_CHECKING_LEVEL_CMT = "Define on which level the entries in the provided hbefa tables are checked for consistency" + "\n\t\t\t" + HbefaTableConsistencyCheckingLevel.allCombinations.name() + " : check if entries for all combinations of HbefaTrafficSituation, HbefaVehicleCategory, HbefaVehicleAttributes, HbefaComponent. " + - "are available in the table. It only checks for paramters that are available in the table (e.g. if there is no HGV in the table, it can also pass. \n\t\t\t" + + "are available in the table. It only checks for parameters that are available in the table (e.g. if there is no HGV in the table, it can also pass. \n\t\t\t" + HbefaTableConsistencyCheckingLevel.consistent.name() + " : check if the entries for the two HbefaTrafficSituations 'StopAndGo' and 'FreeFlow' (nov 2020, may be subject to change) are consistently available in the table. \n\t\t\t" + //TODO HbefaTableConsistencyCheckingLevel.none.name() + " : There is no consistency check. This option is NOT recommended and only for backward capability to inputs from before spring 2020 . \n\t\t\t" + "Default is " + HbefaTableConsistencyCheckingLevel.allCombinations.name(); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/OsmHbefaMappingTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/OsmHbefaMappingTest.java index 195fc6e6fcb..10aff1cbe2a 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/OsmHbefaMappingTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/OsmHbefaMappingTest.java @@ -16,7 +16,7 @@ void testRegularMapping() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("primary", 70 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Trunk-City/70", hbefaType); } @@ -27,7 +27,7 @@ void testMergedLinkTypeMapping() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("primary|railway.tram", 70 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Trunk-City/70", hbefaType); } @@ -39,7 +39,7 @@ void testUnknownType() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("unknown-tag", 100 / 3.6); - mapping.determineHebfaType(link); + mapping.determineHbefaType(link); fail("Expected Runtime Exception."); }); @@ -51,7 +51,7 @@ void testFastMotorway() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("motorway", 100 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/MW-Nat./100", hbefaType); } @@ -62,11 +62,11 @@ void testMotorwayWithNoExactSpeedTag() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("motorway", 100.11 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/MW-Nat./100", hbefaType); link = getTestLink("motorway", 86.11 / 3.6); - hbefaType = mapping.determineHebfaType(link); + hbefaType = mapping.determineHbefaType(link); assertEquals("URB/MW-Nat./90", hbefaType); } @@ -77,7 +77,7 @@ void testFastMotorwayLink() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("motorway_link", 100 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/MW-Nat./100", hbefaType); } @@ -87,7 +87,7 @@ void testLivingStreet() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("living_street", 50 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Access/50", hbefaType); } @@ -98,7 +98,7 @@ void testUnclassified() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("unclassified", 50 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Access/50", hbefaType); } @@ -109,7 +109,7 @@ void testNoHighwayType() { var mapping = OsmHbefaMapping.build(); var link = getTestLink(" ", 60 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Local/60", hbefaType); } @@ -121,7 +121,7 @@ void testNoAllowedSpeedTag() { var link = getTestLink("residential", 40 / 3.6); link.getAttributes().removeAttribute(NetworkUtils.ALLOWED_SPEED); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Access/40", hbefaType); } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModule.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModule.java index 2ed3110e4a9..aa01f57e02d 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModule.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModule.java @@ -87,7 +87,7 @@ public class TestColdEmissionAnalysisModule { private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - // emission factors for tables - no dublicates! + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java index 4e06d69ec20..57aae0aee49 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java @@ -92,7 +92,7 @@ public class TestColdEmissionAnalysisModuleCase1 { private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - // emission factors for tables - no dublicates! + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java index c5ce8831a6a..eba88366726 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java @@ -84,7 +84,7 @@ public class TestColdEmissionAnalysisModuleCase2 { private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - // emission factors for tables - no dublicates! + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase3.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase3.java index 52bee68cde3..6dd637c3be9 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase3.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase3.java @@ -85,7 +85,7 @@ public class TestColdEmissionAnalysisModuleCase3 { private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - // emission factors for tables - no dublicates! + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase4.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase4.java index 3f1b44dc470..636b77c343d 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase4.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase4.java @@ -89,7 +89,7 @@ public class TestColdEmissionAnalysisModuleCase4 { // private static final String nullcase_emConcept = "nullCase"; // this testcase does not exist anymore. kai, jul'18 - // emission factors for tables - no dublicates! + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase6.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase6.java index 117c56e7da8..9f62e65442f 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase6.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase6.java @@ -83,7 +83,7 @@ public class TestColdEmissionAnalysisModuleCase6 { private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - // emission factors for tables - no dublicates! + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; @@ -105,8 +105,8 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { // sixth case: heavy goods vehicle // -> throw warning -> use detailed or average table for passenger cars - String heavygoodsvehicle = "HEAVY_GOODS_VEHICLE"; - Collections.addAll( testCase6, heavygoodsvehicle, petrol_technology, none_sizeClass, none_emConcept, heavyGoodsFactor); + String heavyGoodsVehicle = "HEAVY_GOODS_VEHICLE"; + Collections.addAll( testCase6, heavyGoodsVehicle, petrol_technology, none_sizeClass, none_emConcept, heavyGoodsFactor); logger.info("Running testcase: {} {}", testCase6, testCase6); Id linkId = Id.create( "linkId" + testCase6, Link.class ); @@ -147,7 +147,7 @@ private static void fillDetailedTable( Map Should be used, since HGV shpuld be supported and not fallback to average anymore, kmt apr'20.) + //(pre-existing comment: HEAVY_GOODS_VEHICLE;PC petrol;petrol; --> Should be used, since HGV should be supported and not fallback to average anymore, kmt apr'20.) HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( petrol_technology, none_sizeClass, none_emConcept ); putIntoHbefaColdTable( detailedHbefaColdTable, vehAtt, new HbefaColdEmissionFactor(heavyGoodsFactor), HEAVY_GOODS_VEHICLE ); } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java index ca302cd33ad..05ac81e5bce 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java @@ -103,7 +103,7 @@ public class TestWarmEmissionAnalysisModule { private final Double noeFreeSpeed = AVG_PASSENGER_CAR_SPEED_FF_KMH; // case 6 - data in detailed table, stop-go speed = free flow speed - private final String sgffRoadCatgory = "URB_case7"; + private final String sgffRoadCategory = "URB_case7"; private final String sgffTechnology = "sg ff technology"; private final String sgffConcept = "sg ff concept"; private final String sgffSizeClass = "sg ff size class"; @@ -124,7 +124,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent6(E Id sgffVehicleId = Id.create("vehicle sg equals ff", Vehicle.class); double sgffLinklength = 4000.; Link sgflink = createMockLink("link sgf", sgffLinklength, AVG_PASSENGER_CAR_SPEED_FF_KMH / 3.6); - EmissionUtils.setHbefaRoadType(sgflink, sgffRoadCatgory); + EmissionUtils.setHbefaRoadType(sgflink, sgffRoadCategory); Id sgffVehicleTypeId = Id.create( PASSENGER_CAR + ";" + sgffTechnology + ";"+ sgffSizeClass + ";"+sgffConcept, VehicleType.class ); VehiclesFactory vehFac = VehicleUtils.getFactory(); @@ -344,7 +344,7 @@ private void fillDetailedTable( Map avgHbefaWarmTable ) { // entries for first case "petrol" should not be used since there are entries in the detailed table - // there should only average vehicle attributes in the avgHebfWarmTable jm oct'18 + // there should only average vehicle attributes in the avgHbefaWarmTable jm oct'18 HbefaVehicleAttributes vehAtt = new HbefaVehicleAttributes(); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java index 38330659906..2a0382250ae 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java @@ -59,12 +59,12 @@ * weamParameter - testWarmEmissionAnalysisParameter * throw warm EmissionEvent - testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions - * get free flow occurences - testCounters*() - * get fraction occurences - testCounters*() - * get stop-go occurences - testCounters*() + * get free flow occurrences - testCounters*() + * get fraction occurrences - testCounters*() + * get stop-go occurrences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() - * get top go km couter - testCounters*() + * get top go km counter - testCounters*() * get warm emission event counter - testCounters*() * * private methods and corresponding tests: @@ -241,9 +241,9 @@ void testCounters1(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp /* - * this test method creates a incoff mock link and incoff mock vehicle (petrol technology) with a complete vehicleTypId --> detailed values are used - * for the computationMethod "Stop and Go" and "averageSpeed" the free flow occurences are tested - * the counters (StopGoOccurences, KmCounter, WarmEmissionEventCounter) are tested + * this test method creates an incoff mock link and incoff mock vehicle (petrol technology) with a complete vehicleTypId --> detailed values are used + * for the computationMethod "Stop and Go" and "averageSpeed" the free flow occurrences are tested + * the counters (StopGoOccurrences, KmCounter, WarmEmissionEventCounter) are tested * for the case average speed equals wrong free flow speed the counters are tested */ @@ -305,7 +305,7 @@ void testCounters1fractional(EmissionsConfigGroup.EmissionsComputationMethod emi // yyyyyy !!!!!! /* - * using the same case as above - case 1 and check the counters for all possible combinations of avg, stop go and free flow speed + * using the same case as above - case 1 and check the counters for all possible combinations of avg, stop-go and free flow speed */ Id vehicleId = Id.create("vehicle 1", Vehicle.class); @@ -376,7 +376,7 @@ void testCounters1fractional(EmissionsConfigGroup.EmissionsComputationMethod emi emissionsModule.reset(); emissionsModule.getEcg().setEmissionsComputationMethod(AverageSpeed ); - //@KMT it seems to me that copying the counters from above and chaning the expected values?? + //@KMT it seems to me that copying the counters from above and changing the expected values?? // yyyyyy !!!!!! } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase2.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase2.java index 101c410289d..bb7beab4140 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase2.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase2.java @@ -44,7 +44,7 @@ * / /* - * Case 2 - free flow entry in both tables, stop go entry in average table -> use average + * Case 2 - free flow entry in both tables, stop-go entry in average table -> use average * see (*) below. kai, jan'20 */ @@ -56,12 +56,12 @@ * weamParameter - testWarmEmissionAnalysisParameter * throw warm EmissionEvent - testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions - * get free flow occurences - testCounters*() - * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get free flow occurrences - testCounters*() + * get fraction occurrences - testCounters*() + * get stop-go occurrences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() - * get top go km couter - testCounters*() + * get top go km counter - testCounters*() * get warm emission event counter - testCounters*() * * private methods and corresponding tests: @@ -95,7 +95,7 @@ public class TestWarmEmissionAnalysisModuleCase2{ // vehicle information for regular test cases - // case 2 - free flow entry in both tables, stop go entry in average table -> use average (now fail) + // case 2 - free flow entry in both tables, stop-go entry in average table -> use average (now fail) private static final String PC_TECHNOLOGY = "PC petrol <1,4L lookUpBehaviour: tryDetailedThenTechnologyAverageThenAverageTable - * for two speed cases: avg speed = free flow speed & avg speed = stop go speed the NMHC warm emissions and emissions sum are computed using the two emissionsComputationMethods StopAndGoFraction & AverageSpeed + * for two speed cases: avg speed = free flow speed & avg speed = stop-go speed the NMHC warm emissions and emissions sum are computed using the two emissionsComputationMethods StopAndGoFraction & AverageSpeed */ @ParameterizedTest @@ -115,7 +115,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent2(E WarmEmissionAnalysisModule emissionsModule = setUp(emissionsComputationMethod); - // case 2 - free flow entry in both tables, stop go entry in average table -> use average + // case 2 - free flow entry in both tables, stop-go entry in average table -> use average // see (*) below. kai, jan'20 // create a link: @@ -128,7 +128,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent2(E VehiclesFactory vehFac = VehicleUtils.getFactory(); Vehicle pcVehicle = vehFac.createVehicle(pcVehicleId, vehFac.createVehicleType(pcVehicleTypeId)); - // sub case avg speed = free flow speed + // subcase avg speed = free flow speed { // compute warm emissions with travel time coming from free flow: warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions( pcVehicle, pclink, pclinkLength / PC_FREE_VELOCITY_KMH * 3.6 ); @@ -137,8 +137,8 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent2(E // - DETAILED FreeFlow value is available in the table (1.0E-4 g/km); StopAndGo value is NOT available in the table // - AVERAGE FreeFlow value is available in the table (1.0 g/km) ; StopAndGo value is NOT available in the table ( 10.0 g/km) // --> It seems like it was intended (or only implemented) in a way, that if one of the detailed values is missing (FreeFlow or StopGo) there is a fallback to average. So the result of this would be 1.0 g/km * 0.1 km = 0.1 g/km - // --> Now, after implementing the new fallback behaviour, it is looking up both values (FreeFlow or StopGo) ways independently from each other. Therefore the result comes from the detailed table (1.0E-4 g/km) * * 0.1 km = 1.0E-5 g/km - // -----> We need a decision here, if we want allow that inconsistent(?) lookup of FreeFlow and Detailed values with different grade of detail or not. + // --> Now, after implementing the new fallback behaviour, it is looking up both values (FreeFlow or StopGo) ways independently of each other. Therefore, the result comes from the detailed table (1.0E-4 g/km) * * 0.1 km = 1.0E-5 g/km + // -----> We need a decision here, if we want to allow that inconsistent(?) lookup of FreeFlow and Detailed values with different grade of detail or not. // After discussion with Kai N. we decided to let it as it is for the time being. I will add a log.info in the consistency checker. KMT Jul'20 //results should be equal here, because in both cases only the freeflow value is relevant (100% freeflow, 0% stop&go). @@ -152,7 +152,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent2(E warmEmissions.clear(); } - // sub case avg speed = stop go speed + // subcase avg speed = stop-go speed { warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions( pcVehicle, pclink, pclinkLength / PCSG_VELOCITY_KMH * 3.6 ); Assertions.assertEquals( AVG_PC_FACTOR_SG * pclinkLength / 1000., warmEmissions.get( NMHC ), MatsimTestUtils.EPSILON ); @@ -166,7 +166,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent2(E /* * this test method creates a vehicle and mock link - * for three cases: "current speed equals free flow speed" & "current speed equals stop go speed" & "current speed equals stop go speed" the counters are tested + * for three cases: "current speed equals free flow speed" & "current speed equals stop-go speed" & "current speed equals stop-go speed" the counters are tested * average values are used */ @ParameterizedTest @@ -175,7 +175,7 @@ void testCounters3(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp WarmEmissionAnalysisModule emissionsModule = setUp(emissionsComputationMethod); - // case 2 - free flow entry in both tables, stop go entry in average table -> use average + // case 2 - free flow entry in both tables, stop-go entry in average table -> use average Id pcVehicleId = Id.create("vehicle 2", Vehicle.class); double pclinkLength= 20.*1000; Id pcVehicleTypeId = Id.create( PASSENGER_CAR + ";"+ PC_TECHNOLOGY + ";"+ PC_SIZE_CLASS +";"+ PC_CONCEPT, VehicleType.class ); @@ -183,7 +183,7 @@ void testCounters3(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Vehicle pcVehicle = vehFac.createVehicle(pcVehicleId, vehFac.createVehicleType(pcVehicleTypeId)); Link pclink = TestWarmEmissionAnalysisModule.createMockLink("link 2", pclinkLength, PC_FREE_VELOCITY_KMH / 3.6 ); - // sub case: current speed equals free flow speed + // subcase: current speed equals free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(pcVehicle,pclink, pclinkLength/ PC_FREE_VELOCITY_KMH *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(pclinkLength/1000, emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); @@ -194,7 +194,7 @@ void testCounters3(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Assertions.assertEquals(1, emissionsModule.getWarmEmissionEventCounter() ); emissionsModule.reset(); - // sub case: current speed equals stop go speed + // subcase: current speed equals stop-go speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(pcVehicle, pclink, pclinkLength/ PCSG_VELOCITY_KMH *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(0., emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase3.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase3.java index 4a8f8f5827b..c0741ed1ced 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase3.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase3.java @@ -54,9 +54,9 @@ * weamParameter - testWarmEmissionAnalysisParameter * throw warm EmissionEvent - testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions - * get free flow occurences - testCounters*() - * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get free flow occurrences - testCounters*() + * get fraction occurrences - testCounters*() + * get stop-go occurrences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() * get top go km counter - testCounters*() @@ -91,14 +91,14 @@ public class TestWarmEmissionAnalysisModuleCase3{ private static final Double AVG_PC_FACTOR_FF = 1.; private static final Double AVG_PC_FACTOR_SG = 10.; - // case 3 - stop go entry in both tables, free flow entry in average table -> use average (now fail) + // case 3 - stop-go entry in both tables, free flow entry in average table -> use average (now fail) private final String dieselTechnology = "PC diesel"; private final String dieselSizeClass = "diesel"; private final String dieselConcept = ">=2L"; /* * this test method creates a diesel vehicle and mock link - * for two cases: "avg speed = free flow speed" & "avg speed = stop go speed" the average values are used to calculate the PM warm emissions + * for two cases: "avg speed = free flow speed" & "avg speed = stop-go speed" the average values are used to calculate the PM warm emissions */ @ParameterizedTest @EnumSource(EmissionsConfigGroup.EmissionsComputationMethod.class) @@ -107,7 +107,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent3(E //-- set up tables, event handler, parameters, module WarmEmissionAnalysisModule emissionsModule = setUp(emissionsComputationMethod); - // case 3 - stop go entry in both tables, free flow entry in average table -> use average + // case 3 - stop-go entry in both tables, free flow entry in average table -> use average Id dieselVehicleId = Id.create("veh 3", Vehicle.class); double dieselLinkLength= 20.; Link diesellink = TestWarmEmissionAnalysisModule.createMockLink("link 3", dieselLinkLength, TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_FF_KMH / 3.6 ); @@ -117,7 +117,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent3(E VehiclesFactory vehFac = VehicleUtils.getFactory(); Vehicle dieselVehicle = vehFac.createVehicle(dieselVehicleId, vehFac.createVehicleType(dieselVehicleTypeId)); - // sub case avg speed = free flow speed + // subcase avg speed = free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(dieselVehicle, diesellink, dieselLinkLength/ TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_FF_KMH *3.6 ); Assertions.assertEquals( AVG_PC_FACTOR_FF *dieselLinkLength/1000., warmEmissions.get(PM ), MatsimTestUtils.EPSILON ); emissionEventManager.reset(); @@ -126,7 +126,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent3(E emissionEventManager.reset(); warmEmissions.clear(); - // sub case avg speed = stop go speed + // subcase avg speed = stop-go speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(dieselVehicle, diesellink, dieselLinkLength/ TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_SG_KMH *3.6 ); Assertions.assertEquals( AVG_PC_FACTOR_SG *dieselLinkLength/1000., warmEmissions.get(PM ), MatsimTestUtils.EPSILON ); emissionEventManager.reset(); @@ -138,7 +138,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent3(E /* * this test method creates a diesel vehicle and mock link - * for two cases: "current speed equals free flow speed" & "current speed equals stop go speed" the counters are tested + * for two cases: "current speed equals free flow speed" & "current speed equals stop-go speed" the counters are tested */ @ParameterizedTest @EnumSource(EmissionsConfigGroup.EmissionsComputationMethod.class) @@ -146,7 +146,7 @@ void testCounters4(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp WarmEmissionAnalysisModule emissionsModule = setUp(emissionsComputationMethod); - // case 3 - stop go entry in both tables, free flow entry in average table -> use average + // case 3 - stop-go entry in both tables, free flow entry in average table -> use average Id dieselVehicleId = Id.create("vehicle 3", Vehicle.class); double dieselLinkLength= 200.*1000; Id dieselVehicleTypeId = Id.create( @@ -155,7 +155,7 @@ void testCounters4(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Vehicle dieselVehicle = vehFac.createVehicle(dieselVehicleId, vehFac.createVehicleType(dieselVehicleTypeId)); Link diesellink = TestWarmEmissionAnalysisModule.createMockLink("link 3", dieselLinkLength, TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_FF_KMH / 3.6 ); - // sub case: current speed equals free flow speed + // subcase: current speed equals free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(dieselVehicle, diesellink, dieselLinkLength/ TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_FF_KMH *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(dieselLinkLength/1000., emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); @@ -166,7 +166,7 @@ void testCounters4(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Assertions.assertEquals(1, emissionsModule.getWarmEmissionEventCounter() ); emissionsModule.reset(); - // sub case: current speed equals stop go speed + // subcase: current speed equals stop-go speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(dieselVehicle, diesellink, dieselLinkLength/ TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_SG_KMH *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(0., emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase4.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase4.java index f7a25a4d003..7f085baf2fb 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase4.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase4.java @@ -56,12 +56,12 @@ * weamParameter - testWarmEmissionAnalysisParameter * throw warm EmissionEvent - testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions - * get free flow occurences - testCounters*() - * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get free flow occurrences - testCounters*() + * get fraction occurrences - testCounters*() + * get stop-go occurrences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() - * get top go km couter - testCounters*() + * get top go km counter - testCounters*() * get warm emission event counter - testCounters*() * * private methods and corresponding tests: @@ -104,7 +104,7 @@ public class TestWarmEmissionAnalysisModuleCase4{ /* * this test method creates a vehicle (lpg properties) and a mock link - * for two cases: "avg speed = stop go speed" & "avg speed = free flow speed" the PM warm Emissions and the Emissions "sum" are tested + * for two cases: "avg speed = stop-go speed" & "avg speed = free flow speed" the PM warm Emissions and the Emissions "sum" are tested * average values are used */ @ParameterizedTest @@ -122,7 +122,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent4(E VehiclesFactory vehFac = VehicleUtils.getFactory(); Vehicle lpgVehicle = vehFac.createVehicle(lpgVehicleId, vehFac.createVehicleType(lpgVehicleTypeId)); - // sub case avg speed = stop go speed + // subcase avg speed = stop-go speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(lpgVehicle, lpglink, lpgLinkLength/ SPEED_SG *3.6 ); Assertions.assertEquals( AVG_PC_FACTOR_SG *lpgLinkLength/1000., warmEmissions.get(PM), MatsimTestUtils.EPSILON ); emissionEventManager.reset(); @@ -131,7 +131,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent4(E emissionEventManager.reset(); warmEmissions.clear(); - // sub case avg speed = free flow speed + // subcase avg speed = free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(lpgVehicle, lpglink, lpgLinkLength/ SPEED_FF *3.6 ); Assertions.assertEquals( AVG_PC_FACTOR_FF *lpgLinkLength/1000., warmEmissions.get(PM ), MatsimTestUtils.EPSILON ); emissionEventManager.reset(); @@ -143,7 +143,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent4(E /* * this test method creates a vehicle and mock link - * for two cases: "avg speed = stop go speed" & "avg speed = free flow speed" the PM warm Emissions are tested + * for two cases: "avg speed = stop-go speed" & "avg speed = free flow speed" the PM warm Emissions are tested * average values are used */ @ParameterizedTest @@ -160,7 +160,7 @@ void testCounters2(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Link lpgLink = TestWarmEmissionAnalysisModule.createMockLink("link zero", lpgLinkLength, SPEED_FF / 3.6 ); - // sub case: current speed equals free flow speed + // subcase: current speed equals free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(vehicle, lpgLink, lpgLinkLength/ SPEED_FF *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(lpgLinkLength/1000, emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); @@ -171,7 +171,7 @@ void testCounters2(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Assertions.assertEquals(1, emissionsModule.getWarmEmissionEventCounter() ); emissionsModule.reset(); - // sub case: current speed equals free flow speed + // subcase: current speed equals free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(vehicle, lpgLink, lpgLinkLength/ SPEED_SG *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(0., emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase5.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase5.java index bbc1ce82970..a792d37d620 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase5.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase5.java @@ -43,7 +43,7 @@ */ /* - * Case 5 - data in detailed table, stop go speed zero + * Case 5 - data in detailed table, stop-go speed zero */ @@ -57,12 +57,12 @@ * testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, * testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions - * get free flow occurences - testCounters*() - * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get free flow occurrences - testCounters*() + * get fraction occurrences - testCounters*() + * get stop-go occurrences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() - * get top go km couter - testCounters*() + * get top go km counter - testCounters*() * get warm emission event counter - testCounters*() * * private methods and corresponding tests: @@ -90,7 +90,7 @@ public class TestWarmEmissionAnalysisModuleCase5 { private final HandlerToTestEmissionAnalysisModules emissionEventManager = new HandlerToTestEmissionAnalysisModules(); // vehicle information for regular test cases - // case 5 - data in detailed table, stop go speed zero + // case 5 - data in detailed table, stop-go speed zero private final String zeroRoadCategory = "URB_case6"; private final String zeroTechnology = "zero technology"; private final String zeroConcept = "zero concept"; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleTrafficSituations.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleTrafficSituations.java index 49f3a0494d9..6d65c3ea4f6 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleTrafficSituations.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleTrafficSituations.java @@ -74,7 +74,7 @@ public class TestWarmEmissionAnalysisModuleTrafficSituations { private static final String petrolConcept ="<1,4L"; private static final double[] detailedPetrolFactor = {10, 100, 1000, 10000, 100000}; - // case 2 - free flow entry in both tables, stop go entry in average table -> use average + // case 2 - free flow entry in both tables, stop-go entry in average table -> use average private static final String pcTechnology = "PC petrol <1,4L warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFull, link, travelTimeOnLink); double expectedValue = 30.34984742; // = 200m * 151.7492371 g/km @@ -92,7 +92,7 @@ void testWarm_DetailedElseAbort_ShouldAbort1() { assertThrows(RuntimeException.class, () -> { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToTechnologyAverage, link, travelTimeOnLink); }); } @@ -110,7 +110,7 @@ void testWarm_DetailedElseAbort_ShouldAbort2() { assertThrows(RuntimeException.class, () -> { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToAverageTable, link, travelTimeOnLink); }); } @@ -128,7 +128,7 @@ void testWarm_DetailedElseAbort_ShouldAbort2() { void testWarm_DetailedThenTechnologyAverageElseAbort_FallbackNotNeeded() { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageElseAbort); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s Map warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFull, link, travelTimeOnLink); double expectedValue = 30.34984742; // = 200m * 151.7492371 g/km @@ -147,7 +147,7 @@ void testWarm_DetailedThenTechnologyAverageElseAbort_FallbackNotNeeded() { void testWarm_DetailedThenTechnologyAverageElseAbort_FallbackToTechnologyAverage() { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageElseAbort); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s Map warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToTechnologyAverage, link, travelTimeOnLink); double expectedValue = 31.53711548; // = 200m * 157.6855774 g/km @@ -167,7 +167,7 @@ void testWarm_DetailedThenTechnologyAverageElseAbort_ShouldAbort() { assertThrows(RuntimeException.class, () -> { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToAverageTable, link, travelTimeOnLink); }); } @@ -184,7 +184,7 @@ void testWarm_DetailedThenTechnologyAverageElseAbort_ShouldAbort() { void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackNotNeeded() { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s Map warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFull, link, travelTimeOnLink); double expectedValue = 30.34984742; // = 200m * 151.7492371 g/km @@ -203,7 +203,7 @@ void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackNotNeeded() void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackToTechnology() { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s Map warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToTechnologyAverage, link, travelTimeOnLink); double expectedValue = 31.53711548; // = 200m * 157.6855774 g/km @@ -223,7 +223,7 @@ void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackToTechnology void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackToAverageTable() { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s Map warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToAverageTable, link, travelTimeOnLink); double expectedValue = 31.1947174; // = 200m * 155.973587 g/km diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMappingTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMappingTest.java index f0164d11e86..fb906ac6f63 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMappingTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMappingTest.java @@ -16,7 +16,7 @@ void testSimpleMapping() { var mapper = new VspHbefaRoadTypeMapping(); var link = getTestLink("", 70 / 3.6); - var result = mapper.determineHebfaType(link); + var result = mapper.determineHbefaType(link); assertEquals("URB/MW-Nat./80", result); } @@ -36,4 +36,4 @@ private static Link getTestLink(String osmRoadType, double allowedSpeed) { return link; } -} \ No newline at end of file +} diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzerTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzerTest.java index e000400d4ca..ef291d8d788 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzerTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzerTest.java @@ -386,9 +386,9 @@ private void writeGridToCSV(TimeBinMap>> bins, Strin } } - private void assertCsvValuesAreSame(Path expected, Path acutal) throws IOException { + private void assertCsvValuesAreSame(Path expected, Path actual) throws IOException { - try (FileReader expectedReader = new FileReader(expected.toString()); var actualReader = new FileReader(acutal.toString())) { + try (FileReader expectedReader = new FileReader(expected.toString()); var actualReader = new FileReader(actual.toString())) { var actualIterator = CSVFormat.TDF.withFirstRecordAsHeader().parse(actualReader).iterator(); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReaderTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReaderTest.java index 5495783715a..955c1d4313d 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReaderTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReaderTest.java @@ -36,7 +36,7 @@ void handleNonEventNode() { @Test void handleNonEmissionEvent() { - // read in events file wihtout emission events. Those events should be ignored + // read in events file without emission events. Those events should be ignored var eventsUrl = IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "output_events.xml.gz"); new RawEmissionEventsReader((time, linkId, vehicleId, pollutant, value) -> { // this method should not be called diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java index 121aabefc72..31eb7805137 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java @@ -292,7 +292,7 @@ final void testGetTotalEmissions_completeData() { //put some content into the list // no incorrect/incomplete input data here - // warm and cold emissions are already sumed up -> sumUpEmissionsPerId is tested seperatly + // warm and cold emissions are already summed up -> sumUpEmissionsPerId is tested separately //person1 SortedMap allEmissionsP1 = new TreeMap<>(); @@ -442,7 +442,7 @@ final void testSetNonCalculatedEmissionsForPopulation_completeData(){ } //nothing else in the list int numOfPolls = pollsFromEU.size(); - Assertions.assertEquals(numOfPolls, finalMap.get(id).keySet().size(), "the number of pullutants is " + finalMap.get(id).keySet().size() + " but should be" + numOfPolls); + Assertions.assertEquals(numOfPolls, finalMap.get(id).keySet().size(), "the number of pollutants is " + finalMap.get(id).keySet().size() + " but should be" + numOfPolls); } //check: values for all emissions are correct -person 1 @@ -498,7 +498,7 @@ final void testSetNonCalculatedEmissionsForPopulation_missingMap() { } //nothing else in the list int numOfPolls = pollsFromEU.size(); - message = "the number of pullutants is " + finalMap.get(idp3).keySet().size() + " but should be" + numOfPolls; + message = "the number of pollutants is " + finalMap.get(idp3).keySet().size() + " but should be" + numOfPolls; Assertions.assertEquals(numOfPolls, finalMap.get(idp3).keySet().size(), message); } From adcb9f828f4d1b3b8637c91227f8870337c92c1f Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 14:42:22 +0200 Subject: [PATCH 095/101] more simplifications --- .../emissions/ColdEmissionAnalysisModule.java | 49 ++++--------------- .../contrib/emissions/EmissionUtils.java | 3 +- 2 files changed, 10 insertions(+), 42 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java index bc201e3761c..52ab385cf7d 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java @@ -155,20 +155,15 @@ private Map calculateColdEmissions(Id vehicleId, dou //HBEFA 3 provides cold start emissions for "pass. car" and Light_Commercial_Vehicles (LCV) only. //HBEFA 4.1 provides cold start emissions for "pass. car" and Light_Commercial_Vehicles (LCV) only. //see https://www.hbefa.net/e/documents/HBEFA41_Development_Report.pdf (WP 4 , page 23) kturner, may'20 - //Mapping everything except "motorcycle" to "pass.car", since this was done in the last years for HGV. - //This may can be improved: What should be better set to LGV or zero???? kturner, may'20 - if (vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.HEAVY_GOODS_VEHICLE)) { - changeVehCategory(key, HbefaVehicleCategory.HEAVY_GOODS_VEHICLE, HbefaVehicleCategory.PASSENGER_CAR); - } - if (vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.URBAN_BUS)) { - changeVehCategory(key, HbefaVehicleCategory.URBAN_BUS, HbefaVehicleCategory.PASSENGER_CAR ); - } - if (vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.COACH)) { - changeVehCategory(key, HbefaVehicleCategory.COACH, HbefaVehicleCategory.PASSENGER_CAR); - } - if (vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.MOTORCYCLE)){ - changeVehCategory(key, HbefaVehicleCategory.MOTORCYCLE, HbefaVehicleCategory.PASSENGER_CAR); - return coldEmissionsOfEvent; + if (vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.HEAVY_GOODS_VEHICLE) || + vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.COACH) || + vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.URBAN_BUS) || + vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.MOTORCYCLE)) { + if (vehInfoWarnHDVCnt < maxWarnCnt) { + vehInfoWarnHDVCnt++; + logger.warn("Automagic changing of VehCategory is disabled. Please make sure that your table contains the necessary values for {}", HbefaVehicleCategory.HEAVY_GOODS_VEHICLE.name()); + if (vehInfoWarnHDVCnt == maxWarnCnt) logger.warn(Gbl.FUTURE_SUPPRESSED); + } } if(this.detailedHbefaColdTable != null) { @@ -197,32 +192,6 @@ private Map calculateColdEmissions(Id vehicleId, dou return coldEmissionsOfEvent; } - /** - * Replace the vehicleCategory with HbefaVehicleCategory.PASSENGER_CAR - * This is the old behaviour as it was until Aug 21. - * (Aug'21, KMT) This does not help, since the emConcepts are not the same. So it is _not_ usable if using - * some kind of detailed values. - * @param key - * @param originVehCat - * @param targetvehCat - */ - //TODO Maybe make the behaviour settable by an enum? -> keep some kind of backwards capability or just return a 0.0 as it is for motorcycle? - private void changeVehCategory(HbefaColdEmissionFactorKey key, HbefaVehicleCategory originVehCat, HbefaVehicleCategory targetvehCat) { -// key.setVehicleCategory(targetvehCat); -// if (vehInfoWarnHDVCnt < maxWarnCnt) { -// vehInfoWarnHDVCnt++; -// logger.warn("HBEFA does not provide cold start emission factors for " + -// originVehCat + -// ". Setting vehicle category to " + targetvehCat + "..."); -// if (vehInfoWarnHDVCnt == maxWarnCnt) logger.warn(Gbl.FUTURE_SUPPRESSED); -// } - if (vehInfoWarnHDVCnt < maxWarnCnt) { - vehInfoWarnHDVCnt++; - logger.warn("Automagic changing of VehCategory is disabled. Please make sure that your table contains the necessary values for {}", originVehCat.name()); - if (vehInfoWarnHDVCnt == maxWarnCnt) logger.warn(Gbl.FUTURE_SUPPRESSED); - } - } - private HbefaColdEmissionFactor getEmissionsFactor(Tuple vehicleInformationTuple, int distance_km, HbefaColdEmissionFactorKey efkey, Pollutant coldPollutant) { efkey.setDistance(distance_km); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java index e174e14192c..bd28e89992c 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java @@ -346,7 +346,7 @@ static Pollutant getPollutant( String pollutantString ){ // setCo2TotalKeys( Set keys ) // as we have it, e.g., with network modes. kai, feb'20 - Pollutant pollutant = switch (pollutantString) { + return switch (pollutantString) { case "CO2(total)" -> Pollutant.CO2_TOTAL; case "CO2(rep)" -> Pollutant.CO2_rep; case "PM2.5 (non-exhaust)" -> Pollutant.PM2_5_non_exhaust; @@ -360,7 +360,6 @@ static Pollutant getPollutant( String pollutantString ){ // (2) It is a different spelling of an already existing pollutant. In that case, see above. // kai, jan'20 }; - return pollutant; } /** From 2d5c06fcd9904e0ff89c6db8a8aca6fd18afdbc6 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 14:45:13 +0200 Subject: [PATCH 096/101] cleanup: remove commented out code --- .../contrib/emissions/WarmEmissionAnalysisModule.java | 4 ---- .../example/RunAverageEmissionToolOfflineExample.java | 6 +----- .../example/RunDetailedEmissionToolOfflineExample.java | 5 ----- ...ssionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java | 3 --- .../matsim/contrib/emissions/utils/EmissionUtilsTest.java | 6 ------ 5 files changed, 1 insertion(+), 23 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java index 9da932e67a5..8eff2d52a29 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java @@ -63,10 +63,6 @@ public final class WarmEmissionAnalysisModule implements LinkEmissionsCalculator private int detailedFallbackAverageTableWarnCnt = 0; private int averageReadingInfoCnt = 0; - // The following was tested to slow down significantly, therefore counters were commented out: -// Set vehAttributesNotSpecified = Collections.synchronizedSet(new HashSet()); -// Set vehicleIdSet = Collections.synchronizedSet(new HashSet()); - private int freeFlowCounter = 0; private int saturatedCounter = 0; private int heavyFlowCounter = 0; diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java index 4361e146329..c1f344dc331 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java @@ -60,14 +60,10 @@ public static void main (String[] args){ emissionToolOfflineExampleV2.run(); } -// public Config prepareConfig() { -// config = ConfigUtils.loadConfig(configFile, new EmissionsConfigGroup()); -// return config; -// } - public Config prepareConfig(String args){ throw new RuntimeException("execution path no longer exists"); } + public Config prepareConfig(String [] args) { config = ConfigUtils.loadConfig(args, new EmissionsConfigGroup()); EmissionsConfigGroup ecg = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java index cb999fd8d78..83d4499706a 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java @@ -60,11 +60,6 @@ public static void main (String[] args){ emissionToolOfflineExampleV2Vehv1.run(); } -// public Config prepareConfig() { -// config = ConfigUtils.loadConfig(configFile, new EmissionsConfigGroup()); -// return config; -// } - public Config prepareConfig(String [] args) { config = ConfigUtils.loadConfig(args, new EmissionsConfigGroup()); return config; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java index 65f2c8a4850..2c89b956450 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java @@ -45,9 +45,6 @@ public class RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage { @Test final void testDetailed_vehTypeV2_FallbackToAverage() { try { -// RunDetailedEmissionToolOnlineExample onlineExample = new RunDetailedEmissionToolOnlineExample(); - -// Config config = onlineExample.prepareConfig( new String[]{"./scenarios/sampleScenario/testv2_Vehv2/config_detailed.xml"} ) ; var scenarioUrl = ExamplesUtils.getTestScenarioURL( "emissions-sampleScenario/testv2_Vehv2" ); var configUrl = IOUtils.extendUrl( scenarioUrl, "config_detailed.xml" ); Config config = RunDetailedEmissionToolOnlineExample.prepareConfig( new String [] { configUrl.toString() } ); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java index 31eb7805137..f71692faa5e 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java @@ -74,8 +74,6 @@ public class EmissionUtilsTest { private boolean nullPointerEx; public static Map createUntypedEmissions() { -// return Arrays.asList("co2", CO, NOx, "NO", NO2, HC).stream() -// .collect(Collectors.toMap(p -> p, p -> Math.random())); return Stream.of(CO2_TOTAL, CO, NOx, NO2, HC) .collect(Collectors.toMap(p -> p, p -> Math.random())); } @@ -793,10 +791,6 @@ public static Map createEmissions() { return Arrays.stream( Pollutant.values() ).collect( Collectors.toMap( p -> p, p -> Math.random() ) ) ; } -// public static Map createEmissionsWithFixedValue(double value) { -// return Arrays.asList("co2", CO, NOx, "NO", NO2, HC).stream() -// .collect(Collectors.toMap(p -> p, p -> value)); -// } public static Map createEmissionsWithFixedValue( double value ) { return Arrays.stream( Pollutant.values() ).collect( Collectors.toMap( p -> p, p -> value ) ) ; } From dac7488fa93e8ac3b63d8efe4f8e4e62ecd53228 Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Thu, 25 Jul 2024 14:55:03 +0200 Subject: [PATCH 097/101] small cleanups --- .../events/EmissionEventsReader.java | 18 ++++++++---- .../contrib/emissions/package-info.java | 3 +- .../analysis/EmissionsByPollutantTest.java | 9 ++---- .../events/TestColdEmissionEventImpl.java | 28 +++++++++---------- .../events/TestWarmEmissionEventImpl.java | 4 +-- 5 files changed, 32 insertions(+), 30 deletions(-) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java index 83bf51bc0f2..11f73caf526 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java @@ -67,9 +67,12 @@ public EmissionEventsReader( EventsManager events ){ case WarmEmissionEvent.ATTRIBUTE_LINK_ID -> linkId = Id.createLinkId(entry.getValue()); case WarmEmissionEvent.ATTRIBUTE_VEHICLE_ID -> vehicleId = Id.createVehicleId(entry.getValue()); case null, default -> { - String pollutant = entry.getKey().equals("NOX") ? - "NOx" : - entry.getKey(); // the previous versions would write NOX instead of NOx + String pollutant = null; // the previous versions would write NOX instead of NOx + if (entry.getKey() != null) { + pollutant = entry.getKey().equals("NOX") ? + "NOx" : + entry.getKey(); + } Double value = Double.parseDouble(entry.getValue()); warmEmissions.put(Pollutant.valueOf(pollutant), value); @@ -100,9 +103,12 @@ public EmissionEventsReader( EventsManager events ){ case ColdEmissionEvent.ATTRIBUTE_LINK_ID -> linkId = Id.createLinkId(entry.getValue()); case ColdEmissionEvent.ATTRIBUTE_VEHICLE_ID -> vehicleId = Id.createVehicleId(entry.getValue()); case null, default -> { - String pollutant = entry.getKey().equals("NOX") ? - "NOx" : - entry.getKey(); // the previous versions would write NOX instead of NOx + String pollutant = null; // the previous versions would write NOX instead of NOx + if (entry.getKey() != null) { + pollutant = entry.getKey().equals("NOX") ? + "NOx" : + entry.getKey(); + } Double value = Double.parseDouble(entry.getValue()); coldEmissions.put(Pollutant.valueOf(pollutant), value); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/package-info.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/package-info.java index 2d954229c63..811d521cb60 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/package-info.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/package-info.java @@ -46,7 +46,8 @@ * or see {@link org.matsim.contrib.emissions.utils.EmissionsConfigGroup} for a detailed description. * *

    • emissionVehicleFile: This data type is defined in the EmissionsConfigGroup, - * see {@link org.matsim.contrib.emissions.utils.EmissionsConfigGroup}. The following information is surrounded by {@link org.matsim.contrib.emissions.EmissionUtils.EmissionSpecificationMarker}. It is described as "definition of a vehicle + * see {@link org.matsim.contrib.emissions.utils.EmissionsConfigGroup}. + * The following information is surrounded by {@link org.matsim.contrib.emissions.EmissionUtils.EmissionSpecificationMarker}. It is described as "definition of a vehicle * for every person (who is allowed to choose a vehicle in the simulation): *
        *
      • REQUIRED: Vehicle description must start with the respective HbefaVehicleCategory followed by ";" diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java index 114802a4de0..52ed3393a4f 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java @@ -45,8 +45,7 @@ void addEmission() { final Pollutant pollutant = CO; final double expectedValue = emissions.get(pollutant) + valueToAdd; - Map map = new LinkedHashMap<>(); - map.putAll(emissions); + Map map = new LinkedHashMap<>(emissions); EmissionsByPollutant emissionsByPollutant = new EmissionsByPollutant(map); @@ -78,13 +77,11 @@ void addEmissions() { Map emissions = EmissionUtilsTest.createEmissions(); - Map map = new LinkedHashMap<>(); - map.putAll(emissions); + Map map = new LinkedHashMap<>(emissions); EmissionsByPollutant linkEmissions = new EmissionsByPollutant(map); - Map map2 = new LinkedHashMap<>(); - map2.putAll(emissions); + Map map2 = new LinkedHashMap<>(emissions); linkEmissions.addEmissions(map2); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestColdEmissionEventImpl.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestColdEmissionEventImpl.java index 022265df9f0..9a3af2d8601 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestColdEmissionEventImpl.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestColdEmissionEventImpl.java @@ -62,7 +62,7 @@ final void testGetAttributesForCompleteEmissionMaps(){ Map coldEmissionsMap = new HashMap<>(); setColdEmissions(coldEmissionsMap); ColdEmissionEvent ce = new ColdEmissionEvent(0.0, linkId, vehicleId, coldEmissionsMap); - + Map ceg = ce.getAttributes(); Assertions.assertEquals(Double.parseDouble(ceg.get(CO.name())), co, MatsimTestUtils.EPSILON, "the CO value of this cold emission event was "+ Double.parseDouble(ceg.get(CO.name()))+ "but should have been "+ co); Assertions.assertEquals(Double.parseDouble(ceg.get(FC.name())), fc, MatsimTestUtils.EPSILON, "the FC value of this cold emission event was "+ Double.parseDouble(ceg.get(FC.name()))+ "but should have been "+ fc); @@ -71,7 +71,7 @@ final void testGetAttributesForCompleteEmissionMaps(){ Assertions.assertEquals(Double.parseDouble(ceg.get(NO2.name())), n2, MatsimTestUtils.EPSILON, "the NO2 value of this cold emission event was "+ Double.parseDouble(ceg.get(NO2.name()))+ "but should have been "+ n2); Assertions.assertEquals(Double.parseDouble(ceg.get(NOx.name())), nx, MatsimTestUtils.EPSILON, "the NOx value of this cold emission event was "+ Double.parseDouble(ceg.get(NOx.name()))+ "but should have been "+ nx); Assertions.assertEquals(Double.parseDouble(ceg.get(PM.name())), pm, MatsimTestUtils.EPSILON, "the PM value of this cold emission event was "+ Double.parseDouble(ceg.get(PM.name()))+ "but should have been "+ pm); - + } private void setColdEmissions( Map coldEmissionsMap ) { @@ -90,12 +90,12 @@ final void testGetAttributesForIncompleteMaps(){ //the getAttributesMethod should // - return null if the emission map is empty // - throw NullPointerExceptions if the emission values are not set - // - throw NullPointerExceptions if no emission map is assigned - + // - throw NullPointerExceptions if no emission map is assigned + //empty map Map emptyMap = new HashMap<>(); ColdEmissionEvent emptyMapEvent = new ColdEmissionEvent(22., linkId, vehicleId, emptyMap); - + //values not set Map valuesNotSet = new HashMap<>(); valuesNotSet.put(CO, null); @@ -106,30 +106,30 @@ final void testGetAttributesForIncompleteMaps(){ valuesNotSet.put(NOx, null); valuesNotSet.put(PM, null); ColdEmissionEvent valuesNotSetEvent = new ColdEmissionEvent(44., linkId, vehicleId, valuesNotSet); - + //no map ColdEmissionEvent noMap = new ColdEmissionEvent(50., linkId, vehicleId, null); - + int numberOfColdPollutants = coldPollutants.size(); int valNullPointers = 0, noMapNullPointers=0; - + for(Pollutant cp : coldPollutants){ //empty map - Assertions.assertNull(emptyMapEvent.getAttributes().get(cp)); - + Assertions.assertNull(emptyMapEvent.getAttributes().get(cp.name())); + //values not set try{ - valuesNotSetEvent.getAttributes().get(cp); + valuesNotSetEvent.getAttributes().get(cp.name()); } catch(NullPointerException e){ valNullPointers ++; } - + //no map try{ - noMap.getAttributes().get(cp); + noMap.getAttributes().get(cp.name()); } catch(NullPointerException e){ noMapNullPointers++; @@ -138,5 +138,5 @@ final void testGetAttributesForIncompleteMaps(){ Assertions.assertEquals(numberOfColdPollutants, valNullPointers); Assertions.assertEquals(numberOfColdPollutants, noMapNullPointers); } - + } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java index 2244cb6dde7..b203c8792ce 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java @@ -111,9 +111,7 @@ final void testGetAttributesForIncompleteMaps(){ valuesNotSet.put(NOx, null); valuesNotSet.put(PM, null); - Map map = new LinkedHashMap<>(); - valuesNotSet.forEach(map::put); - // (this could be made more direct) + Map map = new LinkedHashMap<>(valuesNotSet); WarmEmissionEvent valuesNotSetEvent = new WarmEmissionEvent(44., linkId, vehicleId, map); From 213fae045ebc45a9adda8941d87b7afee170a338 Mon Sep 17 00:00:00 2001 From: nkuehnel Date: Sat, 27 Jul 2024 21:26:29 +0200 Subject: [PATCH 098/101] optimize h3 zone system initialization; move h3 test to common module --- .../zones/systems/grid/h3/H3ZoneSystem.java | 63 ++++++++++--------- .../grid/square/SquareGridZoneSystem.java | 4 +- .../systems/h3}/H3DrtZonalSystemTest.java | 62 +++++++++--------- 3 files changed, 65 insertions(+), 64 deletions(-) rename contribs/{drt-extensions/src/test/java/org/matsim/contrib/drt/extension/h3/drtZone => common/src/test/java/org/matsim/contrib/common/zones/systems/h3}/H3DrtZonalSystemTest.java (55%) diff --git a/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/h3/H3ZoneSystem.java b/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/h3/H3ZoneSystem.java index e9c84bccc4a..286bc9a09ca 100644 --- a/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/h3/H3ZoneSystem.java +++ b/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/h3/H3ZoneSystem.java @@ -13,8 +13,12 @@ import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.transformations.TransformationFactory; -import java.util.*; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; import java.util.function.Predicate; +import java.util.stream.Collectors; /** * @author nkuehnel / MOIA @@ -39,41 +43,38 @@ public H3ZoneSystem(String crs, int resolution, Network network, Predicate this.resolution = resolution; this.network = network; this.filter = filter; - this.network.getLinks().values().forEach(l -> getZoneForCoord(l.getToNode().getCoord())); + init(); } - - @Override - public Optional getZoneForCoord(Coord coord) { - - long h3Address = getH3Cell(coord); - Id zoneId = Id.create(h3Address, Zone.class); - - if(zones.containsKey(zoneId)) { - return Optional.of(zones.get(zoneId)); - } else { - Optional zone = H3Utils.createZone(h3Address, fromLatLong); - if(zone.isPresent() && filter.test(zone.get())) { - initZone(zone.get(), h3Address); - return zone; - } else { - return Optional.empty(); - } + private void init() { + Map> linksToH3 = + this.network.getLinks().values() + .stream() + .collect(Collectors.groupingBy(link -> getH3Cell(link.getToNode().getCoord()))); + for (Map.Entry> linksH3 : linksToH3.entrySet()) { + Optional maybeZone = createZone(linksH3.getKey()); + maybeZone.ifPresent(z -> { + zones.put(z.getId(), z); + zoneToLinksMap.put(z.getId(), linksH3.getValue()); + }); } } - private void initZone(Zone zone, long h3Address) { - if(filter.test(zone)) { - zones.put(zone.getId(), zone); - for (Link link : network.getLinks().values()) { - long linkH3Address = getH3Cell(link.getToNode().getCoord()); - - if (linkH3Address == h3Address) { - List links = zoneToLinksMap.computeIfAbsent(zone.getId(), id -> new ArrayList<>()); - links.add(link); - } - } + private Optional createZone(Long h3) { + Optional zone = H3Utils.createZone(h3, fromLatLong); + if(zone.isPresent() && filter.test(zone.get())) { + return zone; } + return Optional.empty(); + } + + @Override + public Optional getZoneForCoord(Coord coord) { + long h3Address = getH3Cell(coord); + Id zoneId = Id.create(h3Address, Zone.class); + // create new zone if absent, should not be linked to existing links in the network, + // as all of them are covered in the init() phase. + return Optional.ofNullable(zones.computeIfAbsent(zoneId, id -> createZone(h3Address).orElse(null))); } private long getH3Cell(Coord coord) { @@ -106,4 +107,4 @@ public List getLinksForZoneId(Id zone) { public Map, Zone> getZones() { return Collections.unmodifiableMap(zones); } -} +} \ No newline at end of file diff --git a/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/square/SquareGridZoneSystem.java b/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/square/SquareGridZoneSystem.java index f11fa58f614..b1319fed1a9 100644 --- a/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/square/SquareGridZoneSystem.java +++ b/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/square/SquareGridZoneSystem.java @@ -66,11 +66,11 @@ public SquareGridZoneSystem(Network network, double cellSize, Predicate zo } public SquareGridZoneSystem(Network network, double cellSize, boolean filterByNetwork, Predicate zoneFilter) { this.zoneFilter = zoneFilter; - Preconditions.checkArgument(!network.getNodes().isEmpty(), "Cannot create SquareGrid if no nodes"); - this.network = network; this.cellSize = cellSize; + Preconditions.checkArgument(!network.getNodes().isEmpty(), "Cannot create SquareGrid if no nodes"); + initBounds(); this.rows = Math.max(1, (int) Math.ceil((maxY - minY) / cellSize)); diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/h3/drtZone/H3DrtZonalSystemTest.java b/contribs/common/src/test/java/org/matsim/contrib/common/zones/systems/h3/H3DrtZonalSystemTest.java similarity index 55% rename from contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/h3/drtZone/H3DrtZonalSystemTest.java rename to contribs/common/src/test/java/org/matsim/contrib/common/zones/systems/h3/H3DrtZonalSystemTest.java index 3724d5d8eac..723e4026825 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/h3/drtZone/H3DrtZonalSystemTest.java +++ b/contribs/common/src/test/java/org/matsim/contrib/common/zones/systems/h3/H3DrtZonalSystemTest.java @@ -18,7 +18,7 @@ * *********************************************************************** * */ -package org.matsim.contrib.drt.extension.h3.drtZone; +package org.matsim.contrib.common.zones.systems.h3; import org.junit.jupiter.api.Test; import org.matsim.api.core.v01.Id; @@ -48,20 +48,20 @@ void test_Holzkirchen_Resolution3() { Network network = getNetwork(); String crs = TransformationFactory.DHDN_GK4; int resolution = 3; - ZoneSystem drtZonalSystem = new H3ZoneSystem(crs, resolution, network, z -> true); + ZoneSystem zoneSystem = new H3ZoneSystem(crs, resolution, network, z -> true); - assertThat(drtZonalSystem.getZones().containsKey(createZoneId("590526392240701439"))).isTrue(); + assertThat(zoneSystem.getZones().containsKey(createZoneId("590526392240701439"))).isTrue(); // center of Holzkirchen - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("590526667118608383")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("590526667118608383")); // Thanning (Western border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("590526667118608383")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("590526667118608383")); // between Gross- and Kleinpienzenau (Southeastern border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("590526392240701439")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("590526392240701439")); //check all links are mapped for (Link link : network.getLinks().values()) { - assertNotNull(drtZonalSystem.getZoneForLinkId(link.getId())); + assertNotNull(zoneSystem.getZoneForLinkId(link.getId())); } } @@ -71,23 +71,23 @@ void test_Holzkirchen_Resolution5() { String crs = TransformationFactory.DHDN_GK4; int resolution = 5; - ZoneSystem drtZonalSystem = new H3ZoneSystem(crs, resolution, network, z -> true); + ZoneSystem zoneSystem = new H3ZoneSystem(crs, resolution, network, z -> true); - assertThat(drtZonalSystem.getZones().containsKey(createZoneId("599533579684282367"))).isTrue(); - assertThat(drtZonalSystem.getZones().containsKey(createZoneId("599533826644901887"))).isTrue(); - assertThat(drtZonalSystem.getZones().containsKey(createZoneId("599533499153645567"))).isTrue(); - assertThat(drtZonalSystem.getZones().containsKey(createZoneId("599533503448612863"))).isTrue(); + assertThat(zoneSystem.getZones().containsKey(createZoneId("599533579684282367"))).isTrue(); + assertThat(zoneSystem.getZones().containsKey(createZoneId("599533826644901887"))).isTrue(); + assertThat(zoneSystem.getZones().containsKey(createZoneId("599533499153645567"))).isTrue(); + assertThat(zoneSystem.getZones().containsKey(createZoneId("599533503448612863"))).isTrue(); // center of Holzkirchen - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("599533826644901887")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("599533826644901887")); // Thanning (Western border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("599533503448612863")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("599533503448612863")); // between Gross- and Kleinpienzenau (Southeastern border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("599533579684282367")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("599533579684282367")); //check all links are mapped for (Link link : network.getLinks().values()) { - assertNotNull(drtZonalSystem.getZoneForLinkId(link.getId())); + assertNotNull(zoneSystem.getZoneForLinkId(link.getId())); } } @@ -97,18 +97,18 @@ void test_Holzkirchen_Resolution6() { String crs = TransformationFactory.DHDN_GK4; int resolution = 6; - ZoneSystem drtZonalSystem = new H3ZoneSystem(crs, resolution, network, z -> true); + ZoneSystem zoneSystem = new H3ZoneSystem(crs, resolution, network, z -> true); // center of Holzkirchen - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("604037425601183743")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("604037425601183743")); // Thanning (Western border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("604037102136459263")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("604037102136459263")); // between Gross- and Kleinpienzenau (Southeastern border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("604037178372128767")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("604037178372128767")); //check all links are mapped for (Link link : network.getLinks().values()) { - assertNotNull(drtZonalSystem.getZoneForLinkId(link.getId())); + assertNotNull(zoneSystem.getZoneForLinkId(link.getId())); } } @@ -117,18 +117,18 @@ void test_Holzkirchen_Resolution10() { Network network = getNetwork(); String crs = TransformationFactory.DHDN_GK4; int resolution = 10; - ZoneSystem drtZonalSystem = new H3ZoneSystem(crs, resolution, network, z -> true); + ZoneSystem zoneSystem = new H3ZoneSystem(crs, resolution, network, z -> true); // center of Holzkirchen - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("622051824027533311")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("622051824027533311")); // Thanning (Western border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("622051500514213887")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("622051500514213887")); // between Gross- and Kleinpienzenau (Southeastern border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("622051576862081023")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("622051576862081023")); //check all links are mapped for (Link link : network.getLinks().values()) { - assertNotNull(drtZonalSystem.getZoneForLinkId(link.getId())); + assertNotNull(zoneSystem.getZoneForLinkId(link.getId())); } } @@ -138,19 +138,19 @@ void test_Holzkirchen_Resolution12() { String crs = TransformationFactory.DHDN_GK4; int resolution = 12; - ZoneSystem drtZonalSystem = new H3ZoneSystem(crs, resolution, network, z -> true); + ZoneSystem zoneSystem = new H3ZoneSystem(crs, resolution, network, z -> true); // center of Holzkirchen - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("631059023282267135")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("631059023282267135")); // Thanning (Western border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("631058699768943103")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("631058699768943103")); // between Gross- and Kleinpienzenau (Southeastern border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("631058776116789759")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("631058776116789759")); //check all links are mapped for (Link link : network.getLinks().values()) { - assertNotNull(drtZonalSystem.getZoneForLinkId(link.getId())); + assertNotNull(zoneSystem.getZoneForLinkId(link.getId())); } } From 8caaa375a2b75a021b69b88f638e6a3f39b9be69 Mon Sep 17 00:00:00 2001 From: nkuehnel Date: Mon, 29 Jul 2024 14:08:34 +0200 Subject: [PATCH 099/101] shift drt maintenance; fix bug for prebooked e-drt scenarios that need shifts to be assignable to requests in advance; change priority queues in shift dispatcher to sorted sets to ensure correct iteration order --- .../scheduler/EShiftTaskScheduler.java | 70 +++- .../dispatcher/DrtShiftDispatcherImpl.java | 305 +++++++++--------- 2 files changed, 210 insertions(+), 165 deletions(-) diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/scheduler/EShiftTaskScheduler.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/scheduler/EShiftTaskScheduler.java index dc053728a40..a87c54a1be8 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/scheduler/EShiftTaskScheduler.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/scheduler/EShiftTaskScheduler.java @@ -6,6 +6,7 @@ import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.contrib.drt.extension.operations.eshifts.schedule.EDrtShiftChangeoverTaskImpl; +import org.matsim.contrib.drt.extension.operations.eshifts.schedule.EDrtWaitForShiftTask; import org.matsim.contrib.drt.extension.operations.eshifts.schedule.ShiftEDrtTaskFactoryImpl; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilities; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacility; @@ -22,10 +23,7 @@ import org.matsim.contrib.dvrp.fleet.Fleet; import org.matsim.contrib.dvrp.path.VrpPathWithTravelData; import org.matsim.contrib.dvrp.path.VrpPaths; -import org.matsim.contrib.dvrp.schedule.DriveTask; -import org.matsim.contrib.dvrp.schedule.Schedule; -import org.matsim.contrib.dvrp.schedule.StayTask; -import org.matsim.contrib.dvrp.schedule.Task; +import org.matsim.contrib.dvrp.schedule.*; import org.matsim.contrib.dvrp.tracker.OnlineDriveTaskTracker; import org.matsim.contrib.dvrp.util.LinkTimePair; import org.matsim.contrib.ev.charging.BatteryCharging; @@ -348,16 +346,20 @@ private void appendShiftChange(DvrpVehicle vehicle, DrtShift shift, OperationFac link, breakFacility)); } + @Override public void startShift(ShiftDvrpVehicle vehicle, double now, DrtShift shift) { - Schedule schedule = vehicle.getSchedule(); - StayTask stayTask = (StayTask) schedule.getCurrentTask(); - if (stayTask instanceof WaitForShiftTask) { - ((WaitForShiftTask) stayTask).getFacility().deregisterVehicle(vehicle.getId()); - stayTask.setEndTime(now); - schedule.addTask(taskFactory.createStayTask(vehicle, now, shift.getEndTime(), stayTask.getLink())); - } else { - throw new IllegalStateException("Vehicle cannot start shift during task:" + stayTask.getTaskType().name()); - } + Schedule schedule = vehicle.getSchedule(); + StayTask stayTask = (StayTask) schedule.getCurrentTask(); + if (stayTask instanceof WaitForShiftTask) { + ((WaitForShiftTask) stayTask).getFacility().deregisterVehicle(vehicle.getId()); + stayTask.setEndTime(now); + if(Schedules.getLastTask(schedule).equals(stayTask)) { + //nothing planned yet. + schedule.addTask(taskFactory.createStayTask(vehicle, now, shift.getEndTime(), stayTask.getLink())); + } + } else { + throw new IllegalStateException("Vehicle cannot start shift during task:" + stayTask.getTaskType().name()); + } } public boolean updateShiftChange(ShiftDvrpVehicle vehicle, Link link, DrtShift shift, @@ -379,17 +381,51 @@ public boolean updateShiftChange(ShiftDvrpVehicle vehicle, Link link, DrtShift s public void planAssignedShift(ShiftDvrpVehicle vehicle, double timeStep, DrtShift shift) { Schedule schedule = vehicle.getSchedule(); StayTask stayTask = (StayTask) schedule.getCurrentTask(); - if (stayTask instanceof WaitForShiftTask) { - stayTask.setEndTime(Math.max(timeStep, shift.getStartTime())); + if (stayTask instanceof WaitForShiftTask waitForShiftTask) { + if(waitForShiftTask instanceof EDrtWaitForShiftTask eDrtWaitForShiftTask) { + if(eDrtWaitForShiftTask.getChargingTask() != null) { + Task nextTask = Schedules.getNextTask(vehicle.getSchedule()); + if(nextTask instanceof WaitForShiftTask) { + // set +1 to ensure this update happens after next shift start check + nextTask.setEndTime(Math.max(timeStep + 1, shift.getStartTime())); + //append stay task if required + if(Schedules.getLastTask(schedule).equals(nextTask)) { + schedule.addTask(taskFactory.createStayTask(vehicle, nextTask.getEndTime(), shift.getEndTime(), ((WaitForShiftTask) nextTask).getLink())); + } + } else { + throw new RuntimeException(); + } + } else { + stayTask.setEndTime(Math.max(timeStep +1 , shift.getStartTime())); + //append stay task if required + if(Schedules.getLastTask(schedule).equals(stayTask)) { + schedule.addTask(taskFactory.createStayTask(vehicle, stayTask.getEndTime(), shift.getEndTime(), stayTask.getLink())); + } + } + } } } + @Override public void cancelAssignedShift(ShiftDvrpVehicle vehicle, double timeStep, DrtShift shift) { Schedule schedule = vehicle.getSchedule(); StayTask stayTask = (StayTask) schedule.getCurrentTask(); - if (stayTask instanceof WaitForShiftTask) { - stayTask.setEndTime(vehicle.getServiceEndTime()); + if (stayTask instanceof WaitForShiftTask waitForShiftTask) { + if(waitForShiftTask instanceof EDrtWaitForShiftTask eDrtWaitForShiftTask) { + if(eDrtWaitForShiftTask.getChargingTask() != null) { + Task nextTask = Schedules.getNextTask(vehicle.getSchedule()); + if(nextTask instanceof WaitForShiftTask) { + nextTask.setEndTime(vehicle.getServiceEndTime()); + } else { + throw new RuntimeException(); + } + } else { + stayTask.setEndTime(vehicle.getServiceEndTime()); + } + } + } else { + throw new IllegalStateException("Vehicle should be in WaitForShiftTask"); } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java index 5d983e81f05..6e082f6f7d5 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java @@ -51,10 +51,10 @@ public class DrtShiftDispatcherImpl implements DrtShiftDispatcher { private final String mode; - private Queue unscheduledShifts; - private Queue assignedShifts; - private Queue activeShifts; - private Queue endingShifts; + private SortedSet unscheduledShifts; + private SortedSet assignedShifts; + private SortedSet activeShifts; + private SortedSet endingShifts; private Map, Queue> idleVehiclesQueues; @@ -63,8 +63,8 @@ public class DrtShiftDispatcherImpl implements DrtShiftDispatcher { private final MobsimTimer timer; - private final OperationFacilities operationFacilities; - private final OperationFacilityFinder breakFacilityFinder; + private final OperationFacilities operationFacilities; + private final OperationFacilityFinder breakFacilityFinder; private final ShiftTaskScheduler shiftTaskScheduler; private final Network network; @@ -73,8 +73,8 @@ public class DrtShiftDispatcherImpl implements DrtShiftDispatcher { private final ShiftsParams drtShiftParams; - private final ShiftStartLogic shiftStartLogic; - private final AssignShiftToVehicleLogic assignShiftToVehicleLogic; + private final ShiftStartLogic shiftStartLogic; + private final AssignShiftToVehicleLogic assignShiftToVehicleLogic; public DrtShiftDispatcherImpl(String mode, DrtShifts shifts, Fleet fleet, MobsimTimer timer, OperationFacilities operationFacilities, OperationFacilityFinder breakFacilityFinder, ShiftTaskScheduler shiftTaskScheduler, @@ -84,54 +84,56 @@ public DrtShiftDispatcherImpl(String mode, DrtShifts shifts, Fleet fleet, Mobsim this.shifts = shifts; this.fleet = fleet; this.timer = timer; - this.operationFacilities = operationFacilities; - this.breakFacilityFinder = breakFacilityFinder; + this.operationFacilities = operationFacilities; + this.breakFacilityFinder = breakFacilityFinder; this.shiftTaskScheduler = shiftTaskScheduler; this.network = network; this.eventsManager = eventsManager; this.drtShiftParams = drtShiftParams; - this.shiftStartLogic = shiftStartLogic; - this.assignShiftToVehicleLogic = assignShiftToVehicleLogic; + this.shiftStartLogic = shiftStartLogic; + this.assignShiftToVehicleLogic = assignShiftToVehicleLogic; } - @Override - public void initialize() { + @Override + public void initialize() { - unscheduledShifts = new PriorityQueue<>(Comparator.comparingDouble(DrtShift::getStartTime)); + unscheduledShifts = new TreeSet<>(Comparator.comparingDouble(DrtShift::getStartTime)); unscheduledShifts.addAll(shifts.getShifts().values()); - assignedShifts = new PriorityQueue<>(Comparator.comparingDouble(v -> v.shift().getStartTime())); + assignedShifts = new TreeSet<>(Comparator.comparingDouble(v -> v.shift().getStartTime())); idleVehiclesQueues = new LinkedHashMap<>(); - for(OperationFacility facility: operationFacilities.getDrtOperationFacilities().values()) { - PriorityQueue queue = new PriorityQueue<>((v1, v2) -> String.CASE_INSENSITIVE_ORDER.compare(v1.getId().toString(), v2.getId().toString())); - Set> registeredVehicles = facility.getRegisteredVehicles(); - for (Id registeredVehicle : registeredVehicles) { - queue.add((ShiftDvrpVehicle) fleet.getVehicles().get(registeredVehicle)); - } - idleVehiclesQueues.put( - facility.getId(), - queue - ); - } - activeShifts = new PriorityQueue<>(Comparator.comparingDouble(v -> v.shift().getEndTime())); - endingShifts = new PriorityQueue<>(Comparator.comparingDouble(v -> v.shift().getEndTime())); + for(OperationFacility facility: operationFacilities.getDrtOperationFacilities().values()) { + PriorityQueue queue = new PriorityQueue<>((v1, v2) -> String.CASE_INSENSITIVE_ORDER.compare(v1.getId().toString(), v2.getId().toString())); + Set> registeredVehicles = facility.getRegisteredVehicles(); + for (Id registeredVehicle : registeredVehicles) { + queue.add((ShiftDvrpVehicle) fleet.getVehicles().get(registeredVehicle)); + } + idleVehiclesQueues.put( + facility.getId(), + queue + ); + } + activeShifts = new TreeSet<>(Comparator.comparingDouble(v -> v.shift().getEndTime())); + endingShifts = new TreeSet<>(Comparator.comparingDouble(v -> v.shift().getEndTime())); } - @Override + @Override public void dispatch(double timeStep) { - if(timeStep % drtShiftParams.loggingInterval == 0) { - logger.info(String.format("Active shifts: %s | Assigned shifts: %s | Unscheduled shifts: %s", - activeShifts.size(), assignedShifts.size(), unscheduledShifts.size())); - for (Map.Entry, Queue> queueEntry : idleVehiclesQueues.entrySet()) { - logger.info(String.format("Idle vehicles at facility %s: %d", queueEntry.getKey().toString(), queueEntry.getValue().size())); - } - } + if(timeStep % drtShiftParams.loggingInterval == 0) { + logger.info(String.format("Active shifts: %s | Assigned shifts: %s | Unscheduled shifts: %s", + activeShifts.size(), assignedShifts.size(), unscheduledShifts.size())); + StringJoiner print = new StringJoiner(" | "); + for (Map.Entry, Queue> queueEntry : idleVehiclesQueues.entrySet()) { + print.add(String.format("Idle vehicles at facility %s: %d", queueEntry.getKey().toString(), queueEntry.getValue().size())); + } + logger.info(print.toString()); + } endShifts(timeStep); - if (timeStep % (drtShiftParams.updateShiftEndInterval) == 0) { - updateShiftEnds(timeStep); - } - assignShifts(timeStep); + if (timeStep % (drtShiftParams.updateShiftEndInterval) == 0) { + updateShiftEnds(timeStep); + } + assignShifts(timeStep); startShifts(timeStep); checkBreaks(); } @@ -166,13 +168,13 @@ private void startShifts(double timeStep) { final ShiftEntry assignedShiftEntry = iterator.next(); if (assignedShiftEntry.shift().getStartTime() > timeStep) { shiftTaskScheduler.planAssignedShift(assignedShiftEntry.vehicle(), timeStep, assignedShiftEntry.shift()); - break; + continue; } else if (assignedShiftEntry.shift().getEndTime() < timeStep) { logger.warn("Too late to start shift " + assignedShiftEntry.shift().getId()); shiftTaskScheduler.cancelAssignedShift(assignedShiftEntry.vehicle(), timeStep, assignedShiftEntry.shift()); assignedShiftEntry.vehicle().getShifts().remove(assignedShiftEntry.shift()); iterator.remove(); - continue; + continue; } if (shiftStartLogic.shiftStarts(assignedShiftEntry)) { @@ -193,17 +195,24 @@ private void startShifts(double timeStep) { private void assignShifts(double timeStep) { // Remove elapsed shifts unscheduledShifts.removeIf(shift -> { - if (shift.getStartTime() + drtShiftParams.maxUnscheduledShiftDelay < timeStep ) { - logger.warn("Shift with ID " + shift.getId() + " could not be assigned and is being removed as start time is longer in the past than defined by maxUnscheduledShiftDelay."); + if (shift.getStartTime() + drtShiftParams.maxUnscheduledShiftDelay < timeStep ) { + logger.warn("Shift with ID " + shift.getId() + " could not be assigned and is being removed as start time is longer in the past than defined by maxUnscheduledShiftDelay."); return true; - } - return false; - }); + } + return false; + }); // Assign shifts Set assignableShifts = new LinkedHashSet<>(); - while (!this.unscheduledShifts.isEmpty() && isSchedulable(this.unscheduledShifts.peek(), timeStep)) { - assignableShifts.add(this.unscheduledShifts.poll()); + Iterator unscheduledShiftsIterator = unscheduledShifts.iterator(); + while(unscheduledShiftsIterator.hasNext()) { + DrtShift unscheduledShift = unscheduledShiftsIterator.next(); + if(isSchedulable(unscheduledShift, timeStep)) { + assignableShifts.add(unscheduledShift); + unscheduledShiftsIterator.remove(); + } else { + break; + } } for (DrtShift shift : assignableShifts) { @@ -213,24 +222,24 @@ private void assignShifts(double timeStep) { if (active.shift().getEndTime() > shift.getStartTime()) { break; } - if(shift.getOperationFacilityId().isPresent()) { - //we have to check that the vehicle ends the previous shift at the same facility where - //the new shift is to start. - if(active.shift().getOperationFacilityId().isPresent()) { - if(!active.shift().getOperationFacilityId().get().equals(shift.getOperationFacilityId().get())) { - continue; - } - } else { - Optional nextShiftChangeover = ShiftSchedules.getNextShiftChangeover(active.vehicle().getSchedule()); - if(nextShiftChangeover.isPresent()) { - Verify.verify(nextShiftChangeover.get().getShift().equals(active.shift())); - if(!nextShiftChangeover.get().getFacility().getId().equals(shift.getOperationFacilityId().get())) { - // there is already a shift changeover scheduled elsewhere - continue; - } - } - } - } + if(shift.getOperationFacilityId().isPresent()) { + //we have to check that the vehicle ends the previous shift at the same facility where + //the new shift is to start. + if(active.shift().getOperationFacilityId().isPresent()) { + if(!active.shift().getOperationFacilityId().get().equals(shift.getOperationFacilityId().get())) { + continue; + } + } else { + Optional nextShiftChangeover = ShiftSchedules.getNextShiftChangeover(active.vehicle().getSchedule()); + if(nextShiftChangeover.isPresent()) { + Verify.verify(nextShiftChangeover.get().getShift().equals(active.shift())); + if(!nextShiftChangeover.get().getFacility().getId().equals(shift.getOperationFacilityId().get())) { + // there is already a shift changeover scheduled elsewhere + continue; + } + } + } + } if (assignShiftToVehicleLogic.canAssignVehicleToShift(active.vehicle(), shift)) { vehicle = active.vehicle(); break; @@ -238,29 +247,29 @@ private void assignShifts(double timeStep) { } if (vehicle == null) { - final Iterator iterator; - - if(shift.getOperationFacilityId().isPresent()) { - //shift has to start at specific hub/facility - iterator = idleVehiclesQueues.get(shift.getOperationFacilityId().get()).iterator(); - } else { - //shift can start at random location - IteratorChain iteratorChain = new IteratorChain<>(); - for (Queue value : idleVehiclesQueues.values()) { - iteratorChain.addIterator(value.iterator()); - } - iterator = iteratorChain; - } - - while (iterator.hasNext()) { - final ShiftDvrpVehicle next = iterator.next(); - if (assignShiftToVehicleLogic.canAssignVehicleToShift(next, shift)) { - vehicle = next; - iterator.remove(); - break; - } - } - } + final Iterator iterator; + + if(shift.getOperationFacilityId().isPresent()) { + //shift has to start at specific hub/facility + iterator = idleVehiclesQueues.get(shift.getOperationFacilityId().get()).iterator(); + } else { + //shift can start at random location + IteratorChain iteratorChain = new IteratorChain<>(); + for (Queue value : idleVehiclesQueues.values()) { + iteratorChain.addIterator(value.iterator()); + } + iterator = iteratorChain; + } + + while (iterator.hasNext()) { + final ShiftDvrpVehicle next = iterator.next(); + if (assignShiftToVehicleLogic.canAssignVehicleToShift(next, shift)) { + vehicle = next; + iterator.remove(); + break; + } + } + } if (vehicle != null) { logger.debug("Shift assigned"); @@ -297,37 +306,37 @@ private void endShifts(double timeStep) { throw new IllegalStateException("Shifts don't match!"); } - logger.debug("Scheduling shift end for shift " + next.shift().getId() + " of vehicle " + next.vehicle().getId()); - scheduleShiftEnd(next); - endingShifts.add(next); - iterator.remove(); + logger.debug("Scheduling shift end for shift " + next.shift().getId() + " of vehicle " + next.vehicle().getId()); + scheduleShiftEnd(next); + endingShifts.add(next); + iterator.remove(); + } + } + + private void updateShiftEnds(double timeStep) { + final Iterator endingShiftsIterator = this.endingShifts.iterator(); + while (endingShiftsIterator.hasNext()) { + final ShiftEntry next = endingShiftsIterator.next(); + if (next.shift().isEnded()) { + endingShiftsIterator.remove(); + continue; + } + if (timeStep + drtShiftParams.shiftEndRescheduleLookAhead > next.shift().getEndTime()) { + if (next.vehicle().getShifts().size() > 1) { + updateShiftEnd(next); + } + } else { + break; + } + } + } + + private void updateShiftEnd(ShiftEntry next) { + + if(next.shift().getOperationFacilityId().isPresent()) { + //start and end facility are fixed + return; } - } - - private void updateShiftEnds(double timeStep) { - final Iterator endingShiftsIterator = this.endingShifts.iterator(); - while (endingShiftsIterator.hasNext()) { - final ShiftEntry next = endingShiftsIterator.next(); - if (next.shift().isEnded()) { - endingShiftsIterator.remove(); - continue; - } - if (timeStep + drtShiftParams.shiftEndRescheduleLookAhead > next.shift().getEndTime()) { - if (next.vehicle().getShifts().size() > 1) { - updateShiftEnd(next); - } - } else { - break; - } - } - } - - private void updateShiftEnd(ShiftEntry next) { - - if(next.shift().getOperationFacilityId().isPresent()) { - //start and end facility are fixed - return; - } final List tasks = next.vehicle().getSchedule().getTasks(); @@ -415,31 +424,31 @@ private void scheduleShiftEnd(ShiftEntry endingShift) { } final Coord coord = lastLink.getCoord(); - OperationFacility shiftChangeoverFacility = null; - - //check whether current shift has to end at specific facility - if(endingShift.shift().getOperationFacilityId().isPresent()) { - shiftChangeoverFacility = operationFacilities - .getDrtOperationFacilities() - .get(endingShift.shift().getOperationFacilityId().get()); - } else { - //check whether next shift has to start at specific facility - for (DrtShift shift : endingShift.vehicle().getShifts()) { - if (shift != endingShift.shift()) { - if (shift.getOperationFacilityId().isPresent()) { - shiftChangeoverFacility = operationFacilities - .getDrtOperationFacilities() - .get(shift.getOperationFacilityId().get()); - } - break; - } - } - } - - if(shiftChangeoverFacility == null) { - shiftChangeoverFacility = breakFacilityFinder.findFacilityOfType(coord, - OperationFacilityType.hub).orElseThrow(() -> new RuntimeException("Could not find shift end location!")); - } + OperationFacility shiftChangeoverFacility = null; + + //check whether current shift has to end at specific facility + if(endingShift.shift().getOperationFacilityId().isPresent()) { + shiftChangeoverFacility = operationFacilities + .getDrtOperationFacilities() + .get(endingShift.shift().getOperationFacilityId().get()); + } else { + //check whether next shift has to start at specific facility + for (DrtShift shift : endingShift.vehicle().getShifts()) { + if (shift != endingShift.shift()) { + if (shift.getOperationFacilityId().isPresent()) { + shiftChangeoverFacility = operationFacilities + .getDrtOperationFacilities() + .get(shift.getOperationFacilityId().get()); + } + break; + } + } + } + + if(shiftChangeoverFacility == null) { + shiftChangeoverFacility = breakFacilityFinder.findFacilityOfType(coord, + OperationFacilityType.hub).orElseThrow(() -> new RuntimeException("Could not find shift end location!")); + } Verify.verify(shiftChangeoverFacility.register(endingShift.vehicle().getId()), "Could not register vehicle at facility."); @@ -488,14 +497,14 @@ public void endBreak(ShiftDvrpVehicle vehicle, ShiftBreakTask previousTask) { new VehicleLeftShiftFacilityEvent(timer.getTimeOfDay(), mode, vehicle.getId(), facility.getId())); eventsManager.processEvent( new DrtShiftBreakEndedEvent(timer.getTimeOfDay(), mode, vehicle.getShifts().peek().getId(), - vehicle.getId(), previousTask.getFacility().getLinkId()) + vehicle.getId(), previousTask.getFacility().getLinkId()) ); } public void startBreak(ShiftDvrpVehicle vehicle, Id linkId) { eventsManager.processEvent( new DrtShiftBreakStartedEvent(timer.getTimeOfDay(), mode, - vehicle.getShifts().peek().getId(), vehicle.getId(), linkId) + vehicle.getShifts().peek().getId(), vehicle.getId(), linkId) ); } From 3af17e545de4acf1ad4f322a50e11e520d0dee7f Mon Sep 17 00:00:00 2001 From: nkuehnel Date: Mon, 29 Jul 2024 15:18:50 +0200 Subject: [PATCH 100/101] make FISS integration test less sensible to smaller changes in link events --- .../matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java index fc58f3b3b63..120cff4f5a3 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java @@ -184,7 +184,7 @@ public void install() { } run.run(); - Assertions.assertEquals(20842, linkCounter.getLinkLeaveCount()); + Assertions.assertEquals(20000, linkCounter.getLinkLeaveCount(), 2000); } static class LinkCounter implements LinkLeaveEventHandler { From 4fa6530cc84ec4e37e3179745bcc87311c6bd73e Mon Sep 17 00:00:00 2001 From: Kai Martins-Turner Date: Mon, 29 Jul 2024 16:06:14 +0200 Subject: [PATCH 101/101] set level of some logging's back from WARN to DEBUG --- .../org/matsim/freight/carriers/controler/CarrierAgent.java | 2 +- .../matsim/freight/carriers/controler/FreightAgentSource.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgent.java index 88423d00a1f..da31ae5637d 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgent.java @@ -179,7 +179,7 @@ void scoreSelectedPlan() { } scoringFunction.finish(); final double score = scoringFunction.getScore(); - log.warn("score={}", score); + log.debug("score of carrier {} = {}", carrier.getId(), score); carrier.getSelectedPlan().setScore( score ); } void handleEvent(Event event, Id driverId) { diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightAgentSource.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightAgentSource.java index 6b60f14d91b..f5613f1a961 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightAgentSource.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightAgentSource.java @@ -83,7 +83,7 @@ public final class FreightAgentSource implements AgentSource { vehicle = CarriersUtils.getVehicle( freightDriverPlan ); } - log.warn("inserting vehicleId={} into mobsim.", vehicle.getId()); + log.debug("inserting vehicleId={} into mobsim.", vehicle.getId()); qsim.addParkedVehicle( new QVehicleImpl( vehicle ), agent.getCurrentLinkId() ); // yyyyyy should rather use QVehicleFactory. kai, nov'18