diff --git a/contribs/application/src/main/java/org/matsim/application/CommandRunner.java b/contribs/application/src/main/java/org/matsim/application/CommandRunner.java index b55fc548a56..ea0af2e6dd2 100644 --- a/contribs/application/src/main/java/org/matsim/application/CommandRunner.java +++ b/contribs/application/src/main/java/org/matsim/application/CommandRunner.java @@ -108,7 +108,7 @@ private void runCommand(Class clazz, Path input) thr MATSimAppCommand command = clazz.getDeclaredConstructor().newInstance(); String[] args = this.args.get(clazz); args = ArrayUtils.addAll(args, createArgs(clazz, args, input)); - log.info("Running {} with arguments: {}", clazz, Arrays.toString(args)); + log.info("Running {} with arguments: {}", clazz, String.join(" ", args)); command.execute(args); } diff --git a/contribs/application/src/main/java/org/matsim/application/analysis/emissions/AirPollutionAnalysis.java b/contribs/application/src/main/java/org/matsim/application/analysis/emissions/AirPollutionAnalysis.java index dbf40292057..4b54cb14200 100644 --- a/contribs/application/src/main/java/org/matsim/application/analysis/emissions/AirPollutionAnalysis.java +++ b/contribs/application/src/main/java/org/matsim/application/analysis/emissions/AirPollutionAnalysis.java @@ -205,11 +205,11 @@ private void writeOutput(Network network, EmissionsOnLinkEventHandler emissionsE if (link2pollutants.get(linkId).get(pollutant) != null) { emissionValue = link2pollutants.get(linkId).get(pollutant); } - absolute.print(nf.format(emissionValue)); + absolute.print(nf.format(emissionValue * sample.getUpscaleFactor())); Link link = network.getLinks().get(linkId); double emissionPerM = emissionValue / link.getLength(); - perMeter.print(nf.format(emissionPerM)); + perMeter.print(nf.format(emissionPerM * sample.getUpscaleFactor())); } absolute.println(); @@ -246,7 +246,7 @@ private void writeTotal(Network network, EmissionsOnLinkEventHandler emissionsEv total.printRecord("Pollutant", "kg"); for (Pollutant p : Pollutant.values()) { - double val = (sum.getDouble(p) / sample.getSample()) / 1000; + double val = (sum.getDouble(p) * sample.getUpscaleFactor()) / 1000; total.printRecord(p, val < 100_000 && val > 100 ? simple.format(val) : scientific.format(val)); } @@ -286,7 +286,7 @@ private void writeAvroRaster(Network network, Config config, EmissionsOnLinkEven for (int xi = 0; xi < xLength.get(0); xi++) { for (int yi = 0; yi < yLength.get(0); yi++) { Coord coord = raster.getCoordForIndex(xi, yi); - double value = rasterMap.get(Pollutant.CO2_TOTAL).getValueByIndex(xi, yi); + double value = rasterMap.get(Pollutant.CO2_TOTAL).getValueByIndex(xi, yi) * sample.getUpscaleFactor(); if (xi == 0) yCoords.add((float) coord.getY()); if (yi == 0) xCoords.add((float) coord.getX()); valuesList.add((float) value); @@ -349,7 +349,7 @@ private void writeRaster(Network network, Config config, EmissionsOnLinkEventHan for (int yi = 0; yi < yLength.get(0); yi++) { Coord coord = raster.getCoordForIndex(xi, yi); - double value = rasterMap.get(Pollutant.CO2_TOTAL).getValueByIndex(xi, yi); + double value = rasterMap.get(Pollutant.CO2_TOTAL).getValueByIndex(xi, yi) * sample.getUpscaleFactor(); if (value == 0) continue; @@ -406,7 +406,7 @@ private void writeTimeDependentRaster(Network network, Config config, EmissionsO for (TimeBinMap.TimeBin> timeBin : timeBinMap.getTimeBins()) { Coord coord = raster.getCoordForIndex(xi, yi); - double value = timeBin.getValue().get(Pollutant.CO2_TOTAL).getValueByIndex(xi, yi); + double value = timeBin.getValue().get(Pollutant.CO2_TOTAL).getValueByIndex(xi, yi) * sample.getUpscaleFactor(); if (value == 0) continue; @@ -467,7 +467,8 @@ private void writeTimeDependentAvroRaster(Network network, Config config, Emissi if (yi == 0 && isFirst) xCoords.add((float) coord.getX()); - valuesList.add((float) timeBin.getValue().get(Pollutant.CO2_TOTAL).getValueByIndex(xi, yi)); + double value = timeBin.getValue().get(Pollutant.CO2_TOTAL).getValueByIndex(xi, yi) * sample.getUpscaleFactor(); + valuesList.add((float) value); } } } diff --git a/contribs/application/src/main/java/org/matsim/application/analysis/population/TripAnalysis.java b/contribs/application/src/main/java/org/matsim/application/analysis/population/TripAnalysis.java index 4da59a48294..6d6ee80f8c1 100644 --- a/contribs/application/src/main/java/org/matsim/application/analysis/population/TripAnalysis.java +++ b/contribs/application/src/main/java/org/matsim/application/analysis/population/TripAnalysis.java @@ -8,6 +8,7 @@ import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; +import org.apache.commons.math3.analysis.interpolation.LoessInterpolator; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.locationtech.jts.geom.Coordinate; @@ -32,6 +33,7 @@ import java.math.RoundingMode; import java.nio.file.Files; import java.util.*; +import java.util.stream.IntStream; import static tech.tablesaw.aggregate.AggregateFunctions.count; @@ -41,6 +43,7 @@ produces = { "mode_share.csv", "mode_share_per_dist.csv", "mode_users.csv", "trip_stats.csv", "mode_share_per_%s.csv", "population_trip_stats.csv", "trip_purposes_by_hour.csv", + "mode_share_distance_distribution.csv", "mode_choices.csv", "mode_choice_evaluation.csv", "mode_choice_evaluation_per_mode.csv", "mode_confusion_matrix.csv", "mode_prediction_error.csv" } @@ -109,6 +112,25 @@ private static int durationToSeconds(String d) { return (Integer.parseInt(split[0]) * 60 * 60) + (Integer.parseInt(split[1]) * 60) + Integer.parseInt(split[2]); } + private static double[] calcHistogram(double[] data, double[] bins) { + + double[] hist = new double[bins.length - 1]; + + for (int i = 0; i < bins.length - 1; i++) { + + double binStart = bins[i]; + double binEnd = bins[i + 1]; + + // The last right bin edge is inclusive, which is consistent with the numpy implementation + if (i == bins.length - 2) + hist[i] = Arrays.stream(data).filter(d -> d >= binStart && d <= binEnd).count(); + else + hist[i] = Arrays.stream(data).filter(d -> d >= binStart && d < binEnd).count(); + } + + return hist; + } + @Override public Integer call() throws Exception { @@ -247,6 +269,8 @@ public Integer call() throws Exception { writeTripPurposes(joined); + writeTripDistribution(joined); + return 0; } @@ -293,6 +317,7 @@ private void writeTripStats(Table trips) throws IOException { Object2IntMap n = new Object2IntLinkedOpenHashMap<>(); Object2LongMap travelTime = new Object2LongOpenHashMap<>(); Object2LongMap travelDistance = new Object2LongOpenHashMap<>(); + Object2LongMap beelineDistance = new Object2LongOpenHashMap<>(); for (Row trip : trips) { String mainMode = trip.getString("main_mode"); @@ -300,6 +325,7 @@ private void writeTripStats(Table trips) throws IOException { n.mergeInt(mainMode, 1, Integer::sum); travelTime.mergeLong(mainMode, durationToSeconds(trip.getString("trav_time")), Long::sum); travelDistance.mergeLong(mainMode, trip.getLong("traveled_distance"), Long::sum); + beelineDistance.mergeLong(mainMode, trip.getLong("euclidean_distance"), Long::sum); } try (CSVPrinter printer = new CSVPrinter(Files.newBufferedWriter(output.getPath("trip_stats.csv")), CSVFormat.DEFAULT)) { @@ -338,6 +364,13 @@ private void writeTripStats(Table trips) throws IOException { } printer.println(); + printer.print("Avg. beeline speed [km/h]"); + for (String m : modeOrder) { + double speed = (beelineDistance.getLong(m) / 1000d) / (travelTime.getLong(m) / (60d * 60d)); + printer.print(new BigDecimal(speed).setScale(2, RoundingMode.HALF_UP)); + } + printer.println(); + printer.print("Avg. distance per trip [km]"); for (String m : modeOrder) { double avg = (travelDistance.getLong(m) / 1000d) / (n.getInt(m)); @@ -458,6 +491,55 @@ private void writeTripPurposes(Table trips) { } + private void writeTripDistribution(Table trips) throws IOException { + + Map dists = new LinkedHashMap<>(); + + // Note that the results of this interpolator are consistent with the one performed in matsim-python-tools + // This makes the results comparable with reference data, changes here will also require changes in the python package + LoessInterpolator inp = new LoessInterpolator(0.05, 0); + + long max = distGroups.get(distGroups.size() - 3) + distGroups.get(distGroups.size() - 2); + + double[] bins = IntStream.range(0, (int) (max / 100)).mapToDouble(i -> i * 100).toArray(); + double[] x = Arrays.copyOf(bins, bins.length - 1); + + for (String mode : modeOrder) { + double[] distances = trips.where( + trips.stringColumn("main_mode").equalsIgnoreCase(mode)) + .numberColumn("traveled_distance").asDoubleArray(); + + double[] hist = calcHistogram(distances, bins); + + double[] y = inp.smooth(x, hist); + dists.put(mode, y); + } + + try (CSVPrinter printer = new CSVPrinter(Files.newBufferedWriter(output.getPath("mode_share_distance_distribution.csv")), CSVFormat.DEFAULT)) { + + printer.print("dist"); + for (String s : modeOrder) { + printer.print(s); + } + printer.println(); + + for (int i = 0; i < x.length; i++) { + + double sum = 0; + for (String s : modeOrder) { + sum += Math.max(0, dists.get(s)[i]); + } + + printer.print(x[i]); + for (String s : modeOrder) { + double value = Math.max(0, dists.get(s)[i]) / sum; + printer.print(value); + } + printer.println(); + } + } + } + /** * How shape file filtering should be applied. */ diff --git a/contribs/application/src/main/java/org/matsim/application/analysis/population/TripByGroupAnalysis.java b/contribs/application/src/main/java/org/matsim/application/analysis/population/TripByGroupAnalysis.java index 47edfec0824..b63a58f5ed8 100644 --- a/contribs/application/src/main/java/org/matsim/application/analysis/population/TripByGroupAnalysis.java +++ b/contribs/application/src/main/java/org/matsim/application/analysis/population/TripByGroupAnalysis.java @@ -81,6 +81,22 @@ final class TripByGroupAnalysis { } } + // Norm shares per instance of each group to sum of 1 + for (Group group : this.groups) { + + String norm = group.columns.get(0); + if (group.columns.size() > 1) + throw new UnsupportedOperationException("Multiple columns not supported yet"); + + Table df = group.data; + for (String label : df.stringColumn(norm).asSet()) { + DoubleColumn dist_group = df.doubleColumn("share"); + Selection sel = df.stringColumn(norm).isEqualTo(label); + double total = dist_group.where(sel).sum(); + if (total > 0) + dist_group.set(sel, dist_group.divide(total)); + } + } } } diff --git a/contribs/application/src/main/java/org/matsim/application/analysis/traffic/TrafficStatsCalculator.java b/contribs/application/src/main/java/org/matsim/application/analysis/traffic/TrafficStatsCalculator.java index b6d29a5319b..f24ad081146 100644 --- a/contribs/application/src/main/java/org/matsim/application/analysis/traffic/TrafficStatsCalculator.java +++ b/contribs/application/src/main/java/org/matsim/application/analysis/traffic/TrafficStatsCalculator.java @@ -13,7 +13,7 @@ /** * Class to calculate the traffic congestion index based on the paper - * "A Traffic Congestion Assessment Method for Urban Road Networks Based on Speed Performance Index" by Feifei He, Xuedong Yan*, Yang Liu, Lu Ma. + * "A Traffic Congestion Assessment Method for Urban Road Networks Based on Speed Performance Index" by Feifei He, Xuedong Yan, Yang Liu, Lu Ma. */ public final class TrafficStatsCalculator { diff --git a/contribs/application/src/main/java/org/matsim/application/options/SampleOptions.java b/contribs/application/src/main/java/org/matsim/application/options/SampleOptions.java index 6a1cba85545..f9ac12190a9 100644 --- a/contribs/application/src/main/java/org/matsim/application/options/SampleOptions.java +++ b/contribs/application/src/main/java/org/matsim/application/options/SampleOptions.java @@ -124,6 +124,13 @@ public double getSample() { return sample; } + /** + * Return factor that is used to upscale the sample size. + */ + public double getUpscaleFactor() { + return 1.0 / sample; + } + private void setSize(double sample) { this.set = true; this.sample = sample; diff --git a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java index 126eff63188..02ae5072583 100644 --- a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java +++ b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/DemandReaderFromCSV.java @@ -667,18 +667,25 @@ else if (samplingOption.equals("changeDemandOnLocation")) { int demandForThisLink = calculateDemandBasedOnLinkLength(countOfLinks, distributedDemand, demandToDistribute, possibleLinksForService.size(), sumOfPossibleLinkLength, link); countOfLinks++; - double serviceTime = newDemandInformationElement.getFirstJobElementTimePerUnit() - * demandForThisLink; - Id idNewService = Id.create( + Carrier thisCarrier = CarriersUtils.getCarriers(scenario).getCarriers() + .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)); + int numberOfJobsForDemand = calculateNumberOfJobsForDemand(thisCarrier, demandForThisLink); + for (int i = 0; i < numberOfJobsForDemand; i++) { + int singleDemandForThisLink = demandForThisLink / numberOfJobsForDemand; + if (i == numberOfJobsForDemand - 1) + singleDemandForThisLink = demandForThisLink - (numberOfJobsForDemand - 1) * singleDemandForThisLink; + double serviceTime = newDemandInformationElement.getFirstJobElementTimePerUnit() + * singleDemandForThisLink; + Id idNewService = Id.create( createJobId(scenario, newDemandInformationElement, link.getId(), null), CarrierService.class); - if (demandToDistribute > 0 && demandForThisLink > 0) { - CarrierService thisService = CarrierService.Builder.newInstance(idNewService, link.getId()) - .setCapacityDemand(demandForThisLink).setServiceDuration(serviceTime) + if (demandToDistribute > 0 && singleDemandForThisLink > 0) { + CarrierService thisService = CarrierService.Builder.newInstance(idNewService, link.getId()) + .setCapacityDemand(singleDemandForThisLink).setServiceDuration(serviceTime) .setServiceStartTimeWindow(newDemandInformationElement.getFirstJobElementTimeWindow()) .build(); - CarriersUtils.getCarriers(scenario).getCarriers().values().iterator().next().getServices() - .put(thisService.getId(), thisService); + thisCarrier.getServices().put(thisService.getId(), thisService); + } } distributedDemand = distributedDemand + demandForThisLink; } @@ -705,24 +712,31 @@ else if (samplingOption.equals("changeDemandOnLocation")) { .skip(rand.nextInt(usedServiceLocations.size() - 1)).findFirst().get())); } int demandForThisLink = calculateDemandForThisLink(demandToDistribute, numberOfJobs, distributedDemand, i); + Carrier thisCarrier = CarriersUtils.getCarriers(scenario).getCarriers() + .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)); + int numberOfJobsForDemand = calculateNumberOfJobsForDemand(thisCarrier, demandForThisLink); + for (int j = 0; j < numberOfJobsForDemand; j++) { + int singleDemandForThisLink = demandForThisLink / numberOfJobsForDemand; + if (j == numberOfJobsForDemand - 1) + singleDemandForThisLink = demandForThisLink - (numberOfJobsForDemand - 1) * singleDemandForThisLink; + double serviceTime; + if (singleDemandForThisLink == 0) + serviceTime = newDemandInformationElement.getFirstJobElementTimePerUnit(); + else + serviceTime = newDemandInformationElement.getFirstJobElementTimePerUnit() * demandForThisLink; + usedServiceLocations.add(link.getId().toString()); - double serviceTime; - if (demandToDistribute == 0) - serviceTime = newDemandInformationElement.getFirstJobElementTimePerUnit(); - else - serviceTime = newDemandInformationElement.getFirstJobElementTimePerUnit() * demandForThisLink; - usedServiceLocations.add(link.getId().toString()); - - Id idNewService = Id.create( + Id idNewService = Id.create( createJobId(scenario, newDemandInformationElement, link.getId(), null), CarrierService.class); - if ((demandToDistribute > 0 && demandForThisLink > 0) || demandToDistribute == 0) { - CarrierService thisService = CarrierService.Builder.newInstance(idNewService, link.getId()) - .setCapacityDemand(demandForThisLink).setServiceDuration(serviceTime) + if ((demandToDistribute > 0 && singleDemandForThisLink > 0) || demandToDistribute == 0) { + CarrierService thisService = CarrierService.Builder.newInstance(idNewService, link.getId()) + .setCapacityDemand(singleDemandForThisLink).setServiceDuration(serviceTime) .setServiceStartTimeWindow(newDemandInformationElement.getFirstJobElementTimeWindow()) .build(); - CarriersUtils.getCarriers(scenario).getCarriers() + CarriersUtils.getCarriers(scenario).getCarriers() .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)).getServices() .put(thisService.getId(), thisService); + } } distributedDemand = distributedDemand + demandForThisLink; } @@ -1007,29 +1021,56 @@ else if (numberOfPickupLocations != null) { private static void createSingleShipment(Scenario scenario, DemandInformationElement newDemandInformationElement, Link linkPickup, Link linkDelivery, int demandForThisLink) { - Id idNewShipment = Id.create(createJobId(scenario, newDemandInformationElement, - linkPickup.getId(), linkDelivery.getId()), CarrierShipment.class); + Carrier thisCarrier = CarriersUtils.getCarriers(scenario).getCarriers() + .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)); + int numberOfJobsForDemand = calculateNumberOfJobsForDemand(thisCarrier, demandForThisLink); TimeWindow timeWindowPickup = newDemandInformationElement.getFirstJobElementTimeWindow(); TimeWindow timeWindowDelivery = newDemandInformationElement.getSecondJobElementTimeWindow(); - double serviceTimePickup; - double serviceTimeDelivery; - if (demandForThisLink == 0) { - serviceTimePickup = newDemandInformationElement.getFirstJobElementTimePerUnit(); - serviceTimeDelivery = newDemandInformationElement.getSecondJobElementTimePerUnit(); - } else { - serviceTimePickup = newDemandInformationElement.getFirstJobElementTimePerUnit() * demandForThisLink; - serviceTimeDelivery = newDemandInformationElement.getSecondJobElementTimePerUnit() * demandForThisLink; + for (int i = 0; i < numberOfJobsForDemand; i++) { + Id idNewShipment = Id.create(createJobId(scenario, newDemandInformationElement, + linkPickup.getId(), linkDelivery.getId()), CarrierShipment.class); + double serviceTimePickup; + double serviceTimeDelivery; + int singleDemandForThisLink = Math.round ((float) demandForThisLink / numberOfJobsForDemand); + if (i == numberOfJobsForDemand - 1) + singleDemandForThisLink = demandForThisLink - (numberOfJobsForDemand - 1) * singleDemandForThisLink; + if (singleDemandForThisLink == 0) { + serviceTimePickup = newDemandInformationElement.getFirstJobElementTimePerUnit(); + serviceTimeDelivery = newDemandInformationElement.getSecondJobElementTimePerUnit(); + } else { + serviceTimePickup = newDemandInformationElement.getFirstJobElementTimePerUnit() * singleDemandForThisLink; + serviceTimeDelivery = newDemandInformationElement.getSecondJobElementTimePerUnit() * singleDemandForThisLink; + } + CarrierShipment thisShipment = CarrierShipment.Builder + .newInstance(idNewShipment, linkPickup.getId(), linkDelivery.getId(), singleDemandForThisLink) + .setPickupServiceTime(serviceTimePickup).setPickupTimeWindow(timeWindowPickup) + .setDeliveryServiceTime(serviceTimeDelivery).setDeliveryTimeWindow(timeWindowDelivery) + .build(); + thisCarrier.getShipments().put(thisShipment.getId(), thisShipment); + } + } + + /** + * Method calculates the number of jobs for a demand on one link based on the largest vehicle capacity of the carrier. + * + * @param thisCarrier the carrier of a job + * @param demandForThisLink Demand for this link + * @return Number of jobs for this demand + */ + private static int calculateNumberOfJobsForDemand(Carrier thisCarrier, int demandForThisLink) { + double largestVehicleCapacity = 0; + for (CarrierVehicle vehicle : thisCarrier.getCarrierCapabilities().getCarrierVehicles().values()) { + if (vehicle.getType().getCapacity().getOther() > largestVehicleCapacity) { + largestVehicleCapacity = vehicle.getType().getCapacity().getOther(); + } + } + if (demandForThisLink > largestVehicleCapacity) { + log.info("Demand {} is larger than the largest vehicle capacity ({}). Splitting demand into multiple jobs.", demandForThisLink, largestVehicleCapacity); + return (int) Math.ceil((double) demandForThisLink / largestVehicleCapacity); } - CarrierShipment thisShipment = CarrierShipment.Builder - .newInstance(idNewShipment, linkPickup.getId(), linkDelivery.getId(), demandForThisLink) - .setPickupServiceTime(serviceTimePickup).setPickupTimeWindow(timeWindowPickup) - .setDeliveryServiceTime(serviceTimeDelivery).setDeliveryTimeWindow(timeWindowDelivery) - .build(); - CarriersUtils.getCarriers(scenario).getCarriers() - .get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class)).getShipments() - .put(thisShipment.getId(), thisShipment); + return 1; } /** @@ -1086,7 +1127,7 @@ private static int calculateDemandForThisLink(int demandToDistribute, int number } else { roundingError = roundingError + ((double) demandForThisLink - ((double) demandToDistribute / (double) numberOfJobs)); - if (roundingError > 1) { + if (roundingError >= 1) { demandForThisLink = demandForThisLink - 1; roundingError = roundingError - 1; } @@ -1113,7 +1154,7 @@ private static int calculateDemandBasedOnLinkLength(int countOfLinks, int distri .ceil(link.getLength() / sumOfPossibleLinkLength * (double) demandToDistribute); roundingError = roundingError + ((double) demandForThisLink - (link.getLength() / sumOfPossibleLinkLength * (double) demandToDistribute)); - if (roundingError > 1) { + if (roundingError >= 1) { demandForThisLink = demandForThisLink - 1; roundingError = roundingError - 1; } @@ -1265,7 +1306,7 @@ private static HashMap, Link> findAllPossibleLinks(Scenario scenario, crsTransformationNetworkAndShape); if (!possibleLinks.containsKey(newPossibleLink.getId())) possibleLinks.put(newPossibleLink.getId(), newPossibleLink); - if (nearestLinkPerPerson.size() == possiblePersons.size()) + if (!possiblePersons.isEmpty() && nearestLinkPerPerson.size() == possiblePersons.size()) break; } } diff --git a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGeneration.java b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGeneration.java index 76dda11fc9b..09ba9e75623 100644 --- a/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGeneration.java +++ b/contribs/application/src/main/java/org/matsim/freightDemandGeneration/FreightDemandGeneration.java @@ -381,6 +381,13 @@ private void createDemand(DemandGenerationOptions selectedDemandGenerationOption */ FreightDemandGenerationUtils.preparePopulation(population, sampleSizeInputPopulation, upSamplePopulationTo, "changeDemandOnLocation"); + case noPopulationSampling -> + /* + * If the demand sample is equal to the population sample, the demand is created + * based on the given population and the set input population sampleSize + */ + FreightDemandGenerationUtils.preparePopulation(population, sampleSizeInputPopulation, + sampleSizeInputPopulation, "noPopulationSampling"); default -> throw new RuntimeException("No valid sampling option selected!"); } switch (selectedPopulationOption) { diff --git a/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/h3/H3ZoneSystem.java b/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/h3/H3ZoneSystem.java index e9c84bccc4a..286bc9a09ca 100644 --- a/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/h3/H3ZoneSystem.java +++ b/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/h3/H3ZoneSystem.java @@ -13,8 +13,12 @@ import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.transformations.TransformationFactory; -import java.util.*; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; import java.util.function.Predicate; +import java.util.stream.Collectors; /** * @author nkuehnel / MOIA @@ -39,41 +43,38 @@ public H3ZoneSystem(String crs, int resolution, Network network, Predicate this.resolution = resolution; this.network = network; this.filter = filter; - this.network.getLinks().values().forEach(l -> getZoneForCoord(l.getToNode().getCoord())); + init(); } - - @Override - public Optional getZoneForCoord(Coord coord) { - - long h3Address = getH3Cell(coord); - Id zoneId = Id.create(h3Address, Zone.class); - - if(zones.containsKey(zoneId)) { - return Optional.of(zones.get(zoneId)); - } else { - Optional zone = H3Utils.createZone(h3Address, fromLatLong); - if(zone.isPresent() && filter.test(zone.get())) { - initZone(zone.get(), h3Address); - return zone; - } else { - return Optional.empty(); - } + private void init() { + Map> linksToH3 = + this.network.getLinks().values() + .stream() + .collect(Collectors.groupingBy(link -> getH3Cell(link.getToNode().getCoord()))); + for (Map.Entry> linksH3 : linksToH3.entrySet()) { + Optional maybeZone = createZone(linksH3.getKey()); + maybeZone.ifPresent(z -> { + zones.put(z.getId(), z); + zoneToLinksMap.put(z.getId(), linksH3.getValue()); + }); } } - private void initZone(Zone zone, long h3Address) { - if(filter.test(zone)) { - zones.put(zone.getId(), zone); - for (Link link : network.getLinks().values()) { - long linkH3Address = getH3Cell(link.getToNode().getCoord()); - - if (linkH3Address == h3Address) { - List links = zoneToLinksMap.computeIfAbsent(zone.getId(), id -> new ArrayList<>()); - links.add(link); - } - } + private Optional createZone(Long h3) { + Optional zone = H3Utils.createZone(h3, fromLatLong); + if(zone.isPresent() && filter.test(zone.get())) { + return zone; } + return Optional.empty(); + } + + @Override + public Optional getZoneForCoord(Coord coord) { + long h3Address = getH3Cell(coord); + Id zoneId = Id.create(h3Address, Zone.class); + // create new zone if absent, should not be linked to existing links in the network, + // as all of them are covered in the init() phase. + return Optional.ofNullable(zones.computeIfAbsent(zoneId, id -> createZone(h3Address).orElse(null))); } private long getH3Cell(Coord coord) { @@ -106,4 +107,4 @@ public List getLinksForZoneId(Id zone) { public Map, Zone> getZones() { return Collections.unmodifiableMap(zones); } -} +} \ No newline at end of file diff --git a/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/square/SquareGridZoneSystem.java b/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/square/SquareGridZoneSystem.java index f11fa58f614..b1319fed1a9 100644 --- a/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/square/SquareGridZoneSystem.java +++ b/contribs/common/src/main/java/org/matsim/contrib/common/zones/systems/grid/square/SquareGridZoneSystem.java @@ -66,11 +66,11 @@ public SquareGridZoneSystem(Network network, double cellSize, Predicate zo } public SquareGridZoneSystem(Network network, double cellSize, boolean filterByNetwork, Predicate zoneFilter) { this.zoneFilter = zoneFilter; - Preconditions.checkArgument(!network.getNodes().isEmpty(), "Cannot create SquareGrid if no nodes"); - this.network = network; this.cellSize = cellSize; + Preconditions.checkArgument(!network.getNodes().isEmpty(), "Cannot create SquareGrid if no nodes"); + initBounds(); this.rows = Math.max(1, (int) Math.ceil((maxY - minY) / cellSize)); diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/h3/drtZone/H3DrtZonalSystemTest.java b/contribs/common/src/test/java/org/matsim/contrib/common/zones/systems/h3/H3DrtZonalSystemTest.java similarity index 55% rename from contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/h3/drtZone/H3DrtZonalSystemTest.java rename to contribs/common/src/test/java/org/matsim/contrib/common/zones/systems/h3/H3DrtZonalSystemTest.java index 3724d5d8eac..723e4026825 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/h3/drtZone/H3DrtZonalSystemTest.java +++ b/contribs/common/src/test/java/org/matsim/contrib/common/zones/systems/h3/H3DrtZonalSystemTest.java @@ -18,7 +18,7 @@ * *********************************************************************** * */ -package org.matsim.contrib.drt.extension.h3.drtZone; +package org.matsim.contrib.common.zones.systems.h3; import org.junit.jupiter.api.Test; import org.matsim.api.core.v01.Id; @@ -48,20 +48,20 @@ void test_Holzkirchen_Resolution3() { Network network = getNetwork(); String crs = TransformationFactory.DHDN_GK4; int resolution = 3; - ZoneSystem drtZonalSystem = new H3ZoneSystem(crs, resolution, network, z -> true); + ZoneSystem zoneSystem = new H3ZoneSystem(crs, resolution, network, z -> true); - assertThat(drtZonalSystem.getZones().containsKey(createZoneId("590526392240701439"))).isTrue(); + assertThat(zoneSystem.getZones().containsKey(createZoneId("590526392240701439"))).isTrue(); // center of Holzkirchen - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("590526667118608383")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("590526667118608383")); // Thanning (Western border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("590526667118608383")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("590526667118608383")); // between Gross- and Kleinpienzenau (Southeastern border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("590526392240701439")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("590526392240701439")); //check all links are mapped for (Link link : network.getLinks().values()) { - assertNotNull(drtZonalSystem.getZoneForLinkId(link.getId())); + assertNotNull(zoneSystem.getZoneForLinkId(link.getId())); } } @@ -71,23 +71,23 @@ void test_Holzkirchen_Resolution5() { String crs = TransformationFactory.DHDN_GK4; int resolution = 5; - ZoneSystem drtZonalSystem = new H3ZoneSystem(crs, resolution, network, z -> true); + ZoneSystem zoneSystem = new H3ZoneSystem(crs, resolution, network, z -> true); - assertThat(drtZonalSystem.getZones().containsKey(createZoneId("599533579684282367"))).isTrue(); - assertThat(drtZonalSystem.getZones().containsKey(createZoneId("599533826644901887"))).isTrue(); - assertThat(drtZonalSystem.getZones().containsKey(createZoneId("599533499153645567"))).isTrue(); - assertThat(drtZonalSystem.getZones().containsKey(createZoneId("599533503448612863"))).isTrue(); + assertThat(zoneSystem.getZones().containsKey(createZoneId("599533579684282367"))).isTrue(); + assertThat(zoneSystem.getZones().containsKey(createZoneId("599533826644901887"))).isTrue(); + assertThat(zoneSystem.getZones().containsKey(createZoneId("599533499153645567"))).isTrue(); + assertThat(zoneSystem.getZones().containsKey(createZoneId("599533503448612863"))).isTrue(); // center of Holzkirchen - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("599533826644901887")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("599533826644901887")); // Thanning (Western border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("599533503448612863")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("599533503448612863")); // between Gross- and Kleinpienzenau (Southeastern border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("599533579684282367")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("599533579684282367")); //check all links are mapped for (Link link : network.getLinks().values()) { - assertNotNull(drtZonalSystem.getZoneForLinkId(link.getId())); + assertNotNull(zoneSystem.getZoneForLinkId(link.getId())); } } @@ -97,18 +97,18 @@ void test_Holzkirchen_Resolution6() { String crs = TransformationFactory.DHDN_GK4; int resolution = 6; - ZoneSystem drtZonalSystem = new H3ZoneSystem(crs, resolution, network, z -> true); + ZoneSystem zoneSystem = new H3ZoneSystem(crs, resolution, network, z -> true); // center of Holzkirchen - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("604037425601183743")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("604037425601183743")); // Thanning (Western border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("604037102136459263")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("604037102136459263")); // between Gross- and Kleinpienzenau (Southeastern border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("604037178372128767")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("604037178372128767")); //check all links are mapped for (Link link : network.getLinks().values()) { - assertNotNull(drtZonalSystem.getZoneForLinkId(link.getId())); + assertNotNull(zoneSystem.getZoneForLinkId(link.getId())); } } @@ -117,18 +117,18 @@ void test_Holzkirchen_Resolution10() { Network network = getNetwork(); String crs = TransformationFactory.DHDN_GK4; int resolution = 10; - ZoneSystem drtZonalSystem = new H3ZoneSystem(crs, resolution, network, z -> true); + ZoneSystem zoneSystem = new H3ZoneSystem(crs, resolution, network, z -> true); // center of Holzkirchen - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("622051824027533311")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("622051824027533311")); // Thanning (Western border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("622051500514213887")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("622051500514213887")); // between Gross- and Kleinpienzenau (Southeastern border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("622051576862081023")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("622051576862081023")); //check all links are mapped for (Link link : network.getLinks().values()) { - assertNotNull(drtZonalSystem.getZoneForLinkId(link.getId())); + assertNotNull(zoneSystem.getZoneForLinkId(link.getId())); } } @@ -138,19 +138,19 @@ void test_Holzkirchen_Resolution12() { String crs = TransformationFactory.DHDN_GK4; int resolution = 12; - ZoneSystem drtZonalSystem = new H3ZoneSystem(crs, resolution, network, z -> true); + ZoneSystem zoneSystem = new H3ZoneSystem(crs, resolution, network, z -> true); // center of Holzkirchen - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("631059023282267135")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(358598)).orElseThrow().getId()).isEqualTo(createZoneId("631059023282267135")); // Thanning (Western border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("631058699768943103")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(78976)).orElseThrow().getId()).isEqualTo(createZoneId("631058699768943103")); // between Gross- and Kleinpienzenau (Southeastern border of network) - assertThat(drtZonalSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("631058776116789759")); + assertThat(zoneSystem.getZoneForLinkId(Id.createLinkId(59914)).orElseThrow().getId()).isEqualTo(createZoneId("631058776116789759")); //check all links are mapped for (Link link : network.getLinks().values()) { - assertNotNull(drtZonalSystem.getZoneForLinkId(link.getId())); + assertNotNull(zoneSystem.getZoneForLinkId(link.getId())); } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtDashboard.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtDashboard.java index a62f46a1ebc..6131d9f0edd 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtDashboard.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/dashboards/DrtDashboard.java @@ -159,7 +159,7 @@ public void configure(Header header, Layout layout) { viz.description = "Number of rides (customers) is displayed in bars, wait statistics in lines"; Plotly.DataSet waitStats = viz.addDataset(data.output("*_waitStats_" + drtConfigGroup.mode + ".csv")); - Plotly.DataSet rejections = viz.addDataset(data.output("*drt_rejections_perTimeBin_" + drtConfigGroup.mode + ".csv")); + Plotly.DataSet rejections = viz.addDataset(data.output("*drt_rejections_perTimeBin_" + drtConfigGroup.mode + ".csv")); viz.layout = tech.tablesaw.plotly.components.Layout.builder() .xAxis(Axis.builder().title("Time Bin").build()) @@ -244,7 +244,7 @@ public void configure(Header header, Layout layout) { viz.layout = tech.tablesaw.plotly.components.Layout.builder() .xAxis(Axis.builder().title("Iteration").build()) - .yAxis(Axis.builder().title("Wait Time [s]").build()) + .yAxis(Axis.builder().title("Number of Rides").build()) .barMode(tech.tablesaw.plotly.components.Layout.BarMode.STACK) .build(); @@ -272,12 +272,12 @@ public void configure(Header header, Layout layout) { viz.description = ""; viz.dataset = data.output("*customer_stats_" + drtConfigGroup.mode + ".csv"); viz.x = "iteration"; - viz.columns = List.of("wait_average","wait_median", "wait_p95"); + viz.columns = List.of("wait_average", "wait_median", "wait_p95"); viz.legendName = List.of("Average", "Median", "95th Percentile"); viz.xAxisName = "Iteration"; viz.yAxisName = "Waiting Time [s]"; }) - ; + ; layout.row("Demand And Travel Time Statistics per iteration") .el(Plotly.class, (viz, data) -> { diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/run/EDrtControlerCreator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/run/EDrtControlerCreator.java index 1db60059c37..3d54738d88e 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/run/EDrtControlerCreator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/edrt/run/EDrtControlerCreator.java @@ -41,11 +41,13 @@ public class EDrtControlerCreator { public static Controler createControler(Config config, boolean otfvis) { - MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); - DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.scoring(), config.routing()); - Scenario scenario = DrtControlerCreator.createScenarioWithDrtRouteFactory(config); ScenarioUtils.loadScenario(scenario); + return createControler(config, scenario, otfvis); + } + public static Controler createControler(Config config, Scenario scenario, boolean otfvis) { + MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); + DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.scoring(), config.routing()); Controler controler = new Controler(scenario); controler.addOverridingModule(new MultiModeEDrtModule()); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtOperationsControlerCreator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtOperationsControlerCreator.java index 9a1772ca184..ccc1576a348 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtOperationsControlerCreator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtOperationsControlerCreator.java @@ -1,5 +1,7 @@ package org.matsim.contrib.drt.extension.operations; +import org.matsim.api.core.v01.Scenario; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilitiesModeModule; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilitiesQSimModule; import org.matsim.contrib.drt.extension.operations.shifts.analysis.efficiency.DrtShiftEfficiencyModeModule; @@ -26,20 +28,34 @@ public class DrtOperationsControlerCreator { * @return */ public static Controler createControler(Config config, boolean otfvis) { - MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); - Controler controler = DrtControlerCreator.createControler(config, otfvis); + return prepareController(config, controler); + } + + /** + * Creates a controller in one step. + * + * @param config + * @param scenario + * @param otfvis + * @return + */ + public static Controler createControler(Config config, Scenario scenario, boolean otfvis) { + Controler controler = DrtControlerCreator.createControler(config, scenario, otfvis); + return prepareController(config, controler); + } + private static Controler prepareController(Config config, Controler controler) { + MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); for (DrtConfigGroup drtCfg : multiModeDrtConfig.getModalElements()) { controler.addOverridingModule(new ShiftDrtModeModule(drtCfg)); controler.addOverridingQSimModule(new DrtModeQSimModule(drtCfg, new ShiftDrtModeOptimizerQSimModule(drtCfg))); - controler.addOverridingModule(new OperationFacilitiesModeModule((DrtWithOperationsConfigGroup) drtCfg)); + controler.addOverridingModule(new OperationFacilitiesModeModule((DrtWithExtensionsConfigGroup) drtCfg)); controler.addOverridingQSimModule(new OperationFacilitiesQSimModule(drtCfg)); controler.addOverridingModule(new DrtShiftEfficiencyModeModule(drtCfg)); } controler.configureQSimComponents(DvrpQSimComponents.activateAllModes(multiModeDrtConfig)); - return controler; } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtWithOperationsConfigGroup.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtWithOperationsConfigGroup.java deleted file mode 100644 index d33e6c74c2e..00000000000 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/DrtWithOperationsConfigGroup.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2022 MOIA GmbH - All Rights Reserved - * - * You may use, distribute and modify this code under the terms - * of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, - * or (at your option) any later version. - */ -package org.matsim.contrib.drt.extension.operations; - -import jakarta.validation.constraints.NotNull; -import org.matsim.contrib.drt.run.DrtConfigGroup; - -/** - * @author mdziakowski / MOIA - */ -public class DrtWithOperationsConfigGroup extends DrtConfigGroup { - - @NotNull - private DrtOperationsParams drtOperationsParams; - - public DrtWithOperationsConfigGroup() { - addDefinition(DrtOperationsParams.SET_NAME, DrtOperationsParams::new, - () -> drtOperationsParams, - params -> drtOperationsParams = (DrtOperationsParams)params); - } - - public DrtOperationsParams getDrtOperationsParams() { - return drtOperationsParams; - } -} diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/EDrtOperationsControlerCreator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/EDrtOperationsControlerCreator.java index c0b78a1a5bb..855cba7f143 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/EDrtOperationsControlerCreator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/EDrtOperationsControlerCreator.java @@ -1,5 +1,7 @@ package org.matsim.contrib.drt.extension.operations; +import org.matsim.api.core.v01.Scenario; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.edrt.run.EDrtControlerCreator; import org.matsim.contrib.drt.extension.operations.eshifts.charging.ShiftOperatingVehicleProvider; import org.matsim.contrib.drt.extension.operations.eshifts.fleet.EvShiftDvrpFleetQSimModule; @@ -23,29 +25,34 @@ public class EDrtOperationsControlerCreator { public static Controler createControler(Config config, boolean otfvis) { - - MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); - Controler controler = EDrtControlerCreator.createControler(config, otfvis); + prepareController(config, controler); + return controler; + } + + public static Controler createControler(Config config, Scenario scenario, boolean otfvis) { + Controler controler = EDrtControlerCreator.createControler(config, scenario, otfvis); + prepareController(config, controler); + return controler; + } + private static void prepareController(Config config, Controler controler) { + MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); for (DrtConfigGroup drtCfg : multiModeDrtConfig.getModalElements()) { controler.addOverridingModule(new ShiftDrtModeModule(drtCfg)); controler.addOverridingQSimModule(new DrtModeQSimModule(drtCfg, new ShiftDrtModeOptimizerQSimModule(drtCfg))); controler.addOverridingQSimModule(new ShiftEDrtModeOptimizerQSimModule(drtCfg)); controler.addOverridingQSimModule(new EvShiftDvrpFleetQSimModule(drtCfg.getMode())); - controler.addOverridingModule(new OperationFacilitiesModeModule((DrtWithOperationsConfigGroup) drtCfg)); + controler.addOverridingModule(new OperationFacilitiesModeModule((DrtWithExtensionsConfigGroup) drtCfg)); controler.addOverridingQSimModule(new OperationFacilitiesQSimModule(drtCfg)); controler.addOverridingModule(new DrtShiftEfficiencyModeModule(drtCfg)); } - controler.addOverridingQSimModule(new AbstractQSimModule() { @Override protected void configureQSim() { this.bind(IdleDischargingHandler.VehicleProvider.class).to(ShiftOperatingVehicleProvider.class); } }); - - return controler; } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/README.md b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/README.md new file mode 100644 index 00000000000..9f7200cc257 --- /dev/null +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/README.md @@ -0,0 +1,72 @@ +# DRT Operations + +Provides functionality to realistically simulate operational aspects, +designed for, bot not limited to, non-autonomous services. + +Initially developed for MOIA GmbH + +If used, please cite: + +Felix Zwick, Nico Kuehnel, Sebastian Hörl. +Shifts in perspective: Operational aspects in (non-)autonomous +ride-pooling simulations. +Transportation Research Part A: Policy and Practice, +Volume 165, 2022, Pages 300-320. +https://doi.org/10.1016/j.tra.2022.09.001. + + +## Core features: + +- Operation facilities +- (Driver) shifts + + +The entry point for setting up a simulation are the specific control(l)er creators: +- DrtOperationsControlerCreator + - or +- EDrtOperationsControlerCreator + - in the electric vehicles case + +## Operation Facilities +Operation facilities are meant to represent hubs and in-field break locations. +The facilities have a capacity that cannot be exceeded and may be linked to +existing chargers via the id. + +(Driver) shifts may only start or end at operation facilities in the default setup. +Vehicles will route to operation facilities to end a shift or for scheduling a break. + +Operational facilities may be described with an xml file like this: +``` + + + + + + + + +``` + +## Shifts +Shifts define periods in which vehicles may be active serving passengers. +Shifts are dynamically assigned to vehicles. + +In autonomous settings, shifts may be used to model up- and down-time and/or cleaning +cycles. + +Shifts have a start and end time and can optionally have a break which is defined +by earliest start and latest end as well as a duration. Optionally, as operation +facility id may be defined to control the location of the start/end of the shift. + +Shifts may be described in an xml file likes this: +``` + + + + + + + + +``` + diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtAssignShiftToVehicleLogic.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtAssignShiftToVehicleLogic.java index 32f74d1196c..0c2d4fd79c8 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtAssignShiftToVehicleLogic.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtAssignShiftToVehicleLogic.java @@ -9,7 +9,7 @@ package org.matsim.contrib.drt.extension.operations.eshifts.dispatcher; import org.matsim.contrib.drt.extension.operations.eshifts.fleet.EvShiftDvrpVehicle; -import org.matsim.contrib.drt.extension.operations.eshifts.schedule.EDrtWaitForShiftStayTask; +import org.matsim.contrib.drt.extension.operations.eshifts.schedule.EDrtWaitForShiftTask; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; import org.matsim.contrib.drt.extension.operations.shifts.dispatcher.AssignShiftToVehicleLogic; import org.matsim.contrib.drt.extension.operations.shifts.fleet.ShiftDvrpVehicle; @@ -37,8 +37,8 @@ public boolean canAssignVehicleToShift(ShiftDvrpVehicle vehicle, DrtShift shift) // no, if charging if(vehicle.getSchedule().getStatus() == Schedule.ScheduleStatus.STARTED) { final Task currentTask = vehicle.getSchedule().getCurrentTask(); - if (currentTask instanceof EDrtWaitForShiftStayTask) { - if (((EDrtWaitForShiftStayTask) currentTask).getChargingTask() != null) { + if (currentTask instanceof EDrtWaitForShiftTask) { + if (((EDrtWaitForShiftTask) currentTask).getChargingTask() != null) { if (currentTask.getEndTime() > shift.getStartTime()) { return false; } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtShiftDispatcherImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtShiftDispatcherImpl.java index e18008e4ce5..ace6e8d66e0 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtShiftDispatcherImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtShiftDispatcherImpl.java @@ -3,7 +3,7 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.drt.extension.operations.eshifts.fleet.EvShiftDvrpVehicle; -import org.matsim.contrib.drt.extension.operations.eshifts.schedule.EDrtWaitForShiftStayTask; +import org.matsim.contrib.drt.extension.operations.eshifts.schedule.EDrtWaitForShiftTask; import org.matsim.contrib.drt.extension.operations.eshifts.scheduler.EShiftTaskScheduler; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; import org.matsim.contrib.drt.extension.operations.shifts.dispatcher.DrtShiftDispatcher; @@ -11,7 +11,7 @@ import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilities; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacility; import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftBreakTask; -import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftStayTask; +import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftTask; import org.matsim.contrib.dvrp.fleet.DvrpVehicle; import org.matsim.contrib.dvrp.fleet.Fleet; import org.matsim.contrib.dvrp.schedule.Schedule; @@ -96,8 +96,8 @@ private void checkChargingAtHub(double timeStep) { final ElectricVehicle electricVehicle = eShiftVehicle.getElectricVehicle(); if (electricVehicle.getBattery().getCharge() / electricVehicle.getBattery().getCapacity() < drtShiftParams.chargeAtHubThreshold) { final Task currentTask = eShiftVehicle.getSchedule().getCurrentTask(); - if (currentTask instanceof EDrtWaitForShiftStayTask - && ((EDrtWaitForShiftStayTask) currentTask).getChargingTask() == null) { + if (currentTask instanceof EDrtWaitForShiftTask + && ((EDrtWaitForShiftTask) currentTask).getChargingTask() == null) { Optional selectedCharger = chargerIds .stream() .map(id -> chargingInfrastructure.getChargers().get(id)) @@ -122,7 +122,7 @@ private void checkChargingAtHub(double timeStep) { .calcRemainingEnergyToCharge(electricVehicle); final double endTime = timeStep + waitTime + chargingTime; if (endTime < currentTask.getEndTime()) { - shiftTaskScheduler.chargeAtHub((WaitForShiftStayTask) currentTask, eShiftVehicle, + shiftTaskScheduler.chargeAtHub((WaitForShiftTask) currentTask, eShiftVehicle, electricVehicle, selectedChargerImpl, timeStep, endTime, energy); } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtShiftStartLogic.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtShiftStartLogic.java index ad3c83ca0f7..97ceadbb433 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtShiftStartLogic.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/dispatcher/EDrtShiftStartLogic.java @@ -8,7 +8,7 @@ */ package org.matsim.contrib.drt.extension.operations.eshifts.dispatcher; -import org.matsim.contrib.drt.extension.operations.eshifts.schedule.EDrtWaitForShiftStayTask; +import org.matsim.contrib.drt.extension.operations.eshifts.schedule.EDrtWaitForShiftTask; import org.matsim.contrib.drt.extension.operations.shifts.dispatcher.DrtShiftDispatcher; import org.matsim.contrib.drt.extension.operations.shifts.dispatcher.ShiftStartLogic; import org.matsim.contrib.dvrp.schedule.Schedule; @@ -29,9 +29,9 @@ public EDrtShiftStartLogic(ShiftStartLogic delegate) { public boolean shiftStarts(DrtShiftDispatcher.ShiftEntry shiftEntry) { Schedule schedule = shiftEntry.vehicle().getSchedule(); Task currentTask = schedule.getCurrentTask(); - if (currentTask instanceof EDrtWaitForShiftStayTask) { + if (currentTask instanceof EDrtWaitForShiftTask) { //check whether vehicle still needs to complete charging task - if(((EDrtWaitForShiftStayTask) currentTask).getChargingTask() == null) { + if(((EDrtWaitForShiftTask) currentTask).getChargingTask() == null) { return delegate.shiftStarts(shiftEntry); } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/run/ShiftEDrtModeOptimizerQSimModule.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/run/ShiftEDrtModeOptimizerQSimModule.java index afbf606fc1d..aefdfeb5e6c 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/run/ShiftEDrtModeOptimizerQSimModule.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/run/ShiftEDrtModeOptimizerQSimModule.java @@ -2,12 +2,12 @@ import com.google.inject.Singleton; import org.matsim.api.core.v01.network.Network; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.edrt.EDrtActionCreator; import org.matsim.contrib.drt.extension.edrt.optimizer.EDrtVehicleDataEntryFactory; import org.matsim.contrib.drt.extension.edrt.schedule.EDrtTaskFactoryImpl; import org.matsim.contrib.drt.extension.edrt.scheduler.EmptyVehicleChargingScheduler; import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; -import org.matsim.contrib.drt.extension.operations.DrtWithOperationsConfigGroup; import org.matsim.contrib.drt.extension.operations.eshifts.dispatcher.EDrtAssignShiftToVehicleLogic; import org.matsim.contrib.drt.extension.operations.eshifts.dispatcher.EDrtShiftDispatcherImpl; import org.matsim.contrib.drt.extension.operations.eshifts.dispatcher.EDrtShiftStartLogic; @@ -53,7 +53,7 @@ public class ShiftEDrtModeOptimizerQSimModule extends AbstractDvrpModeQSimModule public ShiftEDrtModeOptimizerQSimModule(DrtConfigGroup drtCfg) { super(drtCfg.getMode()); - this.drtOperationsParams = ((DrtWithOperationsConfigGroup) drtCfg).getDrtOperationsParams(); + this.drtOperationsParams = ((DrtWithExtensionsConfigGroup) drtCfg).getDrtOperationsParams().orElseThrow(); this.drtCfg = drtCfg; } @@ -76,7 +76,9 @@ drtShiftParams, new EDrtShiftStartLogic(new DefaultShiftStartLogic()), new EDrtAssignShiftToVehicleLogic(new DefaultAssignShiftToVehicleLogic(drtShiftParams), drtShiftParams)), getter.getModal(Fleet.class)))).asEagerSingleton(); - bindModal(VehicleEntry.EntryFactory.class).toProvider(modalProvider(getter -> new ShiftVehicleDataEntryFactory(new EDrtVehicleDataEntryFactory(0)))).asEagerSingleton(); + bindModal(VehicleEntry.EntryFactory.class).toProvider(modalProvider(getter -> + new ShiftVehicleDataEntryFactory(new EDrtVehicleDataEntryFactory(0), + drtShiftParams.considerUpcomingShiftsForInsertion))).asEagerSingleton(); bindModal(DrtTaskFactory.class).toProvider(modalProvider(getter -> new ShiftEDrtTaskFactoryImpl(new EDrtTaskFactoryImpl(), getter.getModal(OperationFacilities.class)))).in(Singleton.class); bindModal(ShiftDrtTaskFactory.class).toProvider(modalProvider(getter -> ((ShiftDrtTaskFactory) getter.getModal(DrtTaskFactory.class)))); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/EDrtWaitForShiftStayTask.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/EDrtWaitForShiftTask.java similarity index 69% rename from contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/EDrtWaitForShiftStayTask.java rename to contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/EDrtWaitForShiftTask.java index c60e0214f1d..546b4e6b770 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/EDrtWaitForShiftStayTask.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/EDrtWaitForShiftTask.java @@ -1,23 +1,23 @@ package org.matsim.contrib.drt.extension.operations.eshifts.schedule; import org.matsim.api.core.v01.network.Link; +import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftTask; import org.matsim.contrib.evrp.ChargingTask; import org.matsim.contrib.evrp.ETask; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacility; -import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftStayTask; /** * @author nkuehnel / MOIA */ -public class EDrtWaitForShiftStayTask extends WaitForShiftStayTask implements ETask { +public class EDrtWaitForShiftTask extends WaitForShiftTask implements ETask { private final double consumedEnergy; private final ChargingTask chargingTask; - public EDrtWaitForShiftStayTask(double beginTime, double endTime, Link link, - double consumedEnergy, OperationFacility facility, - ChargingTask chargingTask) { + public EDrtWaitForShiftTask(double beginTime, double endTime, Link link, + double consumedEnergy, OperationFacility facility, + ChargingTask chargingTask) { super(beginTime, endTime, link, facility); this.consumedEnergy = consumedEnergy; this.chargingTask = chargingTask; diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/ShiftEDrtActionCreator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/ShiftEDrtActionCreator.java index 4604771bed9..6092021974c 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/ShiftEDrtActionCreator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/ShiftEDrtActionCreator.java @@ -42,9 +42,9 @@ public DynAction createAction(DynAgent dynAgent, DvrpVehicle vehicle, double now task.initTaskTracker(new OfflineETaskTracker((EvDvrpVehicle) vehicle, timer)); DrtStopTask t = (DrtStopTask) task; return new ChargingChangeoverActivity(((EDrtShiftChangeoverTaskImpl) task).getChargingTask(), passengerHandler, dynAgent, t, t.getDropoffRequests(), t.getPickupRequests()); - } else if (task instanceof EDrtWaitForShiftStayTask && ((EDrtWaitForShiftStayTask) task).getChargingTask() != null) { + } else if (task instanceof EDrtWaitForShiftTask && ((EDrtWaitForShiftTask) task).getChargingTask() != null) { task.initTaskTracker(new OfflineETaskTracker((EvDvrpVehicle) vehicle, timer)); - return new ChargingWaitForShiftActivity(((EDrtWaitForShiftStayTask) task).getChargingTask()); + return new ChargingWaitForShiftActivity(((EDrtWaitForShiftTask) task).getChargingTask()); } DynAction dynAction = delegate.createAction(dynAgent, vehicle, now); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/ShiftEDrtTaskFactoryImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/ShiftEDrtTaskFactoryImpl.java index 5e0c085c1bb..b7c2657f1bf 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/ShiftEDrtTaskFactoryImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/schedule/ShiftEDrtTaskFactoryImpl.java @@ -9,7 +9,7 @@ import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftBreakTask; import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftChangeOverTask; import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftDrtTaskFactory; -import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftStayTask; +import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftTask; import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShift; import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftBreak; import org.matsim.contrib.drt.schedule.DrtDriveTask; @@ -69,14 +69,14 @@ public DefaultStayTask createInitialTask(DvrpVehicle vehicle, double beginTime, } catch (Throwable e) { throw new RuntimeException(e); } - WaitForShiftStayTask waitForShiftStayTask = createWaitForShiftStayTask(vehicle, vehicle.getServiceBeginTime(), vehicle.getServiceEndTime(), + WaitForShiftTask waitForShiftTask = createWaitForShiftStayTask(vehicle, vehicle.getServiceBeginTime(), vehicle.getServiceEndTime(), vehicle.getStartLink(), operationFacility); boolean success = operationFacility.register(vehicle.getId()); if (!success) { throw new RuntimeException(String.format("Cannot register vehicle %s at facility %s at start-up. Please check" + "facility capacity and initial fleet distribution.", vehicle.getId().toString(), operationFacility.getId().toString())); } - return waitForShiftStayTask; + return waitForShiftTask; } @Override @@ -92,16 +92,16 @@ public ShiftChangeOverTask createShiftChangeoverTask(DvrpVehicle vehicle, double } @Override - public WaitForShiftStayTask createWaitForShiftStayTask(DvrpVehicle vehicle, double beginTime, double endTime, Link link, - OperationFacility facility) { - return new EDrtWaitForShiftStayTask(beginTime, endTime, link, 0, facility, null); + public WaitForShiftTask createWaitForShiftStayTask(DvrpVehicle vehicle, double beginTime, double endTime, Link link, + OperationFacility facility) { + return new EDrtWaitForShiftTask(beginTime, endTime, link, 0, facility, null); } - public WaitForShiftStayTask createChargingWaitForShiftStayTask(DvrpVehicle vehicle, double beginTime, - double endTime, Link link, OperationFacility facility, - double totalEnergy, Charger charger) { + public WaitForShiftTask createChargingWaitForShiftStayTask(DvrpVehicle vehicle, double beginTime, + double endTime, Link link, OperationFacility facility, + double totalEnergy, Charger charger) { ChargingTask chargingTask = new ChargingTaskImpl(EDrtChargingTask.TYPE, beginTime, endTime, charger, ((EvDvrpVehicle)vehicle).getElectricVehicle(), totalEnergy); - return new EDrtWaitForShiftStayTask(beginTime, endTime, link, totalEnergy, facility, chargingTask); + return new EDrtWaitForShiftTask(beginTime, endTime, link, totalEnergy, facility, chargingTask); } public EDrtShiftBreakTaskImpl createChargingShiftBreakTask(DvrpVehicle vehicle, double beginTime, double endTime, Link link, diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/scheduler/EShiftTaskScheduler.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/scheduler/EShiftTaskScheduler.java index 7352f32c261..a87c54a1be8 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/scheduler/EShiftTaskScheduler.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/eshifts/scheduler/EShiftTaskScheduler.java @@ -6,6 +6,7 @@ import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.contrib.drt.extension.operations.eshifts.schedule.EDrtShiftChangeoverTaskImpl; +import org.matsim.contrib.drt.extension.operations.eshifts.schedule.EDrtWaitForShiftTask; import org.matsim.contrib.drt.extension.operations.eshifts.schedule.ShiftEDrtTaskFactoryImpl; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilities; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacility; @@ -22,10 +23,7 @@ import org.matsim.contrib.dvrp.fleet.Fleet; import org.matsim.contrib.dvrp.path.VrpPathWithTravelData; import org.matsim.contrib.dvrp.path.VrpPaths; -import org.matsim.contrib.dvrp.schedule.DriveTask; -import org.matsim.contrib.dvrp.schedule.Schedule; -import org.matsim.contrib.dvrp.schedule.StayTask; -import org.matsim.contrib.dvrp.schedule.Task; +import org.matsim.contrib.dvrp.schedule.*; import org.matsim.contrib.dvrp.tracker.OnlineDriveTaskTracker; import org.matsim.contrib.dvrp.util.LinkTimePair; import org.matsim.contrib.ev.charging.BatteryCharging; @@ -348,16 +346,20 @@ private void appendShiftChange(DvrpVehicle vehicle, DrtShift shift, OperationFac link, breakFacility)); } + @Override public void startShift(ShiftDvrpVehicle vehicle, double now, DrtShift shift) { - Schedule schedule = vehicle.getSchedule(); - StayTask stayTask = (StayTask) schedule.getCurrentTask(); - if (stayTask instanceof WaitForShiftStayTask) { - ((WaitForShiftStayTask) stayTask).getFacility().deregisterVehicle(vehicle.getId()); - stayTask.setEndTime(now); - schedule.addTask(taskFactory.createStayTask(vehicle, now, shift.getEndTime(), stayTask.getLink())); - } else { - throw new IllegalStateException("Vehicle cannot start shift during task:" + stayTask.getTaskType().name()); - } + Schedule schedule = vehicle.getSchedule(); + StayTask stayTask = (StayTask) schedule.getCurrentTask(); + if (stayTask instanceof WaitForShiftTask) { + ((WaitForShiftTask) stayTask).getFacility().deregisterVehicle(vehicle.getId()); + stayTask.setEndTime(now); + if(Schedules.getLastTask(schedule).equals(stayTask)) { + //nothing planned yet. + schedule.addTask(taskFactory.createStayTask(vehicle, now, shift.getEndTime(), stayTask.getLink())); + } + } else { + throw new IllegalStateException("Vehicle cannot start shift during task:" + stayTask.getTaskType().name()); + } } public boolean updateShiftChange(ShiftDvrpVehicle vehicle, Link link, DrtShift shift, @@ -375,6 +377,58 @@ public boolean updateShiftChange(ShiftDvrpVehicle vehicle, Link link, DrtShift s return false; } + @Override + public void planAssignedShift(ShiftDvrpVehicle vehicle, double timeStep, DrtShift shift) { + Schedule schedule = vehicle.getSchedule(); + StayTask stayTask = (StayTask) schedule.getCurrentTask(); + if (stayTask instanceof WaitForShiftTask waitForShiftTask) { + if(waitForShiftTask instanceof EDrtWaitForShiftTask eDrtWaitForShiftTask) { + if(eDrtWaitForShiftTask.getChargingTask() != null) { + Task nextTask = Schedules.getNextTask(vehicle.getSchedule()); + if(nextTask instanceof WaitForShiftTask) { + // set +1 to ensure this update happens after next shift start check + nextTask.setEndTime(Math.max(timeStep + 1, shift.getStartTime())); + //append stay task if required + if(Schedules.getLastTask(schedule).equals(nextTask)) { + schedule.addTask(taskFactory.createStayTask(vehicle, nextTask.getEndTime(), shift.getEndTime(), ((WaitForShiftTask) nextTask).getLink())); + } + } else { + throw new RuntimeException(); + } + } else { + stayTask.setEndTime(Math.max(timeStep +1 , shift.getStartTime())); + //append stay task if required + if(Schedules.getLastTask(schedule).equals(stayTask)) { + schedule.addTask(taskFactory.createStayTask(vehicle, stayTask.getEndTime(), shift.getEndTime(), stayTask.getLink())); + } + } + } + } + } + + + @Override + public void cancelAssignedShift(ShiftDvrpVehicle vehicle, double timeStep, DrtShift shift) { + Schedule schedule = vehicle.getSchedule(); + StayTask stayTask = (StayTask) schedule.getCurrentTask(); + if (stayTask instanceof WaitForShiftTask waitForShiftTask) { + if(waitForShiftTask instanceof EDrtWaitForShiftTask eDrtWaitForShiftTask) { + if(eDrtWaitForShiftTask.getChargingTask() != null) { + Task nextTask = Schedules.getNextTask(vehicle.getSchedule()); + if(nextTask instanceof WaitForShiftTask) { + nextTask.setEndTime(vehicle.getServiceEndTime()); + } else { + throw new RuntimeException(); + } + } else { + stayTask.setEndTime(vehicle.getServiceEndTime()); + } + } + } else { + throw new IllegalStateException("Vehicle should be in WaitForShiftTask"); + } + } + private void updateShiftChangeImpl(DvrpVehicle vehicle, VrpPathWithTravelData vrpPath, DrtShift shift, OperationFacility facility, Task lastTask) { Schedule schedule = vehicle.getSchedule(); @@ -413,19 +467,19 @@ private void updateShiftChangeImpl(DvrpVehicle vehicle, VrpPathWithTravelData vr vrpPath.getToLink(), facility)); } - public void chargeAtHub(WaitForShiftStayTask currentTask, ShiftDvrpVehicle vehicle, + public void chargeAtHub(WaitForShiftTask currentTask, ShiftDvrpVehicle vehicle, ElectricVehicle electricVehicle, Charger charger, double beginTime, double endTime, double energy) { final double initialEndTime = currentTask.getEndTime(); currentTask.setEndTime(beginTime); ((ChargingWithAssignmentLogic) charger.getLogic()).assignVehicle(electricVehicle); - final WaitForShiftStayTask chargingWaitForShiftStayTask = ((ShiftEDrtTaskFactoryImpl) taskFactory).createChargingWaitForShiftStayTask(vehicle, + final WaitForShiftTask chargingWaitForShiftTask = ((ShiftEDrtTaskFactoryImpl) taskFactory).createChargingWaitForShiftStayTask(vehicle, beginTime, endTime, currentTask.getLink(), currentTask.getFacility(), energy, charger); - final WaitForShiftStayTask waitForShiftStayTask = taskFactory.createWaitForShiftStayTask(vehicle, endTime, + final WaitForShiftTask waitForShiftTask = taskFactory.createWaitForShiftStayTask(vehicle, endTime, initialEndTime, currentTask.getLink(), currentTask.getFacility()); - vehicle.getSchedule().addTask(currentTask.getTaskIdx() + 1, chargingWaitForShiftStayTask); - vehicle.getSchedule().addTask(currentTask.getTaskIdx() + 2, waitForShiftStayTask); + vehicle.getSchedule().addTask(currentTask.getTaskIdx() + 1, chargingWaitForShiftTask); + vehicle.getSchedule().addTask(currentTask.getTaskIdx() + 2, waitForShiftTask); } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/NearestOperationFacilityWithCapacityFinder.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/NearestOperationFacilityWithCapacityFinder.java index 1df98354824..7d41752548e 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/NearestOperationFacilityWithCapacityFinder.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/NearestOperationFacilityWithCapacityFinder.java @@ -4,6 +4,7 @@ import org.matsim.contrib.common.util.DistanceUtils; import java.util.Comparator; +import java.util.Optional; import java.util.function.Predicate; /** @@ -21,7 +22,7 @@ public NearestOperationFacilityWithCapacityFinder(OperationFacilities operationF } @Override - public OperationFacility findFacilityOfType(Coord coord, OperationFacilityType type) { + public Optional findFacilityOfType(Coord coord, OperationFacilityType type) { Predicate filter; switch (type) { case hub: @@ -37,15 +38,15 @@ public OperationFacility findFacilityOfType(Coord coord, OperationFacilityType t .filter(filter) .filter(OperationFacility::hasCapacity) .min(Comparator.comparing( - f -> DistanceUtils.calculateSquaredDistance(coord, f.getCoord()))).orElse(null); + f -> DistanceUtils.calculateSquaredDistance(coord, f.getCoord()))); } @Override - public OperationFacility findFacility(Coord coord) { + public Optional findFacility(Coord coord) { return operationFacilities.getDrtOperationFacilities().values().stream() .filter(OperationFacility::hasCapacity) .min(Comparator.comparing( - f -> DistanceUtils.calculateSquaredDistance(coord, f.getCoord()))).orElse(null); + f -> DistanceUtils.calculateSquaredDistance(coord, f.getCoord()))); } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/OperationFacilitiesModeModule.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/OperationFacilitiesModeModule.java index 15276252c50..e178fc0a69d 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/OperationFacilitiesModeModule.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/OperationFacilitiesModeModule.java @@ -1,6 +1,6 @@ package org.matsim.contrib.drt.extension.operations.operationFacilities; -import org.matsim.contrib.drt.extension.operations.DrtWithOperationsConfigGroup; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.operations.shifts.io.OperationFacilitiesReader; import org.matsim.contrib.dvrp.run.AbstractDvrpModeModule; @@ -8,9 +8,9 @@ public class OperationFacilitiesModeModule extends AbstractDvrpModeModule { private final OperationFacilitiesParams operationFacilitiesParams; - public OperationFacilitiesModeModule(DrtWithOperationsConfigGroup drtCfg) { + public OperationFacilitiesModeModule(DrtWithExtensionsConfigGroup drtCfg) { super(drtCfg.getMode()); - this.operationFacilitiesParams = drtCfg.getDrtOperationsParams().getOperationFacilitiesParams().orElseThrow(); + this.operationFacilitiesParams = drtCfg.getDrtOperationsParams().orElseThrow().getOperationFacilitiesParams().orElseThrow(); } @Override diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/OperationFacilityFinder.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/OperationFacilityFinder.java index 8262f5938f5..469f7f3703b 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/OperationFacilityFinder.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/operationFacilities/OperationFacilityFinder.java @@ -2,12 +2,14 @@ import org.matsim.api.core.v01.Coord; +import java.util.Optional; + /** * @author nkuehnel / MOIA */ public interface OperationFacilityFinder { - OperationFacility findFacilityOfType(Coord coord, OperationFacilityType type); + Optional findFacilityOfType(Coord coord, OperationFacilityType type); - OperationFacility findFacility(Coord coord); + Optional findFacility(Coord coord); } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/config/ShiftsParams.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/config/ShiftsParams.java index 4d76cbddfc0..e61e5541896 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/config/ShiftsParams.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/config/ShiftsParams.java @@ -8,8 +8,8 @@ */ package org.matsim.contrib.drt.extension.operations.shifts.config; -import org.matsim.contrib.ev.infrastructure.ChargerSpecification; import org.matsim.contrib.common.util.ReflectiveConfigGroupWithConfigurableParameterSets; +import org.matsim.contrib.ev.infrastructure.ChargerSpecification; import org.matsim.core.config.ConfigGroup; import java.net.URL; @@ -43,7 +43,7 @@ public class ShiftsParams extends ReflectiveConfigGroupWithConfigurableParameter @Parameter @Comment("Time of shift end rescheduling (i.e. check whether shift should end" + - " at a different facillity) before end of shift in [seconds]") + " at a different facility) before end of shift in [seconds]") public double shiftEndRescheduleLookAhead = 1800; @Parameter @@ -53,7 +53,7 @@ public class ShiftsParams extends ReflectiveConfigGroupWithConfigurableParameter @Parameter @Comment("set to true if shifts can start and end at in field operational facilities," + - " false if changerover is only allowed at hubs") + " false if changeover is only allowed at hubs") public boolean allowInFieldChangeover = true; //electric shifts @@ -91,7 +91,13 @@ public class ShiftsParams extends ReflectiveConfigGroupWithConfigurableParameter @Comment("defines the logging interval in [seconds]") public double loggingInterval = 600; - public ShiftsParams() { + @Parameter + @Comment("Defines whether vehicles should be eligible for insertion when they have a shift assigned which has not yet started. " + + "Defaults to false. Should be set to true if used together with prebookings that are inserted before shift starts. " + + "In this case, make sure that 'shiftScheduleLookAhead' is larger than the prebboking slack.") + public boolean considerUpcomingShiftsForInsertion = false; + + public ShiftsParams() { super(SET_NAME); } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DefaultShiftStartLogic.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DefaultShiftStartLogic.java index cb9e5d76a9f..f2b006cbae7 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DefaultShiftStartLogic.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DefaultShiftStartLogic.java @@ -11,7 +11,7 @@ import com.google.common.base.Verify; import org.matsim.api.core.v01.Id; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacility; -import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftStayTask; +import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftTask; import org.matsim.contrib.dvrp.schedule.Schedule; import org.matsim.contrib.dvrp.schedule.Task; @@ -34,11 +34,11 @@ public boolean shiftStarts(DrtShiftDispatcher.ShiftEntry peek) { // current task is WaitForShiftTask Task currentTask = schedule.getCurrentTask(); - if(currentTask instanceof WaitForShiftStayTask) { + if(currentTask instanceof WaitForShiftTask) { //check if optional location requirement is met if(peek.shift().getOperationFacilityId().isPresent()) { Id operationFacilityId = peek.shift().getOperationFacilityId().get(); - Verify.verify((operationFacilityId.equals(((WaitForShiftStayTask) currentTask).getFacility().getId())), + Verify.verify((operationFacilityId.equals(((WaitForShiftTask) currentTask).getFacility().getId())), "Vehicle and shift start locations do not match."); } return true; diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java index c32b5d1b12b..6e082f6f7d5 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcherImpl.java @@ -51,10 +51,10 @@ public class DrtShiftDispatcherImpl implements DrtShiftDispatcher { private final String mode; - private Queue unscheduledShifts; - private Queue assignedShifts; - private Queue activeShifts; - private Queue endingShifts; + private SortedSet unscheduledShifts; + private SortedSet assignedShifts; + private SortedSet activeShifts; + private SortedSet endingShifts; private Map, Queue> idleVehiclesQueues; @@ -63,8 +63,8 @@ public class DrtShiftDispatcherImpl implements DrtShiftDispatcher { private final MobsimTimer timer; - private final OperationFacilities operationFacilities; - private final OperationFacilityFinder breakFacilityFinder; + private final OperationFacilities operationFacilities; + private final OperationFacilityFinder breakFacilityFinder; private final ShiftTaskScheduler shiftTaskScheduler; private final Network network; @@ -73,8 +73,8 @@ public class DrtShiftDispatcherImpl implements DrtShiftDispatcher { private final ShiftsParams drtShiftParams; - private final ShiftStartLogic shiftStartLogic; - private final AssignShiftToVehicleLogic assignShiftToVehicleLogic; + private final ShiftStartLogic shiftStartLogic; + private final AssignShiftToVehicleLogic assignShiftToVehicleLogic; public DrtShiftDispatcherImpl(String mode, DrtShifts shifts, Fleet fleet, MobsimTimer timer, OperationFacilities operationFacilities, OperationFacilityFinder breakFacilityFinder, ShiftTaskScheduler shiftTaskScheduler, @@ -84,54 +84,56 @@ public DrtShiftDispatcherImpl(String mode, DrtShifts shifts, Fleet fleet, Mobsim this.shifts = shifts; this.fleet = fleet; this.timer = timer; - this.operationFacilities = operationFacilities; - this.breakFacilityFinder = breakFacilityFinder; + this.operationFacilities = operationFacilities; + this.breakFacilityFinder = breakFacilityFinder; this.shiftTaskScheduler = shiftTaskScheduler; this.network = network; this.eventsManager = eventsManager; this.drtShiftParams = drtShiftParams; - this.shiftStartLogic = shiftStartLogic; - this.assignShiftToVehicleLogic = assignShiftToVehicleLogic; + this.shiftStartLogic = shiftStartLogic; + this.assignShiftToVehicleLogic = assignShiftToVehicleLogic; } - @Override - public void initialize() { + @Override + public void initialize() { - unscheduledShifts = new PriorityQueue<>(Comparator.comparingDouble(DrtShift::getStartTime)); + unscheduledShifts = new TreeSet<>(Comparator.comparingDouble(DrtShift::getStartTime)); unscheduledShifts.addAll(shifts.getShifts().values()); - assignedShifts = new PriorityQueue<>(Comparator.comparingDouble(v -> v.shift().getStartTime())); + assignedShifts = new TreeSet<>(Comparator.comparingDouble(v -> v.shift().getStartTime())); idleVehiclesQueues = new LinkedHashMap<>(); - for(OperationFacility facility: operationFacilities.getDrtOperationFacilities().values()) { - PriorityQueue queue = new PriorityQueue<>((v1, v2) -> String.CASE_INSENSITIVE_ORDER.compare(v1.getId().toString(), v2.getId().toString())); - Set> registeredVehicles = facility.getRegisteredVehicles(); - for (Id registeredVehicle : registeredVehicles) { - queue.add((ShiftDvrpVehicle) fleet.getVehicles().get(registeredVehicle)); - } - idleVehiclesQueues.put( - facility.getId(), - queue - ); - } - activeShifts = new PriorityQueue<>(Comparator.comparingDouble(v -> v.shift().getEndTime())); - endingShifts = new PriorityQueue<>(Comparator.comparingDouble(v -> v.shift().getEndTime())); + for(OperationFacility facility: operationFacilities.getDrtOperationFacilities().values()) { + PriorityQueue queue = new PriorityQueue<>((v1, v2) -> String.CASE_INSENSITIVE_ORDER.compare(v1.getId().toString(), v2.getId().toString())); + Set> registeredVehicles = facility.getRegisteredVehicles(); + for (Id registeredVehicle : registeredVehicles) { + queue.add((ShiftDvrpVehicle) fleet.getVehicles().get(registeredVehicle)); + } + idleVehiclesQueues.put( + facility.getId(), + queue + ); + } + activeShifts = new TreeSet<>(Comparator.comparingDouble(v -> v.shift().getEndTime())); + endingShifts = new TreeSet<>(Comparator.comparingDouble(v -> v.shift().getEndTime())); } - @Override + @Override public void dispatch(double timeStep) { - if(timeStep % drtShiftParams.loggingInterval == 0) { - logger.info(String.format("Active shifts: %s | Assigned shifts: %s | Unscheduled shifts: %s", - activeShifts.size(), assignedShifts.size(), unscheduledShifts.size())); - for (Map.Entry, Queue> queueEntry : idleVehiclesQueues.entrySet()) { - logger.info(String.format("Idle vehicles at facility %s: %d", queueEntry.getKey().toString(), queueEntry.getValue().size())); - } - } + if(timeStep % drtShiftParams.loggingInterval == 0) { + logger.info(String.format("Active shifts: %s | Assigned shifts: %s | Unscheduled shifts: %s", + activeShifts.size(), assignedShifts.size(), unscheduledShifts.size())); + StringJoiner print = new StringJoiner(" | "); + for (Map.Entry, Queue> queueEntry : idleVehiclesQueues.entrySet()) { + print.add(String.format("Idle vehicles at facility %s: %d", queueEntry.getKey().toString(), queueEntry.getValue().size())); + } + logger.info(print.toString()); + } endShifts(timeStep); - if (timeStep % (drtShiftParams.updateShiftEndInterval) == 0) { - updateShiftEnds(timeStep); - } - assignShifts(timeStep); + if (timeStep % (drtShiftParams.updateShiftEndInterval) == 0) { + updateShiftEnds(timeStep); + } + assignShifts(timeStep); startShifts(timeStep); checkBreaks(); } @@ -140,40 +142,52 @@ private void checkBreaks() { for (ShiftEntry activeShift : activeShifts) { final DrtShift shift = activeShift.shift(); if (shift != null && shift.isStarted()) { - OperationFacility breakFacility = decideOnBreak(activeShift); - if (breakFacility != null) { - shiftTaskScheduler.relocateForBreak(activeShift.vehicle(), breakFacility, shift); - eventsManager.processEvent(new DrtShiftBreakScheduledEvent(timer.getTimeOfDay(), mode, shift.getId(), - activeShift.vehicle().getId(), breakFacility.getLinkId(), - shift.getBreak().orElseThrow().getScheduledLatestArrival())); + if (hasSchedulableBreak(shift, timer.getTimeOfDay())) { + Optional breakFacility = findBreakFacility(activeShift); + if (breakFacility.isPresent()) { + OperationFacility facility = breakFacility.get(); + if (facility.register(activeShift.vehicle().getId())) { + eventsManager.processEvent(new ShiftFacilityRegistrationEvent( + timer.getTimeOfDay(), mode, activeShift.vehicle().getId(), facility.getId())); + shiftTaskScheduler.relocateForBreak(activeShift.vehicle(), facility, shift); + eventsManager.processEvent(new DrtShiftBreakScheduledEvent(timer.getTimeOfDay(), mode, shift.getId(), + activeShift.vehicle().getId(), facility.getLinkId(), + shift.getBreak().orElseThrow().getScheduledLatestArrival())); + return; + } + } + throw new RuntimeException("Could not schedule break!"); } } } } private void startShifts(double timeStep) { - // Start shifts final Iterator iterator = this.assignedShifts.iterator(); while (iterator.hasNext()) { - final ShiftEntry next = iterator.next(); - if (next.shift().getStartTime() > timeStep) { - break; - } else if (next.shift().getEndTime() < timeStep) { - logger.warn("Too late to start shift " + next.shift().getId()); - next.vehicle().getShifts().remove(next.shift()); + final ShiftEntry assignedShiftEntry = iterator.next(); + if (assignedShiftEntry.shift().getStartTime() > timeStep) { + shiftTaskScheduler.planAssignedShift(assignedShiftEntry.vehicle(), timeStep, assignedShiftEntry.shift()); + continue; + } else if (assignedShiftEntry.shift().getEndTime() < timeStep) { + logger.warn("Too late to start shift " + assignedShiftEntry.shift().getId()); + shiftTaskScheduler.cancelAssignedShift(assignedShiftEntry.vehicle(), timeStep, assignedShiftEntry.shift()); + assignedShiftEntry.vehicle().getShifts().remove(assignedShiftEntry.shift()); iterator.remove(); - continue; + continue; } - if (shiftStartLogic.shiftStarts(next)) { - next.shift().start(); - shiftTaskScheduler.startShift(next.vehicle(), timeStep, next.shift()); - activeShifts.add(next); + if (shiftStartLogic.shiftStarts(assignedShiftEntry)) { + assignedShiftEntry.shift().start(); + shiftTaskScheduler.startShift(assignedShiftEntry.vehicle(), timeStep, assignedShiftEntry.shift()); + activeShifts.add(assignedShiftEntry); iterator.remove(); - logger.debug("Started shift " + next.shift()); - StayTask currentTask = (StayTask) next.vehicle().getSchedule().getCurrentTask(); - eventsManager.processEvent(new DrtShiftStartedEvent(timeStep, mode, next.shift().getId(), next.vehicle().getId(), + logger.debug("Started shift " + assignedShiftEntry.shift()); + StayTask currentTask = (StayTask) assignedShiftEntry.vehicle().getSchedule().getCurrentTask(); + eventsManager.processEvent(new DrtShiftStartedEvent(timeStep, mode, assignedShiftEntry.shift().getId(), assignedShiftEntry.vehicle().getId(), currentTask.getLink().getId())); + } else { + shiftTaskScheduler.planAssignedShift(assignedShiftEntry.vehicle(), timeStep, assignedShiftEntry.shift()); } } } @@ -181,17 +195,24 @@ private void startShifts(double timeStep) { private void assignShifts(double timeStep) { // Remove elapsed shifts unscheduledShifts.removeIf(shift -> { - if (shift.getStartTime() + drtShiftParams.maxUnscheduledShiftDelay < timeStep ) { - logger.warn("Shift with ID " + shift.getId() + " could not be assigned and is being removed as start time is longer in the past than defined by maxUnscheduledShiftDelay."); - return true; - } - return false; - }); + if (shift.getStartTime() + drtShiftParams.maxUnscheduledShiftDelay < timeStep ) { + logger.warn("Shift with ID " + shift.getId() + " could not be assigned and is being removed as start time is longer in the past than defined by maxUnscheduledShiftDelay."); + return true; + } + return false; + }); // Assign shifts Set assignableShifts = new LinkedHashSet<>(); - while (!this.unscheduledShifts.isEmpty() && isSchedulable(this.unscheduledShifts.peek(), timeStep)) { - assignableShifts.add(this.unscheduledShifts.poll()); + Iterator unscheduledShiftsIterator = unscheduledShifts.iterator(); + while(unscheduledShiftsIterator.hasNext()) { + DrtShift unscheduledShift = unscheduledShiftsIterator.next(); + if(isSchedulable(unscheduledShift, timeStep)) { + assignableShifts.add(unscheduledShift); + unscheduledShiftsIterator.remove(); + } else { + break; + } } for (DrtShift shift : assignableShifts) { @@ -201,24 +222,24 @@ private void assignShifts(double timeStep) { if (active.shift().getEndTime() > shift.getStartTime()) { break; } - if(shift.getOperationFacilityId().isPresent()) { - //we have to check that the vehicle ends the previous shift at the same facility where - //the new shift is to start. - if(active.shift().getOperationFacilityId().isPresent()) { - if(!active.shift().getOperationFacilityId().get().equals(shift.getOperationFacilityId().get())) { - continue; - } - } else { - Optional nextShiftChangeover = ShiftSchedules.getNextShiftChangeover(active.vehicle().getSchedule()); - if(nextShiftChangeover.isPresent()) { - Verify.verify(nextShiftChangeover.get().getShift().equals(active.shift())); - if(!nextShiftChangeover.get().getFacility().getId().equals(shift.getOperationFacilityId().get())) { - // there is already a shift changeover scheduled elsewhere - continue; - } - } - } - } + if(shift.getOperationFacilityId().isPresent()) { + //we have to check that the vehicle ends the previous shift at the same facility where + //the new shift is to start. + if(active.shift().getOperationFacilityId().isPresent()) { + if(!active.shift().getOperationFacilityId().get().equals(shift.getOperationFacilityId().get())) { + continue; + } + } else { + Optional nextShiftChangeover = ShiftSchedules.getNextShiftChangeover(active.vehicle().getSchedule()); + if(nextShiftChangeover.isPresent()) { + Verify.verify(nextShiftChangeover.get().getShift().equals(active.shift())); + if(!nextShiftChangeover.get().getFacility().getId().equals(shift.getOperationFacilityId().get())) { + // there is already a shift changeover scheduled elsewhere + continue; + } + } + } + } if (assignShiftToVehicleLogic.canAssignVehicleToShift(active.vehicle(), shift)) { vehicle = active.vehicle(); break; @@ -226,29 +247,29 @@ private void assignShifts(double timeStep) { } if (vehicle == null) { - final Iterator iterator; - - if(shift.getOperationFacilityId().isPresent()) { - //shift has to start at specific hub/facility - iterator = idleVehiclesQueues.get(shift.getOperationFacilityId().get()).iterator(); - } else { - //shift can start at random location - IteratorChain iteratorChain = new IteratorChain<>(); - for (Queue value : idleVehiclesQueues.values()) { - iteratorChain.addIterator(value.iterator()); - } - iterator = iteratorChain; - } - - while (iterator.hasNext()) { - final ShiftDvrpVehicle next = iterator.next(); - if (assignShiftToVehicleLogic.canAssignVehicleToShift(next, shift)) { - vehicle = next; - iterator.remove(); - break; - } - } - } + final Iterator iterator; + + if(shift.getOperationFacilityId().isPresent()) { + //shift has to start at specific hub/facility + iterator = idleVehiclesQueues.get(shift.getOperationFacilityId().get()).iterator(); + } else { + //shift can start at random location + IteratorChain iteratorChain = new IteratorChain<>(); + for (Queue value : idleVehiclesQueues.values()) { + iteratorChain.addIterator(value.iterator()); + } + iterator = iteratorChain; + } + + while (iterator.hasNext()) { + final ShiftDvrpVehicle next = iterator.next(); + if (assignShiftToVehicleLogic.canAssignVehicleToShift(next, shift)) { + vehicle = next; + iterator.remove(); + break; + } + } + } if (vehicle != null) { logger.debug("Shift assigned"); @@ -264,6 +285,7 @@ private void assignShifts(double timeStep) { private void assignShiftToVehicle(DrtShift shift, ShiftDvrpVehicle vehicle) { Gbl.assertNotNull(vehicle); vehicle.addShift(shift); + shiftTaskScheduler.planAssignedShift(vehicle, timer.getTimeOfDay(), shift); assignedShifts.add(new ShiftEntry(shift, vehicle)); eventsManager.processEvent(new DrtShiftAssignedEvent(timer.getTimeOfDay(), mode, shift.getId(), vehicle.getId())); } @@ -284,37 +306,37 @@ private void endShifts(double timeStep) { throw new IllegalStateException("Shifts don't match!"); } - logger.debug("Scheduling shift end for shift " + next.shift().getId() + " of vehicle " + next.vehicle().getId()); - scheduleShiftEnd(next); - endingShifts.add(next); - iterator.remove(); + logger.debug("Scheduling shift end for shift " + next.shift().getId() + " of vehicle " + next.vehicle().getId()); + scheduleShiftEnd(next); + endingShifts.add(next); + iterator.remove(); + } + } + + private void updateShiftEnds(double timeStep) { + final Iterator endingShiftsIterator = this.endingShifts.iterator(); + while (endingShiftsIterator.hasNext()) { + final ShiftEntry next = endingShiftsIterator.next(); + if (next.shift().isEnded()) { + endingShiftsIterator.remove(); + continue; + } + if (timeStep + drtShiftParams.shiftEndRescheduleLookAhead > next.shift().getEndTime()) { + if (next.vehicle().getShifts().size() > 1) { + updateShiftEnd(next); + } + } else { + break; + } + } + } + + private void updateShiftEnd(ShiftEntry next) { + + if(next.shift().getOperationFacilityId().isPresent()) { + //start and end facility are fixed + return; } - } - - private void updateShiftEnds(double timeStep) { - final Iterator endingShiftsIterator = this.endingShifts.iterator(); - while (endingShiftsIterator.hasNext()) { - final ShiftEntry next = endingShiftsIterator.next(); - if (next.shift().isEnded()) { - endingShiftsIterator.remove(); - continue; - } - if (timeStep + drtShiftParams.shiftEndRescheduleLookAhead > next.shift().getEndTime()) { - if (next.vehicle().getShifts().size() > 1) { - updateShiftEnd(next); - } - } else { - break; - } - } - } - - private void updateShiftEnd(ShiftEntry next) { - - if(next.shift().getOperationFacilityId().isPresent()) { - //start and end facility are fixed - return; - } final List tasks = next.vehicle().getSchedule().getTasks(); @@ -357,23 +379,25 @@ private void updateShiftEnd(ShiftEntry next) { } } - final OperationFacility shiftChangeFacility; + final Optional maybeFacility; if (drtShiftParams.allowInFieldChangeover) { - shiftChangeFacility = breakFacilityFinder.findFacility(start.link.getCoord()); + maybeFacility = breakFacilityFinder.findFacility(start.link.getCoord()); } else { - shiftChangeFacility = breakFacilityFinder.findFacilityOfType(start.link.getCoord(), + maybeFacility = breakFacilityFinder.findFacilityOfType(start.link.getCoord(), OperationFacilityType.hub); } - if (shiftChangeFacility != null && changeOverTask != null - && !(shiftChangeFacility.getId().equals(changeOverTask.getFacility().getId()))) { - if (shiftChangeFacility.hasCapacity()) { - if (shiftTaskScheduler.updateShiftChange(next.vehicle(), - network.getLinks().get(shiftChangeFacility.getLinkId()), next.shift(), start, - shiftChangeFacility, lastTask)) { - shiftChangeFacility.register(next.vehicle().getId()); - changeOverTask.getFacility().deregisterVehicle(next.vehicle().getId()); - eventsManager.processEvent(new ShiftFacilityRegistrationEvent(timer.getTimeOfDay(), - mode, next.vehicle().getId(), shiftChangeFacility.getId())); + if (maybeFacility.isPresent()) { + OperationFacility shiftChangeFacility = maybeFacility.get(); + if(changeOverTask != null && !(shiftChangeFacility.getId().equals(changeOverTask.getFacility().getId()))) { + if (shiftChangeFacility.hasCapacity()) { + if (shiftTaskScheduler.updateShiftChange(next.vehicle(), + network.getLinks().get(shiftChangeFacility.getLinkId()), next.shift(), start, + shiftChangeFacility, lastTask)) { + shiftChangeFacility.register(next.vehicle().getId()); + changeOverTask.getFacility().deregisterVehicle(next.vehicle().getId()); + eventsManager.processEvent(new ShiftFacilityRegistrationEvent(timer.getTimeOfDay(), + mode, next.vehicle().getId(), shiftChangeFacility.getId())); + } } } } @@ -400,73 +424,58 @@ private void scheduleShiftEnd(ShiftEntry endingShift) { } final Coord coord = lastLink.getCoord(); - OperationFacility shiftChangeoverFacility = null; - - //check whether current shift has to end at specific facility - if(endingShift.shift().getOperationFacilityId().isPresent()) { - shiftChangeoverFacility = operationFacilities - .getDrtOperationFacilities() - .get(endingShift.shift().getOperationFacilityId().get()); - } else { - //check whether next shift has to start at specific facility - for (DrtShift shift : endingShift.vehicle().getShifts()) { - if (shift != endingShift.shift()) { - if (shift.getOperationFacilityId().isPresent()) { - shiftChangeoverFacility = operationFacilities - .getDrtOperationFacilities() - .get(shift.getOperationFacilityId().get()); - } - break; - } - } - } - - if(shiftChangeoverFacility == null) { - shiftChangeoverFacility = breakFacilityFinder.findFacilityOfType(coord, - OperationFacilityType.hub); - } - - if (shiftChangeoverFacility != null && shiftChangeoverFacility.register(endingShift.vehicle().getId())) { - shiftTaskScheduler.relocateForShiftChange(endingShift.vehicle(), - network.getLinks().get(shiftChangeoverFacility.getLinkId()), endingShift.shift(), shiftChangeoverFacility); - eventsManager.processEvent(new ShiftFacilityRegistrationEvent(timer.getTimeOfDay(), mode, endingShift.vehicle().getId(), - shiftChangeoverFacility.getId())); + OperationFacility shiftChangeoverFacility = null; + + //check whether current shift has to end at specific facility + if(endingShift.shift().getOperationFacilityId().isPresent()) { + shiftChangeoverFacility = operationFacilities + .getDrtOperationFacilities() + .get(endingShift.shift().getOperationFacilityId().get()); } else { - throw new RuntimeException("Could not find shift end location!"); + //check whether next shift has to start at specific facility + for (DrtShift shift : endingShift.vehicle().getShifts()) { + if (shift != endingShift.shift()) { + if (shift.getOperationFacilityId().isPresent()) { + shiftChangeoverFacility = operationFacilities + .getDrtOperationFacilities() + .get(shift.getOperationFacilityId().get()); + } + break; + } + } + } + + if(shiftChangeoverFacility == null) { + shiftChangeoverFacility = breakFacilityFinder.findFacilityOfType(coord, + OperationFacilityType.hub).orElseThrow(() -> new RuntimeException("Could not find shift end location!")); } + + Verify.verify(shiftChangeoverFacility.register(endingShift.vehicle().getId()), "Could not register vehicle at facility."); + + shiftTaskScheduler.relocateForShiftChange(endingShift.vehicle(), + network.getLinks().get(shiftChangeoverFacility.getLinkId()), endingShift.shift(), shiftChangeoverFacility); + eventsManager.processEvent(new ShiftFacilityRegistrationEvent(timer.getTimeOfDay(), mode, endingShift.vehicle().getId(), + shiftChangeoverFacility.getId())); } - private OperationFacility decideOnBreak(ShiftEntry activeShift) { - if (activeShift.shift() != null) { - if (shiftNeedsBreak(activeShift.shift(), timer.getTimeOfDay())) { - final Schedule schedule = activeShift.vehicle().getSchedule(); - Task currentTask = schedule.getCurrentTask(); - Link lastLink; - if (currentTask instanceof DriveTask - && currentTask.getTaskType().equals(EmptyVehicleRelocator.RELOCATE_VEHICLE_TASK_TYPE) - && currentTask.equals(schedule.getTasks().get(schedule.getTaskCount()-2))) { - LinkTimePair start = ((OnlineDriveTaskTracker) currentTask.getTaskTracker()).getDiversionPoint(); - if(start != null) { - lastLink = start.link; - } else { - lastLink = ((DriveTask) currentTask).getPath().getToLink(); - } - } else { - lastLink = ((DrtStayTask) schedule.getTasks() - .get(schedule.getTaskCount() - 1)).getLink(); - } - final OperationFacility shiftBreakFacility = breakFacilityFinder.findFacility(lastLink.getCoord()); - if (shiftBreakFacility == null) { - throw new RuntimeException("Could not schedule break!"); - } - if (shiftBreakFacility.register(activeShift.vehicle().getId())) { - eventsManager.processEvent(new ShiftFacilityRegistrationEvent(timer.getTimeOfDay(), - mode, activeShift.vehicle().getId(), shiftBreakFacility.getId())); - return shiftBreakFacility; - } + private Optional findBreakFacility(ShiftEntry activeShift) { + final Schedule schedule = activeShift.vehicle().getSchedule(); + Task currentTask = schedule.getCurrentTask(); + Link lastLink; + if (currentTask instanceof DriveTask + && currentTask.getTaskType().equals(EmptyVehicleRelocator.RELOCATE_VEHICLE_TASK_TYPE) + && currentTask.equals(schedule.getTasks().get(schedule.getTaskCount()-2))) { + LinkTimePair start = ((OnlineDriveTaskTracker) currentTask.getTaskTracker()).getDiversionPoint(); + if(start != null) { + lastLink = start.link; + } else { + lastLink = ((DriveTask) currentTask).getPath().getToLink(); } + } else { + lastLink = ((DrtStayTask) schedule.getTasks() + .get(schedule.getTaskCount() - 1)).getLink(); } - return null; + return breakFacilityFinder.findFacility(lastLink.getCoord()); } @Override @@ -488,24 +497,22 @@ public void endBreak(ShiftDvrpVehicle vehicle, ShiftBreakTask previousTask) { new VehicleLeftShiftFacilityEvent(timer.getTimeOfDay(), mode, vehicle.getId(), facility.getId())); eventsManager.processEvent( new DrtShiftBreakEndedEvent(timer.getTimeOfDay(), mode, vehicle.getShifts().peek().getId(), - vehicle.getId(), previousTask.getFacility().getLinkId()) + vehicle.getId(), previousTask.getFacility().getLinkId()) ); } public void startBreak(ShiftDvrpVehicle vehicle, Id linkId) { eventsManager.processEvent( new DrtShiftBreakStartedEvent(timer.getTimeOfDay(), mode, - vehicle.getShifts().peek().getId(), vehicle.getId(), linkId) + vehicle.getShifts().peek().getId(), vehicle.getId(), linkId) ); } private boolean isSchedulable(DrtShift shift, double timeStep) { - return shift.getStartTime() <= timeStep + drtShiftParams.shiftScheduleLookAhead; // && shift.getEndTime() > timeStep; + return shift.getStartTime() <= timeStep + drtShiftParams.shiftScheduleLookAhead; } - - - private boolean shiftNeedsBreak(DrtShift shift, double timeStep) { + private boolean hasSchedulableBreak(DrtShift shift, double timeStep) { return shift.getBreak().isPresent() && shift.getBreak().get().getEarliestBreakStartTime() == timeStep && !shift.getBreak().get().isScheduled(); } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/ShiftVehicleDataEntryFactory.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/ShiftVehicleDataEntryFactory.java index 3262fe787fc..66a3470ddbe 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/ShiftVehicleDataEntryFactory.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/ShiftVehicleDataEntryFactory.java @@ -1,16 +1,11 @@ package org.matsim.contrib.drt.extension.operations.shifts.optimizer; -import com.google.inject.Provider; import org.matsim.contrib.drt.extension.operations.shifts.fleet.ShiftDvrpVehicle; -import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShift; import org.matsim.contrib.drt.extension.operations.shifts.schedule.OperationalStop; -import org.matsim.contrib.drt.optimizer.VehicleDataEntryFactoryImpl; +import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftTask; +import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShift; import org.matsim.contrib.drt.optimizer.VehicleEntry; -import org.matsim.contrib.drt.run.DrtConfigGroup; import org.matsim.contrib.dvrp.fleet.DvrpVehicle; -import org.matsim.core.config.Config; - -import jakarta.inject.Inject; /** * @author nkuehnel / MOIA @@ -19,10 +14,13 @@ public class ShiftVehicleDataEntryFactory implements VehicleEntry.EntryFactory { private final VehicleEntry.EntryFactory entryFactory; + private final boolean considerUpcomingShifts; + - public ShiftVehicleDataEntryFactory(VehicleEntry.EntryFactory delegate) { + public ShiftVehicleDataEntryFactory(VehicleEntry.EntryFactory delegate, boolean considerUpcomingShifts) { entryFactory = delegate; - } + this.considerUpcomingShifts = considerUpcomingShifts; + } @Override public VehicleEntry create(DvrpVehicle vehicle, double currentTime) { @@ -36,12 +34,21 @@ public VehicleEntry create(DvrpVehicle vehicle, double currentTime) { public boolean isEligibleForRequestInsertion(DvrpVehicle dvrpVehicle, double currentTime) { final DrtShift currentShift = ((ShiftDvrpVehicle) dvrpVehicle).getShifts().peek(); - if(currentShift == null || - currentTime > currentShift.getEndTime() || - !currentShift.isStarted() || - currentShift.isEnded()) { - return false; + + // no shift assigned + if (currentShift == null) { + return false; + } + + if(currentShift.isStarted()) { + if(currentTime > currentShift.getEndTime()) { + return false; + } + // do not insert into operational stops such as breaks + return !(dvrpVehicle.getSchedule().getCurrentTask() instanceof OperationalStop); + } else { + // upcoming shift assigned but not started yet. Only consider vehicles already waiting for shift start + return considerUpcomingShifts && dvrpVehicle.getSchedule().getCurrentTask() instanceof WaitForShiftTask; } - return !(dvrpVehicle.getSchedule().getCurrentTask() instanceof OperationalStop); } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/insertion/ShiftInsertionCostCalculator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/insertion/ShiftInsertionCostCalculator.java index db74fcd4d85..d6b3c978146 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/insertion/ShiftInsertionCostCalculator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/insertion/ShiftInsertionCostCalculator.java @@ -1,7 +1,9 @@ package org.matsim.contrib.drt.extension.operations.shifts.optimizer.insertion; +import org.matsim.contrib.drt.extension.operations.shifts.fleet.ShiftDvrpVehicle; import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftBreakTask; import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftChangeOverTask; +import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShift; import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftBreak; import org.matsim.contrib.drt.optimizer.VehicleEntry; import org.matsim.contrib.drt.optimizer.Waypoint; @@ -32,19 +34,24 @@ public ShiftInsertionCostCalculator(MobsimTimer timer, @Override public double calculate(DrtRequest drtRequest, Insertion insertion, DetourTimeInfo detourTimeInfo) { - if (!checkShiftTimeConstraintsForScheduledRequests(insertion, - detourTimeInfo.pickupDetourInfo.pickupTimeLoss, detourTimeInfo.getTotalTimeLoss())) { + if (!checkShiftTimeConstraintsForScheduledRequests(insertion, detourTimeInfo)) { return INFEASIBLE_SOLUTION_COST; } return delegate.calculate(drtRequest, insertion, detourTimeInfo); } - boolean checkShiftTimeConstraintsForScheduledRequests(Insertion insertion, double pickupDetourTimeLoss, - double totalTimeLoss) { + boolean checkShiftTimeConstraintsForScheduledRequests(Insertion insertion, DetourTimeInfo detourTimeInfo) { VehicleEntry vEntry = insertion.vehicleEntry; final int pickupIdx = insertion.pickup.index; final int dropoffIdx = insertion.dropoff.index; + DrtShift currentShift = ((ShiftDvrpVehicle) vEntry.vehicle).getShifts().peek(); + double shiftEndTime = currentShift.getEndTime(); + if(shiftEndTime < detourTimeInfo.dropoffDetourInfo.arrivalTime) { + // fast fail which also captures requests that are prebooked for times outside of the shift. + return false; + } + for (int s = 0; s < pickupIdx; s++) { Waypoint.Stop stop = vEntry.stops.get(s); if (stop.task instanceof ShiftChangeOverTask) { @@ -53,6 +60,8 @@ boolean checkShiftTimeConstraintsForScheduledRequests(Insertion insertion, doubl } } + double pickupDetourTimeLoss = detourTimeInfo.pickupDetourInfo.pickupTimeLoss; + // each existing stop has 2 time constraints: latestArrivalTime and latestDepartureTime (see: Waypoint.Stop) // we are looking only at the time constraints of the scheduled requests (the new request is checked separately) @@ -73,6 +82,8 @@ boolean checkShiftTimeConstraintsForScheduledRequests(Insertion insertion, doubl } } + double totalTimeLoss = detourTimeInfo.getTotalTimeLoss(); + // all stops after the new (potential) dropoff are delayed by totalTimeLoss // check if this delay satisfies the time constraints at these stops for (int s = dropoffIdx; s < vEntry.stops.size(); s++) { @@ -109,6 +120,31 @@ boolean checkShiftTimeConstraintsForScheduledRequests(Insertion insertion, doubl return false; } } + + + // avoid shrinking break corridor too much (rather coarse for now) + if(currentShift.getBreak().isPresent()) { + DrtShiftBreak drtShiftBreak = currentShift.getBreak().get(); + if(!drtShiftBreak.isScheduled()) { + + + if(detourTimeInfo.dropoffDetourInfo.arrivalTime < drtShiftBreak.getEarliestBreakStartTime()) { + // insertion finished before break corridor + //ok + } else if(detourTimeInfo.pickupDetourInfo.departureTime > drtShiftBreak.getLatestBreakEndTime()) { + // insertion start after break corridor + //ok + } else { + double remainingTime = drtShiftBreak.getLatestBreakEndTime() - detourTimeInfo.dropoffDetourInfo.arrivalTime; + if (remainingTime < drtShiftBreak.getDuration()) { + // no meaningful break possible after insertion + // (there could still be enough time before a prebooking though) + return false; + } + } + } + } + return true; //all time constraints of all stops are satisfied } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeModule.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeModule.java index 91e324456d1..8b52ca88951 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeModule.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeModule.java @@ -6,15 +6,15 @@ import com.google.inject.Singleton; import com.google.inject.TypeLiteral; import org.matsim.api.core.v01.population.Population; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; -import org.matsim.contrib.drt.extension.operations.DrtWithOperationsConfigGroup; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilitiesSpecification; import org.matsim.contrib.drt.extension.operations.shifts.analysis.*; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; import org.matsim.contrib.drt.extension.operations.shifts.io.DrtShiftsReader; import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftBreakTaskImpl; import org.matsim.contrib.drt.extension.operations.shifts.schedule.ShiftChangeoverTaskImpl; -import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftStayTask; +import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftTask; import org.matsim.contrib.drt.extension.operations.shifts.scheduler.ShiftTaskScheduler; import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftsSpecification; import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftsSpecificationImpl; @@ -52,12 +52,12 @@ public class ShiftDrtModeModule extends AbstractDvrpModeModule { public ShiftDrtModeModule(DrtConfigGroup drtCfg) { super(drtCfg.getMode()); this.drtConfigGroup = drtCfg; - this.drtOperationsParams = ((DrtWithOperationsConfigGroup) drtCfg).getDrtOperationsParams(); + this.drtOperationsParams = ((DrtWithExtensionsConfigGroup) drtCfg).getDrtOperationsParams().orElseThrow(); } private static final Comparator taskTypeComparator = Comparator.comparing((Task.TaskType type) -> { //we want the following order on the plot: STAY, RELOCATE, other - if (type.equals(WaitForShiftStayTask.TYPE)) { + if (type.equals(WaitForShiftTask.TYPE)) { return "F"; } else if (type.equals(ShiftChangeoverTaskImpl.TYPE)) { return "E"; @@ -73,7 +73,7 @@ public ShiftDrtModeModule(DrtConfigGroup drtCfg) { }).reversed(); private static final Map taskTypePaints = ImmutableMap.of( - WaitForShiftStayTask.TYPE, Color.WHITE, + WaitForShiftTask.TYPE, Color.WHITE, ShiftChangeoverTaskImpl.TYPE, Color.GRAY, ShiftBreakTaskImpl.TYPE, Color.DARK_GRAY, DrtStayTask.TYPE, Color.LIGHT_GRAY); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeOptimizerQSimModule.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeOptimizerQSimModule.java index a10c6e409e3..a65de06b2c4 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeOptimizerQSimModule.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/run/ShiftDrtModeOptimizerQSimModule.java @@ -4,8 +4,8 @@ import com.google.inject.Singleton; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Network; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; -import org.matsim.contrib.drt.extension.operations.DrtWithOperationsConfigGroup; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilities; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilityFinder; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; @@ -70,7 +70,7 @@ public class ShiftDrtModeOptimizerQSimModule extends AbstractDvrpModeQSimModule public ShiftDrtModeOptimizerQSimModule(DrtConfigGroup drtCfg) { super(drtCfg.getMode()); this.drtCfg = drtCfg; - this.drtOperationsParams = ((DrtWithOperationsConfigGroup) drtCfg).getDrtOperationsParams(); + this.drtOperationsParams = ((DrtWithExtensionsConfigGroup) drtCfg).getDrtOperationsParams().orElseThrow(); } @Override @@ -124,7 +124,9 @@ shiftsParams, new DefaultShiftStartLogic(), new DefaultAssignShiftToVehicleLogic new DefaultInsertionCostCalculator(getter.getModal(CostCalculationStrategy.class), drtCfg.addOrGetDrtOptimizationConstraintsParams().addOrGetDefaultDrtOptimizationConstraintsSet())))); - bindModal(VehicleEntry.EntryFactory.class).toInstance(new ShiftVehicleDataEntryFactory(new VehicleDataEntryFactoryImpl())); + bindModal(VehicleEntry.EntryFactory.class).toInstance( + new ShiftVehicleDataEntryFactory(new VehicleDataEntryFactoryImpl(), shiftsParams.considerUpcomingShiftsForInsertion) + ); bindModal(DrtTaskFactory.class).toProvider(modalProvider(getter -> new ShiftDrtTaskFactoryImpl(new DrtTaskFactoryImpl(), getter.getModal(OperationFacilities.class)))); bindModal(ShiftDrtTaskFactory.class).toProvider(modalProvider(getter -> ((ShiftDrtTaskFactory) getter.getModal(DrtTaskFactory.class)))); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtActionCreator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtActionCreator.java index 0f65e1208f0..5deb47eba47 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtActionCreator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtActionCreator.java @@ -38,7 +38,7 @@ public DynAction createAction(DynAgent dynAgent, DvrpVehicle vehicle, double now DrtStopTask t = (DrtStopTask) task; return new DrtStopActivity(passengerHandler, dynAgent, t::getEndTime, t.getDropoffRequests(), t.getPickupRequests(), DRT_SHIFT_CHANGEOVER_NAME); - } else if (task instanceof WaitForShiftStayTask) { + } else if (task instanceof WaitForShiftTask) { return new IdleDynActivity(DRT_SHIFT_WAIT_FOR_SHIFT_NAME, task::getEndTime); } else { return dynActionCreator.createAction(dynAgent, vehicle, now); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtStayTaskEndTimeCalculator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtStayTaskEndTimeCalculator.java index ddeaf4ffb9e..546f0843673 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtStayTaskEndTimeCalculator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtStayTaskEndTimeCalculator.java @@ -1,8 +1,8 @@ package org.matsim.contrib.drt.extension.operations.shifts.schedule; +import com.google.common.base.Verify; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShiftBreak; import org.matsim.contrib.drt.schedule.DrtStayTaskEndTimeCalculator; @@ -31,17 +31,21 @@ public ShiftDrtStayTaskEndTimeCalculator(ShiftsParams drtShiftParams, DrtStayTas @Override public double calcNewEndTime(DvrpVehicle vehicle, StayTask task, double newBeginTime) { - if(task instanceof ShiftBreakTask) { + if (task instanceof WaitForShiftTask) { + Verify.verify(newBeginTime <= task.getEndTime(), "WaitForShiftTasks should not be delayed"); + return task.getEndTime(); + } + if (task instanceof ShiftBreakTask) { final DrtShiftBreak shiftBreak = ((ShiftBreakTask) task).getShiftBreak(); return newBeginTime + shiftBreak.getDuration(); - } else if(task instanceof ShiftChangeOverTask) { + } else if (task instanceof ShiftChangeOverTask) { return Math.max(newBeginTime, ((ShiftChangeOverTask) task).getShift().getEndTime()) + drtShiftParams.changeoverDuration; - } else if(DrtTaskBaseType.getBaseTypeOrElseThrow(task).equals(DrtTaskBaseType.STAY)) { + } else if (DrtTaskBaseType.getBaseTypeOrElseThrow(task).equals(DrtTaskBaseType.STAY)) { final List tasks = vehicle.getSchedule().getTasks(); final int taskIdx = tasks.indexOf(task); - if(tasks.size() > taskIdx+1) { - final Task nextTask = tasks.get(taskIdx +1); - if(nextTask instanceof ShiftChangeOverTask) { + if (tasks.size() > taskIdx + 1) { + final Task nextTask = tasks.get(taskIdx + 1); + if (nextTask instanceof ShiftChangeOverTask) { return Math.max(newBeginTime, ((ShiftChangeOverTask) nextTask).getShift().getEndTime()); } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtTaskFactory.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtTaskFactory.java index 9de610a8b84..eaaf5c371ef 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtTaskFactory.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtTaskFactory.java @@ -18,6 +18,6 @@ ShiftBreakTask createShiftBreakTask(DvrpVehicle vehicle, double beginTime, doubl ShiftChangeOverTask createShiftChangeoverTask(DvrpVehicle vehicle, double beginTime, double endTime, Link link, DrtShift shift, OperationFacility facility); - WaitForShiftStayTask createWaitForShiftStayTask(DvrpVehicle vehicle, double beginTime, double endTime, Link link, - OperationFacility facility); + WaitForShiftTask createWaitForShiftStayTask(DvrpVehicle vehicle, double beginTime, double endTime, Link link, + OperationFacility facility); } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtTaskFactoryImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtTaskFactoryImpl.java index 57460d2bee6..e59d40dbac6 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtTaskFactoryImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/ShiftDrtTaskFactoryImpl.java @@ -58,9 +58,9 @@ public ShiftChangeOverTask createShiftChangeoverTask(DvrpVehicle vehicle, double } @Override - public WaitForShiftStayTask createWaitForShiftStayTask(DvrpVehicle vehicle, double beginTime, double endTime, - Link link, OperationFacility facility) { - return new WaitForShiftStayTask(beginTime, endTime, link, facility); + public WaitForShiftTask createWaitForShiftStayTask(DvrpVehicle vehicle, double beginTime, double endTime, + Link link, OperationFacility facility) { + return new WaitForShiftTask(beginTime, endTime, link, facility); } public DefaultStayTask createInitialTask(DvrpVehicle vehicle, double beginTime, double endTime, Link link) { @@ -71,7 +71,7 @@ public DefaultStayTask createInitialTask(DvrpVehicle vehicle, double beginTime, } catch (Throwable e) { throw new RuntimeException(e); } - WaitForShiftStayTask waitForShiftStayTask = createWaitForShiftStayTask(vehicle, vehicle.getServiceBeginTime(), vehicle.getServiceEndTime(), + WaitForShiftTask waitForShiftStayTask = createWaitForShiftStayTask(vehicle, vehicle.getServiceBeginTime(), vehicle.getServiceEndTime(), vehicle.getStartLink(), operationFacility); boolean success = operationFacility.register(vehicle.getId()); if (!success) { diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/WaitForShiftStayTask.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/WaitForShiftStayTask.java deleted file mode 100644 index 25556e16db7..00000000000 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/WaitForShiftStayTask.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.matsim.contrib.drt.extension.operations.shifts.schedule; - -import org.matsim.api.core.v01.network.Link; -import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacility; -import org.matsim.contrib.drt.schedule.DrtTaskType; -import org.matsim.contrib.dvrp.schedule.DefaultStayTask; - -import static org.matsim.contrib.drt.schedule.DrtTaskBaseType.STAY; - -/** - * @author nkuehnel / MOIA - */ -public class WaitForShiftStayTask extends DefaultStayTask implements OperationalStop { - - public static final DrtTaskType TYPE = new DrtTaskType("WAIT_FOR_SHIFT", STAY); - - private final OperationFacility facility; - - public WaitForShiftStayTask(double beginTime, double endTime, Link link, OperationFacility facility) { - super(TYPE, beginTime, endTime, link); - this.facility = facility; - } - - @Override - public OperationFacility getFacility() { - return facility; - } - -} diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/WaitForShiftTask.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/WaitForShiftTask.java new file mode 100644 index 00000000000..dcb0e9a1927 --- /dev/null +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/schedule/WaitForShiftTask.java @@ -0,0 +1,65 @@ +package org.matsim.contrib.drt.extension.operations.shifts.schedule; + +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.network.Link; +import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacility; +import org.matsim.contrib.drt.passenger.AcceptedDrtRequest; +import org.matsim.contrib.drt.schedule.DrtStopTask; +import org.matsim.contrib.drt.schedule.DrtTaskType; +import org.matsim.contrib.dvrp.optimizer.Request; +import org.matsim.contrib.dvrp.schedule.DefaultStayTask; + +import java.util.Collections; +import java.util.Map; + +import static org.matsim.contrib.drt.schedule.DrtTaskBaseType.STOP; + +/** + * @author nkuehnel / MOIA + */ +public class WaitForShiftTask extends DefaultStayTask implements DrtStopTask, OperationalStop { + + public static final DrtTaskType TYPE = new DrtTaskType("WAIT_FOR_SHIFT", STOP); + + private final OperationFacility facility; + + public WaitForShiftTask(double beginTime, double endTime, Link link, OperationFacility facility) { + super(TYPE, beginTime, endTime, link); + this.facility = facility; + } + + @Override + public OperationFacility getFacility() { + return facility; + } + + @Override + public Map, AcceptedDrtRequest> getDropoffRequests() { + return Collections.emptyMap(); + } + + @Override + public Map, AcceptedDrtRequest> getPickupRequests() { + return Collections.emptyMap(); + } + + @Override + public void addDropoffRequest(AcceptedDrtRequest request) { + throw new RuntimeException("Not supported"); + } + + @Override + public void addPickupRequest(AcceptedDrtRequest request) { + throw new RuntimeException("Not supported"); + } + + @Override + public void removePickupRequest(Id requestId) { + throw new RuntimeException("Not supported"); + } + + @Override + public void removeDropoffRequest(Id requestId) { + throw new RuntimeException("Not supported"); + } +} diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftDrtScheduleInquiry.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftDrtScheduleInquiry.java index 7fb582caea6..d598bb29b13 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftDrtScheduleInquiry.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftDrtScheduleInquiry.java @@ -2,13 +2,13 @@ import com.google.inject.Inject; import org.matsim.contrib.drt.extension.operations.shifts.fleet.ShiftDvrpVehicle; +import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftTask; import org.matsim.contrib.drt.extension.operations.shifts.shift.DrtShift; import org.matsim.contrib.drt.scheduler.DrtScheduleInquiry; import org.matsim.contrib.dvrp.fleet.DvrpVehicle; import org.matsim.contrib.dvrp.schedule.Schedule; import org.matsim.contrib.dvrp.schedule.ScheduleInquiry; import org.matsim.contrib.dvrp.schedule.Task; -import org.matsim.contrib.drt.extension.operations.shifts.schedule.WaitForShiftStayTask; import org.matsim.core.mobsim.framework.MobsimTimer; import static org.matsim.contrib.drt.schedule.DrtTaskBaseType.STAY; @@ -42,7 +42,7 @@ public boolean isIdle(DvrpVehicle vehicle) { } } Task currentTask = schedule.getCurrentTask(); - if(currentTask instanceof WaitForShiftStayTask) { + if(currentTask instanceof WaitForShiftTask) { return false; } return currentTask.getTaskIdx() == schedule.getTaskCount() - 1 diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskScheduler.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskScheduler.java index 2b9b3415d5c..dc8187c0fce 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskScheduler.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskScheduler.java @@ -23,4 +23,8 @@ public interface ShiftTaskScheduler { boolean updateShiftChange(ShiftDvrpVehicle vehicle, Link link, DrtShift shift, LinkTimePair start, OperationFacility facility, Task lastTask); + + void planAssignedShift(ShiftDvrpVehicle vehicle, double timeStep, DrtShift shift); + + void cancelAssignedShift(ShiftDvrpVehicle vehicle, double timeStep, DrtShift shift); } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskSchedulerImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskSchedulerImpl.java index d6d272371e9..94b5c3d0fed 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskSchedulerImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/scheduler/ShiftTaskSchedulerImpl.java @@ -18,10 +18,7 @@ import org.matsim.contrib.dvrp.fleet.Fleet; import org.matsim.contrib.dvrp.path.VrpPathWithTravelData; import org.matsim.contrib.dvrp.path.VrpPaths; -import org.matsim.contrib.dvrp.schedule.DriveTask; -import org.matsim.contrib.dvrp.schedule.Schedule; -import org.matsim.contrib.dvrp.schedule.StayTask; -import org.matsim.contrib.dvrp.schedule.Task; +import org.matsim.contrib.dvrp.schedule.*; import org.matsim.contrib.dvrp.tracker.OnlineDriveTaskTracker; import org.matsim.contrib.dvrp.util.LinkTimePair; import org.matsim.core.mobsim.framework.MobsimTimer; @@ -95,7 +92,7 @@ public void relocateForBreak(ShiftDvrpVehicle vehicle, OperationFacility breakFa double startTime = path.getArrivalTime(); double endTime = startTime + shift.getBreak().orElseThrow().getDuration(); - double latestDetourArrival = path.getDepartureTime() + path.getTravelTime() + 1.5; + double latestDetourArrival = path.getDepartureTime() + path.getTravelTime() * 1.5; relocateForBreakImpl(vehicle, startTime, endTime, latestDetourArrival, toLink, shift, breakFacility); } else { @@ -156,10 +153,10 @@ private void relocateForBreakImpl(ShiftDvrpVehicle vehicle, double startTime, do // append SHIFT_BREAK task DrtShiftBreak shiftBreak = shift.getBreak().orElseThrow(); - ShiftBreakTask dropoffStopTask = taskFactory.createShiftBreakTask(vehicle, startTime, + ShiftBreakTask shiftBreakTask = taskFactory.createShiftBreakTask(vehicle, startTime, endTime, link, shiftBreak, breakFacility); - schedule.addTask(dropoffStopTask); + schedule.addTask(shiftBreakTask); schedule.addTask(taskFactory.createStayTask(vehicle, endTime, shift.getEndTime(), link)); @@ -266,10 +263,13 @@ private void appendShiftChange(DvrpVehicle vehicle, DrtShift shift, OperationFac public void startShift(ShiftDvrpVehicle vehicle, double now, DrtShift shift) { Schedule schedule = vehicle.getSchedule(); StayTask stayTask = (StayTask) schedule.getCurrentTask(); - if (stayTask instanceof WaitForShiftStayTask) { - ((WaitForShiftStayTask) stayTask).getFacility().deregisterVehicle(vehicle.getId()); + if (stayTask instanceof WaitForShiftTask) { + ((WaitForShiftTask) stayTask).getFacility().deregisterVehicle(vehicle.getId()); stayTask.setEndTime(now); - schedule.addTask(taskFactory.createStayTask(vehicle, now, shift.getEndTime(), stayTask.getLink())); + if(Schedules.getLastTask(schedule).equals(stayTask)) { + //nothing planned yet. + schedule.addTask(taskFactory.createStayTask(vehicle, now, shift.getEndTime(), stayTask.getLink())); + } } else { throw new IllegalStateException("Vehicle cannot start shift during task:" + stayTask.getTaskType().name()); } @@ -291,6 +291,24 @@ public boolean updateShiftChange(ShiftDvrpVehicle vehicle, Link link, DrtShift s return false; } + @Override + public void planAssignedShift(ShiftDvrpVehicle vehicle, double timeStep, DrtShift shift) { + Schedule schedule = vehicle.getSchedule(); + StayTask stayTask = (StayTask) schedule.getCurrentTask(); + if (stayTask instanceof WaitForShiftTask) { + stayTask.setEndTime(Math.max(timeStep, shift.getStartTime())); + } + } + + @Override + public void cancelAssignedShift(ShiftDvrpVehicle vehicle, double timeStep, DrtShift shift) { + Schedule schedule = vehicle.getSchedule(); + StayTask stayTask = (StayTask) schedule.getCurrentTask(); + if (stayTask instanceof WaitForShiftTask) { + stayTask.setEndTime(vehicle.getServiceEndTime()); + } + } + private void updateShiftChangeImpl(DvrpVehicle vehicle, VrpPathWithTravelData vrpPath, DrtShift shift, OperationFacility facility, Task lastTask) { Schedule schedule = vehicle.getSchedule(); diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/shift/DefaultShiftBreakImpl.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/shift/DefaultShiftBreakImpl.java index 07b094f3dc0..10f36a1d387 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/shift/DefaultShiftBreakImpl.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/shift/DefaultShiftBreakImpl.java @@ -54,9 +54,4 @@ public boolean isScheduled() { public double getScheduledLatestArrival() { return latestArrivalTime; } - - @Override - public void reset() { - this.latestArrivalTime = UNSCHEDULED_ARRIVAL_TIME; - } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/shift/DrtShiftBreak.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/shift/DrtShiftBreak.java index 2009dcd02f6..86e5500401a 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/shift/DrtShiftBreak.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/shift/DrtShiftBreak.java @@ -16,6 +16,4 @@ public interface DrtShiftBreak { boolean isScheduled(); double getScheduledLatestArrival(); - - void reset(); } diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java index 3ae153f665a..120cff4f5a3 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/fiss/RunFissDrtScenarioIT.java @@ -7,9 +7,9 @@ import org.matsim.api.core.v01.events.handler.LinkLeaveEventHandler; import org.matsim.contrib.common.zones.systems.grid.square.SquareGridZoneSystemParams; import org.matsim.contrib.drt.analysis.zonal.DrtZoneSystemParams; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.operations.DrtOperationsControlerCreator; import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; -import org.matsim.contrib.drt.extension.operations.DrtWithOperationsConfigGroup; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilitiesParams; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; import org.matsim.contrib.drt.optimizer.constraints.DefaultDrtOptimizationConstraintsSet; @@ -42,7 +42,7 @@ public class RunFissDrtScenarioIT { @Test void test() { - MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithOperationsConfigGroup::new); + MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithExtensionsConfigGroup::new); String fleetFile = "holzkirchenFleet.xml"; String plansFile = "holzkirchenPlans_car_drt.xml.gz"; @@ -50,7 +50,7 @@ void test() { String opFacilitiesFile = "holzkirchenOperationFacilities.xml"; String shiftsFile = "holzkirchenShifts.xml"; - DrtWithOperationsConfigGroup drtWithShiftsConfigGroup = (DrtWithOperationsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); + DrtWithExtensionsConfigGroup drtWithShiftsConfigGroup = (DrtWithExtensionsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); DrtConfigGroup drtConfigGroup = drtWithShiftsConfigGroup; drtConfigGroup.mode = TransportMode.drt; @@ -135,7 +135,7 @@ void test() { stratSets.setStrategyName("ChangeExpBeta"); config.replanning().addStrategySettings(stratSets); - config.controller().setLastIteration(2); + config.controller().setLastIteration(1); config.controller().setWriteEventsInterval(1); config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); @@ -184,7 +184,7 @@ public void install() { } run.run(); - Assertions.assertEquals(23817, linkCounter.getLinkLeaveCount()); + Assertions.assertEquals(20000, linkCounter.getLinkLeaveCount(), 2000); } static class LinkCounter implements LinkLeaveEventHandler { diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/eshifts/run/RunEShiftDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/eshifts/run/RunEShiftDrtScenarioIT.java index 3b5d9830c29..a137d932fe5 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/eshifts/run/RunEShiftDrtScenarioIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/eshifts/run/RunEShiftDrtScenarioIT.java @@ -4,8 +4,9 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.contrib.common.zones.systems.grid.square.SquareGridZoneSystemParams; import org.matsim.contrib.drt.analysis.zonal.DrtZoneSystemParams; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; -import org.matsim.contrib.drt.extension.operations.DrtWithOperationsConfigGroup; + import org.matsim.contrib.drt.extension.operations.EDrtOperationsControlerCreator; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilitiesParams; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; @@ -43,7 +44,7 @@ public class RunEShiftDrtScenarioIT { @Test void test() { - MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithOperationsConfigGroup::new); + MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithExtensionsConfigGroup::new); String fleetFile = "holzkirchenFleet.xml"; String plansFile = "holzkirchenPlans.xml.gz"; @@ -53,7 +54,7 @@ void test() { String chargersFile = "holzkirchenChargers.xml"; String evsFile = "holzkirchenElectricFleet.xml"; - DrtWithOperationsConfigGroup drtWithShiftsConfigGroup = (DrtWithOperationsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); + DrtWithExtensionsConfigGroup drtWithShiftsConfigGroup = (DrtWithExtensionsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); DrtConfigGroup drtConfigGroup = drtWithShiftsConfigGroup; drtConfigGroup.mode = TransportMode.drt; diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunMultiHubShiftDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunMultiHubShiftDrtScenarioIT.java index 6f08a46d3c7..b481b20898f 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunMultiHubShiftDrtScenarioIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunMultiHubShiftDrtScenarioIT.java @@ -4,8 +4,8 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.contrib.common.zones.systems.grid.square.SquareGridZoneSystemParams; import org.matsim.contrib.drt.analysis.zonal.DrtZoneSystemParams; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.operations.DrtOperationsControlerCreator; -import org.matsim.contrib.drt.extension.operations.DrtWithOperationsConfigGroup; import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilitiesParams; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; @@ -34,7 +34,7 @@ public class RunMultiHubShiftDrtScenarioIT { @Test void test() { - MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithOperationsConfigGroup::new); + MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithExtensionsConfigGroup::new); String fleetFile = "holzkirchenMultiHubFleet.xml"; String plansFile = "holzkirchenPlans.xml.gz"; @@ -42,7 +42,7 @@ void test() { String opFacilitiesFile = "holzkirchenMultiHubOperationFacilities.xml"; String shiftsFile = "holzkirchenMultiHubShifts.xml"; - DrtWithOperationsConfigGroup drtWithShiftsConfigGroup = (DrtWithOperationsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); + DrtWithExtensionsConfigGroup drtWithShiftsConfigGroup = (DrtWithExtensionsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); DrtConfigGroup drtConfigGroup = drtWithShiftsConfigGroup; drtConfigGroup.mode = TransportMode.drt; diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunPrebookingShiftDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunPrebookingShiftDrtScenarioIT.java new file mode 100644 index 00000000000..5babef611b3 --- /dev/null +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunPrebookingShiftDrtScenarioIT.java @@ -0,0 +1,329 @@ +package org.matsim.contrib.drt.extension.operations.shifts.run; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.matsim.api.core.v01.Coord; +import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.Scenario; +import org.matsim.api.core.v01.TransportMode; +import org.matsim.api.core.v01.network.Network; +import org.matsim.api.core.v01.network.Node; +import org.matsim.api.core.v01.population.*; +import org.matsim.contrib.common.zones.systems.grid.square.SquareGridZoneSystemParams; +import org.matsim.contrib.drt.analysis.zonal.DrtZoneSystemParams; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; +import org.matsim.contrib.drt.extension.operations.DrtOperationsControlerCreator; +import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; +import org.matsim.contrib.drt.extension.operations.operationFacilities.*; +import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; +import org.matsim.contrib.drt.extension.operations.shifts.shift.*; +import org.matsim.contrib.drt.optimizer.constraints.DefaultDrtOptimizationConstraintsSet; +import org.matsim.contrib.drt.optimizer.insertion.extensive.ExtensiveInsertionSearchParams; +import org.matsim.contrib.drt.optimizer.rebalancing.RebalancingParams; +import org.matsim.contrib.drt.optimizer.rebalancing.mincostflow.MinCostFlowRebalancingStrategyParams; +import org.matsim.contrib.drt.prebooking.PrebookingModeQSimModule; +import org.matsim.contrib.drt.prebooking.PrebookingParams; +import org.matsim.contrib.drt.prebooking.logic.AttributeBasedPrebookingLogic; +import org.matsim.contrib.drt.run.DrtConfigGroup; +import org.matsim.contrib.drt.run.DrtControlerCreator; +import org.matsim.contrib.drt.run.MultiModeDrtConfigGroup; +import org.matsim.contrib.dvrp.fleet.DvrpVehicle; +import org.matsim.contrib.dvrp.fleet.FleetSpecification; +import org.matsim.contrib.dvrp.fleet.FleetSpecificationImpl; +import org.matsim.contrib.dvrp.fleet.ImmutableDvrpVehicleSpecification; +import org.matsim.contrib.dvrp.passenger.PassengerRequestRejectedEventHandler; +import org.matsim.contrib.dvrp.run.AbstractDvrpModeModule; +import org.matsim.contrib.dvrp.run.DvrpConfigGroup; +import org.matsim.contrib.zone.skims.DvrpTravelTimeMatrixParams; +import org.matsim.core.config.Config; +import org.matsim.core.config.ConfigGroup; +import org.matsim.core.config.ConfigUtils; +import org.matsim.core.config.groups.QSimConfigGroup; +import org.matsim.core.config.groups.ReplanningConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup; +import org.matsim.core.controler.AbstractModule; +import org.matsim.core.controler.Controler; +import org.matsim.core.controler.OutputDirectoryHierarchy; +import org.matsim.core.network.NetworkUtils; +import org.matsim.core.population.PopulationUtils; +import org.matsim.core.utils.geometry.CoordUtils; + +import java.util.HashSet; +import java.util.Set; + + + +/** + * @author nkuehnel / MOIA + */ +public class RunPrebookingShiftDrtScenarioIT { + + + @Test + void test() { + + MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithExtensionsConfigGroup::new); + + DrtWithExtensionsConfigGroup drtWithShiftsConfigGroup = (DrtWithExtensionsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); + drtWithShiftsConfigGroup.mode = TransportMode.drt; + DefaultDrtOptimizationConstraintsSet defaultConstraintsSet = + (DefaultDrtOptimizationConstraintsSet) drtWithShiftsConfigGroup.addOrGetDrtOptimizationConstraintsParams() + .addOrGetDefaultDrtOptimizationConstraintsSet(); + drtWithShiftsConfigGroup.stopDuration = 30.; + defaultConstraintsSet.maxTravelTimeAlpha = 1.5; + defaultConstraintsSet.maxTravelTimeBeta = 10. * 60.; + defaultConstraintsSet.maxWaitTime = 600.; + defaultConstraintsSet.rejectRequestIfMaxWaitOrTravelTimeViolated = true; + defaultConstraintsSet.maxWalkDistance = 1000.; + drtWithShiftsConfigGroup.operationalScheme = DrtConfigGroup.OperationalScheme.door2door; + + drtWithShiftsConfigGroup.addParameterSet(new ExtensiveInsertionSearchParams()); + + ConfigGroup rebalancing = drtWithShiftsConfigGroup.createParameterSet("rebalancing"); + drtWithShiftsConfigGroup.addParameterSet(rebalancing); + ((RebalancingParams) rebalancing).interval = 600; + + MinCostFlowRebalancingStrategyParams strategyParams = new MinCostFlowRebalancingStrategyParams(); + strategyParams.targetAlpha = 0.3; + strategyParams.targetBeta = 0.3; + + drtWithShiftsConfigGroup.getRebalancingParams().get().addParameterSet(strategyParams); + + SquareGridZoneSystemParams zoneParams = new SquareGridZoneSystemParams(); + zoneParams.cellSize = 500.; + + DrtZoneSystemParams drtZoneSystemParams = new DrtZoneSystemParams(); + drtZoneSystemParams.addParameterSet(zoneParams); + drtWithShiftsConfigGroup.addParameterSet(drtZoneSystemParams); + + DvrpConfigGroup dvrpConfigGroup = new DvrpConfigGroup(); + DvrpTravelTimeMatrixParams matrixParams = dvrpConfigGroup.getTravelTimeMatrixParams(); + matrixParams.addParameterSet(zoneParams); + + multiModeDrtConfigGroup.addParameterSet(drtWithShiftsConfigGroup); + + final Config config = ConfigUtils.createConfig(multiModeDrtConfigGroup, + dvrpConfigGroup); + + Set modes = new HashSet<>(); + modes.add("drt"); + config.travelTimeCalculator().setAnalyzedModes(modes); + + ScoringConfigGroup.ModeParams scoreParams = new ScoringConfigGroup.ModeParams("drt"); + config.scoring().addModeParams(scoreParams); + ScoringConfigGroup.ModeParams scoreParams2 = new ScoringConfigGroup.ModeParams("walk"); + config.scoring().addModeParams(scoreParams2); + + final ScoringConfigGroup.ActivityParams start = new ScoringConfigGroup.ActivityParams("start"); + start.setScoringThisActivityAtAll(false); + final ScoringConfigGroup.ActivityParams end = new ScoringConfigGroup.ActivityParams("end"); + end.setScoringThisActivityAtAll(false); + + config.scoring().addActivityParams(start); + config.scoring().addActivityParams(end); + + config.qsim().setSimStarttimeInterpretation(QSimConfigGroup.StarttimeInterpretation.onlyUseStarttime); + config.qsim().setSimEndtimeInterpretation(QSimConfigGroup.EndtimeInterpretation.minOfEndtimeAndMobsimFinished); + + final ReplanningConfigGroup.StrategySettings stratSets = new ReplanningConfigGroup.StrategySettings(); + stratSets.setWeight(1); + stratSets.setStrategyName("ChangeExpBeta"); + config.replanning().addStrategySettings(stratSets); + + config.controller().setLastIteration(0); + config.controller().setWriteEventsInterval(1); + + config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); + config.controller().setOutputDirectory("test/output/prebooking_shifts"); + + DrtOperationsParams operationsParams = (DrtOperationsParams) drtWithShiftsConfigGroup.createParameterSet(DrtOperationsParams.SET_NAME); + ShiftsParams shiftsParams = (ShiftsParams) operationsParams.createParameterSet(ShiftsParams.SET_NAME); + OperationFacilitiesParams operationFacilitiesParams = (OperationFacilitiesParams) operationsParams.createParameterSet(OperationFacilitiesParams.SET_NAME); + operationsParams.addParameterSet(shiftsParams); + operationsParams.addParameterSet(operationFacilitiesParams); + + shiftsParams.considerUpcomingShiftsForInsertion = true; + shiftsParams.shiftEndLookAhead = 900.; + drtWithShiftsConfigGroup.addParameterSet(operationsParams); + + PrebookingParams prebookingParams = new PrebookingParams(); + prebookingParams.maximumPassengerDelay = 600; + prebookingParams.unschedulingMode = PrebookingParams.UnschedulingMode.Routing; + prebookingParams.scheduleWaitBeforeDrive = true; + drtWithShiftsConfigGroup.addParameterSet(prebookingParams); + + Scenario scenario = DrtControlerCreator.createScenarioWithDrtRouteFactory(config); + prepareNetwork(scenario); + preparePopulation(scenario); + + final Controler run = DrtOperationsControlerCreator.createControler(config, scenario, false); + prepareOperations(run, drtWithShiftsConfigGroup); + + run.addOverridingQSimModule(new PrebookingModeQSimModule(drtWithShiftsConfigGroup.getMode(), + prebookingParams)); + AttributeBasedPrebookingLogic.install(run, drtWithShiftsConfigGroup); + + Set> rejectedPersons = new HashSet<>(); + run.addOverridingModule(new AbstractModule() { + @Override + public void install() { + addEventHandlerBinding().toInstance((PassengerRequestRejectedEventHandler) event -> rejectedPersons.addAll(event.getPersonIds())); + } + }); + + run.run(); + + + Assertions.assertFalse(rejectedPersons.contains(Id.createPersonId(1))); + Assertions.assertTrue(rejectedPersons.contains(Id.createPersonId(2))); + Assertions.assertFalse(rejectedPersons.contains(Id.createPersonId(3))); + Assertions.assertTrue(rejectedPersons.contains(Id.createPersonId(4))); + Assertions.assertFalse(rejectedPersons.contains(Id.createPersonId(5))); + Assertions.assertTrue(rejectedPersons.contains(Id.createPersonId(6))); + } + + private void preparePopulation(Scenario scenario) { + Population population = scenario.getPopulation(); + PopulationFactory factory = PopulationUtils.getFactory(); + + //person 1 - prebooking submitted once shift is assigned (but not started) for time when shift should be active - ok + { + Person person = factory.createPerson(Id.createPersonId(1)); + Plan plan = factory.createPlan(); + Activity start = factory.createActivityFromLinkId("start", Id.createLinkId(1)); + start.setEndTime(5000); + start.getAttributes().putAttribute("prebooking:submissionTime" + "drt", 1800.); + start.getAttributes().putAttribute("prebooking:plannedDepartureTime" + "drt", 5000.); + plan.addActivity(start); + plan.addLeg(factory.createLeg("drt")); + plan.addActivity(factory.createActivityFromLinkId("end", Id.createLinkId(2))); + person.addPlan(plan); + population.addPerson(person); + } + + //person 2 - prebooking submitted before shift is assigned for time when shift should be active - rejected + { + Person person = factory.createPerson(Id.createPersonId(2)); + Plan plan = factory.createPlan(); + Activity start = factory.createActivityFromLinkId("start", Id.createLinkId(1)); + start.setEndTime(5000); + start.getAttributes().putAttribute("prebooking:submissionTime" + "drt", 900.); + start.getAttributes().putAttribute("prebooking:plannedDepartureTime" + "drt", 5000.); + plan.addActivity(start); + plan.addLeg(factory.createLeg("drt")); + plan.addActivity(factory.createActivityFromLinkId("end", Id.createLinkId(2))); + person.addPlan(plan); + population.addPerson(person); + } + + //person 3 - prebooking submitted during shift for time when shift should be active - ok + { + Person person = factory.createPerson(Id.createPersonId(3)); + Plan plan = factory.createPlan(); + Activity start = factory.createActivityFromLinkId("start", Id.createLinkId(1)); + start.setEndTime(5000); + start.getAttributes().putAttribute("prebooking:submissionTime" + "drt", 4000.); + start.getAttributes().putAttribute("prebooking:plannedDepartureTime" + "drt", 5000.); + plan.addActivity(start); + plan.addLeg(factory.createLeg("drt")); + plan.addActivity(factory.createActivityFromLinkId("end", Id.createLinkId(2))); + person.addPlan(plan); + population.addPerson(person); + } + + //person 4 - prebooking submitted during shift for time when shift should be ended - rejected + { + Person person = factory.createPerson(Id.createPersonId(4)); + Plan plan = factory.createPlan(); + Activity start = factory.createActivityFromLinkId("start", Id.createLinkId(1)); + start.setEndTime(8000); + start.getAttributes().putAttribute("prebooking:submissionTime" + "drt", 4000.); + start.getAttributes().putAttribute("prebooking:plannedDepartureTime" + "drt", 11000.); + plan.addActivity(start); + plan.addLeg(factory.createLeg("drt")); + plan.addActivity(factory.createActivityFromLinkId("end", Id.createLinkId(2))); + person.addPlan(plan); + population.addPerson(person); + } + + //person 5 - prebooking submitted during shift for time which falls into break beginning of break corridor with enough remaining time - ok + { + Person person = factory.createPerson(Id.createPersonId(5)); + Plan plan = factory.createPlan(); + Activity start = factory.createActivityFromLinkId("start", Id.createLinkId(1)); + start.setEndTime(6000.); + start.getAttributes().putAttribute("prebooking:submissionTime" + "drt", 4000.); + start.getAttributes().putAttribute("prebooking:plannedDepartureTime" + "drt", 6000.); + plan.addActivity(start); + plan.addLeg(factory.createLeg("drt")); + plan.addActivity(factory.createActivityFromLinkId("end", Id.createLinkId(2))); + person.addPlan(plan); + population.addPerson(person); + } + + //person 6 - prebooking submitted during shift for time which would preclude meaningful break - rejected + { + Person person = factory.createPerson(Id.createPersonId(6)); + Plan plan = factory.createPlan(); + Activity start = factory.createActivityFromLinkId("start", Id.createLinkId(1)); + start.setEndTime(6500.); + start.getAttributes().putAttribute("prebooking:submissionTime" + "drt", 4000.); + start.getAttributes().putAttribute("prebooking:plannedDepartureTime" + "drt", 6500.); + plan.addActivity(start); + plan.addLeg(factory.createLeg("drt")); + plan.addActivity(factory.createActivityFromLinkId("end", Id.createLinkId(2))); + person.addPlan(plan); + population.addPerson(person); + } + } + + private static void prepareOperations(Controler run, DrtWithExtensionsConfigGroup drtWithShiftsConfigGroup) { + FleetSpecification fleetSpecification = new FleetSpecificationImpl(); + fleetSpecification.addVehicleSpecification(ImmutableDvrpVehicleSpecification.newBuilder() // + .id(Id.create("v1", DvrpVehicle.class)) // + .capacity(1) // + .serviceBeginTime(0.0) // + .serviceEndTime(24 * 3600) // + .startLinkId(Id.createLinkId(1)) // + .build()); + + OperationFacilitiesSpecification opFasSpecification = new OperationFacilitiesSpecificationImpl(); + opFasSpecification.addOperationFacilitySpecification(OperationFacilitySpecificationImpl + .newBuilder() + .capacity(1) + .type(OperationFacilityType.hub) + .coord(new Coord(1000, 1000)) + .linkId(Id.createLinkId(1)) + .id(Id.create(1, OperationFacility.class)) + .build()); + + DrtShiftsSpecification shiftsSpecification = new DrtShiftsSpecificationImpl(); + shiftsSpecification.addShiftSpecification(DrtShiftSpecificationImpl.newBuilder() + .start(3600) + .end(10800) + .id(Id.create(1, DrtShift.class)) + .shiftBreak(DrtShiftBreakSpecificationImpl.newBuilder().duration(600.).earliestStart(6000.).latestEnd(7000.).build()) + .operationFacility(Id.create(1, OperationFacility.class)) + .build() + ); + run.addOverridingModule(new AbstractDvrpModeModule(drtWithShiftsConfigGroup.getMode()) { + @Override + public void install() { + bindModal(FleetSpecification.class).toInstance(fleetSpecification); + bindModal(OperationFacilitiesSpecification.class).toInstance(opFasSpecification); + bindModal(DrtShiftsSpecification.class).toInstance(shiftsSpecification); + } + }); + + } + + private void prepareNetwork(Scenario scenario) { + Network network = scenario.getNetwork(); + Node node1 = NetworkUtils.createAndAddNode(network, Id.createNodeId(1), new Coord(0, 0)); + Node node2 = NetworkUtils.createAndAddNode(network, Id.createNodeId(2), new Coord(1000, 1000)); + + NetworkUtils.createAndAddLink(network, Id.createLinkId(1), node1, node2, CoordUtils.length(node2.getCoord()), 50 / 3.6, 100, 1, null, null); + NetworkUtils.createAndAddLink(network, Id.createLinkId(2), node2, node1, CoordUtils.length(node2.getCoord()), 50 / 3.6, 100, 1, null, null); + } + +} diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunShiftDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunShiftDrtScenarioIT.java index 1b866a314d2..acfc878a000 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunShiftDrtScenarioIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/operations/shifts/run/RunShiftDrtScenarioIT.java @@ -4,9 +4,9 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.contrib.common.zones.systems.grid.square.SquareGridZoneSystemParams; import org.matsim.contrib.drt.analysis.zonal.DrtZoneSystemParams; +import org.matsim.contrib.drt.extension.DrtWithExtensionsConfigGroup; import org.matsim.contrib.drt.extension.operations.DrtOperationsControlerCreator; import org.matsim.contrib.drt.extension.operations.DrtOperationsParams; -import org.matsim.contrib.drt.extension.operations.DrtWithOperationsConfigGroup; import org.matsim.contrib.drt.extension.operations.operationFacilities.OperationFacilitiesParams; import org.matsim.contrib.drt.extension.operations.shifts.config.ShiftsParams; import org.matsim.contrib.drt.optimizer.constraints.DefaultDrtOptimizationConstraintsSet; @@ -36,7 +36,7 @@ public class RunShiftDrtScenarioIT { @Test void test() { - MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithOperationsConfigGroup::new); + MultiModeDrtConfigGroup multiModeDrtConfigGroup = new MultiModeDrtConfigGroup(DrtWithExtensionsConfigGroup::new); String fleetFile = "holzkirchenFleet.xml"; String plansFile = "holzkirchenPlans.xml.gz"; @@ -44,7 +44,7 @@ void test() { String opFacilitiesFile = "holzkirchenOperationFacilities.xml"; String shiftsFile = "holzkirchenShifts.xml"; - DrtWithOperationsConfigGroup drtWithShiftsConfigGroup = (DrtWithOperationsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); + DrtWithExtensionsConfigGroup drtWithShiftsConfigGroup = (DrtWithExtensionsConfigGroup) multiModeDrtConfigGroup.createParameterSet("drt"); drtWithShiftsConfigGroup.mode = TransportMode.drt; DefaultDrtOptimizationConstraintsSet defaultConstraintsSet = diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingModeQSimModule.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingModeQSimModule.java index badbb8624f5..19274c3fd8b 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingModeQSimModule.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingModeQSimModule.java @@ -17,12 +17,15 @@ import org.matsim.contrib.dvrp.fleet.DvrpVehicleLookup; import org.matsim.contrib.dvrp.optimizer.VrpOptimizer; import org.matsim.contrib.dvrp.passenger.*; +import org.matsim.contrib.dvrp.router.TimeAsTravelDisutility; import org.matsim.contrib.dvrp.run.AbstractDvrpModeQSimModule; import org.matsim.contrib.dvrp.schedule.ScheduleTimingUpdater; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.mobsim.framework.MobsimTimer; import org.matsim.core.mobsim.qsim.QSim; +import org.matsim.core.router.speedy.SpeedyALTFactory; import org.matsim.core.router.util.LeastCostPathCalculator; +import org.matsim.core.router.util.TravelDisutility; import org.matsim.core.router.util.TravelTime; public class PrebookingModeQSimModule extends AbstractDvrpModeQSimModule { @@ -97,6 +100,10 @@ protected void configureQSim() { bindModal(RequestUnscheduler.class).to(modalKey(SimpleRequestUnscheduler.class)); break; case Routing: + bindModal(LeastCostPathCalculator.class).toProvider(modalProvider(getter -> + new SpeedyALTFactory().createPathCalculator(getter.getModal(Network.class), + new TimeAsTravelDisutility(getter.getModal(TravelTime.class)), getter.getModal(TravelTime.class) + ))); bindModal(RequestUnscheduler.class).to(modalKey(ComplexRequestUnscheduler.class)); break; default: diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingStopActivity.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingStopActivity.java index 762c80500b1..fd81c1745f3 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingStopActivity.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingStopActivity.java @@ -73,14 +73,14 @@ public PrebookingStopActivity(PassengerHandler passengerHandler, DynAgent driver @Override protected boolean isLastStep(double now) { boolean dropoffsReady = updateDropoffRequests(now); - boolean pickupsReady = updatePickupRequests(now); + boolean pickupsReady = updatePickupRequests(now, false); return pickupsReady && dropoffsReady && now >= endTime.get(); } @Override protected void beforeFirstStep(double now) { initDropoffRequests(now); - updatePickupRequests(now); + updatePickupRequests(now, true); } private void initDropoffRequests(double now) { @@ -112,7 +112,7 @@ public int compareTo(QueuedRequest o) { } } - private boolean updatePickupRequests(double now) { + private boolean updatePickupRequests(double now, boolean isFirstStep) { var pickupIterator = pickupRequests.values().iterator(); while (pickupIterator.hasNext()) { @@ -125,7 +125,7 @@ private boolean updatePickupRequests(double now) { if (passengerHandler.notifyWaitForPassengers(this, this.driver, request.getId())) { // agent starts to enter queuePickup(request, now); - } else if (now > request.getEarliestStartTime()) { + } else if (now > request.getEarliestStartTime() && !isFirstStep) { if (abandonVoter.abandonRequest(now, vehicle, request)) { prebookingManager.abandon(request.getId()); } diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/unscheduler/ComplexRequestUnscheduler.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/unscheduler/ComplexRequestUnscheduler.java index 4fb0cae5339..ca25cb41cbf 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/unscheduler/ComplexRequestUnscheduler.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/unscheduler/ComplexRequestUnscheduler.java @@ -65,7 +65,7 @@ public void unscheduleRequest(double now, Id vehicleId, Id DvrpVehicle vehicle = vehicleLookup.lookupVehicle(vehicleId); VehicleEntry vEntry = vehicleEntryFactory.create(vehicle, now); - Waypoint.Stop pickupStop = null; + Waypoint pickupStop = null; Waypoint.Stop dropoffStop = null; DrtStopTask pickupStopTask = null; @@ -89,6 +89,15 @@ public void unscheduleRequest(double now, Id vehicleId, Id } } + if(pickupStopTask == null) { + if(vEntry.start.task.orElseThrow() instanceof DrtStopTask stopTask) { + if(stopTask.getPickupRequests().containsKey(requestId)) { + pickupStopTask = stopTask; + pickupStop = vEntry.start; + } + } + } + Verify.verifyNotNull(pickupStopTask, "Could not find request that I'm supposed to unschedule"); Verify.verifyNotNull(dropoffStopTask, "Could not find request that I'm supposed to unschedule"); Verify.verifyNotNull(pickupStop); @@ -103,12 +112,13 @@ public void unscheduleRequest(double now, Id vehicleId, Id // removed the pickup and the StopAction will handle the situation // - or we found a stop, then it is not started yet and we can remove it - boolean removePickup = pickupStopTask.getPickupRequests().size() == 0 - && pickupStopTask.getDropoffRequests().size() == 0; - boolean removeDropoff = dropoffStopTask.getPickupRequests().size() == 0 - && dropoffStopTask.getDropoffRequests().size() == 0; + boolean removePickup = pickupStopTask.getPickupRequests().isEmpty() + && pickupStopTask.getDropoffRequests().isEmpty() + && pickupStop instanceof Waypoint.Stop; + boolean removeDropoff = dropoffStopTask.getPickupRequests().isEmpty() + && dropoffStopTask.getDropoffRequests().isEmpty(); - Replacement pickupReplacement = removePickup ? findReplacement(vEntry, pickupStop) : null; + Replacement pickupReplacement = removePickup ? findReplacement(vEntry, (Waypoint.Stop) pickupStop) : null; Replacement dropoffReplacement = removeDropoff ? findReplacement(vEntry, dropoffStop) : null; if (pickupReplacement != null && dropoffReplacement != null) { diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtControlerCreator.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtControlerCreator.java index ab438acc805..1b4435829f1 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtControlerCreator.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtControlerCreator.java @@ -60,11 +60,22 @@ public static Scenario createScenarioWithDrtRouteFactory(Config config) { * @return */ public static Controler createControler(Config config, boolean otfvis) { - MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); - DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.scoring(), config.routing()); - Scenario scenario = createScenarioWithDrtRouteFactory(config); ScenarioUtils.loadScenario(scenario); + return createControler(config, scenario, otfvis); + } + + /** + * Creates a controller in one step. + * + * @param config + * @param scenario + * @param otfvis + * @return + */ + public static Controler createControler(Config config, Scenario scenario, boolean otfvis) { + MultiModeDrtConfigGroup multiModeDrtConfig = MultiModeDrtConfigGroup.get(config); + DrtConfigs.adjustMultiModeDrtConfig(multiModeDrtConfig, config.scoring(), config.routing()); Controler controler = new Controler(scenario); controler.addOverridingModule(new DvrpModule()); diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/AbandonAndCancelTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/AbandonAndCancelTest.java index 61241d7c293..ca3f22dd46f 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/AbandonAndCancelTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/AbandonAndCancelTest.java @@ -265,4 +265,69 @@ public void notifyMobsimBeforeSimStep(MobsimBeforeSimStepEvent e) { assertTrue(requestInfo.rejected); } } + + @Test + void cancelLateWithComplexUnschedulerTest() { + /* + * One person requests to depart at 2000 and also is there at 2000. Another + * person asks also to depart at 2000, but only arrives at 4000, i.e. the person + * has 1000s delay. + * + * In this test we manually cancel the second request at 3000.0 (so after + * departure of the first agent). + */ + + PrebookingTestEnvironment environment = new PrebookingTestEnvironment(utils) // + .addVehicle("vehicle", 1, 1) // + .addRequest("personOk", 0, 0, 5, 5, 2000.0, 0.0, 2000.0) // + .addRequest("personLate", 0, 0, 5, 5, 4000.0, 0.0, 2000.0) // + .configure(600.0, 1.3, 600.0, 60.0) // + .endTime(10.0 * 3600.0); + + Controler controller = environment.build(); + PrebookingParams prebookingParams = new PrebookingParams(); + prebookingParams.unschedulingMode = PrebookingParams.UnschedulingMode.Routing; + PrebookingTest.installPrebooking(controller, prebookingParams); + + controller.addOverridingQSimModule(new AbstractDvrpModeQSimModule("drt") { + @Override + protected void configureQSim() { + addModalQSimComponentBinding().toProvider(modalProvider(getter -> { + PrebookingManager prebookingManager = getter.getModal(PrebookingManager.class); + QSim qsim = getter.get(QSim.class); + + return new MobsimBeforeSimStepListener() { + @Override + public void notifyMobsimBeforeSimStep(MobsimBeforeSimStepEvent e) { + if (e.getSimulationTime() == 3000.0) { + PlanAgent planAgent = (PlanAgent) qsim.getAgents() + .get(Id.createPersonId("personLate")); + + Leg leg = TripStructureUtils.getLegs(planAgent.getCurrentPlan()).get(1); + + prebookingManager.cancel(leg); + } + } + }; + })); + } + }); + + controller.run(); + + { + RequestInfo requestInfo = environment.getRequestInfo().get("personOk"); + assertEquals(0.0, requestInfo.submissionTime, 1e-3); + assertEquals(2061.0, requestInfo.pickupTime, 1e-3); + assertEquals(3212.0, requestInfo.dropoffTime, 1e-3); // still waited quite a bit + } + + { + RequestInfo requestInfo = environment.getRequestInfo().get("personLate"); + assertEquals(0.0, requestInfo.submissionTimes.get(0), 1e-3); + // agent tries a non-prebooked request upon arrival + assertEquals(4000.0, requestInfo.submissionTimes.get(1), 1e-3); + assertTrue(requestInfo.rejected); + } + } } diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/PrebookingTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/PrebookingTest.java index 8a2f236a7b0..4809a205c8a 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/PrebookingTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/PrebookingTest.java @@ -12,7 +12,6 @@ import org.matsim.contrib.drt.stops.StaticPassengerStopDurationProvider; import org.matsim.contrib.dvrp.fleet.DvrpVehicle; import org.matsim.contrib.dvrp.run.AbstractDvrpModeModule; -import org.matsim.contrib.dvrp.run.AbstractDvrpModeQSimModule; import org.matsim.core.controler.Controler; import org.matsim.testcases.MatsimTestUtils; @@ -57,12 +56,20 @@ void withoutPrebookedRequests() { } static PrebookingParams installPrebooking(Controler controller) { - return installPrebooking(controller, true); + return installPrebooking(controller, true, new PrebookingParams()); + } + + static PrebookingParams installPrebooking(Controler controller, PrebookingParams prebookingParams) { + return installPrebooking(controller, true, prebookingParams); } static PrebookingParams installPrebooking(Controler controller, boolean installLogic) { + return installPrebooking(controller, installLogic, new PrebookingParams()); + } + + static PrebookingParams installPrebooking(Controler controller, boolean installLogic, PrebookingParams prebookingParams) { DrtConfigGroup drtConfig = DrtConfigGroup.getSingleModeDrtConfig(controller.getConfig()); - drtConfig.addParameterSet(new PrebookingParams()); + drtConfig.addParameterSet(prebookingParams); if (installLogic) { AttributeBasedPrebookingLogic.install(controller, drtConfig); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java index 45013b10201..52ab385cf7d 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/ColdEmissionAnalysisModule.java @@ -17,7 +17,7 @@ * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * - * + * * *********************************************************************** */ package org.matsim.contrib.emissions; @@ -130,7 +130,7 @@ private Map calculateColdEmissions(Id vehicleId, dou final Map coldEmissionsOfEvent = new EnumMap<>( Pollutant.class ); - logger.debug("VehId: " + vehicleId + " ; Tuple.first = " +vehicleInformationTuple.getFirst()); + logger.debug("VehId: {} ; Tuple.first = {}", vehicleId, vehicleInformationTuple.getFirst()); // fallback vehicle types that we cannot or do not want to map onto a hbefa vehicle type: if ( vehicleInformationTuple.getFirst()==HbefaVehicleCategory.NON_HBEFA_VEHICLE ) { for ( Pollutant coldPollutant : coldPollutants) { @@ -155,20 +155,15 @@ private Map calculateColdEmissions(Id vehicleId, dou //HBEFA 3 provides cold start emissions for "pass. car" and Light_Commercial_Vehicles (LCV) only. //HBEFA 4.1 provides cold start emissions for "pass. car" and Light_Commercial_Vehicles (LCV) only. //see https://www.hbefa.net/e/documents/HBEFA41_Development_Report.pdf (WP 4 , page 23) kturner, may'20 - //Mapping everything except "motorcycle" to "pass.car", since this was done in the last years for HGV. - //This may can be improved: What should be better set to LGV or zero???? kturner, may'20 - if (vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.HEAVY_GOODS_VEHICLE)) { - changeVehCategory(key, HbefaVehicleCategory.HEAVY_GOODS_VEHICLE, HbefaVehicleCategory.PASSENGER_CAR); - } - if (vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.URBAN_BUS)) { - changeVehCategory(key, HbefaVehicleCategory.URBAN_BUS, HbefaVehicleCategory.PASSENGER_CAR ); - } - if (vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.COACH)) { - changeVehCategory(key, HbefaVehicleCategory.COACH, HbefaVehicleCategory.PASSENGER_CAR); - } - if (vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.MOTORCYCLE)){ - changeVehCategory(key, HbefaVehicleCategory.MOTORCYCLE, HbefaVehicleCategory.PASSENGER_CAR); - return coldEmissionsOfEvent; + if (vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.HEAVY_GOODS_VEHICLE) || + vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.COACH) || + vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.URBAN_BUS) || + vehicleInformationTuple.getFirst().equals(HbefaVehicleCategory.MOTORCYCLE)) { + if (vehInfoWarnHDVCnt < maxWarnCnt) { + vehInfoWarnHDVCnt++; + logger.warn("Automagic changing of VehCategory is disabled. Please make sure that your table contains the necessary values for {}", HbefaVehicleCategory.HEAVY_GOODS_VEHICLE.name()); + if (vehInfoWarnHDVCnt == maxWarnCnt) logger.warn(Gbl.FUTURE_SUPPRESSED); + } } if(this.detailedHbefaColdTable != null) { @@ -197,33 +192,6 @@ private Map calculateColdEmissions(Id vehicleId, dou return coldEmissionsOfEvent; } - /** - * Replace the vehicleCategory with HbefaVehicleCategory.PASSENGER_CAR - * This is the old behaviour as it was until Aug 21. - * (Aug'21, KMT) This does not help, since the emConcepts are not the same. So it is _not_ usable if using - * some kind of detailed values. - * @param key - * @param originVehCat - * @param targetvehCat - */ - //TODO Mabe make the behaviour settable by an enum? -> keep some kind of backwards capability or just return a 0.0 as it is for motorcycle? - private void changeVehCategory(HbefaColdEmissionFactorKey key, HbefaVehicleCategory originVehCat, HbefaVehicleCategory targetvehCat) { -// key.setVehicleCategory(targetvehCat); -// if (vehInfoWarnHDVCnt < maxWarnCnt) { -// vehInfoWarnHDVCnt++; -// logger.warn("HBEFA does not provide cold start emission factors for " + -// originVehCat + -// ". Setting vehicle category to " + targetvehCat + "..."); -// if (vehInfoWarnHDVCnt == maxWarnCnt) logger.warn(Gbl.FUTURE_SUPPRESSED); -// } - if (vehInfoWarnHDVCnt < maxWarnCnt) { - vehInfoWarnHDVCnt++; - logger.warn("Automagic changing of VehCategory is disabled. Please make sure that your table contains the " + - "necessary values for " + originVehCat.name()); - if (vehInfoWarnHDVCnt == maxWarnCnt) logger.warn(Gbl.FUTURE_SUPPRESSED); - } - } - private HbefaColdEmissionFactor getEmissionsFactor(Tuple vehicleInformationTuple, int distance_km, HbefaColdEmissionFactorKey efkey, Pollutant coldPollutant) { efkey.setDistance(distance_km); @@ -241,7 +209,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple; average; average'"); logger.warn(Gbl.ONLYONCE); logger.warn(Gbl.FUTURE_SUPPRESSED); @@ -306,7 +274,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple; average; average" should, I think, just be entered as such. kai, feb'20 @@ -336,7 +304,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple; average; average'"); logger.warn(Gbl.ONLYONCE); logger.warn(Gbl.FUTURE_SUPPRESSED); @@ -370,7 +338,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple; average; average" should, I think, just be entered as such. kai, feb'20 @@ -387,7 +355,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple list = new ArrayList<>(this.avgHbefaColdTable.keySet()); list.sort(Comparator.comparing(HbefaColdEmissionFactorKey::toString)); for (HbefaColdEmissionFactorKey key : list) { @@ -420,7 +388,7 @@ private HbefaColdEmissionFactor getEmissionsFactor(Tuple vehicleId, EmissionsConfigGroup emi + " Aborting..." ); case ignore: if ( noVehWarnCnt < 10 ){ - logger.warn( - "No vehicle defined for id " + vehicleId + ". The vehicle will be ignored." ); + logger.warn("No vehicle defined for id {}. The vehicle will be ignored.", vehicleId); noVehWarnCnt++; if ( noVehWarnCnt == 10 ) logger.warn( Gbl.FUTURE_SUPPRESSED ); } @@ -201,7 +200,7 @@ public void handleEvent(VehicleEntersTrafficEvent event) { private void warnIfZeroLinkLength(Id linkId, double linkLength) { if (linkLength == 0.) { if (zeroLinkLengthWarnCnt == 0) { - logger.warn("Length of the link " + linkId + " is zero. No emissions will be estimated for this link. Make sure, this is intentional."); + logger.warn("Length of the link {} is zero. No emissions will be estimated for this link. Make sure, this is intentional.", linkId); logger.warn(Gbl.ONLYONCE); zeroLinkLengthWarnCnt++; } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java index 196d7e77255..39e58239d09 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionModule.java @@ -77,11 +77,13 @@ public EmissionModule(final Scenario scenario, final EventsManager eventsManager // Event handlers are now added to the event manager inside the respective Handlers, jm march '18 } + @SuppressWarnings("ClassEscapesDefinedScope") public WarmEmissionAnalysisModule getWarmEmissionAnalysisModule() { // makes sense to have this public for externalization computations. kai, jan'20 return this.warmEmissionHandler.getWarmEmissionAnalysisModule(); } + @SuppressWarnings("ClassEscapesDefinedScope") public ColdEmissionAnalysisModule getColdEmissionAnalysisModule() { // makes sense to have this public for externalization computations. kai, jan'20 return this.coldEmissionHandler.getColdEmissionAnalysisModule(); @@ -103,27 +105,19 @@ public EventsManager getEmissionEventsManager() { } public void writeEmissionInformation() { - logger.info("Warm emissions were not calculated for " + warmEmissionHandler.getLinkLeaveWarnCnt() + " of " + - warmEmissionHandler.getLinkLeaveCnt() + " link leave events (no corresponding link enter event)."); + logger.info("Warm emissions were not calculated for {} of {} link leave events (no corresponding link enter event).", warmEmissionHandler.getLinkLeaveWarnCnt(), warmEmissionHandler.getLinkLeaveCnt()); int noVehicleLeavesTrafficEmissions = warmEmissionHandler.getSameLinkTrafficLeaveWarnCnt() + warmEmissionHandler.getUnusualTrafficLeaveWarnCnt(); - logger.info("Warm emissions were not calculated for " + noVehicleLeavesTrafficEmissions + " of " + warmEmissionHandler.getTrafficLeaveCnt() + - " vehicle leaves traffic events (no corresponding link enter event)."); + logger.info("Warm emissions were not calculated for {} of {} vehicle leaves traffic events (no corresponding link enter event).", noVehicleLeavesTrafficEmissions, warmEmissionHandler.getTrafficLeaveCnt()); if ( warmEmissionHandler.getUnusualTrafficLeaveWarnCnt() > 0 ) { - logger.info(warmEmissionHandler.getUnusualTrafficLeaveWarnCnt() + " events occurred where the vehicle left traffic without entering ANY link " + - "(no warm emissions calculated). These events might need to be investigated."); } + logger.info("{} events occurred where the vehicle left traffic without entering ANY link (no warm emissions calculated). These events might need to be investigated.", warmEmissionHandler.getUnusualTrafficLeaveWarnCnt()); } WarmEmissionAnalysisModule wam = warmEmissionHandler.getWarmEmissionAnalysisModule(); - logger.info("Emission calculation based on `Free flow only' occured for " + wam.getFreeFlowOccurences() + " of " + - wam.getWarmEmissionEventCounter() + " warm emission events."); - logger.info("Emission calculation based on `Stop&Go only' occured for " + wam.getStopGoOccurences() + " of " + - wam.getWarmEmissionEventCounter() + " warm emission events."); - logger.info("Emission calculation based on `Fractions' occured for " + wam.getFractionOccurences() + " of " + - wam.getWarmEmissionEventCounter() + " warm emission events."); - logger.info("Free flow occured on " + wam.getFreeFlowKmCounter() + " km of total " + - wam.getKmCounter() + " km, where emissions were calculated."); - logger.info("Stop&Go occured on " + wam.getStopGoKmCounter() + " km of total " + - wam.getKmCounter() + " km, where emissions were calculated."); + logger.info("Emission calculation based on `Free flow only' occurred for {} of {} warm emission events.", wam.getFreeFlowOccurences(), wam.getWarmEmissionEventCounter()); + logger.info("Emission calculation based on `Stop&Go only' occurred for {} of {} warm emission events.", wam.getStopGoOccurences(), wam.getWarmEmissionEventCounter()); + logger.info("Emission calculation based on `Fractions' occurred for {} of {} warm emission events.", wam.getFractionOccurences(), wam.getWarmEmissionEventCounter()); + logger.info("Free flow occurred on {} km of total {} km, where emissions were calculated.", wam.getFreeFlowKmCounter(), wam.getKmCounter()); + logger.info("Stop&Go occurred on {} km of total {} km, where emissions were calculated.", wam.getStopGoKmCounter(), wam.getKmCounter()); logger.info("Emission calculation terminated. Emission events can be found in regular events file."); } @@ -171,9 +165,10 @@ private void createLookupTables() { if (shouldCreateAverageTables()) { this.avgHbefaColdTable = HbefaTables.loadAverageCold(emissionConfigGroup.getAverageColdEmissionFactorsFileURL(scenario.getConfig().getContext())); addPollutantsToMap(coldPollutants, avgHbefaColdTable.keySet()); - // yy The naming and signature of the above should presumably be changed: (1) addPollutantsToX implies signature (pollutants, - // X). But it is actually the other way round (even if it does not read that way. (2) "coldPollutants" is not a Map. Since - // this is a private method, maybe one could also have a method "memorizeColdPollutants" and then not have coldPollutants as + // yy The naming and signature of the above should presumably be changed: + // (1) addPollutantsToX implies signature (pollutants,X). But it is actually the other way round (even if it does not read that way.) + // (2) "coldPollutants" is not a Map. + // Since this is a private method, maybe one could also have a method "memorizeColdPollutants" and then not have coldPollutants as // field. kai, dec'22 this.avgHbefaWarmTable = HbefaTables.loadAverageWarm(emissionConfigGroup.getAverageWarmEmissionFactorsFileURL(scenario.getConfig().getContext())); @@ -205,24 +200,17 @@ private void addPollutantsToMap(Set addTo, Set true; + default -> false; + }; } private boolean shouldCreateDetailedTables() { - switch (emissionConfigGroup.getDetailedVsAverageLookupBehavior()) { - case onlyTryDetailedElseAbort: - case tryDetailedThenTechnologyAverageElseAbort: - case tryDetailedThenTechnologyAverageThenAverageTable: - return true; - default: - return false; - } + return switch (emissionConfigGroup.getDetailedVsAverageLookupBehavior()) { + case onlyTryDetailedElseAbort, tryDetailedThenTechnologyAverageElseAbort, tryDetailedThenTechnologyAverageThenAverageTable -> true; + default -> false; + }; } private void createEmissionHandlers() { diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java index a24186833db..bd28e89992c 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/EmissionUtils.java @@ -97,7 +97,7 @@ public static Map, SortedMap> setNonCalculatedEmis for (Pollutant pollutant : pollutants) { emissionType2Value.put(pollutant, 0.0); } - } else { // person in map, but some emissions are not set; setting these to 0.0 + } else { // person in map, but some emissions are not set; setting these to 0.0 emissionType2Value = totalEmissions.get(personId); for (Pollutant pollutant : emissionType2Value.keySet()) { // else do nothing @@ -225,7 +225,7 @@ static Tuple convertVehicleDescrip EngineInformation engineInformation; // get information from where it used to be in previous versions and move to where it should be now: - logger.debug("emissionsConfigGroup.getHbefaVehicleDescriptionSource=" + emissionsConfigGroup.getHbefaVehicleDescriptionSource()); + logger.debug("emissionsConfigGroup.getHbefaVehicleDescriptionSource={}", emissionsConfigGroup.getHbefaVehicleDescriptionSource()); switch( emissionsConfigGroup.getHbefaVehicleDescriptionSource() ) { case usingVehicleTypeId: // (v1, hbefa vehicle description is in vehicle type id. Copy to where it is expected now) @@ -320,7 +320,7 @@ public static HbefaVehicleCategory mapString2HbefaVehicleCategory(String string) try{ hbefaVehicleCategory = HbefaVehicleCategory.valueOf(string); } catch (IllegalArgumentException e) { - logger.warn("Could not map String " + string + " to any HbefaVehicleCategory; please check syntax in hbefa input file."); + logger.warn("Could not map String {} to any HbefaVehicleCategory; please check syntax in hbefa input file.", string); throw new RuntimeException(); } } @@ -329,22 +329,15 @@ public static HbefaVehicleCategory mapString2HbefaVehicleCategory(String string) public static String mapHbefaVehicleCategory2String(HbefaVehicleCategory category) { - switch (category) { - case COACH: - return "coach"; - case HEAVY_GOODS_VEHICLE: - return "HGV"; - case LIGHT_COMMERCIAL_VEHICLE: - return "LCV"; - case MOTORCYCLE: - return "motorcycle"; - case PASSENGER_CAR: - return "pass. car"; - case URBAN_BUS: - return "urban bus"; - default: - throw new RuntimeException("Could not transform category to string: " + category); - } + return switch (category) { + case COACH -> "coach"; + case HEAVY_GOODS_VEHICLE -> "HGV"; + case LIGHT_COMMERCIAL_VEHICLE -> "LCV"; + case MOTORCYCLE -> "motorcycle"; + case PASSENGER_CAR -> "pass. car"; + case URBAN_BUS -> "urban bus"; + default -> throw new RuntimeException("Could not transform category to string: " + category); + }; } static Pollutant getPollutant( String pollutantString ){ @@ -353,37 +346,20 @@ static Pollutant getPollutant( String pollutantString ){ // setCo2TotalKeys( Set keys ) // as we have it, e.g., with network modes. kai, feb'20 - Pollutant pollutant; - switch( pollutantString ){ - case "CO2(total)": - pollutant = Pollutant.CO2_TOTAL; - break; - case "CO2(rep)": - pollutant = Pollutant.CO2_rep; - break; - case "PM2.5 (non-exhaust)": - pollutant = Pollutant.PM2_5_non_exhaust; - break; - case "PM2.5": - pollutant = Pollutant.PM2_5; - break; - case "PM (non-exhaust)": - pollutant = Pollutant.PM_non_exhaust; - break; - case "BC (exhaust)": - pollutant = Pollutant.BC_exhaust; - break; - case "BC (non-exhaust)": - pollutant = Pollutant.BC_non_exhaust; - break; - default: - pollutant = Pollutant.valueOf( pollutantString ); - // the Pollutant.valueOf(...) should fail if the incoming key is not consistent with what is available in the enum. Two possibilities: - // (1) it is a new pollutant. In that case, just add to the enum. - // (2) It is a different spelling of an already existing pollutant. In that case, see above. - // kai, jan'20 - } - return pollutant; + return switch (pollutantString) { + case "CO2(total)" -> Pollutant.CO2_TOTAL; + case "CO2(rep)" -> Pollutant.CO2_rep; + case "PM2.5 (non-exhaust)" -> Pollutant.PM2_5_non_exhaust; + case "PM2.5" -> Pollutant.PM2_5; + case "PM (non-exhaust)" -> Pollutant.PM_non_exhaust; + case "BC (exhaust)" -> Pollutant.BC_exhaust; + case "BC (non-exhaust)" -> Pollutant.BC_non_exhaust; + default -> Pollutant.valueOf(pollutantString); + // the Pollutant.valueOf(...) should fail if the incoming key is not consistent with what is available in the enum. Two possibilities: + // (1) it is a new pollutant. In that case, just add to the enum. + // (2) It is a different spelling of an already existing pollutant. In that case, see above. + // kai, jan'20 + }; } /** diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaEmissionFactorKey.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaEmissionFactorKey.java index aa11fc55018..3ce7f9632e7 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaEmissionFactorKey.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaEmissionFactorKey.java @@ -66,13 +66,11 @@ public void setComponent(Pollutant component) { @Override public boolean equals(Object o) { if (this == o) return true; - if (!(o instanceof HbefaEmissionFactorKey)) return false; + if (!(o instanceof HbefaEmissionFactorKey efk)) return false; - var that = (HbefaEmissionFactorKey) o; - - if (vehicleCategory != that.getVehicleCategory()) return false; - if (!Objects.equals(vehicleAttributes, that.vehicleAttributes)) return false; - return Objects.equals(component, that.component); + if (vehicleCategory != efk.getVehicleCategory()) return false; + if (!Objects.equals(vehicleAttributes, efk.vehicleAttributes)) return false; + return Objects.equals(component, efk.component); } @Override diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaRoadTypeMapping.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaRoadTypeMapping.java index bca754b259d..5074b708db5 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaRoadTypeMapping.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaRoadTypeMapping.java @@ -33,11 +33,11 @@ public void addHbefaMappings(Network network) { network.getLinks().values().parallelStream() .forEach(link -> { - String hbefaString = determineHebfaType(link); + String hbefaString = determineHbefaType(link); EmissionUtils.setHbefaRoadType(link, hbefaString); }); } - protected abstract String determineHebfaType(Link link); + protected abstract String determineHbefaType(Link link); } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaTables.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaTables.java index b3d23dedb82..f01d42bb0f7 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaTables.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/HbefaTables.java @@ -125,7 +125,7 @@ private static HbefaTrafficSituation mapString2HbefaTrafficSituation(String stri else if (string.endsWith("St+Go")) return HbefaTrafficSituation.STOPANDGO; else if (string.endsWith("St+Go2")) return HbefaTrafficSituation.STOPANDGO_HEAVY; else { - logger.warn("Could not map String " + string + " to any HbefaTrafficSituation; please check syntax in hbefa input file."); + logger.warn("Could not map String {} to any HbefaTrafficSituation; please check syntax in hbefa input file.", string); throw new RuntimeException(); } } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java index 4938d75e993..ccce2492711 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/OsmHbefaMapping.java @@ -22,24 +22,22 @@ package org.matsim.contrib.emissions; import com.google.inject.Provides; -import org.apache.commons.lang3.StringUtils; import org.matsim.api.core.v01.network.Link; import org.matsim.core.network.NetworkUtils; -import java.util.Arrays; import java.util.HashMap; -import java.util.List; import java.util.Map; +import java.util.stream.Stream; /** * Created by molloyj on 01.12.2017. - * + *

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

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

* Conversions from OSM to hbefa types * motorway;MW * primary;Trunk @@ -63,14 +61,14 @@ public class OsmHbefaMapping extends HbefaRoadTypeMapping { private final Map hbfeaMap = new HashMap<>(); static class Hbefa { - String name; - int min; - int max; + final String name; + final int min_speed; + final int max_speed; - Hbefa(String name, int min, int max) { + Hbefa(String name, int min_speed, int max) { this.name = name; - this.min = min; - this.max = max; + this.min_speed = min_speed; + this.max_speed = max; } } @@ -96,7 +94,7 @@ private void put(String s, Hbefa hbefa) { } @Override - public String determineHebfaType(Link link) { + public String determineHbefaType(Link link) { String roadType = NetworkUtils.getHighwayType(link); double allowedSpeed = NetworkUtils.getAllowedSpeed(link); @@ -110,7 +108,7 @@ private String getHEBFAtype(String type, double speed) { /* * speed attributes are sometimes rounded beforehand. - * make sure the speed is a multiple of 10, as the HBEFA emission key factors are and otherwise we get problems later... + * make sure the speed is a multiple of 10, as the HBEFA emission key factors are, and otherwise we get problems later... */ freeVelocity_kmh = Math.round(freeVelocity_kmh/10.0) * 10; @@ -125,8 +123,7 @@ private String getHEBFAtype(String type, double speed) { //sometimes link type is smth like 'motorway_link' or 'living_street' or 'primary|railway.tram'. We only care about the first part, here - int idx = Arrays.asList(type.indexOf('.'), type.indexOf('|'), type.indexOf('_'), type.indexOf(',')) - .stream() + int idx = Stream.of(type.indexOf('.'), type.indexOf('|'), type.indexOf('_'), type.indexOf(',')) .filter(i -> i>= 0) //if chrc is not in String indexOf returns -1 .min(Integer::compare) .orElse(type.length()); @@ -139,8 +136,8 @@ private String getHEBFAtype(String type, double speed) { if (!hbfeaMap.containsKey(type)) { throw new RuntimeException("'" + type + "' not in hbefa map"); } - int min_speed = hbfeaMap.get(type).min; - int max_speed = hbfeaMap.get(type).max; + int min_speed = hbfeaMap.get(type).min_speed; + int max_speed = hbfeaMap.get(type).max_speed; int clamped_speed = (int) Math.min(Math.max(min_speed, freeVelocity_kmh), max_speed); return "URB/" + hbfeaMap.get(type).name + "/" + clamped_speed; diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/Pollutant.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/Pollutant.java index 7e0f815d747..2db4b9607e9 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/Pollutant.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/Pollutant.java @@ -33,11 +33,11 @@ public enum Pollutant{ NMHC, // non-methane hydro carbons NOx, // nitrogen oxide NO2, // provided as g/km, but based on %-values of NOx - PM, // = PM10 --> particulate matterof size below 10μm, i.e. equivalent to PM10. unit = g/km + PM, // = PM10 --> particulate matter of size below 10μm, i.e. equivalent to PM10. unit = g/km SO2, //sulphur dioxide FC_MJ, // fuel consumption in MJ/km - CO2_rep, // CO2(reported): = carbon dioxide “reported”, i.e. withoutthe biofuel share in the fuel -> input for CO2e calculation - CO2e, // CO2 equivalents (WTW basis), CO2 equivalents contain CO2, CH4 and N2O, i.e. the relevant greenhouse gases from thetransport sector,multiplied with their respective 100-year Global Warming Potentials and summed up. + CO2_rep, // CO2(reported): = carbon dioxide “reported”, i.e. without the biofuel share in the fuel -> input for CO2e calculation + CO2e, // CO2 equivalents (WTW basis), CO2 equivalents contain CO2, CH4 and N2O, i.e. the relevant greenhouse gases from the transport sector, multiplied with their respective 100-year Global Warming Potentials and summed up. PM2_5, // particle mass for particles < 2.5 µm. unit = g/km PM2_5_non_exhaust, // tire wear! PM_non_exhaust, // PM10 from non-exhaust sources(e.g. road, tyre wear) diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java index 4652c3d7339..d43d1f941e2 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/PositionEmissionsModule.java @@ -111,7 +111,7 @@ Map calculateColdEmissions(Vehicle vehicle, double parkingDur } private Tuple getVehicleAttributes(Vehicle vehicle) { - // the following block fixes the vehicle types's emission information whenusing an old vehicle type format + // the following block fixes the vehicle type's emission information when using an old vehicle type format // the unit test I found uses an old format, so have it here. { String hbefaVehicleTypeDescription = EmissionUtils.getHbefaVehicleDescription(vehicle.getType(), emissionsConfigGroup); @@ -209,7 +209,7 @@ private void handlePositionEvent(PositionEvent event) { return; // only calculate emissions for cars if (!vehiclesInTraffic.containsKey(event.getVehicleId())) - return; // only collect positions if vehicle has entered traffic (if vehicle is wait2link its position is calculated but it hasn't entered traffic yet. + return; // only collect positions if vehicle has entered traffic (if vehicle is wait2link its position is calculated, but it hasn't entered traffic yet.) if (trajectories.containsKey(event.getVehicleId())) { computeCombinedEmissionEvent(event); @@ -223,23 +223,23 @@ private void handlePositionEvent(PositionEvent event) { private Map computeColdEmissions(PositionEvent event, Vehicle vehicle, double distanceToLastPosition) { - // we remember the vehicles which are currently emmitting cold emissions if not stored here return nothing + // we remember the vehicles which are currently emitting cold emissions if not stored here return nothing if (!vehiclesEmittingColdEmissions.contains(vehicle.getId())) return emissionCalculator.getEmptyColdEmissions(); double distance = calculateTravelledDistance(event); // this model assumes vehicles to emmit cold emissions for the first 2000m of a trip remove a vehicle from - // the list of emmiting vehicles if the current trajectory is longer than 2000m + // the list of emitting vehicles if the current trajectory is longer than 2000m if (distance > 2000) { vehiclesEmittingColdEmissions.remove(vehicle.getId()); return emissionCalculator.getEmptyColdEmissions(); } - // HBEFA assumes a constantly decreasing ammount of cold emissions depending on the distance travelled + // HBEFA assumes a constantly decreasing amount of cold emissions depending on the distance travelled // the underlying emission module simplifies this into two steps. Between 0-1km and 1-2km. We use the same // classes here because we don't want to rewrite all the stuff. The cold emission module computes emissions - // for 1000m. We take these as is and muliply with distanceToLastPosition / 1000. This way we have the fraction + // for 1000m. We take these as is and multiply with distanceToLastPosition / 1000. This way we have the fraction // of cold emissions for the distance travelled during the last time step janek oct' 2021 int distanceClass = distance <= 1000 ? 1 : 2; @@ -290,7 +290,7 @@ private void computeCombinedEmissionEvent(PositionEvent event) { eventsManager.processEvent(new PositionEmissionEvent(event, combinedEmissions, "combined")); } else { - log.warn("speed was too fast: " + speed + "m/s Current time: " + event.getTime() + " prev time: " + previousPosition.getTime() + " current linkId: " + event.getLinkId() + " prev linkId: " + previousPosition.getLinkId() + " agentId: " + event.getPersonId()); + log.warn("speed was too fast: {}m/s Current time: {} prev time: {} current linkId: {} prev linkId: {} agentId: {}", speed, event.getTime(), previousPosition.getTime(), event.getLinkId(), previousPosition.getLinkId(), event.getPersonId()); } } else { // if the vehicle hasn't moved, issue an event with 0 emissions. This way there is an event for every timestep diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VisumHbefaRoadTypeMapping.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VisumHbefaRoadTypeMapping.java index e822003f09f..1fce8b282cb 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VisumHbefaRoadTypeMapping.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VisumHbefaRoadTypeMapping.java @@ -46,7 +46,7 @@ private VisumHbefaRoadTypeMapping() { } @Override - public String determineHebfaType(Link link) { + public String determineHbefaType(Link link) { String roadType = NetworkUtils.getType(link); return mapping.get(roadType); } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMapping.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMapping.java index 12fb81ea572..8a990e6d5ab 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMapping.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMapping.java @@ -13,7 +13,7 @@ public VspHbefaRoadTypeMapping() { } @Override - protected String determineHebfaType(Link link) { + protected String determineHbefaType(Link link) { var freespeed = link.getFreespeed() <= 13.888889 ? link.getFreespeed() * 2 : link.getFreespeed(); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java index ff055cf31fd..8eff2d52a29 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionAnalysisModule.java @@ -63,10 +63,6 @@ public final class WarmEmissionAnalysisModule implements LinkEmissionsCalculator private int detailedFallbackAverageTableWarnCnt = 0; private int averageReadingInfoCnt = 0; - // The following was tested to slow down significantly, therefore counters were commented out: -// Set vehAttributesNotSpecified = Collections.synchronizedSet(new HashSet()); -// Set vehicleIdSet = Collections.synchronizedSet(new HashSet()); - private int freeFlowCounter = 0; private int saturatedCounter = 0; private int heavyFlowCounter = 0; @@ -104,7 +100,7 @@ public WarmEmissionAnalysisModule( // The following tests if the detailed table is consistent, i.e. if there exist all combinations of entries. There used to be some test // cases where this was deliberately not the case, implying that this was assumed as plausible also for studies. This is now forbidding it. // If this causes too many problems, we could insert a switch (or attach it to the fallback behavior switch). kai, feb'20 - // Eventually vehicle category and vehicle attribute should be alligned in order to make the allCombinations setting useful + // Eventually vehicle category and vehicle attribute should be aligned in order to make the allCombinations setting useful // see discussion in https://github.com/matsim-org/matsim-libs/issues/1226 kturner, nov'20 Set roadCategories = new HashSet<>(); Set trafficSituations = EnumSet.noneOf(HbefaTrafficSituation.class); @@ -149,7 +145,7 @@ public WarmEmissionAnalysisModule( // conditions exist for a certain lookup. So we could still have some road categories, vehicle categories or vehicle attributes // where some detailed values exist and others don't. So the thing to check would be if for each existing // roadCategory x vehicleCategory x vehicleAttribute x pollutant - // there is a freeflow and a stopgo entry. Maybe something like this here: + // there is a freeflow and a stop-go entry. Maybe something like this here: Set freeflowSet = new HashSet<>(); Set stopgoSet = new HashSet<>(); for (HbefaWarmEmissionFactorKey key : detailedHbefaWarmTable.keySet()) { @@ -275,7 +271,7 @@ Map calculateWarmEmissions(double travelTime_sec, String road } if ((averageSpeed_kmh - freeVelocity_ms * 3.6) > 1.0){ if (ecg.getHandleHighAverageSpeeds()) { - logger.warn("averageSpeed was capped from " + averageSpeed_kmh + " to" + freeVelocity_ms * 3.6 ); + logger.warn("averageSpeed was capped from {} to{}", averageSpeed_kmh, freeVelocity_ms * 3.6); averageSpeed_kmh = freeVelocity_ms * 3.6; } else { throw new RuntimeException("Average speed has been calculated to be greater than free flow speed; this might produce negative warm emissions. Aborting..."); @@ -307,7 +303,7 @@ Map calculateWarmEmissions(double travelTime_sec, String road // compute emissions from stop-go fraction: efkey.setTrafficSituation(STOPANDGO); efStopGo_gpkm = getEf(vehicleInformationTuple, efkey).getFactor(); - logger.debug("pollutant=" + warmPollutant + "; efStopGo=" + efStopGo_gpkm); + logger.debug("pollutant={}; efStopGo={}", warmPollutant, efStopGo_gpkm); } @@ -316,7 +312,7 @@ Map calculateWarmEmissions(double travelTime_sec, String road // compute emissions for free-flow fraction: efkey.setTrafficSituation(FREEFLOW); efFreeFlow_gpkm = getEf(vehicleInformationTuple, efkey).getFactor(); - logger.debug("pollutant=" + warmPollutant + "; efFreeFlow=" + efFreeFlow_gpkm); + logger.debug("pollutant={}; efFreeFlow={}", warmPollutant, efFreeFlow_gpkm); } // sum them up: @@ -334,7 +330,7 @@ Map calculateWarmEmissions(double travelTime_sec, String road } // update counters: - // yy I don't now what this is good for; I would base downstream analysis rather on events. kai, jan'20 + // yy I don't know what this is good for; I would base downstream analysis rather on events. kai, jan'20 if (ecg.getEmissionsComputationMethod() == StopAndGoFraction) { incrementCountersFractional( linkLength_m / 1000, fractionStopGo ); } @@ -379,7 +375,7 @@ private HbefaWarmEmissionFactor getEf(Tuple; average; average'" ); logger.warn( Gbl.ONLYONCE ); logger.warn( Gbl.FUTURE_SUPPRESSED ); @@ -444,7 +440,7 @@ private HbefaWarmEmissionFactor getEf(Tuple; average; average" should, I think, just be entered as such. kai, feb'20 @@ -462,7 +458,7 @@ private HbefaWarmEmissionFactor getEf(Tuple; average; average'" ); logger.warn( Gbl.ONLYONCE ); logger.warn( Gbl.FUTURE_SUPPRESSED ); @@ -496,7 +492,7 @@ private HbefaWarmEmissionFactor getEf(Tuple; average; average" should, I think, just be entered as such. kai, feb'20 @@ -513,7 +509,7 @@ private HbefaWarmEmissionFactor getEf(Tuple list = new ArrayList<>( this.avgHbefaWarmTable.keySet() ); list.sort( Comparator.comparing( HbefaWarmEmissionFactorKey::toString ) ); for ( HbefaWarmEmissionFactorKey key : list ) { @@ -556,7 +552,7 @@ private HbefaTrafficSituation getTrafficSituation(HbefaWarmEmissionFactorKey efk HbefaRoadVehicleCategoryKey hbefaRoadVehicleCategoryKey = new HbefaRoadVehicleCategoryKey(efkey); Map trafficSpeeds = this.hbefaRoadTrafficSpeeds.get(hbefaRoadVehicleCategoryKey); - //TODO: Hier die Berechunung einfügen, die die trafficSpeedTabelle entsprechend aus den Werten erstellt? + //TODO: Hier die Berechnung einfügen, die die trafficSpeedTabelle entsprechend aus den Werten erstellt? //Frage Laufzeit: Einmal berechnen ha if (trafficSpeeds == null || !trafficSpeeds.containsKey(FREEFLOW)) { @@ -576,7 +572,7 @@ private HbefaTrafficSituation getTrafficSituation(HbefaWarmEmissionFactorKey efk trafficSituation = STOPANDGO; } } - /*FIXME The following lines should be added to account for the HBEFA 4.1's additiona traffic situation, + /*FIXME The following lines should be added to account for the HBEFA 4.1's additional traffic situation, but it currently causes a test failure (jwj, Nov'20) */ // if (trafficSpeeds.containsKey(STOPANDGO_HEAVY) && averageSpeed_kmh <= trafficSpeeds.get(STOPANDGO_HEAVY)) { // if (averageSpeed_kmh != trafficSpeeds.get(FREEFLOW)) { //handle case testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent6 @@ -593,8 +589,8 @@ private void incrementCountersFractional(double linkLength_km, double fractionSt freeFlowKmCounter += linkLength_km * (1-fractionStopGo); stopGoKmCounter += linkLength_km * fractionStopGo; - freeFlowCounter += 1-fractionStopGo; - stopGoCounter += fractionStopGo; + freeFlowCounter += (int) (1-fractionStopGo); + stopGoCounter += (int) fractionStopGo; fractionCounter += (fractionStopGo < 1.0 && fractionStopGo > 0.0) ? 1 : 0; } @@ -626,7 +622,7 @@ private void incrementCountersAverage(HbefaTrafficSituation hbefaTrafficSituatio } } - //------ These (occurrences) seem do be used only for logging statements and tests. KMT/GR Jul'20 + //------ These (occurrences) seem to be used only for logging statements and tests. KMT/GR Jul'20 /*package-private*/ int getFreeFlowOccurences() { return freeFlowCounter; } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionHandler.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionHandler.java index 8213320fdff..03a57d63b17 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionHandler.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/WarmEmissionHandler.java @@ -123,12 +123,10 @@ public void handleEvent(VehicleLeavesTrafficEvent event) { handleNullVehicle(vehicleId); } } else if ( this.vehicleEntersTrafficMap.containsKey( vehicleId ) ) { - logger.warn("At time " + event.getTime() + ", vehicle " + event.getVehicleId() + " enters and leaves traffic without" + - " having entered link " + event.getLinkId() + ". Thus, no emissions are calculated for travel along this link."); + logger.warn("At time {}, vehicle {} enters and leaves traffic without having entered link {}. Thus, no emissions are calculated for travel along this link.", event.getTime(), event.getVehicleId(), event.getLinkId()); sameLinkTrafficLeaveWarnCnt++; } else { - logger.warn("At time " + event.getTime() + ", vehicle " + event.getVehicleId() + " left traffic without entering traffic " + - "or ANY link. Thus, no emissions are calculated for this unusual event."); + logger.warn("At time {}, vehicle {} left traffic without entering traffic or ANY link. Thus, no emissions are calculated for this unusual event.", event.getTime(), event.getVehicleId()); unusualTrafficLeaveWarnCnt++; } } @@ -191,7 +189,7 @@ private void emissionsCalculation(Id vehicleId, Vehicle vehicle, Link l private boolean linkLengthIsZero( Id linkId, double linkLength) { if (linkLength == 0.) { if (zeroLinkLengthWarnCnt == 0) { - logger.warn("Length of the link " + linkId + " is zero. No emissions will be estimated for this link. Make sure that this is intentional."); + logger.warn("Length of the link {} is zero. No emissions will be estimated for this link. Make sure that this is intentional.", linkId); logger.warn(Gbl.ONLYONCE); zeroLinkLengthWarnCnt++; } @@ -211,8 +209,7 @@ private void handleNullVehicle(Id vehicleId) { + " Aborting..."); } else if (this.warmEmissionAnalysisModule.getEcg().getNonScenarioVehicles().equals(NonScenarioVehicles.ignore)) { if (noVehWarnCnt < 10) { - logger.warn( - "No vehicle defined for id " + vehicleId + ". The vehicle will be ignored."); + logger.warn("No vehicle defined for id {}. The vehicle will be ignored.", vehicleId); noVehWarnCnt++; if (noVehWarnCnt == 10) logger.warn(Gbl.FUTURE_SUPPRESSED); } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzer.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzer.java index 1454c799a48..42003c91ffb 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzer.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzer.java @@ -57,7 +57,7 @@ /** * This class may be used to collect emission events of some events file and assign those emissions to a grid structure. - * Additionally those emissions are divided into time bins + * Additionally, those emissions are divided into time bins */ public class EmissionGridAnalyzer { @@ -106,7 +106,7 @@ public TimeBinMap>> process(String eventsFile) { logger.info("Starting grid computation..."); for (var bin : timeBinsWithEmissions.getTimeBins()) { - logger.info("creating grid for time bin with start time: " + bin.getStartTime()); + logger.info("creating grid for time bin with start time: {}", bin.getStartTime()); Grid> grid = writeAllLinksToGrid(bin.getValue()); result.getTimeBin(bin.getStartTime()).setValue(grid); } @@ -153,7 +153,7 @@ public Tuple processNextTimeBin() { if (!this.timeBins.hasNext()) throw new RuntimeException("processNextTimeBin() was called too many times"); TimeBinMap.TimeBin, EmissionsByPollutant>> nextBin = this.timeBins.next(); - logger.info("creating grid for time bin with start time: " + nextBin.getStartTime()); + logger.info("creating grid for time bin with start time: {}", nextBin.getStartTime()); Grid> grid = writeAllLinksToGrid(nextBin.getValue()); @@ -224,7 +224,7 @@ private Grid> writeAllLinksToGrid(Map, Emissions .forEach(entry -> { var count = counter.incrementAndGet(); if (count % 10000 == 0) - logger.info("processing: " + count * 100 / linksWithEmissions.keySet().size() + "% done"); + logger.info("processing: {}% done", count * 100 / linksWithEmissions.keySet().size()); if (network.getLinks().containsKey(entry.getKey()) && isWithinBounds(network.getLinks().get(entry.getKey()))) { processLink(network.getLinks().get(entry.getKey()), entry.getValue(), grid); @@ -316,7 +316,7 @@ public Builder withTimeBinSize(double size) { /** * Sets the used grid type. Default is Square * - * @param type The grid type. Currently either Square or Hexagonal + * @param type The grid type. Currently, either Square or Hexagonal * @return {@link org.matsim.contrib.emissions.analysis.EmissionGridAnalyzer.Builder} */ public Builder withGridType(GridType type) { diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutant.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutant.java index 6b1eda64b73..167bc09caf8 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutant.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutant.java @@ -24,7 +24,6 @@ import org.matsim.contrib.emissions.Pollutant; -import java.util.HashMap; import java.util.Map; /** diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java index b036c3d9f72..347fe2bb3eb 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/FastEmissionGridAnalyzer.java @@ -54,13 +54,13 @@ public abstract class FastEmissionGridAnalyzer { * 2. The aggregated emissions for each link are rastered onto all the raster-cells covered by the link. * 3. In the smoothing step the emissions are blurred onto the surrounding raster-cells. *

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

* If only a certain area of the scenario is of interest for the analysis. The supplied network must be filtered beforehand. * The resulting raster's size depends on the bounding box of the supplied network. *

- * Note: The algorithm is not accurate at the edges of the raster. The kernel is cut of a the edges meaning that emissions - * are underestimated at the edges of the raster. I didn't bother to implement this correctly. Otherwise the overall + * Note: The algorithm is not accurate at the edges of the raster. The kernel is cut of the edges meaning that emissions + * are underestimated at the edges of the raster. I didn't bother to implement this correctly. Otherwise, the overall * amount of emissions doesn't change. * * @param eventsFile The events file which contains the emission events @@ -92,7 +92,7 @@ public static Map processEventsFile(final String eventsFile, logger.info("Start smoothing pollution."); return linkEmissionsByPollutant.entrySet().stream() .map(entry -> { - logger.info("Smoothing of: " + entry.getKey()); + logger.info("Smoothing of: {}", entry.getKey()); return Tuple.of(entry.getKey(), processLinkEmissions(entry.getValue(), network, cellSize, radius)); }) .collect(Collectors.toMap(Tuple::getFirst, Tuple::getSecond)); @@ -116,7 +116,7 @@ public static Map processHandlerEmissions(Map, Map

{ - logger.info("Smoothing of: " + entry.getKey()); + logger.info("Smoothing of: {}", entry.getKey()); return Tuple.of(entry.getKey(), processLinkEmissions(entry.getValue(), network, cellSize, radius)); }) .collect(Collectors.toMap(Tuple::getFirst, Tuple::getSecond)); @@ -192,7 +192,7 @@ public static Raster processLinkEmissions(final Map, Double> emissions, static Raster blur(Raster raster, int radius) { - logger.info("Creating Kernel with " + (radius * 2 + 1) + " taps"); + logger.info("Creating Kernel with {} taps", radius * 2 + 1); var kernel = createKernel(radius * 2 + 1); var result = new Raster(raster.getBounds(), raster.getCellSize()); @@ -279,7 +279,7 @@ static Raster rasterizeNetwork(Network network, Map, Double> emissions, * Rasterizes links into squares. Uses Bresenham's line drawing algorithm, which is supposed to be fast * Maybe the result is too chunky, but it'll do as a first try * - * @param link Matsim network link + * @param link MATSim network link * @return number of cells the link is rastered to */ private static int rasterizeLink(Link link, double value, Raster raster) { diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReader.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReader.java index ff962f67cff..811c3d49181 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReader.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReader.java @@ -57,7 +57,7 @@ class RawEmissionEventsReader extends MatsimXmlParser { RawEmissionEventsReader(HandleEmissionEvent handler) { super(ValidationType.NO_VALIDATION); this.handler = handler; - // events don't have dtd. Therefore validation is not possible + // events don't have dtd. Therefore, validation is not possible this.setValidating(false); } @@ -103,7 +103,7 @@ private void handleEmissionEvent(Attributes atts) { // give some feedback about progress var currentCount = eventsCounter.incrementAndGet(); if (currentCount % 500000 == 0) { - logger.info("Emission Event # " + numberFormat.format(currentCount)); + logger.info("Emission Event # {}", numberFormat.format(currentCount)); } } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/ColdEmissionEvent.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/ColdEmissionEvent.java index e658817da12..fe184d1ce2b 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/ColdEmissionEvent.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/ColdEmissionEvent.java @@ -20,13 +20,11 @@ package org.matsim.contrib.emissions.events; import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.Pollutant; import org.matsim.vehicles.Vehicle; import java.util.Map; -import java.util.Map.Entry; /** diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEvent.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEvent.java index 32a5221e27c..ae7c9c59e2a 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEvent.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEvent.java @@ -23,7 +23,6 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.Event; -import org.matsim.api.core.v01.events.HasLinkId; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.Pollutant; import org.matsim.vehicles.Vehicle; diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java index c9c21926ef9..11f73caf526 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/EmissionEventsReader.java @@ -40,7 +40,7 @@ public final class EmissionEventsReader implements MatsimReader { // leave this public so that external code can generate "standard" emission events. MATSIM-893 - private MatsimEventsReader delegate ; + private final MatsimEventsReader delegate ; public EmissionEventsReader( EventsManager events ){ this.delegate = new MatsimEventsReader(events); @@ -59,20 +59,24 @@ public EmissionEventsReader( EventsManager events ){ // the loop is necessary since we do now know which pollutants are in the event. for (Map.Entry entry : attributes.entrySet()) { - if( "time".equals( entry.getKey() ) ){ - time = Double.parseDouble( entry.getValue() ); - } else if( "type".equals( entry.getKey() ) ){ - // I don't think that we are doing anything here. kai, jan'19 - } else if( WarmEmissionEvent.ATTRIBUTE_LINK_ID.equals( entry.getKey() ) ){ - linkId = Id.createLinkId( entry.getValue() ); - } else if (WarmEmissionEvent.ATTRIBUTE_VEHICLE_ID.equals(entry.getKey())) { - vehicleId = Id.createVehicleId(entry.getValue()); - } else { - String pollutant = entry.getKey().equals("NOX") ? - "NOx" : - entry.getKey(); // the previous versions would write NOX instead of NOx - Double value = Double.parseDouble(entry.getValue()); - warmEmissions.put(Pollutant.valueOf(pollutant), value); + switch (entry.getKey()) { + case "time" -> time = Double.parseDouble(entry.getValue()); + case "type" -> { + // I don't think that we are doing anything here. kai, jan'19 + } + case WarmEmissionEvent.ATTRIBUTE_LINK_ID -> linkId = Id.createLinkId(entry.getValue()); + case WarmEmissionEvent.ATTRIBUTE_VEHICLE_ID -> vehicleId = Id.createVehicleId(entry.getValue()); + case null, default -> { + String pollutant = null; // the previous versions would write NOX instead of NOx + if (entry.getKey() != null) { + pollutant = entry.getKey().equals("NOX") ? + "NOx" : + entry.getKey(); + } + + Double value = Double.parseDouble(entry.getValue()); + warmEmissions.put(Pollutant.valueOf(pollutant), value); + } } } @@ -91,20 +95,24 @@ public EmissionEventsReader( EventsManager events ){ // the loop is necessary since we do now know which pollutants are in the event. for (Map.Entry entry : attributes.entrySet()) { - if( "time".equals( entry.getKey() ) ){ - time = Double.parseDouble( entry.getValue() ); - } else if( "type".equals( entry.getKey() ) ){ - // do nothing - } else if( ColdEmissionEvent.ATTRIBUTE_LINK_ID.equals( entry.getKey() ) ){ - linkId = Id.createLinkId( entry.getValue() ); - } else if (ColdEmissionEvent.ATTRIBUTE_VEHICLE_ID.equals(entry.getKey())) { - vehicleId = Id.createVehicleId(entry.getValue()); - } else { - String pollutant = entry.getKey().equals("NOX") ? - "NOx" : - entry.getKey(); // the previous versions would write NOX instead of NOx - Double value = Double.parseDouble(entry.getValue()); - coldEmissions.put(Pollutant.valueOf(pollutant), value); + switch (entry.getKey()) { + case "time" -> time = Double.parseDouble(entry.getValue()); + case "type" -> { + // do nothing + } + case ColdEmissionEvent.ATTRIBUTE_LINK_ID -> linkId = Id.createLinkId(entry.getValue()); + case ColdEmissionEvent.ATTRIBUTE_VEHICLE_ID -> vehicleId = Id.createVehicleId(entry.getValue()); + case null, default -> { + String pollutant = null; // the previous versions would write NOX instead of NOx + if (entry.getKey() != null) { + pollutant = entry.getKey().equals("NOX") ? + "NOx" : + entry.getKey(); + } + + Double value = Double.parseDouble(entry.getValue()); + coldEmissions.put(Pollutant.valueOf(pollutant), value); + } } } return new ColdEmissionEvent(time, linkId, vehicleId, coldEmissions); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/WarmEmissionEvent.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/WarmEmissionEvent.java index b0504f880ed..02eeb1daaf5 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/WarmEmissionEvent.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/events/WarmEmissionEvent.java @@ -20,13 +20,11 @@ package org.matsim.contrib.emissions.events; import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.Pollutant; import org.matsim.vehicles.Vehicle; import java.util.Map; -import java.util.Map.Entry; /** diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java index f50fc6a6d27..ee492e3bb25 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/CreateEmissionConfig.java @@ -32,7 +32,7 @@ * * Creates a config file * with necessary emission input files for the {@link EmissionsConfigGroup EmissionsConfigGroup}. - * + *

* This config file is used by the {@link RunDetailedEmissionToolOfflineExample OfflineExample} and * the {@link RunDetailedEmissionToolOnlineExample OnlineExample} * @@ -119,13 +119,7 @@ public static void main(String[] args) { // emission vehicles are now set in the default vehicle container config.vehicles().setVehiclesFile(emissionVehicleFile); - if ( (Boolean) false ==null ) { - ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.asEngineInformationAttributes ); - } else if ( false ) { - ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.usingVehicleTypeId ); - } else { - ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.fromVehicleTypeDescription ); - } + ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.fromVehicleTypeDescription ); ecg.setAverageWarmEmissionFactorsFile(averageFleetWarmEmissionFactorsFile); ecg.setAverageColdEmissionFactorsFile(averageFleetColdEmissionFactorsFile); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java index bd1af3c2a90..c1f344dc331 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunAverageEmissionToolOfflineExample.java @@ -49,7 +49,7 @@ public final class RunAverageEmissionToolOfflineExample{ public static final String emissionEventsFilename = "emission.events.offline.xml.gz"; - // (remove dependency of one test/execution path from other. kai/ihab, nov'18) + // (remove dependency of one test/execution path from others. kai/ihab, nov'18) private Config config; @@ -60,14 +60,10 @@ public static void main (String[] args){ emissionToolOfflineExampleV2.run(); } -// public Config prepareConfig() { -// config = ConfigUtils.loadConfig(configFile, new EmissionsConfigGroup()); -// return config; -// } - public Config prepareConfig(String args){ throw new RuntimeException("execution path no longer exists"); } + public Config prepareConfig(String [] args) { config = ConfigUtils.loadConfig(args, new EmissionsConfigGroup()); EmissionsConfigGroup ecg = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); @@ -96,7 +92,7 @@ public void install(){ bind( EmissionModule.class ) ; // bind( OutputDirectoryHierarchy.class ); } - };; + }; com.google.inject.Injector injector = Injector.createInjector(config, module ); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java index 191766556c2..83d4499706a 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExample.java @@ -48,7 +48,7 @@ public final class RunDetailedEmissionToolOfflineExample{ // private static final String configFile = "./scenarios/sampleScenario/testv2_Vehv1/config_detailed.xml"; // private static final String eventsFile = "./scenarios/sampleScenario/5.events.xml.gz"; - // (remove dependency of one test/execution path from other. kai/ihab, nov'18) + // (remove dependency of one test/execution path from others. kai/ihab, nov'18) // private static final String emissionEventOutputFileName = "5.emission.events.offline.xml.gz"; private Config config; @@ -60,11 +60,6 @@ public static void main (String[] args){ emissionToolOfflineExampleV2Vehv1.run(); } -// public Config prepareConfig() { -// config = ConfigUtils.loadConfig(configFile, new EmissionsConfigGroup()); -// return config; -// } - public Config prepareConfig(String [] args) { config = ConfigUtils.loadConfig(args, new EmissionsConfigGroup()); return config; @@ -89,7 +84,7 @@ public void install(){ bind( EventsManager.class ).toInstance( eventsManager ); bind( EmissionModule.class ) ; } - };; + }; com.google.inject.Injector injector = Injector.createInjector(config, module ); diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExample.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExample.java index 32708f736ea..d0518b73dc1 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExample.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExample.java @@ -29,8 +29,8 @@ import org.matsim.core.scenario.ScenarioUtils; /** - * - * After creating a config file with + * + * After creating a config file with * {@link CreateEmissionConfig CreateEmissionConfig} * this class runs a simulation and calculates emissions online. * Results are written into events file (including emission events) for some iterations (as specified by the config). @@ -55,23 +55,6 @@ public static Config prepareConfig( String[] args ) { return config; } - public static Scenario prepareScenario( Config config ) { - Scenario scenario = ScenarioUtils.loadScenario( config ); - - //load emissions config -// EmissionsConfigGroup emissionsConfigGroup = (EmissionsConfigGroup) config.getModules().get(EmissionsConfigGroup.GROUP_NAME); -// URL context = scenario.getConfig().getContext(); -// URL mappingFile = emissionsConfigGroup.getEmissionRoadTypeMappingFileURL(context); - - //add Hbefa mappings to the network -// HbefaRoadTypeMapping vhtm = VisumHbefaRoadTypeMapping.createVisumRoadTypeMapping(mappingFile); -// vhtm.addHbefaMappings(scenario.getNetwork()); - - // no need for the mapping file; hbefa mappings were directly written into the link attributes. ihab nov '18 - - return scenario ; - } - public static void run( Scenario scenario, AbstractModule... modules ) { Controler controler = new Controler(scenario); controler.addOverridingModule(new AbstractModule() { @@ -87,7 +70,8 @@ public void install() { } public static void main(String[] args) { Config config = prepareConfig( args ) ; - Scenario scenario = prepareScenario( config ) ; + + Scenario scenario = ScenarioUtils.loadScenario(config); run( scenario ) ; } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/package-info.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/package-info.java index 95bfb7b8b85..811d521cb60 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/package-info.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/package-info.java @@ -14,7 +14,7 @@ * *

Export from HBEFA 3.x

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

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

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

        Model description

        - * + * *

        Emissions

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

        - * + * * @author benjamin, julia */ diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java index 7a5e1a1ada1..ce87ab17cb0 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionWriter.java @@ -42,39 +42,39 @@ public final class EmissionWriter { // is this useful as a publicly available class? kai, jan'19 private static final Logger logger = LogManager.getLogger(EmissionWriter.class); - + public EmissionWriter(){ } - + public void writeHomeLocation2TotalEmissions( Population population, Map, SortedMap> totalEmissions, Collection pollutants, String outFile) { try{ - FileWriter fstream = new FileWriter(outFile); + FileWriter fstream = new FileWriter(outFile); BufferedWriter out = new BufferedWriter(fstream); out.append("personId \t xHome \t yHome \t"); for (String pollutant : pollutants){ - out.append(pollutant + "[g] \t"); + out.append(pollutant).append("[g] \t"); } out.append("\n"); for(Person person: population.getPersons().values()){ Id personId = person.getId(); Plan plan = person.getSelectedPlan(); - Activity homeAct = (Activity) plan.getPlanElements().get(0); + Activity homeAct = (Activity) plan.getPlanElements().getFirst(); Coord homeCoord = homeAct.getCoord(); Double xHome = homeCoord.getX(); Double yHome = homeCoord.getY(); - out.append(personId + "\t" + xHome + "\t" + yHome + "\t"); + out.append(String.valueOf(personId)).append("\t").append(String.valueOf(xHome)).append("\t").append(String.valueOf(yHome)).append("\t"); Map emissionType2Value = totalEmissions.get(personId); for(String pollutant : pollutants){ if(emissionType2Value.get(pollutant) != null){ - out.append(emissionType2Value.get(pollutant) + "\t"); + out.append(String.valueOf(emissionType2Value.get(pollutant))).append("\t"); } else{ out.append("0.0" + "\t"); // TODO: do I still need this? } @@ -83,7 +83,7 @@ public void writeHomeLocation2TotalEmissions( } //Close the output stream out.close(); - logger.info("Finished writing output to " + outFile); + logger.info("Finished writing output to {}", outFile); } catch (Exception e){ throw new RuntimeException(e); } diff --git a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java index f7107ece5f0..cc958dc1a04 100644 --- a/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java +++ b/contribs/emissions/src/main/java/org/matsim/contrib/emissions/utils/EmissionsConfigGroup.java @@ -82,7 +82,7 @@ public enum HbefaTableConsistencyCheckingLevel { allCombinations, consistent, no private static final String EMISSION_FACTORS_COLD_FILE_DETAILED_CMT = "file with HBEFA detailed cold emission factors"; private static final String HBEFA_TABLE_CONSISTENCY_CHECKING_LEVEL_CMT = "Define on which level the entries in the provided hbefa tables are checked for consistency" + "\n\t\t\t" + HbefaTableConsistencyCheckingLevel.allCombinations.name() + " : check if entries for all combinations of HbefaTrafficSituation, HbefaVehicleCategory, HbefaVehicleAttributes, HbefaComponent. " + - "are available in the table. It only checks for paramters that are available in the table (e.g. if there is no HGV in the table, it can also pass. \n\t\t\t" + + "are available in the table. It only checks for parameters that are available in the table (e.g. if there is no HGV in the table, it can also pass. \n\t\t\t" + HbefaTableConsistencyCheckingLevel.consistent.name() + " : check if the entries for the two HbefaTrafficSituations 'StopAndGo' and 'FreeFlow' (nov 2020, may be subject to change) are consistently available in the table. \n\t\t\t" + //TODO HbefaTableConsistencyCheckingLevel.none.name() + " : There is no consistency check. This option is NOT recommended and only for backward capability to inputs from before spring 2020 . \n\t\t\t" + "Default is " + HbefaTableConsistencyCheckingLevel.allCombinations.name(); @@ -187,7 +187,6 @@ public DetailedVsAverageLookupBehavior getDetailedVsAverageLookupBehavior() { // =============== /** * @param hbefaTableConsistencyCheckingLevel -- {@value #HBEFA_TABLE_CONSISTENCY_CHECKING_LEVEL} - * @noinspection JavadocReference */ @StringSetter(HBEFA_TABLE_CONSISTENCY_CHECKING_LEVEL) public void setHbefaTableConsistencyCheckingLevel(HbefaTableConsistencyCheckingLevel hbefaTableConsistencyCheckingLevel) { @@ -318,12 +317,8 @@ public void setEmissionsComputationMethod(EmissionsComputationMethod emissionsCo @Override protected final void checkConsistency(Config config){ switch( this.emissionsComputationMethod ){ - case StopAndGoFraction -> log.info( "Please note that with setting of emissionsComputationMethod " + EmissionsComputationMethod.StopAndGoFraction + "" + - " the emission factors for both freeFlow and StopAndGo fractions are looked up independently and are " + - "therefore following the fallback behaviour set in " + DETAILED_VS_AVERAGE_LOOKUP_BEHAVIOR + - " independently. --> Depending on the input, it may be that e.g. for ff the detailed value is taken, while for the stopAndGo part " + - "a less detailed value is used, because the value with the same level of detail is missing." ); - case AverageSpeed -> log.warn( "This setting of emissionsComputationMethod. " + EmissionsComputationMethod.AverageSpeed + " is not covered by many test cases." ); + case StopAndGoFraction -> log.info("Please note that with setting of emissionsComputationMethod {} the emission factors for both freeFlow and StopAndGo fractions are looked up independently and are therefore following the fallback behaviour set in " + DETAILED_VS_AVERAGE_LOOKUP_BEHAVIOR + " independently. --> Depending on the input, it may be that e.g. for ff the detailed value is taken, while for the stopAndGo part a less detailed value is used, because the value with the same level of detail is missing.", EmissionsComputationMethod.StopAndGoFraction); + case AverageSpeed -> log.warn("This setting of emissionsComputationMethod. {} is not covered by many test cases.", EmissionsComputationMethod.AverageSpeed); default -> throw new IllegalStateException( "Unexpected value: " + this.emissionsComputationMethod ); } } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/OsmHbefaMappingTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/OsmHbefaMappingTest.java index 195fc6e6fcb..10aff1cbe2a 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/OsmHbefaMappingTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/OsmHbefaMappingTest.java @@ -16,7 +16,7 @@ void testRegularMapping() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("primary", 70 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Trunk-City/70", hbefaType); } @@ -27,7 +27,7 @@ void testMergedLinkTypeMapping() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("primary|railway.tram", 70 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Trunk-City/70", hbefaType); } @@ -39,7 +39,7 @@ void testUnknownType() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("unknown-tag", 100 / 3.6); - mapping.determineHebfaType(link); + mapping.determineHbefaType(link); fail("Expected Runtime Exception."); }); @@ -51,7 +51,7 @@ void testFastMotorway() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("motorway", 100 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/MW-Nat./100", hbefaType); } @@ -62,11 +62,11 @@ void testMotorwayWithNoExactSpeedTag() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("motorway", 100.11 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/MW-Nat./100", hbefaType); link = getTestLink("motorway", 86.11 / 3.6); - hbefaType = mapping.determineHebfaType(link); + hbefaType = mapping.determineHbefaType(link); assertEquals("URB/MW-Nat./90", hbefaType); } @@ -77,7 +77,7 @@ void testFastMotorwayLink() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("motorway_link", 100 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/MW-Nat./100", hbefaType); } @@ -87,7 +87,7 @@ void testLivingStreet() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("living_street", 50 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Access/50", hbefaType); } @@ -98,7 +98,7 @@ void testUnclassified() { var mapping = OsmHbefaMapping.build(); var link = getTestLink("unclassified", 50 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Access/50", hbefaType); } @@ -109,7 +109,7 @@ void testNoHighwayType() { var mapping = OsmHbefaMapping.build(); var link = getTestLink(" ", 60 / 3.6); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Local/60", hbefaType); } @@ -121,7 +121,7 @@ void testNoAllowedSpeedTag() { var link = getTestLink("residential", 40 / 3.6); link.getAttributes().removeAttribute(NetworkUtils.ALLOWED_SPEED); - var hbefaType = mapping.determineHebfaType(link); + var hbefaType = mapping.determineHbefaType(link); assertEquals("URB/Access/40", hbefaType); } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModule.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModule.java index d5d32b96239..aa01f57e02d 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModule.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModule.java @@ -20,7 +20,6 @@ package org.matsim.contrib.emissions; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.matsim.api.core.v01.Id; @@ -88,7 +87,7 @@ public class TestColdEmissionAnalysisModule { private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - // emission factors for tables - no dublicates! + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java index 690ee4ed802..57aae0aee49 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase1.java @@ -92,7 +92,7 @@ public class TestColdEmissionAnalysisModuleCase1 { private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - // emission factors for tables - no dublicates! + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; @@ -107,18 +107,18 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { // first case: complete data // corresponding entry in average table Collections.addAll(testCase1, "PASSENGER_CAR", petrol_technology, none_sizeClass, none_emConcept, averagePetrolFactor); - logger.info("Running testcase:" + testCase1.toString()); + logger.info("Running testcase:{}", testCase1); Id linkId = Id.create("linkId" + testCase1, Link.class); Id vehicleId = Id.create("vehicleId" + testCase1, Vehicle.class); Id vehicleTypeId = Id.create(testCase1.get(0) + ";" + testCase1.get(1) + ";" + testCase1.get(2) + ";" + testCase1.get(3), VehicleType.class); Vehicle vehicle = VehicleUtils.getFactory().createVehicle(vehicleId, VehicleUtils.getFactory().createVehicleType(vehicleTypeId)); - logger.info("VehicleId: " + vehicle.getId().toString()); - logger.info("VehicleTypeId: " + vehicle.getType().getId()); + logger.info("VehicleId: {}", vehicle.getId().toString()); + logger.info("VehicleTypeId: {}", vehicle.getType().getId()); final Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); - String message = "The expected emissions for " + testCase1.toString() + " are " + pollutants.size() * (Double) testCase1.get(4) + " but were " + sumOfEmissions; + String message = "The expected emissions for " + testCase1 + " are " + pollutants.size() * (Double) testCase1.get(4) + " but were " + sumOfEmissions; Assertions.assertEquals(pollutants.size() * (Double) testCase1.get(4), sumOfEmissions, MatsimTestUtils.EPSILON, message); } @@ -135,7 +135,7 @@ private static ColdEmissionAnalysisModule setUp() { // This represents the previous behavior, which fallbacks to the average table, // if values are not found in the detailed table, kmt apr'20 - // This test seems to refer to an direct lookup in average table + // This test seems to refer to a direct lookup in average table ecg.setDetailedVsAverageLookupBehavior(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); return new ColdEmissionAnalysisModule(avgHbefaColdTable, detailedHbefaColdTable, ecg, pollutants, emissionEventManager); } @@ -227,5 +227,5 @@ private static void putIntoHbefaColdTable( detailedHbefaColdTable.put(detColdKey, detColdFactor); } } - + } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java index c97de7d7ecd..eba88366726 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestColdEmissionAnalysisModuleCase2.java @@ -70,7 +70,7 @@ public class TestColdEmissionAnalysisModuleCase2 { // The material below was confused in the way that strings like "petrol" or "diesel" were given for the // size classes, and "<1,4L" or ">=2L" for the emissions concept. Tried to make it consistent, // but I don't know if it is still testing the original functionality. kai, jul'18 - + // first case: complete data - corresponding entry in average table private static final String petrol_technology = "petrol"; private static final String none_sizeClass = "average"; @@ -84,7 +84,7 @@ public class TestColdEmissionAnalysisModuleCase2 { private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - // emission factors for tables - no dublicates! + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; @@ -105,13 +105,13 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { Id vehicleId = Id.create( "vehicleId" + testCase2 , Vehicle.class ); Id vehicleTypeId = Id.create( testCase2.get( 0 ) + ";" + testCase2.get( 1 ) + ";" + testCase2.get( 2 ) + ";" + testCase2.get( 3 ), VehicleType.class ); Vehicle vehicle = VehicleUtils.getFactory().createVehicle( vehicleId, VehicleUtils.getFactory().createVehicleType( vehicleTypeId ) ); - logger.info("VehicleId: " + vehicle.getId().toString()); - logger.info("VehicleTypeId: " + vehicle.getType().getId()); + logger.info("VehicleId: {}", vehicle.getId().toString()); + logger.info("VehicleTypeId: {}", vehicle.getType().getId()); Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); - - String message = "The expected emissions for " + testCase2.toString() + " are " + pollutants.size() * (Double) testCase2.get( 4 ) + " but were " + sumOfEmissions; + + String message = "The expected emissions for " + testCase2 + " are " + pollutants.size() * (Double) testCase2.get( 4 ) + " but were " + sumOfEmissions; Assertions.assertEquals( pollutants.size() * (Double) testCase2.get( 4 ), sumOfEmissions, MatsimTestUtils.EPSILON, message ); } @@ -120,10 +120,10 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { private ColdEmissionAnalysisModule setUp() { Map avgHbefaColdTable = new HashMap<>(); Map detailedHbefaColdTable = new HashMap<>(); - + fillAveragesTable( avgHbefaColdTable ); fillDetailedTable( detailedHbefaColdTable ); - + EventsManager emissionEventManager = new HandlerToTestEmissionAnalysisModules(); EmissionsConfigGroup ecg = new EmissionsConfigGroup(); ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.usingVehicleTypeId ); @@ -133,7 +133,7 @@ private ColdEmissionAnalysisModule setUp() { return new ColdEmissionAnalysisModule( avgHbefaColdTable, detailedHbefaColdTable, ecg, pollutants, emissionEventManager ); } - + private static void fillDetailedTable( Map detailedHbefaColdTable ) { // create all needed and one unneeded entry for the detailed table { @@ -154,19 +154,19 @@ private static void fillDetailedTable( Map avgHbefaColdTable ) { // create all needed and one unneeded entry for the average table { // add passenger car entry "average;average;average": HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( "average", "average", "average" ) ; - + putIntoHbefaColdTable( avgHbefaColdTable, vehAtt, new HbefaColdEmissionFactor(averageAverageFactor), PASSENGER_CAR ); } { HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( petrol_technology, none_sizeClass, none_emConcept ); - + putIntoHbefaColdTable( avgHbefaColdTable, vehAtt, new HbefaColdEmissionFactor( averagePetrolFactor ), PASSENGER_CAR ); } { @@ -182,7 +182,7 @@ private static void fillAveragesTable( Map detailedHbefaColdTable, final HbefaVehicleAttributes vehAtt, final HbefaColdEmissionFactor detColdFactor, final HbefaVehicleCategory hbefaVehicleCategory ) { for ( Pollutant cp : pollutants ) { HbefaColdEmissionFactorKey detColdKey = new HbefaColdEmissionFactorKey(); @@ -194,5 +194,5 @@ private static void putIntoHbefaColdTable( final Map pollutants = new HashSet<>(Arrays.asList(Pollutant.values())); // strings for test cases - + // The material below was confused in the way that strings like "petrol" or "diesel" were given for the // size classes, and "<1,4L" or ">=2L" for the emissions concept. Tried to make it consistent, // but I don't know if it is still testing the original functionality. kai, jul'18 - + // first case: complete data - corresponding entry in average table private static final String petrol_technology = "petrol"; private static final String none_sizeClass = "average"; @@ -85,7 +85,7 @@ public class TestColdEmissionAnalysisModuleCase3 { private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - // emission factors for tables - no dublicates! + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; @@ -103,19 +103,19 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { // error when using the average entry. Collections.addAll( testCase3, "PASSENGER_CAR", diesel_technology, geq2l_sizeClass, PC_D_Euro_3_emConcept, detailedDieselFactor ); - logger.info("Running testcase: " + testCase3.toString()); + logger.info("Running testcase: {}", testCase3); Id linkId = Id.create( "linkId" + testCase3 , Link.class ); Id vehicleId = Id.create( "vehicleId" + testCase3, Vehicle.class ); Id vehicleTypeId = Id.create( testCase3.get( 0 ) + ";" + testCase3.get( 1 ) + ";" + testCase3.get( 2 ) + ";" + testCase3.get( 3 ), VehicleType.class ); Vehicle vehicle = VehicleUtils.getFactory().createVehicle( vehicleId, VehicleUtils.getFactory().createVehicleType( vehicleTypeId ) ); - logger.info("VehicleId: " + vehicle.getId().toString()); - logger.info("VehicleTypeId: " + vehicle.getType().getId()); + logger.info("VehicleId: {}", vehicle.getId().toString()); + logger.info("VehicleTypeId: {}", vehicle.getType().getId()); Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); - String message = "The expected emissions for " + testCase3.toString() + " are " + pollutants.size() * (Double) testCase3.get( 4 ) + " but were " + sumOfEmissions; + String message = "The expected emissions for " + testCase3 + " are " + pollutants.size() * (Double) testCase3.get( 4 ) + " but were " + sumOfEmissions; Assertions.assertEquals( pollutants.size() * (Double) testCase3.get( 4 ), sumOfEmissions, MatsimTestUtils.EPSILON, message ); @@ -124,10 +124,10 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { private ColdEmissionAnalysisModule setUp() { Map avgHbefaColdTable = new HashMap<>(); Map detailedHbefaColdTable = new HashMap<>(); - + fillAveragesTable( avgHbefaColdTable ); fillDetailedTable( detailedHbefaColdTable ); - + EventsManager emissionEventManager = new HandlerToTestEmissionAnalysisModules(); EmissionsConfigGroup ecg = new EmissionsConfigGroup(); ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.usingVehicleTypeId ); @@ -136,12 +136,12 @@ private ColdEmissionAnalysisModule setUp() { ecg.setDetailedVsAverageLookupBehavior(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); // return new ColdEmissionAnalysisModule( avgHbefaColdTable, detailedHbefaColdTable, ecg, pollutants, emissionEventManager ); - + } - + private static void fillDetailedTable( Map detailedHbefaColdTable ) { // create all needed and one unneeded entry for the detailed table - + { // add passenger car entry "petrol;<=1.4L;PC-P-Euro-1": HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( petrol_technology2, leq14l_sizeClass, PC_P_Euro_1_emConcept ); @@ -151,19 +151,19 @@ private static void fillDetailedTable( Map=2L;PC-D-Euro-3": HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( diesel_technology, geq2l_sizeClass, PC_D_Euro_3_emConcept ); - + putIntoHbefaColdTable( detailedHbefaColdTable, vehAtt, new HbefaColdEmissionFactor( detailedDieselFactor ), PASSENGER_CAR ); } { // add heavy goods vehicle entry "petrol;none;none": //(pre-existing comment: HEAVY_GOODS_VEHICLE;PC petrol;petrol;none should not be used --???) HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( petrol_technology, none_sizeClass, none_emConcept ); - + putIntoHbefaColdTable( detailedHbefaColdTable, vehAtt, new HbefaColdEmissionFactor( fakeFactor ), HEAVY_GOODS_VEHICLE ); } } - + private static void fillAveragesTable( Map avgHbefaColdTable ) { // create all needed and one unneeded entry for the average table @@ -171,30 +171,30 @@ private static void fillAveragesTable( Map detailedHbefaColdTable, final HbefaVehicleAttributes vehAtt, final HbefaColdEmissionFactor detColdFactor, final HbefaVehicleCategory hbefaVehicleCategory ) { for ( Pollutant cp : pollutants ) { HbefaColdEmissionFactorKey detColdKey = new HbefaColdEmissionFactorKey(); @@ -206,5 +206,5 @@ private static void putIntoHbefaColdTable( final Map pollutants = new HashSet<>(Arrays.asList(Pollutant.values())); // strings for test cases - + // The material below was confused in the way that strings like "petrol" or "diesel" were given for the // size classes, and "<1,4L" or ">=2L" for the emissions concept. Tried to make it consistent, // but I don't know if it is still testing the original functionality. kai, jul'18 - + // first case: complete data - corresponding entry in average table private static final String petrol_technology = "petrol"; private static final String none_sizeClass = "average"; @@ -84,12 +84,12 @@ public class TestColdEmissionAnalysisModuleCase4 { private static final String diesel_technology = "diesel"; private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - + // fifth case: cold emission factor not set // private static final String nullcase_emConcept = "nullCase"; - // this testcase does not exist any more. kai, jul'18 + // this testcase does not exist anymore. kai, jul'18 - // emission factors for tables - no dublicates! + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; @@ -113,30 +113,30 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { Collections.addAll( testCase4, "PASSENGER_CAR", "", "", "", averageAverageFactor ); - logger.info("Running testcase: " + testCase4.indexOf( 0 ) + " " + testCase4.toString()); + logger.info("Running testcase: {} {}", testCase4.indexOf(0), testCase4); Id linkId = Id.create( "linkId" + testCase4.indexOf( 0 ), Link.class ); Id vehicleId = Id.create( "vehicleId" + testCase4.indexOf( 0 ), Vehicle.class ); Id vehicleTypeId = Id.create( testCase4.get( 0 ) + ";" + testCase4.get( 1 ) + ";" + testCase4.get( 2 ) + ";" + testCase4.get( 3 ), VehicleType.class ); - + Vehicle vehicle = VehicleUtils.getFactory().createVehicle( vehicleId, VehicleUtils.getFactory().createVehicleType( vehicleTypeId ) ); - logger.info("VehicleId: " + vehicle.getId().toString()); - logger.info("VehicleTypeId: " + vehicle.getType().getId()); + logger.info("VehicleId: {}", vehicle.getId().toString()); + logger.info("VehicleTypeId: {}", vehicle.getType().getId()); Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); - String message = "The expected emissions for " + testCase4.toString() + " are " + pollutants.size() * (Double) testCase4.get( 4 ) + " but were " + sumOfEmissions; + String message = "The expected emissions for " + testCase4 + " are " + pollutants.size() * (Double) testCase4.get( 4 ) + " but were " + sumOfEmissions; Assertions.assertEquals( pollutants.size() * (Double) testCase4.get( 4 ), sumOfEmissions, MatsimTestUtils.EPSILON, message ); - + } - + private ColdEmissionAnalysisModule setUp() { Map avgHbefaColdTable = new HashMap<>(); Map detailedHbefaColdTable = new HashMap<>(); - + fillAveragesTable( avgHbefaColdTable ); fillDetailedTable( detailedHbefaColdTable ); - + EventsManager emissionEventManager = new HandlerToTestEmissionAnalysisModules(); EmissionsConfigGroup ecg = new EmissionsConfigGroup(); @@ -146,10 +146,10 @@ private ColdEmissionAnalysisModule setUp() { ecg.setDetailedVsAverageLookupBehavior(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); return new ColdEmissionAnalysisModule( avgHbefaColdTable, detailedHbefaColdTable, ecg, pollutants, emissionEventManager ); } - + private static void fillDetailedTable( Map detailedHbefaColdTable ) { // create all needed and one unneeded entry for the detailed table - + { // add passenger car entry "petrol;<=1.4L;PC-P-Euro-1": HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( petrol_technology2, leq14l_sizeClass, PC_P_Euro_1_emConcept ); @@ -167,7 +167,7 @@ private static void fillDetailedTable( Map avgHbefaColdTable ) { // create all needed and one unneeded entry for the average table @@ -194,7 +194,7 @@ private static void fillAveragesTable( Map detailedHbefaColdTable, final HbefaVehicleAttributes vehAtt, final HbefaColdEmissionFactor detColdFactor, final HbefaVehicleCategory hbefaVehicleCategory ) { for ( Pollutant cp : pollutants ) { HbefaColdEmissionFactorKey detColdKey = new HbefaColdEmissionFactorKey(); @@ -206,5 +206,5 @@ private static void putIntoHbefaColdTable( final Map pollutants = new HashSet<>(Arrays.asList(Pollutant.values())); // strings for test cases - + // The material below was confused in the way that strings like "petrol" or "diesel" were given for the // size classes, and "<1,4L" or ">=2L" for the emissions concept. Tried to make it consistent, // but I don't know if it is still testing the original functionality. kai, jul'18 - + // case: complete data - corresponding entry in average table private static final String petrol_technology = "petrol"; private static final String none_sizeClass = "average"; @@ -82,8 +82,8 @@ public class TestColdEmissionAnalysisModuleCase6 { private static final String geq2l_sizeClass = ">=2L"; private static final String PC_D_Euro_3_emConcept = "PC-D-Euro-3"; - - // emission factors for tables - no dublicates! + + // emission factors for tables - no duplicates! private static final Double detailedPetrolFactor = 100.; private static final Double detailedDieselFactor = 10.; private static final Double averageAverageFactor = .1; @@ -105,39 +105,39 @@ void calculateColdEmissionsAndThrowEventTest_completeData() { // sixth case: heavy goods vehicle // -> throw warning -> use detailed or average table for passenger cars - String heavygoodsvehicle = "HEAVY_GOODS_VEHICLE"; - Collections.addAll( testCase6, heavygoodsvehicle, petrol_technology, none_sizeClass, none_emConcept, heavyGoodsFactor); + String heavyGoodsVehicle = "HEAVY_GOODS_VEHICLE"; + Collections.addAll( testCase6, heavyGoodsVehicle, petrol_technology, none_sizeClass, none_emConcept, heavyGoodsFactor); - logger.info("Running testcase: " + testCase6 + " " +testCase6.toString()); + logger.info("Running testcase: {} {}", testCase6, testCase6); Id linkId = Id.create( "linkId" + testCase6, Link.class ); Id vehicleId = Id.create( "vehicleId" + testCase6, Vehicle.class ); Id vehicleTypeId = Id.create( testCase6.get( 0 ) + ";" + testCase6.get( 1 ) + ";" + testCase6.get( 2 ) + ";" + testCase6.get( 3 ), VehicleType.class ); - + Vehicle vehicle = VehicleUtils.getFactory().createVehicle( vehicleId, VehicleUtils.getFactory().createVehicleType( vehicleTypeId ) ); - logger.info("VehicleId: " + vehicle.getId().toString()); - logger.info("VehicleTypeId: " + vehicle.getType().getId()); + logger.info("VehicleId: {}", vehicle.getId().toString()); + logger.info("VehicleTypeId: {}", vehicle.getType().getId()); Map calculatedPollutants = coldEmissionAnalysisModule.checkVehicleInfoAndCalculateWColdEmissions(vehicle.getType(), vehicle.getId(), linkId, 0.0, parkingDuration, tableAccDistance); double sumOfEmissions = calculatedPollutants.values().stream().mapToDouble(Double::doubleValue).sum(); - String message = "The expected emissions for " + testCase6.toString() + " are " + pollutants.size() * (Double) testCase6.get( 4 ) + " but were " + sumOfEmissions; + String message = "The expected emissions for " + testCase6 + " are " + pollutants.size() * (Double) testCase6.get( 4 ) + " but were " + sumOfEmissions; Assertions.assertEquals( pollutants.size() * (Double) testCase6.get( 4 ), sumOfEmissions, MatsimTestUtils.EPSILON, message ); } - + private ColdEmissionAnalysisModule setUp() { Map avgHbefaColdTable = new HashMap<>(); Map detailedHbefaColdTable = new HashMap<>(); - + fillAveragesTable( avgHbefaColdTable ); fillDetailedTable( detailedHbefaColdTable ); - + EventsManager emissionEventManager = new HandlerToTestEmissionAnalysisModules(); EmissionsConfigGroup ecg = new EmissionsConfigGroup(); ecg.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.usingVehicleTypeId ); return new ColdEmissionAnalysisModule( avgHbefaColdTable, detailedHbefaColdTable, ecg, pollutants, emissionEventManager ); } - + private static void fillDetailedTable( Map detailedHbefaColdTable ) { // create all needed and one unneeded entry for the detailed table { @@ -147,7 +147,7 @@ private static void fillDetailedTable( Map Should be used, since HGV shpuld be supported and not fallback to average any more, kmt apr'20. + //(pre-existing comment: HEAVY_GOODS_VEHICLE;PC petrol;petrol; --> Should be used, since HGV should be supported and not fallback to average anymore, kmt apr'20.) HbefaVehicleAttributes vehAtt = ColdEmissionAnalysisModule.createHbefaVehicleAttributes( petrol_technology, none_sizeClass, none_emConcept ); putIntoHbefaColdTable( detailedHbefaColdTable, vehAtt, new HbefaColdEmissionFactor(heavyGoodsFactor), HEAVY_GOODS_VEHICLE ); } @@ -160,7 +160,7 @@ private static void fillDetailedTable( Map avgHbefaColdTable ) { // create all needed and one unneeded entry for the average table @@ -184,11 +184,11 @@ private static void fillAveragesTable( Map detailedHbefaColdTable, final HbefaVehicleAttributes vehAtt, final HbefaColdEmissionFactor detColdFactor, final HbefaVehicleCategory hbefaVehicleCategory ) { for ( Pollutant cp : pollutants ) { HbefaColdEmissionFactorKey detColdKey = new HbefaColdEmissionFactorKey(); @@ -200,5 +200,5 @@ private static void putIntoHbefaColdTable( final Map * LookupBehavior: onlyTryDetailedElseAbort - * + *

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

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

        * LookupBehavior: onlyTryDetailedElseAbort - * + *

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

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

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

        * LookupBehavior: onlyTryDetailedElseAbort - * + *

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

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

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

        * LookupBehavior: tryDetailedThenTechnologyAverageThenAverageTable - * + *

        * -> do fall back to average table * ---> should calculate value from average table */ diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java index 13efc7bf890..810c11e8d2c 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaColdEmissionFactorKey.java @@ -43,7 +43,6 @@ public class TestHbefaColdEmissionFactorKey { private Pollutant coldPollutant; private HbefaVehicleAttributes hbefaVehicleAttributes; private HbefaVehicleCategory hbefaVehCategory; - private boolean equalErr; private HbefaColdEmissionFactorKey normal; private void setUp(){ @@ -56,7 +55,6 @@ private void setUp(){ parkingTime = 5; coldPollutant = FC; hbefaVehCategory = HbefaVehicleCategory.PASSENGER_CAR; - equalErr = false; } @@ -82,7 +80,7 @@ final void testEqualsForCompleteKeys() { compare.setVehicleAttributes(attForCompare); compare.setVehicleCategory(hbefaVehCategory); - String message = "these two objects should be the same but are not: " + normal.toString() + " and " + compare.toString(); + String message = "these two objects should be the same but are not: " + normal + " and " + compare; Assertions.assertEquals(normal, compare, message); Assertions.assertEquals(compare, normal, message); } @@ -100,13 +98,13 @@ final void testEqualsForCompleteKeys() { different.setVehicleAttributes(attForDifferent); different.setVehicleCategory(HbefaVehicleCategory.HEAVY_GOODS_VEHICLE); - String message = "these two objects should not be the same: " + normal.toString() + " and " + different.toString(); + String message = "these two objects should not be the same: " + normal + " and " + different; assertNotEquals(normal, different, message); assertNotEquals(different, normal, message); } } - // the following tests each compare a incomplete key to a complete key + // the following tests each compare an incomplete key to a complete key // wanted result: // completeData.equals(partialData) -> return false // uncompleteData.equals(completeData) -> throw nullpointer @@ -127,8 +125,8 @@ final void testEqualsForIncompleteKeys_vehicleCategory(){ noVehCat.setParkingTime(parkingTime); noVehCat.setVehicleAttributes(hbefaVehicleAttributes); - String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noVehCat.toString(); - assertFalse(noVehCat.equals(normal), message); + String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal + " and " + noVehCat; + assertNotEquals(noVehCat, normal, message); } @Test @@ -146,8 +144,8 @@ final void testEqualsForIncompleteKeys_pollutant(){ noColdPollutant.setVehicleCategory(hbefaVehCategory); noColdPollutant.setVehicleAttributes(hbefaVehicleAttributes); - String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noColdPollutant.toString(); - assertFalse(noColdPollutant.equals(normal), message); + String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noColdPollutant; + assertNotEquals(noColdPollutant, normal, message); } @Test @@ -165,8 +163,8 @@ final void testEqualsForIncompleteKeys_parkingTime() { noParkingTime.setVehicleCategory(hbefaVehCategory); noParkingTime.setVehicleAttributes(hbefaVehicleAttributes); - String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noParkingTime.toString(); - assertFalse(noParkingTime.equals(normal), message); + String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noParkingTime; + assertNotEquals(noParkingTime, normal, message); } @Test @@ -184,8 +182,8 @@ final void testEqualsForIncompleteKeys_distance() { noDistance.setVehicleCategory(hbefaVehCategory); noDistance.setVehicleAttributes(hbefaVehicleAttributes); - String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noDistance.toString(); - assertFalse(noDistance.equals(normal), message); + String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noDistance; + assertNotEquals(noDistance, normal, message); } @Test @@ -199,8 +197,8 @@ final void testEqualsForIncompleteKeys_emptyKey() { //empty HbefaColdEmissionFactorKey HbefaColdEmissionFactorKey emptyKey = new HbefaColdEmissionFactorKey(); - String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + emptyKey.toString(); - assertFalse(emptyKey.equals(normal), message); + String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + emptyKey; + assertNotEquals(emptyKey, normal, message); } @Test @@ -226,8 +224,8 @@ final void testEqualsForIncompleteKeys_VehicleAttributes(){ noVehAtt.setParkingTime(parkingTime); noVehAtt.setVehicleCategory(hbefaVehCategory); - String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noVehAtt.toString(); - assertFalse(noVehAtt.equals(normal), message); + String message = "these two HbefaColdEmissionFactorKeys should not be the same: " + normal + " and " + noVehAtt; + assertNotEquals(noVehAtt, normal, message); //set the vehicle attributes of the normal hbefaColdWmissionFactorKey to 'average' @@ -239,7 +237,7 @@ final void testEqualsForIncompleteKeys_VehicleAttributes(){ hbefaVehicleAttributesAverage.setHbefaTechnology("average"); normal.setVehicleAttributes(hbefaVehicleAttributesAverage); - Assertions.assertTrue(noVehAtt.equals(normal), message); + assertEquals(noVehAtt, normal, message); } } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaVehicleAttributes.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaVehicleAttributes.java index bb8743783d9..4cf37da4feb 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaVehicleAttributes.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaVehicleAttributes.java @@ -53,7 +53,7 @@ final void testEqualsForCompleteAttributes(){ compare.setHbefaEmConcept(concept); String assertErrorMessage = "These hbefa vehicle attribute objects should have been the same: "; - assertErrorMessage += normal.toString() + " and " + compare.toString(); + assertErrorMessage += normal.toString() + " and " + compare; Assertions.assertEquals(normal, compare, assertErrorMessage); Assertions.assertEquals(compare, normal, assertErrorMessage); @@ -73,7 +73,7 @@ final void testEqualsForCompleteAttributes_emConcept(){ differentValues.setHbefaSizeClass(sizeClass); differentValues.setHbefaTechnology(technology); assertErrorMessage = "These hbefa vehicle attribute objects should not have been the same: "; - assertErrorMessage += normal.toString() + " and " + differentValues.toString(); + assertErrorMessage += normal.toString() + " and " + differentValues; Assertions.assertNotEquals(normal, differentValues, assertErrorMessage); Assertions.assertNotEquals(differentValues, normal, assertErrorMessage); } @@ -91,7 +91,7 @@ final void testEqualsForCompleteAttributes_sizeClass(){ differentValues.setHbefaSizeClass("small size"); differentValues.setHbefaTechnology(technology); assertErrorMessage = "These hbefa vehicle attribute objects should not have been the same: "; - assertErrorMessage += normal.toString() + " and " + differentValues.toString(); + assertErrorMessage += normal.toString() + " and " + differentValues; Assertions.assertNotEquals(normal, differentValues, assertErrorMessage); Assertions.assertNotEquals(differentValues, normal, assertErrorMessage); @@ -110,7 +110,7 @@ final void testEqualsForCompleteAttributes_technologies(){ differentValues.setHbefaSizeClass(sizeClass); differentValues.setHbefaTechnology("other technology"); assertErrorMessage = "These hbefa vehicle attribute objects should not have been the same: "; - assertErrorMessage += normal.toString() + " and " + differentValues.toString(); + assertErrorMessage += normal.toString() + " and " + differentValues; Assertions.assertNotEquals(normal, differentValues, assertErrorMessage); Assertions.assertNotEquals(differentValues, normal, assertErrorMessage); @@ -195,7 +195,7 @@ private void setToNormal(HbefaVehicleAttributes normal) { } } - - + + diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java index 2ff96fb02bd..df5cf8fd2d7 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestHbefaWarmEmissionFactorKey.java @@ -26,6 +26,7 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.matsim.contrib.emissions.Pollutant.CO; import static org.matsim.contrib.emissions.Pollutant.FC; @@ -37,10 +38,10 @@ public class TestHbefaWarmEmissionFactorKey{ * test for playground.vsp.emissions.types.HbefaWarmEmissionFactorKey * 1 test equals method for complete input: two equal hbefaWarmEmissionFactorKey objects, two unequal objects * 2 test equals method for incomplete input: one complete hbefaWarmEmissionFactorKey against one with a missing argument - * + * * @author julia */ - + private HbefaVehicleAttributes hbefaVehicleAttributes; private String hbefaRoadCategory; private HbefaTrafficSituation hbefaTrafficSituation; @@ -56,22 +57,22 @@ private void setUp(){ hbefaVehicleAttributes.setHbefaEmConcept("concept"); hbefaVehicleAttributes.setHbefaSizeClass("size class"); hbefaVehicleAttributes.setHbefaTechnology("technology"); - hbefaRoadCategory = "road type"; + hbefaRoadCategory = "road type"; hbefaTrafficSituation = HbefaTrafficSituation.FREEFLOW; hbefaVehicleCategory = HbefaVehicleCategory.PASSENGER_CAR; warmPollutant = FC; - + } @Test final void testEqualsForCompleteKeys(){ - // generate a complete HbefaWarmEmissionFactorKey: 'normal' + // generate a complete HbefaWarmEmissionFactorKey: 'normal' // and set some parameters setUp(); setToNormal(normal); - // generate a warm emission factor key equal to 'normal' + // generate a warm emission factor key equal to 'normal' HbefaWarmEmissionFactorKey compare = new HbefaWarmEmissionFactorKey(); compare.setComponent(FC); compare.setRoadCategory(hbefaRoadCategory); @@ -79,9 +80,9 @@ final void testEqualsForCompleteKeys(){ compare.setVehicleAttributes(hbefaVehicleAttributes); compare.setVehicleCategory(hbefaVehicleCategory); - String message = "these two objects should be the same but are not: " + normal.toString() + " and " + compare.toString(); - Assertions.assertTrue(normal.equals(compare), message); - Assertions.assertTrue(compare.equals(normal), message); + String message = "these two objects should be the same but are not: " + normal.toString() + " and " + compare; + Assertions.assertEquals(normal, compare, message); + Assertions.assertEquals(compare, normal, message); //two unequal but complete objects HbefaWarmEmissionFactorKey different = new HbefaWarmEmissionFactorKey(); @@ -95,18 +96,18 @@ final void testEqualsForCompleteKeys(){ different.setVehicleAttributes(attrForDifferent); different.setVehicleCategory(HbefaVehicleCategory.HEAVY_GOODS_VEHICLE); - message = "these two objects should not be the same: " + normal.toString() + " and " + different.toString(); + message = "these two objects should not be the same: " + normal.toString() + " and " + different; - assertFalse(different.equals(normal), message); - assertFalse(normal.equals(different), message); + assertNotEquals(different, normal, message); + assertNotEquals(normal, different, message); } - // the following tests each compare a incomplete key to a complete key + // the following tests each compare an incomplete key to a complete key // wanted result: // completeData.equals(partialData) -> return false // uncompleteData.equals(completeData) -> throw nullpointer // exception: if the vehicleAttributes are set to 'average' by default - + @Test final void testEqualsForIncompleteKeys_vehicleCategory() { // generate a complete HbefaWarmEmissionFactorKey: 'normal' @@ -121,8 +122,8 @@ final void testEqualsForIncompleteKeys_vehicleCategory() { noVehCat.setTrafficSituation(hbefaTrafficSituation); noVehCat.setVehicleAttributes(hbefaVehicleAttributes); - log.warn("normal=" + normal); - log.warn("noVehCat=" + noVehCat); + log.warn("normal={}", normal); + log.warn("noVehCat={}", noVehCat); var result = noVehCat.equals(normal); @@ -167,10 +168,10 @@ final void testEqualsForIncompleteKeys_roadCategory() { equalErr = true; } - String message = "these two HbefaWarmEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noRoadCat.toString(); + String message = "these two HbefaWarmEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noRoadCat; String message2 = "this key should not be comparable since no road category is set"; Assertions.assertTrue(equalErr, message2); - assertFalse(normal.equals(noRoadCat), message); + assertNotEquals(normal, noRoadCat, message); } @Test @@ -213,7 +214,7 @@ final void testEqualsForIncompleteKeys_vehicleAttributes(){ // if no vehicle attributes are set manually they are set to 'average' by default // thus, the equals method should not throw nullpointer exceptions but return false or respectively true - // generate a complete HbefaWarmEmissionFactorKey: 'normal' + // generate a complete HbefaWarmEmissionFactorKey: 'normal' // and set some parameters setUp(); setToNormal(normal); @@ -232,12 +233,12 @@ final void testEqualsForIncompleteKeys_vehicleAttributes(){ equalErr = true; } - String message = "these two HbefaWarmEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noVehAtt.toString(); - assertFalse(noVehAtt.equals(normal), message); + String message = "these two HbefaWarmEmissionFactorKeys should not be the same: " + normal.toString() + " and " + noVehAtt; + assertNotEquals(noVehAtt, normal, message); assertFalse(equalErr); // veh attributes are allowed to be not initiated // therefore this should not throw a nullpointer but return false - assertFalse(normal.equals(noVehAtt), message); + assertNotEquals(normal, noVehAtt, message); //set the vehicle attributes of the normal hbefacoldemissionfactorkey to 'average' //then noVehAtt is equal to normal @@ -247,13 +248,13 @@ final void testEqualsForIncompleteKeys_vehicleAttributes(){ hbefaVehicleAttributesAverage.setHbefaTechnology("average"); normal.setVehicleAttributes(hbefaVehicleAttributesAverage); - message = "these two HbefaWarmEmissionFactorKeys should be the same: " + normal.toString() + " and " + noVehAtt.toString(); - Assertions.assertTrue(normal.equals(noVehAtt), message); - Assertions.assertTrue(noVehAtt.equals(normal), message); + message = "these two HbefaWarmEmissionFactorKeys should be the same: " + normal.toString() + " and " + noVehAtt; + Assertions.assertEquals(normal, noVehAtt, message); + Assertions.assertEquals(noVehAtt, normal, message); } - + private void setToNormal(HbefaWarmEmissionFactorKey normal) { normal.setComponent(warmPollutant); normal.setRoadCategory(hbefaRoadCategory); @@ -261,10 +262,10 @@ private void setToNormal(HbefaWarmEmissionFactorKey normal) { normal.setVehicleAttributes(hbefaVehicleAttributes); normal.setVehicleCategory(hbefaVehicleCategory); } - - + + } - - + + diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java index 30b456f1455..05ac81e5bce 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModule.java @@ -20,10 +20,8 @@ package org.matsim.contrib.emissions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; @@ -49,7 +47,7 @@ /* * test for playground.vsp.emissions.WarmEmissionAnalysisModule - * + *

        * WarmEmissionAnalysisModule (weam) * public methods and corresponding tests: * weamParameter - testWarmEmissionAnalysisParameter @@ -57,17 +55,17 @@ * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * get free flow occurences - testCounters*() * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get stop-go occurences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() * get top go km couter - testCounters*() * get warm emission event counter - testCounters*() - * + *

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

        * in all cases the needed tables are created manually by the setUp() method * see test methods for details on the particular test cases **/ @@ -104,8 +102,8 @@ public class TestWarmEmissionAnalysisModule { private final Double noeFreeSpeed = AVG_PASSENGER_CAR_SPEED_FF_KMH; - // case 6 - data in detailed table, stop go speed = free flow speed - private final String sgffRoadCatgory = "URB_case7"; + // case 6 - data in detailed table, stop-go speed = free flow speed + private final String sgffRoadCategory = "URB_case7"; private final String sgffTechnology = "sg ff technology"; private final String sgffConcept = "sg ff concept"; private final String sgffSizeClass = "sg ff size class"; @@ -126,7 +124,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent6(E Id sgffVehicleId = Id.create("vehicle sg equals ff", Vehicle.class); double sgffLinklength = 4000.; Link sgflink = createMockLink("link sgf", sgffLinklength, AVG_PASSENGER_CAR_SPEED_FF_KMH / 3.6); - EmissionUtils.setHbefaRoadType(sgflink, sgffRoadCatgory); + EmissionUtils.setHbefaRoadType(sgflink, sgffRoadCategory); Id sgffVehicleTypeId = Id.create( PASSENGER_CAR + ";" + sgffTechnology + ";"+ sgffSizeClass + ";"+sgffConcept, VehicleType.class ); VehiclesFactory vehFac = VehicleUtils.getFactory(); @@ -184,8 +182,6 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Ex excep = true; } Assertions.assertFalse(excep); - - excep=false; } @ParameterizedTest @@ -211,7 +207,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Ex }catch(Exception e){ excep = true; } - Assertions.assertTrue(excep); excep=false; + Assertions.assertTrue(excep); } @ParameterizedTest @@ -236,7 +232,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Ex }catch(Exception e){ excep = true; } - Assertions.assertTrue(excep); excep=false; + Assertions.assertTrue(excep); } @ParameterizedTest @@ -259,7 +255,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Ex }catch(Exception e){ excep = true; } - Assertions.assertTrue(excep); excep=false; + Assertions.assertTrue(excep); } @@ -269,7 +265,7 @@ void testCounters7(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp setUp(emissionsComputationMethod); emissionsModule.reset(); - // case 10 - data in detailed table, stop go speed > free flow speed + // case 10 - data in detailed table, stop-go speed > free flow speed Id tableVehicleId = Id.create("vehicle 8", Vehicle.class); double tableLinkLength= 30.*1000; Id tableVehicleTypeId = Id.create( @@ -348,7 +344,7 @@ private void fillDetailedTable( Map avgHbefaWarmTable ) { // entries for first case "petrol" should not be used since there are entries in the detailed table - // there should only average vehicle attributes in the avgHebfWarmTable jm oct'18 + // there should only average vehicle attributes in the avgHbefaWarmTable jm oct'18 HbefaVehicleAttributes vehAtt = new HbefaVehicleAttributes(); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java index 2bc080b1bc3..2a0382250ae 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase1.java @@ -21,11 +21,8 @@ package org.matsim.contrib.emissions; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; @@ -38,7 +35,6 @@ import org.matsim.vehicles.VehiclesFactory; import java.util.*; -import java.util.stream.Stream; import static org.matsim.contrib.emissions.Pollutant.CO2_TOTAL; import static org.matsim.contrib.emissions.TestWarmEmissionAnalysisModule.HBEFA_ROAD_CATEGORY; @@ -63,12 +59,12 @@ * weamParameter - testWarmEmissionAnalysisParameter * throw warm EmissionEvent - testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions - * get free flow occurences - testCounters*() - * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get free flow occurrences - testCounters*() + * get fraction occurrences - testCounters*() + * get stop-go occurrences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() - * get top go km couter - testCounters*() + * get top go km counter - testCounters*() * get warm emission event counter - testCounters*() * * private methods and corresponding tests: @@ -153,7 +149,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent1(E /* * this test method creates a mock link and mock vehicle (petrol technology) with a complete vehicleTypId --> detailed values are used - * the counters for all possible combinations of avg, stop go and free flow speed are tested + * the counters for all possible combinations of avg, stop-go and free flow speed are tested * for the cases: > s&g speed, vehicleId = Id.create("vehicle 1", Vehicle.class); @@ -245,9 +241,9 @@ void testCounters1(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp /* - * this test method creates a incoff mock link and incoff mock vehicle (petrol technology) with a complete vehicleTypId --> detailed values are used - * for the computationMethod "Stop and Go" and "averageSpeed" the free flow occurences are tested - * the counters (StopGoOccurences, KmCounter, WarmEmissionEventCounter) are tested + * this test method creates an incoff mock link and incoff mock vehicle (petrol technology) with a complete vehicleTypId --> detailed values are used + * for the computationMethod "Stop and Go" and "averageSpeed" the free flow occurrences are tested + * the counters (StopGoOccurrences, KmCounter, WarmEmissionEventCounter) are tested * for the case average speed equals wrong free flow speed the counters are tested */ @@ -309,7 +305,7 @@ void testCounters1fractional(EmissionsConfigGroup.EmissionsComputationMethod emi // yyyyyy !!!!!! /* - * using the same case as above - case 1 and check the counters for all possible combinations of avg, stop go and free flow speed + * using the same case as above - case 1 and check the counters for all possible combinations of avg, stop-go and free flow speed */ Id vehicleId = Id.create("vehicle 1", Vehicle.class); @@ -380,7 +376,7 @@ void testCounters1fractional(EmissionsConfigGroup.EmissionsComputationMethod emi emissionsModule.reset(); emissionsModule.getEcg().setEmissionsComputationMethod(AverageSpeed ); - //@KMT it seems to me that copying the counters from above and chaning the expected values?? + //@KMT it seems to me that copying the counters from above and changing the expected values?? // yyyyyy !!!!!! } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase2.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase2.java index 8fb143e1821..bb7beab4140 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase2.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase2.java @@ -21,10 +21,8 @@ package org.matsim.contrib.emissions; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; @@ -37,7 +35,6 @@ import org.matsim.vehicles.VehiclesFactory; import java.util.*; -import java.util.stream.Stream; import static org.matsim.contrib.emissions.Pollutant.NMHC; import static org.matsim.contrib.emissions.TestWarmEmissionAnalysisModule.fillAverageTable; @@ -47,7 +44,7 @@ * / /* - * Case 2 - free flow entry in both tables, stop go entry in average table -> use average + * Case 2 - free flow entry in both tables, stop-go entry in average table -> use average * see (*) below. kai, jan'20 */ @@ -59,12 +56,12 @@ * weamParameter - testWarmEmissionAnalysisParameter * throw warm EmissionEvent - testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions - * get free flow occurences - testCounters*() - * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get free flow occurrences - testCounters*() + * get fraction occurrences - testCounters*() + * get stop-go occurrences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() - * get top go km couter - testCounters*() + * get top go km counter - testCounters*() * get warm emission event counter - testCounters*() * * private methods and corresponding tests: @@ -98,7 +95,7 @@ public class TestWarmEmissionAnalysisModuleCase2{ // vehicle information for regular test cases - // case 2 - free flow entry in both tables, stop go entry in average table -> use average (now fail) + // case 2 - free flow entry in both tables, stop-go entry in average table -> use average (now fail) private static final String PC_TECHNOLOGY = "PC petrol <1,4L lookUpBehaviour: tryDetailedThenTechnologyAverageThenAverageTable - * for two speed cases: avg speed = free flow speed & avg speed = stop go speed the NMHC warm emissions and emissions sum are computed using the two emissionsComputationMethods StopAndGoFraction & AverageSpeed + * for two speed cases: avg speed = free flow speed & avg speed = stop-go speed the NMHC warm emissions and emissions sum are computed using the two emissionsComputationMethods StopAndGoFraction & AverageSpeed */ @ParameterizedTest @@ -118,7 +115,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent2(E WarmEmissionAnalysisModule emissionsModule = setUp(emissionsComputationMethod); - // case 2 - free flow entry in both tables, stop go entry in average table -> use average + // case 2 - free flow entry in both tables, stop-go entry in average table -> use average // see (*) below. kai, jan'20 // create a link: @@ -131,7 +128,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent2(E VehiclesFactory vehFac = VehicleUtils.getFactory(); Vehicle pcVehicle = vehFac.createVehicle(pcVehicleId, vehFac.createVehicleType(pcVehicleTypeId)); - // sub case avg speed = free flow speed + // subcase avg speed = free flow speed { // compute warm emissions with travel time coming from free flow: warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions( pcVehicle, pclink, pclinkLength / PC_FREE_VELOCITY_KMH * 3.6 ); @@ -140,8 +137,8 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent2(E // - DETAILED FreeFlow value is available in the table (1.0E-4 g/km); StopAndGo value is NOT available in the table // - AVERAGE FreeFlow value is available in the table (1.0 g/km) ; StopAndGo value is NOT available in the table ( 10.0 g/km) // --> It seems like it was intended (or only implemented) in a way, that if one of the detailed values is missing (FreeFlow or StopGo) there is a fallback to average. So the result of this would be 1.0 g/km * 0.1 km = 0.1 g/km - // --> Now, after implementing the new fallback behaviour, it is looking up both values (FreeFlow or StopGo) ways independently from each other. Therefore the result comes from the detailed table (1.0E-4 g/km) * * 0.1 km = 1.0E-5 g/km - // -----> We need a decision here, if we want allow that inconsistent(?) lookup of FreeFlow and Detailed values with different grade of detail or not. + // --> Now, after implementing the new fallback behaviour, it is looking up both values (FreeFlow or StopGo) ways independently of each other. Therefore, the result comes from the detailed table (1.0E-4 g/km) * * 0.1 km = 1.0E-5 g/km + // -----> We need a decision here, if we want to allow that inconsistent(?) lookup of FreeFlow and Detailed values with different grade of detail or not. // After discussion with Kai N. we decided to let it as it is for the time being. I will add a log.info in the consistency checker. KMT Jul'20 //results should be equal here, because in both cases only the freeflow value is relevant (100% freeflow, 0% stop&go). @@ -155,7 +152,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent2(E warmEmissions.clear(); } - // sub case avg speed = stop go speed + // subcase avg speed = stop-go speed { warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions( pcVehicle, pclink, pclinkLength / PCSG_VELOCITY_KMH * 3.6 ); Assertions.assertEquals( AVG_PC_FACTOR_SG * pclinkLength / 1000., warmEmissions.get( NMHC ), MatsimTestUtils.EPSILON ); @@ -169,7 +166,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent2(E /* * this test method creates a vehicle and mock link - * for three cases: "current speed equals free flow speed" & "current speed equals stop go speed" & "current speed equals stop go speed" the counters are tested + * for three cases: "current speed equals free flow speed" & "current speed equals stop-go speed" & "current speed equals stop-go speed" the counters are tested * average values are used */ @ParameterizedTest @@ -178,7 +175,7 @@ void testCounters3(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp WarmEmissionAnalysisModule emissionsModule = setUp(emissionsComputationMethod); - // case 2 - free flow entry in both tables, stop go entry in average table -> use average + // case 2 - free flow entry in both tables, stop-go entry in average table -> use average Id pcVehicleId = Id.create("vehicle 2", Vehicle.class); double pclinkLength= 20.*1000; Id pcVehicleTypeId = Id.create( PASSENGER_CAR + ";"+ PC_TECHNOLOGY + ";"+ PC_SIZE_CLASS +";"+ PC_CONCEPT, VehicleType.class ); @@ -186,7 +183,7 @@ void testCounters3(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Vehicle pcVehicle = vehFac.createVehicle(pcVehicleId, vehFac.createVehicleType(pcVehicleTypeId)); Link pclink = TestWarmEmissionAnalysisModule.createMockLink("link 2", pclinkLength, PC_FREE_VELOCITY_KMH / 3.6 ); - // sub case: current speed equals free flow speed + // subcase: current speed equals free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(pcVehicle,pclink, pclinkLength/ PC_FREE_VELOCITY_KMH *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(pclinkLength/1000, emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); @@ -197,7 +194,7 @@ void testCounters3(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Assertions.assertEquals(1, emissionsModule.getWarmEmissionEventCounter() ); emissionsModule.reset(); - // sub case: current speed equals stop go speed + // subcase: current speed equals stop-go speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(pcVehicle, pclink, pclinkLength/ PCSG_VELOCITY_KMH *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(0., emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase3.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase3.java index b9df5a7e9bf..c0741ed1ced 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase3.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase3.java @@ -22,9 +22,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; @@ -37,7 +35,6 @@ import org.matsim.vehicles.VehiclesFactory; import java.util.*; -import java.util.stream.Stream; import static org.matsim.contrib.emissions.Pollutant.PM; @@ -57,9 +54,9 @@ * weamParameter - testWarmEmissionAnalysisParameter * throw warm EmissionEvent - testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions - * get free flow occurences - testCounters*() - * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get free flow occurrences - testCounters*() + * get fraction occurrences - testCounters*() + * get stop-go occurrences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() * get top go km counter - testCounters*() @@ -94,14 +91,14 @@ public class TestWarmEmissionAnalysisModuleCase3{ private static final Double AVG_PC_FACTOR_FF = 1.; private static final Double AVG_PC_FACTOR_SG = 10.; - // case 3 - stop go entry in both tables, free flow entry in average table -> use average (now fail) + // case 3 - stop-go entry in both tables, free flow entry in average table -> use average (now fail) private final String dieselTechnology = "PC diesel"; private final String dieselSizeClass = "diesel"; private final String dieselConcept = ">=2L"; /* * this test method creates a diesel vehicle and mock link - * for two cases: "avg speed = free flow speed" & "avg speed = stop go speed" the average values are used to calculate the PM warm emissions + * for two cases: "avg speed = free flow speed" & "avg speed = stop-go speed" the average values are used to calculate the PM warm emissions */ @ParameterizedTest @EnumSource(EmissionsConfigGroup.EmissionsComputationMethod.class) @@ -110,7 +107,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent3(E //-- set up tables, event handler, parameters, module WarmEmissionAnalysisModule emissionsModule = setUp(emissionsComputationMethod); - // case 3 - stop go entry in both tables, free flow entry in average table -> use average + // case 3 - stop-go entry in both tables, free flow entry in average table -> use average Id dieselVehicleId = Id.create("veh 3", Vehicle.class); double dieselLinkLength= 20.; Link diesellink = TestWarmEmissionAnalysisModule.createMockLink("link 3", dieselLinkLength, TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_FF_KMH / 3.6 ); @@ -120,7 +117,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent3(E VehiclesFactory vehFac = VehicleUtils.getFactory(); Vehicle dieselVehicle = vehFac.createVehicle(dieselVehicleId, vehFac.createVehicleType(dieselVehicleTypeId)); - // sub case avg speed = free flow speed + // subcase avg speed = free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(dieselVehicle, diesellink, dieselLinkLength/ TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_FF_KMH *3.6 ); Assertions.assertEquals( AVG_PC_FACTOR_FF *dieselLinkLength/1000., warmEmissions.get(PM ), MatsimTestUtils.EPSILON ); emissionEventManager.reset(); @@ -129,7 +126,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent3(E emissionEventManager.reset(); warmEmissions.clear(); - // sub case avg speed = stop go speed + // subcase avg speed = stop-go speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(dieselVehicle, diesellink, dieselLinkLength/ TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_SG_KMH *3.6 ); Assertions.assertEquals( AVG_PC_FACTOR_SG *dieselLinkLength/1000., warmEmissions.get(PM ), MatsimTestUtils.EPSILON ); emissionEventManager.reset(); @@ -141,7 +138,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent3(E /* * this test method creates a diesel vehicle and mock link - * for two cases: "current speed equals free flow speed" & "current speed equals stop go speed" the counters are tested + * for two cases: "current speed equals free flow speed" & "current speed equals stop-go speed" the counters are tested */ @ParameterizedTest @EnumSource(EmissionsConfigGroup.EmissionsComputationMethod.class) @@ -149,7 +146,7 @@ void testCounters4(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp WarmEmissionAnalysisModule emissionsModule = setUp(emissionsComputationMethod); - // case 3 - stop go entry in both tables, free flow entry in average table -> use average + // case 3 - stop-go entry in both tables, free flow entry in average table -> use average Id dieselVehicleId = Id.create("vehicle 3", Vehicle.class); double dieselLinkLength= 200.*1000; Id dieselVehicleTypeId = Id.create( @@ -158,7 +155,7 @@ void testCounters4(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Vehicle dieselVehicle = vehFac.createVehicle(dieselVehicleId, vehFac.createVehicleType(dieselVehicleTypeId)); Link diesellink = TestWarmEmissionAnalysisModule.createMockLink("link 3", dieselLinkLength, TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_FF_KMH / 3.6 ); - // sub case: current speed equals free flow speed + // subcase: current speed equals free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(dieselVehicle, diesellink, dieselLinkLength/ TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_FF_KMH *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(dieselLinkLength/1000., emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); @@ -169,7 +166,7 @@ void testCounters4(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Assertions.assertEquals(1, emissionsModule.getWarmEmissionEventCounter() ); emissionsModule.reset(); - // sub case: current speed equals stop go speed + // subcase: current speed equals stop-go speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(dieselVehicle, diesellink, dieselLinkLength/ TestWarmEmissionAnalysisModule.AVG_PASSENGER_CAR_SPEED_SG_KMH *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(0., emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase4.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase4.java index 838573a0e35..7f085baf2fb 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase4.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase4.java @@ -23,7 +23,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.matsim.api.core.v01.Id; @@ -57,12 +56,12 @@ * weamParameter - testWarmEmissionAnalysisParameter * throw warm EmissionEvent - testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions - * get free flow occurences - testCounters*() - * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get free flow occurrences - testCounters*() + * get fraction occurrences - testCounters*() + * get stop-go occurrences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() - * get top go km couter - testCounters*() + * get top go km counter - testCounters*() * get warm emission event counter - testCounters*() * * private methods and corresponding tests: @@ -105,7 +104,7 @@ public class TestWarmEmissionAnalysisModuleCase4{ /* * this test method creates a vehicle (lpg properties) and a mock link - * for two cases: "avg speed = stop go speed" & "avg speed = free flow speed" the PM warm Emissions and the Emissions "sum" are tested + * for two cases: "avg speed = stop-go speed" & "avg speed = free flow speed" the PM warm Emissions and the Emissions "sum" are tested * average values are used */ @ParameterizedTest @@ -123,7 +122,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent4(E VehiclesFactory vehFac = VehicleUtils.getFactory(); Vehicle lpgVehicle = vehFac.createVehicle(lpgVehicleId, vehFac.createVehicleType(lpgVehicleTypeId)); - // sub case avg speed = stop go speed + // subcase avg speed = stop-go speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(lpgVehicle, lpglink, lpgLinkLength/ SPEED_SG *3.6 ); Assertions.assertEquals( AVG_PC_FACTOR_SG *lpgLinkLength/1000., warmEmissions.get(PM), MatsimTestUtils.EPSILON ); emissionEventManager.reset(); @@ -132,7 +131,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent4(E emissionEventManager.reset(); warmEmissions.clear(); - // sub case avg speed = free flow speed + // subcase avg speed = free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(lpgVehicle, lpglink, lpgLinkLength/ SPEED_FF *3.6 ); Assertions.assertEquals( AVG_PC_FACTOR_FF *lpgLinkLength/1000., warmEmissions.get(PM ), MatsimTestUtils.EPSILON ); emissionEventManager.reset(); @@ -144,7 +143,7 @@ void testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent4(E /* * this test method creates a vehicle and mock link - * for two cases: "avg speed = stop go speed" & "avg speed = free flow speed" the PM warm Emissions are tested + * for two cases: "avg speed = stop-go speed" & "avg speed = free flow speed" the PM warm Emissions are tested * average values are used */ @ParameterizedTest @@ -161,7 +160,7 @@ void testCounters2(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Link lpgLink = TestWarmEmissionAnalysisModule.createMockLink("link zero", lpgLinkLength, SPEED_FF / 3.6 ); - // sub case: current speed equals free flow speed + // subcase: current speed equals free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(vehicle, lpgLink, lpgLinkLength/ SPEED_FF *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(lpgLinkLength/1000, emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); @@ -172,7 +171,7 @@ void testCounters2(EmissionsConfigGroup.EmissionsComputationMethod emissionsComp Assertions.assertEquals(1, emissionsModule.getWarmEmissionEventCounter() ); emissionsModule.reset(); - // sub case: current speed equals free flow speed + // subcase: current speed equals free flow speed warmEmissions = emissionsModule.checkVehicleInfoAndCalculateWarmEmissions(vehicle, lpgLink, lpgLinkLength/ SPEED_SG *3.6 ); Assertions.assertEquals(0, emissionsModule.getFractionOccurences() ); Assertions.assertEquals(0., emissionsModule.getFreeFlowKmCounter(), MatsimTestUtils.EPSILON ); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase5.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase5.java index c1ba590dcfa..a792d37d620 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase5.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleCase5.java @@ -22,9 +22,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; @@ -37,7 +35,6 @@ import org.matsim.vehicles.VehiclesFactory; import java.util.*; -import java.util.stream.Stream; import static org.matsim.contrib.emissions.Pollutant.PM; @@ -46,7 +43,7 @@ */ /* - * Case 5 - data in detailed table, stop go speed zero + * Case 5 - data in detailed table, stop-go speed zero */ @@ -60,12 +57,12 @@ * testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions * check vehicle info and calculate warm emissions -testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent*, * testCheckVehicleInfoAndCalculateWarmEmissions_and_throwWarmEmissionEvent_Exceptions - * get free flow occurences - testCounters*() - * get fraction occurences - testCounters*() - * get stop go occurences - testCounters*() + * get free flow occurrences - testCounters*() + * get fraction occurrences - testCounters*() + * get stop-go occurrences - testCounters*() * get km counter - testCounters*() * get free flow km counter - testCounters*() - * get top go km couter - testCounters*() + * get top go km counter - testCounters*() * get warm emission event counter - testCounters*() * * private methods and corresponding tests: @@ -93,7 +90,7 @@ public class TestWarmEmissionAnalysisModuleCase5 { private final HandlerToTestEmissionAnalysisModules emissionEventManager = new HandlerToTestEmissionAnalysisModules(); // vehicle information for regular test cases - // case 5 - data in detailed table, stop go speed zero + // case 5 - data in detailed table, stop-go speed zero private final String zeroRoadCategory = "URB_case6"; private final String zeroTechnology = "zero technology"; private final String zeroConcept = "zero concept"; diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleTrafficSituations.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleTrafficSituations.java index 3289f013639..6d65c3ea4f6 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleTrafficSituations.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/TestWarmEmissionAnalysisModuleTrafficSituations.java @@ -19,12 +19,8 @@ * *********************************************************************** */ import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Node; @@ -39,7 +35,6 @@ import org.matsim.vehicles.VehiclesFactory; import java.util.*; -import java.util.stream.Stream; import static org.matsim.contrib.emissions.HbefaTrafficSituation.*; import static org.matsim.contrib.emissions.Pollutant.NOx; @@ -79,7 +74,7 @@ public class TestWarmEmissionAnalysisModuleTrafficSituations { private static final String petrolConcept ="<1,4L"; private static final double[] detailedPetrolFactor = {10, 100, 1000, 10000, 100000}; - // case 2 - free flow entry in both tables, stop go entry in average table -> use average + // case 2 - free flow entry in both tables, stop-go entry in average table -> use average private static final String pcTechnology = "PC petrol <1,4L * LookupBehavior: onlyTryDetailedElseAbort - * + *

        * -> should calculate value */ @Test void testWarmDetailedValueOnlyDetailed() { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s Map warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFull, link, travelTimeOnLink); double expectedValue = 30.34984742; // = 200m * 151.7492371 g/km @@ -84,7 +84,7 @@ void testWarmDetailedValueOnlyDetailed() { * * vehicles information is complete but fully specified entry is NOT available in detailed table * LookupBehavior: onlyTryDetailedElseAbort - * + *

        * -> should abort --> RuntimeException */ @Test @@ -92,7 +92,7 @@ void testWarm_DetailedElseAbort_ShouldAbort1() { assertThrows(RuntimeException.class, () -> { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToTechnologyAverage, link, travelTimeOnLink); }); } @@ -100,9 +100,9 @@ void testWarm_DetailedElseAbort_ShouldAbort1() { /** * vehicles information is complete but fully specified entry is NOT available in detailed table * HbefaTechnology is also not in detailed table -> fall back to technology average is NOT possible as well. - * + *

        * LookupBehavior: onlyTryDetailedElseAbort - * + *

        * -> should abort --> RuntimeException */ @Test @@ -110,17 +110,17 @@ void testWarm_DetailedElseAbort_ShouldAbort2() { assertThrows(RuntimeException.class, () -> { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToAverageTable, link, travelTimeOnLink); }); } -// --------- DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageElseAbort) ----------- +// --------- DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageElseAbort) ----------- /** * vehicles information is complete * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

        * -> do NOT fall back to technology average * ---> should calculate value from detailed value */ @@ -128,7 +128,7 @@ void testWarm_DetailedElseAbort_ShouldAbort2() { void testWarm_DetailedThenTechnologyAverageElseAbort_FallbackNotNeeded() { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageElseAbort); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s Map warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFull, link, travelTimeOnLink); double expectedValue = 30.34984742; // = 200m * 151.7492371 g/km @@ -139,7 +139,7 @@ void testWarm_DetailedThenTechnologyAverageElseAbort_FallbackNotNeeded() { /** * vehicles information is complete but fully specified entry is NOT available in detailed table * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

        * -> do fall back to technology average * ---> should calculate value from technology average */ @@ -147,7 +147,7 @@ void testWarm_DetailedThenTechnologyAverageElseAbort_FallbackNotNeeded() { void testWarm_DetailedThenTechnologyAverageElseAbort_FallbackToTechnologyAverage() { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageElseAbort); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s Map warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToTechnologyAverage, link, travelTimeOnLink); double expectedValue = 31.53711548; // = 200m * 157.6855774 g/km @@ -157,9 +157,9 @@ void testWarm_DetailedThenTechnologyAverageElseAbort_FallbackToTechnologyAverage /** * vehicles information is complete but fully specified entry is NOT available in detailed table * HbefaTechnology is also not in detailed table -> fall back to technology average is NOT possible as well. - * + *

        * LookupBehavior: onlyTryDetailedElseAbort - * + *

        * -> should abort --> RuntimeException */ @Test @@ -167,16 +167,16 @@ void testWarm_DetailedThenTechnologyAverageElseAbort_ShouldAbort() { assertThrows(RuntimeException.class, () -> { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToAverageTable, link, travelTimeOnLink); }); } -// --------- DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable ----------- +// --------- DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable ----------- /** * vehicles information is complete * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

        * -> do NOT fall back to technology average or average table * ---> should calculate value from detailed value */ @@ -184,7 +184,7 @@ void testWarm_DetailedThenTechnologyAverageElseAbort_ShouldAbort() { void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackNotNeeded() { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s Map warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFull, link, travelTimeOnLink); double expectedValue = 30.34984742; // = 200m * 151.7492371 g/km @@ -195,7 +195,7 @@ void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackNotNeeded() /** * vehicles information is complete but fully specified entry is NOT available in detailed table * LookupBehavior: tryDetailedThenTechnologyAverageElseAbort - * + *

        * -> do fall back to technology average; do NOT fall back to average table * ---> should calculate value from technology average */ @@ -203,7 +203,7 @@ void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackNotNeeded() void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackToTechnology() { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s Map warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToTechnologyAverage, link, travelTimeOnLink); double expectedValue = 31.53711548; // = 200m * 157.6855774 g/km @@ -213,9 +213,9 @@ void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackToTechnology /** * vehicles information is complete but fully specified entry is NOT available in detailed table * HbefaTechnology is also not in detailed table -> fall back to technology average is NOT possible as well. - * + *

        * LookupBehavior: tryDetailedThenTechnologyAverageThenAverageTable - * + *

        * -> do fall back to average table * ---> should calculate value from average table */ @@ -223,7 +223,7 @@ void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackToTechnology void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackToAverageTable() { EmissionModule emissionModule = setUpScenario(EmissionsConfigGroup.DetailedVsAverageLookupBehavior.tryDetailedThenTechnologyAverageThenAverageTable); - double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72.. m/s) approx 20.57 s + double travelTimeOnLink = 21; //sec. approx freeSpeed of link12 is : (200 m) / (9.72... m/s) approx 20.57 s Map warmEmissions = emissionModule.getWarmEmissionAnalysisModule().checkVehicleInfoAndCalculateWarmEmissions(vehicleFallbackToAverageTable, link, travelTimeOnLink); double expectedValue = 31.1947174; // = 200m * 155.973587 g/km @@ -233,7 +233,7 @@ void testWarm_DetailedThenTechnologyAverageThenAverageTable_FallbackToAverageTab -// ---------- setup and helper methods ------------- +// ---------- setup and helper methods ------------- /** * load and prepare the scenario, create the emissionsModule diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMappingTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMappingTest.java index f0164d11e86..fb906ac6f63 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMappingTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/VspHbefaRoadTypeMappingTest.java @@ -16,7 +16,7 @@ void testSimpleMapping() { var mapper = new VspHbefaRoadTypeMapping(); var link = getTestLink("", 70 / 3.6); - var result = mapper.determineHebfaType(link); + var result = mapper.determineHbefaType(link); assertEquals("URB/MW-Nat./80", result); } @@ -36,4 +36,4 @@ private static Link getTestLink(String osmRoadType, double allowedSpeed) { return link; } -} \ No newline at end of file +} diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzerTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzerTest.java index d9614bd3dea..ef291d8d788 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzerTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionGridAnalyzerTest.java @@ -69,7 +69,7 @@ void process() { final Pollutant pollutant = HC; final double pollutionPerEvent = 1; - Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); Network network = TestUtils.createRandomNetwork(100, 1000, 1000); TestUtils.writeWarmEventsToFile(eventsFile, network, pollutant, pollutionPerEvent, 1, 99); @@ -95,7 +95,7 @@ void process_singleLinkWithOneEvent() { final Pollutant pollutant = CO; final double pollutionPerEvent = 1000; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); final Network network = NetworkUtils.createNetwork(); Node from = network.getFactory().createNode(Id.createNodeId("from"), new Coord(5, 5)); network.addNode(from); @@ -134,7 +134,7 @@ void process_singleLinkWithTwoEvents() { final Pollutant pollutant = CO; final double pollutionPerEvent = 1000; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); final Network network = NetworkUtils.createNetwork(); Node from = network.getFactory().createNode(Id.createNodeId("from"), new Coord(5, 5)); network.addNode(from); @@ -173,7 +173,7 @@ void process_twoLinksWithOneEventEach() { final Pollutant pollutant = CO; final double pollutionPerEvent = 1000; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); final Network network = NetworkUtils.createNetwork(); Node from = network.getFactory().createNode(Id.createNodeId("from"), new Coord(5, 5)); network.addNode(from); @@ -215,7 +215,7 @@ void process_twoLinksWithTwoEventsEach() { final Pollutant pollutant = NOx; final double pollutionPerEvent = 1000; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); final Network network = NetworkUtils.createNetwork(); Node from = network.getFactory().createNode(Id.createNodeId("from"), new Coord(5, 5)); network.addNode(from); @@ -255,7 +255,7 @@ void process_twoLinksWithTwoEventsEach() { void process_withBoundaries() { final double pollutionPerEvent = 1; - Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); Network network = TestUtils.createRandomNetwork(100, 1000, 1000); TestUtils.writeWarmEventsToFile(eventsFile, network, NOx, pollutionPerEvent, 1, 99); @@ -281,7 +281,7 @@ void processToJson() { final double pollutionPerEvent = 1; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); final Network network = TestUtils.createRandomNetwork(1, 1000, 1000); TestUtils.writeWarmEventsToFile(eventsFile, network, NO2, pollutionPerEvent, time, time + 3); @@ -302,8 +302,8 @@ void processToJsonFile() throws IOException { final double pollutionPerEvent = 1; final int time = 1; - final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".xml"); - final Path jsonFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID().toString() + ".json"); + final Path eventsFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".xml"); + final Path jsonFile = Paths.get(testUtils.getOutputDirectory()).resolve(UUID.randomUUID() + ".json"); final Network network = TestUtils.createRandomNetwork(1, 1000, 1000); TestUtils.writeWarmEventsToFile(eventsFile, network, NO2, pollutionPerEvent, time, time + 3); @@ -386,9 +386,9 @@ private void writeGridToCSV(TimeBinMap>> bins, Strin } } - private void assertCsvValuesAreSame(Path expected, Path acutal) throws IOException { + private void assertCsvValuesAreSame(Path expected, Path actual) throws IOException { - try (FileReader expectedReader = new FileReader(expected.toString()); var actualReader = new FileReader(acutal.toString())) { + try (FileReader expectedReader = new FileReader(expected.toString()); var actualReader = new FileReader(actual.toString())) { var actualIterator = CSVFormat.TDF.withFirstRecordAsHeader().parse(actualReader).iterator(); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java index 635affd8832..52ed3393a4f 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/EmissionsByPollutantTest.java @@ -17,7 +17,7 @@ public class EmissionsByPollutantTest { // The EmissionsByPollutant potentially adds up the same emissions coming from cold and warm. Thus, this cannot be combined into the enum approach // without some thinking. kai, jan'20 - // Quite possibly, should just combine them into an enum "pollutant"?! There is, anyways, the JM map of those emissions that are actually present in the + // Quite possibly, should just combine them into an enum "pollutant"?! There is, anyway, the JM map of those emissions that are actually present in the // input file. kai, jan'20 @Test @@ -25,8 +25,7 @@ void initialize() { Map emissions = EmissionUtilsTest.createEmissions(); - Map map = new LinkedHashMap<>(); - emissions.forEach( map::put ) ; + Map map = new LinkedHashMap<>(emissions); EmissionsByPollutant linkEmissions = new EmissionsByPollutant( map ) ; @@ -46,8 +45,7 @@ void addEmission() { final Pollutant pollutant = CO; final double expectedValue = emissions.get(pollutant) + valueToAdd; - Map map = new LinkedHashMap<>(); - emissions.forEach( map::put ) ; + Map map = new LinkedHashMap<>(emissions); EmissionsByPollutant emissionsByPollutant = new EmissionsByPollutant(map); @@ -79,13 +77,11 @@ void addEmissions() { Map emissions = EmissionUtilsTest.createEmissions(); - Map map = new LinkedHashMap<>(); - emissions.forEach( map::put ) ; + Map map = new LinkedHashMap<>(emissions); EmissionsByPollutant linkEmissions = new EmissionsByPollutant(map); - Map map2 = new LinkedHashMap<>(); - emissions.forEach( map2::put ) ; + Map map2 = new LinkedHashMap<>(emissions); linkEmissions.addEmissions(map2); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReaderTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReaderTest.java index 4592d26ec17..955c1d4313d 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReaderTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/analysis/RawEmissionEventsReaderTest.java @@ -22,7 +22,7 @@ public class RawEmissionEventsReaderTest { @Test void handleNonEventNode() { - // read in an xml file which doesn't have events. It will parse the whole file but will not handle any of the + // read in a xml file which doesn't have events. It will parse the whole file but will not handle any of the // parsed nodes var networkUrl = IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "network.xml"); new RawEmissionEventsReader((time, linkId, vehicleId, pollutant, value) -> { @@ -36,7 +36,7 @@ void handleNonEventNode() { @Test void handleNonEmissionEvent() { - // read in events file wihtout emission events. Those events should be ignored + // read in events file without emission events. Those events should be ignored var eventsUrl = IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("equil"), "output_events.xml.gz"); new RawEmissionEventsReader((time, linkId, vehicleId, pollutant, value) -> { // this method should not be called diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestColdEmissionEventImpl.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestColdEmissionEventImpl.java index 022265df9f0..9a3af2d8601 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestColdEmissionEventImpl.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestColdEmissionEventImpl.java @@ -62,7 +62,7 @@ final void testGetAttributesForCompleteEmissionMaps(){ Map coldEmissionsMap = new HashMap<>(); setColdEmissions(coldEmissionsMap); ColdEmissionEvent ce = new ColdEmissionEvent(0.0, linkId, vehicleId, coldEmissionsMap); - + Map ceg = ce.getAttributes(); Assertions.assertEquals(Double.parseDouble(ceg.get(CO.name())), co, MatsimTestUtils.EPSILON, "the CO value of this cold emission event was "+ Double.parseDouble(ceg.get(CO.name()))+ "but should have been "+ co); Assertions.assertEquals(Double.parseDouble(ceg.get(FC.name())), fc, MatsimTestUtils.EPSILON, "the FC value of this cold emission event was "+ Double.parseDouble(ceg.get(FC.name()))+ "but should have been "+ fc); @@ -71,7 +71,7 @@ final void testGetAttributesForCompleteEmissionMaps(){ Assertions.assertEquals(Double.parseDouble(ceg.get(NO2.name())), n2, MatsimTestUtils.EPSILON, "the NO2 value of this cold emission event was "+ Double.parseDouble(ceg.get(NO2.name()))+ "but should have been "+ n2); Assertions.assertEquals(Double.parseDouble(ceg.get(NOx.name())), nx, MatsimTestUtils.EPSILON, "the NOx value of this cold emission event was "+ Double.parseDouble(ceg.get(NOx.name()))+ "but should have been "+ nx); Assertions.assertEquals(Double.parseDouble(ceg.get(PM.name())), pm, MatsimTestUtils.EPSILON, "the PM value of this cold emission event was "+ Double.parseDouble(ceg.get(PM.name()))+ "but should have been "+ pm); - + } private void setColdEmissions( Map coldEmissionsMap ) { @@ -90,12 +90,12 @@ final void testGetAttributesForIncompleteMaps(){ //the getAttributesMethod should // - return null if the emission map is empty // - throw NullPointerExceptions if the emission values are not set - // - throw NullPointerExceptions if no emission map is assigned - + // - throw NullPointerExceptions if no emission map is assigned + //empty map Map emptyMap = new HashMap<>(); ColdEmissionEvent emptyMapEvent = new ColdEmissionEvent(22., linkId, vehicleId, emptyMap); - + //values not set Map valuesNotSet = new HashMap<>(); valuesNotSet.put(CO, null); @@ -106,30 +106,30 @@ final void testGetAttributesForIncompleteMaps(){ valuesNotSet.put(NOx, null); valuesNotSet.put(PM, null); ColdEmissionEvent valuesNotSetEvent = new ColdEmissionEvent(44., linkId, vehicleId, valuesNotSet); - + //no map ColdEmissionEvent noMap = new ColdEmissionEvent(50., linkId, vehicleId, null); - + int numberOfColdPollutants = coldPollutants.size(); int valNullPointers = 0, noMapNullPointers=0; - + for(Pollutant cp : coldPollutants){ //empty map - Assertions.assertNull(emptyMapEvent.getAttributes().get(cp)); - + Assertions.assertNull(emptyMapEvent.getAttributes().get(cp.name())); + //values not set try{ - valuesNotSetEvent.getAttributes().get(cp); + valuesNotSetEvent.getAttributes().get(cp.name()); } catch(NullPointerException e){ valNullPointers ++; } - + //no map try{ - noMap.getAttributes().get(cp); + noMap.getAttributes().get(cp.name()); } catch(NullPointerException e){ noMapNullPointers++; @@ -138,5 +138,5 @@ final void testGetAttributesForIncompleteMaps(){ Assertions.assertEquals(numberOfColdPollutants, valNullPointers); Assertions.assertEquals(numberOfColdPollutants, noMapNullPointers); } - + } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java index 62691c3670f..b203c8792ce 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/events/TestWarmEmissionEventImpl.java @@ -42,55 +42,52 @@ public class TestWarmEmissionEventImpl { - + private final Id vehicleId = Id.create("veh 1", Vehicle.class); private final Id linkId = Id.create("link 1", Link.class); - private final Double co = 20.; - private final Double c2 = 8.; - private final Double fc = 30.; - private final Double hc=4.; - private final Double nm=5.; - private final Double n2=6.; - private final Double nx=7.; - private final Double pm=8.; - private final Double so=1.6; -// private final Set pollutants = new HashSet<>(Arrays.asList(CO, CO2_TOTAL, FC, HC, NMHC, NOx, NO2,PM, SO2)); + private final Double co_value = 20.; + private final Double co2total_value = 8.; + private final Double fc_value = 30.; + private final Double hc_value =4.; + private final Double nmhc_value =5.; + private final Double no2_value =6.; + private final Double nox_value =7.; + private final Double pm_value =8.; + private final Double so2_value =1.6; private final Set pollutants = new HashSet<>( Arrays.asList( Pollutant.values() ) ); @Test final void testGetAttributesForCompleteEmissionMaps(){ //test normal functionality - + //create a normal event impl Map warmEmissionsMap = new HashMap<>(); - warmEmissionsMap.put(CO, co ); - warmEmissionsMap.put(CO2_TOTAL, c2 ); - warmEmissionsMap.put(FC, fc ); - warmEmissionsMap.put(HC, hc ); - warmEmissionsMap.put(NMHC, nm ); - warmEmissionsMap.put(NO2, n2 ); - warmEmissionsMap.put(NOx, nx ); - warmEmissionsMap.put(PM, pm ); - warmEmissionsMap.put(SO2, so ); + warmEmissionsMap.put(CO, co_value); + warmEmissionsMap.put(CO2_TOTAL, co2total_value); + warmEmissionsMap.put(FC, fc_value); + warmEmissionsMap.put(HC, hc_value); + warmEmissionsMap.put(NMHC, nmhc_value); + warmEmissionsMap.put(NO2, no2_value); + warmEmissionsMap.put(NOx, nox_value); + warmEmissionsMap.put(PM, pm_value); + warmEmissionsMap.put(SO2, so2_value); - Map map = new LinkedHashMap<>(); - warmEmissionsMap.forEach( (key,value) -> map.put( key, value ) ); - // (this could be made more direct) + Map map = new LinkedHashMap<>(warmEmissionsMap); WarmEmissionEvent we = new WarmEmissionEvent(0.0, linkId, vehicleId, map); - + Map weg = we.getAttributes(); - Assertions.assertEquals(Double.parseDouble(weg.get(CO.name())), co, MatsimTestUtils.EPSILON, "the CO value of this warm emission event was "+ Double.parseDouble(weg.get(CO.name()))+ "but should have been "+ co); - Assertions.assertEquals(Double.parseDouble(weg.get(CO2_TOTAL.name())), c2, MatsimTestUtils.EPSILON, "the CO2 value of this warm emission event was "+ Double.parseDouble(weg.get(CO2_TOTAL.name()))+ "but should have been "+ c2); - Assertions.assertEquals(Double.parseDouble(weg.get(FC.name())), fc, MatsimTestUtils.EPSILON, "the FC value of this warm emission event was "+ Double.parseDouble(weg.get(FC.name()))+ "but should have been "+ fc); - Assertions.assertEquals(Double.parseDouble(weg.get(HC.name())), hc, MatsimTestUtils.EPSILON, "the HC value of this warm emission event was "+ Double.parseDouble(weg.get(HC.name()))+ "but should have been "+ hc); - Assertions.assertEquals(Double.parseDouble(weg.get(NMHC.name())), nm, MatsimTestUtils.EPSILON, "the NMHC value of this warm emission event was "+ Double.parseDouble(weg.get(NMHC.name()))+ "but should have been "+ nm); - Assertions.assertEquals(Double.parseDouble(weg.get(NO2.name())), n2, MatsimTestUtils.EPSILON, "the NO2 value of this warm emission event was "+ Double.parseDouble(weg.get(NO2.name()))+ "but should have been "+ n2); - Assertions.assertEquals(Double.parseDouble(weg.get(NOx.name())), nx, MatsimTestUtils.EPSILON, "the NOx value of this warm emission event was "+ Double.parseDouble(weg.get(NOx.name()))+ "but should have been "+ nx); - Assertions.assertEquals(Double.parseDouble(weg.get(PM.name())), pm, MatsimTestUtils.EPSILON, "the PM value of this warm emission event was "+ Double.parseDouble(weg.get(PM.name()))+ "but should have been "+ pm); - Assertions.assertEquals(Double.parseDouble(weg.get(SO2.name())), so, MatsimTestUtils.EPSILON, "the SO2 value of this warm emission event was "+ Double.parseDouble(weg.get(SO2.name()))+ "but should have been "+ so); + Assertions.assertEquals(Double.parseDouble(weg.get(CO.name())), co_value, MatsimTestUtils.EPSILON, "the CO value of this warm emission event was "+ Double.parseDouble(weg.get(CO.name()))+ "but should have been "+ co_value); + Assertions.assertEquals(Double.parseDouble(weg.get(CO2_TOTAL.name())), co2total_value, MatsimTestUtils.EPSILON, "the CO2 value of this warm emission event was "+ Double.parseDouble(weg.get(CO2_TOTAL.name()))+ "but should have been "+ co2total_value); + Assertions.assertEquals(Double.parseDouble(weg.get(FC.name())), fc_value, MatsimTestUtils.EPSILON, "the FC value of this warm emission event was "+ Double.parseDouble(weg.get(FC.name()))+ "but should have been "+ fc_value); + Assertions.assertEquals(Double.parseDouble(weg.get(HC.name())), hc_value, MatsimTestUtils.EPSILON, "the HC value of this warm emission event was "+ Double.parseDouble(weg.get(HC.name()))+ "but should have been "+ hc_value); + Assertions.assertEquals(Double.parseDouble(weg.get(NMHC.name())), nmhc_value, MatsimTestUtils.EPSILON, "the NMHC value of this warm emission event was "+ Double.parseDouble(weg.get(NMHC.name()))+ "but should have been "+ nmhc_value); + Assertions.assertEquals(Double.parseDouble(weg.get(NO2.name())), no2_value, MatsimTestUtils.EPSILON, "the NO2 value of this warm emission event was "+ Double.parseDouble(weg.get(NO2.name()))+ "but should have been "+ no2_value); + Assertions.assertEquals(Double.parseDouble(weg.get(NOx.name())), nox_value, MatsimTestUtils.EPSILON, "the NOx value of this warm emission event was "+ Double.parseDouble(weg.get(NOx.name()))+ "but should have been "+ nox_value); + Assertions.assertEquals(Double.parseDouble(weg.get(PM.name())), pm_value, MatsimTestUtils.EPSILON, "the PM value of this warm emission event was "+ Double.parseDouble(weg.get(PM.name()))+ "but should have been "+ pm_value); + Assertions.assertEquals(Double.parseDouble(weg.get(SO2.name())), so2_value, MatsimTestUtils.EPSILON, "the SO2 value of this warm emission event was "+ Double.parseDouble(weg.get(SO2.name()))+ "but should have been "+ so2_value); } @Test @@ -98,12 +95,12 @@ final void testGetAttributesForIncompleteMaps(){ //the getAttributesMethod should // - return null if the emission map is empty // - throw NullPointerExceptions if the emission values are not set - // - throw NullPointerExceptions if no emission map is assigned - + // - throw NullPointerExceptions if no emission map is assigned + //empty map Map emptyMap = new HashMap<>(); WarmEmissionEvent emptyMapEvent = new WarmEmissionEvent(22., linkId, vehicleId, emptyMap); - + //values not set Map valuesNotSet = new HashMap<>(); valuesNotSet.put(CO, null); @@ -114,25 +111,23 @@ final void testGetAttributesForIncompleteMaps(){ valuesNotSet.put(NOx, null); valuesNotSet.put(PM, null); - Map map = new LinkedHashMap<>(); - valuesNotSet.forEach( (key,value) -> map.put( key, value ) ); - // (this could be made more direct) + Map map = new LinkedHashMap<>(valuesNotSet); WarmEmissionEvent valuesNotSetEvent = new WarmEmissionEvent(44., linkId, vehicleId, map); - + //no map WarmEmissionEvent noMap = new WarmEmissionEvent(23, linkId, vehicleId, null); - + int numberOfWarmPollutants = pollutants.size(); int valuesNotSetNullPointers =0, noMapNullPointers=0; - + for( Pollutant wpEnum : pollutants){ String wp=wpEnum.name(); //empty map Assertions.assertNull(emptyMapEvent.getAttributes().get(wp)); - + //values not set try{ valuesNotSetEvent.getAttributes().get(wp); @@ -140,7 +135,7 @@ final void testGetAttributesForIncompleteMaps(){ catch(NullPointerException e){ valuesNotSetNullPointers++; } - + //no map try{ noMap.getAttributes().get(wp); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExampleIT.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExampleIT.java index e2ed6c54bba..09d0e9bc5b0 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExampleIT.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOfflineExampleIT.java @@ -42,7 +42,7 @@ public class RunDetailedEmissionToolOfflineExampleIT { * * */ - // Expecting RuntimeException, because requested values are only in average file. Without fallback it has to fail! + // Expecting RuntimeException, because requested values are only in average file. Without fallback, it has to fail! // @Test(expected=RuntimeException.class) @Test final void testDetailed_vehTypeV1() { @@ -67,7 +67,7 @@ final void testDetailed_vehTypeV1() { Assertions.assertTrue( gotAnException ); } - // Expecting RuntimeException, because requested values are only in average file. Without fallback it has to fail! + // Expecting RuntimeException, because requested values are only in average file. Without fallback, it has to fail! // @Test(expected=RuntimeException.class) @Test final void testDetailed_vehTypeV2() { @@ -91,7 +91,7 @@ final void testDetailed_vehTypeV2() { Assertions.assertTrue( gotAnException ); } - // Expecting RuntimeException, because requested values are only in average file. Without fallback it has to fail! + // Expecting RuntimeException, because requested values are only in average file. Without fallback, it has to fail! // @Test(expected=RuntimeException.class) @Test final void testDetailed_vehTypeV2_HBEFA4() { diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java index 1c16db00fa9..892803c548e 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1.java @@ -26,6 +26,7 @@ import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; +import org.matsim.core.scenario.ScenarioUtils; import org.matsim.testcases.MatsimTestUtils; /** @@ -45,21 +46,21 @@ public class RunDetailedEmissionToolOnlineExampleIT_vehTypeV1 { * This is by now (feb'20) the default. Setting it here for the tests explicitly * * */ -// @Test(expected=RuntimeException.class) // Expecting RuntimeException, because requested values are only in average file. Without fallback it has to fail! - @Disabled //Ignore this test, because the thrown exception during events handling does not always leads to an abort of the Simulation ->> Maybe a problem in @link{ParallelEventsManagerImpl.class}? +// @Test(expected=RuntimeException.class) // Expecting RuntimeException, because requested values are only in average file. Without fallback, it has to fail! + @Disabled //Ignore this test, because the thrown exception during events handling does not always lead to an abort of the Simulation ->> Maybe a problem in @link{ParallelEventsManagerImpl.class}? @Test final void testDetailed_vehTypeV1() { boolean gotAnException = false ; try { - RunDetailedEmissionToolOnlineExample onlineExample = new RunDetailedEmissionToolOnlineExample(); - Config config = onlineExample.prepareConfig( new String[]{"./scenarios/sampleScenario/testv2_Vehv1/config_detailed.xml"} ) ; + Config config = RunDetailedEmissionToolOnlineExample.prepareConfig( new String[]{"./scenarios/sampleScenario/testv2_Vehv1/config_detailed.xml"} ) ; config.controller().setOutputDirectory( utils.getOutputDirectory() ); config.controller().setLastIteration( 1 ); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setHbefaVehicleDescriptionSource( EmissionsConfigGroup.HbefaVehicleDescriptionSource.fromVehicleTypeDescription ); emissionsConfig.setDetailedVsAverageLookupBehavior( EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort ); - Scenario scenario = onlineExample.prepareScenario( config ) ; - onlineExample.run( scenario ) ; + + Scenario scenario = ScenarioUtils.loadScenario(config); + RunDetailedEmissionToolOnlineExample.run( scenario ) ; } catch (Exception ee ) { gotAnException = true ; } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1FallbackToAverage.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1FallbackToAverage.java index 8715b4525ed..21f6baf1404 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1FallbackToAverage.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV1FallbackToAverage.java @@ -26,6 +26,7 @@ import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; +import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; import org.matsim.testcases.MatsimTestUtils; @@ -65,7 +66,7 @@ final void testDetailed_vehTypeV1_FallbackToAverage() { emissionsConfig.setAverageWarmEmissionFactorsFile( "../sample_41_EFA_HOT_vehcat_2020average.csv" ); emissionsConfig.setHbefaTableConsistencyCheckingLevel( EmissionsConfigGroup.HbefaTableConsistencyCheckingLevel.consistent ); - Scenario scenario = RunDetailedEmissionToolOnlineExample.prepareScenario( config ) ; + Scenario scenario = ScenarioUtils.loadScenario(config); RunDetailedEmissionToolOnlineExample.run( scenario ) ; } catch ( Exception ee ) { ee.printStackTrace(); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java index 95cbc87199b..d6e33fc37f1 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2.java @@ -26,6 +26,7 @@ import org.matsim.contrib.emissions.utils.EmissionsConfigGroup; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; +import org.matsim.core.scenario.ScenarioUtils; import org.matsim.testcases.MatsimTestUtils; /** @@ -39,20 +40,20 @@ public class RunDetailedEmissionToolOnlineExampleIT_vehTypeV2 { * Test method for {@link RunDetailedEmissionToolOnlineExample#main(String[])}. */ -// @Test(expected=RuntimeException.class) // Expecting RuntimeException, because requested values are only in average file. Without fallback it has to fail! - @Disabled //Ignore this test, because the thrown exception during events handling does not always leads to an abort of the Simulation ->> Maybe a problem in @link{ParallelEventsManagerImpl.class}? +// @Test(expected=RuntimeException.class) // Expecting RuntimeException, because requested values are only in average file. Without fallback, it has to fail! + @Disabled //Ignore this test, because the thrown exception during events handling does not always lead to an abort of the Simulation ->> Maybe a problem in @link{ParallelEventsManagerImpl.class}? @Test final void testDetailed_vehTypeV2() { boolean gotAnException = false ; try { - RunDetailedEmissionToolOnlineExample onlineExample = new RunDetailedEmissionToolOnlineExample(); - Config config = onlineExample.prepareConfig( new String[]{"./scenarios/sampleScenario/testv2_Vehv2/config_detailed.xml"} ) ; + Config config = RunDetailedEmissionToolOnlineExample.prepareConfig( new String[]{"./scenarios/sampleScenario/testv2_Vehv2/config_detailed.xml"} ) ; config.controller().setOutputDirectory( utils.getOutputDirectory() ); config.controller().setLastIteration( 1 ); EmissionsConfigGroup emissionsConfig = ConfigUtils.addOrGetModule( config, EmissionsConfigGroup.class ); emissionsConfig.setDetailedVsAverageLookupBehavior( EmissionsConfigGroup.DetailedVsAverageLookupBehavior.onlyTryDetailedElseAbort ); - Scenario scenario = onlineExample.prepareScenario( config ) ; - onlineExample.run( scenario ) ; + + Scenario scenario = ScenarioUtils.loadScenario(config); + RunDetailedEmissionToolOnlineExample.run( scenario ) ; } catch (Exception ee ) { gotAnException = true ; } diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java index ef667425698..2c89b956450 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/example/RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage.java @@ -27,6 +27,7 @@ import org.matsim.contrib.emissions.utils.EmissionsConfigGroup.DetailedVsAverageLookupBehavior; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; +import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; import org.matsim.testcases.MatsimTestUtils; @@ -44,9 +45,6 @@ public class RunDetailedEmissionToolOnlineExampleIT_vehTypeV2FallbackToAverage { @Test final void testDetailed_vehTypeV2_FallbackToAverage() { try { -// RunDetailedEmissionToolOnlineExample onlineExample = new RunDetailedEmissionToolOnlineExample(); - -// Config config = onlineExample.prepareConfig( new String[]{"./scenarios/sampleScenario/testv2_Vehv2/config_detailed.xml"} ) ; var scenarioUrl = ExamplesUtils.getTestScenarioURL( "emissions-sampleScenario/testv2_Vehv2" ); var configUrl = IOUtils.extendUrl( scenarioUrl, "config_detailed.xml" ); Config config = RunDetailedEmissionToolOnlineExample.prepareConfig( new String [] { configUrl.toString() } ); @@ -60,7 +58,7 @@ final void testDetailed_vehTypeV2_FallbackToAverage() { emissionsConfig.setAverageWarmEmissionFactorsFile( "../sample_41_EFA_HOT_vehcat_2020average.csv" ); emissionsConfig.setHbefaTableConsistencyCheckingLevel( EmissionsConfigGroup.HbefaTableConsistencyCheckingLevel.consistent ); - Scenario scenario = RunDetailedEmissionToolOnlineExample.prepareScenario( config ) ; + Scenario scenario = ScenarioUtils.loadScenario(config); RunDetailedEmissionToolOnlineExample.run( scenario ) ; } catch ( Exception ee ) { ee.printStackTrace(); diff --git a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java index 4f20dfbf78f..f71692faa5e 100644 --- a/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java +++ b/contribs/emissions/src/test/java/org/matsim/contrib/emissions/utils/EmissionUtilsTest.java @@ -52,8 +52,8 @@ * missing data is not tested here * negative emission values are allowed * 1 test constructor - * 2 test sumUpEmissions - * 3 test sumUpEmissionPerId + * 2 test sumUpEmissions + * 3 test sumUpEmissionPerId * 4 test getTotalEmissions * 5 test SetNonCalculatedEmissionsForPopulation * - correct input - population does not match map of emissions - empty map of emissions @@ -74,8 +74,6 @@ public class EmissionUtilsTest { private boolean nullPointerEx; public static Map createUntypedEmissions() { -// return Arrays.asList("co2", CO, NOx, "NO", NO2, HC).stream() -// .collect(Collectors.toMap(p -> p, p -> Math.random())); return Stream.of(CO2_TOTAL, CO, NOx, NO2, HC) .collect(Collectors.toMap(p -> p, p -> Math.random())); } @@ -292,7 +290,7 @@ final void testGetTotalEmissions_completeData() { //put some content into the list // no incorrect/incomplete input data here - // warm and cold emissions are already sumed up -> sumUpEmissionsPerId is tested seperatly + // warm and cold emissions are already summed up -> sumUpEmissionsPerId is tested separately //person1 SortedMap allEmissionsP1 = new TreeMap<>(); @@ -430,7 +428,7 @@ final void testSetNonCalculatedEmissionsForPopulation_completeData(){ //check: all values for person 1 and 2 are not null or zero // and of type double for(Object id : finalMap.keySet()) { - Assertions.assertTrue(id instanceof Id); + Assertions.assertInstanceOf(Id.class, id); for (Object pollutant : finalMap.get(id).values()) { Assertions.assertSame(pollutant.getClass(), Double.class); Assertions.assertNotSame(0.0, pollutant); @@ -442,7 +440,7 @@ final void testSetNonCalculatedEmissionsForPopulation_completeData(){ } //nothing else in the list int numOfPolls = pollsFromEU.size(); - Assertions.assertEquals(numOfPolls, finalMap.get(id).keySet().size(), "the number of pullutants is " + finalMap.get(id).keySet().size() + " but should be" + numOfPolls); + Assertions.assertEquals(numOfPolls, finalMap.get(id).keySet().size(), "the number of pollutants is " + finalMap.get(id).keySet().size() + " but should be" + numOfPolls); } //check: values for all emissions are correct -person 1 @@ -486,11 +484,11 @@ final void testSetNonCalculatedEmissionsForPopulation_missingMap() { message = "the calculated map should contain " + pop.getPersons().size() + " person(s) but contains " + finalMap.keySet().size() + "person(s)."; Assertions.assertEquals(pop.getPersons().keySet().size(), finalMap.keySet().size(), message); - //check: all values for the this person are zero and of type double - for (Object pollutant : finalMap.get(idp3).values()) { - Assertions.assertSame(pollutant.getClass(), Double.class); - Assertions.assertEquals(0.0, (Double) pollutant, MatsimTestUtils.EPSILON); - Assertions.assertNotNull(pollutant); + //check: all values for this person are zero and of type double + for (Double pollutantValues : finalMap.get(idp3).values()) { + Assertions.assertSame(pollutantValues.getClass(), Double.class); + Assertions.assertEquals(0.0, pollutantValues, MatsimTestUtils.EPSILON); + Assertions.assertNotNull(pollutantValues); } //check: all types of emissions appear for (Pollutant emission : pollsFromEU) { @@ -498,7 +496,7 @@ final void testSetNonCalculatedEmissionsForPopulation_missingMap() { } //nothing else in the list int numOfPolls = pollsFromEU.size(); - message = "the number of pullutants is " + finalMap.get(idp3).keySet().size() + " but should be" + numOfPolls; + message = "the number of pollutants is " + finalMap.get(idp3).keySet().size() + " but should be" + numOfPolls; Assertions.assertEquals(numOfPolls, finalMap.get(idp3).keySet().size(), message); } @@ -553,7 +551,7 @@ final void testSetNonCalculatedEmissionsForPopulation_nullEmissions(){ //test setNonCalculatedEmissionsForPopulation with 'null' // throw nullpointer exception setUpForNonCaculatedEmissions(); - + Id idp5 = Id.create("p5", Person.class); Person p5 = populationFactory.createPerson(idp5); pop.addPerson(p5); @@ -576,7 +574,7 @@ final void testSetNonCalculatedEmissionsForPopulation_emptyPopulation(){ // empty list should be returned setUpForNonCaculatedEmissions(); - //person 7 in totalEmissions but not in population + //person 7 in totalEmissions but not in population SortedMap p7Emissions = new TreeMap<>(); //complete list of all pollutants - missing data is not tested here p7Emissions.put( CO, .0 ); @@ -625,9 +623,9 @@ final void testSetNonCalculatedEmissionsForPopulation_emptyEmissionMap() { //check: all values for all persons are zero and of type double for (Id id : finalMap.keySet()) { - for (Object pollutant : finalMap.get(id).values()) { + for (Double pollutant : finalMap.get(id).values()) { Assertions.assertSame(pollutant.getClass(), Double.class); - Assertions.assertEquals(0.0, (Double) pollutant, MatsimTestUtils.EPSILON, "map of pollutants was missing. Therefore all values should be set to zero."); + Assertions.assertEquals(0.0, pollutant, MatsimTestUtils.EPSILON, "map of pollutants was missing. Therefore all values should be set to zero."); Assertions.assertNotNull(pollutant); } //check: alle types of emissions appear @@ -793,10 +791,6 @@ public static Map createEmissions() { return Arrays.stream( Pollutant.values() ).collect( Collectors.toMap( p -> p, p -> Math.random() ) ) ; } -// public static Map createEmissionsWithFixedValue(double value) { -// return Arrays.asList("co2", CO, NOx, "NO", NO2, HC).stream() -// .collect(Collectors.toMap(p -> p, p -> value)); -// } public static Map createEmissionsWithFixedValue( double value ) { return Arrays.stream( Pollutant.values() ).collect( Collectors.toMap( p -> p, p -> value ) ) ; } @@ -815,6 +809,6 @@ private void addLinksToNetwork(Scenario sc) { NetworkUtils.createAndAddLink(network, Id.create("link24", Link.class), node2, node4, 1000., 20., 3600, 2); NetworkUtils.createAndAddLink(network, Id.create("link34", Link.class), node3, node4, 1000., 20., 3600, 2); //w/o orig id and type } - + } - + diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2.java index fb921395d19..a63697cfab4 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2.java @@ -306,7 +306,7 @@ public void startTag(String name, Attributes atts, Stack context) { // do nothing break ; default: - logger.warn("Unexpected value while reading in. This field will be ignored: " + name); + logger.warn("Unexpected value while reading in. This field will be ignored: {}", name); } } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2_1.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2_1.java index 862123d3201..8503eb4acad 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2_1.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlParserV2_1.java @@ -309,7 +309,7 @@ public void startTag(String name, Attributes atts, Stack context) { // do nothing break ; default: - logger.warn("Unexpected value while reading in. This field will be ignored: " + name); + logger.warn("Unexpected value while reading in. This field will be ignored: {}", name); } } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlReader.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlReader.java index 5019604572d..5155f5bdebc 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlReader.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlReader.java @@ -56,9 +56,9 @@ public void readFile( String filename ){ try { reader.readFile( filename ); } catch (Exception e) { - log.warn("### Exception found while trying to read CarrierPlan: Message: " + e.getMessage() + " ; cause: " + e.getCause() + " ; class " + e.getClass()); + log.warn("### Exception found while trying to read CarrierPlan: Message: {} ; cause: {} ; class {}", e.getMessage(), e.getCause(), e.getClass()); if (e.getCause().getMessage().contains("cvc-elt.1")) { // "Cannot find the declaration of element" -> exception comes most probably because no validation information was found - log.warn("read with validation = true failed. Try it again without validation... filename: " + filename); + log.warn("read with validation = true failed. Try it again without validation... filename: {}", filename); reader.setValidating(false); reader.readFile(filename); } else { //other problem: e.g. validation does not work, because of missing validation file. @@ -72,9 +72,9 @@ public void readURL( URL url ){ try { reader.readURL(url); } catch (Exception e) { - log.warn("### Exception found while trying to read CarrierPlan: Message: " + e.getMessage() + " ; cause: " + e.getCause() + " ; class " + e.getClass()); + log.warn("### Exception found while trying to read CarrierPlan: Message: {} ; cause: {} ; class {}", e.getMessage(), e.getCause(), e.getClass()); if (e.getCause().getMessage().contains("cvc-elt.1")) { // "Cannot find the declaration of element" -> exception comes most probably because no validation information was found - log.warn("read with validation = true failed. Try it again without validation... url: " + url.toString()); + log.warn("read with validation = true failed. Try it again without validation... url: {}", url.toString()); reader.setValidating(false); reader.readURL(url); } else { //other problem: e.g. validation does not work, because of missing validation file. @@ -89,7 +89,7 @@ public void readStream( InputStream inputStream ){ reader.setValidating(false); reader.parse(inputStream); } catch (Exception e) { - log.warn("### Exception found while trying to read CarrierPlan: Message: " + e.getMessage() + " ; cause: " + e.getCause() + " ; class " + e.getClass()); + log.warn("### Exception found while trying to read CarrierPlan: Message: {} ; cause: {} ; class {}", e.getMessage(), e.getCause(), e.getClass()); throw e; } } @@ -110,7 +110,7 @@ private static final class CarriersPlanReader extends MatsimXmlParser { public void startTag(final String name, final Attributes attributes, final Stack context) { if ( CARRIERS.equalsIgnoreCase( name ) ) { String str = attributes.getValue( "xsi:schemaLocation" ); - log.info("Found following schemeLocation in carriers definition file: " + str); + log.info("Found following schemeLocation in carriers definition file: {}", str); if (str == null){ log.warn("Carrier plans file does not contain a valid xsd header. Using CarrierPlanReaderV2."); delegate = new CarrierPlanXmlParserV2( carriers, carrierVehicleTypes ) ; diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1.java index 8b89b8f8216..92699982378 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1.java @@ -104,7 +104,7 @@ public void write(String filename) { } } - private void writeRootElement() throws UncheckedIOException, IOException { + private void writeRootElement() throws UncheckedIOException { List> atts = new ArrayList<>(); atts.add(createTuple(XMLNS, MatsimXmlWriter.MATSIM_NAMESPACE)); atts.add(createTuple(XMLNS + ":xsi", DEFAULTSCHEMANAMESPACELOCATION)); @@ -112,15 +112,14 @@ private void writeRootElement() throws UncheckedIOException, IOException { this.writeStartTag(CARRIERS, atts); } - private void startCarrier(Carrier carrier, BufferedWriter writer) - throws IOException { + private void startCarrier(Carrier carrier, BufferedWriter writer) { this.writeStartTag(CARRIER, List.of( createTuple(ID, carrier.getId().toString())), false, true ); attributesWriter.writeAttributes("\t\t", writer, carrier.getAttributes(), false); } - private void writeVehiclesAndTheirTypes(Carrier carrier)throws IOException { + private void writeVehiclesAndTheirTypes(Carrier carrier) { this.writeStartTag(CAPABILITIES, List.of( createTuple(FLEET_SIZE, carrier.getCarrierCapabilities().getFleetSize().toString()) )); @@ -142,7 +141,7 @@ private void writeVehiclesAndTheirTypes(Carrier carrier)throws IOException { this.writeEndTag(CAPABILITIES); } - private void writeShipments(Carrier carrier, BufferedWriter writer) throws IOException { + private void writeShipments(Carrier carrier, BufferedWriter writer) { if(carrier.getShipments().isEmpty()) return; this.writeStartTag(SHIPMENTS, null); for (CarrierShipment s : carrier.getShipments().values()) { @@ -173,7 +172,7 @@ private void writeShipment(CarrierShipment s, Id shipmentId, bo ); } - private void writeServices(Carrier carrier, BufferedWriter writer) throws IOException { + private void writeServices(Carrier carrier, BufferedWriter writer) { if(carrier.getServices().isEmpty()) return; this.writeStartTag(SERVICES, null); for (CarrierService s : carrier.getServices().values()) { @@ -283,8 +282,7 @@ else if (tourElement instanceof Tour.ShipmentBasedActivity act) { createTuple(SHIPMENT_ID, act.getShipment().getId().toString())), true ); if (!carrier.getShipments().containsKey(act.getShipment().getId())) { - logger.error("Shipment with id " + act.getShipment().getId().toString() + " is contained in the carriers plan, " + - "but not available in the list of shipments. Carrier with carrierId: " + carrier.getId()); + logger.error("Shipment with id {} is contained in the carriers plan, but not available in the list of shipments. Carrier with carrierId: {}", act.getShipment().getId().toString(), carrier.getId()); } } else if (tourElement instanceof Tour.ServiceActivity act) { @@ -293,8 +291,7 @@ else if (tourElement instanceof Tour.ServiceActivity act) { createTuple(SERVICE_ID, act.getService().getId().toString())), true ); if (!carrier.getServices().containsKey(act.getService().getId())) { - logger.error("service with id " + act.getService().getId().toString() + " is contained in the carriers plan, " + - "but not available in the list of services. Carrier with carrierId: " + carrier.getId()); + logger.error("service with id {} is contained in the carriers plan, but not available in the list of services. Carrier with carrierId: {}", act.getService().getId().toString(), carrier.getId()); } } } @@ -308,11 +305,11 @@ else if (tourElement instanceof Tour.ServiceActivity act) { this.writeEndTag(PLANS); } - private void endCarrier() throws IOException { + private void endCarrier() { this.writeEndTag(CARRIER); } - private void writeEndElement() throws IOException { + private void writeEndElement() { this.writeEndTag(CARRIERS); } } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierShipment.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierShipment.java index 1298f3eb5b2..9472ffaac91 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierShipment.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierShipment.java @@ -81,9 +81,9 @@ public static Builder newInstance(Id id, Id from, Id id; - Id from; - Id to; - int size; + final Id from; + final Id to; + final int size; TimeWindow pickTW = TimeWindow.newInstance(0.0, Integer.MAX_VALUE); TimeWindow delTW = TimeWindow.newInstance(0.0, Integer.MAX_VALUE); double pickServiceTime = 0.0; diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleType.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleType.java index 8f5a5ea31e7..16b7e92a03d 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleType.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleType.java @@ -50,7 +50,7 @@ private CarrierVehicleType(){} // do not instantiate * */ public static class Builder { - VehicleType delegate ; + final VehicleType delegate ; /** * Returns a new instance of builder initialized with the typeId. diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeReader.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeReader.java index ce87229d7ee..f10e5fc9bd5 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeReader.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarrierVehicleTypeReader.java @@ -60,9 +60,9 @@ public void readFile( String filename ){ reader.setValidating(true) ; reader.readFile( filename ); } catch (Exception e) { - log.warn("### Exception: Message=" + e.getMessage() + " ; cause=" + e.getCause() + " ; class=" + e.getClass()); + log.warn("### Exception: Message={} ; cause={} ; class={}", e.getMessage(), e.getCause(), e.getClass()); if (e.getCause().getMessage().contains("cvc-elt.1")) { // "Cannot find the declaration of element" -> exception comes most probably because no validation information was found - log.warn("read with validation = true failed. Try it again without validation. filename: " + filename); + log.warn("read with validation = true failed. Try it again without validation. filename: {}", filename); reader.setValidating(false); reader.readFile(filename); } else { //other problem: e.g. validation does not work, because of missing validation file. @@ -78,11 +78,11 @@ public void readURL( URL url ){ reader.setValidating(true) ; reader.readURL(url); } catch (Exception e) { - log.warn("### Exception: Message=" + e.getMessage() ); - log.warn("### Exception: Cause=" + e.getCause() ); - log.warn("### Exception: Class=" + e.getClass() ); + log.warn("### Exception: Message={}", e.getMessage()); + log.warn("### Exception: Cause={}", e.getCause()); + log.warn("### Exception: Class={}", e.getClass()); if (e.getCause().getMessage().contains("cvc-elt.1.a")) { // "Cannot find the declaration of element" -> exception comes most probably because no validation information was found - log.warn("read with validation = true failed. Try it again without validation... url: " + url.toString()); + log.warn("read with validation = true failed. Try it again without validation... url: {}", url.toString()); reader.setValidating(false); reader.readURL(url); } else { //other problem: e.g. validation does not work, because of missing validation file. @@ -97,7 +97,8 @@ public void readStream( InputStream inputStream ){ reader.setValidating(true) ; reader.parse( inputStream ) ; } catch (Exception e) - {log.warn("### Exception found while trying to read Carrier Vehicle Type: Message: " + e.getMessage() + " ; cause: " + e.getCause() + " ; class " + e.getClass()); + { + log.warn("### Exception found while trying to read Carrier Vehicle Type: Message: {} ; cause: {} ; class {}", e.getMessage(), e.getCause(), e.getClass()); if (e.getCause().getMessage().contains("cvc-elt.1.a")) { // "Cannot find the declaration of element" -> exception comes most probably because no validation information was found log.warn("read with validation = true failed. Try it again without validation... "); reader.setValidating(false); @@ -121,10 +122,10 @@ private static final class CarrierVehicleTypeParser extends MatsimXmlParser { @Override public void startTag(final String name, final Attributes attributes, final Stack context) { - log.debug("Reading start tag. name: " + name + " , attributes: " + attributes.toString() + " , context: " + context); + log.debug("Reading start tag. name: {} , attributes: {} , context: {}", name, attributes.toString(), context); if ( "vehicleTypes".equalsIgnoreCase( name ) ) { String str = attributes.getValue( "xsi:schemaLocation" ); - log.info("Found following schemeLocation in carriers definition file: " + str); + log.info("Found following schemeLocation in carriers definition file: {}", str); if (str == null){ log.warn( "No validation information found. Using ReaderV1." ); delegate = new CarrierVehicleTypeReaderV1( vehicleTypes ); diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/Carriers.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/Carriers.java index 8746def11e9..f13f0bc56ae 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/Carriers.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/Carriers.java @@ -63,7 +63,7 @@ public void addCarrier(Carrier carrier) { if(!carriers.containsKey(carrier.getId())){ carriers.put(carrier.getId(), carrier); } - else log.warn("carrier " + carrier.getId() + " already exists"); + else log.warn("carrier {} already exists", carrier.getId()); } } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java index 9b594c05f6b..de88f529862 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/CarriersUtils.java @@ -47,7 +47,6 @@ import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.Collectors; public class CarriersUtils { @@ -237,10 +236,10 @@ public static Carriers createShipmentVRPCarrierFromServiceVRPSolution(Carriers c Carriers carriersWithShipments = new Carriers(); for (Carrier carrier : carriers.getCarriers().values()) { Carrier carrierWS = createCarrier(carrier.getId()); - if (carrier.getShipments().size() > 0) { + if (!carrier.getShipments().isEmpty()) { copyShipments(carrierWS, carrier); } - if (carrier.getServices().size() > 0) { + if (!carrier.getServices().isEmpty()) { createShipmentsFromServices(carrierWS, carrier); } carrierWS.setCarrierCapabilities(carrier.getCarrierCapabilities()); // vehicles and other carrierCapabilities @@ -314,7 +313,7 @@ public static void loadCarriersAccordingToFreightConfig(Scenario scenario) { */ private static void copyShipments(Carrier carrierWS, Carrier carrier) { for (CarrierShipment carrierShipment : carrier.getShipments().values()) { - log.debug("Copy CarrierShipment: " + carrierShipment.toString()); + log.debug("Copy CarrierShipment: {}", carrierShipment.toString()); addShipment(carrierWS, carrierShipment); } } @@ -349,7 +348,7 @@ private static void createShipmentsFromServices(Carrier carrierWS, Carrier carri } } for (CarrierService carrierService : carrier.getServices().values()) { - log.debug("Converting CarrierService to CarrierShipment: " + carrierService.getId()); + log.debug("Converting CarrierService to CarrierShipment: {}", carrierService.getId()); CarrierShipment carrierShipment = CarrierShipment.Builder .newInstance(Id.create(carrierService.getId().toString(), CarrierShipment.class), depotServiceIsDeliveredFrom.get(carrierService.getId()), carrierService.getLocationLinkId(), @@ -513,7 +512,7 @@ private static void addSkill(Attributes attributes, String skill) { List skills = convertSkillsAttributeToList(attributes); if (!skills.contains(skill)) { String skillString; - if (skills.size() == 0) { + if (skills.isEmpty()) { skillString = skill; } else { skillString = attributes.getAttribute(ATTR_SKILLS) + "," + skill; @@ -556,7 +555,7 @@ private static List convertSkillsAttributeToList(Attributes attributes) } private static void setSkills(Attributes attributes, Set skills) { - if (skills.size() != 0) { + if (!skills.isEmpty()) { Iterator skillIterator = skills.iterator(); StringBuilder skillString = new StringBuilder(skillIterator.next()); while (skillIterator.hasNext()) { diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/TimeWindow.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/TimeWindow.java index 167dc424028..8c5e9fc0d25 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/TimeWindow.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/TimeWindow.java @@ -96,11 +96,9 @@ public boolean equals(Object o){ @Override public int hashCode(){ int result = 59; - long startLong = Double.doubleToLongBits(start); - int startHash = (int) (startLong^(startLong>>>32)); + int startHash = Double.hashCode(start); result = 31 * result + startHash; - long endLong = Double.doubleToLongBits(end); - int endHash = (int) (endLong^(endLong>>>32)); + int endHash = Double.hashCode(end); result = 31 * result + endHash; return result; } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/Tour.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/Tour.java index 9b0e9d91696..cb522e857fb 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/Tour.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/Tour.java @@ -163,7 +163,7 @@ public Leg createLeg(Route route, double dep_time, double transportTime) { @Deprecated public Builder insertLegAtBeginning(Leg leg) { Gbl.assertNotNull(leg); - tourElements.add(0,leg); + tourElements.addFirst(leg); return this; } @@ -183,7 +183,7 @@ public Builder schedulePickupAtBeginning(CarrierShipment shipment) { } // assertLastElementIsLeg(); Pickup pickup = createPickup(shipment); - tourElements.add(0, pickup); + tourElements.addFirst(pickup); // previousElementIsActivity = true; return this; } @@ -197,7 +197,7 @@ public Builder schedulePickupAtBeginning(CarrierShipment shipment) { */ public void schedulePickup(CarrierShipment shipment) { Gbl.assertNotNull(shipment); - logger.debug("Pickup to get scheduled: " + shipment); + logger.debug("Pickup to get scheduled: {}", shipment); boolean wasNew = openPickups.add(shipment); if (!wasNew) { throw new IllegalStateException("Trying to deliver something which was already picked up."); @@ -223,8 +223,8 @@ private void assertLastElementIsLeg() { */ public void scheduleDelivery(CarrierShipment shipment) { Gbl.assertNotNull(shipment); - logger.debug("Delivery to get scheduled: " + shipment); - logger.debug("OpenPickups: " + openPickups); + logger.debug("Delivery to get scheduled: {}", shipment); + logger.debug("OpenPickups: {}", openPickups); boolean wasOpen = openPickups.remove(shipment); if (!wasOpen) { throw new IllegalStateException("Trying to deliver something which was not picked up."); diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgent.java index d3e08e9afbb..da31ae5637d 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierAgent.java @@ -179,7 +179,7 @@ void scoreSelectedPlan() { } scoringFunction.finish(); final double score = scoringFunction.getScore(); - log.warn("score=" + score); + log.debug("score of carrier {} = {}", carrier.getId(), score); carrier.getSelectedPlan().setScore( score ); } void handleEvent(Event event, Id driverId) { diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java index 5a0889c8dc2..00233bbbf18 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/CarrierDriverAgent.java @@ -83,7 +83,7 @@ final class CarrierDriverAgent{ this.carrier = carrier; this.events = events; this.carrierEventCreators = carrierEventCreators; - log.debug( "creating CarrierDriverAgent with driverId=" + driverId ); + log.debug("creating CarrierDriverAgent with driverId={}", driverId); this.driverId = driverId; this.scheduledTour = tour; } @@ -91,18 +91,13 @@ final class CarrierDriverAgent{ void handleAnEvent(Event event){ // the event comes to here from CarrierAgent#handleEvent only for events concerning this driver - if( event instanceof PersonArrivalEvent ){ - handleEvent( (PersonArrivalEvent) event); - } else if( event instanceof PersonDepartureEvent ){ - handleEvent( (PersonDepartureEvent) event ); - } else if( event instanceof LinkEnterEvent ){ - handleEvent( (LinkEnterEvent) event ); - } else if( event instanceof ActivityEndEvent ){ - handleEvent( (ActivityEndEvent) event ); - } else if( event instanceof ActivityStartEvent ){ - handleEvent( (ActivityStartEvent) event ); - } else{ - createAdditionalEvents( event, null, scheduledTour, driverId, planElementCounter); + switch (event) { + case PersonArrivalEvent personArrivalEvent -> handleEvent(personArrivalEvent); + case PersonDepartureEvent personDepartureEvent -> handleEvent(personDepartureEvent); + case LinkEnterEvent linkEnterEvent -> handleEvent(linkEnterEvent); + case ActivityEndEvent activityEndEvent -> handleEvent(activityEndEvent); + case ActivityStartEvent activityStartEvent -> handleEvent(activityStartEvent); + case null, default -> createAdditionalEvents(event, null, scheduledTour, driverId, planElementCounter); } } @@ -119,8 +114,8 @@ private void handleEvent( PersonArrivalEvent event ){ currentRoute = null; } else{ Id startLink; - if( currentRoute.size() != 0 ){ - startLink = currentRoute.get( 0 ); + if(!currentRoute.isEmpty()){ + startLink = currentRoute.getFirst(); } else{ startLink = event.getLinkId(); } @@ -163,7 +158,7 @@ private void handleEvent( ActivityEndEvent event ){ createAdditionalEvents( event, currentActivity, scheduledTour, driverId, planElementCounter ); - log.debug( "handling activity end event=" + event ); + log.debug("handling activity end event={}", event); if( CarrierConstants.START.equals( event.getActType() ) ){ planElementCounter += 1; return; diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightAgentSource.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightAgentSource.java index 0feadd08226..f5613f1a961 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightAgentSource.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/controler/FreightAgentSource.java @@ -75,15 +75,15 @@ public final class FreightAgentSource implements AgentSource { Vehicle vehicle; if( CarriersUtils.getVehicle( freightDriverPlan ) == null ){ vehicle = VehicleUtils.getFactory().createVehicle( Id.create( agent.getId(), Vehicle.class ), VehicleUtils.createDefaultVehicleType() ); - log.warn( "vehicle for agent " + freightDriverPlan.getPerson().getId() + " is missing. set default vehicle where maxVelocity is solely defined by link.speed." ); + log.warn("vehicle for agent {} is missing. set default vehicle where maxVelocity is solely defined by link.speed.", freightDriverPlan.getPerson().getId()); } else if( CarriersUtils.getVehicle( freightDriverPlan ).getType() == null ){ vehicle = VehicleUtils.getFactory().createVehicle( Id.create( agent.getId(), Vehicle.class ), VehicleUtils.createDefaultVehicleType() ); - log.warn( "vehicleType for agent " + freightDriverPlan.getPerson().getId() + " is missing. set default vehicleType where maxVelocity is solely defined by link.speed." ); + log.warn("vehicleType for agent {} is missing. set default vehicleType where maxVelocity is solely defined by link.speed.", freightDriverPlan.getPerson().getId()); } else { vehicle = CarriersUtils.getVehicle( freightDriverPlan ); } - log.warn( "inserting vehicleId=" + vehicle.getId() + " into mobsim." ); + log.debug("inserting vehicleId={} into mobsim.", vehicle.getId()); qsim.addParkedVehicle( new QVehicleImpl( vehicle ), agent.getCurrentLinkId() ); // yyyyyy should rather use QVehicleFactory. kai, nov'18 diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourStartEventCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourStartEventCreator.java index eb015551dd0..aacf3e6ef12 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourStartEventCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/events/CarrierTourStartEventCreator.java @@ -36,8 +36,8 @@ /*package-private*/ final class CarrierTourStartEventCreator implements CarrierEventCreator { - TreeMap, ActivityEndEvent> endEventMap = new TreeMap<>(); - TreeMap, PersonEntersVehicleEvent> personEntersVehicleEventMap = new TreeMap<>(); + final TreeMap, ActivityEndEvent> endEventMap = new TreeMap<>(); + final TreeMap, PersonEntersVehicleEvent> personEntersVehicleEventMap = new TreeMap<>(); @Override diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceConstraint.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceConstraint.java index 0d6c4725b97..068c70506cd 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceConstraint.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/DistanceConstraint.java @@ -142,14 +142,14 @@ private double calculateRouteDistanceWithAssociatedPickup(JobInsertionContext co if (positionOfRelatedPickup == 0 && context.getRoute().getActivities().isEmpty()) { context.getRoute().getStart().setLocation(context.getNewVehicle().getStartLocation()); context.getRoute().getEnd().setLocation(context.getNewVehicle().getEndLocation()); - routeDistance = getDistance(context.getAssociatedActivities().get(0), context.getRoute().getEnd(), + routeDistance = getDistance(context.getAssociatedActivities().getFirst(), context.getRoute().getEnd(), context.getNewVehicle(), context.getNewDepTime()); return routeDistance; } else if (positionOfRelatedPickup == 0 && !context.getRoute().getActivities().isEmpty()) { - routeDistance = getDistance(context.getAssociatedActivities().get(0), - context.getRoute().getActivities().get(0), context.getNewVehicle(), context.getNewDepTime()); + routeDistance = getDistance(context.getAssociatedActivities().getFirst(), + context.getRoute().getActivities().getFirst(), context.getNewVehicle(), context.getNewDepTime()); } else { - routeDistance = getDistance(context.getRoute().getStart(), context.getRoute().getActivities().get(0), + routeDistance = getDistance(context.getRoute().getStart(), context.getRoute().getActivities().getFirst(), context.getNewVehicle(), context.getNewDepTime()); } // adds distances between every tour activity and adds the associated pickup on @@ -157,8 +157,8 @@ private double calculateRouteDistanceWithAssociatedPickup(JobInsertionContext co while (context.getRoute().getTourActivities().getActivities().size() > (nextRouteActivity + 1)) { if (positionOfRelatedPickup == (nextRouteActivity + 1) && positionOfRelatedPickup != 0) { routeDistance = routeDistance + getDistance(context.getRoute().getActivities().get(nextRouteActivity), - context.getAssociatedActivities().get(0), context.getNewVehicle()); - routeDistance = routeDistance + getDistance(context.getAssociatedActivities().get(0), + context.getAssociatedActivities().getFirst(), context.getNewVehicle()); + routeDistance = routeDistance + getDistance(context.getAssociatedActivities().getFirst(), context.getRoute().getActivities().get(nextRouteActivity), context.getNewVehicle()); } else { routeDistance = routeDistance + getDistance(context.getRoute().getActivities().get(nextRouteActivity), @@ -168,8 +168,8 @@ private double calculateRouteDistanceWithAssociatedPickup(JobInsertionContext co } if (positionOfRelatedPickup == context.getRoute().getActivities().size()) { routeDistance = routeDistance + getDistance(context.getRoute().getActivities().get(nextRouteActivity), - context.getAssociatedActivities().get(0), context.getNewVehicle()); - routeDistance = routeDistance + getDistance(context.getAssociatedActivities().get(0), + context.getAssociatedActivities().getFirst(), context.getNewVehicle()); + routeDistance = routeDistance + getDistance(context.getAssociatedActivities().getFirst(), context.getRoute().getEnd(), context.getNewVehicle()); } else routeDistance = routeDistance + getDistance(context.getRoute().getActivities().get(nextRouteActivity), @@ -189,7 +189,7 @@ private double calculateRouteDistance(JobInsertionContext context, Vehicle newVe return realRouteDistance; int n = 0; realRouteDistance = getDistance(context.getRoute().getStart(), - context.getRoute().getTourActivities().getActivities().get(0), newVehicle); + context.getRoute().getTourActivities().getActivities().getFirst(), newVehicle); while (context.getRoute().getTourActivities().getActivities().size() > (n + 1)) { realRouteDistance = realRouteDistance + getDistance(context.getRoute().getTourActivities().getActivities().get(n), @@ -258,9 +258,9 @@ private double findMinimalAdditionalDistance(JobInsertionContext context, TourAc } // checks the distance if the delivery is the last activity before the end of // the tour - if (route.getTourActivities().getActivities().size() > 0) { + if (!route.getTourActivities().getActivities().isEmpty()) { TourActivity activityLastDelivery = route.getTourActivities().getActivities() - .get(route.getTourActivities().getActivities().size() - 1); + .getLast(); TourActivity activityEnd = route.getEnd(); double possibleAdditionalDistance = getDistance(activityLastDelivery, assignedDelivery, newVehicle) + getDistance(assignedDelivery, activityEnd, newVehicle) diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java index 0b16a1dbbed..8710e50c7ba 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/MatsimJspritFactory.java @@ -32,6 +32,7 @@ import com.graphhopper.jsprit.core.problem.cost.VehicleRoutingActivityCosts; import com.graphhopper.jsprit.core.problem.cost.VehicleRoutingTransportCosts; import com.graphhopper.jsprit.core.problem.job.Service; +import com.graphhopper.jsprit.core.problem.job.Service.Builder; import com.graphhopper.jsprit.core.problem.job.Shipment; import com.graphhopper.jsprit.core.problem.solution.VehicleRoutingProblemSolution; import com.graphhopper.jsprit.core.problem.solution.route.VehicleRoute; @@ -164,7 +165,7 @@ static Service createJspritService(CarrierService carrierService, Coord location } Location location = locationBuilder.build(); - Service.Builder serviceBuilder = Service.Builder.newInstance(carrierService.getId().toString()); + Builder serviceBuilder = Builder.newInstance(carrierService.getId().toString()); serviceBuilder.addSizeDimension(0, carrierService.getCapacityDemand()); serviceBuilder.setLocation(location).setServiceTime(carrierService.getServiceDuration()) .setTimeWindow(com.graphhopper.jsprit.core.problem.solution.route.activity.TimeWindow.newInstance( @@ -318,7 +319,7 @@ static com.graphhopper.jsprit.core.problem.vehicle.VehicleType createJspritVehic final double vehicleCapacity = matsimVehicleType.getCapacity().getOther(); final int vehicleCapacityInt = (int) vehicleCapacity; if (vehicleCapacity - vehicleCapacityInt > 0) { - log.warn("vehicle capacity truncated to int: before=" + vehicleCapacity + "; after=" + vehicleCapacityInt); + log.warn("vehicle capacity truncated to int: before={}; after={}", vehicleCapacity, vehicleCapacityInt); // yyyyyy this implies that we would have fewer problems if we set vehicle // capacity in kg instead of in tons in our data model. kai, aug'19 } @@ -329,13 +330,13 @@ static com.graphhopper.jsprit.core.problem.vehicle.VehicleType createJspritVehic if (VehicleUtils.getCostsPerSecondInService(matsimVehicleType.getCostInformation()) != null) { jspritVehTypeBuilder.setCostPerServiceTime(VehicleUtils.getCostsPerSecondInService(matsimVehicleType.getCostInformation())); } else { - log.info("'costsPerSecondInService' is not set in VehicleType attributes. Will use the value of 'costsPerSecond' instead. VehicleTypeId: " + matsimVehicleType.getId()); + log.info("'costsPerSecondInService' is not set in VehicleType attributes. Will use the value of 'costsPerSecond' instead. VehicleTypeId: {}", matsimVehicleType.getId()); jspritVehTypeBuilder.setCostPerServiceTime(matsimVehicleType.getCostInformation().getCostsPerSecond()); } if (VehicleUtils.getCostsPerSecondWaiting(matsimVehicleType.getCostInformation()) != null) { jspritVehTypeBuilder.setCostPerWaitingTime(VehicleUtils.getCostsPerSecondWaiting(matsimVehicleType.getCostInformation())); } else { - log.info("'costsPerSecondWaiting' is not set in VehicleType attributes. Will use the value of 'costsPerSecond' instead. VehicleTypeId: " + matsimVehicleType.getId()); + log.info("'costsPerSecondWaiting' is not set in VehicleType attributes. Will use the value of 'costsPerSecond' instead. VehicleTypeId: {}", matsimVehicleType.getId()); jspritVehTypeBuilder.setCostPerWaitingTime(matsimVehicleType.getCostInformation().getCostsPerSecond()); } jspritVehTypeBuilder.setFixedCost(matsimVehicleType.getCostInformation().getFixedCosts()); @@ -369,22 +370,19 @@ static ScheduledTour createScheduledTour(VehicleRoute jspritRoute, Id tour matsimFreightTourBuilder.scheduleStart(Id.create(jspritRoute.getStart().getLocation().getId(), Link.class)); for (TourActivity act : tour.getActivities()) { if (act instanceof ServiceActivity || act instanceof PickupService) { - log.debug("Found ServiceActivity or PickupService : " + act.getName() + " at location " - + act.getLocation().getId() + " : " + act.getLocation().getCoordinate()); + log.debug("Found ServiceActivity or PickupService : {} at location {} : {}", act.getName(), act.getLocation().getId(), act.getLocation().getCoordinate()); Service job = (Service) ((JobActivity) act).getJob(); CarrierService carrierService = createCarrierService(job); matsimFreightTourBuilder.addLeg(new Tour.Leg()); matsimFreightTourBuilder.scheduleService(carrierService); } else if (act instanceof DeliverShipment) { - log.debug("Found DeliveryShipment: " + act.getName() + " at location " + act.getLocation().getId() - + " : " + act.getLocation().getCoordinate()); + log.debug("Found DeliveryShipment: {} at location {} : {}", act.getName(), act.getLocation().getId(), act.getLocation().getCoordinate()); Shipment job = (Shipment) ((JobActivity) act).getJob(); CarrierShipment carrierShipment = createCarrierShipment(job); matsimFreightTourBuilder.addLeg(new Tour.Leg()); matsimFreightTourBuilder.scheduleDelivery(carrierShipment); } else if (act instanceof PickupShipment) { - log.debug("Found PickupShipment: " + act.getName() + " at location " + act.getLocation().getId() + " : " - + act.getLocation().getCoordinate()); + log.debug("Found PickupShipment: {} at location {} : {}", act.getName(), act.getLocation().getId(), act.getLocation().getCoordinate()); Shipment job = (Shipment) ((JobActivity) act).getJob(); CarrierShipment carrierShipment = createCarrierShipment(job); matsimFreightTourBuilder.addLeg(new Tour.Leg()); @@ -445,13 +443,12 @@ public static VehicleRoute createRoute(ScheduledTour scheduledTour, VehicleRouti } } VehicleRoute jspritRoute = jspritRouteBuilder.build(); - log.debug("jsprit route: " + jspritRoute); - log.debug("start-location: " + jspritRoute.getStart().getLocation() + " endTime: " + jspritRoute.getDepartureTime() + "(" - + jspritRoute.getStart().getEndTime() + ")"); + log.debug("jsprit route: {}", jspritRoute); + log.debug("start-location: {} endTime: {}({})", jspritRoute.getStart().getLocation(), jspritRoute.getDepartureTime(), jspritRoute.getStart().getEndTime()); for (TourActivity act : jspritRoute.getActivities()) { - log.debug("act: " + act); + log.debug("act: {}", act); } - log.debug("end: " + jspritRoute.getEnd()); + log.debug("end: {}", jspritRoute.getEnd()); if (jspritRoute.getDepartureTime() != scheduledTour.getDeparture()) throw new AssertionError("departureTimes of both routes must be equal"); return jspritRoute; @@ -502,7 +499,7 @@ public static VehicleRoutingProblem createRoutingProblem(Carrier carrier, Networ + carrierVehicle.getId() + "][locationId=" + carrierVehicle.getLinkId() + "]"); coordinate = link.getCoord(); } else - log.warn("cannot find linkId " + carrierVehicle.getId()); + log.warn("cannot find linkId {}", carrierVehicle.getId()); Vehicle veh = createJspritVehicle(carrierVehicle, coordinate); if (veh.getEarliestDeparture() != carrierVehicle.getEarliestStartTime()) @@ -523,7 +520,7 @@ public static VehicleRoutingProblem createRoutingProblem(Carrier carrier, Networ if (link != null) { coordinate = link.getCoord(); } else - log.warn("cannot find linkId " + service.getLocationLinkId()); + log.warn("cannot find linkId {}", service.getLocationLinkId()); } vrpBuilder.addJob(createJspritService(service, coordinate)); } @@ -606,13 +603,13 @@ public static VehicleRoutingProblem.Builder createRoutingProblemBuilder(Carrier + carrierVehicle.getId() + "][locationId=" + carrierVehicle.getLinkId() + "]"); coordinate = link.getCoord(); } else - log.warn("cannot find linkId " + carrierVehicle.getId()); + log.warn("cannot find linkId {}", carrierVehicle.getId()); vrpBuilder.addVehicle(createJspritVehicle(carrierVehicle, coordinate)); } if (serviceInVrp) { for (CarrierService service : carrier.getServices().values()) { - log.debug("Handle CarrierService: " + service.toString()); + log.debug("Handle CarrierService: {}", service.toString()); Coord coordinate = null; if (network != null) { Link link = network.getLinks().get(service.getLocationLinkId()); @@ -628,7 +625,7 @@ public static VehicleRoutingProblem.Builder createRoutingProblemBuilder(Carrier if (shipmentInVrp) { for (CarrierShipment carrierShipment : carrier.getShipments().values()) { - log.debug("Handle CarrierShipment: " + carrierShipment.toString()); + log.debug("Handle CarrierShipment: {}", carrierShipment.toString()); Coord fromCoordinate = null; Coord toCoordinate = null; if (network != null) { @@ -637,7 +634,7 @@ public static VehicleRoutingProblem.Builder createRoutingProblemBuilder(Carrier if (fromLink != null && toLink != null) { // Shipment to be delivered from specified location to // specified location - log.debug("Shipment identified as Shipment: " + carrierShipment.getId().toString()); + log.debug("Shipment identified as Shipment: {}", carrierShipment.getId().toString()); fromCoordinate = fromLink.getCoord(); toCoordinate = toLink.getCoord(); } else @@ -734,8 +731,8 @@ public static VehicleRoutingAlgorithm loadOrCreateVehicleRoutingAlgorithm(Scenar VehicleRoutingAlgorithm algorithm; final String vehicleRoutingAlgorithmFile = freightConfig.getVehicleRoutingAlgorithmFile(); - if (vehicleRoutingAlgorithmFile != null && !vehicleRoutingAlgorithmFile.equals("")) { - log.info("Will read in VehicleRoutingAlgorithm from " + vehicleRoutingAlgorithmFile); + if (vehicleRoutingAlgorithmFile != null && !vehicleRoutingAlgorithmFile.isEmpty()) { + log.info("Will read in VehicleRoutingAlgorithm from {}", vehicleRoutingAlgorithmFile); URL vraURL; try { vraURL = IOUtils.extendUrl(scenario.getConfig().getContext(), vehicleRoutingAlgorithmFile); diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCosts.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCosts.java index 6ae0c93d705..f332b84cb0b 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCosts.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCosts.java @@ -191,9 +191,7 @@ public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((from == null) ? 0 : from.hashCode()); - long temp; - temp = Double.doubleToLongBits(time); - result = prime * result + (int) (temp ^ (temp >>> 32)); + result = prime * result + Double.hashCode(time); result = prime * result + ((to == null) ? 0 : to.hashCode()); result = prime * result + ((vehicleType == null) ? 0 : vehicleType.hashCode()); return result; diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCostsFactory.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCostsFactory.java index 3fcc5ca9868..6a0be5414f0 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCostsFactory.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/jsprit/NetworkBasedTransportCostsFactory.java @@ -38,10 +38,10 @@ * @author steffenaxer */ public class NetworkBasedTransportCostsFactory implements VRPTransportCostsFactory { - Scenario scenario; - Carriers carriers; - Map travelTimes; - Config config; + final Scenario scenario; + final Carriers carriers; + final Map travelTimes; + final Config config; public NetworkBasedTransportCostsFactory(Scenario scenario, Carriers carriers, Map travelTimes, Config config) { this.scenario = scenario; diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/CarrierScoreStats.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/CarrierScoreStats.java index dd289a49b1b..84556de1a14 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/CarrierScoreStats.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/CarrierScoreStats.java @@ -178,10 +178,10 @@ public void notifyIterationEnds(final IterationEndsEvent event) { nofAvgScores++; } } - log.info("-- avg. score of the executed plan of each agent: " + (sumExecutedScores / nofExecutedScores)); - log.info("-- avg. score of the worst plan of each agent: " + (sumScoreWorst / nofScoreWorst)); - log.info("-- avg. of the avg. plan score per agent: " + (sumAvgScores / nofAvgScores)); - log.info("-- avg. score of the best plan of each agent: " + (sumScoreBest / nofScoreBest)); + log.info("-- avg. score of the executed plan of each agent: {}", sumExecutedScores / nofExecutedScores); + log.info("-- avg. score of the worst plan of each agent: {}", sumScoreWorst / nofScoreWorst); + log.info("-- avg. of the avg. plan score per agent: {}", sumAvgScores / nofAvgScores); + log.info("-- avg. score of the best plan of each agent: {}", sumScoreBest / nofScoreBest); try { this.out.write(event.getIteration() + "\t" + (sumExecutedScores / nofExecutedScores) + "\t" + diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/LegHistogram.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/LegHistogram.java index 1db193121ec..fff393eee93 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/LegHistogram.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/analysis/LegHistogram.java @@ -391,11 +391,8 @@ private int getBinIndex(final double time) { } private ModeData getDataForMode(final String legMode) { - ModeData modeData = this.data.get(legMode); - if (modeData == null) { - modeData = new ModeData(this.nofBins + 1); // +1 for all times out of our range - this.data.put(legMode, modeData); - } + // +1 for all times out of our range + ModeData modeData = this.data.computeIfAbsent(legMode, k -> new ModeData(this.nofBins + 1)); return modeData; } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/CarrierScoringFunctionFactoryImpl.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/CarrierScoringFunctionFactoryImpl.java index 6d137ce6f27..759b3da5890 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/CarrierScoringFunctionFactoryImpl.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/CarrierScoringFunctionFactoryImpl.java @@ -237,7 +237,7 @@ public void handleEvent(Event event) { CarrierVehicle carrierVehicle = CarriersUtils.getCarrierVehicle(carrier, ((LinkEnterEvent) event).getVehicleId()); if(carrierVehicle == null) throw new IllegalStateException("carrier vehicle missing"); double toll = roadPricing.getTollAmount(carrierVehicle.getType().getId(),network.getLinks().get(((LinkEnterEvent) event).getLinkId() ),event.getTime() ); - if(toll > 0.) System.out.println("bing: vehicle " + carrierVehicle.getId() + " paid toll " + toll + "" ); + if(toll > 0.) System.out.println("bing: vehicle " + carrierVehicle.getId() + " paid toll " + toll ); score += (-1) * toll; } } diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/FreightScenarioCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/FreightScenarioCreator.java index be215bd0d7e..c258d01e703 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/FreightScenarioCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/FreightScenarioCreator.java @@ -47,7 +47,7 @@ final class FreightScenarioCreator { static int agentCounter = 1; - static Random random = new Random(Long.MAX_VALUE); + static final Random random = new Random(Long.MAX_VALUE); public static void main(String[] args) { diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/PassengerScenarioCreator.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/PassengerScenarioCreator.java index e19d4b506bb..3a742ced5e6 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/PassengerScenarioCreator.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/PassengerScenarioCreator.java @@ -43,7 +43,7 @@ final class PassengerScenarioCreator { static int agentCounter = 1; - static int nuOfAgentsPerHomeLink = 1; + static final int nuOfAgentsPerHomeLink = 1; public static void main(String[] args) { diff --git a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerAlongWithCarriers.java b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerAlongWithCarriers.java index 36f76f30787..9d54c7299e1 100644 --- a/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerAlongWithCarriers.java +++ b/contribs/freight/src/main/java/org/matsim/freight/carriers/usecases/chessboard/RunPassengerAlongWithCarriers.java @@ -97,7 +97,7 @@ public void run() { } - public final Config prepareConfig() { + public Config prepareConfig() { Config config = ConfigUtils.loadConfig(IOUtils.extendUrl(url, "config.xml")); config.controller().setOverwriteFileSetting( OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles ); config.global().setRandomSeed(4177); @@ -105,7 +105,7 @@ public final Config prepareConfig() { return config; } - public final Scenario prepareScenario(Config config) { + public Scenario prepareScenario(Config config) { Gbl.assertNotNull( config ); Scenario scenario = ScenarioUtils.loadScenario(config); CarriersUtils.addOrGetCarriers(scenario); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanReaderV1Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanReaderV1Test.java index 1be22630df2..38749fbabdf 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanReaderV1Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanReaderV1Test.java @@ -70,7 +70,7 @@ void testReaderReadsCorrectly() { Carrier carrier = carriers.getCarriers().values().iterator().next(); Assertions.assertEquals(1, carrier.getSelectedPlan().getScheduledTours().size()); Leg leg = (Leg) carrier.getSelectedPlan().getScheduledTours() - .iterator().next().getTour().getTourElements().get(0); + .iterator().next().getTour().getTourElements().getFirst(); NetworkRoute route = (NetworkRoute) leg.getRoute(); Assertions.assertEquals(3, route.getLinkIds().size()); Assertions.assertEquals("23", route.getStartLinkId().toString()); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test.java index e5412431ca5..0deffa73889 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2Test.java @@ -50,7 +50,7 @@ public class CarrierPlanXmlReaderV2Test { private Carrier testCarrier; @BeforeEach - public void setUp() throws Exception{ + public void setUp() { CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); new CarrierVehicleTypeReader( carrierVehicleTypes ).readFile( utils.getPackageInputDirectory() + "vehicleTypes_v2.xml" ); @@ -132,7 +132,7 @@ void test_whenReadingPlans_nuOfToursIsCorrect(){ @Test void test_whenReadingToursOfPlan1_nuOfActivitiesIsCorrect(){ List plans = new ArrayList<>(testCarrier.getPlans()); - CarrierPlan plan1 = plans.get(0); + CarrierPlan plan1 = plans.getFirst(); ScheduledTour tour1 = plan1.getScheduledTours().iterator().next(); Assertions.assertEquals(5,tour1.getTour().getTourElements().size()); } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest.java index 22d23f8eefe..fb12a37ff82 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlReaderV2WithDtdTest.java @@ -43,7 +43,7 @@ public class CarrierPlanXmlReaderV2WithDtdTest { private Carrier testCarrier; @BeforeEach - public void setUp() throws Exception{ + public void setUp() { CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); new CarrierVehicleTypeReader( carrierVehicleTypes ).readFile( utils.getPackageInputDirectory() + "vehicleTypes_v2.xml" ); @@ -134,7 +134,7 @@ void test_whenReadingPlans_nuOfToursIsCorrect(){ @Disabled void test_whenReadingToursOfPlan1_nuOfActivitiesIsCorrect(){ List plans = new ArrayList<>(testCarrier.getPlans()); - CarrierPlan plan1 = plans.get(0); + CarrierPlan plan1 = plans.getFirst(); ScheduledTour tour1 = plan1.getScheduledTours().iterator().next(); Assertions.assertEquals(5,tour1.getTour().getTourElements().size()); } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java index 822b98269d6..46444ed07d3 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2Test.java @@ -43,7 +43,7 @@ public class CarrierPlanXmlWriterV2Test { private Carrier testCarrier; @BeforeEach - public void setUp() throws Exception{ + public void setUp() { CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); new CarrierVehicleTypeReader( carrierVehicleTypes ).readFile( this.testUtils.getPackageInputDirectory() + "vehicleTypes_v2.xml" ); @@ -104,7 +104,7 @@ void test_whenReadingCarrier_itSelectsPlansCorrectly(){ @Test void test_whenReadingPlans_nuOfToursIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); assertEquals(1, plans.get(0).getScheduledTours().size()); assertEquals(1, plans.get(1).getScheduledTours().size()); assertEquals(1, plans.get(2).getScheduledTours().size()); @@ -112,15 +112,15 @@ void test_whenReadingPlans_nuOfToursIsCorrect(){ @Test void test_whenReadingToursOfPlan1_nuOfActivitiesIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); - CarrierPlan plan1 = plans.get(0); + List plans = new ArrayList<>(testCarrier.getPlans()); + CarrierPlan plan1 = plans.getFirst(); ScheduledTour tour1 = plan1.getScheduledTours().iterator().next(); assertEquals(5,tour1.getTour().getTourElements().size()); } @Test void test_whenReadingToursOfPlan2_nuOfActivitiesIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan2 = plans.get(1); ScheduledTour tour1 = plan2.getScheduledTours().iterator().next(); assertEquals(9,tour1.getTour().getTourElements().size()); @@ -128,7 +128,7 @@ void test_whenReadingToursOfPlan2_nuOfActivitiesIsCorrect(){ @Test void test_whenReadingToursOfPlan3_nuOfActivitiesIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan3 = plans.get(2); ScheduledTour tour1 = plan3.getScheduledTours().iterator().next(); assertEquals(9,tour1.getTour().getTourElements().size()); @@ -136,7 +136,7 @@ void test_whenReadingToursOfPlan3_nuOfActivitiesIsCorrect(){ private boolean exactlyTheseVehiclesAreInVehicleCollection(List> asList, Collection carrierVehicles) { - List vehicles = new ArrayList(carrierVehicles); + List vehicles = new ArrayList<>(carrierVehicles); for(CarrierVehicle type : carrierVehicles) if(asList.contains(type.getId() )) vehicles.remove(type ); return vehicles.isEmpty(); } @@ -151,10 +151,10 @@ void test_CarrierHasAttributes(){ void test_ServicesAndShipmentsHaveAttributes(){ Object serviceCustomerAtt = testCarrier.getServices().get(Id.create("serv1",CarrierService.class)).getAttributes().getAttribute("customer"); assertNotNull(serviceCustomerAtt); - assertEquals("someRandomCustomer", (String) serviceCustomerAtt); + assertEquals("someRandomCustomer", serviceCustomerAtt); Object shipmentCustomerAtt = testCarrier.getShipments().get(Id.create("s1",CarrierShipment.class)).getAttributes().getAttribute("customer"); assertNotNull(shipmentCustomerAtt); - assertEquals("someRandomCustomer", (String) shipmentCustomerAtt); + assertEquals("someRandomCustomer", shipmentCustomerAtt); } } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java index 7788b8895f5..b3a12fdb60f 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierPlanXmlWriterV2_1Test.java @@ -26,7 +26,6 @@ import org.junit.jupiter.api.extension.RegisterExtension; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.TransportMode; -import org.matsim.freight.carriers.*; import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; import org.matsim.testcases.MatsimTestUtils; import org.matsim.vehicles.Vehicle; @@ -43,7 +42,7 @@ public class CarrierPlanXmlWriterV2_1Test { private Carrier testCarrier; @BeforeEach - public void setUp() throws Exception{ + public void setUp() { CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); new CarrierVehicleTypeReader( carrierVehicleTypes ).readFile( this.testUtils.getPackageInputDirectory() + "vehicleTypes_v2.xml" ); @@ -65,12 +64,15 @@ void test_whenReadingServices_nuOfServicesIsCorrect(){ void test_whenReadingCarrier_itReadsTypeIdsCorrectly(){ CarrierVehicle light = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("lightVehicle")); + assert light != null; assertEquals("light",light.getVehicleTypeId().toString()); CarrierVehicle medium = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("mediumVehicle")); + assert medium != null; assertEquals("medium",medium.getVehicleTypeId().toString()); CarrierVehicle heavy = CarriersUtils.getCarrierVehicle(testCarrier, Id.createVehicleId("heavyVehicle")); + assert heavy != null; assertEquals("heavy",heavy.getVehicleTypeId().toString()); } @@ -104,7 +106,7 @@ void test_whenReadingCarrier_itSelectsPlansCorrectly(){ @Test void test_whenReadingPlans_nuOfToursIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); assertEquals(1, plans.get(0).getScheduledTours().size()); assertEquals(1, plans.get(1).getScheduledTours().size()); assertEquals(1, plans.get(2).getScheduledTours().size()); @@ -112,15 +114,15 @@ void test_whenReadingPlans_nuOfToursIsCorrect(){ @Test void test_whenReadingToursOfPlan1_nuOfActivitiesIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); - CarrierPlan plan1 = plans.get(0); + List plans = new ArrayList<>(testCarrier.getPlans()); + CarrierPlan plan1 = plans.getFirst(); ScheduledTour tour1 = plan1.getScheduledTours().iterator().next(); assertEquals(5,tour1.getTour().getTourElements().size()); } @Test void test_whenReadingToursOfPlan2_nuOfActivitiesIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan2 = plans.get(1); ScheduledTour tour1 = plan2.getScheduledTours().iterator().next(); assertEquals(9,tour1.getTour().getTourElements().size()); @@ -128,7 +130,7 @@ void test_whenReadingToursOfPlan2_nuOfActivitiesIsCorrect(){ @Test void test_whenReadingToursOfPlan3_nuOfActivitiesIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan3 = plans.get(2); ScheduledTour tour1 = plan3.getScheduledTours().iterator().next(); assertEquals(9,tour1.getTour().getTourElements().size()); @@ -136,31 +138,32 @@ void test_whenReadingToursOfPlan3_nuOfActivitiesIsCorrect(){ @Test void test_whenReadingToursOfPlan1_SpritScoreIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); - CarrierPlan plan1 = plans.get(0); + List plans = new ArrayList<>(testCarrier.getPlans()); + CarrierPlan plan1 = plans.getFirst(); plan1.getAttributes().getAttribute("jspritScore"); - assertEquals(Double.NaN, CarriersUtils.getJspritScore(plan1), testUtils.EPSILON); + assertEquals(Double.NaN, CarriersUtils.getJspritScore(plan1), MatsimTestUtils.EPSILON); + assertEquals(Double.NaN, CarriersUtils.getJspritScore(plan1), MatsimTestUtils.EPSILON); } @Test void test_whenReadingToursOfPlan2_jSpritScoreIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan2 = plans.get(1); plan2.getAttributes().getAttribute("jspritScore"); - assertEquals(80.0, CarriersUtils.getJspritScore(plan2), testUtils.EPSILON); + assertEquals(80.0, CarriersUtils.getJspritScore(plan2), MatsimTestUtils.EPSILON); } @Test void test_whenReadingToursOfPlan3_jSpritIsCorrect(){ - List plans = new ArrayList(testCarrier.getPlans()); + List plans = new ArrayList<>(testCarrier.getPlans()); CarrierPlan plan3 = plans.get(2); plan3.getAttributes().getAttribute("jspritScore"); - assertEquals(105.0, CarriersUtils.getJspritScore(plan3), testUtils.EPSILON); + assertEquals(105.0, CarriersUtils.getJspritScore(plan3), MatsimTestUtils.EPSILON); } private boolean exactlyTheseVehiclesAreInVehicleCollection(List> asList, Collection carrierVehicles) { - List vehicles = new ArrayList(carrierVehicles); + List vehicles = new ArrayList<>(carrierVehicles); for(CarrierVehicle type : carrierVehicles) if(asList.contains(type.getId() )) vehicles.remove(type ); return vehicles.isEmpty(); } @@ -175,10 +178,10 @@ void test_CarrierHasAttributes(){ void test_ServicesAndShipmentsHaveAttributes(){ Object serviceCustomerAtt = testCarrier.getServices().get(Id.create("serv1",CarrierService.class)).getAttributes().getAttribute("customer"); assertNotNull(serviceCustomerAtt); - assertEquals("someRandomCustomer", (String) serviceCustomerAtt); + assertEquals("someRandomCustomer", serviceCustomerAtt); Object shipmentCustomerAtt = testCarrier.getShipments().get(Id.create("s1",CarrierShipment.class)).getAttributes().getAttribute("customer"); assertNotNull(shipmentCustomerAtt); - assertEquals("someRandomCustomer", (String) shipmentCustomerAtt); + assertEquals("someRandomCustomer", shipmentCustomerAtt); } @Test diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java index be71e48b2ca..71d69e6d216 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierReadWriteV2_1Test.java @@ -26,8 +26,6 @@ import org.matsim.freight.carriers.*; import org.matsim.testcases.MatsimTestUtils; -import java.io.FileNotFoundException; -import java.io.IOException; import java.util.Collections; public class CarrierReadWriteV2_1Test { @@ -36,7 +34,7 @@ public class CarrierReadWriteV2_1Test { private MatsimTestUtils utils = new MatsimTestUtils(); @Test - void readWriteTest() throws FileNotFoundException, IOException { + void readWriteTest() { Carriers carriers = new Carriers(Collections.emptyList()); CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); @@ -57,7 +55,7 @@ void readWriteTest() throws FileNotFoundException, IOException { @Test - void readWriteReadTest() throws FileNotFoundException, IOException { + void readWriteReadTest() { Carriers carriers = new Carriers(Collections.emptyList()); CarrierVehicleTypes carrierVehicleTypes = new CarrierVehicleTypes(); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeLoaderTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeLoaderTest.java index df97a944c1d..97954bb151d 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeLoaderTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeLoaderTest.java @@ -40,7 +40,7 @@ public class CarrierVehicleTypeLoaderTest { private Carriers carriers; @BeforeEach - public void setUp() throws Exception{ + public void setUp() { types = new CarrierVehicleTypes(); new CarrierVehicleTypeReader(types).readFile(utils.getClassInputDirectory() + "vehicleTypes.xml"); carriers = new Carriers(); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest.java index 2fe9b82dc26..3a2f5a5648e 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeReaderTest.java @@ -69,7 +69,7 @@ void test_whenReadingTypeMedium_itReadsDescriptionCorrectly(){ @Test void test_whenReadingTypeMedium_itReadsCapacityCorrectly(){ VehicleType medium = types.getVehicleTypes().get(Id.create("medium", org.matsim.vehicles.VehicleType.class ) ); - assertEquals(30., (double) medium.getCapacity().getOther(), Double.MIN_VALUE ); + assertEquals(30., medium.getCapacity().getOther(), Double.MIN_VALUE ); } @Test @@ -104,7 +104,7 @@ void readV2andWriteV2() { log.info("") ; log.info("now starting for real") ; log.info("") ; - String inFilename1 = utils.getClassInputDirectory() + "vehicleTypes_v2.xml";; + String inFilename1 = utils.getClassInputDirectory() + "vehicleTypes_v2.xml"; CarrierVehicleTypes types1 = new CarrierVehicleTypes(); new CarrierVehicleTypeReader( types1 ).readFile( inFilename1 ); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeTest.java index 8ca8a5aae02..24328872de2 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/CarrierVehicleTypeTest.java @@ -39,7 +39,7 @@ public class CarrierVehicleTypeTest { CarrierVehicleTypes types; @BeforeEach - public void setUp() throws Exception{ + public void setUp() { final Id vehicleTypeId = Id.create( "medium", VehicleType.class ); VehicleType mediumType = VehicleUtils.getFactory().createVehicleType( vehicleTypeId ); { @@ -59,14 +59,12 @@ public void setUp() throws Exception{ //Setting up a copy of the one above VehicleType newVehicleType1 = VehicleUtils.getFactory().createVehicleType( Id.create("medium2", VehicleType.class ) ); VehicleUtils.copyFromTo( mediumType, newVehicleType1 ); - VehicleType mediumType2 = newVehicleType1; - types.getVehicleTypes().put(mediumType2.getId(), mediumType2); + types.getVehicleTypes().put(newVehicleType1.getId(), newVehicleType1); //Setting up a smaller one based of the one above and changing all values. final Id smallTypeId = Id.create( "small", VehicleType.class ); - VehicleType newVehicleType = VehicleUtils.getFactory().createVehicleType( smallTypeId ); - VehicleUtils.copyFromTo( mediumType, newVehicleType ); - VehicleType smallType = newVehicleType ; + VehicleType smallType = VehicleUtils.getFactory().createVehicleType( smallTypeId ); + VehicleUtils.copyFromTo( mediumType, smallType ); { CostInformation costInformation = smallType.getCostInformation() ; costInformation.setFixedCost( 25. ); @@ -79,7 +77,7 @@ public void setUp() throws Exception{ capacity.setWeightInTons( 16 ) ; // VehicleType smallType = CarriersUtils.CarrierVehicleTypeBuilder.newInstance( smallTypeId, mediumType ) smallType.setDescription( "Small Vehicle" ).setMaximumVelocity( 10.0 ) ; - types.getVehicleTypes().put( smallType.getId(), smallType ); + types.getVehicleTypes().put( smallType.getId(), smallType); } } diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/FreightCarriersConfigGroupTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/FreightCarriersConfigGroupTest.java index 6113348707b..33a4d6736e8 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/FreightCarriersConfigGroupTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/FreightCarriersConfigGroupTest.java @@ -55,17 +55,18 @@ void test_configXmlCanBeParsed() { FreightCarriersConfigGroup freight = new FreightCarriersConfigGroup(); Config config = ConfigUtils.createConfig(freight); - String xml = "\n" + - "\n" + - "\n" + - " \t\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; + String xml = """ + + + + \t + + + + + + + """; InputStream is = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintFromVehiclesFileTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintFromVehiclesFileTest.java index d7329adc924..43abc654497 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintFromVehiclesFileTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintFromVehiclesFileTest.java @@ -136,8 +136,7 @@ final void CarrierSmallBatteryTest_Version1() throws ExecutionException, Interru List elements = carrierV1.getSelectedPlan().getScheduledTours().iterator().next().getTour() .getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); @@ -214,8 +213,7 @@ final void CarrierLargeBatteryTest_Version2() throws ExecutionException, Interru List elements = carrierV2.getSelectedPlan().getScheduledTours().iterator().next().getTour() .getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); @@ -293,8 +291,7 @@ final void Carrier2SmallBatteryTest_Version3() throws ExecutionException, Interr double distanceTour = 0.0; List elements = scheduledTour.getTour().getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); @@ -380,8 +377,7 @@ final void CarrierWithAdditionalDieselVehicleTest_Version4() throws ExecutionExc double distanceTour = 0.0; List elements = scheduledTour.getTour().getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintTest.java index 16c42c7286c..50b8505cb70 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/DistanceConstraintTest.java @@ -143,8 +143,7 @@ final void CarrierSmallBatteryTest_Version1() throws ExecutionException, Interru List elements = carrierV1.getSelectedPlan().getScheduledTours().iterator().next().getTour() .getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); @@ -227,8 +226,7 @@ final void CarrierLargeBatteryTest_Version2() throws ExecutionException, Interru List elements = carrierV2.getSelectedPlan().getScheduledTours().iterator().next().getTour() .getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); @@ -315,8 +313,7 @@ final void Carrier2SmallBatteryTest_Version3() throws ExecutionException, Interr double distanceTour = 0.0; List elements = scheduledTour.getTour().getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); @@ -415,8 +412,7 @@ final void CarrierWithAdditionalDieselVehicleTest_Version4() throws ExecutionExc double distanceTour = 0.0; List elements = scheduledTour.getTour().getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); @@ -494,13 +490,12 @@ final void CarrierWithShipmentsMidSizeBatteryTest_Version5() throws ExecutionExc MatsimTestUtils.EPSILON, "Wrong maximum distance of the tour of this vehicleType"); - ArrayList distancesOfTours = new ArrayList(); + ArrayList distancesOfTours = new ArrayList<>(); for (ScheduledTour scheduledTour: carrierV5.getSelectedPlan().getScheduledTours()) { double distanceTour = 0.0; List elements = scheduledTour.getTour().getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); @@ -576,13 +571,12 @@ final void CarrierWithShipmentsLargeBatteryTest_Version6() throws ExecutionExcep MatsimTestUtils.EPSILON, "Wrong maximum distance of the tour of this vehicleType"); - ArrayList distancesOfTours = new ArrayList(); + ArrayList distancesOfTours = new ArrayList<>(); for (ScheduledTour scheduledTour: carrierV5.getSelectedPlan().getScheduledTours()) { double distanceTour = 0.0; List elements = scheduledTour.getTour().getTourElements(); for (Tour.TourElement element : elements) { - if (element instanceof Tour.Leg) { - Tour.Leg legElement = (Tour.Leg) element; + if (element instanceof Tour.Leg legElement) { if (legElement.getRoute().getDistance() != 0) distanceTour = distanceTour + RouteUtils.calcDistance((NetworkRoute) legElement.getRoute(), 0, 0, scenario.getNetwork()); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/FixedCostsTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/FixedCostsTest.java index 07ea6e5ac60..13433ede378 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/FixedCostsTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/FixedCostsTest.java @@ -65,7 +65,7 @@ public class FixedCostsTest { private final Carriers carriersPlannedAndRouted = new Carriers(); @BeforeEach - public void setUp() throws Exception { + public void setUp() { // Create carrier with services; service1 nearby the depot, service2 at the opposite side of the network CarrierService service1 = createMatsimService("Service1", "i(3,0)", 1); CarrierService service2 = createMatsimService("Service2", "i(9,9)R", 1); @@ -161,7 +161,7 @@ public void setUp() throws Exception { netBuilder.setTimeSliceWidth(86400) ; // !!!!, otherwise it will not do anything. for (Carrier carrier : carriers.getCarriers().values()) { - log.info("creating and solving VRP for carrier: " + carrier.getId().toString()); + log.info("creating and solving VRP for carrier: {}", carrier.getId().toString()); //Build VRP VehicleRoutingProblem.Builder vrpBuilder = MatsimJspritFactory.createRoutingProblemBuilder(carrier, network); vrpBuilder.setRoutingCost(netBasedCosts) ; diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java index 991ef3eb236..15f7a1a7c86 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/jsprit/MatsimTransformerTest.java @@ -63,7 +63,7 @@ void whenTransforming_jSpritType2matsimType_itIsMadeCorrectly() { VehicleType matsimType = MatsimJspritFactory.createMatsimVehicleType(jspritType); assertNotNull(matsimType); assertEquals("myType", matsimType.getId().toString()); - assertEquals(50., (double) matsimType.getCapacity().getWeightInTons(), Double.MIN_VALUE); + assertEquals(50., matsimType.getCapacity().getWeightInTons(), Double.MIN_VALUE); assertEquals(10.0, matsimType.getCostInformation().getCostsPerMeter(), 0.01); assertEquals(5.0, matsimType.getCostInformation().getCostsPerSecond(), 0.01); assertEquals(100.0, matsimType.getCostInformation().getFixedCosts(), 0.01); @@ -133,8 +133,8 @@ void whenTransforming_matsimService2jspritService_isMadeCorrectly() { assertEquals(10.0, service.getTimeWindow().getStart(), 0.01); Service service2 = MatsimJspritFactory.createJspritService(carrierService, null); - assertTrue(service != service2); - assertTrue(service.equals(service2)); + assertNotSame(service, service2); + assertEquals(service, service2); } @Test @@ -153,8 +153,8 @@ void whenTransforming_jspritService2matsimService_isMadeCorrectly() { assertEquals(10.0, service.getServiceStartTimeWindow().getStart(), 0.01); CarrierService service2 = MatsimJspritFactory.createCarrierService(carrierService); - assertTrue(service != service2); - assertTrue(service.equals(service2)); + assertNotSame(service, service2); + assertEquals(service, service2); } @Test @@ -177,8 +177,8 @@ void whenTransforming_matsimShipment2jspritShipment_isMadeCorrectly() { assertEquals(50, shipment.getSize().get(0)); Shipment shipment2 = MatsimJspritFactory.createJspritShipment(carrierShipment); - assertTrue(shipment != shipment2); - assertTrue(shipment.equals(shipment2)); + assertNotSame(shipment, shipment2); + assertEquals(shipment, shipment2); } @Test @@ -205,8 +205,8 @@ void whenTransforming_jspritShipment2matsimShipment_isMadeCorrectly() { assertEquals(50, carrierShipment.getSize()); CarrierShipment carrierShipment2 = MatsimJspritFactory.createCarrierShipment(shipment); - assertTrue(carrierShipment != carrierShipment2); - assertTrue(carrierShipment.equals(carrierShipment2)); + assertNotSame(carrierShipment, carrierShipment2); + assertEquals(carrierShipment, carrierShipment2); } @Test @@ -228,7 +228,7 @@ private VehicleRoutingProblem getVehicleRoutingProblem(ScheduledTour sTour) { } private Collection getJobsFrom(ScheduledTour sTour) { - Collection services = new ArrayList(); + Collection services = new ArrayList<>(); for (Tour.TourElement e : sTour.getTour().getTourElements()) { if (e instanceof Tour.TourActivity) { if (e instanceof Tour.ServiceActivity) { @@ -295,7 +295,7 @@ void whenTransforming_matsimScheduledTourWithServiceAct2vehicleRoute_firstActIdM ScheduledTour sTour = getMatsimServiceTour(); VehicleRoutingProblem vehicleRoutingProblem = getVehicleRoutingProblem(sTour); VehicleRoute route = MatsimJspritFactory.createRoute(sTour, vehicleRoutingProblem); - assertEquals("to1", route.getTourActivities().getActivities().get(0).getLocation().getId()); + assertEquals("to1", route.getTourActivities().getActivities().getFirst().getLocation().getId()); } @Test @@ -308,7 +308,7 @@ void whenTransforming_matsimScheduledTourWithServiceAct2vehicleRoute_secondActId @Test void whenTransforming_matsimPlan2vehicleRouteSolution_itIsMadeCorrectly() { - List sTours = new ArrayList(); + List sTours = new ArrayList<>(); ScheduledTour matsimTour = getMatsimTour("matsimVehicle"); sTours.add(matsimTour); ScheduledTour matsimTour1 = getMatsimTour("matsimVehicle1"); @@ -401,11 +401,6 @@ private CarrierShipment getMatsimShipment(String id, String from, String to, int .setPickupServiceTime(15.0).setPickupTimeWindow(TimeWindow.newInstance(1.0, 5.0)).build(); } - @Test - void createVehicleRoutingProblemWithServices_isMadeCorrectly() { - // TODO create - } - @Test void createVehicleRoutingProblemBuilderWithServices_isMadeCorrectly() { Carrier carrier = createCarrierWithServices(); @@ -423,7 +418,7 @@ void createVehicleRoutingProblemBuilderWithServices_isMadeCorrectly() { assertEquals("i(6,0)", vehicle.getStartLocation().getId()); assertEquals(10.0, vehicle.getEarliestDeparture(), 0.0); assertEquals(20.0, vehicle.getLatestArrival(), 0.0); - assertEquals("matsimType", vehicle.getType().getTypeId().toString()); + assertEquals("matsimType", vehicle.getType().getTypeId()); assertEquals(10.0, vehicle.getType().getVehicleCostParams().perDistanceUnit, 0.0); assertEquals(5.0, vehicle.getType().getVehicleCostParams().perTransportTimeUnit, 0.0); assertEquals(100.0, vehicle.getType().getVehicleCostParams().fix, 0.0); @@ -436,26 +431,21 @@ void createVehicleRoutingProblemBuilderWithServices_isMadeCorrectly() { assertNotNull(jobS1); assertEquals("serviceId", jobS1.getId()); assertEquals(20, jobS1.getSize().get(0)); - assertTrue(jobS1 instanceof Service); + assertInstanceOf(Service.class, jobS1); Service service1 = (Service) jobS1; assertEquals(20, service1.getSize().get(0)); assertEquals(10.0, service1.getServiceDuration(), 0.0); - assertEquals("i(7,4)R", service1.getLocation().getId().toString()); + assertEquals("i(7,4)R", service1.getLocation().getId()); Job jobS2 = vrp.getJobs().get("serviceId2"); assertNotNull(jobS2); assertEquals("serviceId2", jobS2.getId()); assertEquals(10, jobS2.getSize().get(0)); - assertTrue(jobS2 instanceof Service); + assertInstanceOf(Service.class, jobS2); Service service2 = (Service) jobS2; assertEquals(10, service2.getSize().get(0)); assertEquals(20.0, service2.getServiceDuration(), 0.0); - assertEquals("i(3,9)", service2.getLocation().getId().toString()); - } - - @Test - void createVehicleRoutingProblemWithShipments_isMadeCorrectly() { - // TODO create + assertEquals("i(3,9)", service2.getLocation().getId()); } // @Disabled //Set to ignore due to not implemented functionality of Shipments in MatsimJspritFactory @@ -476,7 +466,7 @@ void createVehicleRoutingProblemBuilderWithShipments_isMadeCorrectly() { assertEquals("i(6,0)", vehicle.getStartLocation().getId()); assertEquals(10.0, vehicle.getEarliestDeparture(), 0.0); assertEquals(20.0, vehicle.getLatestArrival(), 0.0); - assertEquals("matsimType", vehicle.getType().getTypeId().toString()); + assertEquals("matsimType", vehicle.getType().getTypeId()); assertEquals(10.0, vehicle.getType().getVehicleCostParams().perDistanceUnit, 0.0); assertEquals(5.0, vehicle.getType().getVehicleCostParams().perTransportTimeUnit, 0.0); assertEquals(100.0, vehicle.getType().getVehicleCostParams().fix, 0.0); @@ -489,7 +479,7 @@ void createVehicleRoutingProblemBuilderWithShipments_isMadeCorrectly() { assertNotNull(jobS1); assertEquals("shipment1", jobS1.getId()); assertEquals(10, jobS1.getSize().get(0)); - assertTrue(jobS1 instanceof Shipment); + assertInstanceOf(Shipment.class, jobS1); Shipment shipment1 = (Shipment) jobS1; assertEquals(10, shipment1.getSize().get(0)); assertEquals("i(6,0)", shipment1.getPickupLocation().getId()); @@ -505,10 +495,10 @@ void createVehicleRoutingProblemBuilderWithShipments_isMadeCorrectly() { assertNotNull(jobS2); assertEquals("shipment2", jobS2.getId()); assertEquals(20, jobS2.getSize().get(0)); - assertTrue(jobS2 instanceof Shipment); + assertInstanceOf(Shipment.class, jobS2); Shipment shipment2 = (Shipment) jobS2; assertEquals(20, shipment2.getSize().get(0)); - assertEquals("i(3,9)", shipment2.getDeliveryLocation().getId().toString()); + assertEquals("i(3,9)", shipment2.getDeliveryLocation().getId()); } private Carrier createCarrierWithServices() { diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java index 121eb0c5616..81ad7c6e577 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/DistanceScoringFunctionFactoryForTests.java @@ -62,7 +62,7 @@ public DriverLegScoring(Carrier carrier, Network network) { super(); this.network = network; this.carrier = carrier; - employedVehicles = new HashSet(); + employedVehicles = new HashSet<>(); } @@ -94,8 +94,7 @@ public void startLeg(double time, Leg leg) { @Override public void endLeg(double time) { - if(currentLeg.getRoute() instanceof NetworkRoute){ - NetworkRoute nRoute = (NetworkRoute) currentLeg.getRoute(); + if(currentLeg.getRoute() instanceof NetworkRoute nRoute){ Id vehicleId = nRoute.getVehicleId(); CarrierVehicle vehicle = CarriersUtils.getCarrierVehicle(carrier, vehicleId); Gbl.assertNotNull(vehicle); @@ -154,7 +153,7 @@ static class DriverActScoring implements BasicScoring, ActivityScoring{ double startTimeOfEnd; - double amountPerHour = 20.0; + final double amountPerHour = 20.0; @Override public void startActivity(double time, Activity act) { @@ -192,7 +191,7 @@ public void reset() { static class NumberOfToursAward implements BasicScoring{ - private Carrier carrier; + private final Carrier carrier; public NumberOfToursAward(Carrier carrier) { super(); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java index 3bf4716a680..68dbf0bc7ab 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/ScoringFunctionFactoryForTests.java @@ -61,7 +61,7 @@ public DriverLegScoring(Carrier carrier, Network network) { super(); this.network = network; this.carrier = carrier; - employedVehicles = new HashSet(); + employedVehicles = new HashSet<>(); } @@ -93,8 +93,7 @@ public void startLeg(double time, Leg leg) { @Override public void endLeg(double time) { - if(currentLeg.getRoute() instanceof NetworkRoute){ - NetworkRoute nRoute = (NetworkRoute) currentLeg.getRoute(); + if(currentLeg.getRoute() instanceof NetworkRoute nRoute){ Id vehicleId = nRoute.getVehicleId(); CarrierVehicle vehicle = CarriersUtils.getCarrierVehicle(carrier, vehicleId); Gbl.assertNotNull(vehicle); @@ -136,7 +135,7 @@ static class DriverActScoring implements BasicScoring, ActivityScoring{ double startTimeOfEnd; - double amountPerHour = 20.0; + final double amountPerHour = 20.0; @Override public void startActivity(double time, Activity act) { @@ -174,7 +173,7 @@ public void reset() { static class NumberOfToursAward implements BasicScoring{ - private Carrier carrier; + private final Carrier carrier; public NumberOfToursAward(Carrier carrier) { super(); @@ -199,7 +198,7 @@ public void reset() { } - private Network network; + private final Network network; public ScoringFunctionFactoryForTests(Network network) { super(); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/TimeScoringFunctionFactoryForTests.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/TimeScoringFunctionFactoryForTests.java index ee8e1921ed7..a8cc127ba93 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/TimeScoringFunctionFactoryForTests.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/mobsim/TimeScoringFunctionFactoryForTests.java @@ -94,8 +94,7 @@ public void startLeg(double time, Leg leg) { @Override public void endLeg(double time) { - if(currentLeg.getRoute() instanceof NetworkRoute){ - NetworkRoute nRoute = (NetworkRoute) currentLeg.getRoute(); + if(currentLeg.getRoute() instanceof NetworkRoute nRoute){ Id vehicleId = nRoute.getVehicleId(); CarrierVehicle vehicle = CarriersUtils.getCarrierVehicle(carrier, vehicleId); assert vehicle != null : "cannot find vehicle with id=" + vehicleId; @@ -200,7 +199,7 @@ public void reset() { static class NumberOfToursAward implements BasicScoring{ - private Carrier carrier; + private final Carrier carrier; public NumberOfToursAward(Carrier carrier) { super(); diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsIT.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsIT.java index a50b4c5430d..4b86789a97a 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsIT.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsIT.java @@ -87,8 +87,8 @@ public void setUp() { //Create vehicle for Carriers final Id vehTypeId = Id.create( "gridType", VehicleType.class ); - VehicleType carrierVehType = VehicleUtils.getFactory().createVehicleType( vehTypeId );; - EngineInformation engineInformation = carrierVehType.getEngineInformation() ; + VehicleType carrierVehType = VehicleUtils.getFactory().createVehicleType( vehTypeId ); + EngineInformation engineInformation = carrierVehType.getEngineInformation() ; engineInformation.setFuelType( FuelType.diesel ); engineInformation.setFuelConsumption( 0.015 ); VehicleCapacity capacity = carrierVehType.getCapacity() ; diff --git a/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsTest.java b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsTest.java index 678b2727ff1..ba52b1cfd00 100644 --- a/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsTest.java +++ b/contribs/freight/src/test/java/org/matsim/freight/carriers/utils/CarrierControlerUtilsTest.java @@ -58,7 +58,6 @@ import java.net.URL; import java.util.Collection; -import java.util.concurrent.ExecutionException; public class CarrierControlerUtilsTest { @@ -443,7 +442,7 @@ void testRunJsprit_allInformationGiven(){ * This test should lead to an exception, because the NumberOfJspritIterations is not set for carriers. */ @Test - void testRunJsprit_NoOfJspritIterationsMissing() throws ExecutionException, InterruptedException { + void testRunJsprit_NoOfJspritIterationsMissing() { assertThrows(java.util.concurrent.ExecutionException.class, () -> { Config config = prepareConfig(); config.controller().setOutputDirectory(utils.getOutputDirectory()); diff --git a/contribs/hybridsim/pom.xml b/contribs/hybridsim/pom.xml index a94a59e4058..5917f032e3e 100644 --- a/contribs/hybridsim/pom.xml +++ b/contribs/hybridsim/pom.xml @@ -10,8 +10,8 @@ hybridsim - 4.27.1 - 1.64.0 + 4.27.2 + 1.65.0 diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/GeneralParkingModule.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/GeneralParkingModule.java index 29b225d5397..3a85713682c 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/GeneralParkingModule.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/GeneralParkingModule.java @@ -13,59 +13,31 @@ public class GeneralParkingModule implements StartupListener, BeforeMobsimListen private final Controler controler; private ParkingScore parkingScoreManager; -// public final ParkingScore getParkingScoreManager() { -// return parkingScoreManager; -// } - - public final void setParkingScoreManager(ParkingScore parkingScoreManager) { - this.parkingScoreManager = parkingScoreManager; - } - private ParkingInfrastructure parkingInfrastructureManager; private ParkingChoiceSimulation parkingChoiceSimulation; public GeneralParkingModule(Controler controler){ this.controler = controler ; - controler.addControlerListener(this); } - - @Override - public void notifyStartup(StartupEvent event) { + + @Override public void notifyStartup(StartupEvent event) { parkingChoiceSimulation = new ParkingChoiceSimulation(controler.getScenario(), parkingInfrastructureManager); controler.getEvents().addHandler( parkingChoiceSimulation ); -// controler.addControlerListener(parkingSimulation); - // was not doing anything there. kai, jul'15 } -// public final ParkingInfrastructure getParkingInfrastructure() { -// return parkingInfrastructureManager; -// } - - public final void setParkingInfrastructurManager(ParkingInfrastructure parkingInfrastructureManager) { - this.parkingInfrastructureManager = parkingInfrastructureManager; + @Override public void notifyBeforeMobsim(BeforeMobsimEvent event) { + parkingScoreManager.notifyBeforeMobsim(); + parkingInfrastructureManager.notifyBeforeMobsim(); + parkingChoiceSimulation.notifyBeforeMobsim(); } -// @Deprecated -// // lower level objects may keep back pointers to higher level objects if they have to, but we prefer that they do not provide them -// // as a service. kai, apr'15 -// public final Controler getControler() { -// return controler; -// } - - @Override - public void notifyBeforeMobsim(BeforeMobsimEvent event) { - parkingScoreManager.prepareForNewIteration(); - parkingInfrastructureManager.reset(); - parkingChoiceSimulation.prepareForNewIteration(); + public final void setParkingScoreManager(ParkingScore parkingScoreManager) { + this.parkingScoreManager = parkingScoreManager; } -// protected final ParkingInfrastructure getParkingInfrastructureManager() { -// return parkingInfrastructureManager; -// } -// -// protected final ParkingChoiceSimulation getParkingSimulation() { -// return parkingSimulation; -// } + public final void setParkingInfrastructurManager(ParkingInfrastructure parkingInfrastructureManager) { + this.parkingInfrastructureManager = parkingInfrastructureManager; + } } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/infrastructure/PC2Parking.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/infrastructure/PC2Parking.java index d0fdfda187d..0e2a9bc2cbb 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/infrastructure/PC2Parking.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/infrastructure/PC2Parking.java @@ -26,7 +26,7 @@ public interface PC2Parking { public Id getId(); - public int getMaximumParkingCapacity(); +// public int getMaximumParkingCapacity(); public int getAvailableParkingCapacity(); diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/infrastructure/PublicParking.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/infrastructure/PublicParking.java index 28a18a2dce8..93256534074 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/infrastructure/PublicParking.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/infrastructure/PublicParking.java @@ -25,12 +25,12 @@ public class PublicParking implements PC2Parking { - private Id id = null; - private int capacity =0; + private final Id id; + private final int capacity; private int availableParking=0; private Coord coord=null; private ParkingCostModel parkingCostModel=null; - private String groupName; + private final String groupName; public PublicParking(Id id, int capacity, Coord coord, ParkingCostModel parkingCostModel, String groupName){ this.id=id; @@ -56,14 +56,14 @@ public Coord getCoordinate(){ return coord; } - public boolean isParkingAvailable(){ - return availableParking>0; - } - - @Override - public int getMaximumParkingCapacity(){ - return capacity; - } +// public boolean isParkingAvailable(){ +// return availableParking>0; +// } +// +// @Override +// public int getMaximumParkingCapacity(){ +// return capacity; +// } @Override public int getAvailableParkingCapacity(){ diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScore.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScore.java index 1eed79efbf2..a6a36fadc7f 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScore.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScore.java @@ -18,7 +18,7 @@ public interface ParkingScore { void addScore(Id id, double incValue); - void prepareForNewIteration(); + void notifyBeforeMobsim(); double getParkingScoreScalingFactor(); @@ -34,4 +34,4 @@ public interface ParkingScore { void setRandomErrorTermManger(RandomErrorTermManager randomErrorTermManager); -} \ No newline at end of file +} diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScoreManager.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScoreManager.java index 49fd0109768..abc90d45b94 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScoreManager.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/scoring/ParkingScoreManager.java @@ -108,7 +108,7 @@ public synchronized void addScore(Id id, double incValue) { } @Override - public synchronized void prepareForNewIteration() { + public synchronized void notifyBeforeMobsim() { scores = new DoubleValueHashMap<>(); } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingChoiceSimulation.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingChoiceSimulation.java index 29bc9b7c65b..db2a710a0a8 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingChoiceSimulation.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingChoiceSimulation.java @@ -46,11 +46,9 @@ public final class ParkingChoiceSimulation implements PersonDepartureEventHandler, PersonArrivalEventHandler, ActivityEndEventHandler { - - private final ParkingInfrastructure parkingInfrastructureManager; private final Scenario scenario; - private IntegerValueHashMap> currentPlanElementIndex; + private IntegerValueHashMap> currentPlanElementIndices; private HashMap, ParkingOperationRequestAttributes> parkingOperationRequestAttributes; private DoubleValueHashMap> firstDepartureTimeOfDay; @@ -61,7 +59,7 @@ public ParkingChoiceSimulation(Scenario scenario, ParkingInfrastructure parkingI @Override public void handleEvent(ActivityEndEvent event) { - currentPlanElementIndex.increment(event.getPersonId()); + currentPlanElementIndices.increment(event.getPersonId() ); } @Override @@ -76,25 +74,37 @@ public void handleEvent(PersonDepartureEvent event) { } if (isFirstCarDepartureOfDay(event.getPersonId())) { - // (special case, think about it later) + // for the first departure of the day, we do not know when the parking actually started. The scoring is, in + // consequence, not done here, but done when _starting_ the _last_ parking of the day (see there). + // (yy what happens if the agent arrives by car but departs by some other mode, or the other way round? Can happen in particular if there is an additional home stop during the day.) ParkingOperationRequestAttributes parkingAttributes = new ParkingOperationRequestAttributes(); parkingAttributes.personId = event.getPersonId(); - // this is a trick to get the correct departure time + + // for the time being, we memorize a parking record with arrival time zero. This is corrected later, at the last arrival of the day. parkingAttributes.arrivalTime = 0; parkingAttributes.parkingDurationInSeconds = GeneralLib.getIntervalDuration(0, event.getTime()); parkingInfrastructureManager.personCarDepartureEvent(parkingAttributes); } else { + // parking has just ended: + + // finalize the corresponding record: ParkingOperationRequestAttributes parkingAttributes = parkingOperationRequestAttributes.get(event.getPersonId()); parkingAttributes.parkingDurationInSeconds = GeneralLib.getIntervalDuration(parkingAttributes.arrivalTime, event.getTime()); + + // hedge against a special case: if (parkingAttributes.parkingDurationInSeconds == 24 * 3600) { // (yyyy no idea what this is and why. kai, jul'15) + // (Presumably, the code is such that it cannot handle a parking duration of zero. Presumably, a parking + // duration of zero cannot happen, and therefore this is ok. However, if someone parks for exactly 24 hours, + // then this is at some point mapped back to zero, and then it may happen. kai, feb'24) parkingAttributes.parkingDurationInSeconds = 1; // not zero, because this might lead to NaN } - PC2Parking parking = parkingInfrastructureManager.personCarDepartureEvent(parkingAttributes); - parkingInfrastructureManager.scoreParkingOperation(parkingAttributes, parking); + // score the parking: + final PC2Parking parking = parkingInfrastructureManager.personCarDepartureEvent( parkingAttributes ); + parkingInfrastructureManager.scoreParkingOperation(parkingAttributes, parking ); } } @@ -106,7 +116,7 @@ public void handleEvent(PersonArrivalEvent event) { if (event.getLegMode().equalsIgnoreCase(TransportMode.car) && !event.getPersonId().toString().contains("pt") && isNotTransitAgent(event.getPersonId())) { // (exclude some cases (in a brittle way, i.e. based on IDs)) - // I think that this just packages some information together into the parkingAttributes: + // Generate most of the parking record (departure time will be added later): ParkingOperationRequestAttributes parkingAttributes = new ParkingOperationRequestAttributes(); { Link link = scenario.getNetwork().getLinks().get( event.getLinkId() ); @@ -120,9 +130,13 @@ public void handleEvent(PersonArrivalEvent event) { } if (isLastCarLegOfDay(personId)) { - // (special case, think about it later) - + // if this is the last arrival of the day, the parking record is already there, since it was generated at the first + // departure. However, the duration is not correct since at that time the arrival time was not known. + // (yy It looks to me that the arrivalTime remains at 0. why?) parkingAttributes.parkingDurationInSeconds = GeneralLib.getIntervalDuration(event.getTime(), firstDepartureTimeOfDay.get(personId)); + + // scoring of this special case is done further down, see there + } else { Activity activityBeforeNextCarLeg = getActivityBeforeNextCarLeg(personId); @@ -130,19 +144,19 @@ public void handleEvent(PersonArrivalEvent event) { double parkingDuration=0; if (endTime==Double.NEGATIVE_INFINITY || endTime==Double.POSITIVE_INFINITY){ - // (I think that this _can_ happen, especially in context of within-day replanning, if departure time is unknown. (*)) + // (in general, we take the (parking) end time from above. Sometimes, this end time does not have a useful value, in which case the current - // try to estimate parking duration + // try to estimate parking duration: Person person = scenario.getPopulation().getPersons().get(personId); List planElements = person.getSelectedPlan().getPlanElements(); - for (int i = currentPlanElementIndex.get(personId); i < planElements.size(); i++) { - if (planElements.get(i) instanceof Activity) { - parkingDuration+= ((Activity)planElements.get(i)).getMaximumDuration().seconds(); + for ( int ii = currentPlanElementIndices.get(personId ) ; ii < planElements.size(); ii++) { + if (planElements.get(ii) instanceof Activity) { + parkingDuration+= ((Activity)planElements.get(ii)).getMaximumDuration().seconds(); } - if (planElements.get(i) == activityBeforeNextCarLeg) { + if (planElements.get(ii) == activityBeforeNextCarLeg) { endTime=event.getTime()+parkingDuration; break; } @@ -150,15 +164,16 @@ public void handleEvent(PersonArrivalEvent event) { } parkingAttributes.parkingDurationInSeconds = GeneralLib.getIntervalDuration(event.getTime(), endTime); - // (This is the _estimated_ parking duration, since we are at arrival. This is needed to define the "best" parking + // (This is the _estimated_ parking duration, since we are at arrival, and in this special case we did not have the + // corresponding activity end time. This is needed to define the "best" parking // location ... cf. short-term/long-term parking at airports. Could rename the attributed into "expected...", but we // have seen at other places in the code that such attributes may change their interpretation based on context so will // not do this here.) } - parkingAttributes.legIndex = currentPlanElementIndex.get(personId); + parkingAttributes.legIndex = currentPlanElementIndices.get(personId ); - PC2Parking parking = parkingInfrastructureManager.parkVehicle(parkingAttributes); + final PC2Parking parking = parkingInfrastructureManager.parkVehicle(parkingAttributes); // to me this looks like first the agent arrives at his/her activity. And then the negative parking score is added after the // fact, however without consuming time. I.e. there is no physics. kai, jul'15 @@ -171,15 +186,11 @@ public void handleEvent(PersonArrivalEvent event) { } - currentPlanElementIndex.increment(personId); + currentPlanElementIndices.increment(personId ); } - private boolean isNotTransitAgent(Id persondId) { - return (Integer.parseInt(persondId.toString())< 1000000000); - } - - public void prepareForNewIteration() { - currentPlanElementIndex = new IntegerValueHashMap<>(); + public void notifyBeforeMobsim() { + currentPlanElementIndices = new IntegerValueHashMap<>(); parkingOperationRequestAttributes = new HashMap<>(); firstDepartureTimeOfDay = new DoubleValueHashMap<>(); @@ -215,6 +226,10 @@ public void prepareForNewIteration() { // === only private helper functions below this line === + private boolean isNotTransitAgent(Id persondId) { + return (Integer.parseInt(persondId.toString())< 1000000000); + } + private boolean isFirstCarDepartureOfDay(Id personId) { Person person = scenario.getPopulation().getPersons().get(personId); @@ -223,7 +238,7 @@ private boolean isFirstCarDepartureOfDay(Id personId) { } List planElements = person.getSelectedPlan().getPlanElements(); - for (int i = currentPlanElementIndex.get(personId) - 1; i >= 0; i--) { + for ( int i = currentPlanElementIndices.get(personId ) - 1 ; i >= 0; i--) { if (planElements.get(i) instanceof Leg) { Leg leg = (Leg) planElements.get(i); @@ -240,7 +255,7 @@ private boolean isFirstCarDepartureOfDay(Id personId) { private boolean isLastCarLegOfDay(Id personId) { Person person = scenario.getPopulation().getPersons().get(personId); List planElements = person.getSelectedPlan().getPlanElements(); - for (int i = currentPlanElementIndex.get(personId) + 1; i < planElements.size(); i++) { + for ( int i = currentPlanElementIndices.get(personId ) + 1 ; i < planElements.size(); i++) { if (planElements.get(i) instanceof Leg) { Leg Leg = (Leg) planElements.get(i); @@ -257,7 +272,7 @@ private Activity getActivityBeforeNextCarLeg(Id personId) { Person person = scenario.getPopulation().getPersons().get(personId); List planElements = person.getSelectedPlan().getPlanElements(); int indexOfNextCarLeg = -1; - for (int i = currentPlanElementIndex.get(personId) + 1; i < planElements.size(); i++) { + for ( int i = currentPlanElementIndices.get(personId ) + 1 ; i < planElements.size(); i++) { if (planElements.get(i) instanceof Leg) { Leg Leg = (Leg) planElements.get(i); @@ -281,7 +296,7 @@ private Activity getActivityBeforeNextCarLeg(Id personId) { private Activity getNextActivity(Id personId) { Person person = scenario.getPopulation().getPersons().get(personId); List planElements = person.getSelectedPlan().getPlanElements(); - for (int i = currentPlanElementIndex.get(personId); i < planElements.size(); i++) { + for ( int i = currentPlanElementIndices.get(personId ) ; i < planElements.size(); i++) { if (planElements.get(i) instanceof Activity) { return (Activity) planElements.get(i); } diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingInfrastructure.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingInfrastructure.java index d2b170ce801..c4ed7484a32 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingInfrastructure.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingInfrastructure.java @@ -17,18 +17,18 @@ public interface ParkingInfrastructure { void setPublicParkings(LinkedList publicParkings); - void setRentableParking(LinkedList rentableParkings); +// void setRentableParking(LinkedList rentableParkings); - void setPrivateParkingRestrictedToFacilities(LinkedList ppRestrictedToFacilities); +// void setPrivateParkingRestrictedToFacilities(LinkedList ppRestrictedToFacilities); - void reset(); + void notifyBeforeMobsim(); - PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, String groupName); +// PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, String groupName); - void logArrivalEventAtTimeZero(PC2Parking parking); +// void logArrivalEventAtTimeZero(PC2Parking parking); - PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, String groupName, Id personId, - double parkingDurationInSeconds, double arrivalTime); +// PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, String groupName, Id personId, +// double parkingDurationInSeconds, double arrivalTime); // TODO: make this method abstract // when person/vehicleId is clearly distinct, then I can change this to @@ -42,7 +42,7 @@ PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, St void unParkVehicle(PC2Parking parking, double departureTime, Id personId); - ParkingScore getParkingScoreManager(); +// ParkingScore getParkingScoreManager(); EventsManager getEventsManager(); @@ -52,4 +52,4 @@ PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, St void setAllParkings(HashMap, PC2Parking> allParkings); -} \ No newline at end of file +} diff --git a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingInfrastructureManager.java b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingInfrastructureManager.java index 72d6250a771..65c1cf8367f 100644 --- a/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingInfrastructureManager.java +++ b/contribs/parking/src/main/java/org/matsim/contrib/parking/parkingchoice/PC2/simulation/ParkingInfrastructureManager.java @@ -119,27 +119,27 @@ public static void addParkingToQuadTree(QuadTree quadTree, PC2Parkin quadTree.put(parking.getCoordinate().getX(), parking.getCoordinate().getY(), parking); } - @Override - public synchronized void setRentableParking(LinkedList rentableParkings) { - for (RentableParking pp : rentableParkings) { - rentablePrivateParking.put(pp.getOwnerId(), pp); - getAllParkings().put(pp.getId(), pp); - } - } - - @Override - public synchronized void setPrivateParkingRestrictedToFacilities( - LinkedList ppRestrictedToFacilities) { - for (PPRestrictedToFacilities pp : ppRestrictedToFacilities) { - for (Id facilityId : pp.getFacilityIds()) { - privateParkingsRestrictedToFacilities.put(facilityId, pp); - getAllParkings().put(pp.getId(), pp); - } - } - } +// @Override +// public synchronized void setRentableParking(LinkedList rentableParkings) { +// for (RentableParking pp : rentableParkings) { +// rentablePrivateParking.put(pp.getOwnerId(), pp); +// getAllParkings().put(pp.getId(), pp); +// } +// } +// +// @Override +// public synchronized void setPrivateParkingRestrictedToFacilities( +// LinkedList ppRestrictedToFacilities) { +// for (PPRestrictedToFacilities pp : ppRestrictedToFacilities) { +// for (Id facilityId : pp.getFacilityIds()) { +// privateParkingsRestrictedToFacilities.put(facilityId, pp); +// getAllParkings().put(pp.getId(), pp); +// } +// } +// } @Override - public synchronized void reset() { + public synchronized void notifyBeforeMobsim() { parkedVehicles.clear(); for (PC2Parking parking : getAllParkings().values()) { @@ -174,45 +174,45 @@ private synchronized QuadTree getPublicParkingQuadTree() { return publicParkingsQuadTree; } - @Override - public synchronized PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, - String groupName) { - PC2Parking parking = null; - if (groupName == null) { - parking = publicParkingsQuadTree.getClosest(destCoordinate.getX(), destCoordinate.getY()); - } else { - QuadTree quadTree = publicParkingGroupQuadTrees.get(groupName); - parking = quadTree.getClosest(destCoordinate.getX(), destCoordinate.getY()); - - if (parking == null) { - throw new Error("system is in inconsistent state: " + - "not enough parking available for parkingGroupName:" + groupName); - } - } - parkVehicle(parking); - - return parking; - } - - @Override - public synchronized void logArrivalEventAtTimeZero(PC2Parking parking) { - eventsManager.processEvent(new ParkingArrivalEvent(0, parking.getId(), null, null, 0)); - } - - @Override - public synchronized PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, String groupName, - Id personId, double parkingDurationInSeconds, double arrivalTime) { - PC2Parking parking = parkAtClosestPublicParkingNonPersonalVehicle(destCoordinate, groupName); - - double walkScore = parkingScoreManager.calcWalkScore(destCoordinate, parking, personId, - parkingDurationInSeconds); - parkingScoreManager.addScore(personId, walkScore); - - eventsManager.processEvent( - new ParkingArrivalEvent(arrivalTime, parking.getId(), personId, destCoordinate, walkScore)); - - return parking; - } +// @Override +// public synchronized PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, +// String groupName) { +// PC2Parking parking = null; +// if (groupName == null) { +// parking = publicParkingsQuadTree.getClosest(destCoordinate.getX(), destCoordinate.getY()); +// } else { +// QuadTree quadTree = publicParkingGroupQuadTrees.get(groupName); +// parking = quadTree.getClosest(destCoordinate.getX(), destCoordinate.getY()); +// +// if (parking == null) { +// throw new Error("system is in inconsistent state: " + +// "not enough parking available for parkingGroupName:" + groupName); +// } +// } +// parkVehicle(parking); +// +// return parking; +// } + +// @Override +// public synchronized void logArrivalEventAtTimeZero(PC2Parking parking) { +// eventsManager.processEvent(new ParkingArrivalEvent(0, parking.getId(), null, null, 0)); +// } +// +// @Override +// public synchronized PC2Parking parkAtClosestPublicParkingNonPersonalVehicle(Coord destCoordinate, String groupName, +// Id personId, double parkingDurationInSeconds, double arrivalTime) { +// PC2Parking parking = parkAtClosestPublicParkingNonPersonalVehicle(destCoordinate, groupName); +// +// double walkScore = parkingScoreManager.calcWalkScore(destCoordinate, parking, personId, +// parkingDurationInSeconds); +// parkingScoreManager.addScore(personId, walkScore); +// +// eventsManager.processEvent( +// new ParkingArrivalEvent(arrivalTime, parking.getId(), personId, destCoordinate, walkScore)); +// +// return parking; +// } // TODO: make this method abstract // when person/vehicleId is clearly distinct, then I can change this to @@ -227,8 +227,7 @@ public synchronized PC2Parking parkVehicle(ParkingOperationRequestAttributes par boolean parkingFound = false; // first search for parking at selected facility: - for (PPRestrictedToFacilities pp : privateParkingsRestrictedToFacilities - .get(parkingOperationRequestAttributes.facilityId)) { + for (PPRestrictedToFacilities pp : privateParkingsRestrictedToFacilities.get(parkingOperationRequestAttributes.facilityId)) { if (pp.getAvailableParkingCapacity() > 0) { // this tells the parking lot to decrease the number of @@ -248,7 +247,7 @@ public synchronized PC2Parking parkVehicle(ParkingOperationRequestAttributes par if (!parkingFound) { Collection collection = getFilteredCollection(parkingOperationRequestAttributes, distance); - while (collection.size() == 0) { + while ( collection.isEmpty() ) { distance *= 2; collection = getFilteredCollection(parkingOperationRequestAttributes, distance); @@ -278,8 +277,7 @@ public synchronized PC2Parking parkVehicle(ParkingOperationRequestAttributes par selectedParking = poll.getKey(); if (rentablePrivateParking.containsKey(parkingOperationRequestAttributes.personId)) { - RentableParking rentableParking = rentablePrivateParking - .get(parkingOperationRequestAttributes.personId); + RentableParking rentableParking = rentablePrivateParking.get(parkingOperationRequestAttributes.personId); if (rentableParking.getAvailableParkingCapacity() > 0) { @@ -508,16 +506,12 @@ public synchronized void unParkVehicle(PC2Parking parking, double departureTime, if (!(parking instanceof PrivateParking)) { addParkingToQuadTree(publicParkingsQuadTree, parking); addParkingToQuadTree(publicParkingGroupQuadTrees.get(parking.getGroupName()), parking); - // I could speculate that full parking lots are removed from the - // quad tree, and it is re-added as soon - // as space becomes available. But this is not commented, and it - // also does not look like it would work in that way. - // kai, jul'15 - // No, actually I now think that it works. When - // remainingCapacity==0, then the parking is removed from the - // list, and - // when (again) ==1, it is re-inserted. In addition, it is - // re-inserted in reset. + + // I could speculate that full parking lots are removed from the quad tree, and it is re-added as soon as space + // becomes available. But this is not commented, and it also does not look like it would work in that way. kai, jul'15 + + // No, actually I now think that it works. When remainingCapacity==0, then the parking is removed from the list, and + // when (again) ==1, it is re-inserted. In addition, it is re-inserted in reset. } } @@ -528,10 +522,10 @@ public synchronized void unParkVehicle(PC2Parking parking, double departureTime, eventsManager.processEvent(new ParkingDepartureEvent(departureTime, parking.getId(), personId)); } - @Override - public synchronized ParkingScore getParkingScoreManager() { - return parkingScoreManager; - } +// @Override +// public synchronized ParkingScore getParkingScoreManager() { +// return parkingScoreManager; +// } @Override public synchronized EventsManager getEventsManager() { diff --git a/contribs/protobuf/pom.xml b/contribs/protobuf/pom.xml index b93c87b1246..a2c8a4ef62b 100644 --- a/contribs/protobuf/pom.xml +++ b/contribs/protobuf/pom.xml @@ -11,7 +11,7 @@ protobuf - 4.27.1 + 4.27.2 diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/CalculateSkimMatrices.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/CalculateSkimMatrices.java index f65f15224ac..78875ce775c 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/CalculateSkimMatrices.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/CalculateSkimMatrices.java @@ -39,6 +39,9 @@ import java.util.function.BiPredicate; import java.util.function.Predicate; import java.util.function.ToDoubleFunction; + +import javax.annotation.Nullable; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.geotools.api.feature.simple.SimpleFeature; @@ -350,8 +353,8 @@ public final FloatMatrix calculateBeelineMatrix() { return BeelineDistanceMatrix.calculateBeelineDistanceMatrix(this.coordsPerZone.keySet(), coordsPerZone, numberOfThreads); } - public final void calculateAndWriteNetworkMatrices(String networkFilename, String eventsFilename, double[] times, Config config, String outputPrefix, Predicate xy2linksPredicate) - throws IOException { + public final void calculateAndWriteNetworkMatrices(String networkFilename, @Nullable String eventsFilename, + double[] times, Config config, String outputPrefix, Predicate xy2linksPredicate) throws IOException { String prefix = outputPrefix == null ? "" : outputPrefix; var netIndicators = prepareAndCalculateNetworkMatrices(networkFilename, eventsFilename, times, config, xy2linksPredicate); writeNetworkMatricesAsCSV(netIndicators, prefix); @@ -363,7 +366,8 @@ public final void writeNetworkMatricesAsCSV(NetworkIndicators netIndicat FloatMatrixIO.writeAsCSV(netIndicators.distanceMatrix, outputDirectory + "/" + prefix + CAR_DISTANCES_FILENAME); } - public final NetworkIndicators prepareAndCalculateNetworkMatrices(String networkFilename, String eventsFilename, double[] times, Config config, Predicate xy2linksPredicate) { + public final NetworkIndicators prepareAndCalculateNetworkMatrices(String networkFilename, + @Nullable String eventsFilename, double[] times, Config config, Predicate xy2linksPredicate) { Scenario scenario = ScenarioUtils.createScenario(config); log.info("loading network from " + networkFilename); new MatsimNetworkReader(scenario.getNetwork()).readFile(networkFilename); @@ -382,11 +386,16 @@ public final NetworkIndicators prepareAndCalculateNetworkMatrices(String log.info("No events specified. Travel Times will be calculated with free speed travel times."); } + return prepareAndCalculateNetworkMatrices(scenario.getNetwork(), tt, times, config, xy2linksPredicate); + } + + public final NetworkIndicators prepareAndCalculateNetworkMatrices(Network network, TravelTime tt, + double[] times, Config config, Predicate xy2linksPredicate) { TravelDisutility td = new OnlyTimeDependentTravelDisutility(tt); log.info("extracting car-only network"); final Network carNetwork = NetworkUtils.createNetwork(config); - new TransportModeNetworkFilter(scenario.getNetwork()).filter(carNetwork, Collections.singleton(TransportMode.car)); + new TransportModeNetworkFilter(network).filter(carNetwork, Collections.singleton(TransportMode.car)); log.info("filter car-only network for assigning links to locations"); final Network xy2linksNetwork = extractXy2LinksNetwork(carNetwork, xy2linksPredicate, config); diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/DefaultDashboardProvider.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/DefaultDashboardProvider.java index d7befe82fc0..9a6f00f9520 100644 --- a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/DefaultDashboardProvider.java +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/DefaultDashboardProvider.java @@ -19,10 +19,13 @@ public List getDashboards(Config config, SimWrapper simWrapper) { List result = new ArrayList<>(List.of( new OverviewDashboard(), new TripDashboard(), - new TrafficDashboard(), - new StuckAgentDashboard() + new TrafficDashboard() )); + if (config.transit().isUseTransit()) { + result.add(new PublicTransitDashboard()); + } + if (config.counts().getCountsFileName() != null) { result.add(new TrafficCountsDashboard()); } @@ -35,6 +38,8 @@ public List getDashboards(Config config, SimWrapper simWrapper) { result.add(new NoiseDashboard()); } + result.add(new StuckAgentDashboard()); + return result; } diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/EmissionsDashboard.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/EmissionsDashboard.java index b4c044fbe99..a7487fd625b 100644 --- a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/EmissionsDashboard.java +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/EmissionsDashboard.java @@ -20,7 +20,7 @@ public class EmissionsDashboard implements Dashboard { public void configure(Header header, Layout layout) { header.title = "Emissions"; - header.description = "Shows the emissions footprint and spatial distribution."; + header.description = "Shows the emissions footprint and spatial distribution. Shown values are already upscaled from simulated sample size."; layout.row("links") @@ -55,6 +55,7 @@ public void configure(Header header, Layout layout) { layout.row("second") .el(GridMap.class, (viz, data) -> { viz.title = "CO₂ Emissions"; + viz.unit = "CO₂ [g]"; viz.description = "per day"; viz.height = 12.; viz.cellSize = 100; @@ -70,6 +71,7 @@ public void configure(Header header, Layout layout) { layout.row("third") .el(GridMap.class, (viz, data) -> { viz.title = "CO₂ Emissions"; + viz.unit = "CO₂ [g]"; viz.description = "per hour"; viz.height = 12.; viz.cellSize = 100; diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/PublicTransitDashboard.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/PublicTransitDashboard.java new file mode 100644 index 00000000000..6903902d098 --- /dev/null +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/PublicTransitDashboard.java @@ -0,0 +1,28 @@ +package org.matsim.simwrapper.dashboard; + +import org.matsim.simwrapper.Dashboard; +import org.matsim.simwrapper.Header; +import org.matsim.simwrapper.Layout; +import org.matsim.simwrapper.viz.TransitViewer; + +/** + * Standard dashboard for public transit. + */ +public class PublicTransitDashboard implements Dashboard { + + @Override + public void configure(Header header, Layout layout) { + + header.title = "Public Transit"; + header.tab = "PT"; + header.triggerPattern = "*output_transitSchedule*xml*"; + + layout.row("viewer").el(TransitViewer.class, (viz, data) -> { + viz.title = "Transit Viewer"; + viz.height = 12d; + viz.description = "Visualize the transit schedule."; + viz.network = "*output_network.xml.gz"; + viz.transitSchedule = data.output("*output_transitSchedule.xml.gz"); + }); + } +} diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/TrafficCountsDashboard.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/TrafficCountsDashboard.java index 2bd83f1baba..8b65fba29ec 100644 --- a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/TrafficCountsDashboard.java +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/TrafficCountsDashboard.java @@ -69,7 +69,7 @@ public TrafficCountsDashboard withQualityLabels(List limits, List { + viz.backgroundColor = "transparent"; + viz.content = """ + ### Notes + - The speed performance index is the ratio of average travel speed and the maximum permissible road speed. + A performance index of 0.5, means that the average speed is half of the maximum permissible speed. A road with a performance index below 0.5 is considered to be in a congested state. + - The congestion index is the ratio of time a road is in an uncongested state. 0.5 means that a road is congested half of the time. A road with 1.0 is always uncongested. + + cf. *A Traffic Congestion Assessment Method for Urban Road Networks Based on Speed Performance Index* by Feifei He, Xuedong Yan*, Yang Liu, Lu Ma. + """; + }); + } } diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/TripDashboard.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/TripDashboard.java index 7ca920bfa12..7603da2b791 100644 --- a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/TripDashboard.java +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/dashboard/TripDashboard.java @@ -1,5 +1,6 @@ package org.matsim.simwrapper.dashboard; +import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.application.analysis.population.TripAnalysis; @@ -10,7 +11,9 @@ import org.matsim.simwrapper.Layout; import org.matsim.simwrapper.viz.*; import tech.tablesaw.plotly.components.Axis; +import tech.tablesaw.plotly.components.Line; import tech.tablesaw.plotly.traces.BarTrace; +import tech.tablesaw.plotly.traces.ScatterTrace; import javax.annotation.Nullable; import java.io.BufferedReader; @@ -39,6 +42,8 @@ public class TripDashboard implements Dashboard { private String groupedRefCsv; @Nullable private String[] categories; + @Nullable + private String distanceRefCsv; private String[] args; @@ -82,6 +87,14 @@ private static String[] detectCategories(String groupedRefCsv) { } } + /** + * This enables detailed analysis of the distance distribution. + */ + public TripDashboard withDistanceDistribution(String modeShareDistRefCsv) { + this.distanceRefCsv = modeShareDistRefCsv; + return this; + } + /** * Set grouped reference data. Will enable additional tab with analysis for subgroups of the population. * @@ -256,6 +269,7 @@ public void configure(Header header, Layout layout) { }); + createDistancePlot(layout, args, tab); layout.row("departures", tab).el(Plotly.class, (viz, data) -> { @@ -305,11 +319,63 @@ public void configure(Header header, Layout layout) { } + private void createDistancePlot(Layout layout, String[] args, String tab) { + + layout.row("dist-dist", tab).el(Plotly.class, (viz, data) -> { + + viz.title = "Detailed distance distribution"; + viz.description = "by mode."; + viz.layout = tech.tablesaw.plotly.components.Layout.builder() + .xAxis(Axis.builder().title("Distance [m]").build()) + .yAxis(Axis.builder().title("Share").build()) + .showLegend(false) + .build(); + + viz.colorRamp = ColorScheme.Viridis; + viz.interactive = Plotly.Interactive.dropdown; + + Plotly.DataSet ds = viz.addDataset(data.compute(TripAnalysis.class, "mode_share_distance_distribution.csv", args)) + .pivot(List.of("dist"), "main_mode", "share") + .constant("source", "Sim"); + + viz.addTrace(ScatterTrace.builder(Plotly.INPUT, Plotly.INPUT) + .mode(ScatterTrace.Mode.LINE) + .build(), + ds.mapping() + .name("main_mode") + .x("dist") + .y("share") + ); + + if (distanceRefCsv != null) { + viz.description += " Dashed line represents the reference data."; + + Plotly.DataSet ref = viz.addDataset(data.resource(distanceRefCsv)) + .pivot(List.of("dist"), "main_mode", "share") + .constant("source", "Ref"); + + viz.addTrace(ScatterTrace.builder(Plotly.INPUT, Plotly.INPUT) + .mode(ScatterTrace.Mode.LINE) + .line(Line.builder().dash(Line.Dash.DASH).color("black").build()) + .build(), + ref.mapping() + .name("main_mode") + .text("source") + .x("dist") + .y("share") + ); + } + + }); + + } + private void createChoiceTab(Layout layout, String[] args) { layout.row("choice-intro", "Mode Choice").el(TextBlock.class, (viz, data) -> { - viz.title = "Information"; + viz.backgroundColor = "transparent"; viz.content = """ + ### **Information** Note that these metrics are based on a single run and may have limited interpretability. For a more robust evaluation, consider running multiple simulations with different seeds and use metrics that consider probabilities as well. (log-likelihood, Brier score, etc.) For policy cases, these metrics do not have any meaning. They are solely for the base-case. @@ -371,7 +437,14 @@ private void createGroupedTab(Layout layout, String[] args) { for (String cat : Objects.requireNonNull(categories, "Categories not set")) { - layout.row("category_" + cat, "By Groups") + layout.row("category_header_" + cat, "By Groups") + + .el(TextBlock.class, (viz, data) -> { + viz.content = "## **" + StringUtils.capitalize(cat) + "**"; + viz.backgroundColor = "transparent"; + }); + + layout.row("category_1_" + cat, "By Groups") .el(Plotly.class, (viz, data) -> { viz.title = "Mode share"; @@ -399,8 +472,7 @@ private void createGroupedTab(Layout layout, String[] args) { }); - /* - TODO: This part needs some more work in simwrapper and is not yet ready + layout.row("category_2_" + cat, "By Groups") .el(Plotly.class, (viz, data) -> { viz.title = "Modal distance distribution"; @@ -413,8 +485,6 @@ private void createGroupedTab(Layout layout, String[] args) { viz.interactive = Plotly.Interactive.dropdown; - // TODO: modes are not separated into different traces - // probably dropdown config in plotly needs to be extended Plotly.DataMapping ds = viz.addDataset(data.computeWithPlaceholder(TripAnalysis.class, "mode_share_per_%s.csv", cat)) .pivot(List.of("main_mode", "dist_group", cat), "source", "share") .normalize(List.of("dist_group", "source", cat), "share") @@ -433,7 +503,6 @@ private void createGroupedTab(Layout layout, String[] args) { .build(), ds); }); - */ } } diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/GridMap.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/GridMap.java index 08e19a3bd37..190c6f3a083 100644 --- a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/GridMap.java +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/GridMap.java @@ -9,6 +9,12 @@ */ public class GridMap extends Viz { + /** + * The unit of the values. + */ + @JsonProperty(required = false) + public String unit; + /** * The center of the map. */ diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/TransitViewer.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/TransitViewer.java new file mode 100644 index 00000000000..ff9e8176b60 --- /dev/null +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/TransitViewer.java @@ -0,0 +1,19 @@ +package org.matsim.simwrapper.viz; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Transit viewer for pt schedules. + */ +public class TransitViewer extends Viz { + + @JsonProperty(required = true) + public String network; + + @JsonProperty(required = true) + public String transitSchedule; + + public TransitViewer() { + super("transit"); + } +} diff --git a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/Viz.java b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/Viz.java index c943984bf24..04a4a4ecc3e 100644 --- a/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/Viz.java +++ b/contribs/simwrapper/src/main/java/org/matsim/simwrapper/viz/Viz.java @@ -17,6 +17,7 @@ public abstract class Viz { public String description; public Double height; public Double width; + public String backgroundColor; protected Viz(String type) { this.type = type; 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 0f5b273b809..2a248f2e1ea 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 @@ -79,6 +79,7 @@ void tripRef() { TripDashboard dashboard = new TripDashboard("mode_share_ref.csv", "mode_share_per_dist_ref.csv", "mode_users_ref.csv") .withGroupedRefData("mode_share_per_group_dist_ref.csv") + .withDistanceDistribution("mode_share_distance_distribution.csv") .withChoiceEvaluation(true); run(dashboard); diff --git a/contribs/simwrapper/src/test/resources/mode_share_distance_distribution.csv b/contribs/simwrapper/src/test/resources/mode_share_distance_distribution.csv new file mode 100644 index 00000000000..fd654629c14 --- /dev/null +++ b/contribs/simwrapper/src/test/resources/mode_share_distance_distribution.csv @@ -0,0 +1,300 @@ +dist,car,bike,pt,ride,walk +0,0.003944185709709211,0.03574277628200462,0.0,0.00037518566775610664,0.9599378523405301 +100,0.011701245224666933,0.06340817090597038,0.0001121407069974153,0.0042250894716089485,0.9205533536907563 +200,0.019169744514796645,0.0893122044564802,0.0029477228742061396,0.007943944214489625,0.8806263839400273 +300,0.026454120383840485,0.11387016806273764,0.005852946985418339,0.01157440300941457,0.8422483615585888 +400,0.03358969683040535,0.13726864579468073,0.00883146182418116,0.01512659005423139,0.8051836054965014 +500,0.04061323303247179,0.1597872858612186,0.011867749118957528,0.018614271787587497,0.7691174601997646 +600,0.04784678709775937,0.18276920810315928,0.015044169123967811,0.022210598702522306,0.7321292369725912 +700,0.05734213014395564,0.2063976466031354,0.020761095019876587,0.027226351467094633,0.6882727767659378 +800,0.06816214612398162,0.23075623072886828,0.02809996433770487,0.03334978383688804,0.6396318749725572 +900,0.08024003137598233,0.2537713669048177,0.03722715420046467,0.04053105229077874,0.5882303952279565 +1000,0.09364179803228202,0.27369856857082314,0.04819638462547296,0.04853551992162743,0.5359277288497946 +1100,0.10815209473295054,0.2896612754900817,0.061088691181933455,0.05700637493902756,0.48409156365600664 +1200,0.1232212719481538,0.3019622446542897,0.07559986698022046,0.06546549661451352,0.4337511198028226 +1300,0.13836634275344512,0.3108373606129935,0.09091282143275427,0.07344298190904162,0.3864404932917656 +1400,0.15305940553232467,0.3166167362865903,0.106622022782901,0.08054229035462031,0.34315954504356383 +1500,0.16718472705231266,0.3196662233207097,0.12243086717410893,0.0866287797100008,0.30408940274286794 +1600,0.18074160725323074,0.31998662551253926,0.13803737572256664,0.09151578936071274,0.26971860215095056 +1700,0.1935482723020434,0.31817337820339026,0.15321472621092924,0.09518315363206561,0.23988046965157156 +1800,0.20532034709529492,0.31611869272157034,0.1679915712780288,0.09760140565798013,0.21296798324712582 +1900,0.21580176882702776,0.3146373506893864,0.18231537962307767,0.09915606961335534,0.18808943124715283 +2000,0.22468765695699847,0.3135340991553317,0.19583828064196956,0.10039147352520297,0.1655484897204973 +2100,0.2320390038133107,0.3116926400097604,0.20855096231240602,0.10166512340515747,0.14605227045936547 +2200,0.2380819792506679,0.30869778321984614,0.22053019447943822,0.10310428120772884,0.12958576184231907 +2300,0.24319551277452806,0.30508552753141654,0.2313966740266772,0.1046602681206329,0.11566201754674531 +2400,0.24740978487991802,0.3017946569397511,0.24027214876964206,0.10619319093791682,0.10433021847277195 +2500,0.25147380264601127,0.29858419290780464,0.24745094294156134,0.10784057535174722,0.09465048615287541 +2600,0.2557081800597713,0.2944242245483245,0.254338405626125,0.10983364707192515,0.08569554269385418 +2700,0.26005333523487556,0.28838565315986364,0.26158066268749924,0.11234778706359465,0.07763256185416688 +2800,0.26438416817880983,0.280611150092087,0.26888318706237135,0.11521145502857368,0.07091003963815808 +2900,0.2682783800528302,0.2726124724825396,0.2756396595690925,0.11833178417595261,0.06513770371958504 +3000,0.27132169151827706,0.26621281194912927,0.281363176346151,0.12160735741899721,0.05949496276744551 +3100,0.2737623173544646,0.2613722495444328,0.28602764052844565,0.12465212676448884,0.054185665808168096 +3200,0.2752050644701451,0.25765183237406514,0.29053676388248717,0.12692664007901375,0.0496796991942889 +3300,0.2755335668276074,0.25414256527537704,0.2961907003290296,0.12822749403075626,0.045905673537229595 +3400,0.27546962770627187,0.24959144103020722,0.3038254719339772,0.128650706320345,0.04246275300919872 +3500,0.275852888106488,0.24461016400363972,0.31218634809445833,0.12807332486763146,0.03927727492778241 +3600,0.2767344858836351,0.24055620257468846,0.319580451397353,0.12682070092540043,0.03630815921892315 +3700,0.27805269721474923,0.23775684456973434,0.32586250733517447,0.12497622419270152,0.033351726687640526 +3800,0.27990378773934443,0.23490832801299452,0.331806257334882,0.12301388863447164,0.03036773827830728 +3900,0.2824088112165455,0.2310003638838484,0.33771130717376985,0.12131495561119951,0.027564562114636655 +4000,0.2852664175352708,0.22624522603645245,0.3435830853261446,0.11963105302180563,0.025274218080326673 +4100,0.28757227850383676,0.22219425556166225,0.34895088956114434,0.11810340256156933,0.023179173811787322 +4200,0.2892860820110079,0.21950746602333254,0.35266462797361464,0.11730689319530663,0.021234930796738084 +4300,0.2905846066726926,0.21817348003240541,0.3544434350048095,0.11696017192331501,0.01983830636677753 +4400,0.29079767729915024,0.21832389444644654,0.3552632635110481,0.11671696692773488,0.01889819781562023 +4500,0.29054464552643655,0.2187565545308431,0.35621331692068825,0.11644817822293935,0.01803730479909268 +4600,0.29071376079094585,0.21815056970721644,0.35814530168997827,0.11602278248671279,0.016967585325146833 +4700,0.29149314706948726,0.21628524084231726,0.3611948723023975,0.11521754980569271,0.01580918998010539 +4800,0.2927416557039059,0.21329664797980755,0.36484248837838756,0.11448678443678055,0.014632423501118458 +4900,0.2939283284766885,0.2093825114338426,0.36909058733655126,0.11419257101424245,0.01340600173867514 +5000,0.2943703318843527,0.20503505319621854,0.3740579024965238,0.11425386578069209,0.012282846642212707 +5100,0.2947281320102329,0.20064785365238091,0.37920970585179475,0.11399087352866029,0.011423434956931168 +5200,0.2952005810632277,0.1966183253462185,0.3842091954611987,0.11297690633918127,0.010994991790173709 +5300,0.2954694412637997,0.19305650254355664,0.38862751336965484,0.11200435977565158,0.01084218304733732 +5400,0.2956013995192241,0.19003237035082865,0.39145872828055284,0.11198568246374727,0.010921819385647139 +5500,0.295920289526642,0.18765361137233574,0.3928612135544049,0.11245785812593388,0.01110702742068355 +5600,0.29620274791867335,0.18602174454261,0.3939712285519109,0.11278590827065553,0.011018370716150317 +5700,0.29700022366082723,0.18460542080407022,0.3953244047532656,0.1124379144039675,0.010632036377869396 +5800,0.2991712652148869,0.18316762386679863,0.3956759916902435,0.11177576119688537,0.010209358031185575 +5900,0.30281068623960566,0.18107647112858022,0.3948546754217751,0.1112549206294131,0.010003246580626022 +6000,0.30760418385322613,0.17801668245256075,0.39340985019348257,0.11105953395226086,0.009909749548469605 +6100,0.3120780594034644,0.17430955427982733,0.39273877608556473,0.1112310729291791,0.009642537301964448 +6200,0.3149138339517079,0.17060832803704515,0.39421250391680623,0.11101290406126946,0.009252430033171307 +6300,0.3163211386544086,0.16688128870624544,0.39833815779540177,0.10963883358605299,0.008820581257890986 +6400,0.3168885716270779,0.1631029587545106,0.4039846665931847,0.10748564138323057,0.008538161641996302 +6500,0.3163853132336465,0.1601672329456284,0.40972902212947393,0.10514820322266033,0.008570228468590872 +6600,0.3146552775257205,0.15894417720988466,0.4148907108245583,0.1029047418962418,0.008605092543594872 +6700,0.31178450759837123,0.1589825476919096,0.42054070390500253,0.10040983964878102,0.008282401155935619 +6800,0.30765869257616435,0.15897938297567632,0.42790233035724856,0.09788817923493068,0.007571414855980117 +6900,0.3031234488944087,0.15835248013794465,0.43562916456461576,0.09608202872773462,0.006812877675296376 +7000,0.30059353222822577,0.15649830655749544,0.4406048531416794,0.09599479772562099,0.00630851034697845 +7100,0.30147734178805335,0.15348495830904818,0.44207247110851283,0.09697598730724549,0.005989241487140272 +7200,0.30477037670371454,0.15043709304413938,0.44132338730885484,0.09798080768138748,0.005488335261903595 +7300,0.30931379002328574,0.14744495887545409,0.4391650248839597,0.09926294271788191,0.004813283499418607 +7400,0.3145250031363783,0.1441665231160985,0.4361382426512812,0.10084213626174753,0.00432809483449452 +7500,0.3199953787910249,0.1399930976671494,0.4335633611166701,0.1022618051664066,0.004186357258748942 +7600,0.3255444419424304,0.13491940666015817,0.4318459378422744,0.10330157780809669,0.004388635747040414 +7700,0.33066978269969555,0.1303864944222729,0.4305132883122282,0.10356744233071624,0.004862992235087065 +7800,0.3346043891458717,0.1269827960715251,0.4302755165111089,0.10296319610511989,0.005174102166374413 +7900,0.3360715638175254,0.12519883396270184,0.43200679058006564,0.10144914081550105,0.005273670824206123 +8000,0.334640790446691,0.12477426399902476,0.43573008222127113,0.09924847720302252,0.005606386129990566 +8100,0.33213142714296695,0.12443653103813718,0.4395962197986949,0.0976268418752624,0.0062089801449385406 +8200,0.33107092875929944,0.12301440992229622,0.4416068653574643,0.09738599288239812,0.006921803078541837 +8300,0.3322562552375935,0.12071335448683616,0.44175999507415387,0.09785345887779752,0.007416936323619015 +8400,0.3343026623829796,0.11857176277621778,0.44152588643373936,0.09815898784420019,0.007440700562863161 +8500,0.33674968239776865,0.11653183762443622,0.4408253211737455,0.09863097778223112,0.007262181021818691 +8600,0.33912167321391457,0.11504978101230556,0.4399428826279596,0.098746063513719,0.007139599632101268 +8700,0.34161552574285703,0.11377864300132756,0.43921050150302954,0.09829491376650987,0.007100415986275998 +8800,0.34345221253717667,0.11244637975200669,0.43954782701958567,0.09736731572590539,0.007186264965325571 +8900,0.34396420494945923,0.11150514754309751,0.4412610391057008,0.09613948545629122,0.007130122945451008 +9000,0.3427447518662358,0.11145571035801106,0.44449734501386234,0.09452926480212648,0.00677292795976445 +9100,0.33889285241848643,0.11253183053236336,0.45031265872217896,0.09196385741190528,0.006298800915065851 +9200,0.3336669482783479,0.1134892023479546,0.45865681683120374,0.08819420623329507,0.005992826309198492 +9300,0.3289025705331273,0.11348663993291781,0.46731014926673503,0.08447376399968726,0.005826876267532717 +9400,0.32493268245886175,0.11252817183693045,0.4750992797553844,0.08170200775760447,0.0057378581912189775 +9500,0.32214693234402464,0.1106579594925726,0.48173691905293803,0.07995360401807224,0.005504585092392341 +9600,0.3212856976546727,0.10798132357698269,0.4866778855681674,0.07888060651350967,0.005174486686667575 +9700,0.3231233065511186,0.10451121792877666,0.4882523772684013,0.0790186948898093,0.005094403361894107 +9800,0.326591288702599,0.10233748770925298,0.4867177339140384,0.07934799272908354,0.005005496945026043 +9900,0.33033199309304595,0.10223317100731696,0.48295479127151086,0.07964759443149812,0.004832450196628059 +10000,0.332623476986607,0.10392322548495701,0.47831054579067794,0.08034515909139255,0.004797592646365311 +10100,0.33349673860375345,0.1064764414583982,0.4736181791737175,0.08136887706342233,0.0050397637007084245 +10200,0.33432874916821775,0.10839986317417392,0.46940861773685993,0.08239100408191506,0.0054717658388332285 +10300,0.33663453365083645,0.10770460087860513,0.46633675581615114,0.08337864074198886,0.0059454689124185025 +10400,0.3404049839843345,0.10441995340275494,0.46428750916833894,0.08460044534143857,0.0062871081031330295 +10500,0.34365790107945965,0.09964272875511318,0.46364958750285873,0.08671726100033575,0.006332521662232755 +10600,0.34552044112406316,0.09458183118584063,0.4651552779891012,0.0887975232378272,0.005944926463167861 +10700,0.3466808424969561,0.08992592353099621,0.46809316115262406,0.09004150177341785,0.005258571046005839 +10800,0.3476540383110092,0.08531568124768088,0.4715528688669912,0.09077744628192347,0.004699965292395249 +10900,0.3487618868010548,0.08021569909171704,0.47450283652222763,0.09179030665719705,0.0047292709278034875 +11000,0.34981810379387535,0.0756182560815686,0.4766986605697859,0.09269930852597585,0.005165671028794336 +11100,0.35069008988381656,0.07199811807143205,0.4781583176488935,0.09344522991095218,0.005708244484905714 +11200,0.3512373404433965,0.07004144053928892,0.47918590883550166,0.09311988712594702,0.0064154230558660305 +11300,0.3510728703568192,0.06988528846316891,0.4814511810046708,0.09042664919057947,0.007164010984761484 +11400,0.3501659797384926,0.07119782536102774,0.4849013222420671,0.08594282610847258,0.0077920465499397755 +11500,0.3502266428625708,0.07244678514010582,0.48726891172242254,0.08172118958629243,0.008336470688608292 +11600,0.3515476656858425,0.07332265456510285,0.48723536488396574,0.07919064759050176,0.0087036672745871 +11700,0.35280716517037564,0.07392414008446771,0.48688809612729905,0.07788442160756133,0.008496177010296136 +11800,0.3535518317940175,0.07488697212045167,0.4877126534366569,0.07622975764465151,0.007618785004222498 +11900,0.3532559622571539,0.07630204763313102,0.48968744124971497,0.07443407018363783,0.006320478676362388 +12000,0.3515930492142177,0.07766164992831871,0.4925650844213227,0.07325799694409808,0.004922219492042807 +12100,0.3486746530901627,0.0786184358762612,0.49575026770104924,0.07322696307157492,0.0037296802609520364 +12200,0.3459631830156185,0.07910539121020793,0.49734216915848095,0.07471306045813585,0.0028761961575567967 +12300,0.34515164645623286,0.07852330317132618,0.497099722911959,0.07690528383052488,0.002320043629957131 +12400,0.3459692806589574,0.07614271216448953,0.49751775821913646,0.07829200754828933,0.0020782414091272796 +12500,0.3473294269536054,0.07284667617898927,0.49909875988414526,0.078785545697462,0.0019395912857979472 +12600,0.3492697734782812,0.07055652236622659,0.4993771084837752,0.07887081410385641,0.0019257815678606154 +12700,0.35165913759661094,0.06930984359987807,0.49734401770347036,0.0793690132210364,0.0023179878790042198 +12800,0.3534330142705426,0.0685168380910896,0.4942301979699518,0.08060951994893653,0.0032104297194793657 +12900,0.35421885101175854,0.06776758717632732,0.49180707969249465,0.0819005661128331,0.004305916006586208 +13000,0.3540822179979868,0.0661512996857427,0.4919734187183986,0.08253613716916212,0.005256926428709651 +13100,0.35342829486563304,0.06405367530755271,0.49394237720987055,0.08266669727070296,0.005908955346240877 +13200,0.3527830056486237,0.062079886000871755,0.49724567618502824,0.08170438670049396,0.006187045464982326 +13300,0.35118847649542645,0.060669747155702516,0.5014068771485422,0.08043809680516903,0.006296802395159802 +13400,0.3496204769128433,0.05942459609269626,0.5049403839900514,0.07963710509984248,0.006377437904566406 +13500,0.3495314643746348,0.057607537059823515,0.5070270014551675,0.07942874580916505,0.006405251301209198 +13600,0.3512771833636974,0.05467792754601138,0.5088506982237178,0.0792095850794595,0.005984605787114015 +13700,0.3536751452904462,0.05190061697309672,0.5107738723328092,0.0786834845029321,0.004966880900715792 +13800,0.354742578974646,0.05086258511488499,0.5128743614793818,0.07780940769315979,0.00371106673792734 +13900,0.35337846055225414,0.05129948384736346,0.5141394594794085,0.07826314837774705,0.0029194477432267353 +14000,0.3502608353310682,0.05176879006408448,0.5146490409198109,0.08031357999632413,0.0030077536887120047 +14100,0.3479646876052328,0.052001256018598334,0.5126737098783506,0.08369621619637188,0.0036641303014464765 +14200,0.3467724704687371,0.05234536611327431,0.5094025274461869,0.08721332470421704,0.004266311267584765 +14300,0.3458939420186927,0.05283868653849691,0.5069653056867282,0.08982480736812844,0.004477258387953727 +14400,0.34419383949094845,0.05317154579641435,0.5077953632376326,0.09054675442316235,0.0042924970518421 +14500,0.34206579427473216,0.0533915811873866,0.5105773837658292,0.0900344684454732,0.003930772326578891 +14600,0.34096457737932545,0.0531642950978982,0.5137539489580658,0.08847091840444228,0.003646260160268298 +14700,0.34185829504357707,0.05206629441210561,0.5153786536953597,0.08705653960769522,0.0036402172412623502 +14800,0.3451136746853569,0.051363986408669876,0.5139185494433137,0.08605099480616986,0.0035527946564896744 +14900,0.34876836765395003,0.05134269666917897,0.5119371007087012,0.0848413259434568,0.003110509024712872 +15000,0.34987479519923204,0.051848430797233586,0.5123654205637322,0.08354519285053809,0.0023661605892641006 +15100,0.35073491475575935,0.05160374430672114,0.5132647067219768,0.08266891528617965,0.0017277189293630518 +15200,0.3533769908219431,0.04982294800478374,0.51286121936596,0.0824108546089649,0.0015279871983482267 +15300,0.35829879100781925,0.047619887984084106,0.5081203160440892,0.0843046766430162,0.0016563283209913118 +15400,0.36438903901491226,0.046767064832046214,0.4994026972613257,0.08769563691522099,0.0017455619764948213 +15500,0.3703076027775079,0.04560064577822244,0.4919479639255102,0.09047439801465251,0.0016693895041069008 +15600,0.37644880054132307,0.043149337858934884,0.48747282882555154,0.0914725597900988,0.0014564729840916718 +15700,0.3832533527154736,0.03987087187931813,0.4846315317068988,0.09105568446572862,0.001188559232580744 +15800,0.38911481145173965,0.036635718038923376,0.483185340127183,0.09012260707422778,0.0009415233079263451 +15900,0.39333782273404705,0.034346239793475515,0.48148048326239373,0.09007831588833208,0.0007571383217516961 +16000,0.39671288097581386,0.03387630220257963,0.47827303537421684,0.09060979644498543,0.0005279850024043422 +16100,0.3998092415304151,0.03369447134976605,0.4757602526959003,0.09048109019026992,0.00025494423364862264 +16200,0.40144457611037515,0.03301595193542206,0.47597561517437054,0.08951300056839265,5.085621143955609e-05 +16300,0.40307373382750894,0.0317049768812926,0.47757465657186055,0.087646632719338,0.0 +16400,0.40567004311313576,0.030514899198242473,0.4782678421523515,0.08554721553627018,0.0 +16500,0.40777822694196014,0.030177353127346283,0.47763707434011793,0.08440734559057571,0.0 +16600,0.4081581418343006,0.030722333058722327,0.47742204736276,0.0836974777442171,0.0 +16700,0.4072558170344897,0.03105266190784093,0.47890330589226493,0.08273236764788475,5.584751751956769e-05 +16800,0.4077100348839108,0.030938097193742294,0.479310621620526,0.08175182762701788,0.00028941867480312245 +16900,0.4090694716869422,0.03141730714937055,0.4779228616654376,0.08096905727333781,0.00062130222491177 +17000,0.4096325774592674,0.03317240921254907,0.4765725189111758,0.0796999429999717,0.0009225514170361303 +17100,0.409318950129627,0.036416273191669915,0.4759463860501217,0.0772010848219748,0.0011173058066065345 +17200,0.4091322273159482,0.03971971816744722,0.4761228299047345,0.07382438051613933,0.0012008440957308444 +17300,0.40917878287625953,0.041376286772682035,0.47732946132916715,0.07089644446189847,0.0012190245599926076 +17400,0.40796678344949716,0.04134184760987771,0.4808650383610144,0.06860969238333003,0.0012166381962804955 +17500,0.4069055769398501,0.040259317584171485,0.48534215525436136,0.0663396391468098,0.0011533110748072363 +17600,0.4073714217435671,0.03867637636174271,0.48873322626000065,0.06424237237588457,0.0009766032588049169 +17700,0.4082070183450192,0.03681720852155175,0.4917890615422369,0.06251096202188594,0.0006757495693060654 +17800,0.40851930992274343,0.03405948660427341,0.4956107932771341,0.06148761266152315,0.00032279753432586496 +17900,0.40834638056816525,0.030057523585525523,0.4992926369932518,0.062175477327735026,0.00012798152532237834 +18000,0.40869966431198385,0.025485516620014383,0.5007566895943754,0.06473163216966882,0.00032649730395761193 +18100,0.4103114989276243,0.02206435248347342,0.4990825597685239,0.0678483880870413,0.0006932007333369842 +18200,0.4125275955278045,0.020471448306712096,0.4962059690581323,0.06977318455160707,0.0010218025557439737 +18300,0.41556837263605517,0.0206159334052642,0.49291632607629127,0.06966729786541252,0.0012320700169767373 +18400,0.41922344744217654,0.021424654150831928,0.4895518490887264,0.06847296087200397,0.001327088446261135 +18500,0.42232284778449486,0.0217839827158899,0.4867244275846881,0.06780939466890122,0.0013593472460257043 +18600,0.4233615462574494,0.022240682195265638,0.4854909346659724,0.06753024566346263,0.0013765912178499511 +18700,0.42221463009837973,0.023175998277689874,0.4862114474386642,0.06706868155366034,0.0013292426316058692 +18800,0.41938452682387994,0.024671257246244315,0.48845387119608186,0.06634303755896588,0.0011473071748282068 +18900,0.4162698274751706,0.02606826102222086,0.4918802760301444,0.0649713055171278,0.0008103299553361399 +19000,0.41370970500856974,0.02619427177378781,0.49541371836161135,0.06428721934177216,0.00039508551425894553 +19100,0.4111836219465369,0.024935190838525294,0.49810665113387514,0.06569494066032154,7.959542074096334e-05 +19200,0.40900764184359,0.023272440638810805,0.500030017898224,0.06768989961937528,0.0 +19300,0.4077586478909343,0.021863494759432046,0.5012108598178834,0.06916699753175017,0.0 +19400,0.408311133192338,0.02043513389032554,0.5000603914760281,0.07094521295009655,0.0002481284912116819 +19500,0.410657267981849,0.018745544224635223,0.4962127982796929,0.07311330075798793,0.001271088755835052 +19600,0.4129873601348296,0.017541385732083054,0.491204116898825,0.0755496223485488,0.0027175148857134764 +19700,0.4155038566448603,0.01783483589445665,0.48429098444630636,0.0783316029268498,0.004038720087526871 +19800,0.4194232425491414,0.019943310031264753,0.4745851157306195,0.0811460202126344,0.00490231147634016 +19900,0.4237634410357246,0.02274289988633667,0.46453684930906475,0.08366798824179451,0.005288821527079398 +20000,0.42924811067875895,0.025272981164161663,0.45383841362633387,0.08624649868021858,0.005393995850526764 +20100,0.435043355622225,0.02711028131661334,0.44499696189855414,0.08742500693034187,0.005424394232265606 +20200,0.4381158298860281,0.028752098345993304,0.4412202762654395,0.08670593887789967,0.0052058566246392666 +20300,0.43629361335970757,0.030858715295792465,0.44443228092985504,0.08395950185201377,0.004455888562631062 +20400,0.4301135651058379,0.03229097649863405,0.45497696288948875,0.07952490603192432,0.0030935894741149603 +20500,0.4229102459145983,0.03199253408632643,0.4681190576986417,0.07549949461909383,0.001478667681339733 +20600,0.4158022740307024,0.029769281238211487,0.48033066235687283,0.07370570116985865,0.0003920812043545203 +20700,0.4070478601985252,0.027064485172408996,0.49220904618105293,0.073174473103939,0.0005041353440738187 +20800,0.39614273429614333,0.025981097158521337,0.5027713369503549,0.07402198766670785,0.001082843928272513 +20900,0.3872177116718546,0.026557635242180744,0.5087847224084467,0.0758282435040628,0.0016116871734550978 +21000,0.38398482616329394,0.027228215559169877,0.5085444034607474,0.07829032074796632,0.00195223406882252 +21100,0.3875603035923633,0.02685374484593285,0.5021392195650695,0.08134417588854626,0.0021025561080882244 +21200,0.3978927373794572,0.02541002434753572,0.4902379575422398,0.08432013650391704,0.002139144226850326 +21300,0.41151318116860797,0.02372890718179091,0.4770756142023481,0.08543752773436995,0.0022447697128831837 +21400,0.42436562739417444,0.0227365967225967,0.4653685865307477,0.08493939959299171,0.0025897897594894764 +21500,0.4358877624320956,0.02220953030988447,0.45558016303078025,0.08340550425415166,0.002917039973088014 +21600,0.44642680413653185,0.021174874782133524,0.4482061421154049,0.08122859103575707,0.0029635879301725993 +21700,0.45775849923504686,0.019856265060823254,0.44139246353032185,0.07826547741833999,0.0027272947554679993 +21800,0.4658513182991035,0.019149391365781768,0.4374855081463585,0.07505499949051757,0.002458782698238717 +21900,0.46881670530836345,0.019440780279391227,0.4373238344796474,0.07198624195049307,0.0024324379821049984 +22000,0.4681729774766497,0.02094882734441416,0.4379040741275592,0.07048253252957828,0.0024915885217985647 +22100,0.4653750905928244,0.023669971931632054,0.4376461934110921,0.07089950364094785,0.002409240423503521 +22200,0.46265914347386955,0.026838523765721486,0.43511445967853835,0.07332780925396575,0.0020600638279048757 +22300,0.4618967857243901,0.029186048225720025,0.43049337975308427,0.07698764200459184,0.001436144292213776 +22400,0.45995327004306485,0.030540930532941254,0.4275623253211247,0.08125460241384186,0.0006888716890271567 +22500,0.45575973471448344,0.031464642145538894,0.4286101753494344,0.08402988505949326,0.00013556273105010428 +22600,0.4520944155950475,0.03200617677241399,0.4305683798237246,0.08533102780881391,0.0 +22700,0.4518830954733447,0.03168387156406179,0.4312106796254198,0.0852223533371737,0.0 +22800,0.45458546969373964,0.030382457343753496,0.43228790023171615,0.08274417273079053,0.0 +22900,0.46001913818967993,0.02936451405390396,0.4330924556750935,0.07752389208132256,0.0 +23000,0.46778067441738336,0.028956505216714695,0.4309893167285267,0.07227350363737518,0.0 +23100,0.47627422783211293,0.028237285206726033,0.4271334384627051,0.06820951467957559,0.00014553381888040876 +23200,0.48290756775606597,0.02775470136824582,0.4231227486653074,0.06545419917490443,0.0007607830354762156 +23300,0.4858705505533305,0.0279681679700472,0.4202439721647368,0.06427099024193132,0.0016463190699540669 +23400,0.48584305871213085,0.02736877345662722,0.4190982807641512,0.06522977243789538,0.0024601146291954703 +23500,0.4864184247251404,0.02574038245309708,0.4167272558732944,0.0681033683903014,0.0030105685581667432 +23600,0.4905049504365615,0.024752648848085798,0.40830015068507347,0.07316042974375656,0.0032818202865225665 +23700,0.49652123563701683,0.024465530904079637,0.39672567713807644,0.0789294495175657,0.0033581068032613455 +23800,0.5011079550606421,0.022760950317863304,0.3883145259103277,0.08446151073270322,0.0033550579784637157 +23900,0.5019675996278283,0.019104984769266125,0.3877078559911522,0.08802584180783582,0.0031937178039173823 +24000,0.49892111687839974,0.014672586175812668,0.395172204172851,0.08851029255439923,0.002723800218537321 +24100,0.4970959884538086,0.011589232340675552,0.4039045212229103,0.08550835133123207,0.001901906651373451 +24200,0.5008157494993369,0.010812911777747219,0.4068400063549502,0.08060889903084516,0.0009224333371204349 +24300,0.5055672381199657,0.011139838890019089,0.40845148254600955,0.07465550386400038,0.00018593658000528064 +24400,0.5058483546632243,0.011631946219614176,0.4133992078890603,0.0691204912281013,0.0 +24500,0.500471052955471,0.011010559715707507,0.4218404344311667,0.06667795289765487,0.0 +24600,0.49201847943224153,0.009367474600624778,0.4297153384224725,0.06889870754466125,0.0 +24700,0.4840179911951928,0.008072269168697499,0.4352122514459639,0.07269748819014586,0.0 +24800,0.4777419954944325,0.008583703565690076,0.439012971058813,0.07466132988106439,0.0 +24900,0.4743511229403143,0.00993515341935268,0.4400404773560362,0.07567324628429696,0.0 +25000,0.4734263239294324,0.011154329451766821,0.4372720195216476,0.07814732709715325,0.0 +25100,0.47214954717521307,0.012671469202629534,0.4328887995120403,0.08229018411011717,0.0 +25200,0.4690412224027795,0.01458640258016774,0.4293233325637628,0.08685261919026369,0.00019642326302624378 +25300,0.46541516194794424,0.01676258867265909,0.4270562982545973,0.0897400434602404,0.0010259076645590048 +25400,0.46371117679792273,0.019231579596808768,0.4245349273933989,0.090290016396749,0.002232299815120635 +25500,0.46548730579355985,0.02080148751916184,0.42241703205340264,0.0879314977338606,0.0033626769000151876 +25600,0.4702117449491536,0.020905075354453503,0.4202569994500889,0.08426106329527593,0.004365116951028285 +25700,0.47452820586510747,0.019811697793625436,0.41893292325246656,0.08098069950856415,0.005746473580236355 +25800,0.4787973600696003,0.017579398694637944,0.4171538855568278,0.07906001982355138,0.007409335855382714 +25900,0.48142864162616433,0.0140995800494763,0.41736066595998533,0.07793627260616152,0.009174839758212388 +26000,0.48319206932827824,0.00987895547419868,0.41961113811415,0.07634724309639615,0.010970593986977013 +26100,0.4890404081481975,0.005766224994094788,0.41821353168396563,0.07488991983456728,0.012089915339174813 +26200,0.4967791938836907,0.0032090395745093155,0.4136953061633807,0.07421000404663687,0.012106456331782424 +26300,0.5013375254417362,0.003071183723581195,0.4098453014258729,0.07437963568018743,0.011366353728622328 +26400,0.5020974566982717,0.004384168111285972,0.40774669367025057,0.07538033902354604,0.01039134249664566 +26500,0.49960899714016527,0.0063583787595273295,0.4041740782314293,0.08032433322189636,0.00953421264698191 +26600,0.49686458348494156,0.008269567304640532,0.3975788568737938,0.08901742503198401,0.008269567304640181 +26700,0.4928365318579985,0.009846004085564072,0.39367858516160126,0.09725443409512388,0.006384444799712293 +26800,0.48747500664289206,0.011578157452110837,0.39256459798642773,0.10395896155580454,0.004423276362764687 +26900,0.4834007422248019,0.013139469962275342,0.39266560606065687,0.10792090861600813,0.0028732731362576393 +27000,0.48407554133299224,0.014070101502755429,0.39053714985592974,0.1099082970620983,0.0014089102462242521 +27100,0.48654607843642134,0.014122168992316735,0.3872612525025102,0.11177922787737984,0.0002912721913718988 +27200,0.4905762986614257,0.013528898298745684,0.3835451153836923,0.11234968765613614,0.0 +27300,0.4984953521662186,0.013791622013005763,0.37847502002558253,0.10923800579519302,0.0 +27400,0.5089467922889178,0.01658631168041578,0.37301284841924776,0.10145404761141844,0.0 +27500,0.5158703347160895,0.021859211399435936,0.3729749087785873,0.08929554510588739,0.0 +27600,0.5174345326831371,0.027735182067464833,0.3798964310884988,0.07493385416089918,0.0 +27700,0.5146615220449425,0.032430250232968555,0.38999249050927554,0.06291573721281346,0.0 +27800,0.5084072214615385,0.034526829449010144,0.4005966001108651,0.05646934897858625,0.0 +27900,0.4993792257376335,0.035369599090715895,0.4103442288046927,0.05490694636695788,0.0 +28000,0.4938930436802014,0.03587908059151177,0.4147284268946161,0.05549944883367072,0.0 +28100,0.49464245824154235,0.03456594206602891,0.4154814030969438,0.05531019659548498,0.0 +28200,0.5000885569959538,0.030255552773458236,0.4139605901258766,0.05569530010471126,0.0 +28300,0.508379706466494,0.023529079170246145,0.4109854898982044,0.05710572446505556,0.0 +28400,0.5233670056598699,0.01622321288261602,0.4004475127001733,0.0599622687573406,0.0 +28500,0.5415726575196643,0.010398382390995853,0.38416610897816433,0.06386285111117565,0.0 +28600,0.55688077321784,0.006860667426251073,0.36852746617331844,0.06773109318259067,0.0 +28700,0.5647665244047986,0.0052126390629984,0.3603799461996729,0.06964089033253007,0.0 +28800,0.567739962595055,0.003645132545491197,0.3593266707328587,0.06928823412659503,0.0 +28900,0.5668082797742972,0.001788159879239637,0.36319936083069615,0.06820419951576714,0.0 +29000,0.5599182873353039,0.0003668955119694547,0.37100035436052825,0.0687144627921983,0.0 +29100,0.5492079709954166,0.0,0.38185387719312813,0.06893815181145525,0.0 +29200,0.5367564900298941,0.0,0.39640774923272315,0.0668357607373827,0.0 +29300,0.5226709898915272,0.0,0.41003116124743305,0.06729784886103982,0.0 +29400,0.5074946096335676,0.0,0.423084416065869,0.06942097430056333,0.0 +29500,0.4929595511904631,0.0,0.4353468944442865,0.07169355436525046,0.0 +29600,0.4797674757805357,0.0,0.446112691496679,0.07411983272278536,0.0 +29700,0.4683000690972654,0.0,0.45483607519171604,0.07686385571101863,0.0 +29800,0.4583692388607079,0.0,0.46146753125899365,0.08016322988029849,0.0 diff --git a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java index 026c853a5be..1b8a0b260e8 100644 --- a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java +++ b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java @@ -79,7 +79,6 @@ import picocli.CommandLine; import java.io.File; -import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDate; @@ -660,7 +659,7 @@ private void createCarriers(Scenario scenario, TripDistributionMatrix odMatrix, } // find a start category with existing employees in this zone Collections.shuffle(startCategory, rnd); - String selectedStartCategory = startCategory.get(0); + String selectedStartCategory = startCategory.getFirst(); for (int count = 1; resultingDataPerZone.get(startZone).getDouble(selectedStartCategory) == 0; count++) { if (count <= startCategory.size()) selectedStartCategory = startCategory.get(rnd.nextInt(startCategory.size())); @@ -888,7 +887,7 @@ private Id findPossibleLink(String zone, String selectedCategory, List, Link>> filterLinksForZones(Scenario scenario, Index indexZones, Map>> facilitiesPerZone, - String shapeFileZoneNameColumn) throws URISyntaxException { + String shapeFileZoneNameColumn) { Map, Link>> linksPerZone = new HashMap<>(); log.info("Filtering and assign links to zones. This take some time..."); diff --git a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java index f180308e69e..3af4dc1fa7f 100644 --- a/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java +++ b/contribs/small-scale-traffic-generation/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java @@ -79,7 +79,7 @@ public class SmallScaleCommercialTrafficUtils { public static Index getIndexZones(Path shapeFileZonePath, String shapeCRS, String shapeFileZoneNameColumn) { ShpOptions shpZones = new ShpOptions(shapeFileZonePath, shapeCRS, StandardCharsets.UTF_8); - if (shpZones.readFeatures().iterator().next().getAttribute(shapeFileZoneNameColumn) == null) + if (shpZones.readFeatures().getFirst().getAttribute(shapeFileZoneNameColumn) == null) throw new NullPointerException("The column '" + shapeFileZoneNameColumn + "' does not exist in the zones shape file. Please check the input."); return shpZones.createIndex(shapeCRS, shapeFileZoneNameColumn); } @@ -94,7 +94,7 @@ public static Index getIndexZones(Path shapeFileZonePath, String shapeCRS, Strin */ public static Index getIndexLanduse(Path shapeFileLandusePath, String shapeCRS, String shapeFileLanduseTypeColumn) { ShpOptions shpLanduse = new ShpOptions(shapeFileLandusePath, shapeCRS, StandardCharsets.UTF_8); - if (shpLanduse.readFeatures().iterator().next().getAttribute(shapeFileLanduseTypeColumn) == null) + if (shpLanduse.readFeatures().getFirst().getAttribute(shapeFileLanduseTypeColumn) == null) throw new NullPointerException("The column '" + shapeFileLanduseTypeColumn + "' does not exist in the landuse shape file. Please check the input."); return shpLanduse.createIndex(shapeCRS, shapeFileLanduseTypeColumn); } @@ -109,7 +109,7 @@ public static Index getIndexLanduse(Path shapeFileLandusePath, String shapeCRS, */ public static Index getIndexBuildings(Path shapeFileBuildingsPath, String shapeCRS, String shapeFileBuildingTypeColumn) { ShpOptions shpBuildings = new ShpOptions(shapeFileBuildingsPath, shapeCRS, StandardCharsets.UTF_8); - if (shpBuildings.readFeatures().iterator().next().getAttribute(shapeFileBuildingTypeColumn) == null) + if (shpBuildings.readFeatures().getFirst().getAttribute(shapeFileBuildingTypeColumn) == null) throw new NullPointerException("The column '" + shapeFileBuildingTypeColumn + "' does not exist in the building shape file. Please check the input."); return shpBuildings.createIndex(shapeCRS, shapeFileBuildingTypeColumn); @@ -125,7 +125,7 @@ public static Index getIndexBuildings(Path shapeFileBuildingsPath, String shapeC */ public static Index getIndexRegions(Path shapeFileRegionsPath, String shapeCRS, String regionsShapeRegionColumn) { ShpOptions shpRegions = new ShpOptions(shapeFileRegionsPath, shapeCRS, StandardCharsets.UTF_8); - if (shpRegions.readFeatures().iterator().next().getAttribute(regionsShapeRegionColumn) == null) + if (shpRegions.readFeatures().getFirst().getAttribute(regionsShapeRegionColumn) == null) throw new NullPointerException("The column '" + regionsShapeRegionColumn + "' does not exist in the region shape file. Please check the input."); return shpRegions.createIndex(shapeCRS, regionsShapeRegionColumn); } @@ -195,34 +195,29 @@ static void createPlansBasedOnCarrierPlans(Scenario scenario, String smallScaleC Carrier relatedCarrier = CarriersUtils.addOrGetCarriers(scenario).getCarriers() .get(Id.create(carrierName, Carrier.class)); String subpopulation = relatedCarrier.getAttributes().getAttribute("subpopulation").toString(); - final String mode; - if (subpopulation.contains("commercialPersonTraffic")) - mode = "car"; - else if (subpopulation.contains("goodsTraffic")) - mode = "freight"; - else - mode = relatedCarrier.getAttributes().getAttribute("networkMode").toString(); + Id vehicleId = Id.createVehicleId(person.getId().toString()); + String mode = allVehicles.getVehicles().get(vehicleId).getType().getNetworkMode(); + List tourElements = person.getSelectedPlan().getPlanElements(); double tourStartTime = 0; for (PlanElement tourElement : tourElements) { if (tourElement instanceof Activity activity) { - activity.setCoord( + Activity newActivity = PopulationUtils.createActivityFromCoord(activity.getType(), scenario.getNetwork().getLinks().get(activity.getLinkId()).getFromNode().getCoord()); if (activity.getType().equals("start")) { - tourStartTime = activity.getEndTime().seconds(); - activity.setType("commercial_start"); + newActivity.setEndTime(activity.getEndTime().seconds()); + newActivity.setType("commercial_start"); } else - activity.setEndTimeUndefined(); + newActivity.setEndTimeUndefined(); if (activity.getType().equals("end")) { - activity.setStartTime(tourStartTime + 8 * 3600); - activity.setType("commercial_end"); + newActivity.setStartTime(tourStartTime + 8 * 3600); + newActivity.setType("commercial_end"); } - plan.addActivity(activity); + plan.addActivity(newActivity); } if (tourElement instanceof Leg) { - Leg legActivity = popFactory.createLeg(mode); - plan.addLeg(legActivity); + PopulationUtils.createAndAddLeg(plan, mode); } } @@ -241,8 +236,6 @@ else if (subpopulation.contains("goodsTraffic")) newPerson.getAttributes().putAttribute("tourStartArea", relatedCarrier.getAttributes().getAttribute("tourStartArea")); - Id vehicleId = Id.createVehicleId(person.getId().toString()); - VehicleUtils.insertVehicleIdsIntoPersonAttributes(newPerson, Map.of(mode, vehicleId)); VehicleUtils.insertVehicleTypesIntoPersonAttributes(newPerson, Map.of(mode, allVehicles.getVehicles().get(vehicleId).getType().getId())); diff --git a/contribs/vsp/pom.xml b/contribs/vsp/pom.xml index fe92d90b3a5..b2bf9fb3a41 100644 --- a/contribs/vsp/pom.xml +++ b/contribs/vsp/pom.xml @@ -150,7 +150,7 @@ org.apache.poi poi-ooxml - 5.2.5 + 5.3.0 diff --git a/matsim/src/main/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroup.java b/matsim/src/main/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroup.java index c5376acc84b..8bf362f1b2c 100644 --- a/matsim/src/main/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroup.java +++ b/matsim/src/main/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroup.java @@ -65,7 +65,7 @@ public class SwissRailRaptorConfigGroup extends ReflectiveConfigGroup { private static final String PARAM_INTERMODAL_LEG_ONLYHANDLING = "intermodalLegOnlyHandling"; private static final String PARAM_INTERMODAL_LEG_ONLYHANDLING_DESC = "Define how routes containing only intermodal legs are handled: Useful options: alllow, avoid, forbid"; private static final String PARAM_TRANSFER_CALCULATION = "transferCalculation"; - private static final String PARAM_TRANFER_CALCULATION_DESC = "Defines whether all potential transfers are precomputed at the beginning of the simulation (Initial) or whether they are constructed on-demand (Cached). The former incurs potentially long up-front caclulations, but quicker routing. The latter avoids any initial computation, but may require longer routing time."; + private static final String PARAM_TRANFER_CALCULATION_DESC = "Defines whether all potential transfers are precomputed at the beginning of the simulation (Initial) or whether they are constructed on-demand when needed (Adaptive). The former incurs potentially long up-front caclulations, but quicker routing. The latter avoids any initial computation, but may require longer routing time."; private boolean useRangeQuery = false; private boolean useIntermodality = false; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorStaticConfig.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorStaticConfig.java index 8f49f121ab2..5e71b1170ce 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorStaticConfig.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorStaticConfig.java @@ -61,11 +61,11 @@ public enum RaptorTransferCalculation { Initial, /** - * Use this option if you want the algorithm to calculate transfers on demand, + * Use this option if you want the algorithm to calculate transfers adaptively on demand, * which avoids any simulation start-up time but may increase the routing time * itself. */ - Cached + Adaptive } diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorCore.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorCore.java index 3778eebfaea..d6c059897d8 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorCore.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorCore.java @@ -22,6 +22,7 @@ import ch.sbb.matsim.config.SwissRailRaptorConfigGroup; import ch.sbb.matsim.routing.pt.raptor.OccupancyData.DepartureData; import ch.sbb.matsim.routing.pt.raptor.RaptorInVehicleCostCalculator.RouteSegmentIterator; +import ch.sbb.matsim.routing.pt.raptor.RaptorStaticConfig.RaptorTransferCalculation; import ch.sbb.matsim.routing.pt.raptor.SwissRailRaptor.RaptorObserver; import ch.sbb.matsim.routing.pt.raptor.SwissRailRaptorData.CachingTransferProvider; import ch.sbb.matsim.routing.pt.raptor.SwissRailRaptorData.RRoute; @@ -70,6 +71,7 @@ public class SwissRailRaptorCore { private final PathElement[] tmpArrivalPathPerStop; // only used to ensure parallel update private final BitSet tmpImprovedStops; // only used to ensure parallel update private final boolean useCapacityConstraints; + private final boolean useAdaptiveTransferCalculation; private final RaptorInVehicleCostCalculator inVehicleCostCalculator; private final RaptorTransferCostCalculator transferCostCalculator; private final RouteSegmentIteratorImpl routeSegmentIterator; @@ -90,6 +92,7 @@ public class SwissRailRaptorCore { this.tmpArrivalPathPerStop = new PathElement[this.data.countStops]; this.tmpImprovedStops = new BitSet(this.data.countStops); this.useCapacityConstraints = this.data.config.isUseCapacityConstraints(); + this.useAdaptiveTransferCalculation = this.data.config.getTransferCalculation().equals(RaptorTransferCalculation.Adaptive); this.inVehicleCostCalculator = inVehicleCostCalculator; this.transferCostCalculator = transferCostCalculator; this.routeSegmentIterator = new RouteSegmentIteratorImpl(this.data); @@ -827,12 +830,21 @@ private void handleTransfers(boolean strict, RaptorParameters raptorParams, Cach } RRouteStop fromRouteStop = fromPE.toRouteStop; // this is the route stop we arrive with least cost at stop - // obtain on-demand transfers if applicable (will return null if transfers are calculated initially) - RTransfer[] transfers = this.data.calculateTransfers(fromRouteStop); - - int firstTransferIndex = transfers == null ? fromRouteStop.indexFirstTransfer : 0; - int lastTransferIndex = transfers == null ? firstTransferIndex + fromRouteStop.countTransfers : transfers.length; - transfers = transfers == null ? this.data.transfers : transfers; + final int firstTransferIndex; + final int lastTransferIndex; + final RTransfer[] transfers; + + if (!useAdaptiveTransferCalculation) { + // efficient lookup from the precomputed transfer candidates + transfers = this.data.transfers; + firstTransferIndex = fromRouteStop.indexFirstTransfer; + lastTransferIndex = firstTransferIndex + fromRouteStop.countTransfers; + } else { + // more costly calculation and caching of transfer canddiates + transfers = this.data.calculateTransfers(fromRouteStop); + firstTransferIndex = 0; + lastTransferIndex = transfers.length; + } for (int transferIndex = firstTransferIndex; transferIndex < lastTransferIndex; transferIndex++) { RTransfer transfer = transfers[transferIndex]; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorData.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorData.java index 7ec137e6096..a02b58c7b35 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorData.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorData.java @@ -245,15 +245,17 @@ public static SwissRailRaptorData create(TransitSchedule schedule, @Nullable Veh } } - // if cached transfer calculation is used, build a map for quick lookup of minimal transfer times + // if adaptive transfer calculation is used, build a map for quick lookup of and collection of minimal transfer times IdMap> staticTransferTimes = null; - if (staticConfig.getTransferCalculation().equals(RaptorTransferCalculation.Cached)) { + if (staticConfig.getTransferCalculation().equals(RaptorTransferCalculation.Adaptive)) { staticTransferTimes = new IdMap<>(TransitStopFacility.class); MinimalTransferTimes.MinimalTransferTimesIterator iterator = schedule.getMinimalTransferTimes().iterator(); while (iterator.hasNext()) { iterator.next(); + // we only put the predefined transfer times here, the location-based ones will be calculated + // adaptively during routing staticTransferTimes.computeIfAbsent(iterator.getFromStopId(), id -> new HashMap<>()) .put(schedule.getFacilities().get(iterator.getToStopId()), iterator.getSeconds()); } @@ -649,10 +651,6 @@ public Transfer get() { } RTransfer[] calculateTransfers(RRouteStop fromRouteStop) { - if (config.getTransferCalculation().equals(RaptorTransferCalculation.Initial)) { - return null; - } - // We tested this in a parallel set-up and things seem to work as they are // implemented. The routing threads will access the cache as read-only an // retrieve the cached stop connections. It can happen that two of them try to diff --git a/matsim/src/main/java/org/matsim/pt/transitSchedule/MinimalTransferTimesImpl.java b/matsim/src/main/java/org/matsim/pt/transitSchedule/MinimalTransferTimesImpl.java index c78b1b1687e..f8e5bf92d9f 100644 --- a/matsim/src/main/java/org/matsim/pt/transitSchedule/MinimalTransferTimesImpl.java +++ b/matsim/src/main/java/org/matsim/pt/transitSchedule/MinimalTransferTimesImpl.java @@ -19,11 +19,9 @@ package org.matsim.pt.transitSchedule; -import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; -import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.matsim.api.core.v01.Id; @@ -166,15 +164,4 @@ public double getSeconds() { throw new NoSuchElementException(); } } - - @Override - public Set> getCandidates(Id fromStop) { - var inner = minimalTransferTimes.get(fromStop); - - if (inner == null) { - return Collections.emptySet(); - } - - return inner.keySet(); - } } diff --git a/matsim/src/main/java/org/matsim/pt/transitSchedule/api/MinimalTransferTimes.java b/matsim/src/main/java/org/matsim/pt/transitSchedule/api/MinimalTransferTimes.java index c567093f865..72819f5cf70 100644 --- a/matsim/src/main/java/org/matsim/pt/transitSchedule/api/MinimalTransferTimes.java +++ b/matsim/src/main/java/org/matsim/pt/transitSchedule/api/MinimalTransferTimes.java @@ -19,8 +19,6 @@ package org.matsim.pt.transitSchedule.api; -import java.util.Set; - import org.matsim.api.core.v01.Id; /** @@ -68,8 +66,6 @@ public interface MinimalTransferTimes { * @return the previously set minimal transfer time, or Double.NaN if none was set. */ double remove(Id fromStop, Id toStop); - - Set> getCandidates(Id fromStop); /** * @return an iterator to iterate over all minimal transfer times set. diff --git a/matsim/src/main/java/org/matsim/pt/utils/CreatePseudoNetwork.java b/matsim/src/main/java/org/matsim/pt/utils/CreatePseudoNetwork.java index cae2eaf0f43..e2d6ff5078c 100644 --- a/matsim/src/main/java/org/matsim/pt/utils/CreatePseudoNetwork.java +++ b/matsim/src/main/java/org/matsim/pt/utils/CreatePseudoNetwork.java @@ -41,16 +41,15 @@ import org.matsim.pt.transitSchedule.api.TransitRoute; import org.matsim.pt.transitSchedule.api.TransitRouteStop; import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.pt.transitSchedule.api.TransitStopArea; import org.matsim.pt.transitSchedule.api.TransitStopFacility; /** * Builds a network where transit vehicles can drive along and assigns the correct - * links to the transit stop facilities and routes of transit lines. As each transit - * stop facility can only be connected to at most one link, the algorithm is forced - * to duplicated transit stop facilities in certain cases to build the network. + * links to the transit stop facilities and routes of transit lines. Each stop facility + * is assigned to a loop link, located in a node with the same coordinates as the stop. + * The stop facility ID is used for node and link IDs. * - * @author mrieser + * @author mrieser, davibicudo */ public class CreatePseudoNetwork { @@ -59,14 +58,9 @@ public class CreatePseudoNetwork { private final String prefix; private final double linkFreeSpeed; private final double linkCapacity; - - private final Map, Link> links = new HashMap, Link>(); - private final Map, TransitStopFacility> stopFacilities = new HashMap, TransitStopFacility>(); - private final Map nodes = new HashMap(); - private final Map> facilityCopies = new HashMap>(); - - private long linkIdCounter = 0; + private final Map, Link> links = new HashMap<>(); + private final Map nodes = new HashMap<>(); private final Set transitModes = Collections.singleton(TransportMode.pt); @@ -77,8 +71,8 @@ public CreatePseudoNetwork(final TransitSchedule schedule, final Network network this.linkFreeSpeed = 100.0 / 3.6; this.linkCapacity = 100000.0; } - - public CreatePseudoNetwork(final TransitSchedule schedule, final Network network, final String networkIdPrefix, + + public CreatePseudoNetwork(final TransitSchedule schedule, final Network network, final String networkIdPrefix, final double linkFreeSpeed, final double linkCapacity) { this.schedule = schedule; this.network = network; @@ -89,24 +83,27 @@ public CreatePseudoNetwork(final TransitSchedule schedule, final Network network public void createNetwork() { - List> toBeRemoved = new LinkedList>(); + createStopNodesAndLoopLinks(); + List> toBeRemoved = new LinkedList<>(); for (TransitLine tLine : this.schedule.getTransitLines().values()) { for (TransitRoute tRoute : tLine.getRoutes().values()) { - ArrayList> routeLinks = new ArrayList>(); + ArrayList> routeLinks = new ArrayList<>(); TransitRouteStop prevStop = null; for (TransitRouteStop stop : tRoute.getStops()) { - Link link = getNetworkLink(prevStop, stop); - routeLinks.add(link.getId()); + if (prevStop != null) { + Link link = getNetworkLink(prevStop, stop); + routeLinks.add(link.getId()); + } prevStop = stop; } - if (routeLinks.size() > 0) { - NetworkRoute route = RouteUtils.createNetworkRoute(routeLinks ); + if (!routeLinks.isEmpty()) { + NetworkRoute route = RouteUtils.createNetworkRoute(routeLinks); tRoute.setRoute(route); } else { System.err.println("Line " + tLine.getId() + " route " + tRoute.getId() + " has less than two stops. Removing this route from schedule."); - toBeRemoved.add(new Tuple(tLine, tRoute)); + toBeRemoved.add(new Tuple<>(tLine, tRoute)); } } } @@ -116,64 +113,40 @@ public void createNetwork() { } } + private void createStopNodesAndLoopLinks() { + for (TransitStopFacility stop : this.schedule.getFacilities().values()) { + Node node = this.network.getFactory().createNode(Id.createNodeId(this.prefix + stop.getId()), stop.getCoord()); + this.network.addNode(node); + this.nodes.put(stop, node); + + Link loopLink = this.network.getFactory().createLink(Id.createLinkId (this.prefix + stop.getId()), node, node); + stop.setLinkId(loopLink.getId()); + this.network.addLink(loopLink); + Tuple connection = new Tuple<>(node, node); + this.links.put(connection, loopLink); + } + } + private Link getNetworkLink(final TransitRouteStop fromStop, final TransitRouteStop toStop) { - TransitStopFacility fromFacility = (fromStop == null) ? toStop.getStopFacility() : fromStop.getStopFacility(); + TransitStopFacility fromFacility = fromStop.getStopFacility(); TransitStopFacility toFacility = toStop.getStopFacility(); Node fromNode = this.nodes.get(fromFacility); - if (fromNode == null) { - fromNode = this.network.getFactory().createNode(Id.create(this.prefix + toFacility.getId(), Node.class), fromFacility.getCoord()); - this.network.addNode(fromNode); - this.nodes.put(toFacility, fromNode); - } - Node toNode = this.nodes.get(toFacility); - if (toNode == null) { - toNode = this.network.getFactory().createNode(Id.create(this.prefix + toFacility.getId(), Node.class), toFacility.getCoord()); - this.network.addNode(toNode); - this.nodes.put(toFacility, toNode); - } - Tuple connection = new Tuple(fromNode, toNode); + Tuple connection = new Tuple<>(fromNode, toNode); Link link = this.links.get(connection); - if (link == null) { - link = createAndAddLink(fromNode, toNode, connection); - - if (toFacility.getLinkId() == null) { - toFacility.setLinkId(link.getId()); - this.stopFacilities.put(connection, toFacility); - } else { - List copies = this.facilityCopies.get(toFacility); - if (copies == null) { - copies = new ArrayList(); - this.facilityCopies.put(toFacility, copies); - } - Id newId = Id.create(toFacility.getId().toString() + "." + Integer.toString(copies.size() + 1), TransitStopFacility.class); - TransitStopFacility newFacility = this.schedule.getFactory().createTransitStopFacility(newId, toFacility.getCoord(), toFacility.getIsBlockingLane()); - newFacility.setStopAreaId(Id.create(toFacility.getId(), TransitStopArea.class)); - newFacility.setLinkId(link.getId()); - newFacility.setName(toFacility.getName()); - copies.add(newFacility); - this.nodes.put(newFacility, toNode); - this.schedule.addStopFacility(newFacility); - toStop.setStopFacility(newFacility); - this.stopFacilities.put(connection, newFacility); - } - } else { - toStop.setStopFacility(this.stopFacilities.get(connection)); - } - return link; + return link == null ? createAndAddLink(connection) : link; } - private Link createAndAddLink(Node fromNode, Node toNode, - Tuple connection) { + private Link createAndAddLink(Tuple connection) { + Node fromNode = connection.getFirst(); + Node toNode = connection.getSecond(); Link link; - link = this.network.getFactory().createLink(Id.create(this.prefix + this.linkIdCounter++, Link.class), fromNode, toNode); - if (fromNode == toNode) { - link.setLength(50); - } else { - link.setLength(CoordUtils.calcEuclideanDistance(fromNode.getCoord(), toNode.getCoord())); - } + link = this.network.getFactory().createLink(Id.createLinkId(this.prefix + fromNode.getId() + "-" + toNode.getId()), fromNode, + toNode); + link.setLength(CoordUtils.calcEuclideanDistance(fromNode.getCoord(), toNode.getCoord())); + link.setFreespeed(linkFreeSpeed); link.setCapacity(linkCapacity); link.setNumberOfLanes(1); @@ -183,11 +156,4 @@ private Link createAndAddLink(Node fromNode, Node toNode, return link; } - public Link getLinkBetweenStops(final TransitStopFacility fromStop, final TransitStopFacility toStop) { - Node fromNode = this.nodes.get(fromStop); - Node toNode = this.nodes.get(toStop); - Tuple connection = new Tuple(fromNode, toNode); - return this.links.get(connection); - } - } diff --git a/matsim/src/main/resources/dtd/lspsDefinitions_v1.xsd b/matsim/src/main/resources/dtd/lspsDefinitions_v1.xsd index a5a7d6ec747..32a03b4d072 100644 --- a/matsim/src/main/resources/dtd/lspsDefinitions_v1.xsd +++ b/matsim/src/main/resources/dtd/lspsDefinitions_v1.xsd @@ -7,129 +7,123 @@ - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pom.xml b/pom.xml index 70842b4e875..3f97fb8c5d3 100644 --- a/pom.xml +++ b/pom.xml @@ -35,9 +35,9 @@ 0.49.2 1.19.0 7.0.0 - 2.17.1 + 2.17.2 2.5.0 - 5.10.2 + 5.10.3 @@ -296,7 +296,7 @@ org.checkerframework checker-qual - 3.44.0 + 3.45.0 @@ -314,7 +314,7 @@ org.assertj assertj-core - 3.26.0 + 3.26.3 test @@ -358,7 +358,7 @@ net.bytebuddy byte-buddy - 1.14.17 + 1.14.18 test @@ -425,7 +425,7 @@ org.apache.maven.plugins maven-failsafe-plugin - 3.3.0 + 3.3.1 org.apache.maven.plugins