diff --git a/contribs/application/src/main/java/org/matsim/application/analysis/activity/ActivityCountAnalysis.java b/contribs/application/src/main/java/org/matsim/application/analysis/activity/ActivityCountAnalysis.java new file mode 100644 index 00000000000..b944ee044fb --- /dev/null +++ b/contribs/application/src/main/java/org/matsim/application/analysis/activity/ActivityCountAnalysis.java @@ -0,0 +1,220 @@ +package org.matsim.application.analysis.activity; + +import it.unimi.dsi.fastutil.objects.Object2IntMap; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.geotools.api.feature.Property; +import org.geotools.api.feature.simple.SimpleFeature; +import org.locationtech.jts.geom.Geometry; +import org.matsim.api.core.v01.Coord; +import org.matsim.application.CommandSpec; +import org.matsim.application.MATSimAppCommand; +import org.matsim.application.options.*; +import org.matsim.core.utils.io.IOUtils; +import picocli.CommandLine; +import tech.tablesaw.api.*; +import tech.tablesaw.io.csv.CsvReadOptions; +import tech.tablesaw.selection.Selection; + +import java.util.*; +import java.util.regex.Pattern; + +@CommandSpec( + requires = {"activities.csv"}, + produces = {"activities_%s_per_region.csv"} +) +public class ActivityCountAnalysis implements MATSimAppCommand { + + private static final Logger log = LogManager.getLogger(ActivityCountAnalysis.class); + + @CommandLine.Mixin + private final InputOptions input = InputOptions.ofCommand(ActivityCountAnalysis.class); + @CommandLine.Mixin + private final OutputOptions output = OutputOptions.ofCommand(ActivityCountAnalysis.class); + @CommandLine.Mixin + private ShpOptions shp; + @CommandLine.Mixin + private SampleOptions sample; + @CommandLine.Mixin + private CrsOptions crs; + + /** + * Specifies the column in the shapefile used as the region ID. + */ + @CommandLine.Option(names = "--id-column", description = "Column to use as ID for the shapefile", required = true) + private String idColumn; + + /** + * Maps patterns to merge activity types into a single category. + * Example: `home;work` can merge activities "home1" and "work1" into categories "home" and "work". + */ + @CommandLine.Option(names = "--activity-mapping", description = "Map of patterns to merge activity types", split = ";") + private Map activityMapping; + + /** + * Specifies activity types that should be counted only once per agent per region. + */ + @CommandLine.Option(names = "--single-occurrence", description = "Activity types that are only counted once per agent") + private Set singleOccurrence; + + public static void main(String[] args) { + new ActivityCountAnalysis().execute(args); + } + + /** + * Executes the activity count analysis. + * + * @return Exit code (0 for success). + * @throws Exception if errors occur during execution. + */ + @Override + public Integer call() throws Exception { + + // Prepares the activity mappings and reads input data + HashMap> formattedActivityMapping = new HashMap<>(); + Map regionAreaMap = new HashMap<>(); + + if (this.activityMapping == null) this.activityMapping = new HashMap<>(); + + for (Map.Entry entry : this.activityMapping.entrySet()) { + String pattern = entry.getKey(); + String activity = entry.getValue(); + Set activities = new HashSet<>(Arrays.asList(activity.split(","))); + formattedActivityMapping.put(pattern, activities); + } + + // Reading the input csv + Table activities = Table.read().csv(CsvReadOptions.builder(IOUtils.getBufferedReader(input.getPath("activities.csv"))) + .columnTypesPartial(Map.of("person", ColumnType.TEXT, "activity_type", ColumnType.TEXT)) + .sample(false) + .separator(CsvOptions.detectDelimiter(input.getPath("activities.csv"))).build()); + + // remove the underscore and the number from the activity_type column + TextColumn activityType = activities.textColumn("activity_type"); + activityType.set(Selection.withRange(0, activityType.size()), activityType.replaceAll("_[0-9]{2,}$", "")); + + ShpOptions.Index index = crs.getInputCRS() == null ? shp.createIndex(idColumn) : shp.createIndex(crs.getInputCRS(), idColumn); + + // stores the counts of activities per region + Object2ObjectOpenHashMap> regionActivityCounts = new Object2ObjectOpenHashMap<>(); + // stores the activities that have been counted for each person in each region + Object2ObjectOpenHashMap> personActivityTracker = new Object2ObjectOpenHashMap<>(); + + // iterate over the csv rows + for (Row row : activities) { + String person = row.getString("person"); + String activity = row.getText("activity_type"); + + for (Map.Entry> entry : formattedActivityMapping.entrySet()) { + String pattern = entry.getKey(); + Set activities2 = entry.getValue(); + for (String act : activities2) { + if (Pattern.matches(act, activity)) { + activity = pattern; + break; + } + } + } + + Coord coord = new Coord(row.getDouble("coord_x"), row.getDouble("coord_y")); + + // get the region for the current coordinate + SimpleFeature feature = index.queryFeature(coord); + + if (feature == null) { + continue; + } + + Geometry geometry = (Geometry) feature.getDefaultGeometry(); + + Property prop = feature.getProperty(idColumn); + if (prop == null) + throw new IllegalArgumentException("No property found for column %s".formatted(idColumn)); + + Object region = prop.getValue(); + if (region != null && region.toString().length() > 0) { + + double area = geometry.getArea(); + regionAreaMap.put(region.toString(), area); + + // Add region to the activity counts and person activity tracker if not already present + regionActivityCounts.computeIfAbsent(region, k -> new Object2IntOpenHashMap<>()); + personActivityTracker.computeIfAbsent(region, k -> new HashSet<>()); + + Set trackedActivities = personActivityTracker.get(region); + String personActivityKey = person + "_" + activity; + + // adding activity only if it has not been counted for the person in the region + if (singleOccurrence == null || !singleOccurrence.contains(activity) || !trackedActivities.contains(personActivityKey)) { + Object2IntMap activityCounts = regionActivityCounts.get(region); + activityCounts.mergeInt(activity, 1, Integer::sum); + + // mark the activity as counted for the person in the region + trackedActivities.add(personActivityKey); + } + } + } + + Set uniqueActivities = new HashSet<>(); + + for (Object2IntMap map : regionActivityCounts.values()) { + uniqueActivities.addAll(map.keySet()); + } + + for (String activity : uniqueActivities) { + Table resultTable = Table.create(); + TextColumn regionColumn = TextColumn.create("id"); + DoubleColumn activityColumn = DoubleColumn.create("count"); + DoubleColumn distributionColumn = DoubleColumn.create("relative_density"); + DoubleColumn countRatioColumn = DoubleColumn.create("density"); + DoubleColumn areaColumn = DoubleColumn.create("area"); + + resultTable.addColumns(regionColumn, activityColumn, distributionColumn, countRatioColumn, areaColumn); + for (Map.Entry> entry : regionActivityCounts.entrySet()) { + Object region = entry.getKey(); + double value = 0; + for (Map.Entry entry2 : entry.getValue().object2IntEntrySet()) { + String ect = entry2.getKey(); + if (Pattern.matches(ect, activity)) { + value = entry2.getValue() * sample.getUpscaleFactor(); + break; + } + } + + + Row row = resultTable.appendRow(); + row.setString("id", region.toString()); + row.setDouble("count", value); + } + + for (Row row : resultTable) { + Double area = regionAreaMap.get(row.getString("id")); + if (area != null) { + row.setDouble("area", area); + row.setDouble("density", row.getDouble("count") / area); + } else { + log.warn("Area for region {} is not found", row.getString("id")); + } + } + + Double averageDensity = countRatioColumn.mean(); + + for (Row row : resultTable) { + Double value = row.getDouble("density"); + if (averageDensity != 0) { + row.setDouble("relative_density", value / averageDensity); + } else { + row.setDouble("relative_density", 0.0); + } + } + + + resultTable.write().csv(output.getPath("activities_%s_per_region.csv", activity).toFile()); + log.info("Wrote activity counts for {} to {}", activity, output.getPath("activities_%s_per_region.csv", activity)); + } + + return 0; + } +} diff --git a/contribs/application/src/main/java/org/matsim/application/analysis/traffic/traveltime/TravelTimeComparison.java b/contribs/application/src/main/java/org/matsim/application/analysis/traffic/traveltime/TravelTimeComparison.java index 3c22fc678a3..41abdbcff54 100644 --- a/contribs/application/src/main/java/org/matsim/application/analysis/traffic/traveltime/TravelTimeComparison.java +++ b/contribs/application/src/main/java/org/matsim/application/analysis/traffic/traveltime/TravelTimeComparison.java @@ -1,5 +1,7 @@ package org.matsim.application.analysis.traffic.traveltime; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; @@ -47,6 +49,8 @@ ) public class TravelTimeComparison implements MATSimAppCommand { + private static final Logger log = LogManager.getLogger(TravelTimeComparison.class); + @CommandLine.Mixin private InputOptions input = InputOptions.ofCommand(TravelTimeComparison.class); @@ -90,6 +94,13 @@ public Integer call() throws Exception { for (Row row : data) { LeastCostPathCalculator.Path congested = computePath(network, congestedRouter, row); + + // Skip if path is not found + if (congested == null) { + row.setDouble("simulated", Double.NaN); + continue; + } + double dist = congested.links.stream().mapToDouble(Link::getLength).sum(); double speed = 3.6 * dist / congested.travelTime; @@ -102,6 +113,8 @@ public Integer call() throws Exception { row.setDouble("free_flow", speed); } + data = data.dropWhere(data.doubleColumn("simulated").isMissing()); + data.addColumns( data.doubleColumn("simulated").subtract(data.doubleColumn("mean")).setName("bias") ); @@ -129,6 +142,16 @@ private LeastCostPathCalculator.Path computePath(Network network, LeastCostPathC Node fromNode = network.getNodes().get(Id.createNodeId(row.getString("from_node"))); Node toNode = network.getNodes().get(Id.createNodeId(row.getString("to_node"))); + if (fromNode == null) { + log.error("Node {} not found in network", row.getString("from_node")); + return null; + } + + if (toNode == null) { + log.error("Node {} not found in network", row.getString("to_node")); + return null; + } + return router.calcLeastCostPath(fromNode, toNode, row.getInt("hour") * 3600, null, null); } diff --git a/contribs/application/src/main/java/org/matsim/application/options/ShpOptions.java b/contribs/application/src/main/java/org/matsim/application/options/ShpOptions.java index 5d9f8ccec99..55b7e01846e 100644 --- a/contribs/application/src/main/java/org/matsim/application/options/ShpOptions.java +++ b/contribs/application/src/main/java/org/matsim/application/options/ShpOptions.java @@ -230,6 +230,7 @@ public Geometry getGeometry() { /** * Return the union of all geometries in the shape file and project it to the target crs. + * * @param toCRS target coordinate system */ public Geometry getGeometry(String toCRS) { diff --git a/contribs/application/src/main/java/org/matsim/application/prepare/pt/CreateTransitScheduleFromGtfs.java b/contribs/application/src/main/java/org/matsim/application/prepare/pt/CreateTransitScheduleFromGtfs.java index cef7709361e..5483167fcdf 100644 --- a/contribs/application/src/main/java/org/matsim/application/prepare/pt/CreateTransitScheduleFromGtfs.java +++ b/contribs/application/src/main/java/org/matsim/application/prepare/pt/CreateTransitScheduleFromGtfs.java @@ -33,10 +33,7 @@ import java.io.File; import java.nio.file.Path; import java.time.LocalDate; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; @@ -206,6 +203,13 @@ public Integer call() throws Exception { Scenario ptScenario = getScenarioWithPseudoPtNetworkAndTransitVehicles(network, scenario.getTransitSchedule(), "pt_"); + for (TransitLine line : new ArrayList<>(scenario.getTransitSchedule().getTransitLines().values())) { + if (line.getRoutes().isEmpty()) { + log.warn("Line {} with no routes removed.", line.getId()); + scenario.getTransitSchedule().removeTransitLine(line); + } + } + if (validate) { //Check schedule and network TransitScheduleValidator.ValidationResult checkResult = TransitScheduleValidator.validateAll(ptScenario.getTransitSchedule(), ptScenario.getNetwork()); @@ -477,8 +481,12 @@ private Scenario getScenarioWithPseudoPtNetworkAndTransitVehicles(Network networ // so we need to add time for passengers to board and alight double minStopTime = 30.0; + List> routeIds = new LinkedList<>(); + routeIds.add(route.getRoute().getStartLinkId()); + routeIds.addAll(route.getRoute().getLinkIds()); + routeIds.add(route.getRoute().getEndLinkId()); + for (int i = 1; i < routeStops.size(); i++) { - // TODO cater for loop link at first stop? Seems to just work without. TransitRouteStop routeStop = routeStops.get(i); // if there is no departure offset set (or infinity), it is the last stop of the line, // so we don't need to care about the stop duration @@ -490,8 +498,23 @@ private Scenario getScenarioWithPseudoPtNetworkAndTransitVehicles(Network networ // Math.max to avoid negative values of travelTime double travelTime = Math.max(1, routeStop.getArrivalOffset().seconds() - lastDepartureOffset - 1.0 - (stopDuration >= minStopTime ? 0 : (minStopTime - stopDuration))); - Link link = network.getLinks().get(routeStop.getStopFacility().getLinkId()); - increaseLinkFreespeedIfLower(link, link.getLength() / travelTime); + + + Id stopLink = routeStop.getStopFacility().getLinkId(); + List> subRoute = new LinkedList<>(); + do { + Id linkId = routeIds.removeFirst(); + subRoute.add(linkId); + } while (!subRoute.contains(stopLink)); + + List links = subRoute.stream().map(scenario.getNetwork().getLinks()::get) + .toList(); + + double length = links.stream().mapToDouble(Link::getLength).sum(); + + for (Link link : links) { + increaseLinkFreespeedIfLower(link, length / travelTime); + } lastDepartureOffset = routeStop.getDepartureOffset().seconds(); } diff --git a/contribs/application/src/main/java/org/matsim/application/prepare/scenario/CreateScenarioCutOut.java b/contribs/application/src/main/java/org/matsim/application/prepare/scenario/CreateScenarioCutOut.java index 4dcd8a6bf5a..909d311d64f 100644 --- a/contribs/application/src/main/java/org/matsim/application/prepare/scenario/CreateScenarioCutOut.java +++ b/contribs/application/src/main/java/org/matsim/application/prepare/scenario/CreateScenarioCutOut.java @@ -590,9 +590,12 @@ public void run(Person person) { } // Remove all unselected plans because these are not handled - person.getPlans().stream() - .filter(p -> p != person.getSelectedPlan()) - .forEach(person::removePlan); + List plans = new ArrayList<>(person.getPlans()); + for(Plan p : plans){ + if (p != person.getSelectedPlan()){ + person.removePlan(p); + } + } } 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 63179128cc4..6b2d6c10784 100644 --- a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java +++ b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java @@ -655,7 +655,7 @@ else if (samplingOption.equals("changeNumberOfLocationsWithDemand")) { createJobId(scenario, newDemandInformationElement, link.getId(), null), CarrierService.class); CarrierService thisService = CarrierService.Builder.newInstance(idNewService, link.getId()) - .setCapacityDemand(demandForThisLink).setServiceDuration(serviceTime) + .setDemand(demandForThisLink).setServiceDuration(serviceTime) .setServiceStartTimeWindow(newDemandInformationElement.getFirstJobElementTimeWindow()) .build(); CarriersUtils.getCarriers(scenario).getCarriers() @@ -696,7 +696,7 @@ else if (samplingOption.equals("changeNumberOfLocationsWithDemand")) { CarrierService.class); if (demandToDistribute > 0 && singleDemandForThisLink > 0) { CarrierService thisService = CarrierService.Builder.newInstance(idNewService, link.getId()) - .setCapacityDemand(singleDemandForThisLink).setServiceDuration(serviceTime) + .setDemand(singleDemandForThisLink).setServiceDuration(serviceTime) .setServiceStartTimeWindow(newDemandInformationElement.getFirstJobElementTimeWindow()) .build(); thisCarrier.getServices().put(thisService.getId(), thisService); @@ -747,7 +747,7 @@ else if (samplingOption.equals("changeNumberOfLocationsWithDemand")) { createJobId(scenario, newDemandInformationElement, link.getId(), null), CarrierService.class); if ((demandToDistribute > 0 && singleDemandForThisLink > 0) || demandToDistribute == 0) { CarrierService thisService = CarrierService.Builder.newInstance(idNewService, link.getId()) - .setCapacityDemand(singleDemandForThisLink).setServiceDuration(serviceTime) + .setDemand(singleDemandForThisLink).setServiceDuration(serviceTime) .setServiceStartTimeWindow(newDemandInformationElement.getFirstJobElementTimeWindow()) .build(); CarriersUtils.getCarriers(scenario).getCarriers() @@ -1051,8 +1051,8 @@ private static void createSingleShipment(Scenario scenario, DemandInformationEle CarrierShipment thisShipment = CarrierShipment.Builder .newInstance(idNewShipment, linkPickup.getId(), linkDelivery.getId(), singleDemandForThisLink) - .setPickupServiceTime(serviceTimePickup).setPickupTimeWindow(timeWindowPickup) - .setDeliveryServiceTime(serviceTimeDelivery).setDeliveryTimeWindow(timeWindowDelivery) + .setPickupDuration(serviceTimePickup).setPickupStartsTimeWindow(timeWindowPickup) + .setDeliveryDuration(serviceTimeDelivery).setDeliveryStartsTimeWindow(timeWindowDelivery) .build(); thisCarrier.getShipments().put(thisShipment.getId(), thisShipment); if (demandForThisLink == 0) @@ -1188,11 +1188,12 @@ private static void combineSimilarJobs(Scenario scenario) { if (!shipmentsToRemove.containsKey(thisShipmentId)) { CarrierShipment thisShipment = thisCarrier.getShipments().get(thisShipmentId); if (baseShipment.getId() != thisShipment.getId() - && baseShipment.getFrom() == thisShipment.getFrom() - && baseShipment.getTo() == thisShipment.getTo() - && baseShipment.getPickupTimeWindow() == thisShipment.getPickupTimeWindow() - && baseShipment.getDeliveryTimeWindow() == thisShipment.getDeliveryTimeWindow()) - shipmentsToConnect.put(thisShipmentId, thisShipment); + && baseShipment.getPickupLinkId() == thisShipment.getPickupLinkId() + && baseShipment.getDeliveryLinkId() == thisShipment.getDeliveryLinkId()) { + if (baseShipment.getPickupStartsTimeWindow() == thisShipment.getPickupStartsTimeWindow()) { + if (baseShipment.getDeliveryStartsTimeWindow() == thisShipment.getDeliveryStartsTimeWindow()) shipmentsToConnect.put(thisShipmentId, thisShipment); + } + } } } Id idNewShipment = baseShipment.getId(); @@ -1200,17 +1201,17 @@ private static void combineSimilarJobs(Scenario scenario) { double serviceTimePickup = 0; double serviceTimeDelivery = 0; for (CarrierShipment carrierShipment : shipmentsToConnect.values()) { - demandForThisLink = demandForThisLink + carrierShipment.getSize(); - serviceTimePickup = serviceTimePickup + carrierShipment.getPickupServiceTime(); - serviceTimeDelivery = serviceTimeDelivery + carrierShipment.getDeliveryServiceTime(); + demandForThisLink = demandForThisLink + carrierShipment.getDemand(); + serviceTimePickup = serviceTimePickup + carrierShipment.getPickupDuration(); + serviceTimeDelivery = serviceTimeDelivery + carrierShipment.getDeliveryDuration(); shipmentsToRemove.put(carrierShipment.getId(), carrierShipment); } CarrierShipment newShipment = CarrierShipment.Builder - .newInstance(idNewShipment, baseShipment.getFrom(), baseShipment.getTo(), demandForThisLink) - .setPickupServiceTime(serviceTimePickup) - .setPickupTimeWindow(baseShipment.getPickupTimeWindow()) - .setDeliveryServiceTime(serviceTimeDelivery) - .setDeliveryTimeWindow(baseShipment.getDeliveryTimeWindow()).build(); + .newInstance(idNewShipment, baseShipment.getPickupLinkId(), baseShipment.getDeliveryLinkId(), demandForThisLink) + .setPickupDuration(serviceTimePickup) + .setPickupStartsTimeWindow(baseShipment.getPickupStartsTimeWindow()) + .setDeliveryDuration(serviceTimeDelivery) + .setDeliveryStartsTimeWindow(baseShipment.getDeliveryStartsTimeWindow()).build(); shipmentsToAdd.add(newShipment); } } @@ -1236,7 +1237,7 @@ private static void combineSimilarJobs(Scenario scenario) { if (!servicesToRemove.containsKey(thisServiceId)) { CarrierService thisService = thisCarrier.getServices().get(thisServiceId); if (baseService.getId() != thisService.getId() - && baseService.getLocationLinkId() == thisService.getLocationLinkId() && baseService + && baseService.getServiceLinkId() == thisService.getServiceLinkId() && baseService .getServiceStartTimeWindow() == thisService.getServiceStartTimeWindow()) servicesToConnect.put(thisServiceId, thisService); } @@ -1245,15 +1246,15 @@ private static void combineSimilarJobs(Scenario scenario) { int demandForThisLink = 0; double serviceTimeService = 0; for (CarrierService carrierService : servicesToConnect.values()) { - demandForThisLink = demandForThisLink + carrierService.getCapacityDemand(); + demandForThisLink = demandForThisLink + carrierService.getDemand(); serviceTimeService = serviceTimeService + carrierService.getServiceDuration(); servicesToRemove.put(carrierService.getId(), carrierService); } CarrierService newService = CarrierService.Builder - .newInstance(idNewService, baseService.getLocationLinkId()) + .newInstance(idNewService, baseService.getServiceLinkId()) .setServiceDuration(serviceTimeService) .setServiceStartTimeWindow(baseService.getServiceStartTimeWindow()) - .setCapacityDemand(demandForThisLink).build(); + .setDemand(demandForThisLink).build(); servicesToAdd.add(newService); } } diff --git a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGenerationUtils.java b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGenerationUtils.java index ede28ace76d..235789535db 100644 --- a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGenerationUtils.java +++ b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGenerationUtils.java @@ -130,23 +130,23 @@ static void createDemandLocationsFile(Controler controler) { for (Carrier thisCarrier : CarriersUtils.getCarriers(controler.getScenario()).getCarriers().values()) { for (CarrierService thisService : thisCarrier.getServices().values()) { Coord coord = FreightDemandGenerationUtils - .getCoordOfMiddlePointOfLink(network.getLinks().get(thisService.getLocationLinkId())); + .getCoordOfMiddlePointOfLink(network.getLinks().get(thisService.getServiceLinkId())); writer.write(thisCarrier.getId().toString() + thisService.getId().toString() + " " + coord.getX() + " " + coord.getY() + " " + "Service" + " " - + thisService.getLocationLinkId().toString() + " " + "\n"); + + thisService.getServiceLinkId().toString() + " " + "\n"); } for (CarrierShipment thisShipment : thisCarrier.getShipments().values()) { Coord coordFrom = FreightDemandGenerationUtils - .getCoordOfMiddlePointOfLink(network.getLinks().get(thisShipment.getFrom())); + .getCoordOfMiddlePointOfLink(network.getLinks().get(thisShipment.getPickupLinkId())); Coord coordTo = FreightDemandGenerationUtils - .getCoordOfMiddlePointOfLink(network.getLinks().get(thisShipment.getTo())); + .getCoordOfMiddlePointOfLink(network.getLinks().get(thisShipment.getDeliveryLinkId())); writer.write(thisCarrier.getId().toString() + thisShipment.getId().toString() + " " + coordFrom.getX() + " " + coordFrom.getY() + " " + "Pickup" + " " - + thisShipment.getFrom().toString() + " " + thisShipment.getTo().toString() + "\n"); + + thisShipment.getPickupLinkId().toString() + " " + thisShipment.getDeliveryLinkId().toString() + "\n"); writer.write(thisCarrier.getId().toString() + thisShipment.getId() + " " + coordTo.getX() + " " + coordTo.getY() + " " + "Delivery" + " " - + thisShipment.getFrom() + " " + thisShipment.getTo() + "\n"); + + thisShipment.getPickupLinkId() + " " + thisShipment.getDeliveryLinkId() + "\n"); } } writer.flush(); diff --git a/contribs/application/src/test/java/org/matsim/freightDemandGeneration/DemandReaderFromCSVTest.java b/contribs/application/src/test/java/org/matsim/freightDemandGeneration/DemandReaderFromCSVTest.java index 9cd21c16d9d..32972385d8a 100644 --- a/contribs/application/src/test/java/org/matsim/freightDemandGeneration/DemandReaderFromCSVTest.java +++ b/contribs/application/src/test/java/org/matsim/freightDemandGeneration/DemandReaderFromCSVTest.java @@ -101,17 +101,17 @@ void demandCreationWithSampleWithChangeNumberOfLocations() throws IOException { locationsPerShipmentElement = new HashMap<>(); countDemand = 0; for (CarrierShipment shipment : testCarrier3.getShipments().values()) { - countShipmentsWithCertainDemand.merge((Integer) shipment.getSize(), 1, Integer::sum); - countDemand = countDemand + shipment.getSize(); - Assertions.assertEquals(5, shipment.getSize()); - Assertions.assertEquals(2000, shipment.getPickupServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(1250, shipment.getDeliveryServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(TimeWindow.newInstance(8000, 50000), shipment.getPickupTimeWindow()); - Assertions.assertEquals(TimeWindow.newInstance(10000, 60000), shipment.getDeliveryTimeWindow()); + countShipmentsWithCertainDemand.merge((Integer) shipment.getDemand(), 1, Integer::sum); + countDemand = countDemand + shipment.getDemand(); + Assertions.assertEquals(5, shipment.getDemand()); + Assertions.assertEquals(2000, shipment.getPickupDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(1250, shipment.getDeliveryDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(TimeWindow.newInstance(8000, 50000), shipment.getPickupStartsTimeWindow()); + Assertions.assertEquals(TimeWindow.newInstance(10000, 60000), shipment.getDeliveryStartsTimeWindow()); locationsPerShipmentElement.computeIfAbsent("ShipmentElement1_pickup", (k) -> new HashSet<>()) - .add(shipment.getFrom().toString()); + .add(shipment.getPickupLinkId().toString()); locationsPerShipmentElement.computeIfAbsent("ShipmentElement1_delivery", (k) -> new HashSet<>()) - .add(shipment.getTo().toString()); + .add(shipment.getDeliveryLinkId().toString()); } Assertions.assertEquals(20, countDemand); Assertions.assertEquals(4, countShipmentsWithCertainDemand.getInt(5)); @@ -168,17 +168,17 @@ void demandCreationWithSampleWithDemandOnLocation() throws IOException { locationsPerShipmentElement = new HashMap<>(); countDemand = 0; for (CarrierShipment shipment : testCarrier3.getShipments().values()) { - countShipmentsWithCertainDemand.merge((Integer) shipment.getSize(), 1, Integer::sum); - countDemand = countDemand + shipment.getSize(); - Assertions.assertEquals(10, shipment.getSize()); - Assertions.assertEquals(4000, shipment.getPickupServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(2500, shipment.getDeliveryServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(TimeWindow.newInstance(8000, 50000), shipment.getPickupTimeWindow()); - Assertions.assertEquals(TimeWindow.newInstance(10000, 60000), shipment.getDeliveryTimeWindow()); + countShipmentsWithCertainDemand.merge((Integer) shipment.getDemand(), 1, Integer::sum); + countDemand = countDemand + shipment.getDemand(); + Assertions.assertEquals(10, shipment.getDemand()); + Assertions.assertEquals(4000, shipment.getPickupDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(2500, shipment.getDeliveryDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(TimeWindow.newInstance(8000, 50000), shipment.getPickupStartsTimeWindow()); + Assertions.assertEquals(TimeWindow.newInstance(10000, 60000), shipment.getDeliveryStartsTimeWindow()); locationsPerShipmentElement.computeIfAbsent("ShipmentElement1_pickup", (k) -> new HashSet<>()) - .add(shipment.getFrom().toString()); + .add(shipment.getPickupLinkId().toString()); locationsPerShipmentElement.computeIfAbsent("ShipmentElement1_delivery", (k) -> new HashSet<>()) - .add(shipment.getTo().toString()); + .add(shipment.getDeliveryLinkId().toString()); } Assertions.assertEquals(20, countDemand); Assertions.assertEquals(2, countShipmentsWithCertainDemand.getInt(10)); @@ -235,17 +235,17 @@ void demandCreationWithSampleWithDemandOnLocationWithCombiningJobs() throws IOEx locationsPerShipmentElement = new HashMap<>(); countDemand = 0; for (CarrierShipment shipment : testCarrier3.getShipments().values()) { - countShipmentsWithCertainDemand.merge((Integer) shipment.getSize(), 1, Integer::sum); - countDemand = countDemand + shipment.getSize(); - Assertions.assertEquals(10, shipment.getSize()); - Assertions.assertEquals(4000, shipment.getPickupServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(2500, shipment.getDeliveryServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(TimeWindow.newInstance(8000, 50000), shipment.getPickupTimeWindow()); - Assertions.assertEquals(TimeWindow.newInstance(10000, 60000), shipment.getDeliveryTimeWindow()); + countShipmentsWithCertainDemand.merge((Integer) shipment.getDemand(), 1, Integer::sum); + countDemand = countDemand + shipment.getDemand(); + Assertions.assertEquals(10, shipment.getDemand()); + Assertions.assertEquals(4000, shipment.getPickupDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(2500, shipment.getDeliveryDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(TimeWindow.newInstance(8000, 50000), shipment.getPickupStartsTimeWindow()); + Assertions.assertEquals(TimeWindow.newInstance(10000, 60000), shipment.getDeliveryStartsTimeWindow()); locationsPerShipmentElement.computeIfAbsent("ShipmentElement1_pickup", (k) -> new HashSet<>()) - .add(shipment.getFrom().toString()); + .add(shipment.getPickupLinkId().toString()); locationsPerShipmentElement.computeIfAbsent("ShipmentElement1_delivery", (k) -> new HashSet<>()) - .add(shipment.getTo().toString()); + .add(shipment.getDeliveryLinkId().toString()); } Assertions.assertEquals(20, countDemand); Assertions.assertEquals(2, countShipmentsWithCertainDemand.getInt(10)); @@ -305,17 +305,17 @@ void demandCreationNoSampling() throws IOException { locationsPerShipmentElement = new HashMap<>(); countDemand = 0; for (CarrierShipment shipment : testCarrier3.getShipments().values()) { - countShipmentsWithCertainDemand.merge((Integer) shipment.getSize(), 1, Integer::sum); - countDemand = countDemand + shipment.getSize(); - Assertions.assertEquals(10, shipment.getSize()); - Assertions.assertEquals(4000, shipment.getPickupServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(2500, shipment.getDeliveryServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(TimeWindow.newInstance(8000, 50000), shipment.getPickupTimeWindow()); - Assertions.assertEquals(TimeWindow.newInstance(10000, 60000), shipment.getDeliveryTimeWindow()); + countShipmentsWithCertainDemand.merge((Integer) shipment.getDemand(), 1, Integer::sum); + countDemand = countDemand + shipment.getDemand(); + Assertions.assertEquals(10, shipment.getDemand()); + Assertions.assertEquals(4000, shipment.getPickupDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(2500, shipment.getDeliveryDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(TimeWindow.newInstance(8000, 50000), shipment.getPickupStartsTimeWindow()); + Assertions.assertEquals(TimeWindow.newInstance(10000, 60000), shipment.getDeliveryStartsTimeWindow()); locationsPerShipmentElement.computeIfAbsent("ShipmentElement1_pickup", (k) -> new HashSet<>()) - .add(shipment.getFrom().toString()); + .add(shipment.getPickupLinkId().toString()); locationsPerShipmentElement.computeIfAbsent("ShipmentElement1_delivery", (k) -> new HashSet<>()) - .add(shipment.getTo().toString()); + .add(shipment.getDeliveryLinkId().toString()); } Assertions.assertEquals(20, countDemand); Assertions.assertEquals(2, countShipmentsWithCertainDemand.getInt(10)); @@ -474,25 +474,27 @@ private static void checkCarrier1and2(Scenario scenario, Network network, ShpOpt Map> locationsPerServiceElement = new HashMap<>(); int countDemand = 0; for (CarrierService service : testCarrier1.getServices().values()) { - countServicesWithCertainDemand.merge((Integer) service.getCapacityDemand(), 1, Integer::sum); - countDemand = countDemand + service.getCapacityDemand(); - if (service.getCapacityDemand() == 0) { + countServicesWithCertainDemand.merge((Integer) service.getDemand(), 1, Integer::sum); + countDemand = countDemand + service.getDemand(); + if (service.getDemand() == 0) { Assertions.assertEquals(180, service.getServiceDuration(), MatsimTestUtils.EPSILON); Assertions.assertEquals(TimeWindow.newInstance(3000, 13000), service.getServiceStartTimeWindow()); locationsPerServiceElement.computeIfAbsent("serviceElement1", (k) -> new HashSet<>()) - .add(service.getLocationLinkId().toString()); - } else if (service.getCapacityDemand() == 1) { + .add(service.getServiceLinkId().toString()); + } else if (service.getDemand() == 1) { Assertions.assertEquals(100, service.getServiceDuration(), MatsimTestUtils.EPSILON); Assertions.assertEquals(TimeWindow.newInstance(5000, 20000), service.getServiceStartTimeWindow()); locationsPerServiceElement.computeIfAbsent("serviceElement2", (k) -> new HashSet<>()) - .add(service.getLocationLinkId().toString()); - } else if (service.getCapacityDemand() == 2) { - Assertions.assertEquals(200, service.getServiceDuration(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(TimeWindow.newInstance(5000, 20000), service.getServiceStartTimeWindow()); - locationsPerServiceElement.computeIfAbsent("serviceElement2", (k) -> new HashSet<>()) - .add(service.getLocationLinkId().toString()); - } else - Assertions.fail("Service has a wrong demand."); + .add(service.getServiceLinkId().toString()); + } else { + if (service.getDemand() == 2) { + Assertions.assertEquals(200, service.getServiceDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(TimeWindow.newInstance(5000, 20000), service.getServiceStartTimeWindow()); + locationsPerServiceElement.computeIfAbsent("serviceElement2", (k) -> new HashSet<>()) + .add(service.getServiceLinkId().toString()); + } else + Assertions.fail("Service has a wrong demand."); + } } Assertions.assertEquals(12, countDemand); Assertions.assertEquals(4, countServicesWithCertainDemand.getInt(0)); @@ -520,37 +522,39 @@ private static void checkCarrier1and2(Scenario scenario, Network network, ShpOpt Map> locationsPerShipmentElement = new HashMap<>(); countDemand = 0; for (CarrierShipment shipment : testCarrier2.getShipments().values()) { - countShipmentsWithCertainDemand.merge((Integer) shipment.getSize(), 1, Integer::sum); - countDemand = countDemand + shipment.getSize(); - if (shipment.getSize() == 0) { - Assertions.assertEquals(300, shipment.getPickupServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(350, shipment.getDeliveryServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(TimeWindow.newInstance(10000, 45000), shipment.getPickupTimeWindow()); - Assertions.assertEquals(TimeWindow.newInstance(11000, 44000), shipment.getDeliveryTimeWindow()); + countShipmentsWithCertainDemand.merge((Integer) shipment.getDemand(), 1, Integer::sum); + countDemand = countDemand + shipment.getDemand(); + if (shipment.getDemand() == 0) { + Assertions.assertEquals(300, shipment.getPickupDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(350, shipment.getDeliveryDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(TimeWindow.newInstance(10000, 45000), shipment.getPickupStartsTimeWindow()); + Assertions.assertEquals(TimeWindow.newInstance(11000, 44000), shipment.getDeliveryStartsTimeWindow()); locationsPerShipmentElement.computeIfAbsent("ShipmentElement1_pickup", (k) -> new HashSet<>()) - .add(shipment.getFrom().toString()); + .add(shipment.getPickupLinkId().toString()); locationsPerShipmentElement.computeIfAbsent("ShipmentElement1_delivery", (k) -> new HashSet<>()) - .add(shipment.getTo().toString()); - } else if (shipment.getSize() == 2) { - Assertions.assertEquals(400, shipment.getPickupServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(400, shipment.getDeliveryServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(TimeWindow.newInstance(11000, 44000), shipment.getPickupTimeWindow()); - Assertions.assertEquals(TimeWindow.newInstance(20000, 40000), shipment.getDeliveryTimeWindow()); + .add(shipment.getDeliveryLinkId().toString()); + } else if (shipment.getDemand() == 2) { + Assertions.assertEquals(400, shipment.getPickupDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(400, shipment.getDeliveryDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(TimeWindow.newInstance(11000, 44000), shipment.getPickupStartsTimeWindow()); + Assertions.assertEquals(TimeWindow.newInstance(20000, 40000), shipment.getDeliveryStartsTimeWindow()); locationsPerShipmentElement.computeIfAbsent("ShipmentElement2_pickup", (k) -> new HashSet<>()) - .add(shipment.getFrom().toString()); + .add(shipment.getPickupLinkId().toString()); locationsPerShipmentElement.computeIfAbsent("ShipmentElement2_delivery", (k) -> new HashSet<>()) - .add(shipment.getTo().toString()); - } else if (shipment.getSize() == 3) { - Assertions.assertEquals(600, shipment.getPickupServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(600, shipment.getDeliveryServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(TimeWindow.newInstance(11000, 44000), shipment.getPickupTimeWindow()); - Assertions.assertEquals(TimeWindow.newInstance(20000, 40000), shipment.getDeliveryTimeWindow()); - locationsPerShipmentElement.computeIfAbsent("ShipmentElement2_pickup", (k) -> new HashSet<>()) - .add(shipment.getFrom().toString()); - locationsPerShipmentElement.computeIfAbsent("ShipmentElement2_delivery", (k) -> new HashSet<>()) - .add(shipment.getTo().toString()); - } else - Assertions.fail("Shipment has an unexpected demand."); + .add(shipment.getDeliveryLinkId().toString()); + } else { + if (shipment.getDemand() == 3) { + Assertions.assertEquals(600, shipment.getPickupDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(600, shipment.getDeliveryDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(TimeWindow.newInstance(11000, 44000), shipment.getPickupStartsTimeWindow()); + Assertions.assertEquals(TimeWindow.newInstance(20000, 40000), shipment.getDeliveryStartsTimeWindow()); + locationsPerShipmentElement.computeIfAbsent("ShipmentElement2_pickup", (k) -> new HashSet<>()) + .add(shipment.getPickupLinkId().toString()); + locationsPerShipmentElement.computeIfAbsent("ShipmentElement2_delivery", (k) -> new HashSet<>()) + .add(shipment.getDeliveryLinkId().toString()); + } else + Assertions.fail("Shipment has an unexpected demand."); + } } Assertions.assertEquals(15, countDemand); Assertions.assertEquals(4, countShipmentsWithCertainDemand.getInt(0)); @@ -579,18 +583,18 @@ private static void checkCarrier1and2WithCombiningJobs(Scenario scenario, Networ Map> locationsPerServiceElement = new HashMap<>(); int countDemand = 0; for (CarrierService service : testCarrier1.getServices().values()) { - countServicesWithCertainDemand.merge((Integer) service.getCapacityDemand(), 1, Integer::sum); - countDemand = countDemand + service.getCapacityDemand(); - if (service.getCapacityDemand() == 0) { + countServicesWithCertainDemand.merge((Integer) service.getDemand(), 1, Integer::sum); + countDemand = countDemand + service.getDemand(); + if (service.getDemand() == 0) { Assertions.assertEquals(180, service.getServiceDuration(), MatsimTestUtils.EPSILON); Assertions.assertEquals(TimeWindow.newInstance(3000, 13000), service.getServiceStartTimeWindow()); locationsPerServiceElement.computeIfAbsent("serviceElement1", (k) -> new HashSet<>()) - .add(service.getLocationLinkId().toString()); + .add(service.getServiceLinkId().toString()); } else { - Assertions.assertEquals(service.getCapacityDemand() * 100, service.getServiceDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(service.getDemand() * 100, service.getServiceDuration(), MatsimTestUtils.EPSILON); Assertions.assertEquals(TimeWindow.newInstance(5000, 20000), service.getServiceStartTimeWindow()); locationsPerServiceElement.computeIfAbsent("serviceElement2", (k) -> new HashSet<>()) - .add(service.getLocationLinkId().toString()); + .add(service.getServiceLinkId().toString()); } } Assertions.assertEquals(12, countDemand); @@ -617,26 +621,26 @@ private static void checkCarrier1and2WithCombiningJobs(Scenario scenario, Networ Map> locationsPerShipmentElement = new HashMap<>(); countDemand = 0; for (CarrierShipment shipment : testCarrier2.getShipments().values()) { - countShipmentsWithCertainDemand.merge((Integer) shipment.getSize(), 1, Integer::sum); - countDemand = countDemand + shipment.getSize(); - if (shipment.getSize() == 0) { - Assertions.assertEquals(300, shipment.getPickupServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(350, shipment.getDeliveryServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(TimeWindow.newInstance(10000, 45000), shipment.getPickupTimeWindow()); - Assertions.assertEquals(TimeWindow.newInstance(11000, 44000), shipment.getDeliveryTimeWindow()); + countShipmentsWithCertainDemand.merge((Integer) shipment.getDemand(), 1, Integer::sum); + countDemand = countDemand + shipment.getDemand(); + if (shipment.getDemand() == 0) { + Assertions.assertEquals(300, shipment.getPickupDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(350, shipment.getDeliveryDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(TimeWindow.newInstance(10000, 45000), shipment.getPickupStartsTimeWindow()); + Assertions.assertEquals(TimeWindow.newInstance(11000, 44000), shipment.getDeliveryStartsTimeWindow()); locationsPerShipmentElement.computeIfAbsent("ShipmentElement1_pickup", (k) -> new HashSet<>()) - .add(shipment.getFrom().toString()); + .add(shipment.getPickupLinkId().toString()); locationsPerShipmentElement.computeIfAbsent("ShipmentElement1_delivery", (k) -> new HashSet<>()) - .add(shipment.getTo().toString()); + .add(shipment.getDeliveryLinkId().toString()); } else { - Assertions.assertEquals(shipment.getSize() * 200, shipment.getPickupServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(shipment.getSize() * 200, shipment.getDeliveryServiceTime(), MatsimTestUtils.EPSILON); - Assertions.assertEquals(TimeWindow.newInstance(11000, 44000), shipment.getPickupTimeWindow()); - Assertions.assertEquals(TimeWindow.newInstance(20000, 40000), shipment.getDeliveryTimeWindow()); + Assertions.assertEquals(shipment.getDemand() * 200, shipment.getPickupDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(shipment.getDemand() * 200, shipment.getDeliveryDuration(), MatsimTestUtils.EPSILON); + Assertions.assertEquals(TimeWindow.newInstance(11000, 44000), shipment.getPickupStartsTimeWindow()); + Assertions.assertEquals(TimeWindow.newInstance(20000, 40000), shipment.getDeliveryStartsTimeWindow()); locationsPerShipmentElement.computeIfAbsent("ShipmentElement2_pickup", (k) -> new HashSet<>()) - .add(shipment.getFrom().toString()); + .add(shipment.getPickupLinkId().toString()); locationsPerShipmentElement.computeIfAbsent("ShipmentElement2_delivery", (k) -> new HashSet<>()) - .add(shipment.getTo().toString()); + .add(shipment.getDeliveryLinkId().toString()); } } Assertions.assertEquals(15, countDemand); diff --git a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/DefaultCommercialJobGenerator.java b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/DefaultCommercialJobGenerator.java index 3327f46292c..2891b802294 100644 --- a/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/DefaultCommercialJobGenerator.java +++ b/contribs/commercialTrafficApplications/src/main/java/org/matsim/contrib/commercialTrafficApplications/jointDemand/DefaultCommercialJobGenerator.java @@ -329,7 +329,7 @@ public void generateIterationServices(Carriers carriers, Population population) double latestStart = Double.parseDouble(commercialJobProperties.get(COMMERCIALJOB_ATTRIBUTE_END_IDX)); CarrierService.Builder serviceBuilder = CarrierService.Builder.newInstance(serviceId, PopulationUtils.decideOnLinkIdForActivity(activity,scenario)); - serviceBuilder.setCapacityDemand(Integer.parseInt(commercialJobProperties.get(COMMERCIALJOB_ATTRIBUTE_AMOUNT_IDX))); + serviceBuilder.setDemand(Integer.parseInt(commercialJobProperties.get(COMMERCIALJOB_ATTRIBUTE_AMOUNT_IDX))); serviceBuilder.setServiceDuration(Double.parseDouble(commercialJobProperties.get(COMMERCIALJOB_ATTRIBUTE_DURATION_IDX))); serviceBuilder.setServiceStartTimeWindow(TimeWindow.newInstance(earliestStart,latestStart)); diff --git a/contribs/dvrp/src/main/java/org/matsim/contrib/dynagent/DynAgent.java b/contribs/dvrp/src/main/java/org/matsim/contrib/dynagent/DynAgent.java index 8915326d992..d7c15d7552f 100644 --- a/contribs/dvrp/src/main/java/org/matsim/contrib/dynagent/DynAgent.java +++ b/contribs/dvrp/src/main/java/org/matsim/contrib/dynagent/DynAgent.java @@ -19,8 +19,6 @@ package org.matsim.contrib.dynagent; -import java.util.List; - import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.ActivityEndEvent; import org.matsim.api.core.v01.events.ActivityStartEvent; @@ -40,6 +38,8 @@ import org.matsim.pt.transitSchedule.api.TransitStopFacility; import org.matsim.vehicles.Vehicle; +import java.util.List; + public final class DynAgent implements MobsimDriverPassengerAgent { private final DynAgentLogic agentLogic; @@ -83,11 +83,11 @@ private void computeNextAction(DynAction oldDynAction, double now) { DynAction nextDynAction = agentLogic.computeNextAction(oldDynAction, now); if (nextDynAction instanceof DynActivity) { - dynActivity = (DynActivity)nextDynAction; + dynActivity = (DynActivity) nextDynAction; state = MobsimAgent.State.ACTIVITY; events.processEvent(new ActivityStartEvent(now, id, currentLinkId, null, dynActivity.getActivityType())); } else { - dynLeg = (DynLeg)nextDynAction; + dynLeg = (DynLeg) nextDynAction; state = MobsimAgent.State.LEG; } } @@ -145,7 +145,7 @@ public String getMode() { // VehicleUsingAgent @Override public final Id getPlannedVehicleId() { - Id vehId = ((DriverDynLeg)dynLeg).getPlannedVehicleId(); + Id vehId = ((DriverDynLeg) dynLeg).getPlannedVehicleId(); // according to BasicPlanAgentImpl return vehId != null ? vehId : Id.create(id, Vehicle.class); } @@ -177,13 +177,13 @@ public Id getDestinationLinkId() { // DriverAgent @Override public Id chooseNextLinkId() { - return ((DriverDynLeg)dynLeg).getNextLinkId(); + return ((DriverDynLeg) dynLeg).getNextLinkId(); } // DriverAgent @Override public void notifyMoveOverNode(Id newLinkId) { - ((DriverDynLeg)dynLeg).movedOverNode(newLinkId); + ((DriverDynLeg) dynLeg).movedOverNode(newLinkId); currentLinkId = newLinkId; } @@ -226,26 +226,28 @@ public boolean isWantingToArriveOnCurrentLink() { // PTPassengerAgent @Override public boolean getEnterTransitRoute(TransitLine line, TransitRoute transitRoute, List stopsToCome, - TransitVehicle transitVehicle) { - return ((PTPassengerDynLeg)dynLeg).getEnterTransitRoute(line, transitRoute, stopsToCome, transitVehicle); + TransitVehicle transitVehicle) { + return ((PTPassengerDynLeg) dynLeg).getEnterTransitRoute(line, transitRoute, stopsToCome, transitVehicle); } // PTPassengerAgent + // yyyy seems a bit odd, that this and the following methods are implemented for DynAgent as not every DynAgent is a PTPassengerAgent. paul, + // nov'24 @Override public boolean getExitAtStop(TransitStopFacility stop) { - return ((PTPassengerDynLeg)dynLeg).getExitAtStop(stop); + return ((PTPassengerDynLeg) dynLeg).getExitAtStop(stop); } // PTPassengerAgent @Override public Id getDesiredAccessStopId() { - return ((PTPassengerDynLeg)dynLeg).getDesiredAccessStopId(); + return ((PTPassengerDynLeg) dynLeg).getDesiredAccessStopId(); } // PTPassengerAgent @Override public Id getDesiredDestinationStopId() { - return ((PTPassengerDynLeg)dynLeg).getDesiredDestinationStopId(); + return ((PTPassengerDynLeg) dynLeg).getDesiredDestinationStopId(); } // PTPassengerAgent diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/ChargingModule.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/ChargingModule.java index 430484e4943..1f81bac495c 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/ChargingModule.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/ChargingModule.java @@ -54,15 +54,18 @@ public void install() { // this.addMobsimListenerBinding().to( ChargingHandler.class ).in( Singleton.class ); // does not work since ChargingInfrastructure is not available. + + // standard charging priority for all chargers + bind(ChargingPriority.Factory.class).toInstance(ChargingPriority.FIFO); } @Provides @Singleton - ChargingWithQueueingLogic.Factory provideChargingWithQueueingLogicFactory(EventsManager eventsManager) { - return new ChargingWithQueueingLogic.Factory(eventsManager); + ChargingWithQueueingLogic.Factory provideChargingWithQueueingLogicFactory(EventsManager eventsManager, ChargingPriority.Factory chargingPriorityFactory) { + return new ChargingWithQueueingLogic.Factory(eventsManager, chargingPriorityFactory); } @Provides @Singleton - ChargingWithQueueingAndAssignmentLogic.Factory provideChargingWithQueueingAndAssignmentLogicFactory(EventsManager eventsManager) { - return new ChargingWithQueueingAndAssignmentLogic.Factory(eventsManager); + ChargingWithQueueingAndAssignmentLogic.Factory provideChargingWithQueueingAndAssignmentLogicFactory(EventsManager eventsManager, ChargingPriority.Factory chargingPriorityFactory) { + return new ChargingWithQueueingAndAssignmentLogic.Factory(eventsManager, chargingPriorityFactory); } } diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/ChargingPriority.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/ChargingPriority.java new file mode 100644 index 00000000000..83087a37f79 --- /dev/null +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/ChargingPriority.java @@ -0,0 +1,29 @@ +package org.matsim.contrib.ev.charging; + +import org.matsim.contrib.ev.charging.ChargingLogic.ChargingVehicle; +import org.matsim.contrib.ev.infrastructure.ChargerSpecification; + +/** + * This interface is supposed to decide if a vehicle can be plugged right now or + * if it needs to go to / remain in the queue. While the condition whether + * enough of empty plugs are available is *always* checked, the presented method + * allows to define a more complex logic beyond that. + * + * @author Sebastian Hörl (sebhoerl), IRT SystemX + */ +public interface ChargingPriority { + /** + * The vehicle can start charging if the method returns true, otherwise it stays + * in the queue. + */ + boolean requestPlugNext(ChargingVehicle cv, double now); + + public interface Factory { + ChargingPriority create(ChargerSpecification charger); + } + + /** + * The default charging priority: first-in first-out. + */ + static public final Factory FIFO = charger -> (ev, now) -> true; +} \ No newline at end of file diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/ChargingWithQueueingAndAssignmentLogic.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/ChargingWithQueueingAndAssignmentLogic.java index a21fde69f40..1a0aa853af0 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/ChargingWithQueueingAndAssignmentLogic.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/ChargingWithQueueingAndAssignmentLogic.java @@ -34,8 +34,8 @@ public class ChargingWithQueueingAndAssignmentLogic extends ChargingWithQueueing implements ChargingWithAssignmentLogic { private final Map, ChargingVehicle> assignedVehicles = new LinkedHashMap<>(); - public ChargingWithQueueingAndAssignmentLogic(ChargerSpecification charger, EventsManager eventsManager) { - super(charger, eventsManager); + public ChargingWithQueueingAndAssignmentLogic(ChargerSpecification charger, EventsManager eventsManager, ChargingPriority priority) { + super(charger, eventsManager, priority); } @Override @@ -68,14 +68,16 @@ public Collection getAssignedVehicles() { static public class Factory implements ChargingLogic.Factory { private final EventsManager eventsManager; + private final ChargingPriority.Factory priorityFactory; - public Factory(EventsManager eventsManager) { + public Factory(EventsManager eventsManager, ChargingPriority.Factory priorityFactory) { this.eventsManager = eventsManager; + this.priorityFactory = priorityFactory; } @Override public ChargingLogic create(ChargerSpecification charger) { - return new ChargingWithQueueingAndAssignmentLogic(charger, eventsManager); + return new ChargingWithQueueingAndAssignmentLogic(charger, eventsManager, priorityFactory.create(charger)); } } } diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/ChargingWithQueueingLogic.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/ChargingWithQueueingLogic.java index 515a586a4c2..0e0de973ffe 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/ChargingWithQueueingLogic.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/ChargingWithQueueingLogic.java @@ -40,15 +40,17 @@ public class ChargingWithQueueingLogic implements ChargingLogic { protected final ChargerSpecification charger; private final EventsManager eventsManager; + private final ChargingPriority priority; private final Map, ChargingVehicle> pluggedVehicles = new LinkedHashMap<>(); private final Queue queuedVehicles = new LinkedList<>(); private final Queue arrivingVehicles = new LinkedBlockingQueue<>(); private final Map, ChargingListener> listeners = new LinkedHashMap<>(); - public ChargingWithQueueingLogic(ChargerSpecification charger, EventsManager eventsManager) { + public ChargingWithQueueingLogic(ChargerSpecification charger, EventsManager eventsManager, ChargingPriority priority) { this.charger = Objects.requireNonNull(charger); this.eventsManager = Objects.requireNonNull(eventsManager); + this.priority = priority; } @Override @@ -71,21 +73,22 @@ public void chargeVehicles(double chargePeriod, double now) { } } - int queuedToPluggedCount = Math.min(queuedVehicles.size(), charger.getPlugCount() - pluggedVehicles.size()); - for (int i = 0; i < queuedToPluggedCount; i++) { - plugVehicle(queuedVehicles.poll(), now); + var queuedVehiclesIter = queuedVehicles.iterator(); + while (queuedVehiclesIter.hasNext() && pluggedVehicles.size() < charger.getPlugCount()) { + var cv = queuedVehiclesIter.next(); + if (plugVehicle(cv, now)) { + queuedVehiclesIter.remove(); + } } var arrivingVehiclesIter = arrivingVehicles.iterator(); while (arrivingVehiclesIter.hasNext()) { var cv = arrivingVehiclesIter.next(); - if (pluggedVehicles.size() < charger.getPlugCount()) { - plugVehicle(cv, now); - } else { + if (pluggedVehicles.size() >= charger.getPlugCount() || !plugVehicle(cv, now)) { queueVehicle(cv, now); } - arrivingVehiclesIter.remove(); } + arrivingVehicles.clear(); } @Override @@ -106,14 +109,28 @@ public void removeVehicle(ElectricVehicle ev, double now) { eventsManager.processEvent(new ChargingEndEvent(now, charger.getId(), ev.getId(), ev.getBattery().getCharge())); listeners.remove(ev.getId()).notifyChargingEnded(ev, now); - if (!queuedVehicles.isEmpty()) { - plugVehicle(queuedVehicles.poll(), now); + var queuedVehiclesIter = queuedVehicles.iterator(); + while (queuedVehiclesIter.hasNext()) { + var queuedVehicle = queuedVehiclesIter.next(); + if (plugVehicle(queuedVehicle, now)) { + queuedVehiclesIter.remove(); + break; + } } } else { - // make sure ev was in the queue - Preconditions.checkState(queuedVehicles.remove(ev), "Vehicle (%s) is neither queued nor plugged at charger (%s)", ev.getId(), - charger.getId()); - eventsManager.processEvent(new QuitQueueAtChargerEvent(now, charger.getId(), ev.getId())); + var queuedVehiclesIter = queuedVehicles.iterator(); + while (queuedVehiclesIter.hasNext()) { + var queuedVehicle = queuedVehiclesIter.next(); + + if (queuedVehicle.ev() == ev) { + queuedVehiclesIter.remove(); + eventsManager.processEvent(new QuitQueueAtChargerEvent(now, charger.getId(), ev.getId())); + return; // found the vehicle + } + } + + throw new IllegalStateException(String.format("Vehicle (%s) is neither queued nor plugged at charger (%s)", ev.getId(), + charger.getId())); } } @@ -123,12 +140,20 @@ private void queueVehicle(ChargingVehicle cv, double now) { listeners.get(cv.ev().getId()).notifyVehicleQueued(cv.ev(), now); } - private void plugVehicle(ChargingVehicle cv, double now) { + private boolean plugVehicle(ChargingVehicle cv, double now) { + assert pluggedVehicles.size() < charger.getPlugCount(); + + if (!priority.requestPlugNext(cv, now)) { + return false; + } + if (pluggedVehicles.put(cv.ev().getId(), cv) != null) { throw new IllegalArgumentException(); } eventsManager.processEvent(new ChargingStartEvent(now, charger.getId(), cv.ev().getId(), cv.ev().getBattery().getCharge())); listeners.get(cv.ev().getId()).notifyChargingStarted(cv.ev(), now); + + return true; } private final Collection unmodifiablePluggedVehicles = Collections.unmodifiableCollection(pluggedVehicles.values()); @@ -147,14 +172,16 @@ public Collection getQueuedVehicles() { static public class Factory implements ChargingLogic.Factory { private final EventsManager eventsManager; + private final ChargingPriority.Factory chargingPriorityFactory; - public Factory(EventsManager eventsManager) { + public Factory(EventsManager eventsManager, ChargingPriority.Factory chargingPriorityFactory) { this.eventsManager = eventsManager; + this.chargingPriorityFactory = chargingPriorityFactory; } @Override public ChargingLogic create(ChargerSpecification charger) { - return new ChargingWithQueueingLogic(charger, eventsManager); + return new ChargingWithQueueingLogic(charger, eventsManager, chargingPriorityFactory.create(charger)); } } } diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleetSpecificationDefaultImpl.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleetSpecificationDefaultImpl.java index b24583feb13..6b9b30e8cfd 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleetSpecificationDefaultImpl.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricFleetSpecificationDefaultImpl.java @@ -30,7 +30,7 @@ /** * @author Michal Maciejewski (michalm) */ -final class ElectricFleetSpecificationDefaultImpl implements ElectricFleetSpecification { +public final class ElectricFleetSpecificationDefaultImpl implements ElectricFleetSpecification { private final Map, ElectricVehicleSpecification> specifications = new LinkedHashMap<>(); @Override diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleSpecificationDefaultImpl.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleSpecificationDefaultImpl.java index ef18ae6cce6..e3a4caca03e 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleSpecificationDefaultImpl.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/fleet/ElectricVehicleSpecificationDefaultImpl.java @@ -33,7 +33,7 @@ /** * @author Michal Maciejewski (michalm) */ -final class ElectricVehicleSpecificationDefaultImpl implements ElectricVehicleSpecification { +public final class ElectricVehicleSpecificationDefaultImpl implements ElectricVehicleSpecification { private final Vehicle matsimVehicle; diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructureSpecificationDefaultImpl.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructureSpecificationDefaultImpl.java index 48a27563616..763a2cd70e1 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructureSpecificationDefaultImpl.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/infrastructure/ChargingInfrastructureSpecificationDefaultImpl.java @@ -28,7 +28,7 @@ /** * @author Michal Maciejewski (michalm) */ -final class ChargingInfrastructureSpecificationDefaultImpl implements ChargingInfrastructureSpecification { +public final class ChargingInfrastructureSpecificationDefaultImpl implements ChargingInfrastructureSpecification { private final SpecificationContainer container = new SpecificationContainer<>(); @Override diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/reservation/ChargerReservationManager.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/reservation/ChargerReservationManager.java new file mode 100644 index 00000000000..6e6fa1e77c9 --- /dev/null +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/reservation/ChargerReservationManager.java @@ -0,0 +1,106 @@ +package org.matsim.contrib.ev.reservation; + +import java.util.LinkedList; +import java.util.List; + +import org.matsim.api.core.v01.IdMap; +import org.matsim.contrib.ev.fleet.ElectricVehicle; +import org.matsim.contrib.ev.infrastructure.Charger; +import org.matsim.contrib.ev.infrastructure.ChargerSpecification; +import org.matsim.core.controler.events.IterationStartsEvent; +import org.matsim.core.controler.listener.IterationStartsListener; + +/** + * This class is a singleton service that keeps a list of reservations for + * chargers. It can be used in combination with the + * ReservationBasedChargingPriority to let vehicle pass on to charging only if + * they have a proper reservation. + * + * @author Sebastian Hörl (sebhoerl), IRT SystemX + */ +public class ChargerReservationManager implements IterationStartsListener { + private final IdMap> reservations = new IdMap<>(Charger.class); + + public boolean isAvailable(ChargerSpecification charger, ElectricVehicle vehicle, double startTile, + double endTime) { + if (charger.getPlugCount() == 0) { + return false; + } + + if (!reservations.containsKey(charger.getId())) { + return true; + } + + int remaining = charger.getPlugCount(); + for (Reservation reservation : reservations.get(charger.getId())) { + if (reservation.vehicle != vehicle && isOverlapping(reservation, startTile, endTime)) { + remaining--; + } + } + + return remaining > 0; + } + + private boolean isOverlapping(Reservation reservation, double startTime, double endTime) { + if (startTime >= reservation.startTime && startTime <= reservation.endTime) { + return true; // start time within existing range + } else if (endTime >= reservation.startTime && endTime <= reservation.endTime) { + return true; // end time within existing range + } else if (startTime <= reservation.startTime && endTime >= reservation.endTime) { + return true; // new range covers existing range + } else { + return false; + } + } + + public Reservation addReservation(ChargerSpecification charger, ElectricVehicle vehicle, double startTime, + double endTime) { + if (isAvailable(charger, vehicle, startTime, endTime)) { + List chargerReservations = reservations.get(charger.getId()); + + if (chargerReservations == null) { + chargerReservations = new LinkedList<>(); + reservations.put(charger.getId(), chargerReservations); + } + + Reservation reservation = new Reservation(charger, vehicle, startTime, endTime); + chargerReservations.add(reservation); + + return reservation; + } + + return null; + } + + public boolean removeReservation(Reservation reservation) { + List chargerReservations = reservations.get(reservation.charger.getId()); + + if (chargerReservations != null) { + return chargerReservations.remove(reservation); + } + + return false; + } + + public Reservation findReservation(ChargerSpecification charger, ElectricVehicle vehicle, double now) { + List chargerReservations = reservations.get(charger.getId()); + + if (chargerReservations != null) { + for (Reservation reservation : chargerReservations) { + if (reservation.vehicle == vehicle && now >= reservation.startTime && now <= reservation.endTime) { + return reservation; + } + } + } + + return null; + } + + public record Reservation(ChargerSpecification charger, ElectricVehicle vehicle, double startTime, double endTime) { + } + + @Override + public void notifyIterationStarts(IterationStartsEvent event) { + reservations.clear(); + } +} \ No newline at end of file diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/reservation/ChargerReservationModule.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/reservation/ChargerReservationModule.java new file mode 100644 index 00000000000..9a17f208055 --- /dev/null +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/reservation/ChargerReservationModule.java @@ -0,0 +1,35 @@ +package org.matsim.contrib.ev.reservation; + +import org.matsim.contrib.ev.charging.ChargingPriority; +import org.matsim.core.controler.AbstractModule; + +import com.google.inject.Provides; +import com.google.inject.Singleton; + +/** + * This module enables the reservation-based charging logic that requires + * vehicles to have or make a reservation when attempting to charge at a + * charger. + * + * @author Sebastian Hörl (sebhoerl), IRT SystemX + */ +public class ChargerReservationModule extends AbstractModule { + @Override + public void install() { + addControlerListenerBinding().to(ChargerReservationManager.class); + bind(ChargingPriority.Factory.class).to(ReservationBasedChargingPriority.Factory.class); + } + + @Provides + @Singleton + ReservationBasedChargingPriority.Factory provideReservationBasedChargingPriorityFactory( + ChargerReservationManager reservationManager) { + return new ReservationBasedChargingPriority.Factory(reservationManager); + } + + @Provides + @Singleton + ChargerReservationManager provideChargerReservationManager() { + return new ChargerReservationManager(); + } +} \ No newline at end of file diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/reservation/ReservationBasedChargingPriority.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/reservation/ReservationBasedChargingPriority.java new file mode 100644 index 00000000000..8ac5a79a8ad --- /dev/null +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/reservation/ReservationBasedChargingPriority.java @@ -0,0 +1,64 @@ +package org.matsim.contrib.ev.reservation; + +import org.matsim.contrib.ev.charging.ChargingLogic.ChargingVehicle; +import org.matsim.contrib.ev.charging.ChargingPriority; +import org.matsim.contrib.ev.infrastructure.ChargerSpecification; +import org.matsim.contrib.ev.reservation.ChargerReservationManager.Reservation; + +/** + * This is an implementation of a charging priority which is backed by the + * ReservationManager: When a vehicle arrives, it is checked whether a + * reservation for this vehicle exists for the respective charger and the + * current time. In that case, the vehicle can be plugged if it is on top of the + * queue. If not, the ChargingPriority will try to make a reservation and if it + * is successful, the vehicle can start charging. In all other cases, the + * vehicle will stay in the queue until it is removed manually or a successful + * reservation can be made at a future time. + * + * @author Sebastian Hörl (sebhoerl), IRT SystemX + */ +public class ReservationBasedChargingPriority implements ChargingPriority { + private final ChargerReservationManager manager; + private final ChargerSpecification charger; + + public ReservationBasedChargingPriority(ChargerReservationManager manager, ChargerSpecification charger) { + this.charger = charger; + this.manager = manager; + } + + @Override + public boolean requestPlugNext(ChargingVehicle cv, double now) { + Reservation reservation = manager.findReservation(charger, cv.ev(), now); + + if (reservation != null) { + // vehicle has a reservation, can be plugged right away, consume reservation + manager.removeReservation(reservation); + return true; + } + + double endTime = cv.strategy().calcRemainingTimeToCharge() + now; + reservation = manager.addReservation(charger, cv.ev(), now, endTime); + + if (reservation != null) { + // vehicle did not have a reservation, but managed to create one on the fly, + // consume it directly + manager.removeReservation(reservation); + return true; + } + + return false; + } + + static public class Factory implements ChargingPriority.Factory { + private final ChargerReservationManager reservationManager; + + public Factory(ChargerReservationManager reservationManager) { + this.reservationManager = reservationManager; + } + + @Override + public ChargingPriority create(ChargerSpecification charger) { + return new ReservationBasedChargingPriority(reservationManager, charger); + } + } +} \ No newline at end of file diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/ChargingProceduresCSVWriter.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/ChargingProceduresCSVWriter.java index ae1c9d0c013..4cef65da81b 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/ChargingProceduresCSVWriter.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/stats/ChargingProceduresCSVWriter.java @@ -83,8 +83,12 @@ private void proccessChargingEventSequences(CSVPrinter csvPrinter, Collection() { - @Inject - private ChargerPowerTimeProfileCalculator calculator; - @Inject - private MatsimServices matsimServices; + }); + bind(ChargerPowerTimeProfileCalculator.class).asEagerSingleton(); + addEventHandlerBinding().to(ChargerPowerTimeProfileCalculator.class); + addControlerListenerBinding().toProvider(new Provider<>() { + @Inject + private ChargerPowerTimeProfileCalculator calculator; + @Inject + private MatsimServices matsimServices; - @Override - public ControlerListener get() { - var profileView = new ChargerPowerTimeProfileView(calculator); - return new ProfileWriter(matsimServices,"ev",profileView,"charger_power_time_profiles"); + @Override + public ControlerListener get() { + var profileView = new ChargerPowerTimeProfileView(calculator); + return new ProfileWriter(matsimServices, "ev", profileView, "charger_power_time_profiles"); - } - }); + } + }); + } } } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierJob.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierJob.java index 1dc1cd32f8d..926c5ae379f 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierJob.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierJob.java @@ -1,5 +1,6 @@ package org.matsim.freight.carriers; +import org.matsim.api.core.v01.Id; import org.matsim.utils.objectattributes.attributable.Attributable; /** @@ -16,4 +17,7 @@ * future) It maybe gets generalized in way, that we only have one job definition with 1 or 2 * location(s). This then defines, if jsprit takes the job as a service or as a shipment. */ -public interface CarrierJob extends Attributable {} +public interface CarrierJob extends Attributable { + Id getId(); + int getDemand(); +} diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanReaderV1.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanReaderV1.java index 4bb90047d86..c22b5928899 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanReaderV1.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanReaderV1.java @@ -116,19 +116,19 @@ public void startTag(String name, Attributes attributes, Stack context) CarrierShipment.Builder shipmentBuilder = CarrierShipment.Builder.newInstance( Id.create( id, CarrierShipment.class ), Id.create( from, Link.class ), Id.create( to, Link.class ), size ); if( startPickup == null ){ - shipmentBuilder.setPickupTimeWindow( TimeWindow.newInstance( 0.0, Integer.MAX_VALUE ) ).setDeliveryTimeWindow( + shipmentBuilder.setPickupStartsTimeWindow( TimeWindow.newInstance( 0.0, Integer.MAX_VALUE ) ).setDeliveryStartsTimeWindow( TimeWindow.newInstance( 0.0, Integer.MAX_VALUE ) ); } else{ - shipmentBuilder.setPickupTimeWindow( TimeWindow.newInstance( getDouble( startPickup ), getDouble( endPickup ) ) ). - setDeliveryTimeWindow( + shipmentBuilder.setPickupStartsTimeWindow( TimeWindow.newInstance( getDouble( startPickup ), getDouble( endPickup ) ) ). + setDeliveryStartsTimeWindow( TimeWindow.newInstance( getDouble( startDelivery ), getDouble( endDelivery ) ) ); } - if( pickupServiceTime != null ) shipmentBuilder.setPickupServiceTime( getDouble( pickupServiceTime ) ); - if( deliveryServiceTime != null ) shipmentBuilder.setDeliveryServiceTime( getDouble( deliveryServiceTime ) ); + if( pickupServiceTime != null ) shipmentBuilder.setPickupDuration( getDouble( pickupServiceTime ) ); + if( deliveryServiceTime != null ) shipmentBuilder.setDeliveryDuration( getDouble( deliveryServiceTime ) ); CarrierShipment shipment = shipmentBuilder.build(); currentShipments.put( attributes.getValue( ID ), shipment ); CarriersUtils.addShipment(currentCarrier, shipment); @@ -208,16 +208,16 @@ public void startTag(String name, Attributes attributes, Stack context) case "pickup" -> { String id = attributes.getValue(SHIPMENT_ID); CarrierShipment s = currentShipments.get(id); - finishLeg(s.getFrom()); + finishLeg(s.getPickupLinkId()); currentTourBuilder.schedulePickup(s); - previousActLoc = s.getFrom(); + previousActLoc = s.getPickupLinkId(); } case "delivery" -> { String id = attributes.getValue(SHIPMENT_ID); CarrierShipment s = currentShipments.get(id); - finishLeg(s.getTo()); + finishLeg(s.getDeliveryLinkId()); currentTourBuilder.scheduleDelivery(s); - previousActLoc = s.getTo(); + previousActLoc = s.getDeliveryLinkId(); } case "end" -> { finishLeg(currentVehicle.getLinkId()); 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 271871b0970..7bbc83c9479 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 @@ -117,7 +117,7 @@ public void startTag(String name, Attributes atts, Stack context) { Id to = Id.create(toLocation, Link.class); CarrierService.Builder serviceBuilder = CarrierService.Builder.newInstance(id, to); String capDemandString = atts.getValue("capacityDemand"); - if (capDemandString != null) serviceBuilder.setCapacityDemand(getInt(capDemandString)); + if (capDemandString != null) serviceBuilder.setDemand(getInt(capDemandString)); String startString = atts.getValue("earliestStart"); double start = parseTimeToDouble(startString); double end; @@ -157,13 +157,13 @@ public void startTag(String name, Attributes atts, Stack context) { String deliveryServiceTime = atts.getValue("deliveryServiceTime"); if (startPickup != null && endPickup != null) - shipmentBuilder.setPickupTimeWindow(TimeWindow.newInstance(parseTimeToDouble(startPickup), parseTimeToDouble(endPickup))); + shipmentBuilder.setPickupStartsTimeWindow(TimeWindow.newInstance(parseTimeToDouble(startPickup), parseTimeToDouble(endPickup))); if (startDelivery != null && endDelivery != null) - shipmentBuilder.setDeliveryTimeWindow(TimeWindow.newInstance(parseTimeToDouble(startDelivery), parseTimeToDouble(endDelivery))); + shipmentBuilder.setDeliveryStartsTimeWindow(TimeWindow.newInstance(parseTimeToDouble(startDelivery), parseTimeToDouble(endDelivery))); if (pickupServiceTime != null) - shipmentBuilder.setPickupServiceTime(parseTimeToDouble(pickupServiceTime)); + shipmentBuilder.setPickupDuration(parseTimeToDouble(pickupServiceTime)); if (deliveryServiceTime != null) - shipmentBuilder.setDeliveryServiceTime(parseTimeToDouble(deliveryServiceTime)); + shipmentBuilder.setDeliveryDuration(parseTimeToDouble(deliveryServiceTime)); currentShipment = shipmentBuilder.build(); currentShipments.put(atts.getValue(ID), currentShipment); @@ -261,26 +261,26 @@ public void startTag(String name, Attributes atts, Stack context) { String id = atts.getValue(SHIPMENT_ID); if (id == null) throw new IllegalStateException("pickup.shipmentId is missing."); CarrierShipment s = currentShipments.get(id); - finishLeg(s.getFrom()); + finishLeg(s.getPickupLinkId()); currentTourBuilder.schedulePickup(s); - previousActLoc = s.getFrom(); + previousActLoc = s.getPickupLinkId(); } case "delivery" -> { String id = atts.getValue(SHIPMENT_ID); if (id == null) throw new IllegalStateException("delivery.shipmentId is missing."); CarrierShipment s = currentShipments.get(id); - finishLeg(s.getTo()); + finishLeg(s.getDeliveryLinkId()); currentTourBuilder.scheduleDelivery(s); - previousActLoc = s.getTo(); + previousActLoc = s.getDeliveryLinkId(); } case "service" -> { String id = atts.getValue("serviceId"); if (id == null) throw new IllegalStateException("act.serviceId is missing."); CarrierService s = serviceMap.get(Id.create(id, CarrierService.class)); if (s == null) throw new IllegalStateException("serviceId is not known."); - finishLeg(s.getLocationLinkId()); + finishLeg(s.getServiceLinkId()); currentTourBuilder.scheduleService(s); - previousActLoc = s.getLocationLinkId(); + previousActLoc = s.getServiceLinkId(); } case "end" -> { finishLeg(currentVehicle.getLinkId()); 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 9c3f2b7a1e6..f439d323ddd 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 @@ -115,7 +115,7 @@ public void startTag(String name, Attributes atts, Stack context) { Id to = Id.create(toLocation, Link.class); CarrierService.Builder serviceBuilder = CarrierService.Builder.newInstance(id, to); String capDemandString = atts.getValue("capacityDemand"); - if (capDemandString != null) serviceBuilder.setCapacityDemand(getInt(capDemandString)); + if (capDemandString != null) serviceBuilder.setDemand(getInt(capDemandString)); String startString = atts.getValue("earliestStart"); double start = parseTimeToDouble(startString); double end; @@ -155,13 +155,13 @@ public void startTag(String name, Attributes atts, Stack context) { String deliveryServiceTime = atts.getValue("deliveryServiceTime"); if (startPickup != null && endPickup != null) - shipmentBuilder.setPickupTimeWindow(TimeWindow.newInstance(parseTimeToDouble(startPickup), parseTimeToDouble(endPickup))); + shipmentBuilder.setPickupStartsTimeWindow(TimeWindow.newInstance(parseTimeToDouble(startPickup), parseTimeToDouble(endPickup))); if (startDelivery != null && endDelivery != null) - shipmentBuilder.setDeliveryTimeWindow(TimeWindow.newInstance(parseTimeToDouble(startDelivery), parseTimeToDouble(endDelivery))); + shipmentBuilder.setDeliveryStartsTimeWindow(TimeWindow.newInstance(parseTimeToDouble(startDelivery), parseTimeToDouble(endDelivery))); if (pickupServiceTime != null) - shipmentBuilder.setPickupServiceTime(parseTimeToDouble(pickupServiceTime)); + shipmentBuilder.setPickupDuration(parseTimeToDouble(pickupServiceTime)); if (deliveryServiceTime != null) - shipmentBuilder.setDeliveryServiceTime(parseTimeToDouble(deliveryServiceTime)); + shipmentBuilder.setDeliveryDuration(parseTimeToDouble(deliveryServiceTime)); currentShipment = shipmentBuilder.build(); currentShipments.put(atts.getValue(ID), currentShipment); @@ -263,26 +263,26 @@ public void startTag(String name, Attributes atts, Stack context) { String id = atts.getValue(SHIPMENT_ID); if (id == null) throw new IllegalStateException("pickup.shipmentId is missing."); CarrierShipment s = currentShipments.get(id); - finishLeg(s.getFrom()); + finishLeg(s.getPickupLinkId()); currentTourBuilder.schedulePickup(s); - previousActLoc = s.getFrom(); + previousActLoc = s.getPickupLinkId(); } case "delivery" -> { String id = atts.getValue(SHIPMENT_ID); if (id == null) throw new IllegalStateException("delivery.shipmentId is missing."); CarrierShipment s = currentShipments.get(id); - finishLeg(s.getTo()); + finishLeg(s.getDeliveryLinkId()); currentTourBuilder.scheduleDelivery(s); - previousActLoc = s.getTo(); + previousActLoc = s.getDeliveryLinkId(); } case "service" -> { String id = atts.getValue("serviceId"); if (id == null) throw new IllegalStateException("act.serviceId is missing."); CarrierService s = serviceMap.get(Id.create(id, CarrierService.class)); if (s == null) throw new IllegalStateException("serviceId is not known."); - finishLeg(s.getLocationLinkId()); + finishLeg(s.getServiceLinkId()); currentTourBuilder.scheduleService(s); - previousActLoc = s.getLocationLinkId(); + previousActLoc = s.getServiceLinkId(); } case "end" -> { finishLeg(currentVehicle.getLinkId()); 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 6195fb3834f..811153ead21 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 @@ -159,15 +159,15 @@ private void writeShipments(Carrier carrier, BufferedWriter writer) { private void writeShipment(CarrierShipment s, Id shipmentId, boolean closeElement, boolean lineBreak) { this.writeStartTag(SHIPMENT, List.of( createTuple(ID, shipmentId.toString()), - createTuple(FROM, s.getFrom().toString()), - createTuple(TO, s.getTo().toString()), - createTuple(SIZE, s.getSize()), - createTuple(START_PICKUP, getTime(s.getPickupTimeWindow().getStart())), - createTuple(END_PICKUP, getTime(s.getPickupTimeWindow().getEnd())), - createTuple(START_DELIVERY, getTime(s.getDeliveryTimeWindow().getStart())), - createTuple(END_DELIVERY, getTime(s.getDeliveryTimeWindow().getEnd())), - createTuple(PICKUP_SERVICE_TIME, getTime(s.getPickupServiceTime())), - createTuple(DELIVERY_SERVICE_TIME, getTime(s.getDeliveryServiceTime()))), closeElement, lineBreak + createTuple(FROM, s.getPickupLinkId().toString()), + createTuple(TO, s.getDeliveryLinkId().toString()), + createTuple(SIZE, s.getDemand()), + createTuple(START_PICKUP, getTime(s.getPickupStartsTimeWindow().getStart())), + createTuple(END_PICKUP, getTime(s.getPickupStartsTimeWindow().getEnd())), + createTuple(START_DELIVERY, getTime(s.getDeliveryStartsTimeWindow().getStart())), + createTuple(END_DELIVERY, getTime(s.getDeliveryStartsTimeWindow().getEnd())), + createTuple(PICKUP_SERVICE_TIME, getTime(s.getPickupDuration())), + createTuple(DELIVERY_SERVICE_TIME, getTime(s.getDeliveryDuration()))), closeElement, lineBreak ); } @@ -190,8 +190,8 @@ private void writeServices(Carrier carrier, BufferedWriter writer) { private void writeService(CarrierService s, boolean closeElement, boolean lineBreak) { this.writeStartTag(SERVICE, List.of( createTuple(ID, s.getId().toString()), - createTuple(TO, s.getLocationLinkId().toString()), - createTuple(CAPACITY_DEMAND, s.getCapacityDemand()), + createTuple(TO, s.getServiceLinkId().toString()), + createTuple(CAPACITY_DEMAND, s.getDemand()), createTuple(EARLIEST_START, getTime(s.getServiceStartTimeWindow().getStart())), createTuple(LATEST_END, getTime(s.getServiceStartTimeWindow().getEnd())), createTuple(SERVICE_DURATION, getTime(s.getServiceDuration()))), closeElement, lineBreak diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierService.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierService.java index 69a5ce75e42..99be9a2f21f 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierService.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierService.java @@ -23,7 +23,6 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; -import org.matsim.utils.objectattributes.attributable.Attributable; import org.matsim.utils.objectattributes.attributable.Attributes; import org.matsim.utils.objectattributes.attributable.AttributesImpl; @@ -31,95 +30,127 @@ public final class CarrierService implements CarrierJob { public static class Builder { + private final Id id; + private int demand = 0; + + //IMO we could build a general class (CarrierActivity ???), containing the location, StartTimeWindow and Duration. + //This could be used for both, CarrierService and CarrierShipment (Pickup and Delivery). + //kturner dec'24 + private final Id serviceLinkId; + private TimeWindow serviceStartsTimeWindow = TimeWindow.newInstance(0.0, Integer.MAX_VALUE); + private double serviceDuration = 0.0; + public static Builder newInstance(Id id, Id locationLinkId){ return new Builder(id,locationLinkId); } - private final Id id; - private final Id locationLinkId; - private String name = "service"; - - private double serviceTime = 0.0; - private TimeWindow timeWindow = TimeWindow.newInstance(0.0, Integer.MAX_VALUE); - private int capacityDemand = 0; - - private Builder(Id id, Id locationLinkId) { + private Builder(Id id, Id serviceLinkId) { super(); this.id = id; - this.locationLinkId = locationLinkId; + this.serviceLinkId = serviceLinkId; } - public Builder setName(String name){ - this.name = name; + public CarrierService build(){ + return new CarrierService(this); + } + + + /** + * Sets a time-window for the beginning of the service + * When not set, it is by default [0.0., Integer.MAX_VALUE]. + *

+ * Note that the time-window restricts the start-time of the service (i.e. serviceActivity). If one works with hard time-windows (which means that + * time-windows must be met) than the service is allowed to start between startTimeWindow.getStart() and startTimeWindow.getEnd(). + * + * @param startTimeWindow time-window for the beginning of the service activity + * @return the builder + */ + public Builder setServiceStartTimeWindow(TimeWindow startTimeWindow){ + this.serviceStartsTimeWindow = startTimeWindow; return this; } /** - * By default, it is [0.0,Integer.MaxValue]. + * Sets the duration for the pickup activity. + * When not set, it is by default 0.0. * * @param serviceDuration duration of the service * @return the builder */ public Builder setServiceDuration(double serviceDuration){ - this.serviceTime = serviceDuration; + this.serviceDuration = serviceDuration; return this; } /** - * Sets a time-window for the service. - * - *

Note that the time-window restricts the start-time of the service (i.e. serviceActivity). If one works with hard time-windows (which means that - * time-windows must be met) than the service is allowed to start between startTimeWindow.getStart() and startTimeWindow.getEnd(). + * Sets the demand (size; capacity needed) of the service. + * When not set, it is by default 0. + *

+ * IMO we can put this into the Builder directly instead of a separate method? kturner dec'24 * - * @param startTimeWindow time-window for the service - * @return the builder + * @param demand the demand (size; capacity needed) of the service + * @return the builder */ - public Builder setServiceStartTimeWindow(TimeWindow startTimeWindow){ - this.timeWindow = startTimeWindow; + public Builder setDemand(int demand) { + this.demand = demand; return this; } - public CarrierService build(){ - return new CarrierService(this); - } + /** + * Sets the demand (size; capacity needed) of the service. + * When not set, it is by default 0. + *

+ * IMO we can put this into the Builder directly instead of a separate method? kturner dec'24 + * + * @deprecated please use {@link #setDemand(int)} instead + * + * @param value the demand (size; capacity needed) of the service + * @return the builder + */ + @Deprecated(since = "dec'24") public Builder setCapacityDemand(int value) { - this.capacityDemand = value; - return this; + return setDemand(value); } } private final Id id; + private final int demand; - private final Id locationId; - - private final String name; - + //IMO we could build a general class (CarrierActivity ???), containing the location, StartTimeWindow and Duration. + //This could be used for both, CarrierService and CarrierShipment (Pickup and Delivery). + //kturner dec'24 + private final Id serviceLinkId; + private final TimeWindow serviceStartsTimeWindow; private final double serviceDuration; - private final TimeWindow timeWindow; - - private final int demand; - private final Attributes attributes = new AttributesImpl(); private CarrierService(Builder builder){ id = builder.id; - locationId = builder.locationLinkId; - serviceDuration = builder.serviceTime; - timeWindow = builder.timeWindow; - demand = builder.capacityDemand; - name = builder.name; + serviceLinkId = builder.serviceLinkId; + serviceDuration = builder.serviceDuration; + serviceStartsTimeWindow = builder.serviceStartsTimeWindow; + demand = builder.demand; } + @Override public Id getId() { return id; } + public Id getServiceLinkId() { + return serviceLinkId; + } + + /** + * @deprecated please inline and use {@link #getServiceLinkId()} instead + */ + @Deprecated(since = "dec'24") public Id getLocationLinkId() { - return locationId; + return getServiceLinkId(); } public double getServiceDuration() { @@ -127,28 +158,35 @@ public double getServiceDuration() { } public TimeWindow getServiceStartTimeWindow(){ - return timeWindow; + return serviceStartsTimeWindow; } + /** + * @deprecated please inline and use {@link #getDemand()} instead + */ + @Deprecated(since = "dec'24") public int getCapacityDemand() { + return getDemand(); + } + + /** + * @return the demand (size; capacity needed) of the service. + */ + @Override + public int getDemand() { return demand; } + @Override public Attributes getAttributes() { return attributes; } - /** - * @return the name - */ - public String getType() { - return name; - } @Override public String toString() { - return "[id=" + id + "][locationId=" + locationId + "][capacityDemand=" + demand + "][serviceDuration=" + serviceDuration + "][startTimeWindow=" + timeWindow + "]"; + return "[id=" + id + "][locationId=" + serviceLinkId + "][capacityDemand=" + demand + "][serviceDuration=" + serviceDuration + "][startTimeWindow=" + serviceStartsTimeWindow + "]"; } /* (non-Javadoc) 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 01c8b873e70..a74177246d5 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 @@ -23,7 +23,6 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; -import org.matsim.utils.objectattributes.attributable.Attributable; import org.matsim.utils.objectattributes.attributable.Attributes; import org.matsim.utils.objectattributes.attributable.AttributesImpl; @@ -46,152 +45,231 @@ public final class CarrierShipment implements CarrierJob { */ public static class Builder { + private final Id id; + private final int demand; + + //IMO we could build a general class (CarrierActivity ???), containing the location, StartTimeWindow and Duration. + //This could be used for both, CarrierService and CarrierShipment (Pickup and Delivery). + //kturner dec'24 + private final Id pickupLinkId; + private TimeWindow pickupStartsTimeWindow = TimeWindow.newInstance(0.0, Integer.MAX_VALUE); + private double pickupDuration = 0.0; + + //IMO we could build a general class (CarrierActivity ???), containing the location, StartTimeWindow and Duration. + //This could be used for both, CarrierService and CarrierShipment (Pickup and Delivery). + //kturner dec'24 + private final Id deliveryLinkId; + private TimeWindow deliveryStartsTimeWindow = TimeWindow.newInstance(0.0, Integer.MAX_VALUE); + private double deliveryDuration = 0.0; + /** - * @deprecated Please use Builder newInstance(Id id, Id from, Id to, int size) instead. - *

* Returns a new shipment builder. - * - *

The builder is init with the shipment's origin (from), destination (to) and with the shipment's size. + *

+ * The builder is init with the shipment's origin (from), destination (to) and with the shipment's demand. * The default-value for serviceTime is 0.0. The default-value for a timeWindow is [start=0.0, end=Double.maxValue()]. * + * @param id the id of the shipment * @param from the origin * @param to the destination - * @param size size of the shipment + * @param demand demand of the shipment * @return the builder */ - @Deprecated - public static Builder newInstance(Id from, Id to, int size){ - return new Builder(from,to,size); + public static Builder newInstance(Id id, Id from, Id to, int demand){ + return new Builder(id, from, to, demand); + } + + private Builder(Id id, Id pickupLinkId, Id deliveryLinkId, int demand) { + super(); + this.id = id; + this.pickupLinkId = pickupLinkId; + this.deliveryLinkId = deliveryLinkId; + this.demand = demand; } /** - * Returns a new shipment builder. - * - *

The builder is init with the shipment's origin (from), destination (to) and with the shipment's size. - * The default-value for serviceTime is 0.0. The default-value for a timeWindow is [start=0.0, end=Double.maxValue()]. + * Sets a time-window for the beginning of the pickup + * When not set, it is by default [0.0., Integer.MAX_VALUE]. + *

+ * Note that the time-window restricts the start-time of the shipment's pickup . If one works with hard time-windows (which means that + * time-windows must be met) than the pickup is allowed to start between startTimeWindow.getStart() and startTimeWindow.getEnd(). * - * @param id the id of the shipment - * @param from the origin - * @param to the destination - * @param size size of the shipment - * @return the builder + * @param pickupStartsTimeWindow time-window for the beginning of the pickup activity + * @return the builder */ - public static Builder newInstance(Id id, Id from, Id to, int size){ - return new Builder(id, from,to,size); + public Builder setPickupStartsTimeWindow(TimeWindow pickupStartsTimeWindow){ + this.pickupStartsTimeWindow = pickupStartsTimeWindow; + return this; } - Id id; - 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; - double delServiceTime = 0.0; + /** + * Sets the duration for the pickup activity. + * When not set, it is by default 0.0. + * + * @param pickupDuration Duration of the pickup activity (in seconds). + * @return the Builder + */ + public Builder setPickupDuration(double pickupDuration){ + this.pickupDuration = pickupDuration; + return this; + } /** - * @deprecated Please use Builder (Id id, Id from, Id to, int size) instead. + * Sets a time-window for the beginning of the delivery + * When not set, it is by default [0.0., Integer.MAX_VALUE]. + *

+ * Note that the time-window restricts the start-time of the shipment's delivery . If one works with hard time-windows (which means that + * time-windows must be met) than the delivery is allowed to start between startTimeWindow.getStart() and startTimeWindow.getEnd(). + * + * @param deliveryStartsTimeWindow time-window for the beginning of the delivery activity + * @return the builder */ - @Deprecated - public Builder(Id from, Id to, int size) { - super(); - this.from = from; - this.to = to; - this.size = size; + public Builder setDeliveryStartsTimeWindow(TimeWindow deliveryStartsTimeWindow){ + this.deliveryStartsTimeWindow = deliveryStartsTimeWindow; + return this; } - public Builder(Id id, Id from, Id to, int size) { - super(); - this.id = id; - this.from = from; - this.to = to; - this.size = size; + /** + * Sets the duration for the delivery activity. + * When not set, it is by default 0.0. + * + * @param deliveryDuration Duration of the delivery activity (in seconds). + * @return the Builder + */ + public Builder setDeliveryDuration(double deliveryDuration){ + this.deliveryDuration = deliveryDuration; + return this; } - public Builder setPickupTimeWindow(TimeWindow pickupTW){ - this.pickTW = pickupTW; - return this; + public CarrierShipment build(){ + return new CarrierShipment(this); } - public Builder setDeliveryTimeWindow(TimeWindow deliveryTW){ - this.delTW = deliveryTW; - return this; + //*** deprecated methods *** + + + /** + * @deprecated please inline and use {@link #setPickupStartsTimeWindow(TimeWindow)} instead + */ + @Deprecated(since = "dec'24") + public Builder setPickupTimeWindow(TimeWindow pickupTW){ + return setPickupStartsTimeWindow(pickupTW); } + /** + * @deprecated please inline and use {@link #setPickupDuration(double)} instead + */ + @Deprecated(since = "dec'24") public Builder setPickupServiceTime(double pickupServiceTime){ - this.pickServiceTime = pickupServiceTime; - return this; + return setPickupDuration(pickupServiceTime); } - public Builder setDeliveryServiceTime(double deliveryServiceTime){ - this.delServiceTime = deliveryServiceTime; - return this; + /** + * @deprecated please inline and use {@link #setDeliveryStartsTimeWindow(TimeWindow)} instead + */ + @Deprecated(since = "dec'24") + public Builder setDeliveryTimeWindow(TimeWindow deliveryTW){ + return setDeliveryStartsTimeWindow(deliveryTW); } - public CarrierShipment build(){ - return new CarrierShipment(this); + /** + * @deprecated please inline and use {@link #setDeliveryDuration(double)} instead + */ + @Deprecated(since = "dec'24") + public Builder setDeliveryServiceTime(double deliveryServiceTime){ + return setDeliveryDuration(deliveryServiceTime); } } private final Id id; - private final Id from; - private final Id to; - private final int size; - private final TimeWindow pickupTimeWindow; - private final TimeWindow deliveryTimeWindow; - private double pickupServiceTime; - private double deliveryServiceTime; + private final int demand; + + //IMO we could build a general class (CarrierActivity ???), containing the location, StartTimeWindow and Duration. + //This could be used for both, CarrierService and CarrierShipment (Pickup and Delivery). + //kturner dec'24 + private final Id pickupLinkId; + private final TimeWindow pickupStartsTimeWindow; + private double pickupDuration; + + //IMO we could build a general class (CarrierActivity ???), containing the location, StartTimeWindow and Duration. + //This could be used for both, CarrierService and CarrierShipment (Pickup and Delivery). + //kturner dec'24 + private final Id deliveryLinkId; + private final TimeWindow deliveryStartsTimeWindow; + private double deliveryDuration; + private final Attributes attributes = new AttributesImpl(); private CarrierShipment(Builder builder) { id = builder.id; - from = builder.from; - to = builder.to; - size = builder.size; - pickupServiceTime = builder.pickServiceTime; - deliveryServiceTime = builder.delServiceTime; - pickupTimeWindow = builder.pickTW; - deliveryTimeWindow = builder.delTW; + pickupLinkId = builder.pickupLinkId; + deliveryLinkId = builder.deliveryLinkId; + demand = builder.demand; + pickupDuration = builder.pickupDuration; + deliveryDuration = builder.deliveryDuration; + pickupStartsTimeWindow = builder.pickupStartsTimeWindow; + deliveryStartsTimeWindow = builder.deliveryStartsTimeWindow; } - public double getPickupServiceTime() { - return pickupServiceTime; + //* getters and setters + + public double getPickupDuration() { + return pickupDuration; } - public void setPickupServiceTime(double pickupServiceTime) { - this.pickupServiceTime = pickupServiceTime; + public double getDeliveryDuration() { + return deliveryDuration; } - public double getDeliveryServiceTime() { - return deliveryServiceTime; + /** + * Do we really need the setter? We do have it in the builder. + * I do not see, why we should be able to update it, since most of the values are immutable. + * @deprecated Consider setting it using the Builder. This will maybe be removed and the field gets immutable. + * kturner, dec'24 + */ + @Deprecated(since = "dec'24") + public void setPickupDuration(double pickupDuration) { + this.pickupDuration = pickupDuration; } - public void setDeliveryServiceTime(double deliveryServiceTime) { - this.deliveryServiceTime = deliveryServiceTime; + /** + * Do we really need the setter? We do have it in the builder. + * I do not see, why we should be able to update it, since most of the values are immutable. + * @deprecated Consider setting it using the Builder. This will maybe be removed and the field gets immutable. + * kturner, dec'24 + */ + @Deprecated(since = "dec'24") + public void setDeliveryDuration(double deliveryDuration) { + this.deliveryDuration = deliveryDuration; } + @Override public Id getId() { return id; } - public Id getFrom() { - return from; + + public Id getPickupLinkId() { + return pickupLinkId; } - public Id getTo() { - return to; + public Id getDeliveryLinkId() { + return deliveryLinkId; } - public int getSize() { - return size; + /** + * @return the demand (size; capacity needed) of the shipment. + */ + @Override + public int getDemand() { + return demand; } - public TimeWindow getPickupTimeWindow() { - return pickupTimeWindow; + public TimeWindow getPickupStartsTimeWindow() { + return pickupStartsTimeWindow; } - public TimeWindow getDeliveryTimeWindow() { - return deliveryTimeWindow; + public TimeWindow getDeliveryStartsTimeWindow() { + return deliveryStartsTimeWindow; } @Override @@ -199,10 +277,88 @@ public Attributes getAttributes() { return attributes; } + //*** deprecated methods *** + + /** + * @deprecated please inline and use {@link #getDemand()} instead + */ + @Deprecated(since = "dec'24") + public int getSize() { + return getDemand(); + } + + + /** + * @deprecated please inline and use {@link #getPickupLinkId()} instead + */ + @Deprecated(since = "dec'24") + public Id getFrom() { + return getPickupLinkId(); + } + + /** + * @deprecated please inline and use {@link #getPickupStartsTimeWindow()} instead + */ + @Deprecated(since = "dec'24") + public TimeWindow getPickupTimeWindow() { + return getPickupStartsTimeWindow(); + } + + /** + * @deprecated please inline and use {@link #setPickupDuration(double)} instead + */ + @Deprecated(since = "dec'24") + public void setPickupServiceTime(double pickupDuration) { + setPickupDuration(pickupDuration); + } + + /** + * @deprecated please inline and use {@link #getPickupDuration()} instead + */ + @Deprecated(since = "dec'24") + public double getPickupServiceTime() { + return getPickupDuration(); + } + + + /** + * @deprecated please inline and use {@link #getDeliveryLinkId()} instead + */ + @Deprecated(since = "dec'24") + public Id getTo() { + return getDeliveryLinkId(); + } + + /** + * @deprecated please inline and use {@link #getDeliveryStartsTimeWindow()} instead + */ + @Deprecated(since = "dec'24") + public TimeWindow getDeliveryTimeWindow() { + return getDeliveryStartsTimeWindow(); + } + + /** + * @deprecated please inline and use {@link #getDeliveryDuration()} instead + */ + @Deprecated(since = "dec'24") + public double getDeliveryServiceTime() { + return getDeliveryDuration(); + } + + /** + * @deprecated please inline and use {@link #setDeliveryDuration(double)} instead + */ + @Deprecated(since = "dec'24") + public void setDeliveryServiceTime(double deliveryDuration) { + setDeliveryDuration(deliveryDuration); + } + + // *** general methods *** + @Override public String toString() { - return "[id= "+ id.toString() + "][hash=" + this.hashCode() + "][from=" + from.toString() + "][to=" + to.toString() + "][size=" + size + "][pickupServiceTime=" + pickupServiceTime + "]" + - "[deliveryServiceTime="+deliveryServiceTime+"][pickupTimeWindow="+pickupTimeWindow+"][deliveryTimeWindow="+deliveryTimeWindow+"]"; + return "[id= "+ id.toString() + "][hash=" + this.hashCode() + "][from=" + pickupLinkId.toString() + "][to=" + deliveryLinkId.toString() + "][size=" + demand + "][pickupServiceTime=" + pickupDuration + "]" + + "[deliveryServiceTime="+ deliveryDuration +"][pickupTimeWindow="+ pickupStartsTimeWindow +"][deliveryTimeWindow="+ deliveryStartsTimeWindow +"]"; } /* (non-Javadoc) 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 1b6a270e65e..d82e2e0ba46 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 @@ -430,14 +430,14 @@ private static void createShipmentsFromServices(Carrier carrierWS, Carrier carri 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(), - carrierService.getCapacityDemand()) - .setDeliveryServiceTime(carrierService.getServiceDuration()) + depotServiceIsDeliveredFrom.get(carrierService.getId()), carrierService.getServiceLinkId(), + carrierService.getDemand()) + .setDeliveryDuration(carrierService.getServiceDuration()) // .setPickupServiceTime(pickupServiceTime) //Not set yet, because in service we // have now time for that. Maybe change it later, kmt sep18 - .setDeliveryTimeWindow(carrierService.getServiceStartTimeWindow()) + .setDeliveryStartsTimeWindow(carrierService.getServiceStartTimeWindow()) // Limited to end of delivery timeWindow (pickup later than the latest delivery is not useful). - .setPickupTimeWindow(TimeWindow.newInstance(0.0, carrierService.getServiceStartTimeWindow().getEnd())) + .setPickupStartsTimeWindow(TimeWindow.newInstance(0.0, carrierService.getServiceStartTimeWindow().getEnd())) .build(); addShipment(carrierWS, carrierShipment); } 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 55f72325237..fec5bc60655 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 @@ -374,12 +374,12 @@ public CarrierService getService(){ @Override public String getActivityType() { - return service.getType(); + return CarrierConstants.SERVICE; } @Override public Id getLocation() { - return service.getLocationLinkId(); + return service.getServiceLinkId(); } @Override @@ -539,17 +539,17 @@ public String getActivityType() { @Override public TimeWindow getTimeWindow() { - return shipment.getPickupTimeWindow(); + return shipment.getPickupStartsTimeWindow(); } @Override public Id getLocation() { - return shipment.getFrom(); + return shipment.getPickupLinkId(); } @Override public double getDuration() { - return shipment.getPickupServiceTime(); + return shipment.getPickupDuration(); } @Override @@ -592,7 +592,7 @@ public Delivery(CarrierShipment shipment) { @Override public TimeWindow getTimeWindow() { - return shipment.getDeliveryTimeWindow(); + return shipment.getDeliveryStartsTimeWindow(); } @Override @@ -602,12 +602,12 @@ public String getActivityType() { @Override public Id getLocation() { - return shipment.getTo(); + return shipment.getDeliveryLinkId(); } @Override public double getDuration() { - return shipment.getDeliveryServiceTime(); + return shipment.getDeliveryDuration(); } @Override diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/analysis/CarrierLoadAnalysis.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/analysis/CarrierLoadAnalysis.java index 760ce513035..652d0740975 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/analysis/CarrierLoadAnalysis.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/analysis/CarrierLoadAnalysis.java @@ -27,10 +27,8 @@ import java.io.FileWriter; import java.io.IOException; import java.nio.file.Path; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.Map; +import java.util.*; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; @@ -54,6 +52,7 @@ public class CarrierLoadAnalysis implements CarrierShipmentPickupStartEventHandl final Carriers carriers; private final Map, LinkedList> vehicle2Load = new LinkedHashMap<>(); + private final Map, Integer> vehicle2DemandPerTour = new HashMap<>(); public CarrierLoadAnalysis(String delimiter, Carriers carriers) { this.delimiter = delimiter; @@ -69,9 +68,11 @@ public void handleEvent(CarrierShipmentPickupStartEvent event) { if (! vehicle2Load.containsKey(vehicleId)){ list = new LinkedList<>(); list.add(demand); + vehicle2DemandPerTour.put(vehicleId, demand); } else { list = vehicle2Load.get(vehicleId); list.add(list.getLast() + demand); + vehicle2DemandPerTour.put(vehicleId, vehicle2DemandPerTour.get(vehicleId) + demand); } vehicle2Load.put(vehicleId, list); } @@ -98,6 +99,8 @@ void writeLoadPerVehicle(String analysisOutputDirectory, Scenario scenario) thro "vehicleTypeId", "capacity", "maxLoad", + "maxLoadPercentage", + "handledDemand", "load state during tour")); bw1.newLine(); @@ -109,10 +112,15 @@ void writeLoadPerVehicle(String analysisOutputDirectory, Scenario scenario) thro final VehicleType vehicleType = VehicleUtils.findVehicle(vehicleId, scenario).getType(); final Double capacity = vehicleType.getCapacity().getOther(); + final Integer demand = vehicle2DemandPerTour.get(vehicleId); + final double maxLoadPercentage = Math.round(maxLoad / capacity * 10000)/100.0;; + bw1.write(vehicleId.toString()); bw1.write(delimiter + vehicleType.getId().toString()); bw1.write(delimiter + capacity); bw1.write(delimiter + maxLoad); + bw1.write(delimiter + maxLoadPercentage); + bw1.write(delimiter + demand); bw1.write(delimiter + load); bw1.newLine(); } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/analysis/CarrierPlanAnalysis.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/analysis/CarrierPlanAnalysis.java index 362dfaf8793..7c73cb9b551 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/analysis/CarrierPlanAnalysis.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/analysis/CarrierPlanAnalysis.java @@ -101,16 +101,16 @@ public void runAnalysisAndWriteStats(String analysisOutputDirectory) throws IOEx int numberOfHandledDemandSize; int notHandledJobs; if (numberOfPlanedShipments > 0) { - numberOfPlanedDemandSize = carrier.getShipments().values().stream().mapToInt(CarrierShipment::getSize).sum(); + numberOfPlanedDemandSize = carrier.getShipments().values().stream().mapToInt(carrierShipment -> carrierShipment.getDemand()).sum(); numberOfHandledDemandSize = carrier.getSelectedPlan().getScheduledTours().stream().mapToInt( t -> t.getTour().getTourElements().stream().filter(te -> te instanceof Tour.Pickup).mapToInt( - te -> (((Tour.Pickup) te).getShipment().getSize())).sum()).sum(); + te -> ((Tour.Pickup) te).getShipment().getDemand()).sum()).sum(); notHandledJobs = numberOfPlanedShipments - numberOfHandledPickups; } else { - numberOfPlanedDemandSize = carrier.getServices().values().stream().mapToInt(CarrierService::getCapacityDemand).sum(); + numberOfPlanedDemandSize = carrier.getServices().values().stream().mapToInt(carrierService -> carrierService.getDemand()).sum(); numberOfHandledDemandSize = carrier.getSelectedPlan().getScheduledTours().stream().mapToInt( t -> t.getTour().getTourElements().stream().filter(te -> te instanceof Tour.ServiceActivity).mapToInt( - te -> ((Tour.ServiceActivity) te).getService().getCapacityDemand()).sum()).sum(); + te -> ((Tour.ServiceActivity) te).getService().getDemand()).sum()).sum(); notHandledJobs = numberOfPlanedServices - nuOfServiceHandled; } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/analysis/RunFreightAnalysisEventBased.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/analysis/RunFreightAnalysisEventBased.java index 0502ae2e1c4..00c1f1dea61 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/analysis/RunFreightAnalysisEventBased.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/analysis/RunFreightAnalysisEventBased.java @@ -124,6 +124,8 @@ public RunFreightAnalysisEventBased(Carriers carriers, String analysisOutputPath private void createScenarioForFreightAnalysis(String vehiclesPath, String networkPath, String carriersPath, String carriersVehicleTypesPath, String globalCrs) { + log.info("########## Starting Freight Analysis ##########"); + Config config = ConfigUtils.createConfig(); config.vehicles().setVehiclesFile(vehiclesPath); config.network().setInputFile(networkPath); diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceEndEvent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceEndEvent.java index f806248471c..17907fe74eb 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceEndEvent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceEndEvent.java @@ -42,7 +42,7 @@ public final class CarrierServiceEndEvent extends AbstractCarrierEvent { private final double serviceDuration; public CarrierServiceEndEvent(double time, Id carrierId, CarrierService service, Id vehicleId) { - super(time, carrierId, service.getLocationLinkId(), vehicleId); + super(time, carrierId, service.getServiceLinkId(), vehicleId); this.serviceId = service.getId(); this.serviceDuration = service.getServiceDuration(); } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceStartEvent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceStartEvent.java index d1b4d816ace..f0a2cc0fde6 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceStartEvent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierServiceStartEvent.java @@ -44,10 +44,10 @@ public final class CarrierServiceStartEvent extends AbstractCarrierEvent { private final int capacityDemand; public CarrierServiceStartEvent(double time, Id carrierId, CarrierService service, Id vehicleId) { - super(time, carrierId, service.getLocationLinkId(), vehicleId); + super(time, carrierId, service.getServiceLinkId(), vehicleId); this.serviceId = service.getId(); this.serviceDuration = service.getServiceDuration(); - this.capacityDemand = service.getCapacityDemand(); + this.capacityDemand = service.getDemand(); } @Override @@ -85,7 +85,7 @@ public static CarrierServiceStartEvent convert(GenericEvent event) { Id locationLinkId = Id.createLinkId(attributes.get(ATTRIBUTE_LINK)); CarrierService service = CarrierService.Builder.newInstance(carrierServiceId, locationLinkId) .setServiceDuration(Double.parseDouble(attributes.get(CarrierEventAttributes.ATTRIBUTE_SERVICE_DURATION))) - .setCapacityDemand(Integer.parseInt(attributes.get(CarrierEventAttributes.ATTRIBUTE_CAPACITYDEMAND))) + .setDemand(Integer.parseInt(attributes.get(CarrierEventAttributes.ATTRIBUTE_CAPACITYDEMAND))) .build(); Id vehicleId = Id.create(attributes.get(ATTRIBUTE_VEHICLE), Vehicle.class); return new CarrierServiceStartEvent(time, carrierId, service, vehicleId); diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryEndEvent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryEndEvent.java index 8f60260a067..2687b550387 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryEndEvent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryEndEvent.java @@ -44,10 +44,10 @@ public class CarrierShipmentDeliveryEndEvent extends AbstractCarrierEvent { private final double deliveryDuration; private final int capacityDemand; public CarrierShipmentDeliveryEndEvent(double time, Id carrierId, CarrierShipment shipment, Id vehicleId) { - super(time, carrierId, shipment.getTo(), vehicleId); + super(time, carrierId, shipment.getDeliveryLinkId(), vehicleId); this.shipmentId = shipment.getId(); - this.deliveryDuration = shipment.getDeliveryServiceTime(); - this.capacityDemand = shipment.getSize(); + this.deliveryDuration = shipment.getDeliveryDuration(); + this.capacityDemand = shipment.getDemand(); } @Override @@ -83,7 +83,7 @@ public static CarrierShipmentDeliveryEndEvent convert(GenericEvent event) { Id shipmentTo = Id.createLinkId(attributes.get(ATTRIBUTE_LINK)); int size = Integer.parseInt(attributes.get(CarrierEventAttributes.ATTRIBUTE_CAPACITYDEMAND)); CarrierShipment shipment = CarrierShipment.Builder.newInstance(shipmentId, null, shipmentTo, size) - .setDeliveryServiceTime(Double.parseDouble(attributes.get(CarrierEventAttributes.ATTRIBUTE_DROPOFF_DURATION))) + .setDeliveryDuration(Double.parseDouble(attributes.get(CarrierEventAttributes.ATTRIBUTE_DROPOFF_DURATION))) .build(); Id vehicleId = Id.createVehicleId(attributes.get(ATTRIBUTE_VEHICLE)); return new CarrierShipmentDeliveryEndEvent(time, carrierId, shipment, vehicleId); diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryStartEvent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryStartEvent.java index a30035968c0..ca4a2ec4767 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryStartEvent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentDeliveryStartEvent.java @@ -45,10 +45,10 @@ public class CarrierShipmentDeliveryStartEvent extends AbstractCarrierEvent { private final double deliveryDuration; private final int capacityDemand; public CarrierShipmentDeliveryStartEvent(double time, Id carrierId, CarrierShipment shipment, Id vehicleId) { - super(time, carrierId, shipment.getTo(), vehicleId); + super(time, carrierId, shipment.getDeliveryLinkId(), vehicleId); this.shipmentId = shipment.getId(); - this.deliveryDuration = shipment.getDeliveryServiceTime(); - this.capacityDemand = shipment.getSize(); + this.deliveryDuration = shipment.getDeliveryDuration(); + this.capacityDemand = shipment.getDemand(); } @Override @@ -84,7 +84,7 @@ public static CarrierShipmentDeliveryStartEvent convert(GenericEvent event) { Id shipmentTo = Id.createLinkId(attributes.get(ATTRIBUTE_LINK)); int size = Integer.parseInt(attributes.get(ATTRIBUTE_CAPACITYDEMAND)); CarrierShipment shipment = CarrierShipment.Builder.newInstance(shipmentId, null, shipmentTo, size) - .setDeliveryServiceTime(Double.parseDouble(attributes.get(ATTRIBUTE_DROPOFF_DURATION))) + .setDeliveryDuration(Double.parseDouble(attributes.get(ATTRIBUTE_DROPOFF_DURATION))) .build(); Id vehicleId = Id.createVehicleId(attributes.get(ATTRIBUTE_VEHICLE)); return new CarrierShipmentDeliveryStartEvent(time, carrierId, shipment, vehicleId); diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupEndEvent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupEndEvent.java index 4316e6f4dfe..97da9f70817 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupEndEvent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupEndEvent.java @@ -46,10 +46,10 @@ public class CarrierShipmentPickupEndEvent extends AbstractCarrierEvent { public CarrierShipmentPickupEndEvent(double time, Id carrierId, CarrierShipment shipment, Id vehicleId) { - super(time, carrierId, shipment.getFrom(), vehicleId); + super(time, carrierId, shipment.getPickupLinkId(), vehicleId); this.shipmentId = shipment.getId(); - this.pickupDuration = shipment.getPickupServiceTime(); - this.capacityDemand = shipment.getSize(); + this.pickupDuration = shipment.getPickupDuration(); + this.capacityDemand = shipment.getDemand(); } @@ -79,7 +79,7 @@ public static CarrierShipmentPickupEndEvent convert(GenericEvent event) { Id shipmentFrom = Id.createLinkId(attributes.get(ATTRIBUTE_LINK)); int shipmentSize = Integer.parseInt(attributes.get(ATTRIBUTE_CAPACITYDEMAND)); CarrierShipment shipment = CarrierShipment.Builder.newInstance(shipmentId, shipmentFrom, null, shipmentSize) - .setPickupServiceTime(Double.parseDouble(attributes.get(ATTRIBUTE_PICKUP_DURATION))) + .setPickupDuration(Double.parseDouble(attributes.get(ATTRIBUTE_PICKUP_DURATION))) .build(); Id vehicleId = Id.createVehicleId(attributes.get(ATTRIBUTE_VEHICLE)); return new CarrierShipmentPickupEndEvent(time, carrierId, shipment, vehicleId); diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupStartEvent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupStartEvent.java index fe851a10138..7334a9fa8a6 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupStartEvent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierShipmentPickupStartEvent.java @@ -44,10 +44,10 @@ public class CarrierShipmentPickupStartEvent extends AbstractCarrierEvent { public CarrierShipmentPickupStartEvent(double time, Id carrierId, CarrierShipment shipment, Id vehicleId) { - super(time, carrierId, shipment.getFrom(), vehicleId); + super(time, carrierId, shipment.getPickupLinkId(), vehicleId); this.shipmentId = shipment.getId(); - this.pickupDuration = shipment.getPickupServiceTime(); - this.capacityDemand = shipment.getSize(); + this.pickupDuration = shipment.getPickupDuration(); + this.capacityDemand = shipment.getDemand(); } @@ -77,7 +77,7 @@ public static CarrierShipmentPickupStartEvent convert(GenericEvent event) { Id shipmentFrom = Id.createLinkId(attributes.get(ATTRIBUTE_LINK)); int shipmentSize = Integer.parseInt(attributes.get(CarrierEventAttributes.ATTRIBUTE_CAPACITYDEMAND)); CarrierShipment shipment = CarrierShipment.Builder.newInstance(shipmentId, shipmentFrom, null, shipmentSize) - .setPickupServiceTime(Double.parseDouble(attributes.get(CarrierEventAttributes.ATTRIBUTE_PICKUP_DURATION))) + .setPickupDuration(Double.parseDouble(attributes.get(CarrierEventAttributes.ATTRIBUTE_PICKUP_DURATION))) .build(); Id vehicleId = Id.createVehicleId(attributes.get(ATTRIBUTE_VEHICLE)); return new CarrierShipmentPickupStartEvent(time, carrierId, shipment, vehicleId); 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 8615e0b3d75..8265dca2666 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 @@ -23,10 +23,7 @@ import com.graphhopper.jsprit.core.problem.constraint.HardActivityConstraint; import com.graphhopper.jsprit.core.problem.misc.JobInsertionContext; -import com.graphhopper.jsprit.core.problem.solution.route.VehicleRoute; -import com.graphhopper.jsprit.core.problem.solution.route.activity.DeliverShipment; -import com.graphhopper.jsprit.core.problem.solution.route.activity.PickupShipment; -import com.graphhopper.jsprit.core.problem.solution.route.activity.TourActivity; +import com.graphhopper.jsprit.core.problem.solution.route.activity.*; import com.graphhopper.jsprit.core.problem.vehicle.Vehicle; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -64,124 +61,81 @@ public DistanceConstraint(CarrierVehicleTypes vehicleTypes, } /** - * When adding a TourActivity to the tour and the new vehicle has an - * energyCapacity (fuel or electricity etc.) the algorithm always checks the - * fulfilled method if all conditions (constraints) are fulfilled or not. - * Because every activity is added separately and the pickup before the delivery - * of a shipment, it will investigate which additional distance is necessary for - * the pickup and which minimal additional distance of the associated Delivery - * is needed. This is also important for the fulfilled decision of this - * function. At the end the conditions checks if the consumption of the tour - * including the additional shipment is possible with the possible - * energyCapacity. + * When adding a TourActivity to the tour and the new vehicle has an energyCapacity (fuel or electricity etc.) the algorithm always checks the fulfilled method if all conditions (constraints) are fulfilled or not. + * If a delivery is added, it also accounts for the necessary consumption if the pickup is added at the given position of the tour. This is also important for the fulfilled decision of this + * function. In the end, the conditions check if the consumption of the tour including the additional shipment is possible with the possible energyCapacity. */ //TODO add the time dependencies of the distance calculation because the route choice can be different for different times @Override public ConstraintsStatus fulfilled(JobInsertionContext context, TourActivity prevAct, TourActivity newAct, - TourActivity nextAct, double departureTime) { - double additionalDistance; + TourActivity nextAct, double prevActDepTime) { +// double additionalDistance; + Vehicle newVehicle = context.getNewVehicle(); VehicleType vehicleTypeOfNewVehicle = vehicleTypes.getVehicleTypes() - .get(Id.create(context.getNewVehicle().getType().getTypeId(), VehicleType.class)); - if (VehicleUtils.getEnergyCapacity(vehicleTypeOfNewVehicle.getEngineInformation()) != null) { - - Vehicle newVehicle = context.getNewVehicle(); - - Double energyCapacityInKWhOrLiters = VehicleUtils - .getEnergyCapacity(vehicleTypeOfNewVehicle.getEngineInformation()); - Double consumptionPerMeter; - if (VehicleUtils.getHbefaTechnology(vehicleTypeOfNewVehicle.getEngineInformation()).equals("electricity")) - consumptionPerMeter = VehicleUtils - .getEnergyConsumptionKWhPerMeter(vehicleTypeOfNewVehicle.getEngineInformation()); + .get(Id.create(newVehicle.getType().getTypeId(), VehicleType.class)); + if (VehicleUtils.getEnergyCapacity(vehicleTypeOfNewVehicle.getEngineInformation()) == null) return ConstraintsStatus.FULFILLED; + + Double energyCapacityInKWhOrLiters = VehicleUtils + .getEnergyCapacity(vehicleTypeOfNewVehicle.getEngineInformation()); + Double consumptionPerMeter; + if (VehicleUtils.getHbefaTechnology(vehicleTypeOfNewVehicle.getEngineInformation()).equals("electricity")) + consumptionPerMeter = VehicleUtils + .getEnergyConsumptionKWhPerMeter(vehicleTypeOfNewVehicle.getEngineInformation()); + else + consumptionPerMeter = VehicleUtils.getFuelConsumptionLitersPerMeter(vehicleTypeOfNewVehicle.getEngineInformation()); + + double currentDistance = calculateRouteDistance(context, newVehicle); + double currentRouteConsumption = currentDistance * (consumptionPerMeter); + if (currentRouteConsumption > energyCapacityInKWhOrLiters) return ConstraintsStatus.NOT_FULFILLED_BREAK; + + double distancePrevAct2NewAct = getDistance(prevAct, newAct, newVehicle, prevActDepTime); + double distanceNewAct2nextAct = getDistance(newAct, nextAct, newVehicle, prevActDepTime); + double distancePrevAct2NextAct = getDistance(prevAct, nextAct, newVehicle, prevActDepTime); + if (prevAct instanceof Start && nextAct instanceof End) distancePrevAct2NextAct = 0; + if (nextAct instanceof End && !context.getNewVehicle().isReturnToDepot()) { + distanceNewAct2nextAct = 0; + distancePrevAct2NextAct = 0; + } + double additionalDistance = distancePrevAct2NewAct + distanceNewAct2nextAct - distancePrevAct2NextAct; + double additionalConsumption = additionalDistance * (consumptionPerMeter); + if (currentRouteConsumption + additionalConsumption > energyCapacityInKWhOrLiters) return ConstraintsStatus.NOT_FULFILLED; + + + double additionalDistanceOfPickup; + double additionalConsumptionOfPickup = 0; + if (newAct instanceof DeliverShipment) { + int iIndexOfPickup = context.getRelatedActivityContext().getInsertionIndex(); + TourActivity pickup = context.getAssociatedActivities().getFirst(); + TourActivity actBeforePickup; + if (iIndexOfPickup > 0) actBeforePickup = context.getRoute().getActivities().get(iIndexOfPickup - 1); + else actBeforePickup = new Start(context.getNewVehicle().getStartLocation(), 0, Double.MAX_VALUE); + TourActivity actAfterPickup; + if (iIndexOfPickup < context.getRoute().getActivities().size()) + actAfterPickup = context.getRoute().getActivities().get(iIndexOfPickup); else - consumptionPerMeter = VehicleUtils.getFuelConsumptionLitersPerMeter(vehicleTypeOfNewVehicle.getEngineInformation()); - - double routeDistance = calculateRouteDistance(context, newVehicle); - double routeConsumption = routeDistance * (consumptionPerMeter); - - if (newAct instanceof PickupShipment) { - // calculates the additional distance for adding a pickup and checks the shortest possibility for adding the associated delivery - additionalDistance = getDistance(prevAct, newAct, newVehicle) + getDistance(newAct, nextAct, newVehicle) - - getDistance(prevAct, nextAct, newVehicle)+ findMinimalAdditionalDistance(context, newAct, newAct); - - } else if (newAct instanceof DeliverShipment) { - // calculates the distance new for integrating the associated pickup - routeDistance = calculateRouteDistanceWithAssociatedPickup(context); - routeConsumption = routeDistance * (consumptionPerMeter); - - additionalDistance = getDistance(prevAct, newAct, newVehicle) + getDistance(newAct, nextAct, newVehicle) - - getDistance(prevAct, nextAct, newVehicle); - - } else { - additionalDistance = getDistance(prevAct, newAct, newVehicle) + getDistance(newAct, nextAct, newVehicle) - - getDistance(prevAct, nextAct, newVehicle); + actAfterPickup = nextAct; + double distanceActBeforePickup2Pickup = getDistance(actBeforePickup, pickup, newVehicle, actBeforePickup.getEndTime()); + double distancePickup2ActAfterPickup = getDistance(pickup, actAfterPickup, newVehicle, context.getRelatedActivityContext().getEndTime()); + double distanceBeforePickup2AfterPickup = getDistance(actBeforePickup, actAfterPickup,newVehicle, actBeforePickup.getEndTime()); + if (context.getRoute().isEmpty()) distanceBeforePickup2AfterPickup = 0; + if (actAfterPickup instanceof End && !context.getNewVehicle().isReturnToDepot()) { + distancePickup2ActAfterPickup = 0; + distanceBeforePickup2AfterPickup = 0; } - double additionalConsumption = additionalDistance * (consumptionPerMeter); - double newRouteConsumption = routeConsumption + additionalConsumption; - - if (newRouteConsumption > energyCapacityInKWhOrLiters) { - return ConstraintsStatus.NOT_FULFILLED_BREAK; - } else { - return ConstraintsStatus.FULFILLED; - } - } else { - return ConstraintsStatus.FULFILLED; + additionalDistanceOfPickup = distanceActBeforePickup2Pickup + distancePickup2ActAfterPickup - distanceBeforePickup2AfterPickup; + additionalConsumptionOfPickup = additionalDistanceOfPickup * (consumptionPerMeter); } - } - /** - * Calculates the distance based on the route-based distances between every tour - * activities. The method also integrates the associated pickup in the tour. - */ - private double calculateRouteDistanceWithAssociatedPickup(JobInsertionContext context) { - double routeDistance; - int positionOfRelatedPickup = context.getRelatedActivityContext().getInsertionIndex(); - int nextRouteActivity = 0; + if (currentRouteConsumption + additionalConsumption + additionalConsumptionOfPickup > energyCapacityInKWhOrLiters) + return ConstraintsStatus.NOT_FULFILLED; - // checks if the associated pickup is on first position - 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().getFirst(), context.getRoute().getEnd(), - context.getNewVehicle(), context.getNewDepTime()); - return routeDistance; - } else if (positionOfRelatedPickup == 0 && !context.getRoute().getActivities().isEmpty()) { - routeDistance = getDistance(context.getAssociatedActivities().getFirst(), - context.getRoute().getActivities().getFirst(), context.getNewVehicle(), context.getNewDepTime()); - } else { - 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 - // the correct position of the tour - while (context.getRoute().getTourActivities().getActivities().size() > (nextRouteActivity + 1)) { - if (positionOfRelatedPickup == (nextRouteActivity + 1) && positionOfRelatedPickup != 0) { - routeDistance = routeDistance + getDistance(context.getRoute().getActivities().get(nextRouteActivity), - 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), - context.getRoute().getActivities().get(nextRouteActivity + 1), context.getNewVehicle()); - } - nextRouteActivity++; - } - if (positionOfRelatedPickup == context.getRoute().getActivities().size()) { - routeDistance = routeDistance + getDistance(context.getRoute().getActivities().get(nextRouteActivity), - 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), - context.getRoute().getEnd(), context.getNewVehicle()); + return ConstraintsStatus.FULFILLED; - return routeDistance; } /** - * Calculates the distance based on the route-based distances between every tour - * activities. - * + * Calculates the distance based on the route-based distances between every tour activity. */ private double calculateRouteDistance(JobInsertionContext context, Vehicle newVehicle) { double realRouteDistance = 0; @@ -189,121 +143,20 @@ private double calculateRouteDistance(JobInsertionContext context, Vehicle newVe return realRouteDistance; int n = 0; realRouteDistance = getDistance(context.getRoute().getStart(), - context.getRoute().getTourActivities().getActivities().getFirst(), newVehicle); + context.getRoute().getTourActivities().getActivities().getFirst(), newVehicle, context.getRoute().getStart().getEndTime()); while (context.getRoute().getTourActivities().getActivities().size() > (n + 1)) { + + TourActivity from = context.getRoute().getTourActivities().getActivities().get(n); realRouteDistance = realRouteDistance - + getDistance(context.getRoute().getTourActivities().getActivities().get(n), - context.getRoute().getTourActivities().getActivities().get(n + 1), newVehicle); + + getDistance(from, context.getRoute().getTourActivities().getActivities().get(n + 1), newVehicle, from.getEndTime()); n++; } + TourActivity from = context.getRoute().getTourActivities().getActivities().get(n); realRouteDistance = realRouteDistance + getDistance( - context.getRoute().getTourActivities().getActivities().get(n), context.getRoute().getEnd(), newVehicle); + context.getRoute().getTourActivities().getActivities().get(n), context.getRoute().getEnd(), newVehicle, from.getEndTime()); return realRouteDistance; } - /** - * Finds a minimal additional distance for the tour, when a pickup is added to - * the plan. The AssociatedActivities contains both activities of a job which - * should be added to the existing tour. The TourActivities which are already in - * the tour are found in context.getRoute().getTourActivities. In this method - * the position of the new pickup is fixed and three options of the location of - * the delivery activity will be checked: delivery between every other activity - * after the pickup, delivery as the last activity before the end and delivery - * directly behind the new pickup. This method gives back the minimal distance - * of this three options. - * - * @param context the context of the job insertion - * @param newInvestigatedPickup the new pickup which should be added to the tour - * @param nextAct the next activity after the new pickup - * @return minimal distance of the associated delivery - */ - private double findMinimalAdditionalDistance(JobInsertionContext context, TourActivity newInvestigatedPickup, - TourActivity nextAct) { - double minimalAdditionalDistance = 0; - - if (context.getAssociatedActivities().get(1) instanceof DeliverShipment) { - TourActivity assignedDelivery = context.getAssociatedActivities().get(1); - minimalAdditionalDistance = 0; - int indexNextActivity = nextAct.getIndex(); - int tourPositionOfActivityBehindNewPickup = 0; - int countIndex = 0; - Vehicle newVehicle = context.getNewVehicle(); - VehicleRoute route = context.getRoute(); - - // search the index of the activity behind the pickup activity which should be - // added to the tour - a: for (TourActivity tourActivity : route.getTourActivities().getActivities()) { - if (tourActivity.getIndex() == indexNextActivity) { - while (countIndex < route.getTourActivities().getActivities().size()) { - if (route.getTourActivities().getActivities().get(countIndex).getIndex() == indexNextActivity) { - tourPositionOfActivityBehindNewPickup = countIndex; - break a; - } - countIndex++; - } - } - } - - // search the minimal distance between every exiting TourActivity - while ((tourPositionOfActivityBehindNewPickup + 1) < route.getTourActivities().getActivities().size()) { - TourActivity activityBefore = route.getTourActivities().getActivities() - .get(tourPositionOfActivityBehindNewPickup); - TourActivity activityAfter = route.getTourActivities().getActivities() - .get(tourPositionOfActivityBehindNewPickup + 1); - double possibleAdditionalDistance = getDistance(activityBefore, assignedDelivery, newVehicle) - + getDistance(assignedDelivery, activityAfter, newVehicle) - - getDistance(activityBefore, activityAfter, newVehicle); - minimalAdditionalDistance = findMinimalDistance(minimalAdditionalDistance, possibleAdditionalDistance); - tourPositionOfActivityBehindNewPickup++; - } - // checks the distance if the delivery is the last activity before the end of - // the tour - if (!route.getTourActivities().getActivities().isEmpty()) { - TourActivity activityLastDelivery = route.getTourActivities().getActivities() - .getLast(); - TourActivity activityEnd = route.getEnd(); - double possibleAdditionalDistance = getDistance(activityLastDelivery, assignedDelivery, newVehicle) - + getDistance(assignedDelivery, activityEnd, newVehicle) - - getDistance(activityLastDelivery, activityEnd, newVehicle); - minimalAdditionalDistance = findMinimalDistance(minimalAdditionalDistance, possibleAdditionalDistance); - - // Checks the distance if the delivery will be added directly behind the pickup - TourActivity activityAfter = route.getTourActivities().getActivities() - .get(tourPositionOfActivityBehindNewPickup); - possibleAdditionalDistance = getDistance(newInvestigatedPickup, assignedDelivery, newVehicle) - + getDistance(assignedDelivery, activityAfter, newVehicle) - - getDistance(newInvestigatedPickup, activityAfter, newVehicle); - minimalAdditionalDistance = findMinimalDistance(minimalAdditionalDistance, possibleAdditionalDistance); - } - - } - return minimalAdditionalDistance; - } - - /** - * Checks if the find possible distance is the minimal one. - * - * @param minimalAdditionalDistance the minimal additional distance - * @param possibleAdditionalDistance the possible additional distance - * @return the minimal transport distance - */ - private double findMinimalDistance(double minimalAdditionalDistance, double possibleAdditionalDistance) { - if (minimalAdditionalDistance == 0) - minimalAdditionalDistance = possibleAdditionalDistance; - else if (possibleAdditionalDistance < minimalAdditionalDistance) - minimalAdditionalDistance = possibleAdditionalDistance; - return minimalAdditionalDistance; - } - - private double getDistance(TourActivity from, TourActivity to, Vehicle vehicle) { - double distance = netBasedCosts.getDistance(from.getLocation(), to.getLocation(), from.getEndTime(), - vehicle); - if (!(distance >= 0.)) - throw new AssertionError("Distance must not be negative! From, to" + from + ", " + to - + " distance " + distance); - return distance; - } - private double getDistance(TourActivity from, TourActivity to, Vehicle vehicle, double departureTime) { double distance = netBasedCosts.getDistance(from.getLocation(), to.getLocation(), departureTime, vehicle); 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 00cf9347716..11776d0152b 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 @@ -88,11 +88,11 @@ static CarrierShipment createCarrierShipment(Shipment jspritShipment) { .newInstance(Id.create(jspritShipment.getId(), CarrierShipment.class), Id.createLinkId(jspritShipment.getPickupLocation().getId()), Id.createLinkId(jspritShipment.getDeliveryLocation().getId()), jspritShipment.getSize().get(0)) - .setDeliveryServiceTime(jspritShipment.getDeliveryServiceTime()) - .setDeliveryTimeWindow(org.matsim.freight.carriers.TimeWindow.newInstance(jspritShipment.getDeliveryTimeWindow().getStart(), + .setDeliveryDuration(jspritShipment.getDeliveryServiceTime()) + .setDeliveryStartsTimeWindow(org.matsim.freight.carriers.TimeWindow.newInstance(jspritShipment.getDeliveryTimeWindow().getStart(), jspritShipment.getDeliveryTimeWindow().getEnd())) - .setPickupServiceTime(jspritShipment.getPickupServiceTime()) - .setPickupTimeWindow(org.matsim.freight.carriers.TimeWindow.newInstance(jspritShipment.getPickupTimeWindow().getStart(), + .setPickupDuration(jspritShipment.getPickupServiceTime()) + .setPickupStartsTimeWindow(org.matsim.freight.carriers.TimeWindow.newInstance(jspritShipment.getPickupTimeWindow().getStart(), jspritShipment.getPickupTimeWindow().getEnd())) .build(); CarriersUtils.setSkills(carrierShipment, jspritShipment.getRequiredSkills().values()); @@ -108,17 +108,17 @@ static CarrierShipment createCarrierShipment(Shipment jspritShipment) { */ static Shipment createJspritShipment(CarrierShipment carrierShipment) { Shipment.Builder shipmentBuilder = Shipment.Builder.newInstance(carrierShipment.getId().toString()) - .setDeliveryLocation(Location.newInstance(carrierShipment.getTo().toString())) - .setDeliveryServiceTime(carrierShipment.getDeliveryServiceTime()) + .setDeliveryLocation(Location.newInstance(carrierShipment.getDeliveryLinkId().toString())) + .setDeliveryServiceTime(carrierShipment.getDeliveryDuration()) .setDeliveryTimeWindow(com.graphhopper.jsprit.core.problem.solution.route.activity.TimeWindow - .newInstance(carrierShipment.getDeliveryTimeWindow().getStart(), - carrierShipment.getDeliveryTimeWindow().getEnd())) - .setPickupServiceTime(carrierShipment.getPickupServiceTime()) - .setPickupLocation(Location.newInstance(carrierShipment.getFrom().toString())) + .newInstance(carrierShipment.getDeliveryStartsTimeWindow().getStart(), + carrierShipment.getDeliveryStartsTimeWindow().getEnd())) + .setPickupServiceTime(carrierShipment.getPickupDuration()) + .setPickupLocation(Location.newInstance(carrierShipment.getPickupLinkId().toString())) .setPickupTimeWindow(com.graphhopper.jsprit.core.problem.solution.route.activity.TimeWindow.newInstance( - carrierShipment.getPickupTimeWindow().getStart(), - carrierShipment.getPickupTimeWindow().getEnd())) - .addSizeDimension(0, carrierShipment.getSize()); + carrierShipment.getPickupStartsTimeWindow().getStart(), + carrierShipment.getPickupStartsTimeWindow().getEnd())) + .addSizeDimension(0, carrierShipment.getDemand()); for (String skill : CarriersUtils.getSkills(carrierShipment)) { shipmentBuilder.addRequiredSkill(skill); } @@ -127,29 +127,29 @@ static Shipment createJspritShipment(CarrierShipment carrierShipment) { static Shipment createJspritShipment(CarrierShipment carrierShipment, Coord fromCoord, Coord toCoord) { Location.Builder fromLocationBuilder = Location.Builder.newInstance(); - fromLocationBuilder.setId(carrierShipment.getFrom().toString()); + fromLocationBuilder.setId(carrierShipment.getPickupLinkId().toString()); if (fromCoord != null) { fromLocationBuilder.setCoordinate(Coordinate.newInstance(fromCoord.getX(), fromCoord.getY())); } Location fromLocation = fromLocationBuilder.build(); Location.Builder toLocationBuilder = Location.Builder.newInstance(); - toLocationBuilder.setId(carrierShipment.getTo().toString()); + toLocationBuilder.setId(carrierShipment.getDeliveryLinkId().toString()); if (toCoord != null) { toLocationBuilder.setCoordinate(Coordinate.newInstance(toCoord.getX(), toCoord.getY())); } Location toLocation = toLocationBuilder.build(); Shipment.Builder shipmentBuilder = Shipment.Builder.newInstance(carrierShipment.getId().toString()) - .setDeliveryLocation(toLocation).setDeliveryServiceTime(carrierShipment.getDeliveryServiceTime()) + .setDeliveryLocation(toLocation).setDeliveryServiceTime(carrierShipment.getDeliveryDuration()) .setDeliveryTimeWindow(com.graphhopper.jsprit.core.problem.solution.route.activity.TimeWindow - .newInstance(carrierShipment.getDeliveryTimeWindow().getStart(), - carrierShipment.getDeliveryTimeWindow().getEnd())) - .setPickupServiceTime(carrierShipment.getPickupServiceTime()).setPickupLocation(fromLocation) + .newInstance(carrierShipment.getDeliveryStartsTimeWindow().getStart(), + carrierShipment.getDeliveryStartsTimeWindow().getEnd())) + .setPickupServiceTime(carrierShipment.getPickupDuration()).setPickupLocation(fromLocation) .setPickupTimeWindow(com.graphhopper.jsprit.core.problem.solution.route.activity.TimeWindow.newInstance( - carrierShipment.getPickupTimeWindow().getStart(), - carrierShipment.getPickupTimeWindow().getEnd())) - .addSizeDimension(0, carrierShipment.getSize()); + carrierShipment.getPickupStartsTimeWindow().getStart(), + carrierShipment.getPickupStartsTimeWindow().getEnd())) + .addSizeDimension(0, carrierShipment.getDemand()); for (String skill : CarriersUtils.getSkills(carrierShipment)) { shipmentBuilder.addRequiredSkill(skill); } @@ -158,14 +158,14 @@ static Shipment createJspritShipment(CarrierShipment carrierShipment, Coord from static Service createJspritService(CarrierService carrierService, Coord locationCoord) { Location.Builder locationBuilder = Location.Builder.newInstance(); - locationBuilder.setId(carrierService.getLocationLinkId().toString()); + locationBuilder.setId(carrierService.getServiceLinkId().toString()); if (locationCoord != null) { locationBuilder.setCoordinate(Coordinate.newInstance(locationCoord.getX(), locationCoord.getY())); } Location location = locationBuilder.build(); Builder serviceBuilder = Builder.newInstance(carrierService.getId().toString()); - serviceBuilder.addSizeDimension(0, carrierService.getCapacityDemand()); + serviceBuilder.addSizeDimension(0, carrierService.getDemand()); serviceBuilder.setLocation(location).setServiceTime(carrierService.getServiceDuration()) .setTimeWindow(com.graphhopper.jsprit.core.problem.solution.route.activity.TimeWindow.newInstance( carrierService.getServiceStartTimeWindow().getStart(), @@ -184,7 +184,7 @@ static Service createJspritService(CarrierService carrierService, Coord location static CarrierService createCarrierService(Service jspritService) { CarrierService.Builder serviceBuilder = CarrierService.Builder.newInstance( Id.create(jspritService.getId(), CarrierService.class), Id.create(jspritService.getLocation().getId(), Link.class)); - serviceBuilder.setCapacityDemand(jspritService.getSize().get(0)); + serviceBuilder.setDemand(jspritService.getSize().get(0)); serviceBuilder.setServiceDuration(jspritService.getServiceDuration()); serviceBuilder.setServiceStartTimeWindow( org.matsim.freight.carriers.TimeWindow.newInstance(jspritService.getTimeWindow().getStart(), jspritService.getTimeWindow().getEnd())); @@ -515,11 +515,11 @@ public static VehicleRoutingProblem createRoutingProblem(Carrier carrier, Networ Coord coordinate = null; if (network != null) { - Link link = network.getLinks().get(service.getLocationLinkId()); + Link link = network.getLinks().get(service.getServiceLinkId()); if (link != null) { coordinate = link.getCoord(); } else - log.warn("cannot find linkId {}", service.getLocationLinkId()); + log.warn("cannot find linkId {}", service.getServiceLinkId()); } vrpBuilder.addJob(createJspritService(service, coordinate)); } @@ -530,8 +530,8 @@ public static VehicleRoutingProblem createRoutingProblem(Carrier carrier, Networ Coord fromCoordinate = null; Coord toCoordinate = null; if (network != null) { - Link fromLink = network.getLinks().get(carrierShipment.getFrom()); - Link toLink = network.getLinks().get(carrierShipment.getTo()); + Link fromLink = network.getLinks().get(carrierShipment.getPickupLinkId()); + Link toLink = network.getLinks().get(carrierShipment.getDeliveryLinkId()); if (fromLink != null && toLink != null) { // Shipment to be delivered from specified location to // specified location @@ -540,8 +540,8 @@ public static VehicleRoutingProblem createRoutingProblem(Carrier carrier, Networ vrpBuilder.addJob(createJspritShipment(carrierShipment, fromCoordinate, toCoordinate)); } else throw new IllegalStateException( - "cannot create shipment since neither fromLinkId " + carrierShipment.getTo() - + " nor toLinkId " + carrierShipment.getTo() + " exists in network."); + "cannot create shipment since neither fromLinkId " + carrierShipment.getDeliveryLinkId() + + " nor toLinkId " + carrierShipment.getDeliveryLinkId() + " exists in network."); } vrpBuilder.addJob(createJspritShipment(carrierShipment, fromCoordinate, toCoordinate)); @@ -611,9 +611,9 @@ public static VehicleRoutingProblem.Builder createRoutingProblemBuilder(Carrier log.debug("Handle CarrierService: {}", service.toString()); Coord coordinate = null; if (network != null) { - Link link = network.getLinks().get(service.getLocationLinkId()); + Link link = network.getLinks().get(service.getServiceLinkId()); if (link == null) { - throw new IllegalStateException("cannot create service since linkId " + service.getLocationLinkId() + throw new IllegalStateException("cannot create service since linkId " + service.getServiceLinkId() + " does not exists in network."); } else coordinate = link.getCoord(); @@ -628,8 +628,8 @@ public static VehicleRoutingProblem.Builder createRoutingProblemBuilder(Carrier Coord fromCoordinate = null; Coord toCoordinate = null; if (network != null) { - Link fromLink = network.getLinks().get(carrierShipment.getFrom()); - Link toLink = network.getLinks().get(carrierShipment.getTo()); + Link fromLink = network.getLinks().get(carrierShipment.getPickupLinkId()); + Link toLink = network.getLinks().get(carrierShipment.getDeliveryLinkId()); if (fromLink != null && toLink != null) { // Shipment to be delivered from specified location to // specified location @@ -638,8 +638,8 @@ public static VehicleRoutingProblem.Builder createRoutingProblemBuilder(Carrier toCoordinate = toLink.getCoord(); } else throw new IllegalStateException("cannot create shipment " + carrierShipment.getId().toString() - + " since either fromLinkId " + carrierShipment.getFrom() + " or toLinkId " - + carrierShipment.getTo() + " exists in network."); + + " since either fromLinkId " + carrierShipment.getPickupLinkId() + " or toLinkId " + + carrierShipment.getDeliveryLinkId() + " exists in network."); } vrpBuilder.addJob(createJspritShipment(carrierShipment, fromCoordinate, toCoordinate)); 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 3d291829b77..44a4dda7a5f 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 @@ -101,7 +101,7 @@ private static void createCustomers(Carrier carrier, Network network) { for(int i=0;i<20;i++){ CarrierService.Builder serviceBuilder = CarrierService.Builder.newInstance(Id.create((i + 1),CarrierService.class), drawLocationLinkId(innerCityLinks, outerCityLinks)); - serviceBuilder.setCapacityDemand(1); + serviceBuilder.setDemand(1); serviceBuilder.setServiceDuration(5*60); serviceBuilder.setServiceStartTimeWindow(TimeWindow.newInstance(6*60*60, 15*60*60)); CarrierService carrierService = serviceBuilder.build(); diff --git a/contribs/freight/src/main/java/org/matsim/freight/logistics/examples/multipleChains/MultipleChainsUtils.java b/contribs/freight/src/main/java/org/matsim/freight/logistics/examples/multipleChains/MultipleChainsUtils.java index 30517805da5..8670ad977ea 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/logistics/examples/multipleChains/MultipleChainsUtils.java +++ b/contribs/freight/src/main/java/org/matsim/freight/logistics/examples/multipleChains/MultipleChainsUtils.java @@ -59,13 +59,13 @@ public static Collection createLSPShipmentsFromCarrierShipments(Car LspShipmentUtils.LspShipmentBuilder builder = LspShipmentUtils.LspShipmentBuilder.newInstance( Id.create(shipment.getId().toString(), LspShipment.class)); - builder.setCapacityDemand(shipment.getSize()); - builder.setFromLinkId(shipment.getFrom()); - builder.setToLinkId(shipment.getTo()); - builder.setStartTimeWindow(shipment.getPickupTimeWindow()); - builder.setEndTimeWindow(shipment.getDeliveryTimeWindow()); - builder.setPickupServiceTime(shipment.getPickupServiceTime()); - builder.setDeliveryServiceTime(shipment.getDeliveryServiceTime()); + builder.setCapacityDemand(shipment.getDemand()); + builder.setFromLinkId(shipment.getPickupLinkId()); + builder.setToLinkId(shipment.getDeliveryLinkId()); + builder.setStartTimeWindow(shipment.getPickupStartsTimeWindow()); + builder.setEndTimeWindow(shipment.getDeliveryStartsTimeWindow()); + builder.setPickupServiceTime(shipment.getPickupDuration()); + builder.setDeliveryServiceTime(shipment.getDeliveryDuration()); shipmentList.add(builder.build()); } return shipmentList; diff --git a/contribs/freight/src/main/java/org/matsim/freight/logistics/resourceImplementations/CollectionCarrierScheduler.java b/contribs/freight/src/main/java/org/matsim/freight/logistics/resourceImplementations/CollectionCarrierScheduler.java index d91bf1c94f5..f6473a6fcad 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/logistics/resourceImplementations/CollectionCarrierScheduler.java +++ b/contribs/freight/src/main/java/org/matsim/freight/logistics/resourceImplementations/CollectionCarrierScheduler.java @@ -84,7 +84,7 @@ private CarrierService convertToCarrierService(LspShipment lspShipment) { Id serviceId = Id.create(lspShipment.getId().toString(), CarrierService.class); CarrierService carrierService = CarrierService.Builder.newInstance(serviceId, lspShipment.getFrom()) .setServiceStartTimeWindow(TimeWindow.newInstance(lspShipment.getPickupTimeWindow().getStart(), lspShipment.getPickupTimeWindow().getEnd())) - .setCapacityDemand(lspShipment.getSize()) + .setDemand(lspShipment.getSize()) .setServiceDuration(lspShipment.getDeliveryServiceTime()) .build(); //ensure that the ids of the lspShipment and the carrierService are the same. This is needed for updating the LSPShipmentPlan diff --git a/contribs/freight/src/main/java/org/matsim/freight/logistics/resourceImplementations/DistributionCarrierScheduler.java b/contribs/freight/src/main/java/org/matsim/freight/logistics/resourceImplementations/DistributionCarrierScheduler.java index 90abf00ea67..f3814a036e6 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/logistics/resourceImplementations/DistributionCarrierScheduler.java +++ b/contribs/freight/src/main/java/org/matsim/freight/logistics/resourceImplementations/DistributionCarrierScheduler.java @@ -184,7 +184,7 @@ private CarrierService convertToCarrierService(LspShipment lspShipment) { CarrierService carrierService = CarrierService.Builder.newInstance(serviceId, lspShipment.getTo()) //TODO TimeWindows are not set. This seems to be a problem. KMT'Aug'24 //If added here, we also need to decide what happens, if the vehicles StartTime (plus TT) is > TimeWindowEnd .... - .setCapacityDemand(lspShipment.getSize()) + .setDemand(lspShipment.getSize()) .setServiceDuration(lspShipment.getDeliveryServiceTime()) .build(); //ensure that the ids of the lspShipment and the carrierService are the same. This is needed for updating the LSPShipmentPlan @@ -207,7 +207,7 @@ private CarrierShipment convertToCarrierShipment(LspShipment lspShipment) { CarrierShipment carrierShipment = CarrierShipment.Builder.newInstance(serviceId, lspShipment.getFrom(), lspShipment.getTo(), lspShipment.getSize()) //TODO TimeWindows are not set. This seems to be a problem. KMT'Aug'24 //If added here, we also need to decide what happens, if the vehicles StartTime (plus TT) is > TimeWindowEnd .... - .setDeliveryServiceTime(lspShipment.getDeliveryServiceTime()) + .setDeliveryDuration(lspShipment.getDeliveryServiceTime()) .build(); //ensure that the ids of the lspShipment and the carrierShipment are the same. This is needed for updating the LSPShipmentPlan if (! Objects.equals(lspShipment.getId().toString(), carrierShipment.getId().toString())) { diff --git a/contribs/freight/src/main/java/org/matsim/freight/logistics/resourceImplementations/MainRunCarrierScheduler.java b/contribs/freight/src/main/java/org/matsim/freight/logistics/resourceImplementations/MainRunCarrierScheduler.java index 99f49186e11..abcc023fa20 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/logistics/resourceImplementations/MainRunCarrierScheduler.java +++ b/contribs/freight/src/main/java/org/matsim/freight/logistics/resourceImplementations/MainRunCarrierScheduler.java @@ -229,7 +229,7 @@ private CarrierService convertToCarrierService(LspShipment lspShipment) { Id.create(lspShipment.getId().toString(), CarrierService.class); CarrierService.Builder builder = CarrierService.Builder.newInstance(serviceId, resource.getEndLinkId()); - builder.setCapacityDemand(lspShipment.getSize()); + builder.setDemand(lspShipment.getSize()); builder.setServiceDuration(lspShipment.getDeliveryServiceTime()); return builder.build(); } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarriersUtilsTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarriersUtilsTest.java index fe0428621e0..839f2cceaef 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarriersUtilsTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarriersUtilsTest.java @@ -68,21 +68,21 @@ void testAddAndGetServiceToCarrier() { Carrier carrier = new CarrierImpl(Id.create("carrier", Carrier.class)); Id serviceId = Id.create("testVehicle", CarrierService.class); CarrierService service1 = CarrierService.Builder.newInstance(serviceId,Id.createLinkId("link0") ) - .setName("service1").setCapacityDemand(15).setServiceDuration(30).build(); + .setDemand(15).setServiceDuration(30).build(); //add Service CarriersUtils.addService(carrier, service1); Assertions.assertEquals(1, carrier.getServices().size()); CarrierService cs1a = (CarrierService) carrier.getServices().values().toArray()[0]; Assertions.assertEquals(service1, cs1a); - Assertions.assertEquals(Id.createLinkId("link0"), cs1a.getLocationLinkId()); + Assertions.assertEquals(Id.createLinkId("link0"), cs1a.getServiceLinkId()); //get Service CarrierService cs1b = CarriersUtils.getService(carrier, serviceId ); assert cs1b != null; Assertions.assertEquals(serviceId, cs1b.getId()); Assertions.assertEquals(service1.getId(), cs1b.getId()); - Assertions.assertEquals(Id.createLinkId("link0"), cs1b.getLocationLinkId()); + Assertions.assertEquals(Id.createLinkId("link0"), cs1b.getServiceLinkId()); Assertions.assertEquals(30, cs1b.getServiceDuration(), EPSILON); } @@ -97,15 +97,15 @@ void testAddAndGetShipmentToCarrier() { Assertions.assertEquals(1, carrier.getShipments().size()); CarrierShipment carrierShipment1a = (CarrierShipment) carrier.getShipments().values().toArray()[0]; Assertions.assertEquals(service1, carrierShipment1a); - Assertions.assertEquals(Id.createLinkId("link0"), carrierShipment1a.getFrom()); + Assertions.assertEquals(Id.createLinkId("link0"), carrierShipment1a.getPickupLinkId()); //get Shipment CarrierShipment carrierShipment1b = CarriersUtils.getShipment(carrier, shipmentId ); assert carrierShipment1b != null; Assertions.assertEquals(shipmentId, carrierShipment1b.getId()); Assertions.assertEquals(service1.getId(), carrierShipment1b.getId()); - Assertions.assertEquals(Id.createLinkId("link0"), carrierShipment1b.getFrom()); - Assertions.assertEquals(20, carrierShipment1b.getSize(), EPSILON); + Assertions.assertEquals(Id.createLinkId("link0"), carrierShipment1b.getPickupLinkId()); + Assertions.assertEquals(20, carrierShipment1b.getDemand(), EPSILON); } @Test 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 43557b37a2a..e729e5360d6 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 @@ -421,14 +421,14 @@ private static Carrier addTwoServicesToCarrier(Carrier carrier) { CarrierService service1 = CarrierService.Builder .newInstance(Id.create("Service1", CarrierService.class), Id.createLinkId("j(3,8)")) .setServiceDuration(20).setServiceStartTimeWindow(TimeWindow.newInstance(8 * 3600, 10 * 3600)) - .setCapacityDemand(40).build(); + .setDemand(40).build(); CarriersUtils.addService(carrier, service1); // Service 2 CarrierService service2 = CarrierService.Builder .newInstance(Id.create("Service2", CarrierService.class), Id.createLinkId("j(0,3)R")) .setServiceDuration(20).setServiceStartTimeWindow(TimeWindow.newInstance(8 * 3600, 10 * 3600)) - .setCapacityDemand(40).build(); + .setDemand(40).build(); CarriersUtils.addService(carrier, service2); return carrier; @@ -442,7 +442,7 @@ private static Carrier addThreeServicesToCarrier(Carrier carrier) { CarrierService service3 = CarrierService.Builder .newInstance(Id.create("Service3", CarrierService.class), Id.createLinkId("j(9,2)")) .setServiceDuration(20).setServiceStartTimeWindow(TimeWindow.newInstance(8 * 3600, 10 * 3600)) - .setCapacityDemand(40).build(); + .setDemand(40).build(); CarriersUtils.addService(carrier, service3); return carrier; 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 a375cceac46..3747a98a882 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 @@ -614,14 +614,14 @@ private static Carrier addTwoServicesToCarrier(Carrier carrier) { CarrierService service1 = CarrierService.Builder .newInstance(Id.create("Service1", CarrierService.class), Id.createLinkId("j(3,8)")) .setServiceDuration(20).setServiceStartTimeWindow(TimeWindow.newInstance(8 * 3600, 10 * 3600)) - .setCapacityDemand(40).build(); + .setDemand(40).build(); CarriersUtils.addService(carrier, service1); // Service 2 CarrierService service2 = CarrierService.Builder .newInstance(Id.create("Service2", CarrierService.class), Id.createLinkId("j(0,3)R")) .setServiceDuration(20).setServiceStartTimeWindow(TimeWindow.newInstance(8 * 3600, 10 * 3600)) - .setCapacityDemand(40).build(); + .setDemand(40).build(); CarriersUtils.addService(carrier, service2); return carrier; @@ -631,14 +631,14 @@ private static Carrier addTwoShipmentsToCarrier(Carrier carrier) { // Shipment 1 CarrierShipment shipment1 = CarrierShipment.Builder .newInstance(Id.create("Shipment1", CarrierShipment.class), Id.createLinkId("i(1,8)"), Id.createLinkId("j(3,8)"), 40) - .setDeliveryServiceTime(20).setDeliveryTimeWindow(TimeWindow.newInstance(8 * 3600, 12 * 3600)) + .setDeliveryDuration(20).setDeliveryStartsTimeWindow(TimeWindow.newInstance(8 * 3600, 12 * 3600)) .build(); CarriersUtils.addShipment(carrier, shipment1); // Shipment 2 CarrierShipment shipment2 = CarrierShipment.Builder .newInstance(Id.create("Shipment2", CarrierShipment.class),Id.createLinkId("i(1,8)"), Id.createLinkId("j(0,3)R"), 40) - .setDeliveryServiceTime(20).setDeliveryTimeWindow(TimeWindow.newInstance(8 * 3600, 12 * 3600)) + .setDeliveryDuration(20).setDeliveryStartsTimeWindow(TimeWindow.newInstance(8 * 3600, 12 * 3600)) .build(); CarriersUtils.addShipment(carrier, shipment2); @@ -653,7 +653,7 @@ private static Carrier addThreeServicesToCarrier(Carrier carrier) { CarrierService service3 = CarrierService.Builder .newInstance(Id.create("Service3", CarrierService.class), Id.createLinkId("j(9,2)")) .setServiceDuration(20).setServiceStartTimeWindow(TimeWindow.newInstance(8 * 3600, 10 * 3600)) - .setCapacityDemand(40).build(); + .setDemand(40).build(); CarriersUtils.addService(carrier, service3); return carrier; 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 cf5060bf772..494c9f106e6 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 @@ -200,7 +200,7 @@ final void test_carrier3CostsAreCorrectly() { private static CarrierService createMatsimService(String id, String to, int size) { return CarrierService.Builder.newInstance(Id.create(id, CarrierService.class), Id.create(to, Link.class)) - .setCapacityDemand(size) + .setDemand(size) .setServiceDuration(31.0) .setServiceStartTimeWindow(TimeWindow.newInstance(3601.0, 36001.0)) .build(); 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 5025334cc5e..2882cec1336 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 @@ -122,7 +122,7 @@ void whenTransforming_matsimVehicle2jspritVehicle_itIsMadeCorrectly() { void whenTransforming_matsimService2jspritService_isMadeCorrectly() { CarrierService carrierService = CarrierService.Builder .newInstance(Id.create("serviceId", CarrierService.class), Id.create("locationId", Link.class)) - .setCapacityDemand(50).setServiceDuration(30.0) + .setDemand(50).setServiceDuration(30.0) .setServiceStartTimeWindow(TimeWindow.newInstance(10.0, 20.0)).build(); Service service = MatsimJspritFactory.createJspritService(carrierService, null); assertNotNull(service); @@ -146,9 +146,9 @@ void whenTransforming_jspritService2matsimService_isMadeCorrectly() { CarrierService service = MatsimJspritFactory.createCarrierService(carrierService); assertNotNull(service); - assertEquals("locationId", service.getLocationLinkId().toString()); + assertEquals("locationId", service.getServiceLinkId().toString()); assertEquals(30.0, service.getServiceDuration(), 0.01); - assertEquals(50, service.getCapacityDemand()); + assertEquals(50, service.getDemand()); assertEquals(10.0, service.getServiceStartTimeWindow().getStart(), 0.01); CarrierService service2 = MatsimJspritFactory.createCarrierService(carrierService); @@ -161,8 +161,8 @@ void whenTransforming_matsimShipment2jspritShipment_isMadeCorrectly() { CarrierShipment carrierShipment = CarrierShipment.Builder .newInstance(Id.create("ShipmentId", CarrierShipment.class), Id.createLinkId("PickupLocationId"), Id.createLinkId("DeliveryLocationId"), 50) - .setPickupServiceTime(30.0).setPickupTimeWindow(TimeWindow.newInstance(10.0, 20.0)) - .setDeliveryServiceTime(40.0).setDeliveryTimeWindow(TimeWindow.newInstance(50.0, 60.0)).build(); + .setPickupDuration(30.0).setPickupStartsTimeWindow(TimeWindow.newInstance(10.0, 20.0)) + .setDeliveryDuration(40.0).setDeliveryStartsTimeWindow(TimeWindow.newInstance(50.0, 60.0)).build(); Shipment shipment = MatsimJspritFactory.createJspritShipment(carrierShipment); assertNotNull(shipment); assertEquals("PickupLocationId", shipment.getPickupLocation().getId()); @@ -193,15 +193,15 @@ void whenTransforming_jspritShipment2matsimShipment_isMadeCorrectly() { CarrierShipment carrierShipment = MatsimJspritFactory.createCarrierShipment(shipment); assertNotNull(carrierShipment); - assertEquals("PickupLocationId", carrierShipment.getFrom().toString()); - assertEquals(30.0, carrierShipment.getPickupServiceTime(), 0.01); - assertEquals(10.0, carrierShipment.getPickupTimeWindow().getStart(), 0.01); - assertEquals(20.0, carrierShipment.getPickupTimeWindow().getEnd(), 0.01); - assertEquals("DeliveryLocationId", carrierShipment.getTo().toString()); - assertEquals(40.0, carrierShipment.getDeliveryServiceTime(), 0.01); - assertEquals(50.0, carrierShipment.getDeliveryTimeWindow().getStart(), 0.01); - assertEquals(60.0, carrierShipment.getDeliveryTimeWindow().getEnd(), 0.01); - assertEquals(50, carrierShipment.getSize()); + assertEquals("PickupLocationId", carrierShipment.getPickupLinkId().toString()); + assertEquals(30.0, carrierShipment.getPickupDuration(), 0.01); + assertEquals(10.0, carrierShipment.getPickupStartsTimeWindow().getStart(), 0.01); + assertEquals(20.0, carrierShipment.getPickupStartsTimeWindow().getEnd(), 0.01); + assertEquals("DeliveryLocationId", carrierShipment.getDeliveryLinkId().toString()); + assertEquals(40.0, carrierShipment.getDeliveryDuration(), 0.01); + assertEquals(50.0, carrierShipment.getDeliveryStartsTimeWindow().getStart(), 0.01); + assertEquals(60.0, carrierShipment.getDeliveryStartsTimeWindow().getEnd(), 0.01); + assertEquals(50, carrierShipment.getDemand()); CarrierShipment carrierShipment2 = MatsimJspritFactory.createCarrierShipment(shipment); assertNotSame(carrierShipment, carrierShipment2); @@ -234,7 +234,7 @@ private Collection getJobsFrom(ScheduledTour sTour) { CarrierService carrierService = ((Tour.ServiceActivity) e) .getService(); Service service = Service.Builder.newInstance(carrierService.getId().toString()) - .setLocation(Location.newInstance(carrierService.getLocationLinkId().toString())).build(); + .setLocation(Location.newInstance(carrierService.getServiceLinkId().toString())).build(); services.add(service); } } @@ -333,10 +333,10 @@ void whenTransforming_matsimPlan2vehicleRouteSolution_itIsMadeCorrectly() { private ScheduledTour getMatsimServiceTour() { CarrierService s1 = CarrierService.Builder .newInstance(Id.create("serviceId", CarrierService.class), Id.create("to1", Link.class)) - .setCapacityDemand(20).build(); + .setDemand(20).build(); CarrierService s2 = CarrierService.Builder .newInstance(Id.create("serviceId2", CarrierService.class), Id.create("to2", Link.class)) - .setCapacityDemand(10).build(); + .setDemand(10).build(); CarrierVehicle matsimVehicle = getMatsimVehicle("matsimVehicle", "loc", getMatsimVehicleType()); double startTime = 15.0; Tour.Builder sTourBuilder = Tour.Builder.newInstance(Id.create("testTour", Tour.class)); @@ -391,8 +391,8 @@ private CarrierShipment getMatsimShipment(String id, String from, String to, int return CarrierShipment.Builder .newInstance(Id.create(id, CarrierShipment.class), Id.create(from, Link.class), Id.create(to, Link.class), size) - .setDeliveryServiceTime(30.0).setDeliveryTimeWindow(TimeWindow.newInstance(10.0, 20.0)) - .setPickupServiceTime(15.0).setPickupTimeWindow(TimeWindow.newInstance(1.0, 5.0)).build(); + .setDeliveryDuration(30.0).setDeliveryStartsTimeWindow(TimeWindow.newInstance(10.0, 20.0)) + .setPickupDuration(15.0).setPickupStartsTimeWindow(TimeWindow.newInstance(1.0, 5.0)).build(); } @Test @@ -503,11 +503,11 @@ private Carrier createCarrierWithServices() { carrier.setCarrierCapabilities(ccBuilder.build()); CarrierService carrierService1 = CarrierService.Builder .newInstance(Id.create("serviceId", CarrierService.class), Id.create("i(7,4)R", Link.class)) - .setCapacityDemand(20).setServiceDuration(10.0).build(); + .setDemand(20).setServiceDuration(10.0).build(); CarriersUtils.addService(carrier, carrierService1); CarrierService carrierService2 = CarrierService.Builder .newInstance(Id.create("serviceId2", CarrierService.class), Id.create("i(3,9)", Link.class)) - .setCapacityDemand(10).setServiceDuration(20.0).build(); + .setDemand(10).setServiceDuration(20.0).build(); CarriersUtils.addService(carrier, carrierService2); return carrier; } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/SkillsIT.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/SkillsIT.java index 7da556872c2..379fb15486c 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/SkillsIT.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/SkillsIT.java @@ -161,10 +161,10 @@ private void addShipmentsRequiringDifferentSkills(Scenario scenario) { carrierLocation, Id.createLinkId("i(10,10)R"), 1) - .setPickupTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) - .setPickupServiceTime(Time.parseTime("00:05:00")) - .setDeliveryTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) - .setDeliveryServiceTime(Time.parseTime("00:05:00")) + .setPickupStartsTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) + .setPickupDuration(Time.parseTime("00:05:00")) + .setDeliveryStartsTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) + .setDeliveryDuration(Time.parseTime("00:05:00")) .build(); CarriersUtils.addSkill(shipmentOne, "skill 1"); CarriersUtils.addShipment(carrier, shipmentOne); @@ -174,10 +174,10 @@ private void addShipmentsRequiringDifferentSkills(Scenario scenario) { carrierLocation, Id.createLinkId("i(10,10)R"), 1) - .setPickupTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) - .setPickupServiceTime(Time.parseTime("00:05:00")) - .setDeliveryTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) - .setDeliveryServiceTime(Time.parseTime("00:05:00")) + .setPickupStartsTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) + .setPickupDuration(Time.parseTime("00:05:00")) + .setDeliveryStartsTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) + .setDeliveryDuration(Time.parseTime("00:05:00")) .build(); CarriersUtils.addSkill(shipmentTwo, "skill 2"); CarriersUtils.addShipment(carrier, shipmentTwo); @@ -190,10 +190,10 @@ private void addShipmentsRequiringSameSkills(Scenario scenario) { carrierLocation, Id.createLinkId("i(10,10)R"), 1) - .setPickupTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) - .setPickupServiceTime(Time.parseTime("00:05:00")) - .setDeliveryTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) - .setDeliveryServiceTime(Time.parseTime("00:05:00")) + .setPickupStartsTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) + .setPickupDuration(Time.parseTime("00:05:00")) + .setDeliveryStartsTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) + .setDeliveryDuration(Time.parseTime("00:05:00")) .build(); CarriersUtils.addSkill(shipmentOne, "skill 1"); CarriersUtils.addShipment(carrier, shipmentOne); @@ -203,10 +203,10 @@ private void addShipmentsRequiringSameSkills(Scenario scenario) { carrierLocation, Id.createLinkId("i(10,10)R"), 1) - .setPickupTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) - .setPickupServiceTime(Time.parseTime("00:05:00")) - .setDeliveryTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) - .setDeliveryServiceTime(Time.parseTime("00:05:00")) + .setPickupStartsTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) + .setPickupDuration(Time.parseTime("00:05:00")) + .setDeliveryStartsTimeWindow(TimeWindow.newInstance(0.0, Time.parseTime("24:00:00"))) + .setDeliveryDuration(Time.parseTime("00:05:00")) .build(); CarriersUtils.addSkill(shipmentTwo, "skill 1"); CarriersUtils.addShipment(carrier, shipmentTwo); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControllerUtilsIT.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControllerUtilsIT.java index d7127bc80bf..249da6bf44b 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControllerUtilsIT.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControllerUtilsIT.java @@ -44,7 +44,6 @@ import org.matsim.freight.carriers.jsprit.NetworkRouter; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.*; -import org.matsim.vehicles.EngineInformation.FuelType; //TODO: length of routes (legs) AND end time of route are missing. /** @@ -286,16 +285,16 @@ private static CarrierShipment createMatsimShipment(String id, String from, Stri } return CarrierShipment.Builder.newInstance(shipmentId, fromLinkId, toLinkId, size) - .setDeliveryServiceTime(30.0) - .setDeliveryTimeWindow(TimeWindow.newInstance(0.0, 36000.0)) - .setPickupServiceTime(5.0) - .setPickupTimeWindow(TimeWindow.newInstance(0.0, 7200.0)) + .setDeliveryDuration(30.0) + .setDeliveryStartsTimeWindow(TimeWindow.newInstance(0.0, 36000.0)) + .setPickupDuration(5.0) + .setPickupStartsTimeWindow(TimeWindow.newInstance(0.0, 7200.0)) .build(); } private static CarrierService createMatsimService(String id, String to, int size) { return CarrierService.Builder.newInstance(Id.create(id, CarrierService.class), Id.create(to, Link.class)) - .setCapacityDemand(size) + .setDemand(size) .setServiceDuration(31.0) .setServiceStartTimeWindow(TimeWindow.newInstance(0.0, 36001.0)) .build(); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControllerUtilsTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControllerUtilsTest.java index 1896021e805..393f73088a3 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControllerUtilsTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControllerUtilsTest.java @@ -165,7 +165,7 @@ void numberOfInitialServicesIsCorrect() { int demandServices = 0; for (CarrierService carrierService : carrierWServices.getServices().values()) { - demandServices += carrierService.getCapacityDemand(); + demandServices += carrierService.getDemand(); } Assertions.assertEquals(4, demandServices); @@ -180,7 +180,7 @@ void numberOfInitialShipmentsIsCorrect() { Assertions.assertEquals(2, carrierWShipments.getShipments().size()); int demandShipments = 0; for (CarrierShipment carrierShipment : carrierWShipments.getShipments().values()) { - demandShipments += carrierShipment.getSize(); + demandShipments += carrierShipment.getDemand(); } Assertions.assertEquals(3, demandShipments); } @@ -192,7 +192,7 @@ void numberOfShipmentsFromCopiedShipmentsIsCorrect() { Assertions.assertEquals(2, carrierWShipmentsOnlyFromCarrierWShipments.getShipments().size()); int demandShipments = 0; for (CarrierShipment carrierShipment : carrierWShipmentsOnlyFromCarrierWServices.getShipments().values()) { - demandShipments += carrierShipment.getSize(); + demandShipments += carrierShipment.getDemand(); } Assertions.assertEquals(4, demandShipments); } @@ -204,7 +204,7 @@ void numberOfShipmentsFromConvertedServicesIsCorrect() { Assertions.assertEquals(2, carrierWShipmentsOnlyFromCarrierWServices.getShipments().size()); int demandShipments = 0; for (CarrierShipment carrierShipment : carrierWShipmentsOnlyFromCarrierWServices.getShipments().values()) { - demandShipments += carrierShipment.getSize(); + demandShipments += carrierShipment.getDemand(); } Assertions.assertEquals(4, demandShipments); } @@ -244,30 +244,30 @@ void copyingOfShipmentsIsDoneCorrectly() { if (carrierShipment1.getId() == Id.create("shipment1", CarrierShipment.class)) { System.out.println("Found Shipment1"); foundShipment1 = true; - Assertions.assertEquals(Id.createLinkId("i(1,0)"), carrierShipment1.getFrom()); - Assertions.assertEquals(Id.createLinkId("i(7,6)R"), carrierShipment1.getTo()); - Assertions.assertEquals(1, carrierShipment1.getSize()); - Assertions.assertEquals(30.0, carrierShipment1.getDeliveryServiceTime(), 0); - Assertions.assertEquals(3600.0, carrierShipment1.getDeliveryTimeWindow().getStart(), 0); - Assertions.assertEquals(36000.0, carrierShipment1.getDeliveryTimeWindow().getEnd(), 0); - Assertions.assertEquals(5.0, carrierShipment1.getPickupServiceTime(), 0); - Assertions.assertEquals(0.0, carrierShipment1.getPickupTimeWindow().getStart(), 0); - Assertions.assertEquals(7200.0, carrierShipment1.getPickupTimeWindow().getEnd(), 0); + Assertions.assertEquals(Id.createLinkId("i(1,0)"), carrierShipment1.getPickupLinkId()); + Assertions.assertEquals(Id.createLinkId("i(7,6)R"), carrierShipment1.getDeliveryLinkId()); + Assertions.assertEquals(1, carrierShipment1.getDemand()); + Assertions.assertEquals(30.0, carrierShipment1.getDeliveryDuration(), 0); + Assertions.assertEquals(3600.0, carrierShipment1.getDeliveryStartsTimeWindow().getStart(), 0); + Assertions.assertEquals(36000.0, carrierShipment1.getDeliveryStartsTimeWindow().getEnd(), 0); + Assertions.assertEquals(5.0, carrierShipment1.getPickupDuration(), 0); + Assertions.assertEquals(0.0, carrierShipment1.getPickupStartsTimeWindow().getStart(), 0); + Assertions.assertEquals(7200.0, carrierShipment1.getPickupStartsTimeWindow().getEnd(), 0); } CarrierShipment carrierShipment2 = CarriersUtils.getShipment(carrierWShipmentsOnlyFromCarrierWShipments, Id.create("shipment2", CarrierShipment.class)); assert carrierShipment2 != null; if (carrierShipment2.getId() == Id.create("shipment2", CarrierShipment.class)) { System.out.println("Found Shipment2"); foundShipment2 = true; - Assertions.assertEquals(Id.createLinkId("i(3,0)"), carrierShipment2.getFrom()); - Assertions.assertEquals(Id.createLinkId("i(3,7)"), carrierShipment2.getTo()); - Assertions.assertEquals(2, carrierShipment2.getSize()); - Assertions.assertEquals(30.0, carrierShipment2.getDeliveryServiceTime(), 0); - Assertions.assertEquals(3600.0, carrierShipment2.getDeliveryTimeWindow().getStart(), 0); - Assertions.assertEquals(36000.0, carrierShipment2.getDeliveryTimeWindow().getEnd(), 0); - Assertions.assertEquals(5.0, carrierShipment2.getPickupServiceTime(), 0); - Assertions.assertEquals(0.0, carrierShipment2.getPickupTimeWindow().getStart(), 0); - Assertions.assertEquals(7200.0, carrierShipment2.getPickupTimeWindow().getEnd(), 0); + Assertions.assertEquals(Id.createLinkId("i(3,0)"), carrierShipment2.getPickupLinkId()); + Assertions.assertEquals(Id.createLinkId("i(3,7)"), carrierShipment2.getDeliveryLinkId()); + Assertions.assertEquals(2, carrierShipment2.getDemand()); + Assertions.assertEquals(30.0, carrierShipment2.getDeliveryDuration(), 0); + Assertions.assertEquals(3600.0, carrierShipment2.getDeliveryStartsTimeWindow().getStart(), 0); + Assertions.assertEquals(36000.0, carrierShipment2.getDeliveryStartsTimeWindow().getEnd(), 0); + Assertions.assertEquals(5.0, carrierShipment2.getPickupDuration(), 0); + Assertions.assertEquals(0.0, carrierShipment2.getPickupStartsTimeWindow().getStart(), 0); + Assertions.assertEquals(7200.0, carrierShipment2.getPickupStartsTimeWindow().getEnd(), 0); } Assertions.assertTrue(foundShipment1, "Not found Shipment1 after copying"); Assertions.assertTrue(foundShipment2, "Not found Shipment2 after copying"); @@ -282,29 +282,29 @@ void convertionOfServicesIsDoneCorrectly() { assert carrierShipment1 != null; if (carrierShipment1.getId() == Id.create("Service1", CarrierShipment.class)) { foundService1 = true; - Assertions.assertEquals(Id.createLinkId("i(6,0)"), carrierShipment1.getFrom()); - Assertions.assertEquals(Id.createLinkId("i(3,9)"), carrierShipment1.getTo()); - Assertions.assertEquals(2, carrierShipment1.getSize()); - Assertions.assertEquals(31.0, carrierShipment1.getDeliveryServiceTime(), 0); - Assertions.assertEquals(3601.0, carrierShipment1.getDeliveryTimeWindow().getStart(), 0); - Assertions.assertEquals(36001.0, carrierShipment1.getDeliveryTimeWindow().getEnd(), 0); - Assertions.assertEquals(0.0, carrierShipment1.getPickupServiceTime(), 0); - Assertions.assertEquals(0.0, carrierShipment1.getPickupTimeWindow().getStart(), 0); - Assertions.assertEquals(36001.0, carrierShipment1.getPickupTimeWindow().getEnd(), 0); + Assertions.assertEquals(Id.createLinkId("i(6,0)"), carrierShipment1.getPickupLinkId()); + Assertions.assertEquals(Id.createLinkId("i(3,9)"), carrierShipment1.getDeliveryLinkId()); + Assertions.assertEquals(2, carrierShipment1.getDemand()); + Assertions.assertEquals(31.0, carrierShipment1.getDeliveryDuration(), 0); + Assertions.assertEquals(3601.0, carrierShipment1.getDeliveryStartsTimeWindow().getStart(), 0); + Assertions.assertEquals(36001.0, carrierShipment1.getDeliveryStartsTimeWindow().getEnd(), 0); + Assertions.assertEquals(0.0, carrierShipment1.getPickupDuration(), 0); + Assertions.assertEquals(0.0, carrierShipment1.getPickupStartsTimeWindow().getStart(), 0); + Assertions.assertEquals(36001.0, carrierShipment1.getPickupStartsTimeWindow().getEnd(), 0); } CarrierShipment carrierShipment2 = CarriersUtils.getShipment(carrierWShipmentsOnlyFromCarrierWServices, Id.create("Service2", CarrierShipment.class)); assert carrierShipment2 != null; if (carrierShipment2.getId() == Id.create("Service2", CarrierShipment.class)) { foundService2 = true; - Assertions.assertEquals(Id.createLinkId("i(6,0)"), carrierShipment2.getFrom()); - Assertions.assertEquals(Id.createLinkId("i(4,9)"), carrierShipment2.getTo()); - Assertions.assertEquals(2, carrierShipment2.getSize()); - Assertions.assertEquals(31.0, carrierShipment2.getDeliveryServiceTime(), 0); - Assertions.assertEquals(3601.0, carrierShipment2.getDeliveryTimeWindow().getStart(), 0); - Assertions.assertEquals(36001.0, carrierShipment2.getDeliveryTimeWindow().getEnd(), 0); - Assertions.assertEquals(0.0, carrierShipment2.getPickupServiceTime(), 0); - Assertions.assertEquals(0.0, carrierShipment2.getPickupTimeWindow().getStart(), 0); - Assertions.assertEquals(36001.0, carrierShipment2.getPickupTimeWindow().getEnd(), 0); + Assertions.assertEquals(Id.createLinkId("i(6,0)"), carrierShipment2.getPickupLinkId()); + Assertions.assertEquals(Id.createLinkId("i(4,9)"), carrierShipment2.getDeliveryLinkId()); + Assertions.assertEquals(2, carrierShipment2.getDemand()); + Assertions.assertEquals(31.0, carrierShipment2.getDeliveryDuration(), 0); + Assertions.assertEquals(3601.0, carrierShipment2.getDeliveryStartsTimeWindow().getStart(), 0); + Assertions.assertEquals(36001.0, carrierShipment2.getDeliveryStartsTimeWindow().getEnd(), 0); + Assertions.assertEquals(0.0, carrierShipment2.getPickupDuration(), 0); + Assertions.assertEquals(0.0, carrierShipment2.getPickupStartsTimeWindow().getStart(), 0); + Assertions.assertEquals(36001.0, carrierShipment2.getPickupStartsTimeWindow().getEnd(), 0); } Assertions.assertTrue(foundService1, "Not found converted Service1 after converting"); Assertions.assertTrue(foundService2, "Not found converted Service2 after converting"); @@ -343,16 +343,16 @@ private static CarrierShipment createMatsimShipment(String id, String from, Stri } return CarrierShipment.Builder.newInstance(shipmentId, fromLinkId, toLinkId, size) - .setDeliveryServiceTime(30.0) - .setDeliveryTimeWindow(TimeWindow.newInstance(3600.0, 36000.0)) - .setPickupServiceTime(5.0) - .setPickupTimeWindow(TimeWindow.newInstance(0.0, 7200.0)) + .setDeliveryDuration(30.0) + .setDeliveryStartsTimeWindow(TimeWindow.newInstance(3600.0, 36000.0)) + .setPickupDuration(5.0) + .setPickupStartsTimeWindow(TimeWindow.newInstance(0.0, 7200.0)) .build(); } private static CarrierService createMatsimService(String id, String to, int size) { return CarrierService.Builder.newInstance(Id.create(id, CarrierService.class), Id.create(to, Link.class)) - .setCapacityDemand(size) + .setDemand(size) .setServiceDuration(31.0) .setServiceStartTimeWindow(TimeWindow.newInstance(3601.0, 36001.0)) .build(); diff --git a/contribs/freight/src/test/java/org/matsim/freight/logistics/examples/simulationTrackers/CollectionTrackerTest.java b/contribs/freight/src/test/java/org/matsim/freight/logistics/examples/simulationTrackers/CollectionTrackerTest.java index e72394b24ea..b1d60e9665a 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/logistics/examples/simulationTrackers/CollectionTrackerTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/logistics/examples/simulationTrackers/CollectionTrackerTest.java @@ -56,7 +56,6 @@ import org.matsim.freight.logistics.shipment.LspShipment; import org.matsim.freight.logistics.shipment.LspShipmentUtils; import org.matsim.testcases.MatsimTestUtils; -import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleType; import org.matsim.vehicles.VehicleUtils; @@ -238,7 +237,7 @@ public void testCollectionTracker() { if (element instanceof ServiceActivity activity) { scheduledCosts += activity.getService().getServiceDuration() * scheduledTour.getVehicle().getType().getCostInformation().getCostsPerSecond(); totalScheduledCosts += scheduledCosts; - totalScheduledWeight += activity.getService().getCapacityDemand(); + totalScheduledWeight += activity.getService().getDemand(); totalNumberOfScheduledShipments++; } } diff --git a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/CollectionLSPSchedulingTest.java b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/CollectionLSPSchedulingTest.java index 5e071b894d4..ba6d1fd35e7 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/CollectionLSPSchedulingTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/CollectionLSPSchedulingTest.java @@ -196,8 +196,8 @@ public void testCollectionLSPScheduling() { { assertInstanceOf(LSPTourEndEventHandler.class, eventHandlers.getFirst()); LSPTourEndEventHandler endHandler = (LSPTourEndEventHandler) eventHandlers.getFirst(); - assertSame(endHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(endHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(endHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(endHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(endHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(endHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(endHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); @@ -211,8 +211,8 @@ public void testCollectionLSPScheduling() { { assertInstanceOf(CollectionServiceEndEventHandler.class, eventHandlers.get(1)); CollectionServiceEndEventHandler serviceHandler = (CollectionServiceEndEventHandler) eventHandlers.get(1); - assertSame(serviceHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(serviceHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(serviceHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(serviceHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(serviceHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(serviceHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(serviceHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); diff --git a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/CompleteLSPSchedulingTest.java b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/CompleteLSPSchedulingTest.java index c4fd34c0fd3..11d49bd6c0b 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/CompleteLSPSchedulingTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/CompleteLSPSchedulingTest.java @@ -433,8 +433,8 @@ public void testCompletedLSPScheduling() { CarrierService service = entry.getKey(); LspShipment shipment = entry.getValue().lspShipment; LogisticChainElement element = entry.getValue().logisticChainElement; - assertSame(service.getLocationLinkId(), shipment.getFrom()); - assertEquals(service.getCapacityDemand(), shipment.getSize()); + assertSame(service.getServiceLinkId(), shipment.getFrom()); + assertEquals(service.getDemand(), shipment.getSize()); assertEquals(service.getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); boolean handledByTranshipmentHub = false; for (LogisticChainElement clientElement : reloadEventHandler.getTranshipmentHub().getClientElements()) { @@ -460,8 +460,8 @@ public void testCompletedLSPScheduling() { CarrierService service = entry.getKey(); LspShipment shipment = entry.getValue().lspShipment; LogisticChainElement element = entry.getValue().logisticChainElement; - assertSame(service.getLocationLinkId(), toLinkId); - assertEquals(service.getCapacityDemand(), shipment.getSize()); + assertSame(service.getServiceLinkId(), toLinkId); + assertEquals(service.getDemand(), shipment.getSize()); assertEquals(service.getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); boolean handledByTranshipmentHub = false; for (LogisticChainElement clientElement : reloadEventHandler.getTranshipmentHub().getClientElements()) { @@ -484,8 +484,8 @@ public void testCompletedLSPScheduling() { assertInstanceOf(LSPTourEndEventHandler.class, eventHandlers.getFirst()); LSPTourEndEventHandler endHandler = (LSPTourEndEventHandler) eventHandlers.getFirst(); - assertSame(endHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(endHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(endHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(endHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(endHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(endHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(endHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); @@ -502,8 +502,8 @@ public void testCompletedLSPScheduling() { //CollectionServiceEnd assertInstanceOf(CollectionServiceEndEventHandler.class, eventHandlers.get(1)); CollectionServiceEndEventHandler serviceHandler = (CollectionServiceEndEventHandler) eventHandlers.get(1); - assertSame(serviceHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(serviceHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(serviceHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(serviceHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(serviceHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(serviceHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(serviceHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); @@ -520,9 +520,9 @@ public void testCompletedLSPScheduling() { //MainRunStart assertInstanceOf(LSPTourStartEventHandler.class, eventHandlers.get(2)); LSPTourStartEventHandler mainRunStartHandler = (LSPTourStartEventHandler) eventHandlers.get(2); - assertSame(mainRunStartHandler.getCarrierService().getLocationLinkId(), toLinkId); + assertSame(mainRunStartHandler.getCarrierService().getServiceLinkId(), toLinkId); assertEquals(mainRunStartHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); - assertEquals(mainRunStartHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertEquals(mainRunStartHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(0, mainRunStartHandler.getCarrierService().getServiceStartTimeWindow().getStart(), 0.0); assertEquals(Integer.MAX_VALUE, mainRunStartHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), 0.0); assertSame(mainRunStartHandler.getLogisticChainElement(), planElements.get(4).getLogisticChainElement()); @@ -538,9 +538,9 @@ public void testCompletedLSPScheduling() { //MainRunEnd assertInstanceOf(LSPTourEndEventHandler.class, eventHandlers.get(3)); LSPTourEndEventHandler mainRunEndHandler = (LSPTourEndEventHandler) eventHandlers.get(3); - assertSame(mainRunEndHandler.getCarrierService().getLocationLinkId(), toLinkId); + assertSame(mainRunEndHandler.getCarrierService().getServiceLinkId(), toLinkId); assertEquals(mainRunEndHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); - assertEquals(mainRunEndHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertEquals(mainRunEndHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(0, mainRunEndHandler.getCarrierService().getServiceStartTimeWindow().getStart(), 0.0); assertEquals(Integer.MAX_VALUE, mainRunEndHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), 0.0); assertSame(mainRunEndHandler.getLogisticChainElement(), planElements.get(4).getLogisticChainElement()); @@ -556,9 +556,9 @@ public void testCompletedLSPScheduling() { //DistributionRunStart assertInstanceOf(LSPTourStartEventHandler.class, eventHandlers.get(4)); LSPTourStartEventHandler lspTourStartEventHandler = (LSPTourStartEventHandler) eventHandlers.get(4); - assertSame(lspTourStartEventHandler.getCarrierService().getLocationLinkId(), shipment.getTo()); + assertSame(lspTourStartEventHandler.getCarrierService().getServiceLinkId(), shipment.getTo()); assertEquals(lspTourStartEventHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); - assertEquals(lspTourStartEventHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertEquals(lspTourStartEventHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(0, lspTourStartEventHandler.getCarrierService().getServiceStartTimeWindow().getStart(), 0.0); assertEquals(Integer.MAX_VALUE, lspTourStartEventHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), 0.0); assertSame(lspTourStartEventHandler.getLogisticChainElement(), planElements.get(8).getLogisticChainElement()); @@ -574,9 +574,9 @@ public void testCompletedLSPScheduling() { //DistributionServiceStart assertInstanceOf(DistributionServiceStartEventHandler.class, eventHandlers.get(5)); DistributionServiceStartEventHandler distributionServiceHandler = (DistributionServiceStartEventHandler) eventHandlers.get(5); - assertSame(distributionServiceHandler.getCarrierService().getLocationLinkId(), shipment.getTo()); + assertSame(distributionServiceHandler.getCarrierService().getServiceLinkId(), shipment.getTo()); assertEquals(distributionServiceHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); - assertEquals(distributionServiceHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertEquals(distributionServiceHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(0, distributionServiceHandler.getCarrierService().getServiceStartTimeWindow().getStart(), 0.0); assertEquals(Integer.MAX_VALUE, distributionServiceHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), 0.0); assertSame(distributionServiceHandler.getLogisticChainElement(), planElements.get(8).getLogisticChainElement()); diff --git a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/FirstReloadLSPSchedulingTest.java b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/FirstReloadLSPSchedulingTest.java index 3cead4c873c..76191192a70 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/FirstReloadLSPSchedulingTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/FirstReloadLSPSchedulingTest.java @@ -259,8 +259,8 @@ public void testFirstReloadLSPScheduling() { CarrierService service = entry.getKey(); LspShipment shipment = entry.getValue().lspShipment; LogisticChainElement element = entry.getValue().logisticChainElement; - assertSame(service.getLocationLinkId(), shipment.getFrom()); - assertEquals(service.getCapacityDemand(), shipment.getSize()); + assertSame(service.getServiceLinkId(), shipment.getFrom()); + assertEquals(service.getDemand(), shipment.getSize()); assertEquals(service.getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); boolean handledByTranshipmentHub = false; for (LogisticChainElement clientElement : reloadEventHandler.getTranshipmentHub().getClientElements()) { @@ -283,8 +283,8 @@ public void testFirstReloadLSPScheduling() { assertInstanceOf(LSPTourEndEventHandler.class, eventHandlers.getFirst()); LSPTourEndEventHandler endHandler = (LSPTourEndEventHandler) eventHandlers.getFirst(); - assertSame(endHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(endHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(endHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(endHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(endHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(endHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(endHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); @@ -296,8 +296,8 @@ public void testFirstReloadLSPScheduling() { assertInstanceOf(CollectionServiceEndEventHandler.class, eventHandlers.get(1)); CollectionServiceEndEventHandler serviceHandler = (CollectionServiceEndEventHandler) eventHandlers.get(1); - assertSame(serviceHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(serviceHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(serviceHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(serviceHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(serviceHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(serviceHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(serviceHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); diff --git a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MainRunLSPSchedulingTest.java b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MainRunLSPSchedulingTest.java index 4a39f6c6170..ce0a83639a8 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MainRunLSPSchedulingTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MainRunLSPSchedulingTest.java @@ -324,8 +324,8 @@ public void testMainRunLSPScheduling() { CarrierService service = entry.getKey(); LspShipment shipment = entry.getValue().lspShipment; LogisticChainElement element = entry.getValue().logisticChainElement; - assertSame(service.getLocationLinkId(), shipment.getFrom()); - assertEquals(service.getCapacityDemand(), shipment.getSize()); + assertSame(service.getServiceLinkId(), shipment.getFrom()); + assertEquals(service.getDemand(), shipment.getSize()); assertEquals(service.getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); boolean handledByTranshipmentHub = false; for (LogisticChainElement clientElement : reloadEventHandler.getTranshipmentHub().getClientElements()) { @@ -350,8 +350,8 @@ public void testMainRunLSPScheduling() { assertInstanceOf(LSPTourEndEventHandler.class, eventHandlers.getFirst()); LSPTourEndEventHandler endHandler = (LSPTourEndEventHandler) eventHandlers.getFirst(); - assertSame(endHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(endHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(endHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(endHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(endHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(endHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(endHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); @@ -368,8 +368,8 @@ public void testMainRunLSPScheduling() { //CollectionServiceEnd assertInstanceOf(CollectionServiceEndEventHandler.class, eventHandlers.get(1)); CollectionServiceEndEventHandler serviceHandler = (CollectionServiceEndEventHandler) eventHandlers.get(1); - assertSame(serviceHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(serviceHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(serviceHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(serviceHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(serviceHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(serviceHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(serviceHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); @@ -386,9 +386,9 @@ public void testMainRunLSPScheduling() { //MainRunTourStart assertInstanceOf(LSPTourStartEventHandler.class, eventHandlers.get(2)); LSPTourStartEventHandler mainRunStartHandler = (LSPTourStartEventHandler) eventHandlers.get(2); - assertSame(mainRunStartHandler.getCarrierService().getLocationLinkId(), toLinkId); + assertSame(mainRunStartHandler.getCarrierService().getServiceLinkId(), toLinkId); assertEquals(mainRunStartHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); - assertEquals(mainRunStartHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertEquals(mainRunStartHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(0, mainRunStartHandler.getCarrierService().getServiceStartTimeWindow().getStart(), 0.0); assertEquals(Integer.MAX_VALUE, mainRunStartHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), 0.0); assertSame(mainRunStartHandler.getLogisticChainElement(), planElements.get(4).getLogisticChainElement()); @@ -404,9 +404,9 @@ public void testMainRunLSPScheduling() { //MainRunTourEnd assertInstanceOf(LSPTourEndEventHandler.class, eventHandlers.get(3)); LSPTourEndEventHandler mainRunEndHandler = (LSPTourEndEventHandler) eventHandlers.get(3); - assertSame(mainRunEndHandler.getCarrierService().getLocationLinkId(), toLinkId); + assertSame(mainRunEndHandler.getCarrierService().getServiceLinkId(), toLinkId); assertEquals(mainRunEndHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); - assertEquals(mainRunEndHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertEquals(mainRunEndHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(0, mainRunEndHandler.getCarrierService().getServiceStartTimeWindow().getStart(), 0.0); assertEquals(Integer.MAX_VALUE, mainRunEndHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), 0.0); assertSame(mainRunEndHandler.getLogisticChainElement(), planElements.get(4).getLogisticChainElement()); diff --git a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsCollectionLSPSchedulingTest.java b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsCollectionLSPSchedulingTest.java index d30d608f985..d3fe9b5214d 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsCollectionLSPSchedulingTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsCollectionLSPSchedulingTest.java @@ -198,8 +198,8 @@ public void testCollectionLSPScheduling() { assertInstanceOf(LSPTourEndEventHandler.class, eventHandlers.getFirst()); LSPTourEndEventHandler endHandler = (LSPTourEndEventHandler) eventHandlers.getFirst(); - assertSame(endHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(endHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(endHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(endHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(endHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(endHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(endHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); @@ -211,8 +211,8 @@ public void testCollectionLSPScheduling() { assertInstanceOf(CollectionServiceEndEventHandler.class, eventHandlers.get(1)); CollectionServiceEndEventHandler serviceHandler = (CollectionServiceEndEventHandler) eventHandlers.get(1); - assertSame(serviceHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(serviceHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(serviceHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(serviceHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(serviceHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(serviceHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(serviceHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); diff --git a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsCompleteLSPSchedulingTest.java b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsCompleteLSPSchedulingTest.java index f27a1e08219..1a584b463b5 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsCompleteLSPSchedulingTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsCompleteLSPSchedulingTest.java @@ -436,8 +436,8 @@ public void testCompletedLSPScheduling() { CarrierService service = entry.getKey(); LspShipment shipment = entry.getValue().lspShipment; LogisticChainElement element = entry.getValue().logisticChainElement; - assertSame(service.getLocationLinkId(), shipment.getFrom()); - assertEquals(service.getCapacityDemand(), shipment.getSize()); + assertSame(service.getServiceLinkId(), shipment.getFrom()); + assertEquals(service.getDemand(), shipment.getSize()); assertEquals(service.getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); boolean handledByTranshipmentHub = false; for (LogisticChainElement clientElement : reloadEventHandler.getTranshipmentHub().getClientElements()) { @@ -463,8 +463,8 @@ public void testCompletedLSPScheduling() { CarrierService service = entry.getKey(); LspShipment shipment = entry.getValue().lspShipment; LogisticChainElement element = entry.getValue().logisticChainElement; - assertSame(service.getLocationLinkId(), toLinkId); - assertEquals(service.getCapacityDemand(), shipment.getSize()); + assertSame(service.getServiceLinkId(), toLinkId); + assertEquals(service.getDemand(), shipment.getSize()); assertEquals(service.getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); boolean handledByTranshipmentHub = false; for (LogisticChainElement clientElement : reloadEventHandler.getTranshipmentHub().getClientElements()) { @@ -487,8 +487,8 @@ public void testCompletedLSPScheduling() { assertInstanceOf(LSPTourEndEventHandler.class, eventHandlers.getFirst()); LSPTourEndEventHandler endHandler = (LSPTourEndEventHandler) eventHandlers.getFirst(); - assertSame(endHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(endHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(endHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(endHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(endHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(endHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(endHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); @@ -505,8 +505,8 @@ public void testCompletedLSPScheduling() { //CollectionServiceEnd assertInstanceOf(CollectionServiceEndEventHandler.class, eventHandlers.get(1)); CollectionServiceEndEventHandler serviceHandler = (CollectionServiceEndEventHandler) eventHandlers.get(1); - assertSame(serviceHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(serviceHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(serviceHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(serviceHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(serviceHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(serviceHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(serviceHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); @@ -523,9 +523,9 @@ public void testCompletedLSPScheduling() { //MainRunTourStart assertInstanceOf(LSPTourStartEventHandler.class, eventHandlers.get(2)); LSPTourStartEventHandler mainRunStartHandler = (LSPTourStartEventHandler) eventHandlers.get(2); - assertSame(mainRunStartHandler.getCarrierService().getLocationLinkId(), toLinkId); + assertSame(mainRunStartHandler.getCarrierService().getServiceLinkId(), toLinkId); assertEquals(mainRunStartHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); - assertEquals(mainRunStartHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertEquals(mainRunStartHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(0, mainRunStartHandler.getCarrierService().getServiceStartTimeWindow().getStart(), 0.0); assertEquals(Integer.MAX_VALUE, mainRunStartHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), 0.0); assertSame(mainRunStartHandler.getLogisticChainElement(), planElements.get(4).getLogisticChainElement()); @@ -541,9 +541,9 @@ public void testCompletedLSPScheduling() { //MainRunTourEnd assertInstanceOf(LSPTourEndEventHandler.class, eventHandlers.get(3)); LSPTourEndEventHandler mainRunEndHandler = (LSPTourEndEventHandler) eventHandlers.get(3); - assertSame(mainRunEndHandler.getCarrierService().getLocationLinkId(), toLinkId); + assertSame(mainRunEndHandler.getCarrierService().getServiceLinkId(), toLinkId); assertEquals(mainRunEndHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); - assertEquals(mainRunEndHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertEquals(mainRunEndHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(0, mainRunEndHandler.getCarrierService().getServiceStartTimeWindow().getStart(), 0.0); assertEquals(Integer.MAX_VALUE, mainRunEndHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), 0.0); assertSame(mainRunEndHandler.getLogisticChainElement(), planElements.get(4).getLogisticChainElement()); @@ -559,9 +559,9 @@ public void testCompletedLSPScheduling() { //DistributionTourStart assertInstanceOf(LSPTourStartEventHandler.class, eventHandlers.get(4)); LSPTourStartEventHandler lspTourStartEventHandler = (LSPTourStartEventHandler) eventHandlers.get(4); - assertSame(lspTourStartEventHandler.getCarrierService().getLocationLinkId(), shipment.getTo()); + assertSame(lspTourStartEventHandler.getCarrierService().getServiceLinkId(), shipment.getTo()); assertEquals(lspTourStartEventHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); - assertEquals(lspTourStartEventHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertEquals(lspTourStartEventHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(0, lspTourStartEventHandler.getCarrierService().getServiceStartTimeWindow().getStart(), 0.0); assertEquals(Integer.MAX_VALUE, lspTourStartEventHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), 0.0); assertSame(lspTourStartEventHandler.getLogisticChainElement(), planElements.get(8).getLogisticChainElement()); @@ -577,9 +577,9 @@ public void testCompletedLSPScheduling() { //DistributionServiceStart assertInstanceOf(DistributionServiceStartEventHandler.class, eventHandlers.get(5)); DistributionServiceStartEventHandler distributionServiceHandler = (DistributionServiceStartEventHandler) eventHandlers.get(5); - assertSame(distributionServiceHandler.getCarrierService().getLocationLinkId(), shipment.getTo()); + assertSame(distributionServiceHandler.getCarrierService().getServiceLinkId(), shipment.getTo()); assertEquals(distributionServiceHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); - assertEquals(distributionServiceHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertEquals(distributionServiceHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(0, distributionServiceHandler.getCarrierService().getServiceStartTimeWindow().getStart(), 0.0); assertEquals(Integer.MAX_VALUE, distributionServiceHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), 0.0); assertSame(distributionServiceHandler.getLogisticChainElement(), planElements.get(8).getLogisticChainElement()); diff --git a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsFirstReloadLSPSchedulingTest.java b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsFirstReloadLSPSchedulingTest.java index e1661887039..4d41d635e10 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsFirstReloadLSPSchedulingTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsFirstReloadLSPSchedulingTest.java @@ -258,8 +258,8 @@ public void testFirstReloadLSPScheduling() { CarrierService service = entry.getKey(); LspShipment shipment = entry.getValue().lspShipment; LogisticChainElement element = entry.getValue().logisticChainElement; - assertSame(service.getLocationLinkId(), shipment.getFrom()); - assertEquals(service.getCapacityDemand(), shipment.getSize()); + assertSame(service.getServiceLinkId(), shipment.getFrom()); + assertEquals(service.getDemand(), shipment.getSize()); assertEquals(service.getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); boolean handledByTranshipmentHub = false; for (LogisticChainElement clientElement : reloadEventHandler.getTranshipmentHub().getClientElements()) { @@ -282,8 +282,8 @@ public void testFirstReloadLSPScheduling() { assertInstanceOf(LSPTourEndEventHandler.class, eventHandlers.getFirst()); LSPTourEndEventHandler endHandler = (LSPTourEndEventHandler) eventHandlers.getFirst(); - assertSame(endHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(endHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(endHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(endHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(endHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(endHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(endHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); @@ -295,8 +295,8 @@ public void testFirstReloadLSPScheduling() { assertInstanceOf(CollectionServiceEndEventHandler.class, eventHandlers.get(1)); CollectionServiceEndEventHandler serviceHandler = (CollectionServiceEndEventHandler) eventHandlers.get(1); - assertSame(serviceHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(serviceHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(serviceHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(serviceHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(serviceHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(serviceHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(serviceHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); diff --git a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsMainRunLSPSchedulingTest.java b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsMainRunLSPSchedulingTest.java index c9811f9e03d..b63c6d854d4 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsMainRunLSPSchedulingTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsMainRunLSPSchedulingTest.java @@ -222,16 +222,16 @@ public void initialize() { @Test public void testMainRunLSPScheduling() { - + /*for(LSPShipment shipment : lsp.getShipments()) { ArrayList scheduleElements = new ArrayList(shipment.getSchedule().getPlanElements().values()); Collections.sort(scheduleElements, new AbstractShipmentPlanElementComparator()); - + System.out.println(); for(int i = 0; i < shipment.getSchedule().getPlanElements().size(); i++) { System.out.println("Scheduled: " + scheduleElements.get(i).getSolutionElement().getId() + " " + scheduleElements.get(i).getResourceId() +" "+ scheduleElements.get(i).getElementType() + " Start: " + scheduleElements.get(i).getStartTime() + " End: " + scheduleElements.get(i).getEndTime()); } - System.out.println(); + System.out.println(); }*/ @@ -324,8 +324,8 @@ public void testMainRunLSPScheduling() { CarrierService service = entry.getKey(); LspShipment shipment = entry.getValue().lspShipment; LogisticChainElement element = entry.getValue().logisticChainElement; - assertSame(service.getLocationLinkId(), shipment.getFrom()); - assertEquals(service.getCapacityDemand(), shipment.getSize()); + assertSame(service.getServiceLinkId(), shipment.getFrom()); + assertEquals(service.getDemand(), shipment.getSize()); assertEquals(service.getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); boolean handledByTranshipmentHub = false; for (LogisticChainElement clientElement : reloadEventHandler.getTranshipmentHub().getClientElements()) { @@ -350,8 +350,8 @@ public void testMainRunLSPScheduling() { assertInstanceOf(LSPTourEndEventHandler.class, eventHandlers.getFirst()); LSPTourEndEventHandler endHandler = (LSPTourEndEventHandler) eventHandlers.getFirst(); - assertSame(endHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(endHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(endHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(endHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(endHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(endHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(endHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); @@ -368,8 +368,8 @@ public void testMainRunLSPScheduling() { //CollectionServiceEnd assertInstanceOf(CollectionServiceEndEventHandler.class, eventHandlers.get(1)); CollectionServiceEndEventHandler serviceHandler = (CollectionServiceEndEventHandler) eventHandlers.get(1); - assertSame(serviceHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(serviceHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(serviceHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(serviceHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(serviceHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(serviceHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(serviceHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); @@ -386,9 +386,9 @@ public void testMainRunLSPScheduling() { //MainRunTourStart assertInstanceOf(LSPTourStartEventHandler.class, eventHandlers.get(2)); LSPTourStartEventHandler mainRunStartHandler = (LSPTourStartEventHandler) eventHandlers.get(2); - assertSame(mainRunStartHandler.getCarrierService().getLocationLinkId(), toLinkId); + assertSame(mainRunStartHandler.getCarrierService().getServiceLinkId(), toLinkId); assertEquals(mainRunStartHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); - assertEquals(mainRunStartHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertEquals(mainRunStartHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(0, mainRunStartHandler.getCarrierService().getServiceStartTimeWindow().getStart(), 0.0); assertEquals(Integer.MAX_VALUE, mainRunStartHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), 0.0); assertSame(mainRunStartHandler.getLogisticChainElement(), planElements.get(4).getLogisticChainElement()); @@ -404,9 +404,9 @@ public void testMainRunLSPScheduling() { //MainRunEnd assertInstanceOf(LSPTourEndEventHandler.class, eventHandlers.get(3)); LSPTourEndEventHandler mainRunEndHandler = (LSPTourEndEventHandler) eventHandlers.get(3); - assertSame(mainRunEndHandler.getCarrierService().getLocationLinkId(), toLinkId); + assertSame(mainRunEndHandler.getCarrierService().getServiceLinkId(), toLinkId); assertEquals(mainRunEndHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); - assertEquals(mainRunEndHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertEquals(mainRunEndHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(0, mainRunEndHandler.getCarrierService().getServiceStartTimeWindow().getStart(), 0.0); assertEquals(Integer.MAX_VALUE, mainRunEndHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), 0.0); assertSame(mainRunEndHandler.getLogisticChainElement(), planElements.get(4).getLogisticChainElement()); diff --git a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsSecondReloadLSPSchedulingTest.java b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsSecondReloadLSPSchedulingTest.java index 23ee9f61e86..03f374b15f0 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsSecondReloadLSPSchedulingTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/MultipleShipmentsSecondReloadLSPSchedulingTest.java @@ -251,14 +251,14 @@ public void initialize() { @Test public void testSecondReloadLSPScheduling() { - + /*for(LSPShipment shipment : lsp.getShipments()) { ArrayList elementList = new ArrayList(shipment.getSchedule().getPlanElements().values()); Collections.sort(elementList, new AbstractShipmentPlanElementComparator()); System.out.println(); for(AbstractShipmentPlanElement element : elementList) { - System.out.println(element.getSolutionElement().getId() + " " + element.getResourceId() + " " + element.getElementType() + " " + element.getStartTime() + " " + element.getEndTime()); - } + System.out.println(element.getSolutionElement().getId() + " " + element.getResourceId() + " " + element.getElementType() + " " + element.getStartTime() + " " + element.getEndTime()); + } System.out.println(); }*/ @@ -368,8 +368,8 @@ public void testSecondReloadLSPScheduling() { CarrierService service = entry.getKey(); LspShipment shipment = entry.getValue().lspShipment; LogisticChainElement element = entry.getValue().logisticChainElement; - assertSame(service.getLocationLinkId(), shipment.getFrom()); - assertEquals(service.getCapacityDemand(), shipment.getSize()); + assertSame(service.getServiceLinkId(), shipment.getFrom()); + assertEquals(service.getDemand(), shipment.getSize()); assertEquals(service.getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); boolean handledByTranshipmentHub = false; for (LogisticChainElement clientElement : @@ -400,8 +400,8 @@ public void testSecondReloadLSPScheduling() { CarrierService service = entry.getKey(); LspShipment shipment = entry.getValue().lspShipment; LogisticChainElement element = entry.getValue().logisticChainElement; - assertSame(service.getLocationLinkId(), toLinkId); - assertEquals(service.getCapacityDemand(), shipment.getSize()); + assertSame(service.getServiceLinkId(), toLinkId); + assertEquals(service.getDemand(), shipment.getSize()); assertEquals(service.getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); boolean handledByTranshipmentHub = false; for (LogisticChainElement clientElement : reloadEventHandler.getTranshipmentHub().getClientElements()) { @@ -430,8 +430,8 @@ public void testSecondReloadLSPScheduling() { { assertInstanceOf(LSPTourEndEventHandler.class, eventHandlers.getFirst()); LSPTourEndEventHandler collectionEndHandler = (LSPTourEndEventHandler) eventHandlers.getFirst(); - assertSame(collectionEndHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(collectionEndHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(collectionEndHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(collectionEndHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(collectionEndHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(collectionEndHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(collectionEndHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); @@ -449,8 +449,8 @@ public void testSecondReloadLSPScheduling() { {//CollectionServiceEnd assertInstanceOf(CollectionServiceEndEventHandler.class, eventHandlers.get(1)); CollectionServiceEndEventHandler collectionServiceHandler = (CollectionServiceEndEventHandler) eventHandlers.get(1); - assertSame(collectionServiceHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(collectionServiceHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(collectionServiceHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(collectionServiceHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(collectionServiceHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(collectionServiceHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(collectionServiceHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); @@ -468,9 +468,9 @@ public void testSecondReloadLSPScheduling() { {//MainRunStart assertInstanceOf(LSPTourStartEventHandler.class, eventHandlers.get(2)); LSPTourStartEventHandler mainRunStartHandler = (LSPTourStartEventHandler) eventHandlers.get(2); - assertSame(mainRunStartHandler.getCarrierService().getLocationLinkId(), toLinkId); + assertSame(mainRunStartHandler.getCarrierService().getServiceLinkId(), toLinkId); assertEquals(mainRunStartHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); - assertEquals(mainRunStartHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertEquals(mainRunStartHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(0, mainRunStartHandler.getCarrierService().getServiceStartTimeWindow().getStart(), 0.0); assertEquals(Integer.MAX_VALUE, mainRunStartHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), 0.0); assertSame(mainRunStartHandler.getLogisticChainElement(), planElements.get(4).getLogisticChainElement()); @@ -487,9 +487,9 @@ public void testSecondReloadLSPScheduling() { {//MainRunEnd assertInstanceOf(LSPTourEndEventHandler.class, eventHandlers.get(3)); LSPTourEndEventHandler mainRunEndHandler = (LSPTourEndEventHandler) eventHandlers.get(3); - assertSame(mainRunEndHandler.getCarrierService().getLocationLinkId(), toLinkId); + assertSame(mainRunEndHandler.getCarrierService().getServiceLinkId(), toLinkId); assertEquals(mainRunEndHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); - assertEquals(mainRunEndHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertEquals(mainRunEndHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(0, mainRunEndHandler.getCarrierService().getServiceStartTimeWindow().getStart(), 0.0); assertEquals(Integer.MAX_VALUE, mainRunEndHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), 0.0); assertSame(mainRunEndHandler.getLogisticChainElement(), planElements.get(4).getLogisticChainElement()); diff --git a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/SecondReloadLSPSchedulingTest.java b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/SecondReloadLSPSchedulingTest.java index 6a37cd65697..66a30fa10d4 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/SecondReloadLSPSchedulingTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/logistics/resourceImplementations/SecondReloadLSPSchedulingTest.java @@ -368,8 +368,8 @@ public void testSecondReloadLSPScheduling() { CarrierService service = entry.getKey(); LspShipment shipment = entry.getValue().lspShipment; LogisticChainElement element = entry.getValue().logisticChainElement; - assertSame(service.getLocationLinkId(), shipment.getFrom()); - assertEquals(service.getCapacityDemand(), shipment.getSize()); + assertSame(service.getServiceLinkId(), shipment.getFrom()); + assertEquals(service.getDemand(), shipment.getSize()); assertEquals(service.getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); boolean handledByTranshipmentHub = false; for (LogisticChainElement clientElement : @@ -406,8 +406,8 @@ public void testSecondReloadLSPScheduling() { CarrierService service = entry.getKey(); LspShipment shipment = entry.getValue().lspShipment; LogisticChainElement element = entry.getValue().logisticChainElement; - assertSame(service.getLocationLinkId(), toLinkId); - assertEquals(service.getCapacityDemand(), shipment.getSize()); + assertSame(service.getServiceLinkId(), toLinkId); + assertEquals(service.getDemand(), shipment.getSize()); assertEquals(service.getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); boolean handledByTranshipmentHub = false; for (LogisticChainElement clientElement : @@ -437,8 +437,8 @@ public void testSecondReloadLSPScheduling() { {//CollectionTourEnd assertInstanceOf(LSPTourEndEventHandler.class, eventHandlers.getFirst()); LSPTourEndEventHandler collectionEndHandler = (LSPTourEndEventHandler) eventHandlers.getFirst(); - assertSame(collectionEndHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(collectionEndHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(collectionEndHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(collectionEndHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(collectionEndHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(collectionEndHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(collectionEndHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); @@ -456,8 +456,8 @@ public void testSecondReloadLSPScheduling() { {//CollectionServiceEnd assertInstanceOf(CollectionServiceEndEventHandler.class, eventHandlers.get(1)); CollectionServiceEndEventHandler collectionServiceHandler = (CollectionServiceEndEventHandler) eventHandlers.get(1); - assertSame(collectionServiceHandler.getCarrierService().getLocationLinkId(), shipment.getFrom()); - assertEquals(collectionServiceHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertSame(collectionServiceHandler.getCarrierService().getServiceLinkId(), shipment.getFrom()); + assertEquals(collectionServiceHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(collectionServiceHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); assertEquals(collectionServiceHandler.getCarrierService().getServiceStartTimeWindow().getStart(), shipment.getPickupTimeWindow().getStart(), 0.0); assertEquals(collectionServiceHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), shipment.getPickupTimeWindow().getEnd(), 0.0); @@ -475,9 +475,9 @@ public void testSecondReloadLSPScheduling() { {//MainRunStart assertInstanceOf(LSPTourStartEventHandler.class, eventHandlers.get(2)); LSPTourStartEventHandler mainRunStartHandler = (LSPTourStartEventHandler) eventHandlers.get(2); - assertSame(mainRunStartHandler.getCarrierService().getLocationLinkId(), toLinkId); + assertSame(mainRunStartHandler.getCarrierService().getServiceLinkId(), toLinkId); assertEquals(mainRunStartHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); - assertEquals(mainRunStartHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertEquals(mainRunStartHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(0, mainRunStartHandler.getCarrierService().getServiceStartTimeWindow().getStart(), 0.0); assertEquals(Integer.MAX_VALUE, mainRunStartHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), 0.0); assertSame(mainRunStartHandler.getLogisticChainElement(), planElements.get(4).getLogisticChainElement()); @@ -494,9 +494,9 @@ public void testSecondReloadLSPScheduling() { {//MainRunEnd assertInstanceOf(LSPTourEndEventHandler.class, eventHandlers.get(3)); LSPTourEndEventHandler mainRunEndHandler = (LSPTourEndEventHandler) eventHandlers.get(3); - assertSame(mainRunEndHandler.getCarrierService().getLocationLinkId(), toLinkId); + assertSame(mainRunEndHandler.getCarrierService().getServiceLinkId(), toLinkId); assertEquals(mainRunEndHandler.getCarrierService().getServiceDuration(), shipment.getDeliveryServiceTime(), 0.0); - assertEquals(mainRunEndHandler.getCarrierService().getCapacityDemand(), shipment.getSize()); + assertEquals(mainRunEndHandler.getCarrierService().getDemand(), shipment.getSize()); assertEquals(0, mainRunEndHandler.getCarrierService().getServiceStartTimeWindow().getStart(), 0.0); assertEquals(Integer.MAX_VALUE, mainRunEndHandler.getCarrierService().getServiceStartTimeWindow().getEnd(), 0.0); assertSame(mainRunEndHandler.getLogisticChainElement(), planElements.get(4).getLogisticChainElement()); diff --git a/contribs/freight/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runServiceEventTest/Load_perVehicle.tsv b/contribs/freight/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runServiceEventTest/Load_perVehicle.tsv index a1e0058ce5b..3d861e42d95 100644 --- a/contribs/freight/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runServiceEventTest/Load_perVehicle.tsv +++ b/contribs/freight/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runServiceEventTest/Load_perVehicle.tsv @@ -1 +1 @@ -vehicleId vehicleTypeId capacity maxLoad load state during tour +vehicleId vehicleTypeId capacity maxLoad maxLoadPercentage handledDemand load state during tour diff --git a/contribs/freight/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runShipmentEventTest/Load_perVehicle.tsv b/contribs/freight/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runShipmentEventTest/Load_perVehicle.tsv index d61ddd36308..4216eeed0f3 100644 --- a/contribs/freight/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runShipmentEventTest/Load_perVehicle.tsv +++ b/contribs/freight/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/runShipmentEventTest/Load_perVehicle.tsv @@ -1,2 +1,2 @@ -vehicleId vehicleTypeId capacity maxLoad load state during tour -freight_carrier1_veh_freight_carrier1_veh_heavyVehicle_1_1 heavy 50.0 26 [3, 8, 18, 25, 26, 23, 13, 12, 7, 0] +vehicleId vehicleTypeId capacity maxLoad maxLoadPercentage handledDemand load state during tour +freight_carrier1_veh_freight_carrier1_veh_heavyVehicle_1_1 heavy 50.0 26 52.0 26 [3, 8, 18, 25, 26, 23, 13, 12, 7, 0] diff --git a/contribs/freightreceiver/src/main/java/org/matsim/freight/receiver/ReceiverControlerListener.java b/contribs/freightreceiver/src/main/java/org/matsim/freight/receiver/ReceiverControlerListener.java index 852452663a6..a35dddecc24 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/freight/receiver/ReceiverControlerListener.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/freight/receiver/ReceiverControlerListener.java @@ -178,7 +178,7 @@ private void linkReceiverTimeWindowToCarrierTourPosition() throws IOException { String shipmentId = act.getShipment().getId().toString(); if (act.getActivityType().equalsIgnoreCase("delivery")) { - Id linkId = act.getShipment().getTo(); + Id linkId = act.getShipment().getDeliveryLinkId(); if (!receiverLinkMap.containsKey(linkId)) { LOG.error("Woops, the carrier is delivering a shipment to an unknown receiver!"); throw new RuntimeException("Don't know to whom delivery is."); diff --git a/contribs/freightreceiver/src/main/java/org/matsim/freight/receiver/ReceiverTriggersCarrierReplanningListener.java b/contribs/freightreceiver/src/main/java/org/matsim/freight/receiver/ReceiverTriggersCarrierReplanningListener.java index 2b8c4a6dfb9..28820157125 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/freight/receiver/ReceiverTriggersCarrierReplanningListener.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/freight/receiver/ReceiverTriggersCarrierReplanningListener.java @@ -81,12 +81,12 @@ public void notifyIterationStarts(IterationStartsEvent event) { order.getReceiver().getLinkId(), (int) (Math.round(order.getDailyOrderQuantity()*order.getProduct().getProductType().getRequiredCapacity())) ); CarrierShipment newShipment = builder - .setDeliveryServiceTime( order.getServiceDuration() ) - .setDeliveryTimeWindow( receiverPlan.getTimeWindows().get( 0 ) ) + .setDeliveryDuration( order.getServiceDuration() ) + .setDeliveryStartsTimeWindow( receiverPlan.getTimeWindows().get( 0 ) ) // TODO This only looks at the FIRST time window. This may need revision once we handle multiple // time windows. .build(); - if (newShipment.getSize() != 0) { + if (newShipment.getDemand() != 0) { receiverOrder.getCarrier().getShipments().put(newShipment.getId(), newShipment ); } } diff --git a/contribs/freightreceiver/src/main/java/org/matsim/freight/receiver/run/chessboard/ReceiverChessboardScenario.java b/contribs/freightreceiver/src/main/java/org/matsim/freight/receiver/run/chessboard/ReceiverChessboardScenario.java index fd036695370..34b74c242d4 100644 --- a/contribs/freightreceiver/src/main/java/org/matsim/freight/receiver/run/chessboard/ReceiverChessboardScenario.java +++ b/contribs/freightreceiver/src/main/java/org/matsim/freight/receiver/run/chessboard/ReceiverChessboardScenario.java @@ -228,8 +228,8 @@ public static void convertReceiverOrdersToInitialCarrierShipments(Carriers carri LOG.warn("Multiple time windows set. Only the first is used"); } - CarrierShipment shipment = shpBuilder.setDeliveryServiceTime(order.getServiceDuration()) - .setDeliveryTimeWindow(receiverPlan.getTimeWindows().get(0)) + CarrierShipment shipment = shpBuilder.setDeliveryDuration(order.getServiceDuration()) + .setDeliveryStartsTimeWindow(receiverPlan.getTimeWindows().get(0)) .build(); carriers.getCarriers().get(receiverOrder.getCarrierId()).getShipments().put(shipment.getId(), shipment); } diff --git a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/InformedModeChoiceConfigGroup.java b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/InformedModeChoiceConfigGroup.java index 709de1e45ba..76c9e429e0a 100644 --- a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/InformedModeChoiceConfigGroup.java +++ b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/InformedModeChoiceConfigGroup.java @@ -43,7 +43,7 @@ public class InformedModeChoiceConfigGroup extends ReflectiveConfigGroup { @Parameter @Comment("Require that new plan modes are always different from the current one.") - private boolean requireDifferentModes = true; + private boolean requireDifferentModes = false; @Parameter @Comment("Defines how constraint violations are handled.") diff --git a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/InformedModeChoiceModule.java b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/InformedModeChoiceModule.java index e681025ef92..6c422644a14 100644 --- a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/InformedModeChoiceModule.java +++ b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/InformedModeChoiceModule.java @@ -6,6 +6,8 @@ import com.google.inject.TypeLiteral; import com.google.inject.multibindings.MapBinder; import com.google.inject.multibindings.Multibinder; +import org.matsim.core.config.Config; +import org.matsim.core.config.groups.ReplanningConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.listener.ControlerListener; import org.matsim.core.router.PlanRouter; @@ -13,20 +15,14 @@ import org.matsim.core.utils.timing.TimeInterpretation; import org.matsim.facilities.ActivityFacilities; import org.matsim.modechoice.constraints.TripConstraint; -import org.matsim.modechoice.estimators.ActivityEstimator; -import org.matsim.modechoice.estimators.FixedCostsEstimator; -import org.matsim.modechoice.estimators.LegEstimator; -import org.matsim.modechoice.estimators.TripEstimator; +import org.matsim.modechoice.estimators.*; import org.matsim.modechoice.pruning.CandidatePruner; import org.matsim.modechoice.replanning.*; import org.matsim.modechoice.search.BestChoiceGenerator; import org.matsim.modechoice.search.SingleTripChoicesGenerator; import org.matsim.modechoice.search.TopKChoicesGenerator; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; +import java.util.*; /** * The main and only module needed to install to use informed mode choice functionality. @@ -35,12 +31,12 @@ */ public final class InformedModeChoiceModule extends AbstractModule { - public static String SELECT_BEST_K_PLAN_MODES_STRATEGY = "SelectBestKPlanModes"; + public final static String SELECT_BEST_K_PLAN_MODES_STRATEGY = "SelectBestKPlanModes"; - public static String SELECT_SINGLE_TRIP_MODE_STRATEGY = "SelectSingleTripMode"; + public final static String SELECT_SINGLE_TRIP_MODE_STRATEGY = "SelectSingleTripMode"; - public static String SELECT_SUBTOUR_MODE_STRATEGY = "SelectSubtourMode"; - public static String RANDOM_SUBTOUR_MODE_STRATEGY = "RandomSubtourMode"; + public final static String SELECT_SUBTOUR_MODE_STRATEGY = "SelectSubtourMode"; + public final static String RANDOM_SUBTOUR_MODE_STRATEGY = "RandomSubtourMode"; private final Builder builder; @@ -49,6 +45,33 @@ private InformedModeChoiceModule(Builder builder) { this.builder = builder; } + /** + * Replaces a strategy in the config. Can be used to enable one of the strategies in this module programmatically. + */ + public static void replaceReplanningStrategy(Config config, String subpopulation, + String existing, String replacement) { + + // Copy list because it is unmodifiable + List strategies = new ArrayList<>(config.replanning().getStrategySettings()); + List found = strategies.stream() + .filter(s -> s.getSubpopulation().equals(subpopulation)) + .filter(s -> s.getStrategyName().equals(existing)) + .toList(); + + if (found.isEmpty()) + throw new IllegalArgumentException("No strategy %s found for subpopulation %s".formatted(existing, subpopulation)); + + if (found.size() > 1) + throw new IllegalArgumentException("Multiple strategies %s found for subpopulation %s".formatted(existing, subpopulation)); + + ReplanningConfigGroup.StrategySettings old = found.getFirst(); + old.setStrategyName(replacement); + + // reset und set new strategies + config.replanning().clearStrategySettings(); + strategies.forEach(s -> config.replanning().addStrategySettings(s)); + } + public static Builder newBuilder() { return new Builder(); } @@ -56,14 +79,10 @@ public static Builder newBuilder() { @Override public void install() { - bindAllModes(builder.fixedCosts, new TypeLiteral<>() { - }); - bindAllModes(builder.legEstimators, new TypeLiteral<>() { - }); - bindAllModes(builder.tripEstimators, new TypeLiteral<>() { - }); - bindAllModes(builder.options, new TypeLiteral<>() { - }); + bindAllModes(builder.fixedCosts, new TypeLiteral<>() {}); + bindAllModes(builder.legEstimators, new TypeLiteral<>() {}); + bindAllModes(builder.tripEstimators, new TypeLiteral<>() {}); + bindAllModes(builder.options, new TypeLiteral<>() {}); bind(ActivityEstimator.class).to(builder.activityEstimator).in(Singleton.class); @@ -77,12 +96,16 @@ public void install() { bind(PlanModelService.class).asEagerSingleton(); addControlerListenerBinding().to(PlanModelService.class).asEagerSingleton(); - Multibinder> tcBinder = Multibinder.newSetBinder(binder(), new TypeLiteral<>() { - }); + Multibinder> tcBinder = Multibinder.newSetBinder(binder(), new TypeLiteral<>() {}); for (Class> c : builder.constraints) { tcBinder.addBinding().to(c).in(Singleton.class); } + Multibinder tripScores = Multibinder.newSetBinder(binder(), new TypeLiteral<>() {}); + for (Class c : builder.tripScoreEstimators) { + tripScores.addBinding().to(c).in(Singleton.class); + } + MapBinder pBinder = MapBinder.newMapBinder(binder(), String.class, CandidatePruner.class); for (Map.Entry e : builder.pruner.entrySet()) { CandidatePruner instance = e.getValue(); @@ -133,8 +156,7 @@ public PlanRouter planRouter(Provider tripRouter, ActivityFacilities private void bindAllModes(Map> map, TypeLiteral value) { // Ensure to bind to internal strings - MapBinder mapBinder = MapBinder.newMapBinder(binder(), new TypeLiteral<>() { - }, value); + MapBinder mapBinder = MapBinder.newMapBinder(binder(), new TypeLiteral<>() {}, value); for (Map.Entry> e : map.entrySet()) { Class clazz = e.getValue(); mapBinder.addBinding(e.getKey().intern()).to(clazz).in(Singleton.class); @@ -153,6 +175,7 @@ public static final class Builder { private final Map> options = new HashMap<>(); private final Set>> constraints = new LinkedHashSet<>(); + private final Set> tripScoreEstimators = new LinkedHashSet<>(); private final Map pruner = new HashMap<>(); @@ -230,6 +253,14 @@ public Builder withActivityEstimator(Class activity return this; } + /** + * Add general score estimator that is applied to all trips. + */ + public Builder withTripScoreEstimator(Class tripScoreEstimator) { + tripScoreEstimators.add(tripScoreEstimator); + return this; + } + /** * Builds the module, which can then be used with {@link #install()} */ diff --git a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/PlanModelService.java b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/PlanModelService.java index 85f80664279..93e0fb86c67 100644 --- a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/PlanModelService.java +++ b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/PlanModelService.java @@ -12,10 +12,7 @@ import org.matsim.core.router.TripStructureUtils; import org.matsim.core.utils.timing.TimeInterpretation; import org.matsim.modechoice.constraints.TripConstraint; -import org.matsim.modechoice.estimators.ActivityEstimator; -import org.matsim.modechoice.estimators.LegEstimator; -import org.matsim.modechoice.estimators.MinMaxEstimate; -import org.matsim.modechoice.estimators.TripEstimator; +import org.matsim.modechoice.estimators.*; import java.util.*; import java.util.function.Predicate; @@ -33,6 +30,9 @@ public final class PlanModelService implements StartupListener { @Inject private Map tripEstimator; + @Inject + private Set tripScores; + @Inject private Set> constraints; @@ -223,6 +223,10 @@ public void calculateEstimates(EstimatorContext context, PlanModel planModel) { // early or late arrival can also have an effect on the activity scores which is potentially considered here estimate += actEstimator.estimate(context, planModel.getStartTimes()[i] + tt, trip.getDestinationActivity()); + for (TripScoreEstimator tripScore : tripScores) { + estimate += tripScore.estimate(context, c.getMode(), trip); + } + values[i] = estimate; } } diff --git a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/commands/StrategyOptions.java b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/commands/StrategyOptions.java index 532c0995236..0b10695df86 100644 --- a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/commands/StrategyOptions.java +++ b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/commands/StrategyOptions.java @@ -154,8 +154,7 @@ public Module applyModule(Binder binder, Config config, Consumer config.replanning().addStrategySettings(s)); if (group.forceInnovation > 0) - binder.bind(new TypeLiteral>() { - }).toInstance(new ForceInnovationStrategyChooser<>(group.forceInnovation, ForceInnovationStrategyChooser.Permute.yes)); + binder.bind(new TypeLiteral>() {}).toInstance(new ForceInnovationStrategyChooser<>(group.forceInnovation, ForceInnovationStrategyChooser.Permute.yes)); InformedModeChoiceModule.Builder builder = InformedModeChoiceModule.newBuilder(); diff --git a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/estimators/TripScoreEstimator.java b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/estimators/TripScoreEstimator.java new file mode 100644 index 00000000000..d3105ce4514 --- /dev/null +++ b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/estimators/TripScoreEstimator.java @@ -0,0 +1,18 @@ +package org.matsim.modechoice.estimators; + +import org.matsim.core.router.TripStructureUtils; +import org.matsim.modechoice.EstimatorContext; + +/** + * This class can be used to estimate additional scores for a trip. + * These score are added to the existing estimates and might be independent of the mode. + */ +public interface TripScoreEstimator { + + /** + * Compute a score estimate for a trip. + */ + double estimate(EstimatorContext context, String mainMode, TripStructureUtils.Trip trip); + + +} diff --git a/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/pruning/PlanScoreThresholdPruner.java b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/pruning/PlanScoreThresholdPruner.java new file mode 100644 index 00000000000..e3446686715 --- /dev/null +++ b/contribs/informed-mode-choice/src/main/java/org/matsim/modechoice/pruning/PlanScoreThresholdPruner.java @@ -0,0 +1,23 @@ +package org.matsim.modechoice.pruning; + +import org.matsim.modechoice.PlanModel; + +/** + * Removes plans by a fixed utility threshold. + */ +public class PlanScoreThresholdPruner implements CandidatePruner { + + private final double threshold; + + /** + * Threshold to be applied on the best known plan estimate. Candidates with a larger difference to the best, than this threshold are discarded. + */ + public PlanScoreThresholdPruner(double threshold) { + this.threshold = threshold; + } + + @Override + public double planThreshold(PlanModel planModel) { + return threshold; + } +} diff --git a/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/search/TopKMinMaxTest.java b/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/search/TopKMinMaxTest.java index 04cfe9860e2..5490b076de8 100644 --- a/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/search/TopKMinMaxTest.java +++ b/contribs/informed-mode-choice/src/test/java/org/matsim/modechoice/search/TopKMinMaxTest.java @@ -217,6 +217,9 @@ else if (invocationOnMock.getArgument(0).equals(TransportMode.walk)) { Multibinder> tcBinder = Multibinder.newSetBinder(binder(), new TypeLiteral<>() { }); + Multibinder tEstBinder = Multibinder.newSetBinder(binder(), new TypeLiteral<>() { + }); + MapBinder fcBinder = MapBinder.newMapBinder(binder(), new TypeLiteral<>() { }, new TypeLiteral<>() { }); diff --git a/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseConfigGroup.java b/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseConfigGroup.java index c2c9bc8d039..0833d66f019 100644 --- a/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseConfigGroup.java +++ b/contribs/noise/src/main/java/org/matsim/contrib/noise/NoiseConfigGroup.java @@ -43,7 +43,7 @@ * Provides the parameters required to build a simple grid with some basic spatial functionality. * Provides the parameters required to compute noise emissions, immissions and damages. * - * @author ikaddoura + * @author ikaddoura, nkuehnel */ public final class NoiseConfigGroup extends ReflectiveConfigGroup { @@ -81,6 +81,7 @@ public final class NoiseConfigGroup extends ReflectiveConfigGroup { private static final String RECEIVER_POINT_GAP_CMT = "horizontal and vertical distance between receiver points in x-/y-coordinate units"; private static final String WRITE_OUTPUT_ITERATION_CMT = "Specifies how often the noise-specific output is written out."; private static final String CONSIDER_NOISE_BARRIERS = "considerNoiseBarriers"; + private static final String CONSIDER_NOISE_REFLECTION = "considerNoiseReflection"; private static final String NOISE_BARRIERS_GEOJSON_FILE = "noiseBarriersGeojsonPath"; private static final String NOISE_BARRIERS_SOURCE_CRS = "source coordinate reference system of noise barriers geojson file"; private static final String NETWORK_MODES_TO_IGNORE = "networkModesToIgnore"; @@ -142,6 +143,7 @@ public enum NoiseAllocationApproach { private double noiseTollFactor = 1.0; private boolean considerNoiseBarriers = false; + private boolean considerNoiseReflection = false; private String noiseBarriersFilePath = null; private String noiseBarriersSourceCrs = null; @@ -204,6 +206,7 @@ public Map getComments() { comments.put(NOISE_TOLL_FACTOR, "To be used for sensitivity analysis. Default: 1.0 (= the parameter has no effect)"); comments.put(CONSIDER_NOISE_BARRIERS, "Set to 'true' if noise barriers / building shielding should be considered. Otherwise set to 'false'."); + comments.put(CONSIDER_NOISE_REFLECTION, "Set to 'true' if reflections should be considered. Otherwise set to 'false'. Has a considerable performance impact."); comments.put(NOISE_BARRIERS_GEOJSON_FILE, "Path to the geojson file for noise barriers."); comments.put(NOISE_BARRIERS_SOURCE_CRS, "Source coordinate reference system of noise barriers geojson file."); @@ -308,6 +311,14 @@ private void checkNoiseParametersForConsistency(Config config) { + " It is therefore recommended not to use speeds outside of the range of valid parameters!"); } + if(considerNoiseReflection) { + if (!this.considerNoiseBarriers) { + if (this.noiseBarriersFilePath == null || "".equals(this.noiseBarriersFilePath)) { + log.warn("Cannot consider noise reflection without a specified file path to the geojson file of barriers / buildings."); + this.considerNoiseBarriers = false; + } + } + } if (this.considerNoiseBarriers) { if (this.noiseBarriersFilePath == null || "".equals(this.noiseBarriersFilePath)) { log.warn("Cannot consider noise barriers without a specified file path to the geojson file of barriers / buildings."); @@ -782,6 +793,16 @@ public void setConsiderNoiseBarriers(boolean considerNoiseBarriers) { this.considerNoiseBarriers = considerNoiseBarriers; } + @StringGetter(CONSIDER_NOISE_REFLECTION) + public boolean isConsiderNoiseReflection() { + return this.considerNoiseReflection; + } + + @StringSetter(CONSIDER_NOISE_REFLECTION) + public void setConsiderNoiseReflection(boolean considerNoiseReflection) { + this.considerNoiseReflection = considerNoiseReflection; + } + @StringGetter(NOISE_BARRIERS_GEOJSON_FILE) public String getNoiseBarriersFilePath() { return this.noiseBarriersFilePath; diff --git a/contribs/noise/src/main/java/org/matsim/contrib/noise/RLS19NoiseImmission.java b/contribs/noise/src/main/java/org/matsim/contrib/noise/RLS19NoiseImmission.java index 1e8f1cd2563..e0bb566141c 100644 --- a/contribs/noise/src/main/java/org/matsim/contrib/noise/RLS19NoiseImmission.java +++ b/contribs/noise/src/main/java/org/matsim/contrib/noise/RLS19NoiseImmission.java @@ -101,7 +101,9 @@ public double calculateCorrection(double projectedDistance, NoiseReceiverPoint n @Override public void setCurrentRp(NoiseReceiverPoint nrp) { - reflection.setCurrentReceiver(nrp); + if(noiseParams.isConsiderNoiseReflection()) { + reflection.setCurrentReceiver(nrp); + } } private double getSectionsCorrection(NoiseReceiverPoint nrp, Link link) { @@ -127,10 +129,12 @@ private double getSubSectionsCorrection(Coordinate nrpCoordinate, LineSegment se final double sectionCorrection = 10 * Math.log10(length) - calculateCorrection(nrpCoordinate, segment, null); correctionTemp += Math.pow(10, 0.1*sectionCorrection); - final Set reflectionLinks = reflection.getReflections(segment); - for(ReflectionContext.ReflectionTuple reflection: reflectionLinks) { - double sectionCorrectionReflection = 10 * Math.log10(reflection.reflectionLink.getLength()) - calculateCorrection(nrpCoordinate, reflection.reflectionLink, reflection.facade); - correctionTemp += Math.pow(10, 0.1 * sectionCorrectionReflection); + if(noiseParams.isConsiderNoiseReflection()) { + final Set reflectionLinks = reflection.getReflections(segment); + for (ReflectionContext.ReflectionTuple reflection : reflectionLinks) { + double sectionCorrectionReflection = 10 * Math.log10(reflection.reflectionLink().getLength()) - calculateCorrection(nrpCoordinate, reflection.reflectionLink(), reflection.facade()); + correctionTemp += Math.pow(10, 0.1 * sectionCorrectionReflection); + } } } else { double lMid = length / 2; @@ -149,10 +153,12 @@ private double getSubSectionsCorrection(Coordinate nrpCoordinate, LineSegment se final double sectionCorrection = 10 * Math.log10(central.getLength()) - calculateCorrection(nrpCoordinate, central, null); correctionTemp += Math.pow(10, 0.1 * sectionCorrection); - final Set reflectionLinks = reflection.getReflections(central); - for(ReflectionContext.ReflectionTuple reflection: reflectionLinks) { - double sectionCorrectionReflection = 10 * Math.log10(reflection.reflectionLink.getLength()) - calculateCorrection(nrpCoordinate, reflection.reflectionLink, reflection.facade); - correctionTemp += Math.pow(10, 0.1 * sectionCorrectionReflection); + if(noiseParams.isConsiderNoiseReflection()) { + final Set reflectionLinks = reflection.getReflections(central); + for (ReflectionContext.ReflectionTuple reflection : reflectionLinks) { + double sectionCorrectionReflection = 10 * Math.log10(reflection.reflectionLink().getLength()) - calculateCorrection(nrpCoordinate, reflection.reflectionLink(), reflection.facade()); + correctionTemp += Math.pow(10, 0.1 * sectionCorrectionReflection); + } } correctionTemp += getSubSectionsCorrection(nrpCoordinate, leftRemaining); @@ -174,7 +180,10 @@ private double calculateCorrection(Coordinate nrp, LineSegment segment, LineSegm //to maintain the correct signs. nk, Sep'20 double intersectionCorrection = intersection.calculateIntersectionCorrection(coordinate); - double multipleReflectionCorrection = reflection.getMultipleReflectionCorrection(segment); + double multipleReflectionCorrection = 0; + if(noiseParams.isConsiderNoiseReflection()) { + multipleReflectionCorrection = reflection.getMultipleReflectionCorrection(segment); + } double geometricDivergence = 20 * Math.log10(distance) + 10 * Math.log10(2 * Math.PI); double airDampeningFactor = distance / 200.; @@ -191,11 +200,6 @@ private double calculateCorrection(Coordinate nrp, LineSegment segment, LineSegm } else { return geometricDivergence + airDampeningFactor - intersectionCorrection + groundDampening ; } - - //TODO: implement reflection - if someone is looking for a (bachelor) thesis... -// double firstReflectionCorrection = 0; -// double secondReflectionCorrection = 0; -// return dampeningCorrection + firstReflectionCorrection + secondReflectionCorrection; } diff --git a/contribs/noise/src/main/java/org/matsim/contrib/noise/ReflectionContext.java b/contribs/noise/src/main/java/org/matsim/contrib/noise/ReflectionContext.java index 02639ac3d3b..145367afee6 100644 --- a/contribs/noise/src/main/java/org/matsim/contrib/noise/ReflectionContext.java +++ b/contribs/noise/src/main/java/org/matsim/contrib/noise/ReflectionContext.java @@ -1,5 +1,6 @@ package org.matsim.contrib.noise; +import jakarta.inject.Inject; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.locationtech.jts.algorithm.Angle; @@ -7,7 +8,6 @@ import org.locationtech.jts.geom.util.AffineTransformation; import org.matsim.core.config.Config; -import jakarta.inject.Inject; import java.util.*; /** @@ -15,18 +15,19 @@ * * @author nkuehnel */ -public class ReflectionContext { +public final class ReflectionContext { static final double SCAN_LINE_LENGTH = 1; - private final static Logger logger = LogManager.getLogger(org.matsim.contrib.noise.ShieldingContext.class); + private final static Logger logger = LogManager.getLogger(ReflectionContext.class); private Set visibleEdges; private Coordinate receiver; - private BarrierContext barrierContext; - private GeometryFactory geomFactory = new GeometryFactory(); + private final BarrierContext barrierContext; + private final GeometryFactory geomFactory = new GeometryFactory(); + record ReflectionTuple(LineSegment facade, LineSegment reflectionLink) { } @Inject ReflectionContext(BarrierContext barrierContext) { @@ -38,6 +39,7 @@ public class ReflectionContext { } void setCurrentReceiver(NoiseReceiverPoint nrp) { + receiver = new Coordinate(nrp.getCoord().getX(), nrp.getCoord().getY()); final Collection candidates = @@ -60,7 +62,7 @@ void setCurrentReceiver(NoiseReceiverPoint nrp) { } - Set findVisibleEdgesOfPolygon(List polygonEdges, Coordinate coordinate) { + private Set findVisibleEdgesOfPolygon(List polygonEdges, Coordinate coordinate) { Coordinate coordXinc = new Coordinate(coordinate.x + 1, coordinate.y); @@ -155,13 +157,9 @@ Set getReflections(LineSegment originalLink) { } } return reflections; -// return Collections.EMPTY_SET; } double getMultipleReflectionCorrection(LineSegment segment) { - if(this.receiver.x == 1420 && this.receiver.y == 20) { - System.out.println("jo"); - } final Coordinate coordinate = segment.midPoint(); Coordinate candidateRight = getReflectionSegment(coordinate, segment, 400); @@ -174,7 +172,7 @@ Set getReflections(LineSegment originalLink) { } else { return 0; } - if (candidateLeft != null && candidateRight != null){ + if (candidateLeft != null){ double w = candidateLeft.distance(candidateRight); return Math.min(2 * Math.min(candidateLeft.z, candidateRight.z) / w, 1.6); } @@ -265,7 +263,7 @@ private boolean hit(LineSegment facade, LineSegment originalLink) { return true; } - static boolean intersects(LineSegment segment1, LineSegment segment2) { + private static boolean intersects(LineSegment segment1, LineSegment segment2) { double dx0 = segment1.p1.x - segment1.p0.x; double dx1 = segment2.p1.x - segment2.p0.x; @@ -277,17 +275,6 @@ static boolean intersects(LineSegment segment1, LineSegment segment2) { double p1 = dy1 * (segment2.p1.x - segment1.p1.x) - dx1 * (segment2.p1.y - segment1.p1.y); double p2 = dy0 * (segment1.p1.x - segment2.p0.x) - dx0 * (segment1.p1.y - segment2.p0.y); double p3 = dy0 * (segment1.p1.x - segment2.p1.x) - dx0 * (segment1.p1.y - segment2.p1.y); - return (p0 * p1 <= 0) & (p2 * p3 <= 0); - } - - - static class ReflectionTuple { - final LineSegment facade; - final LineSegment reflectionLink; - - public ReflectionTuple(LineSegment facade, LineSegment reflectionLink) { - this.facade = facade; - this.reflectionLink = reflectionLink; - } + return (p0 * p1 <= 0) && (p2 * p3 <= 0); } } diff --git a/contribs/noise/src/main/java/org/matsim/contrib/noise/ShieldingContext.java b/contribs/noise/src/main/java/org/matsim/contrib/noise/ShieldingContext.java index 97af40ce515..ea4e97ca7e6 100644 --- a/contribs/noise/src/main/java/org/matsim/contrib/noise/ShieldingContext.java +++ b/contribs/noise/src/main/java/org/matsim/contrib/noise/ShieldingContext.java @@ -24,8 +24,6 @@ final class ShieldingContext { private final static Logger logger = LogManager.getLogger(ShieldingContext.class); - //STRtree increases performance by ~40% by reducing the amount of potential - //obstruction candidates. nkuehnel, mar '20 private final static double GROUND_HEIGHT = 0.5; private final ShieldingCorrection shieldingCorrection; @@ -35,7 +33,6 @@ final class ShieldingContext { ShieldingContext(Config config, ShieldingCorrection shieldingCorrection, BarrierContext barrierContext) { this.shieldingCorrection = shieldingCorrection; this.barrierContext = barrierContext; - NoiseConfigGroup noiseParams = ConfigUtils.addOrGetModule(config, NoiseConfigGroup.class); } ShieldingContext(ShieldingCorrection shieldingCorrection, BarrierContext barrierContext) { @@ -51,83 +48,73 @@ final class ShieldingContext { final Coordinate midPoint = segment.midPoint(); midPoint.z = GROUND_HEIGHT; -// final Point fromPoint = GeometryUtils.createGeotoolsPoint(link.getFromNode().getCoord()); -// final Point toPoint = GeometryUtils.createGeotoolsPoint(link.getToNode().getCoord()); - - Coordinate from = segment.p0; - Coordinate to = segment.p1; - LineString projectedLineOfSight = constructLineOfSight(rpPoint, midPoint); -// LineString fromLineOfSight = constructLineOfSight(rpPoint, from); -// LineString toLineOfSight = constructLineOfSight(rpPoint, to); NavigableMap edgeCandidates = getObstructionEdges(rpPoint, midPoint, projectedLineOfSight); edgeCandidates.put(projectedLineOfSight.getLength(), midPoint); - if (!edgeCandidates.isEmpty()) { - Coordinate lastFixedEdge = rpPoint; - Coordinate tmpEdge = rpPoint; - double currentHeight = GROUND_HEIGHT; + Coordinate lastFixedEdge = rpPoint; + Coordinate tmpEdge = rpPoint; + double currentHeight = GROUND_HEIGHT; - List consideredEdges = new ArrayList<>(); + List consideredEdges = new ArrayList<>(); - double distToCurrentEdge = 0; - while (lastFixedEdge != midPoint) { - if (edgeCandidates.isEmpty()) { - logger.warn("Skipping obstacle as distance appears to be 0."); - return correctionTermShielding; - } - Iterator edgesIterator = edgeCandidates.values().iterator(); - double maxSlope = Double.NEGATIVE_INFINITY; - double tmpDistance = 0; - while (edgesIterator.hasNext()) { - Coordinate edge = edgesIterator.next(); - double distance = lastFixedEdge.distance(edge); - double slope = (edge.z - currentHeight) / distance; - if (slope >= maxSlope) { - maxSlope = slope; - tmpEdge = edge; - tmpDistance = distance; - } + double distToCurrentEdge = 0; + while (lastFixedEdge != midPoint) { + if (edgeCandidates.isEmpty()) { + logger.warn("Skipping obstacle as distance appears to be 0."); + return correctionTermShielding; + } + Iterator edgesIterator = edgeCandidates.values().iterator(); + double maxSlope = Double.NEGATIVE_INFINITY; + double tmpDistance = 0; + while (edgesIterator.hasNext()) { + Coordinate edge = edgesIterator.next(); + double distance = lastFixedEdge.distance(edge); + double slope = (edge.z - currentHeight) / distance; + if (slope >= maxSlope) { + maxSlope = slope; + tmpEdge = edge; + tmpDistance = distance; } - lastFixedEdge = tmpEdge; - distToCurrentEdge += tmpDistance; - currentHeight = tmpEdge.z; - consideredEdges.add(lastFixedEdge); - edgeCandidates = edgeCandidates.tailMap(distToCurrentEdge, false); } + lastFixedEdge = tmpEdge; + distToCurrentEdge += tmpDistance; + currentHeight = tmpEdge.z; + consideredEdges.add(lastFixedEdge); + edgeCandidates = edgeCandidates.tailMap(distToCurrentEdge, false); + } - consideredEdges.remove(midPoint); + consideredEdges.remove(midPoint); - if (consideredEdges.isEmpty()) { - return correctionTermShielding; - } + if (consideredEdges.isEmpty()) { + return correctionTermShielding; + } - final double firstEdgeYDiff = GROUND_HEIGHT - consideredEdges.get(0).z; - double firstEdgeDistance = rpPoint.distance(consideredEdges.get(0)); - double receiverToFirstEdgeDistance - = Math.sqrt(firstEdgeYDiff * firstEdgeYDiff + firstEdgeDistance * firstEdgeDistance); - - double shieldingDepth = 0; - - Iterator it = consideredEdges.iterator(); - Coordinate edgeTemp = it.next(); - while (it.hasNext()) { - Coordinate edge = it.next(); - double xyDiff = edgeTemp.distance(edge); - double zDiff = edgeTemp.z - edge.z; - shieldingDepth += Math.sqrt(xyDiff * xyDiff + zDiff * zDiff); - edgeTemp = edge; - } + final double firstEdgeYDiff = GROUND_HEIGHT - consideredEdges.get(0).z; + double firstEdgeDistance = rpPoint.distance(consideredEdges.get(0)); + double receiverToFirstEdgeDistance + = Math.sqrt(firstEdgeYDiff * firstEdgeYDiff + firstEdgeDistance * firstEdgeDistance); + + double shieldingDepth = 0; + + Iterator it = consideredEdges.iterator(); + Coordinate edgeTemp = it.next(); + while (it.hasNext()) { + Coordinate edge = it.next(); + double xyDiff = edgeTemp.distance(edge); + double zDiff = edgeTemp.z - edge.z; + shieldingDepth += Math.sqrt(xyDiff * xyDiff + zDiff * zDiff); + edgeTemp = edge; + } - final double lastEdgeSourceXYDiff = midPoint.distance(edgeTemp); - final double lastEdgeSourceZDiff = GROUND_HEIGHT - edgeTemp.z; - double lastEdgeToSourceDistance = Math.sqrt(lastEdgeSourceXYDiff * lastEdgeSourceXYDiff - + lastEdgeSourceZDiff * lastEdgeSourceZDiff); + final double lastEdgeSourceXYDiff = midPoint.distance(edgeTemp); + final double lastEdgeSourceZDiff = GROUND_HEIGHT - edgeTemp.z; + double lastEdgeToSourceDistance = Math.sqrt(lastEdgeSourceXYDiff * lastEdgeSourceXYDiff + + lastEdgeSourceZDiff * lastEdgeSourceZDiff); - correctionTermShielding = shieldingCorrection.calculateShieldingCorrection( - rpPoint.distance(midPoint), lastEdgeToSourceDistance, receiverToFirstEdgeDistance, shieldingDepth); - } + correctionTermShielding = shieldingCorrection.calculateShieldingCorrection( + rpPoint.distance(midPoint), lastEdgeToSourceDistance, receiverToFirstEdgeDistance, shieldingDepth); return correctionTermShielding; } @@ -170,7 +157,6 @@ private ConcurrentSkipListMap getObstructionEdges(Coordinate //using intersects() and intersection() directly on the jts geometry. nkuehnel, aug '20 final Set intersections = intersection((Polygon) noiseBarrier.getGeometry().getGeometry(), directLineOfSight.getCoordinates()); - for (Coordinate coordinate : intersections) { coordinate.z = noiseBarrier.getHeight(); final double distance = receiver.distance(coordinate); @@ -226,25 +212,7 @@ private LineString constructLineOfSight(Coordinate receiver, Coordinate source) private Set intersection(Polygon polygon, Coordinate[] coords) { - - Set externalIntersections = intersection(polygon.getExteriorRing(), coords); - -// Set internalIntersections = null; -// for (int i = 0; i < polygon.getNumInteriorRing(); i++) { -// Set intersects = intersection(polygon.getInteriorRingN(i), coords); -// if (!intersects.isEmpty()) { -// if (internalIntersections == null) { -// internalIntersections = new HashSet<>(); -// } -// internalIntersections.addAll(intersects); -// } -// } - -// if(internalIntersections != null) { -// externalIntersections.addAll(internalIntersections); -// } - - return externalIntersections; + return intersection(polygon.getExteriorRing(), coords); } private Set intersection(LineString ring, Coordinate[] coords) { @@ -285,7 +253,6 @@ private static boolean intersects(Polygon polygon, LineString string) { } - /** * determines the shielding value z for a receiver point for a given link emission source */ @@ -305,70 +272,68 @@ private static boolean intersects(Polygon polygon, LineString string) { NavigableMap edgeCandidates = getObstructionEdges(rpPoint, projectedPoint, projectedLineOfSight, fromLineOfSight, toLineOfSight); edgeCandidates.put(projectedLineOfSight.getLength(), projectedPoint.getCoordinate()); - if (!edgeCandidates.isEmpty()) { - Coordinate lastFixedEdge = rpPoint.getCoordinate(); - Coordinate tmpEdge = rpPoint.getCoordinate(); - double currentHeight = GROUND_HEIGHT; + Coordinate lastFixedEdge = rpPoint.getCoordinate(); + Coordinate tmpEdge = rpPoint.getCoordinate(); + double currentHeight = GROUND_HEIGHT; - List consideredEdges = new ArrayList<>(); + List consideredEdges = new ArrayList<>(); - double distToCurrentEdge = 0; - while (lastFixedEdge != projectedPoint.getCoordinate()) { - if (edgeCandidates.isEmpty()) { - logger.warn("Skipping obstacle as distance appears to be 0."); - return correctionTermShielding; - } - Iterator edgesIterator = edgeCandidates.values().iterator(); - double maxSlope = Double.NEGATIVE_INFINITY; - double tmpDistance = 0; - while (edgesIterator.hasNext()) { - Coordinate edge = edgesIterator.next(); - double distance = lastFixedEdge.distance(edge); - double slope = (edge.z - currentHeight) / distance; - if (slope >= maxSlope) { - maxSlope = slope; - tmpEdge = edge; - tmpDistance = distance; - } + double distToCurrentEdge = 0; + while (lastFixedEdge != projectedPoint.getCoordinate()) { + if (edgeCandidates.isEmpty()) { + logger.warn("Skipping obstacle as distance appears to be 0."); + return correctionTermShielding; + } + Iterator edgesIterator = edgeCandidates.values().iterator(); + double maxSlope = Double.NEGATIVE_INFINITY; + double tmpDistance = 0; + while (edgesIterator.hasNext()) { + Coordinate edge = edgesIterator.next(); + double distance = lastFixedEdge.distance(edge); + double slope = (edge.z - currentHeight) / distance; + if (slope >= maxSlope) { + maxSlope = slope; + tmpEdge = edge; + tmpDistance = distance; } - lastFixedEdge = tmpEdge; - distToCurrentEdge += tmpDistance; - currentHeight = tmpEdge.z; - consideredEdges.add(lastFixedEdge); - edgeCandidates = edgeCandidates.tailMap(distToCurrentEdge, false); } + lastFixedEdge = tmpEdge; + distToCurrentEdge += tmpDistance; + currentHeight = tmpEdge.z; + consideredEdges.add(lastFixedEdge); + edgeCandidates = edgeCandidates.tailMap(distToCurrentEdge, false); + } - consideredEdges.remove(projectedPoint.getCoordinate()); + consideredEdges.remove(projectedPoint.getCoordinate()); - if (consideredEdges.isEmpty()) { - return correctionTermShielding; - } + if (consideredEdges.isEmpty()) { + return correctionTermShielding; + } - final double firstEdgeYDiff = GROUND_HEIGHT - consideredEdges.get(0).z; - double firstEdgeDistance = rpPoint.getCoordinate().distance(consideredEdges.get(0)); - double receiverToFirstEdgeDistance - = Math.sqrt(firstEdgeYDiff * firstEdgeYDiff + firstEdgeDistance * firstEdgeDistance); - - double shieldingDepth = 0; - - Iterator it = consideredEdges.iterator(); - Coordinate edgeTemp = it.next(); - while (it.hasNext()) { - Coordinate edge = it.next(); - double xyDiff = edgeTemp.distance(edge); - double zDiff = edgeTemp.z - edge.z; - shieldingDepth += Math.sqrt(xyDiff * xyDiff + zDiff * zDiff); - edgeTemp = edge; - } + final double firstEdgeYDiff = GROUND_HEIGHT - consideredEdges.getFirst().z; + double firstEdgeDistance = rpPoint.getCoordinate().distance(consideredEdges.getFirst()); + double receiverToFirstEdgeDistance + = Math.sqrt(firstEdgeYDiff * firstEdgeYDiff + firstEdgeDistance * firstEdgeDistance); + + double shieldingDepth = 0; + + Iterator it = consideredEdges.iterator(); + Coordinate edgeTemp = it.next(); + while (it.hasNext()) { + Coordinate edge = it.next(); + double xyDiff = edgeTemp.distance(edge); + double zDiff = edgeTemp.z - edge.z; + shieldingDepth += Math.sqrt(xyDiff * xyDiff + zDiff * zDiff); + edgeTemp = edge; + } - final double lastEdgeSourceXYDiff = projectedPoint.getCoordinate().distance(edgeTemp); - final double lastEdgeSourceZDiff = GROUND_HEIGHT - edgeTemp.z; - double lastEdgeToSourceDistance = Math.sqrt(lastEdgeSourceXYDiff * lastEdgeSourceXYDiff - + lastEdgeSourceZDiff * lastEdgeSourceZDiff); + final double lastEdgeSourceXYDiff = projectedPoint.getCoordinate().distance(edgeTemp); + final double lastEdgeSourceZDiff = GROUND_HEIGHT - edgeTemp.z; + double lastEdgeToSourceDistance = Math.sqrt(lastEdgeSourceXYDiff * lastEdgeSourceXYDiff + + lastEdgeSourceZDiff * lastEdgeSourceZDiff); - correctionTermShielding = shieldingCorrection.calculateShieldingCorrection( - rpPoint.distance(projectedPoint), lastEdgeToSourceDistance, receiverToFirstEdgeDistance, shieldingDepth); - } + correctionTermShielding = shieldingCorrection.calculateShieldingCorrection( + rpPoint.distance(projectedPoint), lastEdgeToSourceDistance, receiverToFirstEdgeDistance, shieldingDepth); return correctionTermShielding; } } diff --git a/contribs/parking/README.md b/contribs/parking/README.md index a9e090515c3..1285c0d5f86 100644 --- a/contribs/parking/README.md +++ b/contribs/parking/README.md @@ -12,4 +12,34 @@ approaches as to how parking can be handled in MATSim, depending on the use case . This was designed for large scenarios where it's not feasable to fully simulate parking agents. Rather, the additional time needed for parking is estimated - Parking Costs, developed by Marcel Rieser and Joschka Bischoff at SBB. This modules allows the integration of parking - costs based on link attribute data. \ No newline at end of file + costs based on link attribute data. + +## Implementations + +### Parking Search + +Model parking search, including walking segments and parking search traffic. + +Different Parking Search Logics: + +1. **Random:** + 1. Drive to the destination. + 2. The next link is chosen randomly. +2. **DistanceMemoryParkingSearch:** + 1. Drive to the destination. + 2. Select the next link: + 1. Choose an unknown link with the shortest straight-line distance to the destination. + 2. If all links are known, choose randomly. +3. **NearestParkingSpotSearchLogic:** + 1. Drive to the destination (??). + 2. Search for the facility with the shortest distance to the current location, considering the expected driving time and parking duration (and + possibly parking time restrictions). + 3. If no suitable facility is found ? +4. **BenensonParkingSearchLogic:** A more sophisticated strategy based on the Benenson + model: https://www.sciencedirect.com/science/article/pii/S0198971508000689 + +### Parking Proxy + +### Parking Costs + +### Parking Choice diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/DynAgent/BenensonDynLeg.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/DynAgent/BenensonDynLeg.java index 5bd6ca248bb..c7b041ba21a 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/DynAgent/BenensonDynLeg.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/DynAgent/BenensonDynLeg.java @@ -21,30 +21,30 @@ /** * @author schlenther *

- * Benenson et al defined 3 phases of parking search + * Benenson et al. defined 3 phases of parking search * OBSERVING: observation of parking situation while driving towards destination * SEARCH_WHILE_APPROACH: estimating the amount of free parking lots on the way to destination * and if applicable parking before arriving * SEARCH_FOR_NEXT: taking the next free parking space if it isn't too far away from destination */ enum ParkingMode { - DRIVING, OBSERVING, SEARCH_WHILE_APPROACH, SEARCH_FOR_NEXT + DRIVING, OBSERVING, SEARCH_WHILE_APPROACH, SEARCH_FOR_NEXT } -public class BenensonDynLeg extends ParkingDynLeg{ +public class BenensonDynLeg extends ParkingDynLeg { private static final Logger logger = LogManager.getLogger(BenensonDynLeg.class); private static final boolean logForDebug = false; private double totalObservedParkingSpaces = 0.0; private double observedFreeParkingSpaces = 0.0; - private double firstDestinationLinkEnterTime = 0; - private ParkingMode legStage = ParkingMode.DRIVING; + private double firstDestinationLinkEnterTime = 0; + private ParkingMode legStage = ParkingMode.DRIVING; public BenensonDynLeg(String mode, NetworkRoute route, ParkingSearchLogic logic, - ParkingSearchManager parkingManager, Id vehicleId, MobsimTimer timer, EventsManager events) { + ParkingSearchManager parkingManager, Id vehicleId, MobsimTimer timer, EventsManager events) { super(mode, route, logic, parkingManager, vehicleId, timer, events); - if (!(logic instanceof BenensonParkingSearchLogic)){ + if (!(logic instanceof BenensonParkingSearchLogic)) { throw new RuntimeException(); } } @@ -55,56 +55,68 @@ public void movedOverNode(Id newLinkId) { currentLinkId = newLinkId; if (this.legStage == ParkingMode.DRIVING) { - if (((BenensonParkingSearchLogic) this.logic).transitionToObservingBehaviour(currentLinkId, this.route.getEndLinkId())) { - this.legStage = ParkingMode.OBSERVING; + if (((BenensonParkingSearchLogic) this.logic).transitionToObservingBehaviour(currentLinkId, this.route.getEndLinkId())) { + this.legStage = ParkingMode.OBSERVING; this.events.processEvent(new StartParkingSearchEvent(timer.getTimeOfDay(), vehicleId, currentLinkId)); - if(logForDebug)logger.error("vehicle " + this.vehicleId + " goes into observing on link " + this.currentLinkId); + if (logForDebug) { + logger.error("vehicle " + this.vehicleId + " goes into observing on link " + this.currentLinkId); + } } } - if(this.legStage == ParkingMode.OBSERVING ){ + if (this.legStage == ParkingMode.OBSERVING) { memorizeParkingSituationAndIsSomethingFree(); - if (((BenensonParkingSearchLogic) this.logic).transitionToParkingBehaviour(currentLinkId, this.route.getEndLinkId())) { - this.legStage = ParkingMode.SEARCH_WHILE_APPROACH; - if(logForDebug)logger.error("vehicle " + this.vehicleId + " goes into parking on link " + this.currentLinkId); + if (((BenensonParkingSearchLogic) this.logic).transitionToParkingBehaviour(currentLinkId, this.route.getEndLinkId())) { + this.legStage = ParkingMode.SEARCH_WHILE_APPROACH; + if (logForDebug) { + logger.error("vehicle " + this.vehicleId + " goes into parking on link " + this.currentLinkId); + } } } - if(this.legStage == ParkingMode.SEARCH_WHILE_APPROACH){ - if(currentLinkId.equals(route.getEndLinkId())){ + if (this.legStage == ParkingMode.SEARCH_WHILE_APPROACH) { + if (currentLinkId.equals(route.getEndLinkId())) { this.legStage = ParkingMode.SEARCH_FOR_NEXT; - this.firstDestinationLinkEnterTime = timer.getTimeOfDay(); - } - else{ - if(memorizeParkingSituationAndIsSomethingFree()){ + this.firstDestinationLinkEnterTime = timer.getTimeOfDay(); + } else { + if (memorizeParkingSituationAndIsSomethingFree()) { double pUnoccupied = 0; - if(this.totalObservedParkingSpaces > 0){ + if (this.totalObservedParkingSpaces > 0) { pUnoccupied = this.observedFreeParkingSpaces / this.totalObservedParkingSpaces; } - if ( ((BenensonParkingSearchLogic)this.logic).wantToParkHere(pUnoccupied, currentLinkId, route.getEndLinkId())){ - if (logForDebug) logger.error("vehicle " + this.vehicleId + " would like to park on link" + currentLinkId - + "\n \t pUnoccupied = " + pUnoccupied + "\n\t totalObservedParkingSpaces = " + totalObservedParkingSpaces + "\n\t observedFreeSpaces = " + this.observedFreeParkingSpaces); - hasFoundParking = parkingManager.reserveSpaceIfVehicleCanParkHere(vehicleId, currentLinkId); - } - } - else{ - if(logForDebug)logger.error("nothing free for vehicle " + vehicleId + " on link " + currentLinkId); + if (((BenensonParkingSearchLogic) this.logic).wantToParkHere(pUnoccupied, currentLinkId, route.getEndLinkId())) { + if (logForDebug) { + logger.error("vehicle " + this.vehicleId + " would like to park on link" + currentLinkId + + "\n \t pUnoccupied = " + pUnoccupied + "\n\t totalObservedParkingSpaces = " + totalObservedParkingSpaces + "\n\t " + + "observedFreeSpaces = " + this.observedFreeParkingSpaces); + } + hasFoundParking = parkingManager.reserveSpaceIfVehicleCanParkHere(vehicleId, currentLinkId); + } + } else { + if (logForDebug) { + logger.error("nothing free for vehicle " + vehicleId + " on link " + currentLinkId); + } } } } - if (this.legStage == ParkingMode.SEARCH_FOR_NEXT){ - if (logForDebug) logger.error("vehicle " + this.vehicleId + " is in PHASE3 on link " + this.currentLinkId); - //if( ((BenensonParkingSearchLogic)this.logic).isDriverInAcceptableDistance(currentLinkId, route.getEndLinkId(), this.firstDestLinkEnterTimer, timer.getTimeOfDay()) ){ + if (this.legStage == ParkingMode.SEARCH_FOR_NEXT) { + if (logForDebug) { + logger.error("vehicle " + this.vehicleId + " is in PHASE3 on link " + this.currentLinkId); + } + //if( ((BenensonParkingSearchLogic)this.logic).isDriverInAcceptableDistance(currentLinkId, route.getEndLinkId(), this + // .firstDestLinkEnterTimer, timer.getTimeOfDay()) ){ - hasFoundParking = parkingManager.reserveSpaceIfVehicleCanParkHere(vehicleId, currentLinkId); + hasFoundParking = parkingManager.reserveSpaceIfVehicleCanParkHere(vehicleId, currentLinkId); - if (logForDebug) logger.error("vehicle " + this.vehicleId + " tries in PHASE3 to park on link " + this.currentLinkId + ", " + - (int) (timer.getTimeOfDay() - this.firstDestinationLinkEnterTime) / 60 + ":" + (int) (timer.getTimeOfDay() - this.firstDestinationLinkEnterTime) % 60 - + " min after passing destination. Result: " + hasFoundParking); - //} - } - } + if (logForDebug) { + logger.error("vehicle " + this.vehicleId + " tries in PHASE3 to park on link " + this.currentLinkId + ", " + + (int) (timer.getTimeOfDay() - this.firstDestinationLinkEnterTime) / 60 + ":" + (int) (timer.getTimeOfDay() - this.firstDestinationLinkEnterTime) % 60 + + " min after passing destination. Result: " + hasFoundParking); + } + //} + } + } - /** + /** * returns true if there is at least one empty slot on the current link */ private boolean memorizeParkingSituationAndIsSomethingFree() { @@ -124,13 +136,14 @@ public Id getNextLinkId() { return route.getEndLinkId(); } return linkIds.get(currentLinkIdx + 1); - } - else { + } else { if (hasFoundParking) { - if(logForDebug)logger.error("vehicle " + this.vehicleId + " has found a parking on link " + this.currentLinkId + " after passing " + Math.abs((this.route.getLinkIds().size() - this.currentLinkIdx - 3)) + " links"); + if (logForDebug) { + logger.error("vehicle " + this.vehicleId + " has found a parking on link " + this.currentLinkId + " after passing " + Math.abs((this.route.getLinkIds() + .size() - this.currentLinkIdx - 3)) + " links"); + } return null; - } - else { + } else { if (this.currentAndNextParkLink != null) { if (currentAndNextParkLink.getFirst().equals(currentLinkId)) { // we already calculated this @@ -139,15 +152,15 @@ public Id getNextLinkId() { } Id nextLinkId; - if(this.legStage == ParkingMode.SEARCH_FOR_NEXT){ - nextLinkId = ((BenensonParkingSearchLogic) this.logic).getNextLinkRandomInAcceptableDistance(currentLinkId, this.route.getEndLinkId(), - vehicleId, firstDestinationLinkEnterTime, this.timer.getTimeOfDay(), mode); - } - else{ + if (this.legStage == ParkingMode.SEARCH_FOR_NEXT) { + nextLinkId = ((BenensonParkingSearchLogic) this.logic).getNextLinkRandomInAcceptableDistance(currentLinkId, + this.route.getEndLinkId(), + vehicleId, firstDestinationLinkEnterTime, this.timer.getTimeOfDay(), mode); + } else { nextLinkId = ((BenensonParkingSearchLogic) (this.logic)).getNextLinkBenensonRouting(currentLinkId, route.getEndLinkId(), mode); - } - currentAndNextParkLink = new Tuple<>(currentLinkId, nextLinkId); - return nextLinkId; + } + currentAndNextParkLink = new Tuple<>(currentLinkId, nextLinkId); + return nextLinkId; } } } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/DynAgent/NearestParkingDynLeg.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/DynAgent/NearestParkingDynLeg.java index a5f4cdcf143..ba81ede9c1d 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/DynAgent/NearestParkingDynLeg.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/DynAgent/NearestParkingDynLeg.java @@ -45,10 +45,12 @@ public NearestParkingDynLeg(Leg currentPlannedLeg, NetworkRoute route, Plan plan this.currentPlannedLeg = currentPlannedLeg; this.plan = plan; this.planIndexNextActivity = planIndexNextActivity; - if (ParkingUtils.checkIfActivityHasNoParking(followingActivity)) + if (ParkingUtils.checkIfActivityHasNoParking(followingActivity)) { parkingAtEndOfLeg = false; - if (ParkingUtils.checkIfActivityHasPassengerInteraction(followingActivity)) + } + if (ParkingUtils.checkIfActivityHasPassengerInteraction(followingActivity)) { passangerInteractionAtParkingFacilityAtEndOfLeg = true; + } } @Override @@ -67,20 +69,22 @@ public void movedOverNode(Id newLinkId) { if (hasFoundParking) { this.events.processEvent(new ReserveParkingLocationEvent(timer.getTimeOfDay(), vehicleId, currentLinkId, currentLinkId)); nextSelectedParkingLink = currentLinkId; - } else + } else { ((FacilityBasedParkingManager) parkingManager).registerRejectedReservation(timer.getTimeOfDay()); + } } } } else if (followingActivity.getLinkId().equals(newLinkId)) { - if (alreadyReservedParking) + if (alreadyReservedParking) { hasFoundParking = true; - else { + } else { hasFoundParking = parkingManager.reserveSpaceIfVehicleCanParkHere(vehicleId, currentLinkId); if (hasFoundParking) { this.events.processEvent(new ReserveParkingLocationEvent(timer.getTimeOfDay(), vehicleId, currentLinkId, currentLinkId)); nextSelectedParkingLink = currentLinkId; - } else + } else { ((FacilityBasedParkingManager) parkingManager).registerRejectedReservation(timer.getTimeOfDay()); + } } } } @@ -138,11 +142,10 @@ public Id getNextLinkId() { // need to find the next link double nextPickupTime; double maxParkingDuration; - if (passangerInteractionAtParkingFacilityAtEndOfLeg){ + if (passangerInteractionAtParkingFacilityAtEndOfLeg) { nextPickupTime = 0.; maxParkingDuration = followingActivity.getMaximumDuration().seconds(); - } - else { + } else { nextPickupTime = currentPlannedLeg.getDepartureTime().seconds() + followingActivity.getMaximumDuration().seconds(); maxParkingDuration = nextPickupTime - timer.getTimeOfDay(); } @@ -163,11 +166,12 @@ public Id getNextLinkId() { nextSelectedParkingLink = nextPlanedParkingLink; if (((NearestParkingSpotSearchLogic) this.logic).canReserveParkingSlot()) { alreadyReservedParking = parkingManager.reserveSpaceIfVehicleCanParkHere(vehicleId, nextSelectedParkingLink); - if (alreadyReservedParking) + if (alreadyReservedParking) { this.events.processEvent( new ReserveParkingLocationEvent(timer.getTimeOfDay(), vehicleId, currentLinkId, nextSelectedParkingLink)); - else + } else { ((FacilityBasedParkingManager) parkingManager).registerRejectedReservation(timer.getTimeOfDay()); + } } else { this.events.processEvent( new SelectNewParkingLocationEvent(timer.getTimeOfDay(), vehicleId, currentLinkId, nextSelectedParkingLink)); @@ -176,13 +180,16 @@ public Id getNextLinkId() { } } currentAndNextParkLink = new Tuple<>(currentLinkId, nextLinkId); - if (((NearestParkingSpotSearchLogic) this.logic).getNextRoute() != null) + if (((NearestParkingSpotSearchLogic) this.logic).getNextRoute() != null) { currentPlannedLeg.setRoute(((NearestParkingSpotSearchLogic) this.logic).getNextRoute()); + } return nextLinkId; } } } + //yyyy I assume, the vehicle is removed from the link's queue and thus waiting for parking does not influence the behaviour of the mobsim? + // Does this make sense? paul, nov'24 private void createWaitingActivityUntilPassengerInteractionIsPossible(Id newLinkId, Id vehicleId, double now) { Activity waitingActivity = PopulationUtils.createActivityFromLinkId(ParkingUtils.WaitingForParkingActivityType, newLinkId); ParkingUtils.setNoParkingForActivity(waitingActivity); @@ -195,7 +202,8 @@ private void removeNextActivityAndFollowingLeg() { plan.getPlanElements().remove(planIndexNextActivity); plan.getPlanElements().remove(planIndexNextActivity); // log.info( -// plan.getPerson().getId().toString() + ": Parking activity after getOff point '" + ((Activity)plan.getPlanElements().get(planIndexNextActivity - 2)).getType() + "' is removed, because no parking facility was found."); +// plan.getPerson().getId().toString() + ": Parking activity after getOff point '" + ((Activity)plan.getPlanElements().get +// (planIndexNextActivity - 2)).getType() + "' is removed, because no parking facility was found."); } public boolean driveToBaseWithoutParking() { diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/DynAgent/agentLogic/NearestParkingSpotAgentLogic.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/DynAgent/agentLogic/NearestParkingSpotAgentLogic.java index f3a7e671b14..b0095eb5cf7 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/DynAgent/agentLogic/NearestParkingSpotAgentLogic.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/DynAgent/agentLogic/NearestParkingSpotAgentLogic.java @@ -52,19 +52,20 @@ public DynAction computeNextAction(DynAction oldAction, double now) { // unpark activity: find the way to the next route & start leg //if a parking activity was skipped we need no change the nexParkActionState - if (lastParkActionState.equals(LastParkActionState.CARTRIP) && ((NearestParkingDynLeg) oldAction).driveToBaseWithoutParking()) + if (lastParkActionState.equals(LastParkActionState.CARTRIP) && ((NearestParkingDynLeg) oldAction).driveToBaseWithoutParking()) { this.lastParkActionState = LastParkActionState.WALKFROMPARK; + } - return switch (lastParkActionState) { - case ACTIVITY -> nextStateAfterActivity(oldAction, now); - case CARTRIP -> nextStateAfterCarTrip(oldAction, now); - case NONCARTRIP -> nextStateAfterNonCarTrip(oldAction, now); - case PARKACTIVITY -> nextStateAfterParkActivity(oldAction, now); - case UNPARKACTIVITY -> nextStateAfterUnParkActivity(oldAction, now); - case WALKFROMPARK -> nextStateAfterWalkFromPark(oldAction, now); - case WALKTOPARK -> nextStateAfterWalkToPark(oldAction, now); - }; - } + return switch (lastParkActionState) { + case ACTIVITY -> nextStateAfterActivity(oldAction, now); + case CARTRIP -> nextStateAfterCarTrip(oldAction, now); + case NONCARTRIP -> nextStateAfterNonCarTrip(oldAction, now); + case PARKACTIVITY -> nextStateAfterParkActivity(oldAction, now); + case UNPARKACTIVITY -> nextStateAfterUnParkActivity(oldAction, now); + case WALKFROMPARK -> nextStateAfterWalkFromPark(oldAction, now); + case WALKTOPARK -> nextStateAfterWalkToPark(oldAction, now); + }; + } @Override protected DynAction nextStateAfterUnParkActivity(DynAction oldAction, double now) { @@ -75,20 +76,24 @@ protected DynAction nextStateAfterUnParkActivity(DynAction oldAction, double now Route plannedRoute = currentPlannedLeg.getRoute(); NetworkRoute actualRoute = this.parkingRouter.getRouteFromParkingToDestination(plannedRoute.getEndLinkId(), now, agent.getCurrentLinkId()); actualRoute.setVehicleId(currentlyAssignedVehicleId); - if (!plannedRoute.getStartLinkId().equals(actualRoute.getStartLinkId())) + if (!plannedRoute.getStartLinkId().equals(actualRoute.getStartLinkId())) { currentPlannedLeg.setRoute(actualRoute); + } if ((this.parkingManager.unParkVehicleHere(currentlyAssignedVehicleId, agent.getCurrentLinkId(), now)) || (isInitialLocation)) { this.lastParkActionState = LastParkActionState.CARTRIP; isInitialLocation = false; // Leg currentLeg = (Leg) this.currentPlanElement; int planIndexNextActivity = planIndex + 1; Activity nextPlanElement = (Activity) plan.getPlanElements().get(planIndexNextActivity); - if (ParkingUtils.checkIfActivityHasNoParking(nextPlanElement)) + if (ParkingUtils.checkIfActivityHasNoParking(nextPlanElement)) { this.lastParkActionState = LastParkActionState.WALKFROMPARK; + } //this could be Car, Carsharing, Motorcylce, or whatever else mode we have, so we want our leg to reflect this. return new NearestParkingDynLeg(currentPlannedLeg, actualRoute, plan, planIndexNextActivity, parkingLogic, parkingManager, currentlyAssignedVehicleId, timer, events); - } else throw new RuntimeException("parking location mismatch"); + } else { + throw new RuntimeException("parking location mismatch"); + } } @@ -101,17 +106,19 @@ protected DynAction nextStateAfterParkActivity(DynAction oldAction, double now) List walkTrip = walkRouter.calcRoute( DefaultRoutingRequest.withoutAttributes(fromFacility, toFacility, now, plan.getPerson())); if (walkTrip.size() != 1 || !(walkTrip.get(0) instanceof Leg)) { - String message = "walkRouter returned something else than a single Leg, e.g. it routes walk on the network with non_network_walk to access the network. Not implemented in parking yet!"; + String message = "walkRouter returned something else than a single Leg, e.g. it routes walk on the network with non_network_walk to " + + "access the network. Not implemented in parking yet!"; log.error(message); throw new RuntimeException(message); } Leg walkLeg = (Leg) walkTrip.get(0); this.lastParkActionState = LastParkActionState.WALKFROMPARK; this.stageInteractionType = null; - if (!walkLeg.getTravelTime().equals(OptionalTime.defined(0.))) + if (!walkLeg.getTravelTime().equals(OptionalTime.defined(0.))) { return new StaticPassengerDynLeg(walkLeg.getRoute(), walkLeg.getMode()); - else + } else { return nextStateAfterWalkFromPark(oldAction, now); + } } @Override @@ -125,15 +132,20 @@ protected DynAction nextStateAfterActivity(DynAction oldAction, double now) { this.parkingManager.parkVehicleHere(Id.create(this.agent.getId(), Vehicle.class), agent.getCurrentLinkId(), now); return nextStateAfterNonCarTrip(oldAction, now); } - if (plan.getPlanElements().get(planIndex + 1) instanceof Activity) + if (plan.getPlanElements().get(planIndex + 1) instanceof Activity) { return nextStateAfterNonCarTrip(oldAction, now); - if (plan.getPlanElements().get(planIndex) instanceof Activity && ((Activity) plan.getPlanElements().get(planIndex)).getType().contains("_GetOff")) { + } + if (plan.getPlanElements().get(planIndex) instanceof Activity && ((Activity) plan.getPlanElements().get(planIndex)).getType() + .contains("_GetOff")) { ((Activity) plan.getPlanElements().get(planIndex)).setEndTime(now); - ((Activity) plan.getPlanElements().get(planIndex + 4)).setStartTime(now + ((Activity) plan.getPlanElements().get(planIndex + 2)).getMaximumDuration().seconds()); + ((Activity) plan.getPlanElements().get(planIndex + 4)).setStartTime(now + ((Activity) plan.getPlanElements() + .get(planIndex + 2)).getMaximumDuration() + .seconds()); // checks if it is possible to stay from getOff until getIn - boolean possibleToStay = checkIfParkingIsPossibleUntilNextActivities(this.planIndex,this.planIndex + 2); - if (possibleToStay) + boolean possibleToStay = checkIfParkingIsPossibleUntilNextActivities(this.planIndex, this.planIndex + 2); + if (possibleToStay) { return nextStateAfterNonCarTrip(oldAction, now); + } } planIndex++; this.currentPlanElement = plan.getPlanElements().get(planIndex); @@ -143,7 +155,8 @@ protected DynAction nextStateAfterActivity(DynAction oldAction, double now) { Id parkLink = this.parkingManager.getVehicleParkingLocation(vehicleId); if (parkLink == null) { - //this is the first activity of a day and our parking manager does not provide information about initial stages. We suppose the car is parked where we are + //this is the first activity of a day and our parking manager does not provide information about initial stages. We suppose the + // car is parked where we are parkLink = agent.getCurrentLinkId(); } @@ -154,7 +167,8 @@ protected DynAction nextStateAfterActivity(DynAction oldAction, double now) { List walkTrip = walkRouter.calcRoute( DefaultRoutingRequest.withoutAttributes(fromFacility, toFacility, now, plan.getPerson())); if (walkTrip.size() != 1 || !(walkTrip.get(0) instanceof Leg walkLeg)) { - String message = "walkRouter returned something else than a single Leg, e.g. it routes walk on the network with non_network_walk to access the network. Not implemented in parking yet!"; + String message = "walkRouter returned something else than a single Leg, e.g. it routes walk on the network with non_network_walk" + + " to access the network. Not implemented in parking yet!"; log.error(message); throw new RuntimeException(message); } @@ -180,9 +194,12 @@ protected DynAction nextStateAfterActivity(DynAction oldAction, double now) { return new StaticPassengerDynLeg(currentLeg.getRoute(), currentLeg.getMode()); } - } else throw new RuntimeException( - "no more leg to follow but activity is ending\nLastPlanElement: " + currentPlanElement.toString() + "\n Agent " + this.agent.getId() + "\nTime: " + Time.writeTime( - now)); + } else { + throw new RuntimeException( + "no more leg to follow but activity is ending\nLastPlanElement: " + currentPlanElement.toString() + "\n Agent " + this.agent.getId() + + "\nTime: " + Time.writeTime( + now)); + } } @Override @@ -190,8 +207,9 @@ protected DynAction nextStateAfterWalkToPark(DynAction oldAction, double now) { //walk2park is complete, we can unpark. this.lastParkActionState = LastParkActionState.UNPARKACTIVITY; Activity beforePlanElement = (Activity) plan.getPlanElements().get(planIndex - 1); - if (ParkingUtils.checkIfActivityHasNoParking(beforePlanElement)) + if (ParkingUtils.checkIfActivityHasNoParking(beforePlanElement)) { return nextStateAfterUnParkActivity(oldAction, now); // wenn kein Parken dann einfach weiter + } return new IdleDynActivity(this.stageInteractionType, now + configGroup.getUnparkduration()); } @@ -211,7 +229,9 @@ protected DynAction nextStateAfterCarTrip(DynAction oldAction, double now) { this.currentlyAssignedVehicleId = null; this.parkingLogic.reset(); return new IdleDynActivity(this.stageInteractionType, now + configGroup.getParkduration()); - } else throw new RuntimeException("No parking possible"); + } else { + throw new RuntimeException("No parking possible"); + } } @Override @@ -221,7 +241,7 @@ protected DynAction nextStateAfterNonCarTrip(DynAction oldAction, double now) { Activity nextPlannedActivity = (Activity) this.currentPlanElement; // checks if you can extend parking here until getIn if (nextPlannedActivity.getType().equals(ParkingUtils.ParkingActivityType) && plan.getPlanElements().get(planIndex + 2) instanceof Leg) { - checkIfParkingIsPossibleUntilNextActivities(planIndex + 1,planIndex + 1); + checkIfParkingIsPossibleUntilNextActivities(planIndex + 1, planIndex + 1); } // switch back to activity planIndex++; @@ -249,11 +269,11 @@ private boolean checkIfParkingIsPossibleUntilNextActivities(int indexOfCurrentAc Activity currentActivity = ((Activity) plan.getPlanElements().get(this.planIndex)); Activity activityAfterFollowing = ((Activity) plan.getPlanElements().get(this.planIndex + 4)); if (agent.getCurrentLinkId().equals(activityAfterFollowing.getLinkId()) && !ParkingUtils.checkIfActivityHasNoParking( - (Activity) currentPlanElement)) { + (Activity) currentPlanElement)) { boolean canParkAtFacilityUntilGetIn = ((FacilityBasedParkingManager) parkingManager).canParkAtThisFacilityUntilEnd( agent.getCurrentLinkId(), - followingActivity.getMaximumDuration().seconds(), currentActivity.getMaximumDuration().seconds(), - activityAfterFollowing.getMaximumDuration().seconds(), timer.getTimeOfDay()); + timer.getTimeOfDay(), currentActivity.getMaximumDuration().seconds(), followingActivity.getMaximumDuration().seconds(), + activityAfterFollowing.getMaximumDuration().seconds()); if (canParkAtFacilityUntilGetIn) { plan.getPlanElements().remove(this.planIndex + 3); plan.getPlanElements().remove(this.planIndex + 1); @@ -269,8 +289,8 @@ else if (indexOfCurrentActivity == indexOfParkingActivity) { followingActivity)) { boolean canParkAtFacilityUntilGetIn = ((FacilityBasedParkingManager) parkingManager).canParkAtThisFacilityUntilEnd( agent.getCurrentLinkId(), - currentActivity.getMaximumDuration().seconds(), 0., - followingActivity.getMaximumDuration().seconds(), timer.getTimeOfDay()); + timer.getTimeOfDay(), 0., currentActivity.getMaximumDuration().seconds(), + followingActivity.getMaximumDuration().seconds()); if (canParkAtFacilityUntilGetIn) { plan.getPlanElements().remove(indexOfParkingActivity + 1); currentActivity.setEndTime(followingActivity.getStartTime().seconds()); diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/DynAgent/agentLogic/ParkingAgentLogic.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/DynAgent/agentLogic/ParkingAgentLogic.java index dd2fb4fa74b..31e175a3d30 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/DynAgent/agentLogic/ParkingAgentLogic.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/DynAgent/agentLogic/ParkingAgentLogic.java @@ -19,25 +19,14 @@ package org.matsim.contrib.parking.parkingsearch.DynAgent.agentLogic; -import java.util.List; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; -import org.matsim.api.core.v01.population.Activity; -import org.matsim.api.core.v01.population.Leg; -import org.matsim.api.core.v01.population.Plan; -import org.matsim.api.core.v01.population.PlanElement; -import org.matsim.api.core.v01.population.Route; -import org.matsim.contrib.dynagent.DynAction; -import org.matsim.contrib.dynagent.DynActivity; -import org.matsim.contrib.dynagent.DynAgent; -import org.matsim.contrib.dynagent.DynAgentLogic; -import org.matsim.contrib.dynagent.IdleDynActivity; -import org.matsim.contrib.dynagent.StaticPassengerDynLeg; +import org.matsim.api.core.v01.population.*; +import org.matsim.contrib.dynagent.*; import org.matsim.contrib.parking.parkingsearch.DynAgent.ParkingDynLeg; import org.matsim.contrib.parking.parkingsearch.ParkingUtils; import org.matsim.contrib.parking.parkingsearch.manager.ParkingSearchManager; @@ -56,8 +45,12 @@ import org.matsim.pt.routes.TransitPassengerRoute; import org.matsim.vehicles.Vehicle; +import java.util.List; + /** + * This class represents the logic for a {@link DynAgent}. It can only handle car legs for parking. + * * @author jbischoff */ public class ParkingAgentLogic implements DynAgentLogic { @@ -139,17 +132,17 @@ public DynAction computeNextAction(DynAction oldAction, double now) { // ordinary activity: get next Leg, if car: go to car, otherwise add ordinary leg by other mode // walk-leg to car: add unpark activity // unpark activity: find the way to the next route & start leg - return switch (lastParkActionState) { - case ACTIVITY -> nextStateAfterActivity(oldAction, now); - case CARTRIP -> nextStateAfterCarTrip(oldAction, now); - case NONCARTRIP -> nextStateAfterNonCarTrip(oldAction, now); - case PARKACTIVITY -> nextStateAfterParkActivity(oldAction, now); - case UNPARKACTIVITY -> nextStateAfterUnParkActivity(oldAction, now); - case WALKFROMPARK -> nextStateAfterWalkFromPark(oldAction, now); - case WALKTOPARK -> nextStateAfterWalkToPark(oldAction, now); - }; + return switch (lastParkActionState) { + case ACTIVITY -> nextStateAfterActivity(oldAction, now); + case CARTRIP -> nextStateAfterCarTrip(oldAction, now); + case NONCARTRIP -> nextStateAfterNonCarTrip(oldAction, now); + case PARKACTIVITY -> nextStateAfterParkActivity(oldAction, now); + case UNPARKACTIVITY -> nextStateAfterUnParkActivity(oldAction, now); + case WALKFROMPARK -> nextStateAfterWalkFromPark(oldAction, now); + case WALKTOPARK -> nextStateAfterWalkToPark(oldAction, now); + }; - } + } protected DynAction nextStateAfterUnParkActivity(DynAction oldAction, double now) { // we have unparked, now we need to get going by car again. @@ -164,7 +157,9 @@ protected DynAction nextStateAfterUnParkActivity(DynAction oldAction, double now //this could be Car, Carsharing, Motorcylce, or whatever else mode we have, so we want our leg to reflect this. return new ParkingDynLeg(currentLeg.getMode(), actualRoute, parkingLogic, parkingManager, currentlyAssignedVehicleId, timer, events); - } else throw new RuntimeException("parking location mismatch"); + } else { + throw new RuntimeException("parking location mismatch"); + } } @@ -175,19 +170,25 @@ protected DynAction nextStateAfterWalkToPark(DynAction oldAction, double now) { } protected DynAction nextStateAfterWalkFromPark(DynAction oldAction, double now) { - //walkleg complete, time to get the next activity from the plan Elements and start it, this is basically the same as arriving on any other mode + //walkleg complete, time to get the next activity from the plan Elements and start it, this is basically the same as arriving on any other + // mode return nextStateAfterNonCarTrip(oldAction, now); } protected DynAction nextStateAfterParkActivity(DynAction oldAction, double now) { // add a walk leg after parking Leg currentPlannedLeg = (Leg) currentPlanElement; + + // yyyy I think we don't want LinkWrapperFacilities but the actual facilities. Right now, only calculates the teleportation from link to + // link, but if the parking happens on the same link as the activity, then it does not consider the coordinates. Thus, it produces a + // degenerated (0m and 0s) walk leg. paul, nov'24 Facility fromFacility = new LinkWrapperFacility(network.getLinks().get(agent.getCurrentLinkId())); Facility toFacility = new LinkWrapperFacility(network.getLinks().get(currentPlannedLeg.getRoute().getEndLinkId())); List walkTrip = walkRouter.calcRoute( DefaultRoutingRequest.withoutAttributes(fromFacility, toFacility, now, plan.getPerson())); if (walkTrip.size() != 1 || !(walkTrip.get(0) instanceof Leg walkLeg)) { - String message = "walkRouter returned something else than a single Leg, e.g. it routes walk on the network with non_network_walk to access the network. Not implemented in parking yet!"; + String message = "walkRouter returned something else than a single Leg, e.g. it routes walk on the network with non_network_walk to " + + "access the network. Not implemented in parking yet!"; log.error(message); throw new RuntimeException(message); } @@ -224,7 +225,9 @@ protected DynAction nextStateAfterCarTrip(DynAction oldAction, double now) { this.currentlyAssignedVehicleId = null; this.parkingLogic.reset(); return new IdleDynActivity(this.stageInteractionType, now + configGroup.getParkduration()); - } else throw new RuntimeException("No parking possible"); + } else { + throw new RuntimeException("No parking possible"); + } } protected DynAction nextStateAfterActivity(DynAction oldAction, double now) { @@ -233,15 +236,22 @@ protected DynAction nextStateAfterActivity(DynAction oldAction, double now) { planIndex++; this.currentPlanElement = plan.getPlanElements().get(planIndex); Leg currentLeg = (Leg) currentPlanElement; + + // yyyy can only handle car legs for parking :-( paul, nov'24 if (currentLeg.getMode().equals(TransportMode.car)) { Id vehicleId = Id.create(this.agent.getId(), Vehicle.class); Id parkLink = this.parkingManager.getVehicleParkingLocation(vehicleId); if (parkLink == null) { - //this is the first activity of a day and our parking manager does not provide informations about initial stages. We suppose the car is parked where we are + //this is the first activity of a day and our parking manager does not provide information about initial stages. We suppose the + // car is parked where we are parkLink = agent.getCurrentLinkId(); } + // yyyy I think we don't want LinkWrapperFacilities but the actual facilities. Right now, only calculates the teleportation from + // link to + // link, but if the parking happens on the same link as the activity, then it does not consider the coordinates. Thus, it produces a + // degenerated (0m and 0s) walk leg. paul, nov'24 Facility fromFacility = new LinkWrapperFacility(network.getLinks().get(agent.getCurrentLinkId())); Id teleportedParkLink = this.teleportationLogic.getVehicleLocation(agent.getCurrentLinkId(), vehicleId, parkLink, now, currentLeg.getMode()); @@ -249,7 +259,8 @@ protected DynAction nextStateAfterActivity(DynAction oldAction, double now) { List walkTrip = walkRouter.calcRoute( DefaultRoutingRequest.withoutAttributes(fromFacility, toFacility, now, plan.getPerson())); if (walkTrip.size() != 1 || !(walkTrip.get(0) instanceof Leg walkLeg)) { - String message = "walkRouter returned something else than a single Leg, e.g. it routes walk on the network with non_network_walk to access the network. Not implemented in parking yet!"; + String message = "walkRouter returned something else than a single Leg, e.g. it routes walk on the network with " + + "non_network_walk to access the network. Not implemented in parking yet!"; log.error(message); throw new RuntimeException(message); } @@ -271,9 +282,11 @@ protected DynAction nextStateAfterActivity(DynAction oldAction, double now) { return new StaticPassengerDynLeg(currentLeg.getRoute(), currentLeg.getMode()); } - } else throw new RuntimeException( - "no more leg to follow but activity is ending\nLastPlanElement: " + currentPlanElement.toString() + "\n Agent " + this.agent.getId() + "\nTime: " + Time.writeTime( - now)); + } else { + throw new RuntimeException( + "no more leg to follow but activity is ending\nLastPlanElement: " + currentPlanElement.toString() + "\n Agent " + this.agent.getId() + + "\nTime: " + Time.writeTime(now)); + } } } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/evaluation/ParkingListener.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/evaluation/ParkingListener.java deleted file mode 100644 index 41e370c8065..00000000000 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/evaluation/ParkingListener.java +++ /dev/null @@ -1,117 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * * - * *********************************************************************** * - * * - * copyright : (C) 2016 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** */ - -package org.matsim.contrib.parking.parkingsearch.evaluation; - - -import com.google.inject.Inject; -import org.matsim.contrib.parking.parkingsearch.manager.FacilityBasedParkingManager; -import org.matsim.contrib.parking.parkingsearch.manager.ParkingSearchManager; -import org.matsim.core.controler.OutputDirectoryHierarchy; -import org.matsim.core.controler.events.IterationEndsEvent; -import org.matsim.core.controler.listener.IterationEndsListener; -import org.matsim.core.mobsim.framework.events.MobsimBeforeSimStepEvent; -import org.matsim.core.mobsim.framework.events.MobsimInitializedEvent; -import org.matsim.core.mobsim.framework.listeners.MobsimBeforeSimStepListener; -import org.matsim.core.mobsim.framework.listeners.MobsimInitializedListener; -import org.matsim.core.mobsim.qsim.QSim; -import org.matsim.core.utils.io.IOUtils; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.util.List; - -/** - * @author jbischoff - * - */ - -public class ParkingListener implements IterationEndsListener, MobsimBeforeSimStepListener, MobsimInitializedListener { - - @Inject - ParkingSearchManager manager; - @Inject - OutputDirectoryHierarchy output; - - /* (non-Javadoc) - * @see org.matsim.core.controler.listener.IterationEndsListener#notifyIterationEnds(org.matsim.core.controler.events.IterationEndsEvent) - */ - @Override - public void notifyIterationEnds(IterationEndsEvent event) { - writeStats(manager.produceStatistics(), event.getIteration()); - writeStatsByTimesteps(((FacilityBasedParkingManager)manager).produceTimestepsStatistics(), event.getIteration()); - manager.reset(event.getIteration()); - } - - private void writeStatsByTimesteps(List produceBeneStatistics, int iteration) { - BufferedWriter bw = IOUtils.getBufferedWriter(output.getIterationFilename(iteration, "parkingStatsPerTimeSteps.csv")); - try { - - String header = "time;rejectedParkingRequest;foundParking;unpark"; - bw.write(header); - bw.newLine(); - for (String s : produceBeneStatistics){ - bw.write(s); - bw.newLine(); - } - bw.flush(); - bw.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - - /** - * @param produceStatistics - */ - private void writeStats(List produceStatistics, int iteration) { - BufferedWriter bw = IOUtils.getBufferedWriter(output.getIterationFilename(iteration, "parkingStats.csv")); - try { - - String header = "linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn"; - bw.write(header); - bw.newLine(); - for (String s : produceStatistics){ - bw.write(s); - bw.newLine(); - } - bw.flush(); - bw.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - - } - - @Override - public void notifyMobsimBeforeSimStep(MobsimBeforeSimStepEvent event) { - ((FacilityBasedParkingManager) manager).checkFreeCapacitiesForWaitingVehicles((QSim) event.getQueueSimulation(), event.getSimulationTime()); - } - - @Override - public void notifyMobsimInitialized(final MobsimInitializedEvent e) { - QSim qSim = (QSim) e.getQueueSimulation(); - ((FacilityBasedParkingManager) manager).setQSim(qSim); - - } -} diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/FacilityBasedParkingManager.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/FacilityBasedParkingManager.java index 9b3b8eff107..8c8491381c3 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/FacilityBasedParkingManager.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/FacilityBasedParkingManager.java @@ -22,231 +22,232 @@ import com.google.inject.Inject; import org.apache.commons.lang3.mutable.MutableLong; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.network.Network; import org.matsim.contrib.dynagent.DynAgent; import org.matsim.contrib.parking.parkingsearch.ParkingUtils; import org.matsim.contrib.parking.parkingsearch.sim.ParkingSearchConfigGroup; +import org.matsim.core.controler.events.IterationEndsEvent; +import org.matsim.core.gbl.Gbl; +import org.matsim.core.mobsim.framework.events.MobsimBeforeSimStepEvent; +import org.matsim.core.mobsim.framework.events.MobsimInitializedEvent; import org.matsim.core.mobsim.qsim.QSim; import org.matsim.core.utils.misc.Time; import org.matsim.facilities.ActivityFacility; import org.matsim.facilities.ActivityOption; +import org.matsim.facilities.OpeningTime; import org.matsim.vehicles.Vehicle; import java.util.*; import java.util.Map.Entry; /** + * Manages vehicles parking actions at facilities or freely on the street. I.e. keeps track of the capacity of the facilities. This class has + * additional functionality: + * - It can handle parking reservations. + * - It triggers reporting of parking statistics. + * - It can handle vehicles waiting for a parking space. * + * * @author jbischoff, schlenther, Ricardo Ewert */ public class FacilityBasedParkingManager implements ParkingSearchManager { + private static final Logger logger = LogManager.getLogger(FacilityBasedParkingManager.class); + private static final int REPORTING_TIME_BIN_SIZE = 15 * 60; + + protected Map, ParkingFacilityInfo> infoByFacilityId = new HashMap<>(); + + protected Map, TreeMap>> waitingVehiclesByLinkId = new HashMap<>(); + protected Map, ActivityFacility> parkingFacilitiesById; + protected Map, Id> parkingFacilityLocationByVehicleId = new HashMap<>(); + protected Map, Id> parkingReservationByVehicleId = new HashMap<>(); + //stores the parking location of vehicles that are parked outside of facilities (e.g. at the side of a link. therefore, there are no capacity + // checks) + protected Map, Id> freeParkingLinkByVehicleId = new HashMap<>(); + protected Map, Set>> parkingFacilitiesByLink = new HashMap<>(); + protected ParkingSearchConfigGroup psConfigGroup; + private QSim qsim; - protected Map, Integer> capacity = new HashMap<>(); - protected Map, MutableLong> occupation = new HashMap<>(); - protected Map, MutableLong> reservationsRequests = new HashMap<>(); - protected Map, MutableLong> rejectedParkingRequest = new HashMap<>(); - protected Map, MutableLong> numberOfParkedVehicles = new HashMap<>(); - protected Map, MutableLong> numberOfWaitingActivities = new HashMap<>(); - protected Map, MutableLong> numberOfStaysFromGetOffUntilGetIn = new HashMap<>(); - protected Map, MutableLong> numberOfParkingBeforeGetIn = new HashMap<>(); - protected Map, TreeMap>> waitingVehicles = new HashMap<>(); + //The following maps are used for reporting + @Inject + private ParkingStatsWriter writer; protected TreeMap rejectedReservationsByTime = new TreeMap<>(); protected TreeMap foundParkingByTime = new TreeMap<>(); protected TreeMap unparkByTime = new TreeMap<>(); - protected Map, ActivityFacility> parkingFacilities; - protected Map, Id> parkingLocations = new HashMap<>(); - protected Map, Id> parkingReservation = new HashMap<>(); - protected Map, Id> parkingLocationsOutsideFacilities = new HashMap<>(); - protected Map, Set>> facilitiesPerLink = new HashMap<>(); - protected Network network; - protected ParkingSearchConfigGroup psConfigGroup; - protected boolean canParkOnlyAtFacilities; - private QSim qsim; - private final int maxSlotIndex; - private final int maxTime; - private final int timeBinSize; - private final int startTime; + private int reportingMaxSlotIndex; + private int reportingMaxTime; @Inject public FacilityBasedParkingManager(Scenario scenario) { - psConfigGroup = (ParkingSearchConfigGroup) scenario.getConfig().getModules().get( - ParkingSearchConfigGroup.GROUP_NAME); - canParkOnlyAtFacilities = psConfigGroup.getCanParkOnlyAtFacilities(); - this.network = scenario.getNetwork(); - parkingFacilities = scenario.getActivityFacilities() - .getFacilitiesForActivityType(ParkingUtils.ParkingStageInteractionType); - LogManager.getLogger(getClass()).info(parkingFacilities.toString()); - this.timeBinSize = 15 * 60; - this.maxTime = 24 * 3600 - 1; - this.maxSlotIndex = (this.maxTime / this.timeBinSize) + 1; - this.startTime = 9 * 3600; - - for (ActivityFacility fac : this.parkingFacilities.values()) { - Id linkId = fac.getLinkId(); - Set> parkingOnLink = new HashSet<>(); - if (this.facilitiesPerLink.containsKey(linkId)) { - parkingOnLink = this.facilitiesPerLink.get(linkId); - } - parkingOnLink.add(fac.getId()); - this.facilitiesPerLink.put(linkId, parkingOnLink); - this.waitingVehicles.computeIfAbsent(linkId, (k) -> new TreeMap<>()); - this.occupation.put(fac.getId(), new MutableLong(0)); - this.reservationsRequests.put(fac.getId(), new MutableLong(0)); - this.rejectedParkingRequest.put(fac.getId(), new MutableLong(0)); - this.numberOfParkedVehicles.put(fac.getId(), new MutableLong(0)); - this.numberOfWaitingActivities.put(fac.getId(), new MutableLong(0)); - this.numberOfStaysFromGetOffUntilGetIn.put(fac.getId(), new MutableLong(0)); - this.numberOfParkingBeforeGetIn.put(fac.getId(), new MutableLong(0)); - } - int slotIndex = getTimeSlotIndex(startTime); - while (slotIndex <= maxSlotIndex) { - rejectedReservationsByTime.put(slotIndex * timeBinSize, new MutableLong(0)); - foundParkingByTime.put(slotIndex * timeBinSize, new MutableLong(0)); - unparkByTime.put(slotIndex * timeBinSize, new MutableLong(0)); - slotIndex++; + psConfigGroup = (ParkingSearchConfigGroup) scenario.getConfig().getModules().get(ParkingSearchConfigGroup.GROUP_NAME); + parkingFacilitiesById = scenario.getActivityFacilities().getFacilitiesForActivityType(ParkingUtils.ParkingStageInteractionType); + + logger.info(parkingFacilitiesById.toString()); + + for (ActivityFacility fac : this.parkingFacilitiesById.values()) { + initParkingFacility(fac); } + + initReporting(scenario); } - @Override - public boolean reserveSpaceIfVehicleCanParkHere(Id vehicleId, Id linkId) { - boolean canPark = false; + private void initReporting(Scenario scenario) { + this.reportingMaxTime = (int) scenario.getConfig().qsim().getEndTime().seconds(); + this.reportingMaxSlotIndex = (this.reportingMaxTime / REPORTING_TIME_BIN_SIZE) + 1; + } - if (linkIdHasAvailableParkingForVehicle(linkId, vehicleId)) { - canPark = true; - // LogManager.getLogger(getClass()).info("veh: "+vehicleId+" link - // "+linkId + " can park "+canPark); - } + private void initParkingFacility(ActivityFacility fac) { + Id linkId = fac.getLinkId(); + Set> parkingOnLink = parkingFacilitiesByLink.getOrDefault(linkId, new HashSet<>()); + parkingOnLink.add(fac.getId()); + this.parkingFacilitiesByLink.put(linkId, parkingOnLink); + this.waitingVehiclesByLinkId.put(linkId, new TreeMap<>()); - return canPark; + ActivityOption activityOption = fac.getActivityOptions().get(ParkingUtils.ParkingStageInteractionType); + this.infoByFacilityId.put(fac.getId(), new ParkingFacilityInfo(activityOption)); + } + + @Override + public boolean reserveSpaceIfVehicleCanParkHere(Id vehicleId, Id linkId) { + return linkIdHasAvailableParkingForVehicle(linkId, vehicleId); } /** * Checks if it is possible if you can park at this link for the complete time. - * - * @param linkId - * @param stopDuration - * @param getOffDuration - * @param pickUpDuration - * @param now - * @return */ - public boolean canParkAtThisFacilityUntilEnd(Id linkId, double stopDuration, double getOffDuration, double pickUpDuration, double now) { - Set> facilities = this.facilitiesPerLink.get(linkId); - if (facilities != null) { - double totalNeededParkingDuration = getOffDuration + stopDuration + pickUpDuration; - for (Id facility : facilities) { - double maxParkingDurationAtFacilityInHours = Double.MAX_VALUE; - if (this.parkingFacilities.get(facility).getAttributes().getAsMap().containsKey("maxParkingDurationInHours")) - maxParkingDurationAtFacilityInHours = 3600 * (double) this.parkingFacilities.get(facility).getAttributes().getAsMap().get( - "maxParkingDurationInHours"); - if (maxParkingDurationAtFacilityInHours > totalNeededParkingDuration) { - ActivityOption parkingOptions = this.parkingFacilities.get(facility).getActivityOptions().get("parking"); - if (!parkingOptions.getOpeningTimes().isEmpty()) { - if ((parkingOptions.getOpeningTimes().first().getStartTime() == 0 && parkingOptions.getOpeningTimes().first().getEndTime() == 24 * 3600)) - if (parkingOptions.getOpeningTimes().first().getStartTime() <= now && parkingOptions.getOpeningTimes().first().getEndTime() >= now + totalNeededParkingDuration) - return true; - } else - return true; + public boolean canParkAtThisFacilityUntilEnd(Id linkId, double now, double getOffDuration, double stopDuration, double pickUpDuration) { + Set> facilities = this.parkingFacilitiesByLink.get(linkId); + if (facilities == null) { + //TODO really? if there is no facility we assume free parking with no time constraint. + return false; + } + double totalDuration = getOffDuration + stopDuration + pickUpDuration; + for (Id facility : facilities) { + double maxParkingDurationAtFacilityInSeconds = + Optional.ofNullable(this.parkingFacilitiesById.get(facility).getAttributes().getAsMap().get("maxParkingDurationInHours")) + .map(attribute -> 3600 * (double) attribute).orElse(Double.MAX_VALUE); + + if (maxParkingDurationAtFacilityInSeconds < totalDuration) { + //Parking duration is limited, so we can't park here. + return false; + } + + ActivityOption parkingOptions = this.infoByFacilityId.get(facility).activityOption; + if (parkingOptions.getOpeningTimes().isEmpty()) { + //No opening times defined, so we can park here. + return true; + } + + OpeningTime firstOpeningTimes = parkingOptions.getOpeningTimes().first(); + //TODO do we really want this constraint? if parking facility has other opening times than 0-24, we can't park here. + if ((firstOpeningTimes.getStartTime() == 0 && firstOpeningTimes.getEndTime() == 24 * 3600)) { + if (firstOpeningTimes.getStartTime() <= now && firstOpeningTimes.getEndTime() >= now + totalDuration) { + //Parking facility is open for the complete duration, so we can park here. + return true; } } + } + //No parking facility is open for the complete duration, so we can't park here. return false; } + /** + * Either parks the vehicle at a link freely (no capacity constraint) or at a facility (capacity constraint). + */ private boolean linkIdHasAvailableParkingForVehicle(Id linkId, Id vid) { - // LogManager.getLogger(getClass()).info("link "+linkId+" vehicle "+vid); - if (!this.facilitiesPerLink.containsKey(linkId) && !canParkOnlyAtFacilities) { - // this implies: If no parking facility is present, we suppose that - // we can park freely (i.e. the matsim standard approach) - // it also means: a link without any parking spaces should have a - // parking facility with 0 capacity. - // LogManager.getLogger(getClass()).info("link not listed as parking - // space, we will say yes "+linkId); - - return true; - } else if (!this.facilitiesPerLink.containsKey(linkId)) { - return false; + if (!this.parkingFacilitiesByLink.containsKey(linkId)) { + // No parking facility at this link. Either parking is allowed only at facilities or not. + // If not, we can park freely, so link has available parking. (MATSim standard approach) + // If yes, we can't park here. + return !psConfigGroup.getCanParkOnlyAtFacilities(); } - Set> parkingFacilitiesAtLink = this.facilitiesPerLink.get(linkId); + Set> parkingFacilitiesAtLink = this.parkingFacilitiesByLink.get(linkId); for (Id fac : parkingFacilitiesAtLink) { - double cap = this.parkingFacilities.get(fac).getActivityOptions().get(ParkingUtils.ParkingStageInteractionType) - .getCapacity(); - this.reservationsRequests.get(fac).increment(); - if (this.occupation.get(fac).doubleValue() < cap) { - // LogManager.getLogger(getClass()).info("occ: - // "+this.occupation.get(fac).toString()+" cap: "+cap); - this.occupation.get(fac).increment(); - this.parkingReservation.put(vid, fac); - + if (this.infoByFacilityId.get(fac).park()) { + this.parkingReservationByVehicleId.put(vid, fac); return true; } - this.rejectedParkingRequest.get(fac).increment(); } return false; } @Override public Id getVehicleParkingLocation(Id vehicleId) { - if (this.parkingLocations.containsKey(vehicleId)) { - return this.parkingFacilities.get(this.parkingLocations.get(vehicleId)).getLinkId(); - } else return this.parkingLocationsOutsideFacilities.getOrDefault(vehicleId, null); + if (this.parkingFacilityLocationByVehicleId.containsKey(vehicleId)) { + //parked at facility + return this.parkingFacilitiesById.get(this.parkingFacilityLocationByVehicleId.get(vehicleId)).getLinkId(); + } else { + //parked freely + return this.freeParkingLinkByVehicleId.getOrDefault(vehicleId, null); + } } + /** + * Parks a vehicle at a link. Either freely outside a facility or at a facility. + */ @Override public boolean parkVehicleHere(Id vehicleId, Id linkId, double time) { return parkVehicleAtLink(vehicleId, linkId, time); } protected boolean parkVehicleAtLink(Id vehicleId, Id linkId, double time) { - Set> parkingFacilitiesAtLink = this.facilitiesPerLink.get(linkId); + Set> parkingFacilitiesAtLink = this.parkingFacilitiesByLink.get(linkId); if (parkingFacilitiesAtLink == null) { - this.parkingLocationsOutsideFacilities.put(vehicleId, linkId); + //park freely + this.freeParkingLinkByVehicleId.put(vehicleId, linkId); return true; - } else { - Id fac = this.parkingReservation.remove(vehicleId); - if (fac != null) { - this.parkingLocations.put(vehicleId, fac); - this.numberOfParkedVehicles.get(fac).increment(); - foundParkingByTime.get(getTimeSlotIndex(time) * timeBinSize).increment(); - return true; - } else { - throw new RuntimeException("no parking reservation found for vehicle " + vehicleId.toString() - + " arrival on link " + linkId + " with parking restriction"); - } } + //park at facility + return parkVehicleInReservedFacility(vehicleId, linkId, time); + } + + private boolean parkVehicleInReservedFacility(Id vehicleId, Id linkId, double time) { + Id fac = this.parkingReservationByVehicleId.remove(vehicleId); + if (fac == null) { + throw new RuntimeException("no parking reservation found for vehicle " + vehicleId.toString() + + " arrival on link " + linkId + " with parking restriction"); + } + + Gbl.assertIf(parkingFacilitiesById.get(fac).getLinkId().equals(linkId)); + + this.parkingFacilityLocationByVehicleId.put(vehicleId, fac); + reportParking(time, fac); + return true; } + /** + * Unparks vehicle from a link. Either freely outside a facility or at a facility. + */ @Override public boolean unParkVehicleHere(Id vehicleId, Id linkId, double time) { - if (!this.parkingLocations.containsKey(vehicleId)) { - this.parkingLocationsOutsideFacilities.remove(vehicleId); - return true; - - // we assume the person parks somewhere else + if (!this.parkingFacilityLocationByVehicleId.containsKey(vehicleId)) { + //unpark freely + this.freeParkingLinkByVehicleId.remove(vehicleId); } else { - Id fac = this.parkingLocations.remove(vehicleId); - this.occupation.get(fac).decrement(); - unparkByTime.get(getTimeSlotIndex(time) * timeBinSize).increment(); - return true; + //unpark at facility + Id fac = this.parkingFacilityLocationByVehicleId.remove(vehicleId); + reportUnParking(time, fac); } + return true; } - @Override - public List produceStatistics() { + private List produceStatistics() { List stats = new ArrayList<>(); - for (Entry, MutableLong> e : this.occupation.entrySet()) { - Id linkId = this.parkingFacilities.get(e.getKey()).getLinkId(); - double capacity = this.parkingFacilities.get(e.getKey()).getActivityOptions() - .get(ParkingUtils.ParkingStageInteractionType).getCapacity(); - double x = this.parkingFacilities.get(e.getKey()).getCoord().getX(); - double y = this.parkingFacilities.get(e.getKey()).getCoord().getY(); - - String s = linkId.toString() + ";" + x + ";" + y + ";" + e.getKey().toString() + ";" + capacity + ";" + e.getValue().toString() + ";" + this.reservationsRequests.get( - e.getKey()).toString() + ";" + this.numberOfParkedVehicles.get(e.getKey()).toString() + ";" + this.rejectedParkingRequest.get( - e.getKey()).toString() + ";" + this.numberOfWaitingActivities.get( - e.getKey()).toString() + ";" + this.numberOfStaysFromGetOffUntilGetIn.get(e.getKey()).intValue() + ";" + this.numberOfParkingBeforeGetIn.get(e.getKey()).intValue(); + for (Entry, ParkingFacilityInfo> e : this.infoByFacilityId.entrySet()) { + Id linkId = this.parkingFacilitiesById.get(e.getKey()).getLinkId(); + double capacity = this.parkingFacilitiesById.get(e.getKey()).getActivityOptions() + .get(ParkingUtils.ParkingStageInteractionType).getCapacity(); + double x = this.parkingFacilitiesById.get(e.getKey()).getCoord().getX(); + double y = this.parkingFacilitiesById.get(e.getKey()).getCoord().getY(); + + String facilityId = e.getKey().toString(); + ParkingFacilityInfo info = e.getValue(); + String s = + linkId.toString() + ";" + x + ";" + y + ";" + facilityId + ";" + capacity + ";" + info.occupation + ";" + info.reservationRequests + + ";" + info.parkedVehiclesCount + ";" + info.rejectedParkingRequests + ";" + info.waitingActivitiesCount + ";" + + info.staysFromGetOffUntilGetIn + ";" + info.parkingBeforeGetInCount; stats.add(s); } return stats; @@ -266,10 +267,10 @@ public List produceTimestepsStatistics() { public double getNrOfAllParkingSpacesOnLink(Id linkId) { double allSpaces = 0; - Set> parkingFacilitiesAtLink = this.facilitiesPerLink.get(linkId); + Set> parkingFacilitiesAtLink = this.parkingFacilitiesByLink.get(linkId); if (!(parkingFacilitiesAtLink == null)) { for (Id fac : parkingFacilitiesAtLink) { - allSpaces += this.parkingFacilities.get(fac).getActivityOptions().get(ParkingUtils.ParkingStageInteractionType).getCapacity(); + allSpaces += this.parkingFacilitiesById.get(fac).getActivityOptions().get(ParkingUtils.ParkingStageInteractionType).getCapacity(); } } return allSpaces; @@ -277,97 +278,89 @@ public double getNrOfAllParkingSpacesOnLink(Id linkId) { public double getNrOfFreeParkingSpacesOnLink(Id linkId) { double allFreeSpaces = 0; - Set> parkingFacilitiesAtLink = this.facilitiesPerLink.get(linkId); + Set> parkingFacilitiesAtLink = this.parkingFacilitiesByLink.get(linkId); if (parkingFacilitiesAtLink == null) { return 0; } else { for (Id fac : parkingFacilitiesAtLink) { - int cap = (int) this.parkingFacilities.get(fac).getActivityOptions().get(ParkingUtils.ParkingStageInteractionType).getCapacity(); - allFreeSpaces += (cap - this.occupation.get(fac).intValue()); + int cap = (int) this.parkingFacilitiesById.get(fac).getActivityOptions().get(ParkingUtils.ParkingStageInteractionType).getCapacity(); + allFreeSpaces += (cap - this.infoByFacilityId.get(fac).occupation); } } return allFreeSpaces; } - public Map, ActivityFacility> getParkingFacilities() { - return this.parkingFacilities; + public Map, ActivityFacility> getParkingFacilitiesById() { + return this.parkingFacilitiesById; } public void registerRejectedReservation(double now) { - rejectedReservationsByTime.get(getTimeSlotIndex(now) * timeBinSize).increment(); - } - - public TreeSet getTimeSteps() { - TreeSet timeSteps = new TreeSet<>(); - int slotIndex = 0; - while (slotIndex <= maxSlotIndex) { - timeSteps.add(slotIndex * timeBinSize); - slotIndex++; - } - return timeSteps; + rejectedReservationsByTime.putIfAbsent(getTimeSlotIndex(now) * REPORTING_TIME_BIN_SIZE, new MutableLong(0)); + rejectedReservationsByTime.get(getTimeSlotIndex(now) * REPORTING_TIME_BIN_SIZE).increment(); } private int getTimeSlotIndex(final double time) { - if (time > this.maxTime) { - return this.maxSlotIndex; + if (time > this.reportingMaxTime) { + return this.reportingMaxSlotIndex; } - return ((int) time / this.timeBinSize); + return ((int) time / REPORTING_TIME_BIN_SIZE); } /** - * Gives the duration of the staging activity of parking - * - * @return + * Returns the duration of the staging activity of parking */ public double getParkStageActivityDuration() { return psConfigGroup.getParkduration(); } - /** - * Gives the duration of the staging activity of unparking - * - * @return - */ - public double getUnParkStageActivityDuration() { - return psConfigGroup.getUnparkduration(); - } - @Override public void reset(int iteration) { - for (Id fac : this.rejectedParkingRequest.keySet()) { - this.rejectedParkingRequest.get(fac).setValue(0); - this.reservationsRequests.get(fac).setValue(0); - this.numberOfParkedVehicles.get(fac).setValue(0); - this.numberOfWaitingActivities.get(fac).setValue(0); - } - waitingVehicles.clear(); + infoByFacilityId.replaceAll((k, v) -> new ParkingFacilityInfo(v.activityOption)); + waitingVehiclesByLinkId.clear(); } public void addVehicleForWaitingForParking(Id linkId, Id vehicleId, double now) { // System.out.println(now + ": vehicle " +vehicleId.toString() + " starts waiting here: " + linkId.toString()); - waitingVehicles.get(linkId).put(now + getParkStageActivityDuration() + 1, vehicleId); - for (Id fac : this.facilitiesPerLink.get(linkId)) { - this.numberOfWaitingActivities.get(fac).increment(); + waitingVehiclesByLinkId.get(linkId).put(now + getParkStageActivityDuration() + 1, vehicleId); + for (Id fac : this.parkingFacilitiesByLink.get(linkId)) { + this.infoByFacilityId.get(fac).waitingActivitiesCount++; break; } } + //@formatter:off + /** + * For all links l with waiting vehicles: + * For all facilities f located at l: + * While there is a free capacity at f and there are waiting vehicles: + * Remove the first waiting vehicle from the list of waiting vehicles. + * Reserve a parking space for this vehicle. + * End the activity of the vehicle. + * Reschedule the activity end of the vehicle. + * + */ + //@formatter:on public void checkFreeCapacitiesForWaitingVehicles(QSim qSim, double now) { - for (Id linkId : waitingVehicles.keySet()) { - if (!waitingVehicles.get(linkId).isEmpty()) { - for (Id fac : this.facilitiesPerLink.get(linkId)) { - int cap = (int) this.parkingFacilities.get(fac).getActivityOptions().get(ParkingUtils.ParkingStageInteractionType).getCapacity(); - while (this.occupation.get(fac).intValue() < cap && !waitingVehicles.get(linkId).isEmpty()) { - double startWaitingTime = waitingVehicles.get(linkId).firstKey(); - if (startWaitingTime > now) - break; - Id vehcileId = waitingVehicles.get(linkId).remove(startWaitingTime); - DynAgent agent = (DynAgent) qSim.getAgents().get(Id.createPersonId(vehcileId.toString())); - reserveSpaceIfVehicleCanParkHere(vehcileId, linkId); - agent.endActivityAndComputeNextState(now); - qsim.rescheduleActivityEnd(agent); + for (Id linkId : waitingVehiclesByLinkId.keySet()) { + TreeMap> vehicleIdByTime = waitingVehiclesByLinkId.get(linkId); + if (vehicleIdByTime.isEmpty()) { + break; + } + for (Id fac : this.parkingFacilitiesByLink.get(linkId)) { + int capacity = (int) this.parkingFacilitiesById.get(fac).getActivityOptions().get(ParkingUtils.ParkingStageInteractionType) + .getCapacity(); + + while (this.infoByFacilityId.get(fac).occupation < capacity && !vehicleIdByTime.isEmpty()) { + double startWaitingTime = vehicleIdByTime.firstKey(); + if (startWaitingTime > now) { + break; } + Id vehcileId = vehicleIdByTime.remove(startWaitingTime); + DynAgent agent = (DynAgent) qSim.getAgents().get(Id.createPersonId(vehcileId.toString())); + reserveSpaceIfVehicleCanParkHere(vehcileId, linkId); + agent.endActivityAndComputeNextState(now); + qsim.rescheduleActivityEnd(agent); } } } @@ -378,10 +371,69 @@ public void setQSim(QSim qSim) { } public void registerStayFromGetOffUntilGetIn(Id vehcileId) { - this.numberOfStaysFromGetOffUntilGetIn.get(parkingLocations.get(vehcileId)).increment(); + infoByFacilityId.get(parkingFacilityLocationByVehicleId.get(vehcileId)).staysFromGetOffUntilGetIn++; } public void registerParkingBeforeGetIn(Id vehcileId) { - this.numberOfParkingBeforeGetIn.get(parkingLocations.get(vehcileId)).increment(); + this.infoByFacilityId.get(parkingFacilityLocationByVehicleId.get(vehcileId)).parkingBeforeGetInCount++; + } + + private void reportParking(double time, Id fac) { + this.infoByFacilityId.get(fac).parkedVehiclesCount++; + int timeSlot = getTimeSlotIndex(time) * REPORTING_TIME_BIN_SIZE; + foundParkingByTime.putIfAbsent(timeSlot, new MutableLong(0)); + foundParkingByTime.get(timeSlot).increment(); + } + + private void reportUnParking(double time, Id fac) { + this.infoByFacilityId.get(fac).occupation--; + int timeSlot = getTimeSlotIndex(time) * REPORTING_TIME_BIN_SIZE; + unparkByTime.putIfAbsent(timeSlot, new MutableLong(0)); + unparkByTime.get(timeSlot).increment(); + } + + @Override + public void notifyIterationEnds(IterationEndsEvent event) { + writer.writeStatsByFacility(produceStatistics(), event.getIteration()); + writer.writeStatsByTimesteps(produceTimestepsStatistics(), event.getIteration()); + reset(event.getIteration()); + } + + + @Override + public void notifyMobsimBeforeSimStep(MobsimBeforeSimStepEvent event) { + checkFreeCapacitiesForWaitingVehicles((QSim) event.getQueueSimulation(), event.getSimulationTime()); + } + + @Override + public void notifyMobsimInitialized(final MobsimInitializedEvent e) { + QSim qSim = (QSim) e.getQueueSimulation(); + setQSim(qSim); + } + + protected static class ParkingFacilityInfo { + protected long occupation = 0; + protected final ActivityOption activityOption; + protected long reservationRequests = 0; + protected long rejectedParkingRequests = 0; + protected long parkedVehiclesCount = 0; + protected long waitingActivitiesCount = 0; + protected long staysFromGetOffUntilGetIn = 0; + protected long parkingBeforeGetInCount = 0; + + ParkingFacilityInfo(ActivityOption activityOption) { + this.activityOption = activityOption; + } + + protected boolean park() { + reservationRequests++; + //TODO check double vs long + if (occupation >= activityOption.getCapacity()) { + rejectedParkingRequests++; + return false; + } + occupation++; + return true; + } } } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/LinkLengthBasedParkingManagerWithRandomInitialUtilisation.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/LinkLengthBasedParkingManagerWithRandomInitialUtilisation.java index 5600260ec7a..56f75d97d14 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/LinkLengthBasedParkingManagerWithRandomInitialUtilisation.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/LinkLengthBasedParkingManagerWithRandomInitialUtilisation.java @@ -19,42 +19,43 @@ package org.matsim.contrib.parking.parkingsearch.manager; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; - import jakarta.inject.Inject; - import org.apache.commons.lang3.mutable.MutableLong; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.core.config.Config; +import org.matsim.core.controler.events.IterationEndsEvent; import org.matsim.core.gbl.MatsimRandom; +import org.matsim.core.mobsim.framework.events.MobsimBeforeSimStepEvent; +import org.matsim.core.mobsim.framework.events.MobsimInitializedEvent; import org.matsim.vehicles.Vehicle; +import java.util.*; + /** - * @author jbischoff - * + * @author jbischoff */ public class LinkLengthBasedParkingManagerWithRandomInitialUtilisation implements ParkingSearchManager { - Map,Integer> capacity = new HashMap<>(); - Map,MutableLong> occupation = new HashMap<>(); - Map,Id> parkingPosition = new HashMap<>(); + Map, Integer> capacity = new HashMap<>(); + Map, MutableLong> occupation = new HashMap<>(); + Map, Id> parkingPosition = new HashMap<>(); Random rand = MatsimRandom.getLocalInstance(); int parkedVehicles = 0; int unparkedVehicles = 0; + + @Inject + private ParkingStatsWriter writer; + @Inject public LinkLengthBasedParkingManagerWithRandomInitialUtilisation(Network network, Config config) { - double assumedParkedVehicleLength = 4.0; - double shareOfLinkLengthUsedForParking = 0.7; + double assumedParkedVehicleLength = 4.0; + double shareOfLinkLengthUsedForParking = 0.7; - //TODO: Make this configurable - for (Link link : network.getLinks().values()){ - int maxCapacity = (int) (link.getLength()*shareOfLinkLengthUsedForParking / assumedParkedVehicleLength); + //TODO: Make this configurable + for (Link link : network.getLinks().values()) { + int maxCapacity = (int) (link.getLength() * shareOfLinkLengthUsedForParking / assumedParkedVehicleLength); this.capacity.put(link.getId(), maxCapacity); this.occupation.put(link.getId(), new MutableLong(rand.nextInt(maxCapacity))); @@ -63,7 +64,7 @@ public LinkLengthBasedParkingManagerWithRandomInitialUtilisation(Network network @Override public boolean reserveSpaceIfVehicleCanParkHere(Id vehicleId, Id linkId) { - return (this.occupation.get(linkId).intValue() getVehicleParkingLocation(Id vehicleId) { @Override public boolean parkVehicleHere(Id vehicleId, Id linkId, double time) { - if (this.occupation.get(linkId).intValue() vehicleId, Id linkId, double time) { - if (!linkId.equals(this.parkingPosition.get(vehicleId))) return false; - else { + if (!linkId.equals(this.parkingPosition.get(vehicleId))) { + return false; + } else { this.parkingPosition.remove(vehicleId); this.occupation.get(linkId).decrement(); unparkedVehicles++; @@ -95,11 +99,10 @@ public boolean unParkVehicleHere(Id vehicleId, Id linkId, double } - @Override public List produceStatistics() { List stats = new ArrayList<>(); - stats.add("parking occurences: "+ parkedVehicles); - stats.add("unparking occurences: "+ unparkedVehicles); + stats.add("parking occurences: " + parkedVehicles); + stats.add("unparking occurences: " + unparkedVehicles); return stats; } @@ -107,6 +110,18 @@ public List produceStatistics() { public void reset(int iteration) { } + @Override + public void notifyIterationEnds(IterationEndsEvent event) { + writer.writePlainStats(produceStatistics(), event.getIteration()); + } + + @Override + public void notifyMobsimBeforeSimStep(MobsimBeforeSimStepEvent e) { + } + + @Override + public void notifyMobsimInitialized(MobsimInitializedEvent e) { + } } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/ParkingSearchManager.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/ParkingSearchManager.java index 7bdd6fb37c2..3cb029157f8 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/ParkingSearchManager.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/ParkingSearchManager.java @@ -19,25 +19,27 @@ package org.matsim.contrib.parking.parkingsearch.manager; -import java.util.List; - import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; +import org.matsim.core.controler.listener.IterationEndsListener; +import org.matsim.core.mobsim.framework.listeners.MobsimBeforeSimStepListener; +import org.matsim.core.mobsim.framework.listeners.MobsimInitializedListener; import org.matsim.vehicles.Vehicle; /** - * @author jbischoff - * + * @author jbischoff */ -public interface ParkingSearchManager { +public interface ParkingSearchManager extends IterationEndsListener, MobsimBeforeSimStepListener, MobsimInitializedListener { boolean reserveSpaceIfVehicleCanParkHere(Id vehicleId, Id linkId); + Id getVehicleParkingLocation(Id vehicleId); + boolean parkVehicleHere(Id vehicleId, Id linkId, double time); + boolean unParkVehicleHere(Id vehicleId, Id linkId, double time); - - List produceStatistics(); + void reset(int iteration); - - + + } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/ParkingStatsWriter.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/ParkingStatsWriter.java new file mode 100644 index 00000000000..9b929dc53c3 --- /dev/null +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/ParkingStatsWriter.java @@ -0,0 +1,74 @@ +package org.matsim.contrib.parking.parkingsearch.manager; + +import com.google.inject.Inject; +import org.matsim.core.controler.OutputDirectoryHierarchy; +import org.matsim.core.utils.io.IOUtils; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.util.List; + +//the functionality of this class is mainly copied from old ParkingListener and could be improved +public class ParkingStatsWriter { + @Inject + OutputDirectoryHierarchy output; + + public void writeStatsByTimesteps(List produceBeneStatistics, int iteration) { + BufferedWriter bw = IOUtils.getBufferedWriter(output.getIterationFilename(iteration, "parkingStatsPerTimeSteps.csv")); + try { + + String header = "time;rejectedParkingRequest;foundParking;unpark"; + bw.write(header); + bw.newLine(); + for (String s : produceBeneStatistics) { + bw.write(s); + bw.newLine(); + } + bw.flush(); + bw.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + /** + * @param produceStatistics + */ + public void writeStatsByFacility(List produceStatistics, int iteration) { + BufferedWriter bw = IOUtils.getBufferedWriter(output.getIterationFilename(iteration, "parkingStats.csv")); + try { + + String header = "linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;" + + "numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn"; + bw.write(header); + bw.newLine(); + for (String s : produceStatistics) { + bw.write(s); + bw.newLine(); + } + bw.flush(); + bw.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public void writePlainStats(List produceStatistics, int iteration) { + BufferedWriter bw = IOUtils.getBufferedWriter(output.getIterationFilename(iteration, "parkingStats.txt")); + try { + for (String s : produceStatistics) { + bw.write(s); + bw.newLine(); + } + bw.flush(); + bw.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + +} diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/ZoneParkingManager.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/ZoneParkingManager.java index b9fbebe4699..5dc503ac08a 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/ZoneParkingManager.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/manager/ZoneParkingManager.java @@ -19,13 +19,16 @@ import java.util.Set; /** + * Extends the facility based manager, thus parks vehicles at facilities but also keeps track of the occupancy of zones. A zone is defined by a set + * of links. + * * @author tschlenther */ public class ZoneParkingManager extends FacilityBasedParkingManager { - private HashMap>> linksOfZone; - private HashMap totalCapOfZone; - private HashMap occupationOfZone; + private final HashMap>> linksByZone; + private final HashMap totalCapByZone; + private final HashMap occupationByZone; /** * @param scenario @@ -34,17 +37,17 @@ public class ZoneParkingManager extends FacilityBasedParkingManager { public ZoneParkingManager(Scenario scenario, String[] pathToZoneTxtFiles) { super(scenario); - this.linksOfZone = new HashMap>>(); - this.totalCapOfZone = new HashMap(); - this.occupationOfZone = new HashMap(); + this.linksByZone = new HashMap>>(); + this.totalCapByZone = new HashMap(); + this.occupationByZone = new HashMap(); for (String zone : pathToZoneTxtFiles) { readZone(zone); } - for (String zone : this.linksOfZone.keySet()) { + for (String zone : this.linksByZone.keySet()) { calculateTotalZoneParkCapacity(zone); - this.occupationOfZone.put(zone, 0.0); + this.occupationByZone.put(zone, 0.0); } } @@ -52,6 +55,7 @@ public ZoneParkingManager(Scenario scenario, String[] pathToZoneTxtFiles) { /** * reads in a tabular file that declares which link id's are in the monitored zone * the part between the last '/' and the file type extension in the given path is considered to be the zone name + * * @param pathToZoneFile */ void readZone(String pathToZoneFile) { @@ -72,61 +76,64 @@ public void startRow(String[] row) { }); - this.linksOfZone.put(zone, links); + this.linksByZone.put(zone, links); } private void calculateTotalZoneParkCapacity(String zoneName) { double cap = 0.0; - for (Id link : this.linksOfZone.get(zoneName)) { + for (Id link : this.linksByZone.get(zoneName)) { cap += getNrOfAllParkingSpacesOnLink(link); } - this.totalCapOfZone.put(zoneName, cap); + this.totalCapByZone.put(zoneName, cap); } @Override public boolean parkVehicleHere(Id vehicleId, Id linkId, double time) { if (parkVehicleAtLink(vehicleId, linkId, time)) { - for (String zone : this.linksOfZone.keySet()) { - if (linksOfZone.get(zone).contains(linkId) && this.facilitiesPerLink.containsKey(linkId)) { - double newOcc = this.occupationOfZone.get(zone) + 1; - if (this.totalCapOfZone.get(zone) < newOcc) { - String s = "FacilityID: " + this.parkingLocations.get(vehicleId); - String t = "Occupied: " + this.occupation.get(this.parkingLocations.get(vehicleId)); - String u = "Capacity: " + this.parkingFacilities.get(this.parkingLocations.get(vehicleId)).getActivityOptions().get( - ParkingUtils.ParkingStageInteractionType).getCapacity(); + for (String zone : this.linksByZone.keySet()) { + if (linksByZone.get(zone).contains(linkId) && this.parkingFacilitiesByLink.containsKey(linkId)) { + double newOcc = this.occupationByZone.get(zone) + 1; + if (this.totalCapByZone.get(zone) < newOcc) { + String s = "FacilityID: " + this.parkingFacilityLocationByVehicleId.get(vehicleId); + String t = "Occupied: " + this.infoByFacilityId.get(this.parkingFacilityLocationByVehicleId.get(vehicleId)).occupation; + String u = + "Capacity: " + this.parkingFacilitiesById.get(this.parkingFacilityLocationByVehicleId.get(vehicleId)).getActivityOptions() + .get( + ParkingUtils.ParkingStageInteractionType).getCapacity(); String v = "TotalCapacityOnLink: " + getNrOfAllParkingSpacesOnLink(linkId); - throw new RuntimeException("occupancy of zone " + zone + " is higher than 100%. Capacity= " + this.totalCapOfZone.get( + throw new RuntimeException("occupancy of zone " + zone + " is higher than 100%. Capacity= " + this.totalCapByZone.get( zone) + " occupancy=" + newOcc + "time = " + time + "\n" + s + "\n" + t + "\n" + u + "\n" + v); } - this.occupationOfZone.put(zone, newOcc); + this.occupationByZone.put(zone, newOcc); return true; // assumes: link is only part of exactly 1 zone } } return true; - } else + } else { return false; + } } @Override public boolean unParkVehicleHere(Id vehicleId, Id linkId, double time) { - if (!this.parkingLocations.containsKey(vehicleId)) { + if (!this.parkingFacilityLocationByVehicleId.containsKey(vehicleId)) { return true; // we assume the person parks somewhere else } else { - Id fac = this.parkingLocations.remove(vehicleId); - this.occupation.get(fac).decrement(); + Id fac = this.parkingFacilityLocationByVehicleId.remove(vehicleId); + this.infoByFacilityId.get(fac).occupation--; - Id parkingLink = this.parkingFacilities.get(fac).getLinkId(); - for (String zone : this.linksOfZone.keySet()) { - if (linksOfZone.get(zone).contains(parkingLink)) { - double newOcc = this.occupationOfZone.get(zone) - 1; + Id parkingLink = this.parkingFacilitiesById.get(fac).getLinkId(); + for (String zone : this.linksByZone.keySet()) { + if (linksByZone.get(zone).contains(parkingLink)) { + double newOcc = this.occupationByZone.get(zone) - 1; if (newOcc < 0) { //in iteration 0 agents can "leave parking spaces" (get into traffic), but the manager didn't record them to be parked newOcc = 0; } - this.occupationOfZone.put(zone, newOcc); + this.occupationByZone.put(zone, newOcc); } } return true; @@ -135,18 +142,19 @@ public boolean unParkVehicleHere(Id vehicleId, Id linkId, double public double getOccupancyRatioOfZone(String zone) { - if (!(this.linksOfZone.keySet().contains(zone))) + if (!(this.linksByZone.keySet().contains(zone))) { throw new RuntimeException("zone " + zone + " was not defined. thus, could'nt calculate occupancy ratio."); + } - return (this.occupationOfZone.get(zone) / this.totalCapOfZone.get(zone)); + return (this.occupationByZone.get(zone) / this.totalCapByZone.get(zone)); } public Set getZones() { - return this.linksOfZone.keySet(); + return this.linksByZone.keySet(); } public double getTotalCapacityOfZone(String zone) { - return this.totalCapOfZone.get(zone); + return this.totalCapByZone.get(zone); } } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/search/BenensonParkingSearchLogic.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/search/BenensonParkingSearchLogic.java index 6b8d1f7bcff..adb5ee1dbb8 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/search/BenensonParkingSearchLogic.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/search/BenensonParkingSearchLogic.java @@ -19,58 +19,57 @@ /** * @author schlenther - * - *the matsim version of the parking strategy used in PARKAGENT. see the following paper for more information: - *doi: 10.1016/j.compenvurbsys.2008.09.011 - * + *

+ * the matsim version of the parking strategy used in PARKAGENT. see the following paper for more information: + * doi: 10.1016/j.compenvurbsys.2008.09.011 */ public class BenensonParkingSearchLogic implements ParkingSearchLogic { private static final Logger logger = LogManager.getLogger(BenensonDynLeg.class); private static final boolean logForDebug = false; - + private Network network; private static final double MIN_THRESHOLD_PROB_FUNCTION = 2; private static final double MAX_THRESHOLD_PROB_FUNCTION = 4; - //thresholds for phase transitions: 1->2 and 2->3 + //thresholds for phase transitions: 1->2 and 2->3 private static final double THRESHOLD_OBSERVING_METER = 1000; private static final double THRESHOLD_PARKING_METER = 500; - + private static final double ACCEPTED_DISTANCE_START = 100; private static final double ACCEPTED_DISTANCE_INCREASING_RATE_PER_MIN = 100; private static final double ACCEPTED_DISTANCE_MAX = 600; - + private final Random random = MatsimRandom.getLocalInstance(); - + private ParkingSearchConfigGroup configGroup; - + public BenensonParkingSearchLogic(Network network, ParkingSearchConfigGroup cfgGroup) { this.network = network; this.configGroup = cfgGroup; } - + @Override public void reset() { } - //----------------------------------------------------phase transitions---------------------------------------------------------------------------- + //----------------------------------------------------phase + // transitions---------------------------------------------------------------------------- - public boolean transitionToObservingBehaviour(Id currLinkId, Id endLinkId) { + public boolean transitionToObservingBehaviour(Id currLinkId, Id endLinkId) { double distToDest = NetworkUtils.getEuclideanDistance( - network.getLinks().get(currLinkId).getCoord(), network.getLinks().get(endLinkId).getCoord()); - return distToDest < THRESHOLD_OBSERVING_METER ; + network.getLinks().get(currLinkId).getCoord(), network.getLinks().get(endLinkId).getCoord()); + return distToDest < THRESHOLD_OBSERVING_METER; } - public boolean transitionToParkingBehaviour(Id currLinkId, Id endLinkId) { + public boolean transitionToParkingBehaviour(Id currLinkId, Id endLinkId) { double distToDest = NetworkUtils.getEuclideanDistance( - network.getLinks().get(currLinkId).getCoord(), network.getLinks().get(endLinkId).getCoord()); - return distToDest < THRESHOLD_PARKING_METER ; + network.getLinks().get(currLinkId).getCoord(), network.getLinks().get(endLinkId).getCoord()); + return distToDest < THRESHOLD_PARKING_METER; } - + //-------------------------------------------------------routing--------------------------------------------------------------------------- - + /** - * * @param currentLinkId * @param destinationLinkId * @return @@ -78,9 +77,9 @@ public boolean transitionToParkingBehaviour(Id currLinkId, Id endLin public Id getNextLinkBenensonRouting(Id currentLinkId, Id destinationLinkId, String mode) { Link currentLink = network.getLinks().get(currentLinkId); - //calculate the distance to fromNode of destination link instead of distance to activity + //calculate the distance to fromNode of destination link instead of distance to activity Node destination = network.getLinks().get(destinationLinkId).getFromNode(); - + double distanceToDest = Double.MAX_VALUE; Node nextNode; Id nextLinkId = null; @@ -91,13 +90,12 @@ public Id getNextLinkBenensonRouting(Id currentLinkId, Id dest return outLinkId; } nextNode = outLink.getToNode(); - double dd = NetworkUtils.getEuclideanDistance(destination.getCoord(),nextNode.getCoord()); - if( dd < distanceToDest){ + double dd = NetworkUtils.getEuclideanDistance(destination.getCoord(), nextNode.getCoord()); + if (dd < distanceToDest) { nextLinkId = outLinkId; distanceToDest = dd; - } - else if(dd == distanceToDest){ - if (Math.random() > 0.5){ + } else if (dd == distanceToDest) { + if (random.nextBoolean()) { nextLinkId = outLinkId; } } @@ -105,7 +103,8 @@ else if(dd == distanceToDest){ return nextLinkId; } - public Id getNextLinkRandomInAcceptableDistance(Id currentLinkId, Id endLinkId, Id vehicleId, double firstDestLinkEnterTime, double timeOfDay, String mode) { + public Id getNextLinkRandomInAcceptableDistance(Id currentLinkId, Id endLinkId, Id vehicleId, + double firstDestLinkEnterTime, double timeOfDay, String mode) { Link nextLink; Link currentLink = network.getLinks().get(currentLinkId); @@ -114,10 +113,14 @@ public Id getNextLinkRandomInAcceptableDistance(Id currentLinkId, Id int nrOfOutGoingLinks = outGoingLinks.size(); for (int i = 1; i <= nrOfOutGoingLinks; i++) { nextLink = outGoingLinks.get(random.nextInt(outGoingLinks.size())); - if (isDriverInAcceptableDistance(nextLink.getId(), endLinkId, firstDestLinkEnterTime, timeOfDay)) return nextLink.getId(); + if (isDriverInAcceptableDistance(nextLink.getId(), endLinkId, firstDestLinkEnterTime, timeOfDay)) { + return nextLink.getId(); + } outGoingLinks.remove(nextLink); - } - logger.error("vehicle " + vehicleId + " finds no outlink in acceptable distance going out from link " + currentLinkId + ". it just takes a random next link"); + } + logger.error("vehicle " + vehicleId + " finds no outlink in acceptable distance going out from link " + currentLinkId + ". it just takes a" + + " " + + "random next link"); return outGoingLinksCopy.get(random.nextInt(outGoingLinksCopy.size())).getId(); } @@ -125,63 +128,70 @@ public Id getNextLinkRandomInAcceptableDistance(Id currentLinkId, Id //---------------------------------------------------park decision----------------------------------------------------------------------- /** - * * estimate amount of free parking spaces on the way to destination Link and decide whether to park on currentLink - * + * * @param pUnoccupied * @param currentLinkId * @param endLinkId - * @return whether vehicle should be parked here + * @return whether vehicle should be parked here */ - public boolean wantToParkHere (double pUnoccupied, Id currentLinkId, Id endLinkId) { - - //if pUnoccupied = 0, no free slot has been detected, so it is realistic to accept the very next free slot + public boolean wantToParkHere(double pUnoccupied, Id currentLinkId, Id endLinkId) { + + //if pUnoccupied = 0, no free slot has been detected, so it is realistic to accept the very next free slot double distToDest = NetworkUtils.getEuclideanDistance( - network.getLinks().get(currentLinkId).getToNode().getCoord(), network.getLinks().get(endLinkId).getToNode().getCoord()); - double expectedFreeSlots = (pUnoccupied*distToDest/configGroup.getAvgparkingslotlength()); - double rnd = Math.random(); - if (logForDebug) - logger.error("\n current link: " + currentLinkId + "\n expected slots: " + expectedFreeSlots + "\n probabilty to continue driving: " + getProbabilityOfContinuingToDrive(expectedFreeSlots) + "\n rnd: " + rnd); - return rnd >= getProbabilityOfContinuingToDrive(expectedFreeSlots); + network.getLinks().get(currentLinkId).getToNode().getCoord(), network.getLinks().get(endLinkId).getToNode().getCoord()); + double expectedFreeSlots = (pUnoccupied * distToDest / configGroup.getAvgparkingslotlength()); + double rnd = random.nextDouble(); + if (logForDebug) { + logger.error("\n current link: " + currentLinkId + "\n expected slots: " + expectedFreeSlots + "\n probabilty to continue driving: " + getProbabilityOfContinuingToDrive(expectedFreeSlots) + "\n rnd: " + rnd); + } + return rnd >= getProbabilityOfContinuingToDrive(expectedFreeSlots); } - + /** - * linear probability function, depending on maximum and minimum threshold + * linear probability function, depending on maximum and minimum threshold */ - private double getProbabilityOfContinuingToDrive(double expectedFreeSlots) { - - if (expectedFreeSlots < MIN_THRESHOLD_PROB_FUNCTION) return 0.0; - else if(expectedFreeSlots > MAX_THRESHOLD_PROB_FUNCTION) return 1.0; - - return (expectedFreeSlots-MIN_THRESHOLD_PROB_FUNCTION)/(MAX_THRESHOLD_PROB_FUNCTION-MIN_THRESHOLD_PROB_FUNCTION); + private double getProbabilityOfContinuingToDrive(double expectedFreeSlots) { + + if (expectedFreeSlots < MIN_THRESHOLD_PROB_FUNCTION) { + return 0.0; + } else if (expectedFreeSlots > MAX_THRESHOLD_PROB_FUNCTION) { + return 1.0; + } + + return (expectedFreeSlots - MIN_THRESHOLD_PROB_FUNCTION) / (MAX_THRESHOLD_PROB_FUNCTION - MIN_THRESHOLD_PROB_FUNCTION); } /** - * * @param currentLinkId * @param endLinkId - * @param firstDestLinkEnterTime + * @param firstDestLinkEnterTime * @param timeOfDay * @return */ - private boolean isDriverInAcceptableDistance(Id currentLinkId, Id endLinkId, double firstDestLinkEnterTime, double timeOfDay) { + private boolean isDriverInAcceptableDistance(Id currentLinkId, Id endLinkId, double firstDestLinkEnterTime, double timeOfDay) { // if we're on the destinationLink, we always want to park - if(currentLinkId.equals(endLinkId)) return true; - - double distToDest = NetworkUtils.getEuclideanDistance(network.getLinks().get(currentLinkId).getCoord(), network.getLinks().get(endLinkId).getCoord()); + if (currentLinkId.equals(endLinkId)) { + return true; + } + + double distToDest = NetworkUtils.getEuclideanDistance(network.getLinks().get(currentLinkId).getCoord(), network.getLinks().get(endLinkId) + .getCoord()); double timeSpent = timeOfDay - firstDestLinkEnterTime; double acceptedDistance = ACCEPTED_DISTANCE_START + ACCEPTED_DISTANCE_INCREASING_RATE_PER_MIN * (timeSpent / 60); - - if (acceptedDistance > ACCEPTED_DISTANCE_MAX) acceptedDistance = ACCEPTED_DISTANCE_MAX; - - if (distToDest <= acceptedDistance){ - if(logForDebug){ + + if (acceptedDistance > ACCEPTED_DISTANCE_MAX) { + acceptedDistance = ACCEPTED_DISTANCE_MAX; + } + + if (distToDest <= acceptedDistance) { + if (logForDebug) { logger.error(" distance between link " + currentLinkId + " and destLink " + endLinkId + ": " + distToDest); logger.error("accepted : " + acceptedDistance); logger.error("time spent: " + timeSpent); } - return true; + return true; } return false; } @@ -190,5 +200,5 @@ private boolean isDriverInAcceptableDistance(Id currentLinkId, Id en public Id getNextLink(Id currentLinkId, Id vehicleId, String mode) { throw new RuntimeException("this should not happen!"); } - + } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/search/DistanceMemoryParkingSearchLogic.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/search/DistanceMemoryParkingSearchLogic.java index c4616c7df1e..5529e5b3c0a 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/search/DistanceMemoryParkingSearchLogic.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/search/DistanceMemoryParkingSearchLogic.java @@ -1,5 +1,5 @@ /** - * + * */ package org.matsim.contrib.parking.parkingsearch.search; @@ -19,24 +19,24 @@ /** * @author tschlenther - * - *Agents drive to destination first. Knowledge about surrounding streets is assumed. If no parking slot is available, they always look - *for a slot on the one outgoing link that has the shortest distance to their destination and is unknown to them so far. If every outlink - *is known they choose the next link to search on randomly. - * + *

+ * Agents drive to destination first. Knowledge about surrounding streets is assumed. If no parking slot is available, they always look + * for a slot on the one outgoing link that has the shortest distance to their destination and is unknown to them so far. If every outlink + * is known they choose the next link to search on randomly. */ public class DistanceMemoryParkingSearchLogic implements ParkingSearchLogic { private static final Logger logger = LogManager.getLogger(DistanceMemoryParkingSearchLogic.class); - private static final boolean doLogging = false; - +// static { +// Configurator.setRootLevel(org.apache.logging.log4j.Level.DEBUG); +// } + private Network network; - private HashSet> knownLinks; - + private HashSet> knownLinks; + /** - * @param network - * + * @param network */ public DistanceMemoryParkingSearchLogic(Network network) { this.network = network; @@ -49,49 +49,50 @@ public Id getNextLink(Id currentLinkId, Id destLinkId, Id nextLink = null; - - if(doLogging) logger.info("number of outlinks of link " + currentLinkId + ": " + outLinks.size()); + + logger.debug("number of outlinks of link {}: {}", currentLinkId, outLinks.size()); for (Link outLink : outLinks) { Id outLinkId = outLink.getId(); - if (this.knownLinks.contains(outLinkId)) nrKnownLinks++; - else{ + if (this.knownLinks.contains(outLinkId)) { + nrKnownLinks++; + } else { double distToDest = NetworkUtils.getEuclideanDistance(outLink.getCoord(), network.getLinks().get(destLinkId).getCoord()); - if (distToDest < shortestDistance){ + if (distToDest < shortestDistance) { nextLink = outLinkId; shortestDistance = distToDest; - if(doLogging) logger.info("currently chosen link: " + nextLink + " distToDest: " + shortestDistance); - } - else if(distToDest == shortestDistance){ + logger.debug("currently chosen link: {} distToDest: {}", nextLink, shortestDistance); + } else if (distToDest == shortestDistance) { String message = "link " + nextLink + " and link " + outLinkId + " both are " + distToDest + "m away from destination."; - if (Math.random() > 0.5) - nextLink = outLinkId; - if(doLogging) logger.info(message + " link " + nextLink + " is chosen."); - } - else{ - if (doLogging){ - logger.info("link " + outLinkId + " was not chosen because it is " + distToDest + "m away whereas shortest distance is " + shortestDistance); + if (MatsimRandom.getRandom().nextBoolean()) { + nextLink = outLinkId; } + logger.debug("{} link {} is chosen.", message, nextLink); + } else { + logger.debug("link {} was not chosen because it is {}m away whereas shortest distance is {}", outLinkId, distToDest, + shortestDistance); } } } - if(doLogging)logger.error("vehicle " + vehicleId + " knew " + nrKnownLinks + " out of " + outLinks.size() + " outlinks of link " + currentLinkId); - if(outLinks.size() == nrKnownLinks ){ - if(doLogging)logger.error("vehicle " + vehicleId + " knows all outlinks of link " + currentLinkId); - + logger.debug("vehicle {} knew {} out of {} outlinks of link {}", vehicleId, nrKnownLinks, outLinks.size(), currentLinkId); + if (outLinks.size() == nrKnownLinks) { + logger.debug("vehicle {} knows all outlinks of link {}", vehicleId, currentLinkId); + //return random Link int index = MatsimRandom.getRandom().nextInt(outLinks.size()); Iterator iter = outLinks.iterator(); for (int i = 0; i < index; i++) { - iter.next(); + iter.next(); } nextLink = iter.next().getId(); - } - - if(nextLink == null){ - throw new RuntimeException("the next Link Id for vehicle " + vehicleId + " on current link " + currentLinkId + " couldn't be calculated."); } - if(doLogging)logger.error("vehicle " + vehicleId + " takes link " + nextLink + " as next link"); + + if (nextLink == null) { + throw new RuntimeException("the next Link Id for vehicle " + vehicleId + " on current link " + currentLinkId + " couldn't be " + + "calculated" + + "."); + } + logger.debug("vehicle {} takes link {} as next link", vehicleId, nextLink); this.knownLinks.add(nextLink); return nextLink; } @@ -105,8 +106,8 @@ public Id getNextLink(Id currentLinkId, Id vehicleId, Strin throw new RuntimeException("shouldn't happen - method not implemented"); } - public void addToKnownLinks(Id linkId){ + public void addToKnownLinks(Id linkId) { this.knownLinks.add(linkId); } - + } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/search/NearestParkingSpotSearchLogic.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/search/NearestParkingSpotSearchLogic.java index d87bf0408fe..de4be67c97f 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/search/NearestParkingSpotSearchLogic.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/search/NearestParkingSpotSearchLogic.java @@ -69,7 +69,7 @@ public NearestParkingSpotSearchLogic(Network network, ParkingRouter parkingRoute this.parkingManager = parkingManager; this.canReserveParkingSlot = canReserveParkingSlot; this.canCheckParkingCapacitiesInAdvanced = canCheckParkingCapacitiesInAdvanced; - activityFacilities = ((FacilityBasedParkingManager) parkingManager).getParkingFacilities(); + activityFacilities = ((FacilityBasedParkingManager) parkingManager).getParkingFacilitiesById(); currentLinkIdx = 0; triedParking = new HashSet<>(); nextLink = null; @@ -83,26 +83,30 @@ public Id getNextLink(Id currentLinkId, Id baseLinkId, Id getNextLink(Id currentLinkId, Id baseLinkId, Id baseLinkId, Coord coordOfAttraction) { for (ActivityFacility activityFacility : activityFacilities.values()) { - if (activityFacility.getLinkId().equals(baseLinkId)) + if (activityFacility.getLinkId().equals(baseLinkId)) { distanceFromBaseToAttraction = NetworkUtils.getEuclideanDistance(activityFacility.getCoord(), coordOfAttraction); + } } } /** - * Checks if it is possible to drive to the new parking facility and to drive back to the base without extending the startTime of the following activity. + * Checks if it is possible to drive to the new parking facility and to drive back to the base without extending the startTime of the following + * activity. * If the resulting parking time at the new facility is less then 5 minutes the vehicle will drive directly to the next activity location. * * @param currentLinkId @@ -148,17 +154,20 @@ private void findDistanceBetweenBaseLinkAndAttraction(Id baseLinkId, Coord private void checkIfDrivingToNextParkingLocationIsPossible(Id currentLinkId, Id baseLinkId, double now, double nextPickupTime) { double expectedTravelTimeFromParkingToBase; - if (actualRoute == null) + if (actualRoute == null) { expectedTravelTimeFromParkingToBase = this.parkingRouter.getRouteFromParkingToDestination(baseLinkId, now, currentLinkId).getTravelTime().seconds(); //TODO better: use the nextLink for the check - else + } else { expectedTravelTimeFromParkingToBase = this.parkingRouter.getRouteFromParkingToDestination(baseLinkId, now, actualRoute.getEndLinkId()).getTravelTime().seconds(); + } double minimumExpectedParkingDuration = 5 * 60; double travelTimeNextPart; - if (actualRoute == null) + if (actualRoute == null) { travelTimeNextPart = 0.; - else travelTimeNextPart = actualRoute.getTravelTime().seconds(); + } else { + travelTimeNextPart = actualRoute.getTravelTime().seconds(); + } if ((nextPickupTime - now - travelTimeNextPart - expectedTravelTimeFromParkingToBase) < minimumExpectedParkingDuration) { actualRoute = this.parkingRouter.getRouteFromParkingToDestination(baseLinkId, now, @@ -168,8 +177,9 @@ private void checkIfDrivingToNextParkingLocationIsPossible(Id currentLinkI } public Id getNextParkingLocation() { - if (actualRoute == null) + if (actualRoute == null) { return null; + } return actualRoute.getEndLinkId(); } @@ -208,34 +218,42 @@ private NetworkRoute findRouteToNearestParkingFacility(Id baseLinkId, Id now && parkingOptions.getOpeningTimes().first().getEndTime() < latestEndOfParking) + if (parkingOptions.getOpeningTimes().first().getStartTime() > now && parkingOptions.getOpeningTimes().first() + .getEndTime() < latestEndOfParking) { continue; + } } //check if approx. the max parking time at facility will not exceed, assumption: "parking duration - 30 minutes" is parking Time. if (activityFacility.getAttributes().getAsMap().containsKey("maxParkingDurationInHours")) { //TODO vielleicht etwas sparsamer machen double maxParkingDurationAtFacility = 3600 * (double) activityFacility.getAttributes().getAsMap().get("maxParkingDurationInHours"); - if (maxParkingDuration - 30*60 > maxParkingDurationAtFacility) + if (maxParkingDuration - 30 * 60 > maxParkingDurationAtFacility) { continue; + } } //TODO beschreiben was passiert if (passangerInteractionAtParkingFacilityAtEndOfLeg) { double distanceBetweenThisParkingFacilityAndTheAttraction = NetworkUtils.getEuclideanDistance(activityFacility.getCoord(), coordOfAttraction); - if (distanceBetweenThisParkingFacilityAndTheAttraction - distanceFromBaseToAttraction > maxDistanceFromBase) + if (distanceBetweenThisParkingFacilityAndTheAttraction - distanceFromBaseToAttraction > maxDistanceFromBase) { continue; + } } // create Euclidean distances to the parking activities to find routes only to the nearest facilities in the next step Coord coordBaseLink = network.getLinks().get(baseLinkId).getCoord(); @@ -243,10 +261,11 @@ private NetworkRoute findRouteToNearestParkingFacility(Id baseLinkId, Id baseLinkId, Id maxParkingDurationAtFacility) + if (expectedParkingTime > maxParkingDurationAtFacility) { continue; + } } counter++; - if (passangerInteractionAtParkingFacilityAtEndOfLeg && euclideanDistanceToParkingFacilities.size() > triedParking.size()) - if (triedParking.contains(activityFacility.getId())) + if (passangerInteractionAtParkingFacilityAtEndOfLeg && euclideanDistanceToParkingFacilities.size() > triedParking.size()) { + if (triedParking.contains(activityFacility.getId())) { continue; - if (passangerInteractionAtParkingFacilityAtEndOfLeg && euclideanDistanceToParkingFacilities.size() == triedParking.size()) + } + } + if (passangerInteractionAtParkingFacilityAtEndOfLeg && euclideanDistanceToParkingFacilities.size() == triedParking.size()) { triedParking.clear(); + } NetworkRoute possibleRoute = this.parkingRouter.getRouteFromParkingToDestination(activityFacility.getLinkId(), now, currentLinkId); // reason is that we expect that the driver will always take the nearest possible getOff point to reduce the walk distance for the guests - if (passangerInteractionAtParkingFacilityAtEndOfLeg){ + if (passangerInteractionAtParkingFacilityAtEndOfLeg) { selectedRoute = possibleRoute; nearstActivityFacility = activityFacility; break; @@ -292,8 +315,9 @@ private NetworkRoute findRouteToNearestParkingFacility(Id baseLinkId, Id getComments() { - Map map = super.getComments(); + Map map = super.getComments(); map.put(UNPARKDURATION, "Duration to unpark a vehicle"); map.put(PARKDURATION, "Duration to park a vehicle"); - map.put(PARKINGSEARCH_STRATEGY, "The strategy to find a parking slot. Possible strategies: " + Arrays.toString(ParkingSearchStrategy.values())); + map.put(PARKINGSEARCH_STRATEGY, + "The strategy to find a parking slot. Possible strategies: " + Arrays.toString(ParkingSearchStrategy.values())); map.put(PARKINGSEARCH_MANAGER, "The type of the ParkingManager, may have the values: " + Arrays.toString(ParkingSearchManagerType.values())); - map.put(FRACTION_CAN_CHECK_FREE_CAPACITIES_IN_ADVANCED, "Fraction of agents who can check free capacities in advanced. This is currently developed for the FacilityBasedParkingManager"); - map.put(FRACTION_CAN_RESERVE_PARKING_IN_ADVANCED, "Fraction of agents who can reserve free capacities in advanced. This is currently developed for the FacilityBasedParkingManager\""); - map.put(CAN_PARK_ONLY_AT_FACILITIES, "Set if a vehicle can park only at given parking facilities or it can park freely at a link without a facility."); + map.put(FRACTION_CAN_CHECK_FREE_CAPACITIES_IN_ADVANCED, "Fraction of agents who can check free capacities in advanced. This is currently " + + "developed for the FacilityBasedParkingManager"); + map.put(FRACTION_CAN_RESERVE_PARKING_IN_ADVANCED, "Fraction of agents who can reserve free capacities in advanced. This is currently " + + "developed for the FacilityBasedParkingManager\""); + map.put(CAN_PARK_ONLY_AT_FACILITIES, "Set if a vehicle can park only at given parking facilities or it can park freely at a link without a" + + " " + + "facility."); return map; } @@ -162,11 +170,16 @@ protected void checkConsistency(Config config) { super.checkConsistency(config); - if (getFractionCanCheckFreeCapacitiesInAdvanced() != 0. && !getParkingSearchManagerType().equals(ParkingSearchManagerType.FacilityBasedParkingManager)) - log.warn("Fraction of agents who can check free capacities in advanced has no impact on your selected ParkingSearchManagerType, because it is only implemented for the FacilityBasedParkingManager."); + if (getFractionCanCheckFreeCapacitiesInAdvanced() != 0. && !getParkingSearchManagerType().equals(ParkingSearchManagerType.FacilityBasedParkingManager)) { + log.warn("Fraction of agents who can check free capacities in advanced has no impact on your selected ParkingSearchManagerType, " + + "because" + + " " + + "it is only implemented for the FacilityBasedParkingManager."); + } - if (getFractionCanCheckFreeCapacitiesInAdvanced() + getFractionCanReserveParkingInAdvanced() > 1.0) - throw new RuntimeException( "The sum of " + FRACTION_CAN_RESERVE_PARKING_IN_ADVANCED + " and " + FRACTION_CAN_CHECK_FREE_CAPACITIES_IN_ADVANCED + " is > 1.0. This should not happen."); + if (getFractionCanCheckFreeCapacitiesInAdvanced() + getFractionCanReserveParkingInAdvanced() > 1.0) { + throw new RuntimeException("The sum of " + FRACTION_CAN_RESERVE_PARKING_IN_ADVANCED + " and " + FRACTION_CAN_CHECK_FREE_CAPACITIES_IN_ADVANCED + " is > 1.0. This should not happen."); + } } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/sim/SetupParking.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/sim/SetupParking.java index 5d8c657d9bb..288434518b1 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/sim/SetupParking.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingsearch/sim/SetupParking.java @@ -22,6 +22,8 @@ */ package org.matsim.contrib.parking.parkingsearch.sim; +import com.google.inject.Key; +import com.google.inject.name.Names; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Network; import org.matsim.contrib.dvrp.router.DvrpGlobalRoutingNetworkProvider; @@ -30,15 +32,15 @@ import org.matsim.contrib.dvrp.run.DvrpConfigGroup; import org.matsim.contrib.dvrp.run.DvrpModes; import org.matsim.contrib.dvrp.trafficmonitoring.DvrpTravelTimeModule; -import org.matsim.contrib.parking.parkingsearch.evaluation.ParkingListener; import org.matsim.contrib.parking.parkingsearch.manager.FacilityBasedParkingManager; import org.matsim.contrib.parking.parkingsearch.manager.ParkingSearchManager; +import org.matsim.contrib.parking.parkingsearch.manager.ParkingStatsWriter; import org.matsim.contrib.parking.parkingsearch.manager.vehicleteleportationlogic.VehicleTeleportationLogic; import org.matsim.contrib.parking.parkingsearch.manager.vehicleteleportationlogic.VehicleTeleportationToNearbyParking; import org.matsim.contrib.parking.parkingsearch.routing.ParkingRouter; import org.matsim.contrib.parking.parkingsearch.routing.WithinDayParkingRouter; import org.matsim.core.controler.AbstractModule; -import org.matsim.core.controler.Controler; +import org.matsim.core.controler.Controller; import org.matsim.core.mobsim.qsim.PopulationModule; import org.matsim.core.mobsim.qsim.components.QSimComponentsConfig; import org.matsim.core.mobsim.qsim.components.StandardQSimComponentConfigurator; @@ -46,9 +48,6 @@ import org.matsim.core.router.speedy.SpeedyALTFactory; import org.matsim.core.router.util.TravelTime; -import com.google.inject.Key; -import com.google.inject.name.Names; - /** * @author jbischoff */ @@ -56,41 +55,42 @@ public class SetupParking { // TODO: create config group and make this all configurable? - static public void installParkingModules(Controler controler) { + static public void installParkingModules(Controller controller) { // No need to route car routes in Routing module in advance, as they are // calculated on the fly - if (!controler.getConfig().getModules().containsKey(DvrpConfigGroup.GROUP_NAME)) { - controler.getConfig().addModule(new DvrpConfigGroup()); + if (!controller.getConfig().getModules().containsKey(DvrpConfigGroup.GROUP_NAME)) { + controller.getConfig().addModule(new DvrpConfigGroup()); } - controler.addOverridingModule(new DvrpTravelTimeModule()); - controler.addOverridingModule(new AbstractModule() { + controller.addOverridingModule(new DvrpTravelTimeModule()); + controller.addOverridingModule(new AbstractModule() { @Override public void install() { bind(TravelTime.class).annotatedWith(DvrpModes.mode(TransportMode.car)) - .to(Key.get(TravelTime.class, Names.named(DvrpTravelTimeModule.DVRP_ESTIMATED))); + .to(Key.get(TravelTime.class, Names.named(DvrpTravelTimeModule.DVRP_ESTIMATED))); bind(TravelDisutilityFactory.class).annotatedWith(DvrpModes.mode(TransportMode.car)) - .toInstance(TimeAsTravelDisutility::new); + .toInstance(TimeAsTravelDisutility::new); bind(Network.class).annotatedWith(DvrpModes.mode(TransportMode.car)) - .to(Key.get(Network.class, Names.named(DvrpGlobalRoutingNetworkProvider.DVRP_ROUTING))); + .to(Key.get(Network.class, Names.named(DvrpGlobalRoutingNetworkProvider.DVRP_ROUTING))); install(new DvrpModeRoutingModule(TransportMode.car, new SpeedyALTFactory())); bind(Network.class).annotatedWith(Names.named(DvrpGlobalRoutingNetworkProvider.DVRP_ROUTING)) - .to(Network.class) - .asEagerSingleton(); + .to(Network.class) + .asEagerSingleton(); bind(ParkingSearchManager.class).to(FacilityBasedParkingManager.class).asEagerSingleton(); + bind(ParkingStatsWriter.class); this.install(new ParkingSearchQSimModule()); - addControlerListenerBinding().to(ParkingListener.class); + addControlerListenerBinding().to(ParkingSearchManager.class); bind(ParkingRouter.class).to(WithinDayParkingRouter.class); bind(VehicleTeleportationLogic.class).to(VehicleTeleportationToNearbyParking.class); } }); - controler.addOverridingModule(new AbstractModule() { + controller.addOverridingModule(new AbstractModule() { @Override public void install() { QSimComponentsConfig components = new QSimComponentsConfig(); - new StandardQSimComponentConfigurator(controler.getConfig()).configure(components); + new StandardQSimComponentConfigurator(controller.getConfig()).configure(components); components.removeNamedComponent(PopulationModule.COMPONENT_NAME); components.addNamedComponent(ParkingSearchPopulationModule.COMPONENT_NAME); diff --git a/contribs/parking/src/main/resources/parkingsearch/parkingFacilities.xml b/contribs/parking/src/main/resources/parkingsearch/parkingFacilities.xml index 95ecbfd1cc2..8f2228dcb5b 100644 --- a/contribs/parking/src/main/resources/parkingsearch/parkingFacilities.xml +++ b/contribs/parking/src/main/resources/parkingsearch/parkingFacilities.xml @@ -2,36 +2,36 @@ - + - - + + - - + + - + - - + + - - + + - + diff --git a/contribs/parking/src/main/resources/parkingsearch/population1.xml b/contribs/parking/src/main/resources/parkingsearch/population1.xml new file mode 100644 index 00000000000..4bace31f8e2 --- /dev/null +++ b/contribs/parking/src/main/resources/parkingsearch/population1.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/parking/src/main/resources/parkingsearch/population10.xml b/contribs/parking/src/main/resources/parkingsearch/population10.xml new file mode 100644 index 00000000000..059d8165658 --- /dev/null +++ b/contribs/parking/src/main/resources/parkingsearch/population10.xml @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingchoice/run/RunParkingSearchScenarioIT.java b/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingchoice/run/RunParkingSearchScenarioIT.java deleted file mode 100644 index e3959961195..00000000000 --- a/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingchoice/run/RunParkingSearchScenarioIT.java +++ /dev/null @@ -1,157 +0,0 @@ -/* *********************************************************************** * - * project: org.matsim.* - * * - * *********************************************************************** * - * * - * copyright : (C) 2017 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** */ - -package org.matsim.contrib.parking.parkingchoice.run; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.population.Person; -import org.matsim.api.core.v01.population.Population; -import org.matsim.contrib.parking.parkingsearch.ParkingSearchStrategy; -import org.matsim.contrib.parking.parkingsearch.RunParkingSearchExample; -import org.matsim.contrib.parking.parkingsearch.sim.ParkingSearchConfigGroup; -import org.matsim.core.config.Config; -import org.matsim.core.config.ConfigUtils; -import org.matsim.core.events.EventsUtils; -import org.matsim.core.population.PopulationUtils; -import org.matsim.testcases.MatsimTestUtils; -import org.matsim.utils.eventsfilecomparison.ComparisonResult; - -/** - * @author jbischoff - */ -public class RunParkingSearchScenarioIT { - @RegisterExtension - private MatsimTestUtils utils = new MatsimTestUtils(); - - @Test - void testRunParkingBenesonStrategy() { - try { - String configFile = "./src/main/resources/parkingsearch/config.xml"; - Config config = ConfigUtils.loadConfig(configFile, new ParkingSearchConfigGroup()); - config.controller().setLastIteration(0); - config.controller().setOutputDirectory(utils.getOutputDirectory()); - - ParkingSearchConfigGroup configGroup = (ParkingSearchConfigGroup) config.getModules().get(ParkingSearchConfigGroup.GROUP_NAME); - configGroup.setParkingSearchStrategy(ParkingSearchStrategy.Benenson); - - new RunParkingSearchExample().run(config, false); - - } catch (Exception e) { - e.printStackTrace(); - Assertions.fail("something went wrong"); - } - } - - @Test - void testRunParkingRandomStrategy() { - String configFile = "./src/main/resources/parkingsearch/config.xml"; - Config config = ConfigUtils.loadConfig(configFile, new ParkingSearchConfigGroup()); - config.controller().setLastIteration(0); - config.controller().setOutputDirectory(utils.getOutputDirectory()); - - ParkingSearchConfigGroup configGroup = (ParkingSearchConfigGroup) config.getModules().get(ParkingSearchConfigGroup.GROUP_NAME); - configGroup.setParkingSearchStrategy(ParkingSearchStrategy.Random); - - try { - new RunParkingSearchExample().run(config, false); - } catch (Exception e) { - e.printStackTrace(); - Assertions.fail("something went wrong"); - } - } - - @Test - void testRunParkingDistanceMemoryStrategy() { - try { - String configFile = "./src/main/resources/parkingsearch/config.xml"; - Config config = ConfigUtils.loadConfig(configFile, new ParkingSearchConfigGroup()); - config.controller().setLastIteration(0); - config.controller().setOutputDirectory(utils.getOutputDirectory()); - - ParkingSearchConfigGroup configGroup = (ParkingSearchConfigGroup) config.getModules().get(ParkingSearchConfigGroup.GROUP_NAME); - configGroup.setParkingSearchStrategy(ParkingSearchStrategy.DistanceMemory); - - new RunParkingSearchExample().run(config, false); - { - Population expected = PopulationUtils.createPopulation(ConfigUtils.createConfig()); - PopulationUtils.readPopulation(expected, utils.getInputDirectory() + "/output_plans.xml.gz"); - - Population actual = PopulationUtils.createPopulation(ConfigUtils.createConfig()); - PopulationUtils.readPopulation(actual, utils.getOutputDirectory() + "/output_plans.xml.gz"); - - for (Id personId : expected.getPersons().keySet()) { - double scoreReference = expected.getPersons().get(personId).getSelectedPlan().getScore(); - double scoreCurrent = actual.getPersons().get(personId).getSelectedPlan().getScore(); - Assertions.assertEquals(scoreReference, scoreCurrent, MatsimTestUtils.EPSILON, "Scores of person=" + personId + " are different"); - } - - } - { - String expected = utils.getInputDirectory() + "/output_events.xml.gz"; - String actual = utils.getOutputDirectory() + "/output_events.xml.gz"; - ComparisonResult result = EventsUtils.compareEventsFiles(expected, actual); - Assertions.assertEquals(ComparisonResult.FILES_ARE_EQUAL, result); - } - } catch (Exception e) { - e.printStackTrace(); - Assertions.fail("something went wrong"); - } - } - - @Test - void testRunParkingNearestParkingSpotStrategy() { - try { - String configFile = "./src/main/resources/parkingsearch/config.xml"; - Config config = ConfigUtils.loadConfig(configFile, new ParkingSearchConfigGroup()); - config.controller().setLastIteration(0); - config.controller().setOutputDirectory(utils.getOutputDirectory()); - - ParkingSearchConfigGroup configGroup = (ParkingSearchConfigGroup) config.getModules().get(ParkingSearchConfigGroup.GROUP_NAME); - configGroup.setParkingSearchStrategy(ParkingSearchStrategy.NearestParkingSpot); - - new RunParkingSearchExample().run(config, false); - { - Population expected = PopulationUtils.createPopulation(ConfigUtils.createConfig()); - PopulationUtils.readPopulation(expected, utils.getInputDirectory() + "/output_plans.xml.gz"); - - Population actual = PopulationUtils.createPopulation(ConfigUtils.createConfig()); - PopulationUtils.readPopulation(actual, utils.getOutputDirectory() + "/output_plans.xml.gz"); - - for (Id personId : expected.getPersons().keySet()) { - double scoreReference = expected.getPersons().get(personId).getSelectedPlan().getScore(); - double scoreCurrent = actual.getPersons().get(personId).getSelectedPlan().getScore(); - Assertions.assertEquals(scoreReference, scoreCurrent, MatsimTestUtils.EPSILON, "Scores of person=" + personId + " are different"); - } - - } - { - String expected = utils.getInputDirectory() + "/output_events.xml.gz"; - String actual = utils.getOutputDirectory() + "/output_events.xml.gz"; - ComparisonResult result = EventsUtils.compareEventsFiles(expected, actual); - Assertions.assertEquals(ComparisonResult.FILES_ARE_EQUAL, result); - } - } catch (Exception e) { - e.printStackTrace(); - Assertions.fail("something went wrong"); - } - } -} diff --git a/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/AbstractParkingTest.java b/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/AbstractParkingTest.java new file mode 100644 index 00000000000..fee02ad587f --- /dev/null +++ b/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/AbstractParkingTest.java @@ -0,0 +1,130 @@ +package org.matsim.contrib.parking.parkingsearch.facilityBasedParking; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.Scenario; +import org.matsim.api.core.v01.population.Person; +import org.matsim.api.core.v01.population.Population; +import org.matsim.contrib.parking.parkingsearch.ParkingSearchStrategy; +import org.matsim.contrib.parking.parkingsearch.sim.ParkingSearchConfigGroup; +import org.matsim.contrib.parking.parkingsearch.sim.SetupParking; +import org.matsim.core.config.Config; +import org.matsim.core.config.ConfigUtils; +import org.matsim.core.controler.Controller; +import org.matsim.core.controler.ControllerUtils; +import org.matsim.core.events.EventsUtils; +import org.matsim.core.population.PopulationUtils; +import org.matsim.core.scenario.ScenarioUtils; +import org.matsim.testcases.MatsimTestUtils; +import org.matsim.utils.eventsfilecomparison.ComparisonResult; + +public abstract class AbstractParkingTest { + @RegisterExtension + MatsimTestUtils utils = new MatsimTestUtils(); + + abstract ParkingSearchStrategy getParkingSearchStrategy(); + + @Test + void testParking1() { + Config config = getConfig(getParkingConfig()); + config.plans().setInputFile("population1.xml"); + run(config); + validate(); + } + + @Test + void testParking10() { + Config config = getConfig(getParkingConfig()); + config.plans().setInputFile("population10.xml"); + run(config); + validate(); + } + + @Test + void testParking100() { + Config config = getConfig(getParkingConfig()); + run(config); + validate(); + } + + @Test + void testParking1_onlyFacilityParking() { + ParkingSearchConfigGroup parkingConfig = getParkingConfig(); + parkingConfig.setCanParkOnlyAtFacilities(true); + Config config = getConfig(parkingConfig); + config.plans().setInputFile("population1.xml"); + run(config); + validate(); + } + + /** + * Tests the behaviour of the parking search when only parking at facilities is allowed. + * Result: Agents are trying to park at facilities and are searching so long for a parking space until they found one. + */ + @Test + void testParking10_onlyFacilityParking() { + ParkingSearchConfigGroup parkingConfig = getParkingConfig(); + parkingConfig.setCanParkOnlyAtFacilities(true); + Config config = getConfig(parkingConfig); + config.plans().setInputFile("population10.xml"); + run(config); + validate(); + } + + private ParkingSearchConfigGroup getParkingConfig() { + ParkingSearchConfigGroup parkingSearchConfigGroup = new ParkingSearchConfigGroup(); + parkingSearchConfigGroup.setParkingSearchStrategy(getParkingSearchStrategy()); + return parkingSearchConfigGroup; + } + + private Config getConfig(ParkingSearchConfigGroup parkingSearchConfigGroup) { + Config config = ConfigUtils.loadConfig("parkingsearch/config.xml", parkingSearchConfigGroup); + config.controller().setOutputDirectory(utils.getOutputDirectory()); + config.controller().setLastIteration(0); + return config; + } + + private void run(Config config) { + Scenario scenario = ScenarioUtils.loadScenario(config); + + Controller controller = ControllerUtils.createController(scenario); + SetupParking.installParkingModules(controller); + controller.run(); + } + + private void validate() { + comparePopulation(); + compareEvents(); + compareCsv("0.parkingStats.csv"); + compareCsv("0.parkingStatsPerTimeSteps.csv"); + } + + private void compareCsv(String fileName) { + String parkingStatsOut = utils.getOutputDirectory() + "/ITERS/it.0/" + fileName; + String parkingStatsIn = utils.getInputDirectory() + "/" + fileName; + MatsimTestUtils.assertEqualFilesLineByLine(parkingStatsIn, parkingStatsOut); + } + + private void compareEvents() { + String expectedEventsFile = utils.getInputDirectory() + "/output_events.xml.gz"; + String actualEventsFile = utils.getOutputDirectory() + "/output_events.xml.gz"; + ComparisonResult result = EventsUtils.compareEventsFiles(expectedEventsFile, actualEventsFile); + Assertions.assertEquals(ComparisonResult.FILES_ARE_EQUAL, result); + } + + private void comparePopulation() { + Population expected = PopulationUtils.createPopulation(ConfigUtils.createConfig()); + PopulationUtils.readPopulation(expected, utils.getInputDirectory() + "/output_plans.xml.gz"); + + Population actual = PopulationUtils.createPopulation(ConfigUtils.createConfig()); + PopulationUtils.readPopulation(actual, utils.getOutputDirectory() + "/output_plans.xml.gz"); + + for (Id personId : expected.getPersons().keySet()) { + double scoreReference = expected.getPersons().get(personId).getSelectedPlan().getScore(); + double scoreCurrent = actual.getPersons().get(personId).getSelectedPlan().getScore(); + Assertions.assertEquals(scoreReference, scoreCurrent, MatsimTestUtils.EPSILON, "Scores of person=" + personId + " are different"); + } + } +} diff --git a/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest.java b/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest.java new file mode 100644 index 00000000000..fe21aa68bbe --- /dev/null +++ b/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest.java @@ -0,0 +1,10 @@ +package org.matsim.contrib.parking.parkingsearch.facilityBasedParking; + +import org.matsim.contrib.parking.parkingsearch.ParkingSearchStrategy; + +public class BenensonParkingTest extends AbstractParkingTest { + @Override + ParkingSearchStrategy getParkingSearchStrategy() { + return ParkingSearchStrategy.Benenson; + } +} diff --git a/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest.java b/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest.java new file mode 100644 index 00000000000..9822c5a68d5 --- /dev/null +++ b/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest.java @@ -0,0 +1,10 @@ +package org.matsim.contrib.parking.parkingsearch.facilityBasedParking; + +import org.matsim.contrib.parking.parkingsearch.ParkingSearchStrategy; + +public class DistanceMemoryParkingTest extends AbstractParkingTest { + @Override + ParkingSearchStrategy getParkingSearchStrategy() { + return ParkingSearchStrategy.DistanceMemory; + } +} diff --git a/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest.java b/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest.java new file mode 100644 index 00000000000..0403332ec60 --- /dev/null +++ b/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest.java @@ -0,0 +1,12 @@ +package org.matsim.contrib.parking.parkingsearch.facilityBasedParking; + +import org.matsim.contrib.parking.parkingsearch.ParkingSearchStrategy; + +public class NearestParkingSpotTest extends AbstractParkingTest { + @Override + ParkingSearchStrategy getParkingSearchStrategy() { + return ParkingSearchStrategy.NearestParkingSpot; + } + + //TODO something is wrong with this strategy. Even for 100 vehicles, all of them are parking in the same parking spot. +} diff --git a/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest.java b/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest.java new file mode 100644 index 00000000000..c473a821ea7 --- /dev/null +++ b/contribs/parking/src/test/java/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest.java @@ -0,0 +1,10 @@ +package org.matsim.contrib.parking.parkingsearch.facilityBasedParking; + +import org.matsim.contrib.parking.parkingsearch.ParkingSearchStrategy; + +public class RandomParkingTest extends AbstractParkingTest { + @Override + ParkingSearchStrategy getParkingSearchStrategy() { + return ParkingSearchStrategy.Random; + } +} diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingchoice/run/RunParkingSearchScenarioIT/testRunParkingDistanceMemoryStrategy/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingchoice/run/RunParkingSearchScenarioIT/testRunParkingDistanceMemoryStrategy/output_events.xml.gz deleted file mode 100644 index e80c449a03b..00000000000 Binary files a/contribs/parking/test/input/org/matsim/contrib/parking/parkingchoice/run/RunParkingSearchScenarioIT/testRunParkingDistanceMemoryStrategy/output_events.xml.gz and /dev/null differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingchoice/run/RunParkingSearchScenarioIT/testRunParkingDistanceMemoryStrategy/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingchoice/run/RunParkingSearchScenarioIT/testRunParkingDistanceMemoryStrategy/output_plans.xml.gz deleted file mode 100644 index e2a50e6fa9a..00000000000 Binary files a/contribs/parking/test/input/org/matsim/contrib/parking/parkingchoice/run/RunParkingSearchScenarioIT/testRunParkingDistanceMemoryStrategy/output_plans.xml.gz and /dev/null differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1/0.parkingStats.csv new file mode 100644 index 00000000000..11b81e47e1d --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;1;1;1;0;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;0;0;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;1;1;0;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;0;0;0;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..aee46863f7a --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1,62 @@ +time;rejectedParkingRequest;foundParking;unpark +09:00;0;0;0 +09:15;0;0;0 +09:30;0;0;0 +09:45;0;0;0 +10:00;0;0;0 +10:15;0;0;0 +10:30;0;0;0 +10:45;0;0;0 +11:00;0;0;0 +11:15;0;0;0 +11:30;0;0;0 +11:45;0;0;0 +12:00;0;0;0 +12:15;0;0;0 +12:30;0;0;0 +12:45;0;0;0 +13:00;0;0;0 +13:15;0;0;0 +13:30;0;0;0 +13:45;0;0;0 +14:00;0;0;0 +14:15;0;0;0 +14:30;0;0;0 +14:45;0;0;0 +15:00;0;0;0 +15:15;0;0;0 +15:30;0;0;0 +15:45;0;0;0 +16:00;0;0;0 +16:15;0;0;0 +16:30;0;0;0 +16:45;0;0;0 +17:00;0;0;0 +17:15;0;0;0 +17:30;0;0;0 +17:45;0;0;0 +18:00;0;0;0 +18:15;0;0;0 +18:30;0;0;0 +18:45;0;0;0 +19:00;0;0;0 +19:15;0;0;0 +19:30;0;0;0 +19:45;0;0;0 +20:00;0;0;0 +20:15;0;0;0 +20:30;0;0;0 +20:45;0;0;0 +21:00;0;0;0 +21:15;0;0;0 +21:30;0;0;0 +21:45;0;0;0 +22:00;0;0;0 +22:15;0;0;0 +22:30;0;0;0 +22:45;0;0;0 +23:00;0;0;0 +23:15;0;0;0 +23:30;0;0;0 +23:45;0;0;0 +24:00;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1/output_events.xml.gz new file mode 100644 index 00000000000..36d8ae41c21 Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1/output_plans.xml.gz new file mode 100644 index 00000000000..cf995fee841 Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10/0.parkingStats.csv new file mode 100644 index 00000000000..7bd305e83eb --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;5;10;5;5;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;0;0;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;10;5;5;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;0;0;0;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..aee46863f7a --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1,62 @@ +time;rejectedParkingRequest;foundParking;unpark +09:00;0;0;0 +09:15;0;0;0 +09:30;0;0;0 +09:45;0;0;0 +10:00;0;0;0 +10:15;0;0;0 +10:30;0;0;0 +10:45;0;0;0 +11:00;0;0;0 +11:15;0;0;0 +11:30;0;0;0 +11:45;0;0;0 +12:00;0;0;0 +12:15;0;0;0 +12:30;0;0;0 +12:45;0;0;0 +13:00;0;0;0 +13:15;0;0;0 +13:30;0;0;0 +13:45;0;0;0 +14:00;0;0;0 +14:15;0;0;0 +14:30;0;0;0 +14:45;0;0;0 +15:00;0;0;0 +15:15;0;0;0 +15:30;0;0;0 +15:45;0;0;0 +16:00;0;0;0 +16:15;0;0;0 +16:30;0;0;0 +16:45;0;0;0 +17:00;0;0;0 +17:15;0;0;0 +17:30;0;0;0 +17:45;0;0;0 +18:00;0;0;0 +18:15;0;0;0 +18:30;0;0;0 +18:45;0;0;0 +19:00;0;0;0 +19:15;0;0;0 +19:30;0;0;0 +19:45;0;0;0 +20:00;0;0;0 +20:15;0;0;0 +20:30;0;0;0 +20:45;0;0;0 +21:00;0;0;0 +21:15;0;0;0 +21:30;0;0;0 +21:45;0;0;0 +22:00;0;0;0 +22:15;0;0;0 +22:30;0;0;0 +22:45;0;0;0 +23:00;0;0;0 +23:15;0;0;0 +23:30;0;0;0 +23:45;0;0;0 +24:00;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10/output_events.xml.gz new file mode 100644 index 00000000000..fd76d129a1b Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10/output_plans.xml.gz new file mode 100644 index 00000000000..b49179b7c90 Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking100/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking100/0.parkingStats.csv new file mode 100644 index 00000000000..ee6192c5425 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking100/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;5;104;5;99;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;26;10;16;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;107;10;97;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;5;30;5;25;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking100/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking100/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..716c4f390f1 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking100/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1,62 @@ +time;rejectedParkingRequest;foundParking;unpark +09:00;0;0;3 +09:15;0;0;1 +09:30;0;0;2 +09:45;0;0;0 +10:00;0;0;0 +10:15;0;0;0 +10:30;0;0;0 +10:45;0;0;0 +11:00;0;0;0 +11:15;0;0;0 +11:30;0;0;0 +11:45;0;0;0 +12:00;0;0;0 +12:15;0;0;0 +12:30;0;0;0 +12:45;0;0;0 +13:00;0;0;0 +13:15;0;0;0 +13:30;0;0;0 +13:45;0;0;0 +14:00;0;0;0 +14:15;0;0;0 +14:30;0;0;0 +14:45;0;0;0 +15:00;0;0;0 +15:15;0;0;0 +15:30;0;0;0 +15:45;0;0;0 +16:00;0;0;0 +16:15;0;0;0 +16:30;0;0;0 +16:45;0;0;0 +17:00;0;0;0 +17:15;0;0;0 +17:30;0;0;0 +17:45;0;0;0 +18:00;0;0;0 +18:15;0;0;0 +18:30;0;0;0 +18:45;0;0;0 +19:00;0;0;0 +19:15;0;0;0 +19:30;0;0;0 +19:45;0;0;0 +20:00;0;0;0 +20:15;0;0;0 +20:30;0;0;0 +20:45;0;0;0 +21:00;0;0;0 +21:15;0;0;0 +21:30;0;0;0 +21:45;0;0;0 +22:00;0;0;0 +22:15;0;0;0 +22:30;0;0;0 +22:45;0;0;0 +23:00;0;0;0 +23:15;0;0;0 +23:30;0;0;0 +23:45;0;0;0 +24:00;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking100/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking100/output_events.xml.gz new file mode 100644 index 00000000000..3300cf6fc43 Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking100/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking100/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking100/output_plans.xml.gz new file mode 100644 index 00000000000..d18738479e9 Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking100/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10OnlyFacilityParking/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10OnlyFacilityParking/0.parkingStats.csv new file mode 100644 index 00000000000..dcdd85c0325 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10OnlyFacilityParking/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;5;12;5;7;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;3;3;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;15;7;8;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;5;5;5;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10OnlyFacilityParking/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10OnlyFacilityParking/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..fc35dee9a03 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10OnlyFacilityParking/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1 @@ +time;rejectedParkingRequest;foundParking;unpark diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10OnlyFacilityParking/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10OnlyFacilityParking/output_events.xml.gz new file mode 100644 index 00000000000..983cb03d56a Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10OnlyFacilityParking/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10OnlyFacilityParking/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10OnlyFacilityParking/output_plans.xml.gz new file mode 100644 index 00000000000..63644bd8eb6 Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10OnlyFacilityParking/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10_onlyFacilityParking/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10_onlyFacilityParking/0.parkingStats.csv new file mode 100644 index 00000000000..dcdd85c0325 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10_onlyFacilityParking/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;5;12;5;7;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;3;3;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;15;7;8;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;5;5;5;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..fc35dee9a03 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1 @@ +time;rejectedParkingRequest;foundParking;unpark diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10_onlyFacilityParking/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10_onlyFacilityParking/output_events.xml.gz new file mode 100644 index 00000000000..983cb03d56a Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10_onlyFacilityParking/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10_onlyFacilityParking/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10_onlyFacilityParking/output_plans.xml.gz new file mode 100644 index 00000000000..63644bd8eb6 Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking10_onlyFacilityParking/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1OnlyFacilityParking/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1OnlyFacilityParking/0.parkingStats.csv new file mode 100644 index 00000000000..11b81e47e1d --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1OnlyFacilityParking/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;1;1;1;0;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;0;0;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;1;1;0;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;0;0;0;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1OnlyFacilityParking/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1OnlyFacilityParking/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..fc35dee9a03 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1OnlyFacilityParking/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1 @@ +time;rejectedParkingRequest;foundParking;unpark diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1OnlyFacilityParking/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1OnlyFacilityParking/output_events.xml.gz new file mode 100644 index 00000000000..36d8ae41c21 Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1OnlyFacilityParking/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1OnlyFacilityParking/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1OnlyFacilityParking/output_plans.xml.gz new file mode 100644 index 00000000000..cf995fee841 Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1OnlyFacilityParking/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1_onlyFacilityParking/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1_onlyFacilityParking/0.parkingStats.csv new file mode 100644 index 00000000000..11b81e47e1d --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1_onlyFacilityParking/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;1;1;1;0;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;0;0;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;1;1;0;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;0;0;0;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..fc35dee9a03 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1 @@ +time;rejectedParkingRequest;foundParking;unpark diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1_onlyFacilityParking/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1_onlyFacilityParking/output_events.xml.gz new file mode 100644 index 00000000000..36d8ae41c21 Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1_onlyFacilityParking/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1_onlyFacilityParking/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1_onlyFacilityParking/output_plans.xml.gz new file mode 100644 index 00000000000..cf995fee841 Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/BenensonParkingTest/testParking1_onlyFacilityParking/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1/0.parkingStats.csv new file mode 100644 index 00000000000..11b81e47e1d --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;1;1;1;0;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;0;0;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;1;1;0;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;0;0;0;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..aee46863f7a --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1,62 @@ +time;rejectedParkingRequest;foundParking;unpark +09:00;0;0;0 +09:15;0;0;0 +09:30;0;0;0 +09:45;0;0;0 +10:00;0;0;0 +10:15;0;0;0 +10:30;0;0;0 +10:45;0;0;0 +11:00;0;0;0 +11:15;0;0;0 +11:30;0;0;0 +11:45;0;0;0 +12:00;0;0;0 +12:15;0;0;0 +12:30;0;0;0 +12:45;0;0;0 +13:00;0;0;0 +13:15;0;0;0 +13:30;0;0;0 +13:45;0;0;0 +14:00;0;0;0 +14:15;0;0;0 +14:30;0;0;0 +14:45;0;0;0 +15:00;0;0;0 +15:15;0;0;0 +15:30;0;0;0 +15:45;0;0;0 +16:00;0;0;0 +16:15;0;0;0 +16:30;0;0;0 +16:45;0;0;0 +17:00;0;0;0 +17:15;0;0;0 +17:30;0;0;0 +17:45;0;0;0 +18:00;0;0;0 +18:15;0;0;0 +18:30;0;0;0 +18:45;0;0;0 +19:00;0;0;0 +19:15;0;0;0 +19:30;0;0;0 +19:45;0;0;0 +20:00;0;0;0 +20:15;0;0;0 +20:30;0;0;0 +20:45;0;0;0 +21:00;0;0;0 +21:15;0;0;0 +21:30;0;0;0 +21:45;0;0;0 +22:00;0;0;0 +22:15;0;0;0 +22:30;0;0;0 +22:45;0;0;0 +23:00;0;0;0 +23:15;0;0;0 +23:30;0;0;0 +23:45;0;0;0 +24:00;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1/output_events.xml.gz new file mode 100644 index 00000000000..2bc7be4d53f Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1/output_plans.xml.gz new file mode 100644 index 00000000000..26b51e95fff Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10/0.parkingStats.csv new file mode 100644 index 00000000000..2ee1656326c --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;5;10;5;5;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;5;5;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;10;5;5;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;5;5;5;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..aee46863f7a --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1,62 @@ +time;rejectedParkingRequest;foundParking;unpark +09:00;0;0;0 +09:15;0;0;0 +09:30;0;0;0 +09:45;0;0;0 +10:00;0;0;0 +10:15;0;0;0 +10:30;0;0;0 +10:45;0;0;0 +11:00;0;0;0 +11:15;0;0;0 +11:30;0;0;0 +11:45;0;0;0 +12:00;0;0;0 +12:15;0;0;0 +12:30;0;0;0 +12:45;0;0;0 +13:00;0;0;0 +13:15;0;0;0 +13:30;0;0;0 +13:45;0;0;0 +14:00;0;0;0 +14:15;0;0;0 +14:30;0;0;0 +14:45;0;0;0 +15:00;0;0;0 +15:15;0;0;0 +15:30;0;0;0 +15:45;0;0;0 +16:00;0;0;0 +16:15;0;0;0 +16:30;0;0;0 +16:45;0;0;0 +17:00;0;0;0 +17:15;0;0;0 +17:30;0;0;0 +17:45;0;0;0 +18:00;0;0;0 +18:15;0;0;0 +18:30;0;0;0 +18:45;0;0;0 +19:00;0;0;0 +19:15;0;0;0 +19:30;0;0;0 +19:45;0;0;0 +20:00;0;0;0 +20:15;0;0;0 +20:30;0;0;0 +20:45;0;0;0 +21:00;0;0;0 +21:15;0;0;0 +21:30;0;0;0 +21:45;0;0;0 +22:00;0;0;0 +22:15;0;0;0 +22:30;0;0;0 +22:45;0;0;0 +23:00;0;0;0 +23:15;0;0;0 +23:30;0;0;0 +23:45;0;0;0 +24:00;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10/output_events.xml.gz new file mode 100644 index 00000000000..a216a012aef Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10/output_plans.xml.gz new file mode 100644 index 00000000000..a8ff7a8b2bd Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking100/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking100/0.parkingStats.csv new file mode 100644 index 00000000000..804d206d189 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking100/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;5;100;5;95;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;90;10;80;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;100;10;90;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;5;95;5;90;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking100/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking100/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..12979cdbad0 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking100/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1,62 @@ +time;rejectedParkingRequest;foundParking;unpark +09:00;0;0;7 +09:15;0;0;0 +09:30;0;0;0 +09:45;0;0;0 +10:00;0;0;0 +10:15;0;0;0 +10:30;0;0;0 +10:45;0;0;0 +11:00;0;0;0 +11:15;0;0;0 +11:30;0;0;0 +11:45;0;0;0 +12:00;0;0;0 +12:15;0;0;0 +12:30;0;0;0 +12:45;0;0;0 +13:00;0;0;0 +13:15;0;0;0 +13:30;0;0;0 +13:45;0;0;0 +14:00;0;0;0 +14:15;0;0;0 +14:30;0;0;0 +14:45;0;0;0 +15:00;0;0;0 +15:15;0;0;0 +15:30;0;0;0 +15:45;0;0;0 +16:00;0;0;0 +16:15;0;0;0 +16:30;0;0;0 +16:45;0;0;0 +17:00;0;0;0 +17:15;0;0;0 +17:30;0;0;0 +17:45;0;0;0 +18:00;0;0;0 +18:15;0;0;0 +18:30;0;0;0 +18:45;0;0;0 +19:00;0;0;0 +19:15;0;0;0 +19:30;0;0;0 +19:45;0;0;0 +20:00;0;0;0 +20:15;0;0;0 +20:30;0;0;0 +20:45;0;0;0 +21:00;0;0;0 +21:15;0;0;0 +21:30;0;0;0 +21:45;0;0;0 +22:00;0;0;0 +22:15;0;0;0 +22:30;0;0;0 +22:45;0;0;0 +23:00;0;0;0 +23:15;0;0;0 +23:30;0;0;0 +23:45;0;0;0 +24:00;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking100/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking100/output_events.xml.gz new file mode 100644 index 00000000000..1bb01ce6e46 Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking100/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking100/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking100/output_plans.xml.gz new file mode 100644 index 00000000000..4c78de8075a Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking100/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10_onlyFacilityParking/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10_onlyFacilityParking/0.parkingStats.csv new file mode 100644 index 00000000000..2ee1656326c --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10_onlyFacilityParking/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;5;10;5;5;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;5;5;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;10;5;5;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;5;5;5;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..fc35dee9a03 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1 @@ +time;rejectedParkingRequest;foundParking;unpark diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10_onlyFacilityParking/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10_onlyFacilityParking/output_events.xml.gz new file mode 100644 index 00000000000..a216a012aef Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10_onlyFacilityParking/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10_onlyFacilityParking/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10_onlyFacilityParking/output_plans.xml.gz new file mode 100644 index 00000000000..a8ff7a8b2bd Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking10_onlyFacilityParking/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1_onlyFacilityParking/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1_onlyFacilityParking/0.parkingStats.csv new file mode 100644 index 00000000000..11b81e47e1d --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1_onlyFacilityParking/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;1;1;1;0;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;0;0;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;1;1;0;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;0;0;0;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..fc35dee9a03 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1 @@ +time;rejectedParkingRequest;foundParking;unpark diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1_onlyFacilityParking/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1_onlyFacilityParking/output_events.xml.gz new file mode 100644 index 00000000000..2bc7be4d53f Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1_onlyFacilityParking/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1_onlyFacilityParking/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1_onlyFacilityParking/output_plans.xml.gz new file mode 100644 index 00000000000..26b51e95fff Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/DistanceMemoryParkingTest/testParking1_onlyFacilityParking/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1/0.parkingStats.csv new file mode 100644 index 00000000000..7e2bf32fac8 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;0;0;0;0;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;0;0;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;0;0;0;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;0;0;0;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..aee46863f7a --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1,62 @@ +time;rejectedParkingRequest;foundParking;unpark +09:00;0;0;0 +09:15;0;0;0 +09:30;0;0;0 +09:45;0;0;0 +10:00;0;0;0 +10:15;0;0;0 +10:30;0;0;0 +10:45;0;0;0 +11:00;0;0;0 +11:15;0;0;0 +11:30;0;0;0 +11:45;0;0;0 +12:00;0;0;0 +12:15;0;0;0 +12:30;0;0;0 +12:45;0;0;0 +13:00;0;0;0 +13:15;0;0;0 +13:30;0;0;0 +13:45;0;0;0 +14:00;0;0;0 +14:15;0;0;0 +14:30;0;0;0 +14:45;0;0;0 +15:00;0;0;0 +15:15;0;0;0 +15:30;0;0;0 +15:45;0;0;0 +16:00;0;0;0 +16:15;0;0;0 +16:30;0;0;0 +16:45;0;0;0 +17:00;0;0;0 +17:15;0;0;0 +17:30;0;0;0 +17:45;0;0;0 +18:00;0;0;0 +18:15;0;0;0 +18:30;0;0;0 +18:45;0;0;0 +19:00;0;0;0 +19:15;0;0;0 +19:30;0;0;0 +19:45;0;0;0 +20:00;0;0;0 +20:15;0;0;0 +20:30;0;0;0 +20:45;0;0;0 +21:00;0;0;0 +21:15;0;0;0 +21:30;0;0;0 +21:45;0;0;0 +22:00;0;0;0 +22:15;0;0;0 +22:30;0;0;0 +22:45;0;0;0 +23:00;0;0;0 +23:15;0;0;0 +23:30;0;0;0 +23:45;0;0;0 +24:00;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1/output_events.xml.gz new file mode 100644 index 00000000000..8e1a8f4a86a Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1/output_plans.xml.gz new file mode 100644 index 00000000000..c3d3666b97e Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10/0.parkingStats.csv new file mode 100644 index 00000000000..7e2bf32fac8 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;0;0;0;0;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;0;0;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;0;0;0;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;0;0;0;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..aee46863f7a --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1,62 @@ +time;rejectedParkingRequest;foundParking;unpark +09:00;0;0;0 +09:15;0;0;0 +09:30;0;0;0 +09:45;0;0;0 +10:00;0;0;0 +10:15;0;0;0 +10:30;0;0;0 +10:45;0;0;0 +11:00;0;0;0 +11:15;0;0;0 +11:30;0;0;0 +11:45;0;0;0 +12:00;0;0;0 +12:15;0;0;0 +12:30;0;0;0 +12:45;0;0;0 +13:00;0;0;0 +13:15;0;0;0 +13:30;0;0;0 +13:45;0;0;0 +14:00;0;0;0 +14:15;0;0;0 +14:30;0;0;0 +14:45;0;0;0 +15:00;0;0;0 +15:15;0;0;0 +15:30;0;0;0 +15:45;0;0;0 +16:00;0;0;0 +16:15;0;0;0 +16:30;0;0;0 +16:45;0;0;0 +17:00;0;0;0 +17:15;0;0;0 +17:30;0;0;0 +17:45;0;0;0 +18:00;0;0;0 +18:15;0;0;0 +18:30;0;0;0 +18:45;0;0;0 +19:00;0;0;0 +19:15;0;0;0 +19:30;0;0;0 +19:45;0;0;0 +20:00;0;0;0 +20:15;0;0;0 +20:30;0;0;0 +20:45;0;0;0 +21:00;0;0;0 +21:15;0;0;0 +21:30;0;0;0 +21:45;0;0;0 +22:00;0;0;0 +22:15;0;0;0 +22:30;0;0;0 +22:45;0;0;0 +23:00;0;0;0 +23:15;0;0;0 +23:30;0;0;0 +23:45;0;0;0 +24:00;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10/output_events.xml.gz new file mode 100644 index 00000000000..cadcc82dcbc Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10/output_plans.xml.gz new file mode 100644 index 00000000000..40f4eaec10e Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking100/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking100/0.parkingStats.csv new file mode 100644 index 00000000000..7e2bf32fac8 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking100/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;0;0;0;0;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;0;0;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;0;0;0;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;0;0;0;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking100/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking100/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..aee46863f7a --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking100/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1,62 @@ +time;rejectedParkingRequest;foundParking;unpark +09:00;0;0;0 +09:15;0;0;0 +09:30;0;0;0 +09:45;0;0;0 +10:00;0;0;0 +10:15;0;0;0 +10:30;0;0;0 +10:45;0;0;0 +11:00;0;0;0 +11:15;0;0;0 +11:30;0;0;0 +11:45;0;0;0 +12:00;0;0;0 +12:15;0;0;0 +12:30;0;0;0 +12:45;0;0;0 +13:00;0;0;0 +13:15;0;0;0 +13:30;0;0;0 +13:45;0;0;0 +14:00;0;0;0 +14:15;0;0;0 +14:30;0;0;0 +14:45;0;0;0 +15:00;0;0;0 +15:15;0;0;0 +15:30;0;0;0 +15:45;0;0;0 +16:00;0;0;0 +16:15;0;0;0 +16:30;0;0;0 +16:45;0;0;0 +17:00;0;0;0 +17:15;0;0;0 +17:30;0;0;0 +17:45;0;0;0 +18:00;0;0;0 +18:15;0;0;0 +18:30;0;0;0 +18:45;0;0;0 +19:00;0;0;0 +19:15;0;0;0 +19:30;0;0;0 +19:45;0;0;0 +20:00;0;0;0 +20:15;0;0;0 +20:30;0;0;0 +20:45;0;0;0 +21:00;0;0;0 +21:15;0;0;0 +21:30;0;0;0 +21:45;0;0;0 +22:00;0;0;0 +22:15;0;0;0 +22:30;0;0;0 +22:45;0;0;0 +23:00;0;0;0 +23:15;0;0;0 +23:30;0;0;0 +23:45;0;0;0 +24:00;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingchoice/run/RunParkingSearchScenarioIT/testRunParkingNearestParkingSpotStrategy/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking100/output_events.xml.gz similarity index 100% rename from contribs/parking/test/input/org/matsim/contrib/parking/parkingchoice/run/RunParkingSearchScenarioIT/testRunParkingNearestParkingSpotStrategy/output_events.xml.gz rename to contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking100/output_events.xml.gz diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingchoice/run/RunParkingSearchScenarioIT/testRunParkingNearestParkingSpotStrategy/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking100/output_plans.xml.gz similarity index 100% rename from contribs/parking/test/input/org/matsim/contrib/parking/parkingchoice/run/RunParkingSearchScenarioIT/testRunParkingNearestParkingSpotStrategy/output_plans.xml.gz rename to contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking100/output_plans.xml.gz diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10_onlyFacilityParking/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10_onlyFacilityParking/0.parkingStats.csv new file mode 100644 index 00000000000..7e2bf32fac8 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10_onlyFacilityParking/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;0;0;0;0;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;0;0;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;0;0;0;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;0;0;0;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..fc35dee9a03 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1 @@ +time;rejectedParkingRequest;foundParking;unpark diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10_onlyFacilityParking/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10_onlyFacilityParking/output_events.xml.gz new file mode 100644 index 00000000000..cadcc82dcbc Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10_onlyFacilityParking/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10_onlyFacilityParking/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10_onlyFacilityParking/output_plans.xml.gz new file mode 100644 index 00000000000..40f4eaec10e Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking10_onlyFacilityParking/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1_onlyFacilityParking/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1_onlyFacilityParking/0.parkingStats.csv new file mode 100644 index 00000000000..7e2bf32fac8 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1_onlyFacilityParking/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;0;0;0;0;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;0;0;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;0;0;0;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;0;0;0;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..fc35dee9a03 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1 @@ +time;rejectedParkingRequest;foundParking;unpark diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1_onlyFacilityParking/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1_onlyFacilityParking/output_events.xml.gz new file mode 100644 index 00000000000..8e1a8f4a86a Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1_onlyFacilityParking/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1_onlyFacilityParking/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1_onlyFacilityParking/output_plans.xml.gz new file mode 100644 index 00000000000..c3d3666b97e Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/NearestParkingSpotTest/testParking1_onlyFacilityParking/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1/0.parkingStats.csv new file mode 100644 index 00000000000..11b81e47e1d --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;1;1;1;0;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;0;0;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;1;1;0;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;0;0;0;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..aee46863f7a --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1,62 @@ +time;rejectedParkingRequest;foundParking;unpark +09:00;0;0;0 +09:15;0;0;0 +09:30;0;0;0 +09:45;0;0;0 +10:00;0;0;0 +10:15;0;0;0 +10:30;0;0;0 +10:45;0;0;0 +11:00;0;0;0 +11:15;0;0;0 +11:30;0;0;0 +11:45;0;0;0 +12:00;0;0;0 +12:15;0;0;0 +12:30;0;0;0 +12:45;0;0;0 +13:00;0;0;0 +13:15;0;0;0 +13:30;0;0;0 +13:45;0;0;0 +14:00;0;0;0 +14:15;0;0;0 +14:30;0;0;0 +14:45;0;0;0 +15:00;0;0;0 +15:15;0;0;0 +15:30;0;0;0 +15:45;0;0;0 +16:00;0;0;0 +16:15;0;0;0 +16:30;0;0;0 +16:45;0;0;0 +17:00;0;0;0 +17:15;0;0;0 +17:30;0;0;0 +17:45;0;0;0 +18:00;0;0;0 +18:15;0;0;0 +18:30;0;0;0 +18:45;0;0;0 +19:00;0;0;0 +19:15;0;0;0 +19:30;0;0;0 +19:45;0;0;0 +20:00;0;0;0 +20:15;0;0;0 +20:30;0;0;0 +20:45;0;0;0 +21:00;0;0;0 +21:15;0;0;0 +21:30;0;0;0 +21:45;0;0;0 +22:00;0;0;0 +22:15;0;0;0 +22:30;0;0;0 +22:45;0;0;0 +23:00;0;0;0 +23:15;0;0;0 +23:30;0;0;0 +23:45;0;0;0 +24:00;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1/output_events.xml.gz new file mode 100644 index 00000000000..2bc7be4d53f Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1/output_plans.xml.gz new file mode 100644 index 00000000000..26b51e95fff Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10/0.parkingStats.csv new file mode 100644 index 00000000000..f3c91e1630b --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;5;10;5;5;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;0;0;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;10;5;5;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;1;1;1;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..aee46863f7a --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1,62 @@ +time;rejectedParkingRequest;foundParking;unpark +09:00;0;0;0 +09:15;0;0;0 +09:30;0;0;0 +09:45;0;0;0 +10:00;0;0;0 +10:15;0;0;0 +10:30;0;0;0 +10:45;0;0;0 +11:00;0;0;0 +11:15;0;0;0 +11:30;0;0;0 +11:45;0;0;0 +12:00;0;0;0 +12:15;0;0;0 +12:30;0;0;0 +12:45;0;0;0 +13:00;0;0;0 +13:15;0;0;0 +13:30;0;0;0 +13:45;0;0;0 +14:00;0;0;0 +14:15;0;0;0 +14:30;0;0;0 +14:45;0;0;0 +15:00;0;0;0 +15:15;0;0;0 +15:30;0;0;0 +15:45;0;0;0 +16:00;0;0;0 +16:15;0;0;0 +16:30;0;0;0 +16:45;0;0;0 +17:00;0;0;0 +17:15;0;0;0 +17:30;0;0;0 +17:45;0;0;0 +18:00;0;0;0 +18:15;0;0;0 +18:30;0;0;0 +18:45;0;0;0 +19:00;0;0;0 +19:15;0;0;0 +19:30;0;0;0 +19:45;0;0;0 +20:00;0;0;0 +20:15;0;0;0 +20:30;0;0;0 +20:45;0;0;0 +21:00;0;0;0 +21:15;0;0;0 +21:30;0;0;0 +21:45;0;0;0 +22:00;0;0;0 +22:15;0;0;0 +22:30;0;0;0 +22:45;0;0;0 +23:00;0;0;0 +23:15;0;0;0 +23:30;0;0;0 +23:45;0;0;0 +24:00;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10/output_events.xml.gz new file mode 100644 index 00000000000..fa9a7b934f2 Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10/output_plans.xml.gz new file mode 100644 index 00000000000..4c36398342c Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking100/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking100/0.parkingStats.csv new file mode 100644 index 00000000000..ddfea464dac --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking100/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;5;106;5;101;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;24;10;14;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;102;10;92;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;5;22;5;17;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking100/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking100/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..89a94f7925f --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking100/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1,62 @@ +time;rejectedParkingRequest;foundParking;unpark +09:00;0;0;2 +09:15;0;0;3 +09:30;0;0;2 +09:45;0;0;0 +10:00;0;0;0 +10:15;0;0;0 +10:30;0;0;0 +10:45;0;0;0 +11:00;0;0;0 +11:15;0;0;0 +11:30;0;0;0 +11:45;0;0;0 +12:00;0;0;0 +12:15;0;0;0 +12:30;0;0;0 +12:45;0;0;0 +13:00;0;0;0 +13:15;0;0;0 +13:30;0;0;0 +13:45;0;0;0 +14:00;0;0;0 +14:15;0;0;0 +14:30;0;0;0 +14:45;0;0;0 +15:00;0;0;0 +15:15;0;0;0 +15:30;0;0;0 +15:45;0;0;0 +16:00;0;0;0 +16:15;0;0;0 +16:30;0;0;0 +16:45;0;0;0 +17:00;0;0;0 +17:15;0;0;0 +17:30;0;0;0 +17:45;0;0;0 +18:00;0;0;0 +18:15;0;0;0 +18:30;0;0;0 +18:45;0;0;0 +19:00;0;0;0 +19:15;0;0;0 +19:30;0;0;0 +19:45;0;0;0 +20:00;0;0;0 +20:15;0;0;0 +20:30;0;0;0 +20:45;0;0;0 +21:00;0;0;0 +21:15;0;0;0 +21:30;0;0;0 +21:45;0;0;0 +22:00;0;0;0 +22:15;0;0;0 +22:30;0;0;0 +22:45;0;0;0 +23:00;0;0;0 +23:15;0;0;0 +23:30;0;0;0 +23:45;0;0;0 +24:00;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking100/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking100/output_events.xml.gz new file mode 100644 index 00000000000..1ba46f218f0 Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking100/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking100/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking100/output_plans.xml.gz new file mode 100644 index 00000000000..f7d3b5d44ea Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking100/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10_onlyFacilityParking/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10_onlyFacilityParking/0.parkingStats.csv new file mode 100644 index 00000000000..8704e2ee490 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10_onlyFacilityParking/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;5;11;6;5;0;0;0 +149;300.0;-190.0;149_curbside;5.0;1;3;3;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;2;13;8;5;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;2;3;3;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..fc35dee9a03 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1 @@ +time;rejectedParkingRequest;foundParking;unpark diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10_onlyFacilityParking/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10_onlyFacilityParking/output_events.xml.gz new file mode 100644 index 00000000000..998560e4410 Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10_onlyFacilityParking/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10_onlyFacilityParking/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10_onlyFacilityParking/output_plans.xml.gz new file mode 100644 index 00000000000..c9e8cf0c736 Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking10_onlyFacilityParking/output_plans.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1_onlyFacilityParking/0.parkingStats.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1_onlyFacilityParking/0.parkingStats.csv new file mode 100644 index 00000000000..11b81e47e1d --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1_onlyFacilityParking/0.parkingStats.csv @@ -0,0 +1,5 @@ +linkId;X;Y;parkingFacility;capacity;EndOccupation;reservationsRequests;numberOfParkedVehicles;rejectedParkingRequest;numberOfWaitingActivities;numberOfStaysFromGetOffUntilGetIn;numberOfParkingBeforeGetIn +114;-300.0;-790.0;114_curbside;5.0;1;1;1;0;0;0;0 +149;300.0;-190.0;149_curbside;5.0;0;0;0;0;0;0;0 +349;300.0;-210.0;349_curbside;5.0;0;1;1;0;0;0;0 +314;-300.0;-810.0;314_curbside;5.0;0;0;0;0;0;0;0 diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv new file mode 100644 index 00000000000..fc35dee9a03 --- /dev/null +++ b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1_onlyFacilityParking/0.parkingStatsPerTimeSteps.csv @@ -0,0 +1 @@ +time;rejectedParkingRequest;foundParking;unpark diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1_onlyFacilityParking/output_events.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1_onlyFacilityParking/output_events.xml.gz new file mode 100644 index 00000000000..2bc7be4d53f Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1_onlyFacilityParking/output_events.xml.gz differ diff --git a/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1_onlyFacilityParking/output_plans.xml.gz b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1_onlyFacilityParking/output_plans.xml.gz new file mode 100644 index 00000000000..26b51e95fff Binary files /dev/null and b/contribs/parking/test/input/org/matsim/contrib/parking/parkingsearch/facilityBasedParking/RandomParkingTest/testParking1_onlyFacilityParking/output_plans.xml.gz differ diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/Data.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/Data.java index d13bbc48ae4..16029040d47 100644 --- a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/Data.java +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/Data.java @@ -3,8 +3,10 @@ import org.apache.commons.io.FilenameUtils; import org.matsim.application.CommandRunner; import org.matsim.application.MATSimAppCommand; +import org.matsim.core.utils.io.IOUtils; import javax.annotation.Nullable; +import java.io.UncheckedIOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; @@ -154,13 +156,40 @@ public String subcommand(String command, String file) { */ public String resource(String name) { - URL resource = this.getClass().getResource(name); + String path = resolveResource(name, true); + + // Handle shape files separately, copy additional files that are known to belong to shp files + if (name.endsWith(".shp")) { + resolveResource(name.replace(".shp", ".cpg"), false); + resolveResource(name.replace(".shp", ".dbf"), false); + resolveResource(name.replace(".shp", ".qix"), false); + resolveResource(name.replace(".shp", ".qmd"), false); + resolveResource(name.replace(".shp", ".prj"), false); + resolveResource(name.replace(".shp", ".shx"), false); + } + + return path; + } + + private String resolveResource(String name, boolean required) { + URL resource = null; + + try { + resource = IOUtils.resolveFileOrResource(name); + } catch (UncheckedIOException e) { + // Nothing to do + } if (resource == null) { // Try to prefix / automatically resource = this.getClass().getResource("/" + name); - if (resource == null) + } + + if (resource == null) { + if (required) throw new IllegalArgumentException("Resource '" + name + "' not found!"); + else + return null; } String baseName = FilenameUtils.getName(resource.getPath()); diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/SimWrapperConfigGroup.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/SimWrapperConfigGroup.java index 6bb420d1292..0914fda1eb7 100644 --- a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/SimWrapperConfigGroup.java +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/SimWrapperConfigGroup.java @@ -1,5 +1,6 @@ package org.matsim.simwrapper; +import org.matsim.core.config.Config; import org.matsim.core.config.ConfigGroup; import org.matsim.core.config.ReflectiveConfigGroup; @@ -28,6 +29,10 @@ public class SimWrapperConfigGroup extends ReflectiveConfigGroup { @Comment("Set of simple class names or fully qualified class names of dashboards to exclude") public Set exclude = new HashSet<>(); + @Parameter + @Comment("Set of simple class names or fully qualified class names of dashboards to include. Any none included dashboard will be excluded.") + public Set include = new HashSet<>(); + @Parameter @Comment("Sample size of the run, which may be required by certain analysis functions.") public Double sampleSize = 1.0d; @@ -83,6 +88,15 @@ public void addParameterSet(ConfigGroup set) { } } + @Override + protected void checkConsistency(Config config) { + super.checkConsistency(config); + + if (!include.isEmpty() && !exclude.isEmpty()) { + throw new IllegalStateException("Include and exclude option can't be set both."); + } + } + /** * Mode how default dashboards are loaded. */ diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/SimWrapperListener.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/SimWrapperListener.java index 1270c938ee4..b9bd8c261a3 100644 --- a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/SimWrapperListener.java +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/SimWrapperListener.java @@ -34,8 +34,8 @@ public class SimWrapperListener implements StartupListener, ShutdownListener { @Inject public SimWrapperListener(SimWrapper simWrapper, Set bindings, Config config) { this.simWrapper = simWrapper; - this.bindings = bindings; - this.config = config; + this.bindings = bindings; + this.config = config; } /** @@ -105,6 +105,9 @@ private void addFromProvider(SimWrapperConfigGroup config, Iterable exclude; + @CommandLine.Option(names = "--include", split = ",", description = "Use only the dashboards which classnames match.") + private Set include; + public static void main(String[] args) { new SimWrapperRunner().execute(args); } @@ -58,6 +61,8 @@ public Integer call() throws Exception { if (exclude != null) simWrapperConfigGroup.exclude.addAll(exclude); + if (include != null) + simWrapperConfigGroup.include.addAll(include); SimWrapperListener listener = new SimWrapperListener(SimWrapper.create(config), config); try { diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/ActivityDashboard.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/ActivityDashboard.java new file mode 100644 index 00000000000..5561ea641e8 --- /dev/null +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/ActivityDashboard.java @@ -0,0 +1,185 @@ +package org.matsim.simwrapper.dashboard; + +import org.apache.commons.lang3.StringUtils; +import org.matsim.application.analysis.activity.ActivityCountAnalysis; +import org.matsim.simwrapper.Dashboard; +import org.matsim.simwrapper.Header; +import org.matsim.simwrapper.Layout; +import org.matsim.simwrapper.viz.ColorScheme; +import org.matsim.simwrapper.viz.MapPlot; +import org.matsim.simwrapper.viz.TextBlock; + +import javax.annotation.Nullable; +import java.util.*; +import java.util.stream.Collectors; + +/** + * Dashboard to show activity related statistics aggregated by type and location. + *

+ * Note that {@link #addActivityType(String, List, List, boolean, String)} needs to be called for each activity type. + * There is no default configuration. + */ +public class ActivityDashboard implements Dashboard { + + private static final String ID_COLUMN = "id"; + private static final String REF_JOIN = "id"; + + private final String shpFile; + private final Map activityMapping = new LinkedHashMap<>(); + private final Map refCsvs = new LinkedHashMap<>(); + private final Set countMultipleOccurrencesSet = new HashSet<>(); + private List indicators = new ArrayList<>(); + + public ActivityDashboard(String shpFile) { + this.shpFile = Objects.requireNonNull(shpFile, "Shapefile can not be null!"); + } + + /** + * Convenience method to add an activity type with default configuration. + */ + public ActivityDashboard addActivityType(String name, List activities, List indicators) { + return addActivityType(name, activities, indicators, true, null); + } + + /** + * Add an activity type to the dashboard. + * + * @param name name to show in the dashboard + * @param activities List of activity names to include in this type + * @param indicators List of indicators to show + * @param countMultipleOccurrences Whether multiple occurrences of the same activity for one person should be counted. + * Can be used to count home or workplaces only once. + * @param refCsv Reference CSV file to compare the activities to. Can be null. + */ + public ActivityDashboard addActivityType(String name, List activities, List indicators, + boolean countMultipleOccurrences, @Nullable String refCsv) { + activityMapping.put(name, String.join(",", activities)); + refCsvs.put(name, refCsv); + + if (countMultipleOccurrences) { + countMultipleOccurrencesSet.add(name); + } + + this.indicators = indicators; + return this; + } + + @Override + public void configure(Header header, Layout layout) { + + header.title = "Activities"; + header.description = "Displays the activities by type and location."; + + List args = new ArrayList<>(List.of("--id-column", ID_COLUMN, "--shp", shpFile)); + args.add("--activity-mapping"); + args.add(activityMapping.entrySet().stream() + .map(e -> "%s=%s".formatted(e.getKey(), e.getValue())) + .collect(Collectors.joining(";"))); + + args.add("--single-occurrence"); + if (!countMultipleOccurrencesSet.isEmpty()) { + args.add(String.join(";", countMultipleOccurrencesSet)); + } + + + for (Map.Entry activity : activityMapping.entrySet()) { + + String activityName = StringUtils.capitalize(activity.getKey()); + + layout.row("category_header_" + activity.getKey()) + .el(TextBlock.class, (viz, data) -> { + viz.content = "## **" + activityName + "**"; + viz.backgroundColor = "transparent"; + }); + + for (Indicator ind : Indicator.values()) { + + if (indicators.contains(ind)) { + + Layout.Row row = layout.row(activity.getKey() + "_" + ind.name) + .el(MapPlot.class, (viz, data) -> { + viz.title = "Simulated %s Activities (%s)".formatted(activityName, ind.displayName); + viz.height = 8.; + String shp = data.resource(shpFile); + viz.setShape(shp, ID_COLUMN); + viz.addDataset("transit-trips", data.computeWithPlaceholder(ActivityCountAnalysis.class, "activities_%s_per_region.csv", activity.getKey(), args.toArray(new String[0]))); + viz.display.fill.columnName = ind.name; + viz.display.fill.dataset = "transit-trips"; + viz.display.fill.join = REF_JOIN; + if (ind == Indicator.RELATIVE_DENSITY) { + viz.display.fill.setColorRamp(ColorScheme.RdBu, 11, false, "0.2, 0.25, 0.33, 0.5, 0.67, 1.5, 2.0, 3.0, 4.0, 5.0"); + } + }); + + if (refCsvs.get(activity.getKey()) != null) { + row.el(MapPlot.class, (viz, data) -> { + + viz.title = "Reference %s Activities (%s)".formatted(activityName, ind.displayName); + viz.height = 8.; + + String shp = data.resource(shpFile); + viz.setShape(shp, ID_COLUMN); + + viz.addDataset("transit-trips", data.resource(refCsvs.get(activity.getKey()))); + + viz.display.fill.dataset = "transit-trips"; + viz.display.fill.join = REF_JOIN; + + if (ind == Indicator.RELATIVE_DENSITY) { + viz.display.fill.columnName = "relative_density"; + viz.display.fill.setColorRamp(ColorScheme.RdBu, 11, false, "0.2, 0.25, 0.33, 0.5, 0.67, 1.5, 2.0, 3.0, 4.0, 5.0"); + } else if (ind == Indicator.DENSITY) { + viz.display.fill.columnName = "density"; + } else { + viz.display.fill.columnName = "count"; + } + }); + } + } + } + } + } + + /** + * Metric to show in the dashboard. + */ + public enum Indicator { + COUNTS("count", "Counts"), + DENSITY("density", "Density"), + RELATIVE_DENSITY("relative_density", "Relative Density"); + + private final String name; + private final String displayName; + + Indicator(String name, String displayName) { + this.name = name; + this.displayName = displayName; + } + } +} + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/MapPlot.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/MapPlot.java index ac675cc6381..96ea10d5d94 100644 --- a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/MapPlot.java +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/MapPlot.java @@ -10,15 +10,14 @@ */ public final class MapPlot extends Viz { + private final Map datasets = new HashMap<>(); public double[] center; public Double zoom; - public Display display = new Display(); public Double minValue; public Double maxValue; @JsonProperty(required = true) private Object shapes; - private Map datasets = new HashMap<>(); public MapPlot() { super("map"); @@ -77,6 +76,9 @@ public static final class DisplaySettings { @JsonProperty(required = true) public String columnName; + @JsonProperty(required = true) + public String normalize; + @JsonProperty(required = true) public String join; diff --git a/contribs/simwrapper/src/test/java/org/matsim/simwrapper/dashboard/DashboardTests.java b/contribs/simwrapper/src/test/java/org/matsim/simwrapper/dashboard/DashboardTests.java index e3e92fa87a7..a741dfeba78 100644 --- a/contribs/simwrapper/src/test/java/org/matsim/simwrapper/dashboard/DashboardTests.java +++ b/contribs/simwrapper/src/test/java/org/matsim/simwrapper/dashboard/DashboardTests.java @@ -20,11 +20,12 @@ import java.io.IOException; import java.nio.file.Path; +import java.util.List; import java.util.Set; public class DashboardTests { @RegisterExtension - private MatsimTestUtils utils = new MatsimTestUtils(); + private final MatsimTestUtils utils = new MatsimTestUtils(); private void run(Dashboard... dashboards) { @@ -153,4 +154,20 @@ void ptCustom() { Assertions.assertThat(out) .isDirectoryContaining("glob:**pt_pax_volumes.csv.gz"); } + + @Test + void activity() { + ActivityDashboard ad = new ActivityDashboard("kehlheim_shape.shp"); + + ad.addActivityType( + "work", + List.of("work"), + List.of(ActivityDashboard.Indicator.COUNTS, ActivityDashboard.Indicator.RELATIVE_DENSITY, ActivityDashboard.Indicator.DENSITY), true, + "kehlheim_ref.csv" + ); + + run(ad); + } + + } diff --git a/contribs/simwrapper/src/test/resources/kehlheim_ref.csv b/contribs/simwrapper/src/test/resources/kehlheim_ref.csv new file mode 100644 index 00000000000..1b3ba9c3824 --- /dev/null +++ b/contribs/simwrapper/src/test/resources/kehlheim_ref.csv @@ -0,0 +1,12 @@ +id;count;area;density;relative_density +2;12000.0;1743518.43;0.006882634;1.07723188785 +6;11000.0;350075.92;0.031421756;3.91795945 +4;2000.0;545791.40;0.003664404;0.5735321986 +8;13000.0;2121061.25;0.006129007;0.9592783427 +9;15000.0;3785838.06;0.003962135;0.6201314016 +10;7000.0;5744728.89;0.001218508;0.19071418629999998 +1;2000.0;1981892.09;0.001009137;0.19071418629999998 +3;12000.0;1955593.52;0.006136245;0.9604110622400001 +7;7000.0;942460.23;0.007427369;1.1624907459 +5;1000.0;876651.07;0.001140705;0.1785367932 +0;8000.0;6205676.03;0.001289142;0.2017694383 \ No newline at end of file diff --git a/contribs/simwrapper/src/test/resources/kehlheim_shape.cpg b/contribs/simwrapper/src/test/resources/kehlheim_shape.cpg new file mode 100644 index 00000000000..3ad133c048f --- /dev/null +++ b/contribs/simwrapper/src/test/resources/kehlheim_shape.cpg @@ -0,0 +1 @@ +UTF-8 \ No newline at end of file diff --git a/contribs/simwrapper/src/test/resources/kehlheim_shape.dbf b/contribs/simwrapper/src/test/resources/kehlheim_shape.dbf new file mode 100644 index 00000000000..d3b37577b5d Binary files /dev/null and b/contribs/simwrapper/src/test/resources/kehlheim_shape.dbf differ diff --git a/contribs/simwrapper/src/test/resources/kehlheim_shape.prj b/contribs/simwrapper/src/test/resources/kehlheim_shape.prj new file mode 100644 index 00000000000..bd846aeb220 --- /dev/null +++ b/contribs/simwrapper/src/test/resources/kehlheim_shape.prj @@ -0,0 +1 @@ +PROJCS["ETRS_1989_UTM_Zone_32N",GEOGCS["GCS_ETRS_1989",DATUM["D_ETRS_1989",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",9.0],PARAMETER["Scale_Factor",0.9996],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]] \ No newline at end of file diff --git a/contribs/simwrapper/src/test/resources/kehlheim_shape.qmd b/contribs/simwrapper/src/test/resources/kehlheim_shape.qmd new file mode 100644 index 00000000000..53f5af5ac96 --- /dev/null +++ b/contribs/simwrapper/src/test/resources/kehlheim_shape.qmd @@ -0,0 +1,44 @@ + + + + + + dataset + + + + + + + + + + + + + + + + + + GEOGCRS["WGS 84",ENSEMBLE["World Geodetic System 1984 ensemble",MEMBER["World Geodetic System 1984 (Transit)"],MEMBER["World Geodetic System 1984 (G730)"],MEMBER["World Geodetic System 1984 (G873)"],MEMBER["World Geodetic System 1984 (G1150)"],MEMBER["World Geodetic System 1984 (G1674)"],MEMBER["World Geodetic System 1984 (G1762)"],ELLIPSOID["WGS 84",6378137,298.257223563,LENGTHUNIT["metre",1]],ENSEMBLEACCURACY[2.0]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],CS[ellipsoidal,2],AXIS["geodetic latitude (Lat)",north,ORDER[1],ANGLEUNIT["degree",0.0174532925199433]],AXIS["geodetic longitude (Lon)",east,ORDER[2],ANGLEUNIT["degree",0.0174532925199433]],USAGE[SCOPE["Horizontal component of 3D system."],AREA["World."],BBOX[-90,-180,90,180]],ID["EPSG",4326]] + +proj=longlat +datum=WGS84 +no_defs + 3452 + 4326 + EPSG:4326 + WGS 84 + longlat + EPSG:7030 + true + + + + + + + + + + + + diff --git a/contribs/simwrapper/src/test/resources/kehlheim_shape.shp b/contribs/simwrapper/src/test/resources/kehlheim_shape.shp new file mode 100644 index 00000000000..ff0f9b67afd Binary files /dev/null and b/contribs/simwrapper/src/test/resources/kehlheim_shape.shp differ diff --git a/contribs/simwrapper/src/test/resources/kehlheim_shape.shx b/contribs/simwrapper/src/test/resources/kehlheim_shape.shx new file mode 100644 index 00000000000..1be796e8141 Binary files /dev/null and b/contribs/simwrapper/src/test/resources/kehlheim_shape.shx differ diff --git a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/DefaultIntegrateExistingTrafficToSmallScaleCommercialImpl.java b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/DefaultIntegrateExistingTrafficToSmallScaleCommercialImpl.java index 6652c17b955..052fb62b9f1 100644 --- a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/DefaultIntegrateExistingTrafficToSmallScaleCommercialImpl.java +++ b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/DefaultIntegrateExistingTrafficToSmallScaleCommercialImpl.java @@ -372,8 +372,8 @@ public void reduceDemandBasedOnExistingCarriers(Scenario scenario, Map createListOfCarrierWithUnhandledJobs(Scenario scenario){ private void redrawAllServiceDurations(Carrier carrier, GenerateSmallScaleCommercialTrafficDemand.CarrierAttributes carrierAttributes, int additionalTravelBufferPerIterationInMinutes) { for (CarrierService service : carrier.getServices().values()) { double newServiceDuration = generator.getServiceTimePerStop(carrier, carrierAttributes, additionalTravelBufferPerIterationInMinutes); - CarrierService redrawnService = CarrierService.Builder.newInstance(service.getId(), service.getLocationLinkId()) + CarrierService redrawnService = CarrierService.Builder.newInstance(service.getId(), service.getServiceLinkId()) .setServiceDuration(newServiceDuration).setServiceStartTimeWindow(service.getServiceStartTimeWindow()).build(); carrier.getServices().put(redrawnService.getId(), redrawnService); } diff --git a/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisEventHandler.java b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisEventHandler.java index 2f322e8640f..3b159189bda 100644 --- a/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisEventHandler.java +++ b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisEventHandler.java @@ -391,8 +391,8 @@ public void exportShipmentInfo(String path, Boolean exportGuesses) { if (shipmentTracker == null) { continue; } - Id from = shipment.getFrom(); - Id toLink = shipment.getTo(); + Id from = shipment.getPickupLinkId(); + Id toLink = shipment.getDeliveryLinkId(); // if info is not certain, export the guess if that is wanted. String carrierIdString = id2String(carrier.getId()); String shipmentIdString = id2String(shipment.getId()); diff --git a/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisServiceTracking.java b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisServiceTracking.java index 88ee09b7b5c..b0e668fdc2f 100644 --- a/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisServiceTracking.java +++ b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisServiceTracking.java @@ -57,7 +57,7 @@ public void addTracker(CarrierService service, Id id) { public void trackServiceActivityStart(ActivityStartEvent activityStartEvent) { for (ServiceTracker.CarrierServiceTracker cst: carrierServiceTrackers.values()) { for (ServiceTracker service : cst.serviceTrackers.values()) { - if (service.service.getLocationLinkId().equals(activityStartEvent.getLinkId())) { + if (service.service.getServiceLinkId().equals(activityStartEvent.getLinkId())) { if (service.driverId == null) { // if there is no driver, but there is a service which is to be performed at the moment at this place, we guess this could be the event for it. // (Does not work well obviously as soon as there are multiple services at a location that have generous time windows, like e.g. at stores). diff --git a/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisShipmentTracking.java b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisShipmentTracking.java index e7126cca05e..5673a46b530 100644 --- a/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisShipmentTracking.java +++ b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/FreightAnalysisShipmentTracking.java @@ -57,12 +57,14 @@ public void trackDeliveryActivity(ActivityStartEvent activityStartEvent) { for (ShipmentTracker shipment: shipments.values()){ if (shipment.to==activityStartEvent.getLinkId() ){ if(shipment.driverId == null){ - if(shipment.shipment.getDeliveryTimeWindow().getStart()<=activityStartEvent.getTime() && activityStartEvent.getTime()<=shipment.shipment.getDeliveryTimeWindow().getEnd()){ - if (shipment.possibleDrivers.contains(activityStartEvent.getPersonId().toString())) { - shipment.driverIdGuess = activityStartEvent.getPersonId(); - shipment.deliveryTimeGuess=activityStartEvent.getTime(); - } - } + if(shipment.shipment.getDeliveryStartsTimeWindow().getStart() <= activityStartEvent.getTime()) { + if (activityStartEvent.getTime()<= shipment.shipment.getDeliveryStartsTimeWindow().getEnd()) { + if (shipment.possibleDrivers.contains(activityStartEvent.getPersonId().toString())) { + shipment.driverIdGuess = activityStartEvent.getPersonId(); + shipment.deliveryTimeGuess=activityStartEvent.getTime(); + } + } + } } else if (shipment.driverId.toString().equals(activityStartEvent.getPersonId().toString())){ shipment.deliveryTime=activityStartEvent.getTime(); } @@ -75,8 +77,10 @@ public void trackPickupActivity(ActivityStartEvent activityStartEvent) { for (ShipmentTracker shipmentTracker: shipments.values()){ if (shipmentTracker.from==activityStartEvent.getLinkId()){ if (shipmentTracker.driverId==null){ - if(shipmentTracker.shipment.getPickupTimeWindow().getStart()<=activityStartEvent.getTime() && activityStartEvent.getTime()<=shipmentTracker.shipment.getPickupTimeWindow().getEnd()){ - shipmentTracker.possibleDrivers.add(activityStartEvent.getPersonId().toString()); + if(shipmentTracker.shipment.getPickupStartsTimeWindow().getStart() <= activityStartEvent.getTime()) { + if (activityStartEvent.getTime()<= shipmentTracker.shipment.getPickupStartsTimeWindow().getEnd()) { + shipmentTracker.possibleDrivers.add(activityStartEvent.getPersonId().toString()); + } } } } @@ -124,8 +128,8 @@ class ShipmentTracker { public ShipmentTracker(CarrierShipment shipment) { this.id = shipment.getId(); - this.from = shipment.getFrom(); - this.to=shipment.getTo(); + this.from = shipment.getPickupLinkId(); + this.to=shipment.getDeliveryLinkId(); this.shipment=shipment; } diff --git a/matsim/src/test/java/org/matsim/testcases/MatsimTestUtils.java b/matsim/src/test/java/org/matsim/testcases/MatsimTestUtils.java index 287858329cb..4432063a364 100644 --- a/matsim/src/test/java/org/matsim/testcases/MatsimTestUtils.java +++ b/matsim/src/test/java/org/matsim/testcases/MatsimTestUtils.java @@ -31,8 +31,8 @@ import org.matsim.core.gbl.MatsimRandom; import org.matsim.core.utils.io.IOUtils; import org.matsim.core.utils.misc.CRCChecksum; -import org.matsim.utils.eventsfilecomparison.EventsFileComparator; import org.matsim.utils.eventsfilecomparison.ComparisonResult; +import org.matsim.utils.eventsfilecomparison.EventsFileComparator; import java.io.BufferedReader; import java.io.File; @@ -41,6 +41,9 @@ import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; import java.util.Objects; /** @@ -51,6 +54,11 @@ public final class MatsimTestUtils implements BeforeEachCallback, AfterEachCallback { private static final Logger log = LogManager.getLogger(MatsimTestUtils.class); + //used for copying files from output to input. Don't delete even if they are unused in production + public static final String FILE_NAME_PLANS = "output_plans.xml.gz"; + public static final String FILE_NAME_NETWORK = "output_network.xml.gz"; + public static final String FILE_NAME_EVENTS = "output_events.xml.gz"; + public enum TestMethodType { Normal, Parameterized } @@ -60,12 +68,16 @@ public enum TestMethodType { */ public static final double EPSILON = 1e-10; - /** The default output directory, where files of this test should be written to. - * Includes the trailing '/' to denote a directory. */ + /** + * The default output directory, where files of this test should be written to. + * Includes the trailing '/' to denote a directory. + */ private String outputDirectory = null; - /** The default input directory, where files of this test should be read from. - * Includes the trailing '/' to denote a directory. */ + /** + * The default input directory, where files of this test should be read from. + * Includes the trailing '/' to denote a directory. + */ private String inputDirectory = null; /** @@ -144,7 +156,7 @@ public URL packageInputResourcePath() { private URL getResourceNotNull(String pathString) { URL resource = this.testClass.getResource(pathString); if (resource == null) { - throw new UncheckedIOException(new IOException("Not found: "+pathString)); + throw new UncheckedIOException(new IOException("Not found: " + pathString)); } return resource; } @@ -171,7 +183,8 @@ public Config createConfig(URL context) { /** * Loads a configuration from file (or the default config if configfile is null) - * and sets the output directory to {classPath}/{methodName}/. For parameterized tests, the output directory is {classPath}/{methodName}/{parameters}/. + * and sets the output directory to {classPath}/{methodName}/. For parameterized tests, the output directory is {classPath}/{methodName}/{ + * parameters}/. * * @param configfile The path/filename of a configuration file, or null to load the default configuration. * @return The loaded configuration. @@ -181,7 +194,7 @@ public Config loadConfig(final String configfile, TestMethodType testMethodType, if (configfile != null) { config = ConfigUtils.loadConfig(configfile, customGroups); } else { - config = ConfigUtils.createConfig( customGroups ); + config = ConfigUtils.createConfig(customGroups); } return setOutputDirectory(config, testMethodType); } @@ -195,7 +208,7 @@ public Config loadConfig(final URL configfile, TestMethodType testMethodType, fi if (configfile != null) { config = ConfigUtils.loadConfig(configfile, customGroups); } else { - config = ConfigUtils.createConfig( customGroups ); + config = ConfigUtils.createConfig(customGroups); } return setOutputDirectory(config, testMethodType); } @@ -226,7 +239,7 @@ public String getParameterizedTestInputString() { } public Config createConfig(final ConfigGroup... customGroups) { - Config config = ConfigUtils.createConfig( customGroups ); + Config config = ConfigUtils.createConfig(customGroups); this.outputDirectory = getOutputDirectory(); config.controller().setOutputDirectory(this.outputDirectory); return config; @@ -254,7 +267,7 @@ public String getOutputDirectory() { public String getOutputDirectory(String subDir) { if (this.outputDirectory == null) { - this.outputDirectory = "test/output/" + this.testClass.getCanonicalName().replace('.', '/') + "/" + getMethodName()+ "/" + subDir; + this.outputDirectory = "test/output/" + this.testClass.getCanonicalName().replace('.', '/') + "/" + getMethodName() + "/" + subDir; } createOutputDirectory(); return this.outputDirectory; @@ -271,18 +284,20 @@ public String getInputDirectory() { } return this.inputDirectory; } + /** - * Returns the path to the input directory one level above the default input directory for this test including a trailing slash as directory delimiter. + * Returns the path to the input directory one level above the default input directory for this test including a trailing slash as directory + * delimiter. * * @return path to the input directory for this test */ public String getClassInputDirectory() { if (this.classInputDirectory == null) { - LogManager.getLogger(this.getClass()).info( "user.dir = " + System.getProperty("user.dir") ) ; + LogManager.getLogger(this.getClass()).info("user.dir = " + System.getProperty("user.dir")); this.classInputDirectory = "test/input/" + - this.testClass.getCanonicalName().replace('.', '/') + "/"; + this.testClass.getCanonicalName().replace('.', '/') + "/"; // this.classInputDirectory = System.getProperty("user.dir") + "/test/input/" + // this.testClass.getCanonicalName().replace('.', '/') + "/"; // (this used to be relative, i.e. ... = "test/input/" + ... . Started failing when @@ -292,8 +307,10 @@ public String getClassInputDirectory() { } return this.classInputDirectory; } + /** - * Returns the path to the input directory two levels above the default input directory for this test including a trailing slash as directory delimiter. + * Returns the path to the input directory two levels above the default input directory for this test including a trailing slash as directory + * delimiter. * * @return path to the input directory for this test */ @@ -321,7 +338,7 @@ public String getMethodName() { * This should be used for "fixtures" only that provide a scenario common to several * test cases. */ - public void initWithoutJUnitForFixture(Class fixture, Method method){ + public void initWithoutJUnitForFixture(Class fixture, Method method) { this.testClass = fixture; this.testMethodName = method.getName(); } @@ -333,27 +350,62 @@ public static void assertEqualFilesLineByLine(String inputFilename, String outpu String lineInput; String lineOutput; - while( ((lineInput = readerV1Input.readLine()) != null) && ((lineOutput = readerV1Output.readLine()) != null) ){ - if ( !Objects.equals( lineInput.trim(), lineOutput.trim() ) ){ - log.info( "Reading line... " ); - log.info( lineInput ); - log.info( lineOutput ); - log.info( "" ); + while (((lineInput = readerV1Input.readLine()) != null) && ((lineOutput = readerV1Output.readLine()) != null)) { + if (!Objects.equals(lineInput.trim(), lineOutput.trim())) { + log.info("Reading line... "); + log.info(lineInput); + log.info(lineOutput); + log.info(""); } - Assertions.assertEquals(lineInput.trim(), lineOutput.trim(), "Lines have different content: " ); + Assertions.assertEquals(lineInput.trim(), lineOutput.trim(), "Lines have different content: "); } } catch (IOException e) { throw new UncheckedIOException(e); } } - public static void assertEqualEventsFiles( String filename1, String filename2 ) { - Assertions.assertEquals(ComparisonResult.FILES_ARE_EQUAL ,EventsFileComparator.compare(filename1, filename2) ); + public static void assertEqualEventsFiles(String filename1, String filename2) { + Assertions.assertEquals(ComparisonResult.FILES_ARE_EQUAL, EventsFileComparator.compare(filename1, filename2)); + } + + public static void assertEqualFilesBasedOnCRC(String filename1, String filename2) { + long checksum1 = CRCChecksum.getCRCFromFile(filename1); + long checksum2 = CRCChecksum.getCRCFromFile(filename2); + Assertions.assertEquals(checksum1, checksum2, "different file checksums"); + } + + /** + * Creates the input directory for this test. + */ + public void createInputDirectory() { + try { + Files.createDirectories(Path.of(getInputDirectory())); + } catch (IOException e) { + e.printStackTrace(); + Assertions.fail(); + } + } + + /** + * Copies a file from the output directory to the input directory. This is normally only needed during development, if one would not do it + * manually. + */ + public void copyFileFromOutputToInput(String fileName) { + createInputDirectory(); + copyFileFromOutputToInput(fileName, fileName); } - public static void assertEqualFilesBasedOnCRC( String filename1, String filename2 ) { - long checksum1 = CRCChecksum.getCRCFromFile(filename1) ; - long checksum2 = CRCChecksum.getCRCFromFile(filename2) ; - Assertions.assertEquals( checksum1, checksum2, "different file checksums" ); - } + /** + * Copies a file from the output directory to the input directory. This is normally only needed during development, if one would not do it + * manually. + */ + public void copyFileFromOutputToInput(String outputFile, String inputFile) { + createInputDirectory(); + try { + Files.copy(Path.of(getOutputDirectory() + outputFile), Path.of(getInputDirectory() + inputFile), StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + e.printStackTrace(); + Assertions.fail(); + } + } }