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; } /** 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) { 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/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: +``` + + + + + + + + +``` + 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/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/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..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 @@ -140,40 +140,52 @@ 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!"); } } } } 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()); + shiftTaskScheduler.cancelAssignedShift(assignedShiftEntry.vehicle(), timeStep, assignedShiftEntry.shift()); + 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()); } } } @@ -183,9 +195,9 @@ 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; + return false; }); // Assign shifts @@ -264,6 +276,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())); } @@ -357,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())); + } } } } @@ -423,50 +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 OperationFacility decideOnBreak(ShiftEntry activeShift) { - if (activeShift.shift() != null) { - if (shiftNeedsBreak(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; - } + private Optional findBreakFacility(ShiftEntry activeShift) { + 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(); } - return null; + return breakFacilityFinder.findFacility(lastLink.getCoord()); } @Override @@ -500,12 +500,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..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 @@ -1,7 +1,9 @@ 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.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; @@ -32,19 +34,24 @@ 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; + 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; + } + for (int s = 0; s < pickupIdx; s++) { Waypoint.Stop stop = vEntry.stops.get(s); if (stop.task instanceof ShiftChangeOverTask) { @@ -53,6 +60,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 +82,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++) { @@ -109,6 +120,31 @@ boolean checkShiftTimeConstraintsForScheduledRequests(Insertion insertion, doubl 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 } } 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..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 @@ -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; @@ -95,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 { @@ -156,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)); @@ -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/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(); } 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 { 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..5babef611b3 --- /dev/null +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunPrebookingShiftDrtScenarioIT.java @@ -0,0 +1,329 @@ +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.*; +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; + shiftsParams.shiftEndLookAhead = 900.; + 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))); + Assertions.assertFalse(rejectedPersons.contains(Id.createPersonId(5))); + Assertions.assertTrue(rejectedPersons.contains(Id.createPersonId(6))); + } + + 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", 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))); + 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(10800) + .id(Id.create(1, DrtShift.class)) + .shiftBreak(DrtShiftBreakSpecificationImpl.newBuilder().duration(600.).earliestStart(6000.).latestEnd(7000.).build()) + .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/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()); } 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()); 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..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()) { @@ -283,8 +282,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 +291,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()); } } } @@ -308,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/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/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..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 @@ -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 { @@ -237,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 @@ -314,7 +313,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 +348,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(), @@ -513,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; @@ -556,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/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/Tour.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/Tour.java index 9b0e9d91696..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; } @@ -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..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 @@ -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; } @@ -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); } } @@ -119,8 +114,8 @@ private void handleEvent( PersonArrivalEvent event ){ currentRoute = null; } else{ Id startLink; - if( currentRoute.size() != 0 ){ - startLink = currentRoute.get( 0 ); + if(!currentRoute.isEmpty()){ + startLink = currentRoute.getFirst(); } else{ startLink = event.getLinkId(); } @@ -163,7 +158,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/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/DistanceConstraint.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceConstraint.java index 0d6c4725b97..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), @@ -258,9 +258,9 @@ 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); + .getLast(); TourActivity activityEnd = route.getEnd(); double possibleAdditionalDistance = getDistance(activityLastDelivery, assignedDelivery, newVehicle) + getDistance(assignedDelivery, activityEnd, newVehicle) 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..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( @@ -318,7 +319,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 +330,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 +370,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 +443,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 +499,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 +520,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 +603,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 +625,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 +634,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 @@ -734,8 +731,8 @@ public static VehicleRoutingAlgorithm loadOrCreateVehicleRoutingAlgorithm(Scenar VehicleRoutingAlgorithm algorithm; final String vehicleRoutingAlgorithmFile = freightConfig.getVehicleRoutingAlgorithmFile(); - if (vehicleRoutingAlgorithmFile != null && !vehicleRoutingAlgorithmFile.equals("")) { - log.info("Will read in VehicleRoutingAlgorithm from " + vehicleRoutingAlgorithmFile); + if (vehicleRoutingAlgorithmFile != null && !vehicleRoutingAlgorithmFile.isEmpty()) { + 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/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; 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/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/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; } 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/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/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); 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 e5412431ca5..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 @@ -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" ); @@ -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 22d23f8eefe..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 @@ -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" ); @@ -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 822b98269d6..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 @@ -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" ); @@ -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,15 +112,15 @@ void test_whenReadingPlans_nuOfToursIsCorrect(){ @Test void test_whenReadingToursOfPlan1_nuOfActivitiesIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); - CarrierPlan plan1 = plans.get(0); + List plans = new ArrayList<>(testCarrier.getPlans()); + CarrierPlan plan1 = plans.getFirst(); ScheduledTour tour1 = plan1.getScheduledTours().iterator().next(); assertEquals(5,tour1.getTour().getTourElements().size()); } @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(); } @@ -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 7788b8895f5..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; @@ -43,7 +42,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" ); @@ -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()); } @@ -104,7 +106,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,15 +114,15 @@ void test_whenReadingPlans_nuOfToursIsCorrect(){ @Test void test_whenReadingToursOfPlan1_nuOfActivitiesIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); - CarrierPlan plan1 = plans.get(0); + List plans = new ArrayList<>(testCarrier.getPlans()); + CarrierPlan plan1 = plans.getFirst(); ScheduledTour tour1 = plan1.getScheduledTours().iterator().next(); assertEquals(5,tour1.getTour().getTourElements().size()); } @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 +130,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,31 +138,32 @@ void test_whenReadingToursOfPlan3_nuOfActivitiesIsCorrect(){ @Test void test_whenReadingToursOfPlan1_SpritScoreIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); - CarrierPlan plan1 = plans.get(0); + 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 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); + assertEquals(80.0, CarriersUtils.getJspritScore(plan2), MatsimTestUtils.EPSILON); } @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); + assertEquals(105.0, CarriersUtils.getJspritScore(plan3), MatsimTestUtils.EPSILON); } 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(); } @@ -175,10 +178,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/CarrierReadWriteV2_1Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java index be71e48b2ca..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 { @@ -36,7 +34,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 +55,7 @@ void readWriteTest() throws FileNotFoundException, IOException { @Test - void readWriteReadTest() throws FileNotFoundException, IOException { + void readWriteReadTest() { Carriers carriers = new Carriers(Collections.emptyList()); CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); 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/CarrierVehicleTypeReaderTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest.java index 2fe9b82dc26..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 @@ -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 @@ -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/CarrierVehicleTypeTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeTest.java index 8ca8a5aae02..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 ); { @@ -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); } } 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)); 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 16c42c7286c..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()); @@ -494,13 +490,12 @@ 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(); 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()); @@ -576,13 +571,12 @@ 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(); 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/FixedCostsTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/FixedCostsTest.java index 07ea6e5ac60..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); @@ -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) ; 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..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 @@ -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); @@ -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 @@ -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) { @@ -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 @@ -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"); @@ -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(); @@ -423,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); @@ -436,26 +431,21 @@ 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); - 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); 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); - assertEquals("i(3,9)", service2.getLocation().getId().toString()); - } - - @Test - void createVehicleRoutingProblemWithShipments_isMadeCorrectly() { - // TODO create + assertEquals("i(3,9)", service2.getLocation().getId()); } // @Disabled //Set to ignore due to not implemented functionality of Shipments in MatsimJspritFactory @@ -476,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); @@ -489,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()); @@ -505,10 +495,10 @@ 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()); + assertEquals("i(3,9)", shipment2.getDeliveryLocation().getId()); } private Carrier createCarrierWithServices() { 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..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 @@ -62,7 +62,7 @@ public DriverLegScoring(Carrier carrier, Network network) { super(); this.network = network; this.carrier = carrier; - employedVehicles = new HashSet(); + employedVehicles = new HashSet<>(); } @@ -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); @@ -154,7 +153,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 +191,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..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 @@ -61,7 +61,7 @@ public DriverLegScoring(Carrier carrier, Network network) { super(); this.network = network; this.carrier = carrier; - employedVehicles = new HashSet(); + employedVehicles = new HashSet<>(); } @@ -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); @@ -136,7 +135,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 +173,7 @@ public void reset() { static class NumberOfToursAward implements BasicScoring{ - private Carrier carrier; + private final Carrier carrier; public NumberOfToursAward(Carrier carrier) { super(); @@ -199,7 +198,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..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; @@ -200,7 +199,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/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() ; 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..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 { @@ -443,7 +442,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()); 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..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 @@ -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())); @@ -888,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..."); 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..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 @@ -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); } @@ -195,34 +195,29 @@ 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) { 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.setEndTime(activity.getEndTime().seconds()); + 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); } } @@ -241,8 +236,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())); 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 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. 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 @@ - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pom.xml b/pom.xml index cb137bfeb6a..3f97fb8c5d3 100644 --- a/pom.xml +++ b/pom.xml @@ -314,7 +314,7 @@ org.assertj assertj-core - 3.26.0 + 3.26.3 test @@ -358,7 +358,7 @@ net.bytebuddy byte-buddy - 1.14.17 + 1.14.18 test @@ -425,7 +425,7 @@ org.apache.maven.plugins maven-failsafe-plugin - 3.3.0 + 3.3.1 org.apache.maven.plugins