diff --git a/contribs/application/src/main/java/org/matsim/application/options/ShpOptions.java b/contribs/application/src/main/java/org/matsim/application/options/ShpOptions.java index 4537c88bfb9..a541548a7d9 100644 --- a/contribs/application/src/main/java/org/matsim/application/options/ShpOptions.java +++ b/contribs/application/src/main/java/org/matsim/application/options/ShpOptions.java @@ -16,6 +16,7 @@ import org.matsim.api.core.v01.Coord; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.geotools.MGC; +import org.matsim.core.utils.geometry.transformations.IdentityTransformation; import org.matsim.core.utils.geometry.transformations.TransformationFactory; import org.matsim.core.utils.gis.ShapeFileReader; import org.matsim.core.utils.io.IOUtils; @@ -47,6 +48,11 @@ */ public final class ShpOptions { + /** + * Special value for {@link #createIndex(String, String)} to use the same crs as the shape file. + */ + public static final String SAME_CRS = "same_crs"; + private static final Logger log = LogManager.getLogger(ShpOptions.class); @CommandLine.Option(names = "--shp", description = "Optional path to shape file used for filtering", required = false) @@ -204,10 +210,15 @@ public Index createIndex(String queryCRS, String attr, Set filter) { if (queryCRS == null) throw new IllegalArgumentException("Query crs must not be null!"); - CoordinateTransformation ct = TransformationFactory.getCoordinateTransformation(queryCRS, detectCRS()); - try { - return new Index(ct, attr, filter); + ShapefileDataStore ds = openDataStoreAndSetCRS(); + CoordinateTransformation ct; + if (queryCRS.equals(SAME_CRS)) + ct = new IdentityTransformation(); + else { + ct = TransformationFactory.getCoordinateTransformation(queryCRS, shpCrs); + } + return new Index(ct, ds, attr, filter); } catch (IOException e) { throw new UncheckedIOException(e); } @@ -222,6 +233,15 @@ public Index createIndex(String queryCRS, String attr) { return createIndex(queryCRS, attr, null); } + /** + * Create an index without a filter and the same query crs as the shape file. + * + * @see #createIndex(String, String) + */ + public Index createIndex(String attr) { + return createIndex(SAME_CRS, attr, null); + } + /** * Create a coordinate transformation to the shape file crs. Tries to autodetect the crs of the shape file. */ @@ -247,6 +267,25 @@ private String detectCRS() { return shpCrs; } + /** + * Open the shape file for processing and set the crs if not already specified. + */ + private ShapefileDataStore openDataStoreAndSetCRS() throws IOException { + ShapefileDataStore ds = openDataStore(shp); + + if (shpCrs == null) { + try { + CoordinateReferenceSystem crs = ds.getSchema().getCoordinateReferenceSystem(); + shpCrs = "EPSG:" + CRS.lookupEpsgCode(crs, true); + log.info("Using detected crs for {}: {}", shp, shpCrs); + } catch (FactoryException | NullPointerException e) { + throw new IllegalStateException("Could not determine crs of the shape file. Try to specify it manually using --shp-crs.", e); + } + } + + return ds; + } + /** * Create an inverse coordinate transformation from the shape file crs. Tries to autodetect the crs of the shape file. */ @@ -269,9 +308,7 @@ public final class Index { * @param ct coordinate transform from query to target crs * @param attr attribute for the result of {@link #query(Coord)} */ - Index(CoordinateTransformation ct, String attr, @Nullable Set filter) throws IOException { - ShapefileDataStore ds = openDataStore(shp); - + Index(CoordinateTransformation ct, ShapefileDataStore ds, String attr, @Nullable Set filter) throws IOException { if (shpCharset != null) ds.setCharset(shpCharset); @@ -342,11 +379,10 @@ public boolean contains(Coord coord) { return false; } - /** * Return all features in the index. */ - public List getAll() { + public List getAllFeatures() { List result = new ArrayList<>(); itemsTree(result, index.getRoot()); @@ -372,6 +408,14 @@ private void itemsTree(List list, AbstractNode node) { public int size() { return index.size(); } + + /** + * Return underlying shp file. Should be used carefully. + */ + public ShpOptions getShp() { + return ShpOptions.this; + } + } } diff --git a/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java b/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java index 0f788f5f9d6..46ec4a745b6 100644 --- a/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java +++ b/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/GenerateSmallScaleCommercialTrafficDemand.java @@ -38,6 +38,10 @@ import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.ShpOptions; import org.matsim.application.options.ShpOptions.Index; +import org.matsim.core.config.consistency.UnmaterializedConfigGroupChecker; +import org.matsim.core.scenario.ProjectionUtils; +import org.matsim.core.utils.geometry.CoordUtils; +import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.freight.carriers.*; import org.matsim.freight.carriers.controler.*; import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; @@ -78,6 +82,8 @@ import java.util.*; import java.util.stream.Collectors; +import static org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles; + /** * Tool to generate small scale commercial traffic for a selected area. The needed input data are: employee information for the area and three shapes files (zones, buildings, landuse). These data should be available with OSM. * @@ -95,8 +101,6 @@ public class GenerateSmallScaleCommercialTrafficDemand implements MATSimAppComma // Option 3: Leerkamp (nur in RVR Modell). private static final Logger log = LogManager.getLogger(GenerateSmallScaleCommercialTrafficDemand.class); - private static final HashMap>> buildingsPerZone = new HashMap<>(); - private static final HashMap> landuseCategoriesAndDataConnection = new HashMap<>(); private enum CreationOption { useExistingCarrierFileWithSolution, createNewCarrierFile, useExistingCarrierFileWithoutSolution @@ -152,10 +156,19 @@ private enum SmallScaleCommercialTrafficType { @CommandLine.Option(names = "--numberOfPlanVariantsPerAgent", description = "If an agent should have variant plans, you should set this parameter.", defaultValue = "1") private int numberOfPlanVariantsPerAgent; + @CommandLine.Option(names = "--network", description = "Overwrite network file in config") + private String network; + @CommandLine.Option(names = "--pathOutput", description = "Path for the output") private Path output; private Random rnd; + private final Map>> buildingsPerZone = new HashMap<>(); + private final Map> landuseCategoriesAndDataConnection = new HashMap<>(); + + private Index indexZones; + private Index indexBuildings; + private Index indexLanduse; public static void main(String[] args) { System.exit(new CommandLine(new GenerateSmallScaleCommercialTrafficDemand()).execute(args)); @@ -213,13 +226,19 @@ public Integer call() throws Exception { throw new Exception("Required districts shape file {} not found" + shapeFileZonePath.toString()); } Path inputDataDirectory = Path.of(config.getContext().toURI()).getParent(); - HashMap> resultingDataPerZone = LanduseBuildingAnalysis - .createInputDataDistribution(output, landuseCategoriesAndDataConnection, inputDataDirectory, - usedLanduseConfiguration.toString(), shapeFileLandusePath, shapeFileZonePath, - shapeFileBuildingsPath, shapeCRS, buildingsPerZone); + ShpOptions shpZones = new ShpOptions(shapeFileZonePath, shapeCRS, StandardCharsets.UTF_8); - Map, Link>> regionLinksMap = filterLinksForZones(scenario, shpZones, - SmallScaleCommercialTrafficUtils.getIndexZones(shapeFileZonePath, shapeCRS), buildingsPerZone); + + indexZones = SmallScaleCommercialTrafficUtils.getIndexZones(shapeFileZonePath, shapeCRS); + indexBuildings = SmallScaleCommercialTrafficUtils.getIndexBuildings(shapeFileBuildingsPath, shapeCRS); + indexLanduse = SmallScaleCommercialTrafficUtils.getIndexLanduse(shapeFileLandusePath, shapeCRS); + + Map> resultingDataPerZone = LanduseBuildingAnalysis + .createInputDataDistribution(output, landuseCategoriesAndDataConnection, inputDataDirectory, + usedLanduseConfiguration.toString(), indexLanduse, indexZones, + indexBuildings, buildingsPerZone); + + Map, Link>> regionLinksMap = filterLinksForZones(scenario, indexZones, buildingsPerZone); switch (usedSmallScaleCommercialTrafficType) { case commercialPersonTraffic, goodsTraffic -> @@ -252,10 +271,20 @@ public Integer call() throws Exception { new CarrierPlanWriter(CarriersUtils.addOrGetCarriers(scenario)) .write( scenario.getConfig().controller().getOutputDirectory() + "/" + scenario.getConfig().controller().getRunId() + ".output_CarrierDemandWithPlans.xml"); + Controler controler = prepareControler(scenario); + + // Creating inject always adds check for unmaterialized config groups. + controler.getInjector(); + + // Removes check after injector has been created + controler.getConfig().removeConfigConsistencyChecker(UnmaterializedConfigGroupChecker.class); + controler.run(); + SmallScaleCommercialTrafficUtils.createPlansBasedOnCarrierPlans(controler.getScenario(), usedSmallScaleCommercialTrafficType.toString(), output, modelName, sampleName, nameOutputPopulation, numberOfPlanVariantsPerAgent); + return 0; } @@ -263,7 +292,7 @@ public Integer call() throws Exception { * @param originalScenario complete Scenario * @param regionLinksMap list with Links for each region */ - private void solveSeparatedVRPs(Scenario originalScenario, Map, Link>> regionLinksMap) throws Exception { + private void solveSeparatedVRPs(Scenario originalScenario, Map, Link>> regionLinksMap) throws Exception { boolean splitCarrier = true; boolean splitVRPs = false; @@ -395,8 +424,8 @@ private void solveSeparatedVRPs(Scenario originalScenario, Map> resultingDataPerZone, - Map, Link>> regionLinksMap, String smallScaleCommercialTrafficType, + Map> resultingDataPerZone, + Map, Link>> regionLinksMap, String smallScaleCommercialTrafficType, boolean includeExistingModels) throws Exception { ArrayList modesORvehTypes; @@ -410,9 +439,9 @@ else if (smallScaleCommercialTrafficType.equals("commercialPersonTraffic")) TrafficVolumeGeneration.setInputParameters(smallScaleCommercialTrafficType); - HashMap> trafficVolumePerTypeAndZone_start = TrafficVolumeGeneration + Map> trafficVolumePerTypeAndZone_start = TrafficVolumeGeneration .createTrafficVolume_start(resultingDataPerZone, output, sample, modesORvehTypes, smallScaleCommercialTrafficType); - HashMap> trafficVolumePerTypeAndZone_stop = TrafficVolumeGeneration + Map> trafficVolumePerTypeAndZone_stop = TrafficVolumeGeneration .createTrafficVolume_stop(resultingDataPerZone, output, sample, modesORvehTypes, smallScaleCommercialTrafficType); if (includeExistingModels) { @@ -426,7 +455,7 @@ else if (smallScaleCommercialTrafficType.equals("commercialPersonTraffic")) } /** - * Reads and checks config if all necessary parameter are set. + * Reads and checks config if all necessary parameters are set. */ private Config readAndCheckConfig(Path configPath, String modelName, String sampleName, Path output) throws Exception { @@ -438,14 +467,34 @@ private Config readAndCheckConfig(Path configPath, String modelName, String samp .toString()); else config.controller().setOutputDirectory(output.toString()); + + // Reset some config values that are not needed + config.controller().setFirstIteration(0); + config.controller().setLastIteration(0); + config.plans().setInputFile(null); + config.transit().setTransitScheduleFile(null); + config.transit().setVehiclesFile(null); + config.counts().setInputFile(null); + + // Set flow and storage capacity to a high value + config.qsim().setFlowCapFactor(sample * 4); + config.qsim().setStorageCapFactor(sample * 4); + config.qsim().setUsePersonIdForMissingVehicleId(true); + + // Overwrite network + if (network != null) + config.network().setInputFile(network); + + // Some files are written before the controller is created, deleting the directory is not an option + config.controller().setOverwriteFileSetting(overwriteExistingFiles); + new OutputDirectoryHierarchy(config.controller().getOutputDirectory(), config.controller().getRunId(), config.controller().getOverwriteFileSetting(), ControllerConfigGroup.CompressionType.gzip); new File(Path.of(config.controller().getOutputDirectory()).resolve("calculatedData").toString()).mkdir(); rnd = new Random(config.global().getRandomSeed()); + if (config.network().getInputFile() == null) throw new Exception("No network file in config"); - if (config.network().getInputCRS() == null) - throw new Exception("No network CRS is set in config"); if (config.global().getCoordinateSystem() == null) throw new Exception("No global CRS is set in config"); if (config.controller().getOutputDirectory() == null) @@ -469,7 +518,9 @@ public void install() { bind(CarrierScoringFunctionFactory.class).toInstance(new MyCarrierScoringFunctionFactory()); } }); - controler.getConfig().vspExperimental().setVspDefaultsCheckingLevel(VspExperimentalConfigGroup.VspDefaultsCheckingLevel.abort); + + controler.getConfig().vspExperimental().setVspDefaultsCheckingLevel(VspExperimentalConfigGroup.VspDefaultsCheckingLevel.warn); + return controler; } @@ -478,8 +529,8 @@ public void install() { * TripDistributionMatrix. */ private void createCarriers(Scenario scenario, TripDistributionMatrix odMatrix, - HashMap> resultingDataPerZone, String smallScaleCommercialTrafficType, - Map, Link>> regionLinksMap) { + Map> resultingDataPerZone, String smallScaleCommercialTrafficType, + Map, Link>> regionLinksMap) { int maxNumberOfCarrier = odMatrix.getListOfPurposes().size() * odMatrix.getListOfZones().size() * odMatrix.getListOfModesOrVehTypes().size(); int createdCarrier = 0; @@ -491,8 +542,11 @@ private void createCarriers(Scenario scenario, TripDistributionMatrix odMatrix, CarrierVehicleTypes carrierVehicleTypes = CarriersUtils.getCarrierVehicleTypes(scenario); Map, VehicleType> additionalCarrierVehicleTypes = scenario.getVehicles().getVehicleTypes(); - additionalCarrierVehicleTypes.values().forEach( - vehicleType -> carrierVehicleTypes.getVehicleTypes().putIfAbsent(vehicleType.getId(), vehicleType)); + + // Only vehicle with cost information will work properly + additionalCarrierVehicleTypes.values().stream() + .filter(vehicleType -> vehicleType.getCostInformation().getCostsPerSecond() != null) + .forEach(vehicleType -> carrierVehicleTypes.getVehicleTypes().putIfAbsent(vehicleType.getId(), vehicleType)); for (VehicleType vehicleType : carrierVehicleTypes.getVehicleTypes().values()) { CostInformation costInformation = vehicleType.getCostInformation(); @@ -662,13 +716,13 @@ private void createCarriers(Scenario scenario, TripDistributionMatrix odMatrix, private void createServices(Scenario scenario, ArrayList noPossibleLinks, String selectedStopCategory, String carrierName, int numberOfJobs, String[] serviceArea, Integer serviceTimePerStop, TimeWindow serviceTimeWindow, - Map, Link>> regionLinksMap) { + Map, Link>> regionLinksMap) { String stopZone = serviceArea[0]; for (int i = 0; i < numberOfJobs; i++) { - Id linkId = findPossibleLink(stopZone, selectedStopCategory, noPossibleLinks, regionLinksMap, shapeCRS); + Id linkId = findPossibleLink(stopZone, selectedStopCategory, noPossibleLinks, regionLinksMap); Id idNewService = Id.create(carrierName + "_" + linkId + "_" + rnd.nextInt(10000), CarrierService.class); @@ -687,7 +741,7 @@ private void createNewCarrierAndAddVehicleTypes(Scenario scenario, Integer purpo String selectedStartCategory, String carrierName, List vehicleTypes, int numberOfDepots, FleetSize fleetSize, int fixedNumberOfVehiclePerTypeAndLocation, - ArrayList vehicleDepots, Map, Link>> regionLinksMap, + List vehicleDepots, Map, Link>> regionLinksMap, String smallScaleCommercialTrafficType, ValueSelectorUnderGivenProbability tourStartTimeSelector, ValueSelectorUnderGivenProbability tourDurationTimeSelector) { @@ -711,7 +765,7 @@ private void createNewCarrierAndAddVehicleTypes(Scenario scenario, Integer purpo carriers.addCarrier(thisCarrier); while (vehicleDepots.size() < numberOfDepots) { - Id link = findPossibleLink(startZone, selectedStartCategory, null, regionLinksMap, shapeCRS); + Id link = findPossibleLink(startZone, selectedStartCategory, null, regionLinksMap); vehicleDepots.add(link.toString()); } @@ -799,16 +853,13 @@ else if (smallScaleCommercialTrafficType.equals(SmallScaleCommercialTrafficType. /** * Finds a possible link for a service or the vehicle location. */ - private Id findPossibleLink(String zone, String selectedCategory, ArrayList noPossibleLinks, - Map, Link>> regionLinksMap, String shapeCRS) { - - Index indexZones = SmallScaleCommercialTrafficUtils.getIndexZones(shapeFileZonePath, shapeCRS); + private Id findPossibleLink(String zone, String selectedCategory, List noPossibleLinks, + Map, Link>> regionLinksMap) { if (buildingsPerZone.isEmpty()) { - ShpOptions shpBuildings = new ShpOptions(shapeFileBuildingsPath, "EPSG:4326", StandardCharsets.UTF_8); - List buildingsFeatures = shpBuildings.readFeatures(); + List buildingsFeatures = indexBuildings.getAllFeatures(); LanduseBuildingAnalysis.analyzeBuildingType(buildingsFeatures, buildingsPerZone, - landuseCategoriesAndDataConnection, shapeFileLandusePath, indexZones, shapeCRS); + landuseCategoriesAndDataConnection, indexLanduse, indexZones); } Id newLink = null; for (int a = 0; newLink == null && a < buildingsPerZone.get(zone).get(selectedCategory).size() * 2; a++) { @@ -834,9 +885,9 @@ private Id findPossibleLink(String zone, String selectedCategory, ArrayLis /** * Filters links by used mode "car" and creates Map with all links in each zone */ - static Map, Link>> filterLinksForZones(Scenario scenario, ShpOptions shpZones, Index indexZones, - HashMap>> buildingsPerZone) throws URISyntaxException { - Map, Link>> regionLinksMap = new HashMap<>(); + static Map, Link>> filterLinksForZones(Scenario scenario, Index indexZones, + Map>> buildingsPerZone) throws URISyntaxException { + Map, Link>> regionLinksMap = new HashMap<>(); List links; log.info("Filtering and assign links to zones. This take some time..."); @@ -849,31 +900,34 @@ static Map, Link>> filterLinksForZones(Scenario scenari Network networkToChange = NetworkUtils.readNetwork(networkPath); NetworkUtils.runNetworkCleaner(networkToChange); + CoordinateTransformation ct = indexZones.getShp().createTransformation(ProjectionUtils.getCRS(scenario.getNetwork())); + links = networkToChange.getLinks().values().stream().filter(l -> l.getAllowedModes().contains("car")) .collect(Collectors.toList()); links.forEach(l -> l.getAttributes().putAttribute("newCoord", - shpZones.createTransformation(scenario.getConfig().network().getInputCRS()).transform(l.getCoord()))); + CoordUtils.round(ct.transform(l.getCoord())))); links.forEach(l -> l.getAttributes().putAttribute("zone", indexZones.query((Coord) l.getAttributes().getAttribute("newCoord")))); links = links.stream().filter(l -> l.getAttributes().getAttribute("zone") != null).collect(Collectors.toList()); links.forEach(l -> regionLinksMap .computeIfAbsent((String) l.getAttributes().getAttribute("zone"), (k) -> new HashMap<>()) .put(l.getId(), l)); - if (regionLinksMap.size() != shpZones.readFeatures().size()) - findNearestLinkForZonesWithoutLinks(networkToChange, regionLinksMap, shpZones, buildingsPerZone); + if (regionLinksMap.size() != indexZones.size()) + findNearestLinkForZonesWithoutLinks(networkToChange, regionLinksMap, indexZones, buildingsPerZone); + return regionLinksMap; } /** - * Finds for areas without links the nearest Link, if the area contains any building. + * Finds for areas without links the nearest Link if the area contains any building. */ - private static void findNearestLinkForZonesWithoutLinks(Network networkToChange, Map, Link>> regionLinksMap, - ShpOptions shpZones, - HashMap>> buildingsPerZone) { - for (SimpleFeature singleArea : shpZones.readFeatures()) { + private static void findNearestLinkForZonesWithoutLinks(Network networkToChange, Map, Link>> regionLinksMap, + Index shpZones, + Map>> buildingsPerZone) { + for (SimpleFeature singleArea : shpZones.getAllFeatures()) { String zoneID = (String) singleArea.getAttribute("areaID"); if (!regionLinksMap.containsKey(zoneID) && buildingsPerZone.get(zoneID) != null) { - for (ArrayList buildingList : buildingsPerZone.get(zoneID).values()) { + for (List buildingList : buildingsPerZone.get(zoneID).values()) { for (SimpleFeature building : buildingList) { Link l = NetworkUtils.getNearestLink(networkToChange, MGC.point2Coord(((Geometry) building.getDefaultGeometry()).getCentroid())); @@ -891,14 +945,14 @@ private static void findNearestLinkForZonesWithoutLinks(Network networkToChange, * Creates the number of trips between the zones for each mode and purpose. */ private TripDistributionMatrix createTripDistribution( - HashMap> trafficVolume_start, - HashMap> trafficVolume_stop, ShpOptions shpZones, - String smallScaleCommercialTrafficType, Scenario scenario, Path output, Map, Link>> regionLinksMap) + Map> trafficVolume_start, + Map> trafficVolume_stop, ShpOptions shpZones, + String smallScaleCommercialTrafficType, Scenario scenario, Path output, Map, Link>> regionLinksMap) throws Exception { final TripDistributionMatrix odMatrix = TripDistributionMatrix.Builder - .newInstance(shpZones, trafficVolume_start, trafficVolume_stop, smallScaleCommercialTrafficType).build(); - ArrayList listOfZones = new ArrayList<>(); + .newInstance(indexZones, trafficVolume_start, trafficVolume_stop, smallScaleCommercialTrafficType).build(); + List listOfZones = new ArrayList<>(); trafficVolume_start.forEach((k, v) -> { if (!listOfZones.contains(k.getZone())) listOfZones.add(k.getZone()); diff --git a/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/LanduseBuildingAnalysis.java b/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/LanduseBuildingAnalysis.java index 8054c953605..faffac894c1 100644 --- a/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/LanduseBuildingAnalysis.java +++ b/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/LanduseBuildingAnalysis.java @@ -29,7 +29,6 @@ import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.Point; import org.matsim.api.core.v01.Coord; -import org.matsim.application.options.ShpOptions; import org.matsim.application.options.ShpOptions.Index; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.core.utils.io.IOUtils; @@ -37,14 +36,10 @@ import java.io.BufferedReader; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; +import java.util.*; /** * @author Ricardo Ewert @@ -58,14 +53,14 @@ public class LanduseBuildingAnalysis { * Creates a distribution of the given input data for each zone based on the * used OSM data. */ - static HashMap> createInputDataDistribution(Path output, - HashMap> landuseCategoriesAndDataConnection, Path inputDataDirectory, - String usedLanduseConfiguration, Path shapeFileLandusePath, Path shapeFileZonePath, - Path shapeFileBuildingsPath, String shapeCRS, HashMap>> buildingsPerZone) + static Map> createInputDataDistribution(Path output, + Map> landuseCategoriesAndDataConnection, Path inputDataDirectory, + String usedLanduseConfiguration, Index indexLanduse, Index indexZones, + Index indexBuildings, Map>> buildingsPerZone) throws IOException { - HashMap> resultingDataPerZone = new HashMap<>(); - HashMap zoneIdNameConnection = new HashMap<>(); + Map> resultingDataPerZone = new HashMap<>(); + Map zoneIdNameConnection = new HashMap<>(); Path outputFileInOutputFolder = output.resolve("calculatedData").resolve("dataDistributionPerZone.csv"); landuseCategoriesAndDataConnection.put("Inhabitants", @@ -113,12 +108,12 @@ static HashMap> createInputDataDistribution(Pat log.info("New analyze for data distribution is started. The used method is: " + usedLanduseConfiguration); - HashMap> landuseCategoriesPerZone = new HashMap<>(); - createLanduseDistribution(landuseCategoriesPerZone, shapeFileLandusePath, shapeFileZonePath, - usedLanduseConfiguration, shapeFileBuildingsPath, landuseCategoriesAndDataConnection, - buildingsPerZone, zoneIdNameConnection, shapeCRS); + Map> landuseCategoriesPerZone = new HashMap<>(); + createLanduseDistribution(landuseCategoriesPerZone, indexLanduse, indexZones, + usedLanduseConfiguration, indexBuildings, landuseCategoriesAndDataConnection, + buildingsPerZone, zoneIdNameConnection); - HashMap> investigationAreaData = new HashMap<>(); + Map> investigationAreaData = new HashMap<>(); readAreaData(investigationAreaData, inputDataDirectory); createResultingDataForLanduseInZones(landuseCategoriesPerZone, investigationAreaData, resultingDataPerZone, @@ -136,14 +131,14 @@ static HashMap> createInputDataDistribution(Pat * and the original data. */ private static void createResultingDataForLanduseInZones( - HashMap> landuseCategoriesPerZone, - HashMap> investigationAreaData, - HashMap> resultingDataPerZone, - HashMap> landuseCategoriesAndDataConnection) { + Map> landuseCategoriesPerZone, + Map> investigationAreaData, + Map> resultingDataPerZone, + Map> landuseCategoriesAndDataConnection) { - HashMap> totalSquareMetersPerCategory = new HashMap>(); - HashMap> totalEmployeesInCategoriesPerZone = new HashMap>(); - HashMap> totalEmployeesPerCategories = new HashMap>(); + Map> totalSquareMetersPerCategory = new HashMap>(); + Map> totalEmployeesInCategoriesPerZone = new HashMap>(); + Map> totalEmployeesPerCategories = new HashMap>(); investigationAreaData.keySet() .forEach(c -> totalSquareMetersPerCategory.computeIfAbsent(c, k -> new Object2DoubleOpenHashMap<>())); @@ -176,7 +171,7 @@ private static void createResultingDataForLanduseInZones( * creates the percentages of each category and zones based on the sum in this * category */ - HashMap> checkPercentages = new HashMap>(); + Map> checkPercentages = new HashMap>(); investigationAreaData.keySet() .forEach(c -> checkPercentages.computeIfAbsent(c, k -> new Object2DoubleOpenHashMap<>())); for (String zoneId : resultingDataPerZone.keySet()) @@ -220,22 +215,18 @@ private static void createResultingDataForLanduseInZones( * Method create the percentage for each land use category in each zone based on * the sum of this category in all zones of the zone shape file */ - private static void createLanduseDistribution(HashMap> landuseCategoriesPerZone, - Path shapeFileLandusePath, Path shapeFileZonePath, String usedLanduseConfiguration, - Path shapeFileBuildingsPath, HashMap> landuseCategoriesAndDataConnection, - HashMap>> buildingsPerZone, - HashMap zoneIdNameConnection, String shapeCRS) { + private static void createLanduseDistribution(Map> landuseCategoriesPerZone, + Index indexLanduse, Index indexZones, String usedLanduseConfiguration, + Index indexBuildings, Map> landuseCategoriesAndDataConnection, + Map>> buildingsPerZone, + Map zoneIdNameConnection) { List neededLanduseCategories = List.of("residential", "industrial", "commercial", "retail", "farmyard", "farmland", "construction"); - ShpOptions shpLanduse = new ShpOptions(shapeFileLandusePath, shapeCRS, StandardCharsets.UTF_8); - ShpOptions shpZones = new ShpOptions(shapeFileZonePath, shapeCRS, StandardCharsets.UTF_8); + List landuseFeatures = indexLanduse.getAllFeatures(); + List zonesFeatures = indexZones.getAllFeatures(); - List landuseFeatures = shpLanduse.readFeatures(); - List zonesFeatures = shpZones.readFeatures(); - - Index indexZones = SmallScaleCommercialTrafficUtils.getIndexZones(shapeFileZonePath, shpZones.getShapeCrs()); for (SimpleFeature singleZone : zonesFeatures) { Object2DoubleMap landusePerCategory = new Object2DoubleOpenHashMap<>(); @@ -246,10 +237,9 @@ private static void createLanduseDistribution(HashMap buildingsFeatures = shpBuildings.readFeatures(); + List buildingsFeatures = indexBuildings.getAllFeatures(); analyzeBuildingType(buildingsFeatures, buildingsPerZone, landuseCategoriesAndDataConnection, - shapeFileLandusePath, indexZones, shpLanduse.getShapeCrs()); + indexLanduse, indexZones); for (String zone : buildingsPerZone.keySet()) for (String category : buildingsPerZone.get(zone).keySet()) @@ -289,7 +279,7 @@ private static void createLanduseDistribution(HashMap> areaData, Path inputDataDirectory) + private static void readAreaData(Map> areaData, Path inputDataDirectory) throws IOException { Path areaDataPath = inputDataDirectory.resolve("investigationAreaData.csv"); @@ -300,7 +290,7 @@ private static void readAreaData(HashMap> areaD CSVFormat.Builder.create(CSVFormat.TDF).setHeader().setSkipHeaderRecord(true).build())) { for (CSVRecord record : parser) { - HashMap lookUpTable = new HashMap<>(); + Map lookUpTable = new HashMap<>(); for (String csvRecord : parser.getHeaderMap().keySet()) { if (parser.getHeaderMap().get(csvRecord) > 0) lookUpTable.put(csvRecord, Integer.valueOf(record.get(csvRecord))); @@ -314,11 +304,9 @@ private static void readAreaData(HashMap> areaD * Analysis the building types so that you have the buildings per zone and type. */ static void analyzeBuildingType(List buildingsFeatures, - HashMap>> buildingsPerZone, - HashMap> landuseCategoriesAndDataConnection, Path shapeFileLandusePath, - Index indexZones, String crsLanduse) { - - Index indexLanduse = SmallScaleCommercialTrafficUtils.getIndexLanduse(shapeFileLandusePath, crsLanduse); + Map>> buildingsPerZone, + Map> landuseCategoriesAndDataConnection, Index indexLanduse, + Index indexZones) { int countOSMObjects = 0; log.info("Analyzing buildings types. This may take some time..."); @@ -360,7 +348,7 @@ static void analyzeBuildingType(List buildingsFeatures, categoriesOfBuilding.add("Employee"); if (singleZone != null) { categoriesOfBuilding.forEach(c -> buildingsPerZone - .computeIfAbsent(singleZone, k -> new HashMap>()) + .computeIfAbsent(singleZone, k -> new HashMap<>()) .computeIfAbsent(c, k -> new ArrayList()).add(singleBuildingFeature)); } } diff --git a/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java b/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java index 3d8563424a1..1ea26e82ee3 100644 --- a/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java +++ b/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtils.java @@ -75,7 +75,7 @@ public class SmallScaleCommercialTrafficUtils { private static final Joiner JOIN = Joiner.on("\t"); /** - * Creates and return the Index of the zones shape. + * Creates and return the Index of the zone shape. * * @return indexZones */ @@ -97,17 +97,28 @@ static Index getIndexLanduse(Path shapeFileLandusePath, String shapeCRS) { } /** - * Writes a csv file with result of the distribution per zone of the input data. + * Creates and return the Index of the building shape. + * + * @return indexBuildings + */ + static Index getIndexBuildings(Path shapeFileBuildingsPath, String shapeCRS) { + + ShpOptions shpLanduse = new ShpOptions(shapeFileBuildingsPath, shapeCRS, StandardCharsets.UTF_8); + return shpLanduse.createIndex(shapeCRS, "type"); + } + + /** + * Writes a csv file with the result of the distribution per zone of the input data. */ - static void writeResultOfDataDistribution(HashMap> resultingDataPerZone, - Path outputFileInOutputFolder, HashMap zoneIdNameConnection) + static void writeResultOfDataDistribution(Map> resultingDataPerZone, + Path outputFileInOutputFolder, Map zoneIdNameConnection) throws IOException { writeCSVWithCategoryHeader(resultingDataPerZone, outputFileInOutputFolder, zoneIdNameConnection); log.info("The data distribution is finished and written to: " + outputFileInOutputFolder); } - static Id findNearestPossibleLink(String zone, ArrayList noPossibleLinks, Map, Link>> regionLinksMap, + static Id findNearestPossibleLink(String zone, List noPossibleLinks, Map, Link>> regionLinksMap, Id newLink, Coord centroidPointOfBuildingPolygon, int numberOfPossibleLinks) { double minDistance = Double.MAX_VALUE; searchLink: @@ -145,9 +156,9 @@ static Id findNearestPossibleLink(String zone, ArrayList noPossibl /** * Writer of data distribution data. */ - private static void writeCSVWithCategoryHeader(HashMap> resultingDataPerZone, + private static void writeCSVWithCategoryHeader(Map> resultingDataPerZone, Path outputFileInInputFolder, - HashMap zoneIdNameConnection) throws MalformedURLException { + Map zoneIdNameConnection) throws MalformedURLException { BufferedWriter writer = IOUtils.getBufferedWriter(outputFileInInputFolder.toUri().toURL(), StandardCharsets.UTF_8, true); try { @@ -286,7 +297,7 @@ static String getSampleNameOfOutputFolder(double sample) { * dispersedTraffic will be added additionally. */ static void readExistingModels(Scenario scenario, double sampleScenario, - Map, Link>> regionLinksMap) throws Exception { + Map, Link>> regionLinksMap) throws Exception { Path existingModelsFolder = Path.of(scenario.getConfig().getContext().toURI()).getParent().resolve("existingModels"); String locationOfExistingModels = existingModelsFolder.resolve("existingModels.csv").toString(); @@ -515,7 +526,7 @@ else if (!carrier.getShipments().isEmpty()) /** * Find the zone where the link is located */ - static String findZoneOfLink(Id linkId, Map, Link>> regionLinksMap) { + static String findZoneOfLink(Id linkId, Map, Link>> regionLinksMap) { for (String area : regionLinksMap.keySet()) { if (regionLinksMap.get(area).containsKey(linkId)) return area; diff --git a/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/TrafficVolumeGeneration.java b/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/TrafficVolumeGeneration.java index ada637b06d7..7e9e591eabc 100644 --- a/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/TrafficVolumeGeneration.java +++ b/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/TrafficVolumeGeneration.java @@ -50,10 +50,10 @@ public class TrafficVolumeGeneration { private static final Logger log = LogManager.getLogger(TrafficVolumeGeneration.class); private static final Joiner JOIN = Joiner.on("\t"); - private static HashMap> generationRatesStart = new HashMap<>(); - private static HashMap> generationRatesStop = new HashMap<>(); - private static HashMap> commitmentRatesStart = new HashMap<>(); - private static HashMap> commitmentRatesStop = new HashMap<>(); + private static Map> generationRatesStart = new HashMap<>(); + private static Map> generationRatesStop = new HashMap<>(); + private static Map> commitmentRatesStart = new HashMap<>(); + private static Map> commitmentRatesStop = new HashMap<>(); static class TrafficVolumeKey { private final String zone; @@ -116,11 +116,11 @@ static TrafficVolumeKey makeTrafficVolumeKey(String zone, String modeORvehType) * @param modesORvehTypes selected mode or vehicleType * @return trafficVolume_start */ - static HashMap> createTrafficVolume_start( - HashMap> resultingDataPerZone, Path output, double sample, - ArrayList modesORvehTypes, String trafficType) throws MalformedURLException { + static Map> createTrafficVolume_start( + Map> resultingDataPerZone, Path output, double sample, + List modesORvehTypes, String trafficType) throws MalformedURLException { - HashMap> trafficVolume_start = new HashMap<>(); + Map> trafficVolume_start = new HashMap<>(); calculateTrafficVolumePerZone(trafficVolume_start, resultingDataPerZone, "start", sample, modesORvehTypes); String sampleName = SmallScaleCommercialTrafficUtils.getSampleNameOfOutputFolder(sample); Path outputFileStart = output.resolve("calculatedData") @@ -140,11 +140,11 @@ static HashMap> createTrafficVolume_ * @param modesORvehTypes selected mode or vehicleType * @return trafficVolume_stop */ - static HashMap> createTrafficVolume_stop( - HashMap> resultingDataPerZone, Path output, double sample, - ArrayList modesORvehTypes, String trafficType) throws MalformedURLException { + static Map> createTrafficVolume_stop( + Map> resultingDataPerZone, Path output, double sample, + List modesORvehTypes, String trafficType) throws MalformedURLException { - HashMap> trafficVolume_stop = new HashMap<>(); + Map> trafficVolume_stop = new HashMap<>(); calculateTrafficVolumePerZone(trafficVolume_stop, resultingDataPerZone, "stop", sample, modesORvehTypes); String sampleName = SmallScaleCommercialTrafficUtils.getSampleNameOfOutputFolder(sample); Path outputFileStop = output.resolve("calculatedData") @@ -164,12 +164,12 @@ static HashMap> createTrafficVolume_ * @param sample sample size */ private static void calculateTrafficVolumePerZone( - HashMap> trafficVolume, - HashMap> resultingDataPerZone, String volumeType, double sample, - ArrayList modesORvehTypes) { + Map> trafficVolume, + Map> resultingDataPerZone, String volumeType, double sample, + List modesORvehTypes) { - HashMap> generationRates; - HashMap> commitmentRates; + Map> generationRates; + Map> commitmentRates; if (volumeType.equals("start")) { generationRates = generationRatesStart; @@ -216,7 +216,7 @@ private static void calculateTrafficVolumePerZone( * @param trafficVolume traffic volumes for each combination * @param outputFileInInputFolder location of written output */ - private static void writeCSVTrafficVolume(HashMap> trafficVolume, + private static void writeCSVTrafficVolume(Map> trafficVolume, Path outputFileInInputFolder) throws MalformedURLException { BufferedWriter writer = IOUtils.getBufferedWriter(outputFileInInputFolder.toUri().toURL(), StandardCharsets.UTF_8, true); @@ -239,7 +239,7 @@ private static void writeCSVTrafficVolume(HashMap, Link>> regionLinksMap, String smallScaleCommercialTrafficType, - HashMap> trafficVolumePerTypeAndZone_start, - HashMap> trafficVolumePerTypeAndZone_stop) { + Map, Link>> regionLinksMap, String smallScaleCommercialTrafficType, + Map> trafficVolumePerTypeAndZone_start, + Map> trafficVolumePerTypeAndZone_stop) { for (Carrier carrier : CarriersUtils.addOrGetCarriers(scenario).getCarriers().values()) { if (!carrier.getAttributes().getAsMap().containsKey("subpopulation") @@ -321,7 +321,7 @@ static void reduceDemandBasedOnExistingCarriers(Scenario scenario, } } } else { - if (carrier.getServices().size() != 0) { + if (!carrier.getServices().isEmpty()) { List possibleStartAreas = new ArrayList<>(); for (CarrierVehicle vehicle : carrier.getCarrierCapabilities().getCarrierVehicles().values()) { possibleStartAreas @@ -341,7 +341,7 @@ static void reduceDemandBasedOnExistingCarriers(Scenario scenario, + " is not part of the zones. That's why the traffic volume was not reduces by this service."); } } - } else if (carrier.getShipments().size() != 0) { + } else if (!carrier.getShipments().isEmpty()) { for (CarrierShipment shipment : carrier.getShipments().values()) { String startZone = SmallScaleCommercialTrafficUtils.findZoneOfLink(shipment.getFrom(), regionLinksMap); @@ -372,8 +372,8 @@ static void reduceDemandBasedOnExistingCarriers(Scenario scenario, * @param stopZone end zone */ private static void reduceVolumeForThisExistingJobElement( - HashMap> trafficVolumePerTypeAndZone_start, - HashMap> trafficVolumePerTypeAndZone_stop, String modeORvehType, + Map> trafficVolumePerTypeAndZone_start, + Map> trafficVolumePerTypeAndZone_stop, String modeORvehType, Integer purpose, String startZone, String stopZone) { if (startZone != null && stopZone != null) { @@ -402,7 +402,7 @@ private static void reduceVolumeForThisExistingJobElement( * @param originalZone zone with volume of 0, although volume in existing model */ private static void reduceVolumeForOtherArea( - HashMap> trafficVolumePerTypeAndZone, String modeORvehType, + Map> trafficVolumePerTypeAndZone, String modeORvehType, Integer purpose, String volumeType, String originalZone) { ArrayList shuffledKeys = new ArrayList<>( trafficVolumePerTypeAndZone.keySet()); @@ -425,16 +425,16 @@ private static void reduceVolumeForOtherArea( * @param smallScaleCommercialTrafficType used trafficType (freight or business traffic) * @param generationType start or stop rates */ - private static HashMap> setGenerationRates(String smallScaleCommercialTrafficType, + private static Map> setGenerationRates(String smallScaleCommercialTrafficType, String generationType) { - HashMap> generationRates = new HashMap<>(); - HashMap ratesPerPurpose1 = new HashMap<>(); - HashMap ratesPerPurpose2 = new HashMap<>(); - HashMap ratesPerPurpose3 = new HashMap<>(); - HashMap ratesPerPurpose4 = new HashMap<>(); - HashMap ratesPerPurpose5 = new HashMap<>(); - HashMap ratesPerPurpose6 = new HashMap<>(); + Map> generationRates = new HashMap<>(); + Map ratesPerPurpose1 = new HashMap<>(); + Map ratesPerPurpose2 = new HashMap<>(); + Map ratesPerPurpose3 = new HashMap<>(); + Map ratesPerPurpose4 = new HashMap<>(); + Map ratesPerPurpose5 = new HashMap<>(); + Map ratesPerPurpose6 = new HashMap<>(); if (smallScaleCommercialTrafficType.equals("commercialPersonTraffic")) { if (generationType.equals("start")) { ratesPerPurpose1.put("Inhabitants", 0.0); @@ -657,43 +657,43 @@ private static HashMap> setGenerationRates(Stri * @param smallScaleCommercialTrafficType used trafficType (freight or business traffic) * @param commitmentType start or stop parameter */ - private static HashMap> setCommitmentRates(String smallScaleCommercialTrafficType, + private static Map> setCommitmentRates(String smallScaleCommercialTrafficType, String commitmentType) { - HashMap> commitmentRates = new HashMap<>(); + Map> commitmentRates = new HashMap<>(); if (smallScaleCommercialTrafficType.equals("goodsTraffic")) { // the first number is the purpose; second number the vehicle type - HashMap ratesPerPurpose1_1 = new HashMap<>(); - HashMap ratesPerPurpose1_2 = new HashMap<>(); - HashMap ratesPerPurpose1_3 = new HashMap<>(); - HashMap ratesPerPurpose1_4 = new HashMap<>(); - HashMap ratesPerPurpose1_5 = new HashMap<>(); - HashMap ratesPerPurpose2_1 = new HashMap<>(); - HashMap ratesPerPurpose2_2 = new HashMap<>(); - HashMap ratesPerPurpose2_3 = new HashMap<>(); - HashMap ratesPerPurpose2_4 = new HashMap<>(); - HashMap ratesPerPurpose2_5 = new HashMap<>(); - HashMap ratesPerPurpose3_1 = new HashMap<>(); - HashMap ratesPerPurpose3_2 = new HashMap<>(); - HashMap ratesPerPurpose3_3 = new HashMap<>(); - HashMap ratesPerPurpose3_4 = new HashMap<>(); - HashMap ratesPerPurpose3_5 = new HashMap<>(); - HashMap ratesPerPurpose4_1 = new HashMap<>(); - HashMap ratesPerPurpose4_2 = new HashMap<>(); - HashMap ratesPerPurpose4_3 = new HashMap<>(); - HashMap ratesPerPurpose4_4 = new HashMap<>(); - HashMap ratesPerPurpose4_5 = new HashMap<>(); - HashMap ratesPerPurpose5_1 = new HashMap<>(); - HashMap ratesPerPurpose5_2 = new HashMap<>(); - HashMap ratesPerPurpose5_3 = new HashMap<>(); - HashMap ratesPerPurpose5_4 = new HashMap<>(); - HashMap ratesPerPurpose5_5 = new HashMap<>(); - HashMap ratesPerPurpose6_1 = new HashMap<>(); - HashMap ratesPerPurpose6_2 = new HashMap<>(); - HashMap ratesPerPurpose6_3 = new HashMap<>(); - HashMap ratesPerPurpose6_4 = new HashMap<>(); - HashMap ratesPerPurpose6_5 = new HashMap<>(); + Map ratesPerPurpose1_1 = new HashMap<>(); + Map ratesPerPurpose1_2 = new HashMap<>(); + Map ratesPerPurpose1_3 = new HashMap<>(); + Map ratesPerPurpose1_4 = new HashMap<>(); + Map ratesPerPurpose1_5 = new HashMap<>(); + Map ratesPerPurpose2_1 = new HashMap<>(); + Map ratesPerPurpose2_2 = new HashMap<>(); + Map ratesPerPurpose2_3 = new HashMap<>(); + Map ratesPerPurpose2_4 = new HashMap<>(); + Map ratesPerPurpose2_5 = new HashMap<>(); + Map ratesPerPurpose3_1 = new HashMap<>(); + Map ratesPerPurpose3_2 = new HashMap<>(); + Map ratesPerPurpose3_3 = new HashMap<>(); + Map ratesPerPurpose3_4 = new HashMap<>(); + Map ratesPerPurpose3_5 = new HashMap<>(); + Map ratesPerPurpose4_1 = new HashMap<>(); + Map ratesPerPurpose4_2 = new HashMap<>(); + Map ratesPerPurpose4_3 = new HashMap<>(); + Map ratesPerPurpose4_4 = new HashMap<>(); + Map ratesPerPurpose4_5 = new HashMap<>(); + Map ratesPerPurpose5_1 = new HashMap<>(); + Map ratesPerPurpose5_2 = new HashMap<>(); + Map ratesPerPurpose5_3 = new HashMap<>(); + Map ratesPerPurpose5_4 = new HashMap<>(); + Map ratesPerPurpose5_5 = new HashMap<>(); + Map ratesPerPurpose6_1 = new HashMap<>(); + Map ratesPerPurpose6_2 = new HashMap<>(); + Map ratesPerPurpose6_3 = new HashMap<>(); + Map ratesPerPurpose6_4 = new HashMap<>(); + Map ratesPerPurpose6_5 = new HashMap<>(); if (commitmentType.equals("start")) { ratesPerPurpose1_1.put("Inhabitants", 0.0); ratesPerPurpose1_1.put("Employee", 0.8); diff --git a/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/TripDistributionMatrix.java b/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/TripDistributionMatrix.java index 68c03dedb7e..7d631a6b96d 100644 --- a/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/TripDistributionMatrix.java +++ b/contribs/application/src/main/java/org/matsim/smallScaleCommercialTrafficGeneration/TripDistributionMatrix.java @@ -32,13 +32,13 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; -import org.matsim.application.options.ShpOptions; -import org.matsim.freight.carriers.jsprit.NetworkBasedTransportCosts; +import org.matsim.application.options.ShpOptions.Index; import org.matsim.core.utils.io.IOUtils; +import org.matsim.freight.carriers.jsprit.NetworkBasedTransportCosts; +import org.matsim.smallScaleCommercialTrafficGeneration.TrafficVolumeGeneration.TrafficVolumeKey; import org.matsim.vehicles.VehicleType; import org.matsim.vehicles.VehicleUtils; import org.opengis.feature.simple.SimpleFeature; -import org.matsim.smallScaleCommercialTrafficGeneration.TrafficVolumeGeneration.TrafficVolumeKey; import java.io.BufferedWriter; import java.io.IOException; @@ -46,7 +46,10 @@ import java.net.MalformedURLException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** @@ -61,8 +64,8 @@ public class TripDistributionMatrix { private final ArrayList listOfModesORvehTypes = new ArrayList<>(); private final ArrayList listOfPurposes = new ArrayList<>(); private final List zonesFeatures; - private final HashMap> trafficVolume_start; - private final HashMap> trafficVolume_stop; + private final Map> trafficVolume_start; + private final Map> trafficVolume_stop; private final String smallScaleCommercialTrafficType; private static class TripDistributionMatrixKey { @@ -232,23 +235,23 @@ public boolean equals(Object obj) { public static class Builder { private final List zonesFeatures; - private final HashMap> trafficVolume_start; - private final HashMap> trafficVolume_stop; + private final Map> trafficVolume_start; + private final Map> trafficVolume_stop; private final String smallScaleCommercialTrafficType; - public static Builder newInstance(ShpOptions shpZones, - HashMap> trafficVolume_start, - HashMap> trafficVolume_stop, + public static Builder newInstance(Index indexZones, + Map> trafficVolume_start, + Map> trafficVolume_stop, String smallScaleCommercialTrafficType) { - return new Builder(shpZones, trafficVolume_start, trafficVolume_stop, smallScaleCommercialTrafficType); + return new Builder(indexZones, trafficVolume_start, trafficVolume_stop, smallScaleCommercialTrafficType); } - private Builder(ShpOptions shpZones, - HashMap> trafficVolume_start, - HashMap> trafficVolume_stop, + private Builder(Index indexZones, + Map> trafficVolume_start, + Map> trafficVolume_stop, String smallScaleCommercialTrafficType) { super(); - this.zonesFeatures = shpZones.readFeatures(); + this.zonesFeatures = indexZones.getAllFeatures(); this.trafficVolume_start = trafficVolume_start; this.trafficVolume_stop = trafficVolume_stop; this.smallScaleCommercialTrafficType = smallScaleCommercialTrafficType; @@ -285,7 +288,7 @@ private TripDistributionMatrix(Builder builder) { * @param regionLinksMap links in each zone */ void setTripDistributionValue(String startZone, String stopZone, String modeORvehType, Integer purpose, String smallScaleCommercialTrafficType, Network network, - Map, Link>> regionLinksMap, double resistanceFactor) { + Map, Link>> regionLinksMap, double resistanceFactor) { double volumeStart = trafficVolume_start.get(TrafficVolumeGeneration.makeTrafficVolumeKey(startZone, modeORvehType)).getDouble(purpose); double volumeStop = trafficVolume_stop.get(TrafficVolumeGeneration.makeTrafficVolumeKey(stopZone, modeORvehType)).getDouble(purpose); int roundedVolume; @@ -337,7 +340,7 @@ Integer getTripDistributionValue(String startZone, String stopZone, String modeO * @param stopZone stop zone * @param regionLinksMap links for each zone */ - private Double getResistanceFunktionValue(String startZone, String stopZone, Network network, Map, Link>> regionLinksMap, double resistanceFactor) { + private Double getResistanceFunktionValue(String startZone, String stopZone, Network network, Map, Link>> regionLinksMap, double resistanceFactor) { //if false the calculation is faster; e.g. for debugging boolean useNetworkRoutesForResistanceFunction = true; @@ -448,8 +451,8 @@ private VehicleImpl getExampleVehicle(Location fromId) { * @return gravity constant */ private double getGravityConstant(String baseZone, - HashMap> trafficVolume, String modeORvehType, - Integer purpose, Network network, Map, Link>> regionLinksMap, double resistanceFactor) { + Map> trafficVolume, String modeORvehType, + Integer purpose, Network network, Map, Link>> regionLinksMap, double resistanceFactor) { GravityConstantKey gravityKey = makeGravityKey(baseZone, modeORvehType, purpose); if (!gravityConstantACache.containsKey(gravityKey)) { @@ -629,7 +632,7 @@ void writeODMatrices(Path output, String smallScaleCommercialTrafficType) throws writer.close(); } catch (IOException e) { - e.printStackTrace(); + log.error("Problem to write OD matrix", e); } log.info("Write OD matrix for mode " + modeORvehType + " and for purpose " + purpose + " to " + outputFolder); diff --git a/contribs/application/src/test/java/org/matsim/application/options/ShpOptionsTest.java b/contribs/application/src/test/java/org/matsim/application/options/ShpOptionsTest.java index 2c9282c4add..7742e1bdc2e 100644 --- a/contribs/application/src/test/java/org/matsim/application/options/ShpOptionsTest.java +++ b/contribs/application/src/test/java/org/matsim/application/options/ShpOptionsTest.java @@ -5,7 +5,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.locationtech.jts.geom.Geometry; -import org.locationtech.jts.geom.GeometryFactory; import org.matsim.testcases.MatsimTestUtils; import org.opengis.feature.simple.SimpleFeature; @@ -57,12 +56,15 @@ void all() { ShpOptions.Index index = shp.createIndex(shp.getShapeCrs(), "_"); - List ft = index.getAll(); + List ft = index.getAllFeatures(); assertThat(ft) .hasSize(4906) .hasSize(Set.copyOf(ft).size()); + assertThat(shp.readFeatures()) + .hasSameElementsAs(ft); + } @Test diff --git a/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/LanduseBuildingAnalysisTest.java b/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/LanduseBuildingAnalysisTest.java index 9957d7ef446..6d562e6fbf1 100644 --- a/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/LanduseBuildingAnalysisTest.java +++ b/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/LanduseBuildingAnalysisTest.java @@ -23,18 +23,17 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; -import org.matsim.application.options.ShpOptions; -import org.matsim.application.options.ShpOptions.Index; import org.matsim.testcases.MatsimTestUtils; import org.opengis.feature.simple.SimpleFeature; import java.io.File; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Path; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; + +import static org.matsim.smallScaleCommercialTrafficGeneration.SCTUtils.*; /** * @author Ricardo Ewert @@ -47,23 +46,19 @@ public class LanduseBuildingAnalysisTest { @Test void testReadOfDataDistributionPerZoneAndBuildingAnalysis() throws IOException { - HashMap> landuseCategoriesAndDataConnection = new HashMap>(); - HashMap>> buildingsPerZone = new HashMap<>(); + Map> landuseCategoriesAndDataConnection = new HashMap<>(); + Map>> buildingsPerZone = new HashMap<>(); Path output = Path.of(utils.getOutputDirectory()); - new File(output.resolve("calculatedData").toString()).mkdir(); + assert(new File(output.resolve("calculatedData").toString()).mkdir()); Path inputDataDirectory = Path.of(utils.getPackageInputDirectory()); String usedLanduseConfiguration = "useExistingDataDistribution"; - Path shapeFileLandusePath = inputDataDirectory.resolve("shp/testLanduse.shp"); - Path shapeFileZonePath = inputDataDirectory.resolve("shp/testZones.shp"); - Path shapeFileBuildingsPath = inputDataDirectory.resolve("shp/testBuildings.shp"); - String shapeCRS = "EPSG:4326"; // Test if the reading of the existing data distribution works correctly - HashMap> resultingDataPerZone = LanduseBuildingAnalysis + Map> resultingDataPerZone = LanduseBuildingAnalysis .createInputDataDistribution(output, landuseCategoriesAndDataConnection, inputDataDirectory, usedLanduseConfiguration, - shapeFileLandusePath, shapeFileZonePath, shapeFileBuildingsPath, null, buildingsPerZone); + getIndexLanduse(inputDataDirectory), getZoneIndex(inputDataDirectory), getIndexBuildings(inputDataDirectory), buildingsPerZone); Assertions.assertEquals(3, resultingDataPerZone.size(), MatsimTestUtils.EPSILON); @@ -150,12 +145,10 @@ void testReadOfDataDistributionPerZoneAndBuildingAnalysis() throws IOException { } // tests if the reading of the buildings works correctly - Index indexZones = SmallScaleCommercialTrafficUtils.getIndexZones(shapeFileZonePath, shapeCRS); - ShpOptions shpBuildings = new ShpOptions(shapeFileBuildingsPath, null, StandardCharsets.UTF_8); - List buildingsFeatures = shpBuildings.readFeatures(); + List buildingsFeatures = getIndexBuildings(inputDataDirectory).getAllFeatures(); Assertions.assertEquals(31, buildingsFeatures.size(), MatsimTestUtils.EPSILON); LanduseBuildingAnalysis.analyzeBuildingType(buildingsFeatures, buildingsPerZone, - landuseCategoriesAndDataConnection, shapeFileLandusePath, indexZones, shapeCRS); + landuseCategoriesAndDataConnection, getIndexLanduse(inputDataDirectory), getZoneIndex(inputDataDirectory)); Assertions.assertEquals(3, buildingsPerZone.size(), MatsimTestUtils.EPSILON); Assertions.assertTrue(buildingsPerZone.containsKey("testArea1_area1")); @@ -163,9 +156,9 @@ void testReadOfDataDistributionPerZoneAndBuildingAnalysis() throws IOException { Assertions.assertTrue(buildingsPerZone.containsKey("testArea2_area3")); // test for area1 - HashMap> builingsPerArea1 = buildingsPerZone.get("testArea1_area1"); + Map> builingsPerArea1 = buildingsPerZone.get("testArea1_area1"); Assertions.assertEquals(7, builingsPerArea1.size(), MatsimTestUtils.EPSILON); - ArrayList inhabitantsBuildings = builingsPerArea1.get("Inhabitants"); + List inhabitantsBuildings = builingsPerArea1.get("Inhabitants"); Assertions.assertEquals(4, inhabitantsBuildings.size(), MatsimTestUtils.EPSILON); for (SimpleFeature singleBuilding : inhabitantsBuildings) { int id = (int) (long) singleBuilding.getAttribute("osm_id"); @@ -193,9 +186,9 @@ void testReadOfDataDistributionPerZoneAndBuildingAnalysis() throws IOException { Assertions.assertEquals(6, builingsPerArea1.get("Employee").size(), MatsimTestUtils.EPSILON); // test for area2 - HashMap> builingsPerArea2 = buildingsPerZone.get("testArea1_area2"); + Map> builingsPerArea2 = buildingsPerZone.get("testArea1_area2"); Assertions.assertEquals(8, builingsPerArea2.size(), MatsimTestUtils.EPSILON); - ArrayList employeeRetail = builingsPerArea2.get("Employee Retail"); + List employeeRetail = builingsPerArea2.get("Employee Retail"); Assertions.assertEquals(2, employeeRetail.size(), MatsimTestUtils.EPSILON); for (SimpleFeature singleBuilding : employeeRetail) { int id = (int) (long) singleBuilding.getAttribute("osm_id"); @@ -217,9 +210,9 @@ void testReadOfDataDistributionPerZoneAndBuildingAnalysis() throws IOException { Assertions.assertEquals(8, builingsPerArea2.get("Employee").size(), MatsimTestUtils.EPSILON); // test for area3 - HashMap> builingsPerArea3 = buildingsPerZone.get("testArea2_area3"); + Map> builingsPerArea3 = buildingsPerZone.get("testArea2_area3"); Assertions.assertEquals(8, builingsPerArea3.size(), MatsimTestUtils.EPSILON); - ArrayList tertiaryRetail = builingsPerArea3.get("Employee Tertiary Sector Rest"); + List tertiaryRetail = builingsPerArea3.get("Employee Tertiary Sector Rest"); Assertions.assertEquals(1, tertiaryRetail.size(), MatsimTestUtils.EPSILON); for (SimpleFeature singleBuilding : tertiaryRetail) { int id = (int) (long) singleBuilding.getAttribute("osm_id"); @@ -240,22 +233,19 @@ void testReadOfDataDistributionPerZoneAndBuildingAnalysis() throws IOException { @Test void testLanduseDistribution() throws IOException { - HashMap> landuseCategoriesAndDataConnection = new HashMap>(); - HashMap>> buildingsPerZone = new HashMap<>(); + Map> landuseCategoriesAndDataConnection = new HashMap<>(); + Map>> buildingsPerZone = new HashMap<>(); Path output = Path.of(utils.getOutputDirectory()); - new File(output.resolve("calculatedData").toString()).mkdir(); + assert(new File(output.resolve("calculatedData").toString()).mkdir()); Path inputDataDirectory = Path.of(utils.getPackageInputDirectory()); String usedLanduseConfiguration = "useOSMBuildingsAndLanduse"; - Path shapeFileLandusePath = inputDataDirectory.resolve("shp/testLanduse.shp"); - Path shapeFileZonePath = inputDataDirectory.resolve("shp/testZones.shp"); - Path shapeFileBuildingsPath = inputDataDirectory.resolve("shp/testBuildings.shp"); // Analyze resultingData per zone - HashMap> resultingDataPerZone = LanduseBuildingAnalysis + Map> resultingDataPerZone = LanduseBuildingAnalysis .createInputDataDistribution(output, landuseCategoriesAndDataConnection, - inputDataDirectory, usedLanduseConfiguration, - shapeFileLandusePath, shapeFileZonePath, shapeFileBuildingsPath, null, buildingsPerZone); + inputDataDirectory, usedLanduseConfiguration, + getIndexLanduse(inputDataDirectory), getZoneIndex(inputDataDirectory), getIndexBuildings(inputDataDirectory), buildingsPerZone); Assertions.assertEquals(3, resultingDataPerZone.size(), MatsimTestUtils.EPSILON); diff --git a/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/SCTUtils.java b/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/SCTUtils.java new file mode 100644 index 00000000000..7b16b902d08 --- /dev/null +++ b/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/SCTUtils.java @@ -0,0 +1,27 @@ +package org.matsim.smallScaleCommercialTrafficGeneration; + +import org.matsim.application.options.ShpOptions; + +import java.nio.file.Path; + +/** + * Helper tests methods. + */ +public class SCTUtils { + + static ShpOptions.Index getZoneIndex(Path inputDataDirectory) { + Path shapeFileZonePath = inputDataDirectory.resolve("shp/testZones.shp"); + return new ShpOptions(shapeFileZonePath, null, null).createIndex("areaID"); + } + + static ShpOptions.Index getIndexLanduse(Path inputDataDirectory) { + Path shapeFileLandusePath = inputDataDirectory.resolve("shp/testLanduse.shp"); + return new ShpOptions(shapeFileLandusePath, null, null).createIndex("fclass"); + } + + static ShpOptions.Index getIndexBuildings(Path inputDataDirectory) { + Path shapeFileBuildingsPath = inputDataDirectory.resolve("shp/testBuildings.shp"); + return new ShpOptions(shapeFileBuildingsPath, null, null).createIndex("type"); + } + +} diff --git a/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtilsTest.java b/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtilsTest.java index 0b89332ca30..3aedc210cde 100644 --- a/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtilsTest.java +++ b/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/SmallScaleCommercialTrafficUtilsTest.java @@ -38,6 +38,7 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; /** @@ -54,17 +55,16 @@ void findZoneOfLinksTest() throws IOException, URISyntaxException { Path inputDataDirectory = Path.of(utils.getPackageInputDirectory()); Path shapeFileZonePath = inputDataDirectory.resolve("shp/testZones.shp"); - ShpOptions shpZones = new ShpOptions(shapeFileZonePath, null, StandardCharsets.UTF_8); String networkPath = "https://raw.githubusercontent.com/matsim-org/matsim-libs/master/examples/scenarios/freight-chessboard-9x9/grid9x9.xml"; Config config = ConfigUtils.createConfig(); config.global().setCoordinateSystem("EPSG:4326"); config.network().setInputFile(networkPath); config.network().setInputCRS("EPSG:4326"); Scenario scenario = ScenarioUtils.loadScenario(config); - HashMap>> buildingsPerZone = new HashMap<>(); + Map>> buildingsPerZone = new HashMap<>(); - Map, Link>> regionLinksMap = GenerateSmallScaleCommercialTrafficDemand - .filterLinksForZones(scenario, shpZones, SmallScaleCommercialTrafficUtils.getIndexZones(shapeFileZonePath, config.global().getCoordinateSystem()), + Map, Link>> regionLinksMap = GenerateSmallScaleCommercialTrafficDemand + .filterLinksForZones(scenario, SmallScaleCommercialTrafficUtils.getIndexZones(shapeFileZonePath, config.global().getCoordinateSystem()), buildingsPerZone); Assertions.assertEquals(3, regionLinksMap.size(), MatsimTestUtils.EPSILON); diff --git a/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/TrafficVolumeGenerationTest.java b/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/TrafficVolumeGenerationTest.java index c1d80ed77d6..ef979568774 100644 --- a/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/TrafficVolumeGenerationTest.java +++ b/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/TrafficVolumeGenerationTest.java @@ -26,23 +26,23 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Link; -import org.matsim.application.options.ShpOptions; -import org.matsim.freight.carriers.Carrier; -import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; -import org.matsim.freight.carriers.CarriersUtils; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.scenario.ScenarioUtils; -import org.matsim.testcases.MatsimTestUtils; +import org.matsim.freight.carriers.Carrier; +import org.matsim.freight.carriers.CarrierCapabilities.FleetSize; +import org.matsim.freight.carriers.CarriersUtils; import org.matsim.smallScaleCommercialTrafficGeneration.TrafficVolumeGeneration.TrafficVolumeKey; +import org.matsim.testcases.MatsimTestUtils; import org.opengis.feature.simple.SimpleFeature; import java.io.File; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.*; +import static org.matsim.smallScaleCommercialTrafficGeneration.SCTUtils.*; + /** * @author Ricardo Ewert * @@ -55,22 +55,18 @@ public class TrafficVolumeGenerationTest { @Test void testTrafficVolumeGenerationCommercialPersonTraffic() throws IOException { - HashMap> landuseCategoriesAndDataConnection = new HashMap<>(); - HashMap>> buildingsPerZone = new HashMap<>(); + Map> landuseCategoriesAndDataConnection = new HashMap<>(); + Map>> buildingsPerZone = new HashMap<>(); Path output = Path.of(utils.getOutputDirectory()); - new File(output.resolve("calculatedData").toString()).mkdir(); + assert(new File(output.resolve("calculatedData").toString()).mkdir()); Path inputDataDirectory = Path.of(utils.getPackageInputDirectory()); String usedLanduseConfiguration = "useExistingDataDistribution"; - Path shapeFileLandusePath = inputDataDirectory.resolve("shp/testLanduse.shp"); - Path shapeFileZonePath = inputDataDirectory.resolve("shp/testZones.shp"); - Path shapeFileBuildingsPath = inputDataDirectory.resolve("shp/testBuildings.shp"); - - HashMap> resultingDataPerZone = LanduseBuildingAnalysis + Map> resultingDataPerZone = LanduseBuildingAnalysis .createInputDataDistribution(output, landuseCategoriesAndDataConnection, - inputDataDirectory, usedLanduseConfiguration, - shapeFileLandusePath, shapeFileZonePath, shapeFileBuildingsPath, null, buildingsPerZone); + inputDataDirectory, usedLanduseConfiguration, + getIndexLanduse(inputDataDirectory), getZoneIndex(inputDataDirectory), getIndexBuildings(inputDataDirectory), buildingsPerZone); String usedTrafficType = "commercialPersonTraffic"; @@ -79,9 +75,9 @@ void testTrafficVolumeGenerationCommercialPersonTraffic() throws IOException { List.of("total")); TrafficVolumeGeneration.setInputParameters(usedTrafficType); - HashMap> trafficVolumePerTypeAndZone_start = TrafficVolumeGeneration + Map> trafficVolumePerTypeAndZone_start = TrafficVolumeGeneration .createTrafficVolume_start(resultingDataPerZone, output, sample, modesORvehTypes, usedTrafficType); - HashMap> trafficVolumePerTypeAndZone_stop = TrafficVolumeGeneration + Map> trafficVolumePerTypeAndZone_stop = TrafficVolumeGeneration .createTrafficVolume_stop(resultingDataPerZone, output, sample, modesORvehTypes, usedTrafficType); Assertions.assertEquals(3, trafficVolumePerTypeAndZone_start.size()); @@ -185,23 +181,18 @@ void testTrafficVolumeGenerationCommercialPersonTraffic() throws IOException { @Test void testTrafficVolumeGenerationGoodsTraffic() throws IOException { - HashMap> landuseCategoriesAndDataConnection = new HashMap<>(); - HashMap>> buildingsPerZone = new HashMap<>(); + Map> landuseCategoriesAndDataConnection = new HashMap<>(); + Map>> buildingsPerZone = new HashMap<>(); Path output = Path.of(utils.getOutputDirectory()); - new File(output.resolve("calculatedData").toString()).mkdir(); + assert(new File(output.resolve("calculatedData").toString()).mkdir()); Path inputDataDirectory = Path.of(utils.getPackageInputDirectory()); String usedLanduseConfiguration = "useExistingDataDistribution"; - Path shapeFileLandusePath = inputDataDirectory.resolve("shp/testLanduse.shp"); - Path shapeFileZonePath = inputDataDirectory.resolve("shp/testZones.shp"); - Path shapeFileBuildingsPath = inputDataDirectory.resolve("shp/testBuildings.shp"); - - HashMap> resultingDataPerZone = LanduseBuildingAnalysis + Map> resultingDataPerZone = LanduseBuildingAnalysis .createInputDataDistribution(output, landuseCategoriesAndDataConnection, - inputDataDirectory, usedLanduseConfiguration, - shapeFileLandusePath, shapeFileZonePath, shapeFileBuildingsPath, null, buildingsPerZone); - + inputDataDirectory, usedLanduseConfiguration, + getIndexLanduse(inputDataDirectory), getZoneIndex(inputDataDirectory), getIndexBuildings(inputDataDirectory), buildingsPerZone); String usedTrafficType = "goodsTraffic"; double sample = 1.; @@ -209,9 +200,9 @@ void testTrafficVolumeGenerationGoodsTraffic() throws IOException { Arrays.asList("vehTyp1", "vehTyp2", "vehTyp3", "vehTyp4", "vehTyp5")); TrafficVolumeGeneration.setInputParameters(usedTrafficType); - HashMap> trafficVolumePerTypeAndZone_start = TrafficVolumeGeneration + Map> trafficVolumePerTypeAndZone_start = TrafficVolumeGeneration .createTrafficVolume_start(resultingDataPerZone, output, sample, modesORvehTypes, usedTrafficType); - HashMap> trafficVolumePerTypeAndZone_stop = TrafficVolumeGeneration + Map> trafficVolumePerTypeAndZone_stop = TrafficVolumeGeneration .createTrafficVolume_stop(resultingDataPerZone, output, sample, modesORvehTypes, usedTrafficType); Assertions.assertEquals(15, trafficVolumePerTypeAndZone_start.size()); @@ -390,7 +381,6 @@ void testAddingExistingScenarios() throws Exception { Path inputDataDirectory = Path.of(utils.getPackageInputDirectory()); Path shapeFileZonePath = inputDataDirectory.resolve("shp/testZones.shp"); - ShpOptions shpZones = new ShpOptions(shapeFileZonePath, null, StandardCharsets.UTF_8); String networkPath = "https://raw.githubusercontent.com/matsim-org/matsim-libs/master/examples/scenarios/freight-chessboard-9x9/grid9x9.xml"; double sample = 1.; Config config = ConfigUtils.createConfig(); @@ -399,9 +389,10 @@ void testAddingExistingScenarios() throws Exception { config.network().setInputCRS("EPSG:4326"); config.setContext(inputDataDirectory.resolve("config.xml").toUri().toURL()); Scenario scenario = ScenarioUtils.loadScenario(config); - HashMap>> buildingsPerZone = new HashMap<>(); - Map, Link>> regionLinksMap = GenerateSmallScaleCommercialTrafficDemand - .filterLinksForZones(scenario, shpZones, SmallScaleCommercialTrafficUtils.getIndexZones(shapeFileZonePath, config.global().getCoordinateSystem()), + Map>> buildingsPerZone = new HashMap<>(); + + Map, Link>> regionLinksMap = GenerateSmallScaleCommercialTrafficDemand + .filterLinksForZones(scenario, SmallScaleCommercialTrafficUtils.getIndexZones(shapeFileZonePath, config.global().getCoordinateSystem()), buildingsPerZone); SmallScaleCommercialTrafficUtils.readExistingModels(scenario, sample, regionLinksMap); @@ -456,7 +447,6 @@ void testAddingExistingScenariosWithSample() throws Exception { Path inputDataDirectory = Path.of(utils.getPackageInputDirectory()); Path shapeFileZonePath = inputDataDirectory.resolve("shp/testZones.shp"); - ShpOptions shpZones = new ShpOptions(shapeFileZonePath, null, StandardCharsets.UTF_8); String networkPath = "https://raw.githubusercontent.com/matsim-org/matsim-libs/master/examples/scenarios/freight-chessboard-9x9/grid9x9.xml"; double sample = 0.2; Config config = ConfigUtils.createConfig(); @@ -465,9 +455,9 @@ void testAddingExistingScenariosWithSample() throws Exception { config.network().setInputCRS("EPSG:4326"); config.setContext(inputDataDirectory.resolve("config.xml").toUri().toURL()); Scenario scenario = ScenarioUtils.loadScenario(config); - HashMap>> buildingsPerZone = new HashMap<>(); - Map, Link>> regionLinksMap = GenerateSmallScaleCommercialTrafficDemand - .filterLinksForZones(scenario, shpZones, SmallScaleCommercialTrafficUtils.getIndexZones(shapeFileZonePath, config.global().getCoordinateSystem()), + Map>> buildingsPerZone = new HashMap<>(); + Map, Link>> regionLinksMap = GenerateSmallScaleCommercialTrafficDemand + .filterLinksForZones(scenario, SmallScaleCommercialTrafficUtils.getIndexZones(shapeFileZonePath, config.global().getCoordinateSystem()), buildingsPerZone); SmallScaleCommercialTrafficUtils.readExistingModels(scenario, sample, regionLinksMap); @@ -504,17 +494,13 @@ void testAddingExistingScenariosWithSample() throws Exception { @Test void testReducingDemandAfterAddingExistingScenarios_goods() throws Exception { - HashMap> landuseCategoriesAndDataConnection = new HashMap<>(); - HashMap>> buildingsPerZone = new HashMap<>(); + Map> landuseCategoriesAndDataConnection = new HashMap<>(); + Map>> buildingsPerZone = new HashMap<>(); Path output = Path.of(utils.getOutputDirectory()); - new File(output.resolve("calculatedData").toString()).mkdir(); + assert(new File(output.resolve("calculatedData").toString()).mkdir()); Path inputDataDirectory = Path.of(utils.getPackageInputDirectory()); String usedLanduseConfiguration = "useExistingDataDistribution"; - Path shapeFileLandusePath = inputDataDirectory.resolve("shp/testLanduse.shp"); - Path shapeFileZonePath = inputDataDirectory.resolve("shp/testZones.shp"); - Path shapeFileBuildingsPath = inputDataDirectory.resolve("shp/testBuildings.shp"); - ShpOptions shpZones = new ShpOptions(shapeFileZonePath, null, StandardCharsets.UTF_8); String networkPath = "https://raw.githubusercontent.com/matsim-org/matsim-libs/master/examples/scenarios/freight-chessboard-9x9/grid9x9.xml"; String usedTrafficType = "goodsTraffic"; double sample = 1.; @@ -528,19 +514,18 @@ void testReducingDemandAfterAddingExistingScenarios_goods() throws Exception { Scenario scenario = ScenarioUtils.loadScenario(config); TrafficVolumeGeneration.setInputParameters(usedTrafficType); - HashMap> resultingDataPerZone = LanduseBuildingAnalysis + Map> resultingDataPerZone = LanduseBuildingAnalysis .createInputDataDistribution(output, landuseCategoriesAndDataConnection, - inputDataDirectory, usedLanduseConfiguration, - shapeFileLandusePath, shapeFileZonePath, shapeFileBuildingsPath, null, buildingsPerZone); + inputDataDirectory, usedLanduseConfiguration, + getIndexLanduse(inputDataDirectory), getZoneIndex(inputDataDirectory), getIndexBuildings(inputDataDirectory), buildingsPerZone); - HashMap> trafficVolumePerTypeAndZone_start = TrafficVolumeGeneration + Map> trafficVolumePerTypeAndZone_start = TrafficVolumeGeneration .createTrafficVolume_start(resultingDataPerZone, output, sample, modesORvehTypes, usedTrafficType); - HashMap> trafficVolumePerTypeAndZone_stop = TrafficVolumeGeneration + Map> trafficVolumePerTypeAndZone_stop = TrafficVolumeGeneration .createTrafficVolume_stop(resultingDataPerZone, output, sample, modesORvehTypes, usedTrafficType); - Map, Link>> regionLinksMap = GenerateSmallScaleCommercialTrafficDemand - .filterLinksForZones(scenario, shpZones, SmallScaleCommercialTrafficUtils.getIndexZones(shapeFileZonePath, config.global().getCoordinateSystem()), - buildingsPerZone); + Map, Link>> regionLinksMap = GenerateSmallScaleCommercialTrafficDemand + .filterLinksForZones(scenario, getZoneIndex(inputDataDirectory), buildingsPerZone); SmallScaleCommercialTrafficUtils.readExistingModels(scenario, sample, regionLinksMap); @@ -664,17 +649,13 @@ void testReducingDemandAfterAddingExistingScenarios_goods() throws Exception { @Test void testReducingDemandAfterAddingExistingScenarios_commercialPersonTraffic() throws Exception { - HashMap> landuseCategoriesAndDataConnection = new HashMap<>(); - HashMap>> buildingsPerZone = new HashMap<>(); + Map> landuseCategoriesAndDataConnection = new HashMap<>(); + Map>> buildingsPerZone = new HashMap<>(); Path output = Path.of(utils.getOutputDirectory()); - new File(output.resolve("calculatedData").toString()).mkdir(); + assert(new File(output.resolve("calculatedData").toString()).mkdir()); Path inputDataDirectory = Path.of(utils.getPackageInputDirectory()); String usedLanduseConfiguration = "useExistingDataDistribution"; - Path shapeFileLandusePath = inputDataDirectory.resolve("shp/testLanduse.shp"); - Path shapeFileZonePath = inputDataDirectory.resolve("shp/testZones.shp"); - Path shapeFileBuildingsPath = inputDataDirectory.resolve("shp/testBuildings.shp"); - ShpOptions shpZones = new ShpOptions(shapeFileZonePath, null, StandardCharsets.UTF_8); String networkPath = "https://raw.githubusercontent.com/matsim-org/matsim-libs/master/examples/scenarios/freight-chessboard-9x9/grid9x9.xml"; String usedTrafficType = "commercialPersonTraffic"; double sample = 1.; @@ -688,19 +669,18 @@ void testReducingDemandAfterAddingExistingScenarios_commercialPersonTraffic() th Scenario scenario = ScenarioUtils.loadScenario(config); TrafficVolumeGeneration.setInputParameters(usedTrafficType); - HashMap> resultingDataPerZone = LanduseBuildingAnalysis + Map> resultingDataPerZone = LanduseBuildingAnalysis .createInputDataDistribution(output, landuseCategoriesAndDataConnection, - inputDataDirectory, usedLanduseConfiguration, - shapeFileLandusePath, shapeFileZonePath, shapeFileBuildingsPath, null, buildingsPerZone); + inputDataDirectory, usedLanduseConfiguration, + getIndexLanduse(inputDataDirectory), getZoneIndex(inputDataDirectory), getIndexBuildings(inputDataDirectory), buildingsPerZone); - HashMap> trafficVolumePerTypeAndZone_start = TrafficVolumeGeneration + Map> trafficVolumePerTypeAndZone_start = TrafficVolumeGeneration .createTrafficVolume_start(resultingDataPerZone, output, sample, modesORvehTypes, usedTrafficType); - HashMap> trafficVolumePerTypeAndZone_stop = TrafficVolumeGeneration + Map> trafficVolumePerTypeAndZone_stop = TrafficVolumeGeneration .createTrafficVolume_stop(resultingDataPerZone, output, sample, modesORvehTypes, usedTrafficType); - Map, Link>> regionLinksMap = GenerateSmallScaleCommercialTrafficDemand - .filterLinksForZones(scenario, shpZones, SmallScaleCommercialTrafficUtils.getIndexZones(shapeFileZonePath, config.global().getCoordinateSystem()), - buildingsPerZone); + Map, Link>> regionLinksMap = GenerateSmallScaleCommercialTrafficDemand + .filterLinksForZones(scenario, getZoneIndex(inputDataDirectory), buildingsPerZone); SmallScaleCommercialTrafficUtils.readExistingModels(scenario, sample, regionLinksMap); diff --git a/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/TripDistributionMatrixTest.java b/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/TripDistributionMatrixTest.java index 0c8f2522a37..adc41f61191 100644 --- a/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/TripDistributionMatrixTest.java +++ b/contribs/application/src/test/java/org/matsim/smallScaleCommercialTrafficGeneration/TripDistributionMatrixTest.java @@ -26,17 +26,18 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; -import org.matsim.application.options.ShpOptions; import org.matsim.core.network.NetworkUtils; +import org.matsim.smallScaleCommercialTrafficGeneration.TrafficVolumeGeneration.TrafficVolumeKey; import org.matsim.testcases.MatsimTestUtils; import org.opengis.feature.simple.SimpleFeature; -import org.matsim.smallScaleCommercialTrafficGeneration.TrafficVolumeGeneration.TrafficVolumeKey; + import java.io.File; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.*; +import static org.matsim.smallScaleCommercialTrafficGeneration.SCTUtils.*; + /** * @author Ricardo Ewert * @@ -49,40 +50,35 @@ public class TripDistributionMatrixTest { @Test void testTripDistributionCommercialPersonTrafficTraffic() throws IOException { - HashMap> landuseCategoriesAndDataConnection = new HashMap>(); - HashMap>> buildingsPerZone = new HashMap<>(); + Map> landuseCategoriesAndDataConnection = new HashMap<>(); + Map>> buildingsPerZone = new HashMap<>(); Path output = Path.of(utils.getOutputDirectory()); - new File(output.resolve("calculatedData").toString()).mkdir(); + assert(new File(output.resolve("calculatedData").toString()).mkdir()); Path inputDataDirectory = Path.of(utils.getPackageInputDirectory()); String usedLanduseConfiguration = "useExistingDataDistribution"; - Path shapeFileLandusePath = inputDataDirectory.resolve("shp/testLanduse.shp"); - Path shapeFileZonePath = inputDataDirectory.resolve("shp/testZones.shp"); - Path shapeFileBuildingsPath = inputDataDirectory.resolve("shp/testBuildings.shp"); String networkLocation = "https://raw.githubusercontent.com/matsim-org/matsim-libs/master/examples/scenarios/freight-chessboard-9x9/grid9x9.xml"; - ShpOptions shpZones = new ShpOptions(shapeFileZonePath, null, StandardCharsets.UTF_8); Network network = NetworkUtils.readNetwork(networkLocation); - HashMap> resultingDataPerZone = LanduseBuildingAnalysis + Map> resultingDataPerZone = LanduseBuildingAnalysis .createInputDataDistribution(output, landuseCategoriesAndDataConnection, - inputDataDirectory, usedLanduseConfiguration, - shapeFileLandusePath, shapeFileZonePath, shapeFileBuildingsPath, null, buildingsPerZone); + inputDataDirectory, usedLanduseConfiguration, + getIndexLanduse(inputDataDirectory), getZoneIndex(inputDataDirectory), getIndexBuildings(inputDataDirectory), buildingsPerZone); String usedTrafficType = "commercialPersonTraffic"; double sample = 1.; double resistanceFactor = 0.005; - ArrayList modesORvehTypes = new ArrayList( - List.of("total")); + List modesORvehTypes = new ArrayList<>(List.of("total")); TrafficVolumeGeneration.setInputParameters(usedTrafficType); - HashMap> trafficVolumePerTypeAndZone_start = TrafficVolumeGeneration + Map> trafficVolumePerTypeAndZone_start = TrafficVolumeGeneration .createTrafficVolume_start(resultingDataPerZone, output, sample, modesORvehTypes, usedTrafficType); - HashMap> trafficVolumePerTypeAndZone_stop = TrafficVolumeGeneration + Map> trafficVolumePerTypeAndZone_stop = TrafficVolumeGeneration .createTrafficVolume_stop(resultingDataPerZone, output, sample, modesORvehTypes, usedTrafficType); final TripDistributionMatrix odMatrix = TripDistributionMatrix.Builder - .newInstance(shpZones, trafficVolumePerTypeAndZone_start, trafficVolumePerTypeAndZone_stop, usedTrafficType).build(); + .newInstance(getZoneIndex(inputDataDirectory), trafficVolumePerTypeAndZone_start, trafficVolumePerTypeAndZone_stop, usedTrafficType).build(); - Map, Link>> regionLinksMap = new HashMap<>(); + Map, Link>> regionLinksMap = new HashMap<>(); regionLinksMap.put("testArea1_area1", new HashMap<>()); regionLinksMap.get("testArea1_area1").put(Id.createLinkId("i(8,6)"), network.getLinks().get(Id.createLinkId("i(8,6)"))); regionLinksMap.put("testArea1_area2", new HashMap<>()); @@ -139,23 +135,19 @@ void testTripDistributionCommercialPersonTrafficTraffic() throws IOException { @Test void testTripDistributionGoodsTraffic() throws IOException { - HashMap> landuseCategoriesAndDataConnection = new HashMap>(); - HashMap>> buildingsPerZone = new HashMap<>(); + Map> landuseCategoriesAndDataConnection = new HashMap<>(); + Map>> buildingsPerZone = new HashMap<>(); Path output = Path.of(utils.getOutputDirectory()); - new File(output.resolve("calculatedData").toString()).mkdir(); + assert(new File(output.resolve("calculatedData").toString()).mkdir()); Path inputDataDirectory = Path.of(utils.getPackageInputDirectory()); String usedLanduseConfiguration = "useExistingDataDistribution"; - Path shapeFileLandusePath = inputDataDirectory.resolve("shp/testLanduse.shp"); - Path shapeFileZonePath = inputDataDirectory.resolve("shp/testZones.shp"); - Path shapeFileBuildingsPath = inputDataDirectory.resolve("shp/testBuildings.shp"); String networkLocation = "https://raw.githubusercontent.com/matsim-org/matsim-libs/master/examples/scenarios/freight-chessboard-9x9/grid9x9.xml"; - ShpOptions shpZones = new ShpOptions(shapeFileZonePath, null, StandardCharsets.UTF_8); Network network = NetworkUtils.readNetwork(networkLocation); - HashMap> resultingDataPerZone = LanduseBuildingAnalysis + Map> resultingDataPerZone = LanduseBuildingAnalysis .createInputDataDistribution(output, landuseCategoriesAndDataConnection, - inputDataDirectory, usedLanduseConfiguration, - shapeFileLandusePath, shapeFileZonePath, shapeFileBuildingsPath, null, buildingsPerZone); + inputDataDirectory, usedLanduseConfiguration, + getIndexLanduse(inputDataDirectory), getZoneIndex(inputDataDirectory), getIndexBuildings(inputDataDirectory), buildingsPerZone); String usedTrafficType = "goodsTraffic"; double sample = 1.; @@ -165,14 +157,14 @@ void testTripDistributionGoodsTraffic() throws IOException { Arrays.asList("vehTyp1", "vehTyp2", "vehTyp3", "vehTyp4", "vehTyp5")); TrafficVolumeGeneration.setInputParameters(usedTrafficType); - HashMap> trafficVolumePerTypeAndZone_start = TrafficVolumeGeneration + Map> trafficVolumePerTypeAndZone_start = TrafficVolumeGeneration .createTrafficVolume_start(resultingDataPerZone, output, sample, modesORvehTypes, usedTrafficType); - HashMap> trafficVolumePerTypeAndZone_stop = TrafficVolumeGeneration + Map> trafficVolumePerTypeAndZone_stop = TrafficVolumeGeneration .createTrafficVolume_stop(resultingDataPerZone, output, sample, modesORvehTypes, usedTrafficType); final TripDistributionMatrix odMatrix = TripDistributionMatrix.Builder - .newInstance(shpZones, trafficVolumePerTypeAndZone_start, trafficVolumePerTypeAndZone_stop, usedTrafficType).build(); + .newInstance(getZoneIndex(inputDataDirectory), trafficVolumePerTypeAndZone_start, trafficVolumePerTypeAndZone_stop, usedTrafficType).build(); - Map, Link>> regionLinksMap = new HashMap<>(); + Map, Link>> regionLinksMap = new HashMap<>(); regionLinksMap.put("testArea1_area1", new HashMap<>()); regionLinksMap.get("testArea1_area1").put(Id.createLinkId("i(8,6)"), network.getLinks().get(Id.createLinkId("i(8,6)"))); regionLinksMap.put("testArea1_area2", new HashMap<>()); diff --git a/contribs/decongestion/pom.xml b/contribs/decongestion/pom.xml index f95fa91552d..42c6ad098c0 100644 --- a/contribs/decongestion/pom.xml +++ b/contribs/decongestion/pom.xml @@ -4,7 +4,15 @@ contrib 16.0-SNAPSHOT - 4.0.0 + + + org.matsim.contrib + otfvis + ${parent.version} + test + + + 4.0.0 org.matsim.contrib decongestion decongestion diff --git a/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionModule.java b/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionModule.java index a6afea61fd6..b8129dd901c 100644 --- a/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionModule.java +++ b/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionModule.java @@ -19,12 +19,15 @@ package org.matsim.contrib.decongestion; -import org.matsim.api.core.v01.Scenario; +import com.google.inject.Inject; +import com.google.inject.Singleton; +import org.matsim.api.core.v01.TransportMode; import org.matsim.contrib.decongestion.data.DecongestionInfo; import org.matsim.contrib.decongestion.handler.DelayAnalysis; import org.matsim.contrib.decongestion.handler.IntervalBasedTolling; import org.matsim.contrib.decongestion.handler.IntervalBasedTollingAll; import org.matsim.contrib.decongestion.handler.PersonVehicleTracker; +import org.matsim.contrib.decongestion.routing.TollTimeDistanceTravelDisutilityFactory; import org.matsim.contrib.decongestion.tollSetting.DecongestionTollSetting; import org.matsim.contrib.decongestion.tollSetting.DecongestionTollingBangBang; import org.matsim.contrib.decongestion.tollSetting.DecongestionTollingPID; @@ -37,51 +40,46 @@ public class DecongestionModule extends AbstractModule { - private final DecongestionConfigGroup decongestionConfigGroup; - - public DecongestionModule(Scenario scenario) { - this.decongestionConfigGroup = (DecongestionConfigGroup) scenario.getConfig().getModules().get(DecongestionConfigGroup.GROUP_NAME); - } + @Inject private DecongestionConfigGroup decongestionConfigGroup; @Override public void install() { if (decongestionConfigGroup.isEnableDecongestionPricing()) { - switch( decongestionConfigGroup.getDecongestionApproach() ) { - case BangBang: - this.bind(DecongestionTollingBangBang.class).asEagerSingleton(); - this.bind(DecongestionTollSetting.class).to(DecongestionTollingBangBang.class); - break; - case PID: - this.bind(DecongestionTollingPID.class).asEagerSingleton(); - this.bind(DecongestionTollSetting.class).to(DecongestionTollingPID.class); - this.addEventHandlerBinding().to(DecongestionTollingPID.class); - break; - case P_MC: - this.bind(DecongestionTollingP_MCP.class).asEagerSingleton(); - this.bind(DecongestionTollSetting.class).to(DecongestionTollingP_MCP.class); - this.addEventHandlerBinding().to(DecongestionTollingP_MCP.class); - break; - default: - throw new RuntimeException("not implemented") ; + switch( decongestionConfigGroup.getDecongestionApproach() ){ + case BangBang -> { + this.bind( DecongestionTollingBangBang.class ).in( Singleton.class ); + this.bind( DecongestionTollSetting.class ).to( DecongestionTollingBangBang.class ); + } + case PID -> { + this.bind( DecongestionTollingPID.class ).in( Singleton.class ); + this.bind( DecongestionTollSetting.class ).to( DecongestionTollingPID.class ); + this.addEventHandlerBinding().to( DecongestionTollingPID.class ); + } + case P_MC -> { + this.bind( DecongestionTollingP_MCP.class ).in( Singleton.class ); + this.bind( DecongestionTollSetting.class ).to( DecongestionTollingP_MCP.class ); + this.addEventHandlerBinding().to( DecongestionTollingP_MCP.class ); + } + default -> throw new RuntimeException( "not implemented" ); } } else { // no pricing } - this.bind(DecongestionInfo.class).asEagerSingleton(); + addTravelDisutilityFactoryBinding( TransportMode.car ).to( TollTimeDistanceTravelDisutilityFactory.class ); + + this.bind(DecongestionInfo.class).in( Singleton.class ); - this.bind(IntervalBasedTollingAll.class).asEagerSingleton(); - this.bind(IntervalBasedTolling.class).to(IntervalBasedTollingAll.class); - this.addEventHandlerBinding().to(IntervalBasedTollingAll.class); + this.bind(IntervalBasedTolling.class).to(IntervalBasedTollingAll.class).in( Singleton.class ); + this.addEventHandlerBinding().to(IntervalBasedTolling.class); - this.bind(DelayAnalysis.class).asEagerSingleton(); - this.addEventHandlerBinding().to(DelayAnalysis.class); + this.addEventHandlerBinding().to(DelayAnalysis.class).in( Singleton.class ); - this.addEventHandlerBinding().to(PersonVehicleTracker.class).asEagerSingleton(); + this.addEventHandlerBinding().to(PersonVehicleTracker.class).in( Singleton.class ); - this.addControlerListenerBinding().to(DecongestionControlerListener.class); + this.addControlerListenerBinding().to(DecongestionControlerListener.class).in( Singleton.class ); } } diff --git a/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/routing/TollTimeDistanceTravelDisutility.java b/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/routing/TollTimeDistanceTravelDisutility.java index f4036b3e1a0..1ad6ad0f479 100644 --- a/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/routing/TollTimeDistanceTravelDisutility.java +++ b/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/routing/TollTimeDistanceTravelDisutility.java @@ -39,7 +39,7 @@ * * @author ikaddoura */ -public final class TollTimeDistanceTravelDisutility implements TravelDisutility { +final class TollTimeDistanceTravelDisutility implements TravelDisutility { private static final Logger log = LogManager.getLogger(TollTimeDistanceTravelDisutility.class); private final TravelDisutility delegate; diff --git a/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionRunExample.java b/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/run/DecongestionRunExample.java similarity index 82% rename from contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionRunExample.java rename to contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/run/DecongestionRunExample.java index 72aca4c0fa7..28ea4b3cfa5 100644 --- a/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionRunExample.java +++ b/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/run/DecongestionRunExample.java @@ -21,7 +21,7 @@ /** * */ -package org.matsim.contrib.decongestion; +package org.matsim.contrib.decongestion.run; import java.io.IOException; @@ -29,14 +29,16 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Scenario; +import org.matsim.api.core.v01.TransportMode; +import org.matsim.contrib.decongestion.DecongestionConfigGroup; import org.matsim.contrib.decongestion.DecongestionConfigGroup.DecongestionApproach; import org.matsim.contrib.decongestion.DecongestionConfigGroup.IntegralApproach; +import org.matsim.contrib.decongestion.DecongestionModule; import org.matsim.contrib.decongestion.routing.TollTimeDistanceTravelDisutilityFactory; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; -import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.scenario.ScenarioUtils; /** @@ -70,7 +72,10 @@ public static void main(String[] args) throws IOException { private void run() { - final DecongestionConfigGroup decongestionSettings = new DecongestionConfigGroup(); + Config config = ConfigUtils.loadConfig(configFile); + + final DecongestionConfigGroup decongestionSettings = ConfigUtils.addOrGetModule( config, DecongestionConfigGroup.class ); + decongestionSettings.setToleratedAverageDelaySec(30.); decongestionSettings.setFractionOfIterationsToEndPriceAdjustment(1.0); decongestionSettings.setFractionOfIterationsToStartPriceAdjustment(0.0); @@ -92,32 +97,29 @@ private void run() { // decongestionSettings.setTOLL_ADJUSTMENT(1.0); // decongestionSettings.setINITIAL_TOLL(1.0); - Config config = ConfigUtils.loadConfig(configFile); - config.addModule(decongestionSettings); + + // --- final Scenario scenario = ScenarioUtils.loadScenario(config); - Controler controler = new Controler(scenario); - // ############################################################# + // --- - // congestion toll computation + Controler controler = new Controler(scenario); - controler.addOverridingModule(new DecongestionModule(scenario)); + // congestion toll computation + controler.addOverridingModule(new DecongestionModule() ); // toll-adjusted routing - controler.addOverridingModule(new AbstractModule(){ @Override public void install() { - final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); - this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); + addTravelDisutilityFactoryBinding( TransportMode.car ).toInstance( new TollTimeDistanceTravelDisutilityFactory() ); + // yyyy try if this could add the class instead of the instance. possibly as singleton. kai, jan'24 + } }); - // ############################################################# - - controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists); - controler.run(); + controler.run(); } } diff --git a/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionRunExampleFromConfig.java b/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/run/DecongestionRunExampleFromConfig.java similarity index 77% rename from contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionRunExampleFromConfig.java rename to contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/run/DecongestionRunExampleFromConfig.java index 339c6fff079..7bfe040d503 100644 --- a/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/DecongestionRunExampleFromConfig.java +++ b/contribs/decongestion/src/main/java/org/matsim/contrib/decongestion/run/DecongestionRunExampleFromConfig.java @@ -21,7 +21,7 @@ /** * */ -package org.matsim.contrib.decongestion; +package org.matsim.contrib.decongestion.run; import java.io.IOException; @@ -29,12 +29,14 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Scenario; +import org.matsim.api.core.v01.TransportMode; +import org.matsim.contrib.decongestion.DecongestionConfigGroup; +import org.matsim.contrib.decongestion.DecongestionModule; import org.matsim.contrib.decongestion.routing.TollTimeDistanceTravelDisutilityFactory; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; -import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.scenario.ScenarioUtils; /** @@ -64,34 +66,27 @@ public static void main(String[] args) throws IOException { main.run(); } - private void run() throws IOException { + private void run() { - Config config = ConfigUtils.loadConfig(configFile, new DecongestionConfigGroup()); + Config config = ConfigUtils.loadConfig(configFile, new DecongestionConfigGroup() ); final Scenario scenario = ScenarioUtils.loadScenario(config); - Controler controler = new Controler(scenario); - // ############################################################# + Controler controler = new Controler(scenario); // congestion toll computation - - controler.addOverridingModule(new DecongestionModule(scenario)); + controler.addOverridingModule(new DecongestionModule() ); // toll-adjusted routing - - final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); - - controler.addOverridingModule(new AbstractModule(){ + controler.addOverridingModule(new AbstractModule(){ @Override public void install() { - this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); + addTravelDisutilityFactoryBinding( TransportMode.car ).toInstance( new TollTimeDistanceTravelDisutilityFactory() ); + // yyyy try if this could add the class instead of the instance. possibly as singleton. kai, jan'24 } }); - // ############################################################# - - controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists); - controler.run(); + controler.run(); } } diff --git a/contribs/decongestion/src/test/java/org/matsim/contrib/decongestion/DecongestionPricingTestIT.java b/contribs/decongestion/src/test/java/org/matsim/contrib/decongestion/DecongestionPricingTestIT.java index 2562177bd77..ee68e87271b 100644 --- a/contribs/decongestion/src/test/java/org/matsim/contrib/decongestion/DecongestionPricingTestIT.java +++ b/contribs/decongestion/src/test/java/org/matsim/contrib/decongestion/DecongestionPricingTestIT.java @@ -28,8 +28,12 @@ import org.matsim.analysis.ScoreStatsControlerListener.ScoreItem; 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.population.Population; import org.matsim.contrib.decongestion.DecongestionConfigGroup.DecongestionApproach; import org.matsim.contrib.decongestion.data.DecongestionInfo; +import org.matsim.contrib.decongestion.data.LinkInfo; import org.matsim.contrib.decongestion.handler.DelayAnalysis; import org.matsim.contrib.decongestion.handler.IntervalBasedTolling; import org.matsim.contrib.decongestion.handler.IntervalBasedTollingAll; @@ -43,9 +47,14 @@ import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; +import org.matsim.core.router.util.TravelTime; import org.matsim.core.scenario.ScenarioUtils; +import org.matsim.core.utils.io.IOUtils; +import org.matsim.examples.ExamplesUtils; import org.matsim.testcases.MatsimTestUtils; +import java.net.URL; + /** * * @@ -114,21 +123,18 @@ public void install() { // toll-adjusted routing - final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); - - controler.addOverridingModule(new AbstractModule(){ + controler.addOverridingModule(new AbstractModule(){ @Override public void install() { - this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); + addTravelDisutilityFactoryBinding( TransportMode.car ).toInstance( new TollTimeDistanceTravelDisutilityFactory() ); } }); - controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - controler.run(); + controler.run(); - double tt0 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 6 * 3600 + 50. * 60, null, null); - double tt1 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 63, null, null); - double tt2 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 15. * 60, null, null); + double tt0 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 6 * 3600 + 50. * 60, null, null); + double tt1 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 63, null, null); + double tt2 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 15. * 60, null, null); Assertions.assertEquals(100.0, tt0, MatsimTestUtils.EPSILON, "Wrong travel time. The run output seems to have changed."); Assertions.assertEquals(150.5, tt1, MatsimTestUtils.EPSILON, "Wrong travel time. The run output seems to have changed."); @@ -138,8 +144,8 @@ public void install() { double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get(index); Assertions.assertEquals(-33.940316666666666, avgScore, MatsimTestUtils.EPSILON, "Wrong average executed score. The tolls seem to have changed."); - System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().toString()); - System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().toString()); + System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().toString()); + System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().toString()); Assertions.assertEquals(50.5, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().get(84), MatsimTestUtils.EPSILON, "Wrong average delay (capacity is set in a way that one of the two agents has to wait 101 sec. Thus the average is 50.5"); Assertions.assertEquals(50.5 * 0.0123, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().get(84), MatsimTestUtils.EPSILON, "Wrong toll."); @@ -155,14 +161,14 @@ final void test0amodified() { System.out.println(testUtils.getPackageInputDirectory()); - final String configFile = testUtils.getPackageInputDirectory() + "/config0.xml"; + // --- - Config config = ConfigUtils.loadConfig(configFile); + Config config = ConfigUtils.loadConfig( testUtils.getPackageInputDirectory() + "/config0.xml" ); - String outputDirectory = testUtils.getOutputDirectory() + "/"; - config.controller().setOutputDirectory(outputDirectory); + config.controller().setOutputDirectory( testUtils.getOutputDirectory() ); + + final DecongestionConfigGroup decongestionSettings = ConfigUtils.addOrGetModule( config, DecongestionConfigGroup.class ); - final DecongestionConfigGroup decongestionSettings = new DecongestionConfigGroup(); decongestionSettings.setWriteOutputIteration(1); decongestionSettings.setKp(0.0123); decongestionSettings.setKd(0.0); @@ -171,31 +177,34 @@ final void test0amodified() { decongestionSettings.setTollBlendFactor(1.0); decongestionSettings.setFractionOfIterationsToEndPriceAdjustment(1.0); decongestionSettings.setFractionOfIterationsToStartPriceAdjustment(0.0); - config.addModule(decongestionSettings); + + // --- final Scenario scenario = ScenarioUtils.loadScenario(config); + + // --- + Controler controler = new Controler(scenario); // congestion toll computation - controler.addOverridingModule(new DecongestionModule(scenario)); + controler.addOverridingModule(new DecongestionModule() ); // toll-adjusted routing - final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); - - controler.addOverridingModule(new AbstractModule(){ + controler.addOverridingModule(new AbstractModule(){ @Override public void install() { - this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); + addTravelDisutilityFactoryBinding( TransportMode.car ).toInstance( new TollTimeDistanceTravelDisutilityFactory() ); } }); - controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - controler.run(); + controler.run(); + + // --- - double tt0 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 6 * 3600 + 50. * 60, null, null); - double tt1 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 63, null, null); - double tt2 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 15. * 60, null, null); + double tt0 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 6 * 3600 + 50. * 60, null, null); + double tt1 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 63, null, null); + double tt2 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 15. * 60, null, null); Assertions.assertEquals(100.0, tt0, MatsimTestUtils.EPSILON, "Wrong travel time. The run output seems to have changed."); Assertions.assertEquals(150.5, tt1, MatsimTestUtils.EPSILON, "Wrong travel time. The run output seems to have changed."); @@ -206,6 +215,114 @@ public void install() { Assertions.assertEquals(-33.940316666666666, avgScore, MatsimTestUtils.EPSILON, "Wrong average executed score. The tolls seem to have changed."); } + /** + * Kp = 0.0123, other syntax, kn + * + */ + @Test + final void test0amodifiedKn() { + + URL configUrl = IOUtils.extendUrl( ExamplesUtils.getTestScenarioURL( "equil" ), "config.xml" ); + + Config config = ConfigUtils.loadConfig( configUrl ); + config.controller().setOutputDirectory( testUtils.getOutputDirectory() ); + + config.plans().setInputFile( "plans2000.xml.gz" ); + // (in my first attempts, the default plans file had too few agents. after my later changes, it may no longer be necessary to use this file here. kai, jan'23) + + config.controller().setLastIteration( 20 ); + // (need some iterations for the decongestion to unfold. 20 may be more than really needed. kai, jan'23) + + final DecongestionConfigGroup decongestionSettings = ConfigUtils.addOrGetModule( config, DecongestionConfigGroup.class ); + + decongestionSettings.setWriteOutputIteration(1); +// decongestionSettings.setKp(0.0123); + decongestionSettings.setKp(0.123); + decongestionSettings.setKd(0.0); + decongestionSettings.setKi(0.0); + decongestionSettings.setMsa(false); + decongestionSettings.setTollBlendFactor(1.0); + decongestionSettings.setFractionOfIterationsToEndPriceAdjustment(1.0); + decongestionSettings.setFractionOfIterationsToStartPriceAdjustment(0.0); + + // === + + final Scenario scenario = ScenarioUtils.loadScenario(config); + + Network network = scenario.getNetwork(); + + // make middle link faster + network.getLinks().get( Id.createLinkId( "6" )).setFreespeed( 100. ); + + // make alternative wider + network.getLinks().get( Id.createLinkId( "14" ) ).setCapacity( 100000. ); + + // increase some other capacities: + network.getLinks().get( Id.createLinkId( "5" ) ).setCapacity( 100000. ); + network.getLinks().get( Id.createLinkId( "6" ) ).setCapacity( 100000. ); + + // remove all other alternatives: + network.removeLink( Id.createLinkId( "11" ) ); + network.removeLink( Id.createLinkId( "12" ) ); + network.removeLink( Id.createLinkId( "13" ) ); + network.removeLink( Id.createLinkId( "16" ) ); + network.removeLink( Id.createLinkId( "17" ) ); + network.removeLink( Id.createLinkId( "18" ) ); + network.removeLink( Id.createLinkId( "19" ) ); + + network.removeLink( Id.createLinkId( "2" ) ); + network.removeLink( Id.createLinkId( "3" ) ); + network.removeLink( Id.createLinkId( "4" ) ); + network.removeLink( Id.createLinkId( "7" ) ); + network.removeLink( Id.createLinkId( "8" ) ); + network.removeLink( Id.createLinkId( "9" ) ); + network.removeLink( Id.createLinkId( "10" ) ); + + // --- + + Population population = scenario.getPopulation(); + + // remove 3/4 of the population to reduce computation time: + for ( int ii=500; ii<2000; ii++ ){ + population.removePerson( Id.createPersonId( ii ) ); + } + + + // --- + + Controler controler = new Controler(scenario); + + controler.addOverridingModule(new DecongestionModule() ); + +// controler.addOverridingModule( new OTFVisLiveModule() ); + + controler.run(); + + // === + + DecongestionInfo info = controler.getInjector().getInstance( DecongestionInfo.class ); + + final LinkInfo linkInfo = info.getlinkInfos().get( Id.createLinkId( "15" ) ); + if ( linkInfo!= null ){ + System.out.println( linkInfo.getTime2toll().toString() ); + } + + final TravelTime linkTravelTimes = controler.getLinkTravelTimes(); + double tt0a = linkTravelTimes.getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("15" ) ), 6 * 3600-1 , null, null ); + double tt0b = linkTravelTimes.getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("15" ) ), 6 * 3600 , null, null ); + double tt0c = linkTravelTimes.getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("15" ) ), 6 * 3600+15*60 , null, null ); + double tt1 = linkTravelTimes.getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("14" ) ), 6 * 3600, null, null ); + + System.err.println( tt0a + " " + tt0b + " " + tt0c ); + System.err.println( tt1 ); + + Assertions.assertEquals(179.985, tt0a, MatsimTestUtils.EPSILON, "Wrong travel time. The run output seems to have changed."); + Assertions.assertEquals(344.04, tt0b, MatsimTestUtils.EPSILON, "Wrong travel time. The run output seems to have changed."); + Assertions.assertEquals(179.985, tt0c, MatsimTestUtils.EPSILON, "Wrong travel time. The run output seems to have changed."); + Assertions.assertEquals(180.0, tt1, MatsimTestUtils.EPSILON, "Wrong travel time. The run output seems to have changed."); + + } + /** * Kp = 2 * @@ -265,19 +382,21 @@ public void install() { final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); - controler.addOverridingModule(new AbstractModule(){ + controler.addOverridingModule(new AbstractModule(){ @Override public void install() { - this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); + addTravelDisutilityFactoryBinding( TransportMode.car ).toInstance( travelDisutilityFactory ); } }); controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - controler.run(); + controler.run(); + + // === - double tt0 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 6 * 3600 + 50. * 60, null, null); - double tt1 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 63, null, null); - double tt2 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 15. * 60, null, null); + double tt0 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 6 * 3600 + 50. * 60, null, null); + double tt1 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 63, null, null); + double tt2 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 15. * 60, null, null); Assertions.assertEquals(100.0, tt0, MatsimTestUtils.EPSILON, "Wrong travel time. The run output seems to have changed."); Assertions.assertEquals(150.5, tt1, MatsimTestUtils.EPSILON, "Wrong travel time. The run output seems to have changed."); @@ -287,8 +406,8 @@ public void install() { double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get(index); Assertions.assertEquals(-134.31916666666666, avgScore, MatsimTestUtils.EPSILON, "Wrong average executed score. The tolls seem to have changed."); - System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().toString()); - System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().toString()); + System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().toString()); + System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().toString()); Assertions.assertEquals(50.5, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().get(84), MatsimTestUtils.EPSILON, "Wrong average delay (capacity is set in a way that one of the two agents has to wait 101 sec. Thus the average is 50.5"); Assertions.assertEquals(50.5 * 2, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().get(84), MatsimTestUtils.EPSILON, "Wrong toll."); @@ -325,25 +444,25 @@ final void test0bmodified() { Controler controler = new Controler(scenario); // congestion toll computation - controler.addOverridingModule(new DecongestionModule(scenario)); + controler.addOverridingModule(new DecongestionModule() ); // toll-adjusted routing final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); - controler.addOverridingModule(new AbstractModule(){ + controler.addOverridingModule(new AbstractModule(){ @Override public void install() { - this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); + addTravelDisutilityFactoryBinding( TransportMode.car ).toInstance( travelDisutilityFactory ); } }); controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - controler.run(); + controler.run(); - double tt0 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 6 * 3600 + 50. * 60, null, null); - double tt1 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 63, null, null); - double tt2 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 15. * 60, null, null); + double tt0 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 6 * 3600 + 50. * 60, null, null); + double tt1 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 63, null, null); + double tt2 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 15. * 60, null, null); Assertions.assertEquals(100.0, tt0, MatsimTestUtils.EPSILON, "Wrong travel time. The run output seems to have changed."); Assertions.assertEquals(150.5, tt1, MatsimTestUtils.EPSILON, "Wrong travel time. The run output seems to have changed."); @@ -405,7 +524,7 @@ public void install() { final TollTimeDistanceTravelDisutilityFactory travelDisutilityFactory = new TollTimeDistanceTravelDisutilityFactory(); - controler.addOverridingModule(new AbstractModule(){ + controler.addOverridingModule(new AbstractModule(){ @Override public void install() { this.bindCarTravelDisutilityFactory().toInstance( travelDisutilityFactory ); @@ -413,11 +532,11 @@ public void install() { }); controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - controler.run(); + controler.run(); - double tt0 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 6 * 3600 + 50. * 60, null, null); - double tt1 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 63, null, null); - double tt2 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 15. * 60, null, null); + double tt0 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 6 * 3600 + 50. * 60, null, null); + double tt1 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 63, null, null); + double tt2 = controler.getLinkTravelTimes().getLinkTravelTime(scenario.getNetwork().getLinks().get(Id.createLinkId("link12")), 7 * 3600 + 15. * 60, null, null); Assertions.assertEquals(100.0, tt0, MatsimTestUtils.EPSILON, "Wrong travel time. The run output seems to have changed."); Assertions.assertEquals(150.5, tt1, MatsimTestUtils.EPSILON, "Wrong travel time. The run output seems to have changed."); @@ -427,8 +546,8 @@ public void install() { double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get(index); Assertions.assertEquals(-33.31916666666666, avgScore, MatsimTestUtils.EPSILON, "Wrong average executed score. The tolls seem to have changed."); - System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().toString()); - System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().toString()); + System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().toString()); + System.out.println(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().toString()); Assertions.assertEquals(50.5, info.getlinkInfos().get(Id.createLinkId("link12")).getTime2avgDelay().get(84), MatsimTestUtils.EPSILON, "Wrong average delay (capacity is set in a way that one of the two agents has to wait 101 sec. Thus the average is 50.5"); Assertions.assertNull(info.getlinkInfos().get(Id.createLinkId("link12")).getTime2toll().get(84), "Wrong toll."); @@ -505,11 +624,9 @@ final void test2() { System.out.println(testUtils.getPackageInputDirectory()); - final String configFile = testUtils.getPackageInputDirectory() + "/config.xml"; - Config config = ConfigUtils.loadConfig(configFile); + Config config = ConfigUtils.loadConfig( testUtils.getPackageInputDirectory() + "/config.xml" ); - String outputDirectory = testUtils.getOutputDirectory() + "/"; - config.controller().setOutputDirectory(outputDirectory); + config.controller().setOutputDirectory( testUtils.getOutputDirectory() ); final DecongestionConfigGroup decongestionSettings = new DecongestionConfigGroup(); decongestionSettings.setWriteOutputIteration(1); @@ -545,9 +662,9 @@ public void install() { } }); - controler.getConfig().controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); - controler.run(); + controler.run(); + // --- final int index = config.controller().getLastIteration() - config.controller().getFirstIteration(); double avgScore = controler.getScoreStats().getScoreHistory().get( ScoreItem.executed ).get( index ) ; diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/companions/DrtCompanionRideGenerator.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/companions/DrtCompanionRideGenerator.java index 5ed8926f465..66f552ee730 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/companions/DrtCompanionRideGenerator.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/companions/DrtCompanionRideGenerator.java @@ -25,7 +25,6 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; -import java.util.UUID; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -88,6 +87,7 @@ private void installSampler(DrtWithExtensionsConfigGroup drtWithExtensionsConfig } void addCompanionAgents() { + int identifier = 0; HashMap drtCompanionAgents = new HashMap<>(); Collection companions = new ArrayList<>(); for (Person person : this.scenario.getPopulation().getPersons().values()) { @@ -105,7 +105,8 @@ void addCompanionAgents() { int groupPart = i; companions.add(createCompanionAgent(mainMode, person, trip, trip.getOriginActivity(), - trip.getDestinationActivity(), groupPart, groupSize)); + trip.getDestinationActivity(), groupPart, groupSize, identifier)); + identifier++; } } } @@ -121,9 +122,9 @@ void addCompanionAgents() { } private Person createCompanionAgent(String drtMode, Person originalPerson, TripStructureUtils.Trip trip, - Activity fromActivity, Activity toActivity, int groupPart, int groupSize) { + Activity fromActivity, Activity toActivity, int groupPart, int groupSize, int identifier) { String prefix = getCompanionPrefix(drtMode); - String companionId = prefix + "_" + originalPerson.getId().toString() + "_" + UUID.randomUUID(); + String companionId = prefix + "_" + originalPerson.getId().toString() + "_" + identifier; Person person = PopulationUtils.getFactory().createPerson(Id.createPersonId(companionId)); DrtCompanionUtils.setDRTCompanionType(person, DRT_COMPANION_TYPE); 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 a6619dbff3c..e18008e4ce5 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 @@ -53,6 +53,11 @@ public EDrtShiftDispatcherImpl(EShiftTaskScheduler shiftTaskScheduler, ChargingI this.fleet = fleet; } + @Override + public void initialize() { + delegate.initialize(); + } + @Override public void dispatch(double timeStep) { delegate.dispatch(timeStep); 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 8f625fdb18e..ad3c83ca0f7 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 @@ -27,7 +27,7 @@ public EDrtShiftStartLogic(ShiftStartLogic delegate) { @Override public boolean shiftStarts(DrtShiftDispatcher.ShiftEntry shiftEntry) { - Schedule schedule = shiftEntry.vehicle.getSchedule(); + Schedule schedule = shiftEntry.vehicle().getSchedule(); Task currentTask = schedule.getCurrentTask(); if (currentTask instanceof EDrtWaitForShiftStayTask) { //check whether vehicle still needs to complete charging task 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 d51712bd996..2f7944d5b9d 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 @@ -13,7 +13,6 @@ import org.matsim.core.config.ConfigGroup; import java.net.URL; -import java.util.Map; /** * @author nkuehnel / MOIA @@ -30,6 +29,10 @@ public class ShiftsParams extends ReflectiveConfigGroupWithConfigurableParameter @Comment("changeover duration in [seconds]") public double changeoverDuration = 900; + @Parameter + @Comment("maximum delay of shift assignment after start time has passed in [seconds]. If a shift can not be assigned to a vehicle until the planned start of the shift plus the defined max delay, the shift is discarded. Defaults to 0") + public double maxUnscheduledShiftDelay = 0; + @Parameter @Comment("Time of shift assignment (i.e. which vehicle carries out a specific shift) before start of shift in [seconds]") public double shiftScheduleLookAhead = 1800; 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 dd0b17860ea..cb9e5d76a9f 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 @@ -22,10 +22,10 @@ public class DefaultShiftStartLogic implements ShiftStartLogic { @Override public boolean shiftStarts(DrtShiftDispatcher.ShiftEntry peek) { // old shift hasn't ended yet - if (!peek.shift.equals(peek.vehicle.getShifts().peek())) { + if (!peek.shift().equals(peek.vehicle().getShifts().peek())) { return false; } - Schedule schedule = peek.vehicle.getSchedule(); + Schedule schedule = peek.vehicle().getSchedule(); // only active vehicles if (schedule.getStatus() != Schedule.ScheduleStatus.STARTED) { @@ -36,8 +36,8 @@ public boolean shiftStarts(DrtShiftDispatcher.ShiftEntry peek) { Task currentTask = schedule.getCurrentTask(); if(currentTask instanceof WaitForShiftStayTask) { //check if optional location requirement is met - if(peek.shift.getOperationFacilityId().isPresent()) { - Id operationFacilityId = peek.shift.getOperationFacilityId().get(); + if(peek.shift().getOperationFacilityId().isPresent()) { + Id operationFacilityId = peek.shift().getOperationFacilityId().get(); Verify.verify((operationFacilityId.equals(((WaitForShiftStayTask) currentTask).getFacility().getId())), "Vehicle and shift start locations do not match."); } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcher.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcher.java index 8bb205b7635..4fd44648565 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcher.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/dispatcher/DrtShiftDispatcher.java @@ -12,15 +12,9 @@ */ public interface DrtShiftDispatcher { - final class ShiftEntry { - public final DrtShift shift; - public final ShiftDvrpVehicle vehicle; - - public ShiftEntry(DrtShift shift, ShiftDvrpVehicle vehicle) { - this.shift = shift; - this.vehicle = vehicle; - } - } + void initialize(); + + record ShiftEntry(DrtShift shift, ShiftDvrpVehicle vehicle){} void dispatch(double timeStep); 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 1fd6de1e5b0..4c070bc1ebf 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 @@ -89,16 +89,15 @@ public DrtShiftDispatcherImpl(DrtShifts shifts, Fleet fleet, MobsimTimer timer, this.drtShiftParams = drtShiftParams; this.shiftStartLogic = shiftStartLogic; this.assignShiftToVehicleLogic = assignShiftToVehicleLogic; - - createQueues(); } + @Override + public void initialize() { - private void createQueues() { unscheduledShifts = new PriorityQueue<>(Comparator.comparingDouble(DrtShift::getStartTime)); unscheduledShifts.addAll(shifts.getShifts().values()); - assignedShifts = new PriorityQueue<>(Comparator.comparingDouble(v -> v.shift.getStartTime())); + assignedShifts = new PriorityQueue<>(Comparator.comparingDouble(v -> v.shift().getStartTime())); idleVehiclesQueues = new LinkedHashMap<>(); for(OperationFacility facility: operationFacilities.getDrtOperationFacilities().values()) { @@ -112,11 +111,11 @@ private void createQueues() { queue ); } - activeShifts = new PriorityQueue<>(Comparator.comparingDouble(v -> v.shift.getEndTime())); - endingShifts = new PriorityQueue<>(Comparator.comparingDouble(v -> v.shift.getEndTime())); + activeShifts = new PriorityQueue<>(Comparator.comparingDouble(v -> v.shift().getEndTime())); + endingShifts = new PriorityQueue<>(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", @@ -136,13 +135,13 @@ public void dispatch(double timeStep) { private void checkBreaks() { for (ShiftEntry activeShift : activeShifts) { - final DrtShift shift = activeShift.shift; + final DrtShift shift = activeShift.shift(); if (shift != null && shift.isStarted()) { OperationFacility breakFacility = decideOnBreak(activeShift); if (breakFacility != null) { - shiftTaskScheduler.relocateForBreak(activeShift.vehicle, breakFacility, shift); + shiftTaskScheduler.relocateForBreak(activeShift.vehicle(), breakFacility, shift); eventsManager.processEvent(new DrtShiftBreakScheduledEvent(timer.getTimeOfDay(), shift.getId(), - activeShift.vehicle.getId(), breakFacility.getLinkId(), + activeShift.vehicle().getId(), breakFacility.getLinkId(), shift.getBreak().orElseThrow().getScheduledLatestArrival())); } } @@ -154,23 +153,23 @@ private void startShifts(double timeStep) { final Iterator iterator = this.assignedShifts.iterator(); while (iterator.hasNext()) { final ShiftEntry next = iterator.next(); - if (next.shift.getStartTime() > timeStep) { + 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); + } else if (next.shift().getEndTime() < timeStep) { + logger.warn("Too late to start shift " + next.shift().getId()); + next.vehicle().getShifts().remove(next.shift()); iterator.remove(); continue; } if (shiftStartLogic.shiftStarts(next)) { - next.shift.start(); - shiftTaskScheduler.startShift(next.vehicle, timeStep, next.shift); + next.shift().start(); + shiftTaskScheduler.startShift(next.vehicle(), timeStep, next.shift()); activeShifts.add(next); iterator.remove(); - logger.debug("Started shift " + next.shift); - StayTask currentTask = (StayTask) next.vehicle.getSchedule().getCurrentTask(); - eventsManager.processEvent(new DrtShiftStartedEvent(timeStep, next.shift.getId(), next.vehicle.getId(), + logger.debug("Started shift " + next.shift()); + StayTask currentTask = (StayTask) next.vehicle().getSchedule().getCurrentTask(); + eventsManager.processEvent(new DrtShiftStartedEvent(timeStep, next.shift().getId(), next.vehicle().getId(), currentTask.getLink().getId())); } } @@ -178,7 +177,13 @@ private void startShifts(double timeStep) { private void assignShifts(double timeStep) { // Remove elapsed shifts - unscheduledShifts.removeIf(shift -> shift.getStartTime() < timeStep); + unscheduledShifts.removeIf(shift -> { + if (shift.getStartTime() + drtShiftParams.maxUnscheduledShiftDelay < timeStep ) { + logger.warn("Shift with ID " + shift.getId() + " could not be assigned and is being removed as start time is longer in the past than defined by maxUnscheduledShiftDelay."); + return true; + } + return false; + }); // Assign shifts Set assignableShifts = new LinkedHashSet<>(); @@ -190,20 +195,20 @@ private void assignShifts(double timeStep) { ShiftDvrpVehicle vehicle = null; for (ShiftEntry active : activeShifts) { - if (active.shift.getEndTime() > shift.getStartTime()) { + 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())) { + if(active.shift().getOperationFacilityId().isPresent()) { + if(!active.shift().getOperationFacilityId().get().equals(shift.getOperationFacilityId().get())) { continue; } } else { - Optional nextShiftChangeover = ShiftSchedules.getNextShiftChangeover(active.vehicle.getSchedule()); + Optional nextShiftChangeover = ShiftSchedules.getNextShiftChangeover(active.vehicle().getSchedule()); if(nextShiftChangeover.isPresent()) { - Verify.verify(nextShiftChangeover.get().getShift().equals(active.shift)); + 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; @@ -211,8 +216,8 @@ private void assignShifts(double timeStep) { } } } - if (assignShiftToVehicleLogic.canAssignVehicleToShift(active.vehicle, shift)) { - vehicle = active.vehicle; + if (assignShiftToVehicleLogic.canAssignVehicleToShift(active.vehicle(), shift)) { + vehicle = active.vehicle(); break; } } @@ -266,17 +271,17 @@ private void endShifts(double timeStep) { while (iterator.hasNext()) { final ShiftEntry next = iterator.next(); - if (timeStep + drtShiftParams.shiftEndLookAhead < next.shift.getEndTime()) { + if (timeStep + drtShiftParams.shiftEndLookAhead < next.shift().getEndTime()) { continue; } - final DrtShift active = next.shift; + final DrtShift active = next.shift(); - if (active != next.vehicle.getShifts().peek()) { + if (active != next.vehicle().getShifts().peek()) { throw new IllegalStateException("Shifts don't match!"); } - logger.debug("Scheduling shift end for shift " + next.shift.getId() + " of vehicle " + next.vehicle.getId()); + logger.debug("Scheduling shift end for shift " + next.shift().getId() + " of vehicle " + next.vehicle().getId()); scheduleShiftEnd(next); endingShifts.add(next); iterator.remove(); @@ -287,12 +292,12 @@ private void updateShiftEnds(double timeStep) { final Iterator endingShiftsIterator = this.endingShifts.iterator(); while (endingShiftsIterator.hasNext()) { final ShiftEntry next = endingShiftsIterator.next(); - if (next.shift.isEnded()) { + if (next.shift().isEnded()) { endingShiftsIterator.remove(); continue; } - if (timeStep + drtShiftParams.shiftEndRescheduleLookAhead > next.shift.getEndTime()) { - if (next.vehicle.getShifts().size() > 1) { + if (timeStep + drtShiftParams.shiftEndRescheduleLookAhead > next.shift().getEndTime()) { + if (next.vehicle().getShifts().size() > 1) { updateShiftEnd(next); } } else { @@ -303,17 +308,17 @@ private void updateShiftEnds(double timeStep) { private void updateShiftEnd(ShiftEntry next) { - if(next.shift.getOperationFacilityId().isPresent()) { + if(next.shift().getOperationFacilityId().isPresent()) { //start and end facility are fixed return; } - final List tasks = next.vehicle.getSchedule().getTasks(); + final List tasks = next.vehicle().getSchedule().getTasks(); Task lastTask = null; LinkTimePair start = null; ShiftChangeOverTask changeOverTask = null; - final Task currentTask = next.vehicle.getSchedule().getCurrentTask(); + final Task currentTask = next.vehicle().getSchedule().getCurrentTask(); for (Task task : tasks.subList(currentTask.getTaskIdx(), tasks.size())) { if (task instanceof ShiftChangeOverTask) { changeOverTask = (ShiftChangeOverTask) task; @@ -359,13 +364,13 @@ private void updateShiftEnd(ShiftEntry next) { 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, + 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()); + shiftChangeFacility.register(next.vehicle().getId()); + changeOverTask.getFacility().deregisterVehicle(next.vehicle().getId()); eventsManager.processEvent(new ShiftFacilityRegistrationEvent(timer.getTimeOfDay(), - next.vehicle.getId(), shiftChangeFacility.getId())); + next.vehicle().getId(), shiftChangeFacility.getId())); } } } @@ -373,7 +378,7 @@ private void updateShiftEnd(ShiftEntry next) { private void scheduleShiftEnd(ShiftEntry endingShift) { // hub return - final Schedule schedule = endingShift.vehicle.getSchedule(); + final Schedule schedule = endingShift.vehicle().getSchedule(); Task currentTask = schedule.getCurrentTask(); Link lastLink; @@ -395,14 +400,14 @@ private void scheduleShiftEnd(ShiftEntry endingShift) { OperationFacility shiftChangeoverFacility = null; //check whether current shift has to end at specific facility - if(endingShift.shift.getOperationFacilityId().isPresent()) { + if(endingShift.shift().getOperationFacilityId().isPresent()) { shiftChangeoverFacility = operationFacilities .getDrtOperationFacilities() - .get(endingShift.shift.getOperationFacilityId().get()); + .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) { + for (DrtShift shift : endingShift.vehicle().getShifts()) { + if (shift != endingShift.shift()) { if (shift.getOperationFacilityId().isPresent()) { shiftChangeoverFacility = operationFacilities .getDrtOperationFacilities() @@ -418,10 +423,10 @@ private void scheduleShiftEnd(ShiftEntry endingShift) { 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(), endingShift.vehicle.getId(), + 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(), endingShift.vehicle().getId(), shiftChangeoverFacility.getId())); } else { throw new RuntimeException("Could not find shift end location!"); @@ -429,9 +434,9 @@ private void scheduleShiftEnd(ShiftEntry endingShift) { } private OperationFacility decideOnBreak(ShiftEntry activeShift) { - if (activeShift.shift != null) { - if (shiftNeedsBreak(activeShift.shift, timer.getTimeOfDay())) { - final Schedule schedule = activeShift.vehicle.getSchedule(); + 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 @@ -451,9 +456,9 @@ private OperationFacility decideOnBreak(ShiftEntry activeShift) { if (shiftBreakFacility == null) { throw new RuntimeException("Could not schedule break!"); } - if (shiftBreakFacility.register(activeShift.vehicle.getId())) { + if (shiftBreakFacility.register(activeShift.vehicle().getId())) { eventsManager.processEvent(new ShiftFacilityRegistrationEvent(timer.getTimeOfDay(), - activeShift.vehicle.getId(), shiftBreakFacility.getId())); + activeShift.vehicle().getId(), shiftBreakFacility.getId())); return shiftBreakFacility; } } diff --git a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/ShiftDrtOptimizer.java b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/ShiftDrtOptimizer.java index f4ab679edd1..0ad63243a61 100644 --- a/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/ShiftDrtOptimizer.java +++ b/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/shifts/optimizer/ShiftDrtOptimizer.java @@ -10,11 +10,13 @@ import org.matsim.contrib.dvrp.schedule.ScheduleTimingUpdater; import org.matsim.contrib.dvrp.schedule.Task; import org.matsim.core.mobsim.framework.events.MobsimBeforeSimStepEvent; +import org.matsim.core.mobsim.framework.events.MobsimInitializedEvent; +import org.matsim.core.mobsim.framework.listeners.MobsimInitializedListener; /** * @author nkuehnel, fzwick / MOIA */ -public class ShiftDrtOptimizer implements DrtOptimizer { +public class ShiftDrtOptimizer implements DrtOptimizer, MobsimInitializedListener { private final DrtOptimizer optimizer; @@ -67,4 +69,8 @@ public void requestSubmitted(Request request) { this.optimizer.requestSubmitted(request); } + @Override + public void notifyMobsimInitialized(MobsimInitializedEvent e) { + dispatcher.initialize(); + } } diff --git a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/edrt/run/RunEDrtScenarioIT.java b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/edrt/run/RunEDrtScenarioIT.java index 051867cb5f8..48a6c4aeeea 100644 --- a/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/edrt/run/RunEDrtScenarioIT.java +++ b/contribs/drt-extensions/src/test/java/org/matsim/contrib/drt/extension/edrt/run/RunEDrtScenarioIT.java @@ -19,24 +19,44 @@ package org.matsim.contrib.drt.extension.edrt.run; import java.net.URL; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.matsim.api.core.v01.Scenario; +import org.matsim.api.core.v01.population.Plan; +import org.matsim.api.core.v01.population.Population; +import org.matsim.contrib.drt.extension.edrt.optimizer.EDrtVehicleDataEntryFactory; import org.matsim.contrib.drt.prebooking.PrebookingParams; import org.matsim.contrib.drt.prebooking.logic.ProbabilityBasedPrebookingLogic; import org.matsim.contrib.drt.run.DrtConfigGroup; +import org.matsim.contrib.drt.run.DrtConfigs; +import org.matsim.contrib.drt.run.DrtControlerCreator; import org.matsim.contrib.drt.run.MultiModeDrtConfigGroup; -import org.matsim.contrib.dvrp.passenger.PassengerRequestRejectedEvent; -import org.matsim.contrib.dvrp.passenger.PassengerRequestRejectedEventHandler; -import org.matsim.contrib.dvrp.passenger.PassengerRequestScheduledEvent; -import org.matsim.contrib.dvrp.passenger.PassengerRequestScheduledEventHandler; +import org.matsim.contrib.dvrp.passenger.*; +import org.matsim.contrib.dvrp.run.AbstractDvrpModeModule; import org.matsim.contrib.dvrp.run.DvrpConfigGroup; +import org.matsim.contrib.dvrp.run.DvrpModule; +import org.matsim.contrib.dvrp.run.DvrpQSimComponents; import org.matsim.contrib.ev.EvConfigGroup; +import org.matsim.contrib.ev.EvModule; +import org.matsim.contrib.ev.charging.*; +import org.matsim.contrib.ev.discharging.IdleDischargingHandler; +import org.matsim.contrib.ev.temperature.TemperatureService; +import org.matsim.contrib.evrp.EvDvrpFleetQSimModule; +import org.matsim.contrib.evrp.OperatingVehicleProvider; +import org.matsim.contrib.otfvis.OTFVisLiveModule; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; +import org.matsim.core.mobsim.qsim.AbstractQSimModule; +import org.matsim.core.population.io.PopulationReader; +import org.matsim.core.population.io.PopulationWriter; +import org.matsim.core.router.TripStructureUtils; +import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; import org.matsim.vis.otfvis.OTFVisConfigGroup; @@ -51,36 +71,82 @@ void test() { RunEDrtScenario.run(configUrl, false); } + @Test + void testMultiModeDrtDeterminism() { + URL configUrl = IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("mielec"), "mielec_multiModeEdrt_config.xml"); + + Config config = ConfigUtils.loadConfig(configUrl, new MultiModeDrtConfigGroup(), new DvrpConfigGroup(), + new OTFVisConfigGroup(), new EvConfigGroup()); + + + Controler controller = RunEDrtScenario.createControler(config, false); + config.controller().setLastIteration(2); + + PassengerPickUpTracker tracker = new PassengerPickUpTracker(); + tracker.install(controller); + + controller.run(); + + assertEquals(2011, tracker.passengerPickupEvents); + } + + @Test void testWithPrebooking() { URL configUrl = IOUtils.extendUrl(ExamplesUtils.getTestScenarioURL("mielec"), "mielec_edrt_config.xml"); - + Config config = ConfigUtils.loadConfig(configUrl, new MultiModeDrtConfigGroup(), new DvrpConfigGroup(), new OTFVisConfigGroup(), new EvConfigGroup()); - + DrtConfigGroup drtConfig = DrtConfigGroup.getSingleModeDrtConfig(config); drtConfig.addParameterSet(new PrebookingParams()); - + Controler controller = RunEDrtScenario.createControler(config, false); ProbabilityBasedPrebookingLogic.install(controller, drtConfig, 0.5, 4.0 * 3600.0); - + PrebookingTracker tracker = new PrebookingTracker(); tracker.install(controller); - + controller.run(); - + assertEquals(74, tracker.immediateScheduled); assertEquals(198, tracker.prebookedScheduled); assertEquals(116, tracker.immediateRejected); assertEquals(7, tracker.prebookedRejected); } - + + static private class PassengerPickUpTracker implements PassengerPickedUpEventHandler { + int passengerPickupEvents = 0; + + void install(Controler controller) { + PassengerPickUpTracker thisTracker = this; + + controller.addOverridingModule(new AbstractModule() { + @Override + public void install() { + addEventHandlerBinding().toInstance(thisTracker); + } + }); + } + + @Override + public void handleEvent(PassengerPickedUpEvent event) { + passengerPickupEvents++; + } + + @Override + public void reset(int iteration) { + passengerPickupEvents=0; + } + + } + static private class PrebookingTracker implements PassengerRequestRejectedEventHandler, PassengerRequestScheduledEventHandler { int immediateScheduled = 0; int prebookedScheduled = 0; int immediateRejected = 0; int prebookedRejected = 0; - + @Override public void handleEvent(PassengerRequestScheduledEvent event) { if (event.getRequestId().toString().contains("prebooked")) { @@ -98,10 +164,10 @@ public void handleEvent(PassengerRequestRejectedEvent event) { immediateRejected++; } } - + void install(Controler controller) { PrebookingTracker thisTracker = this; - + controller.addOverridingModule(new AbstractModule() { @Override public void install() { diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/Waypoint.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/Waypoint.java index 3e99d3df631..d8540facde3 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/Waypoint.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/Waypoint.java @@ -182,7 +182,8 @@ public int getOutgoingOccupancy() { } public int getOccupancyChange() { - return task.getPickupRequests().size() - task.getDropoffRequests().size(); + return task.getPickupRequests().values().stream().mapToInt(AcceptedDrtRequest::getPassengerCount).sum() - + task.getDropoffRequests().values().stream().mapToInt(AcceptedDrtRequest::getPassengerCount).sum(); } private double calcLatestArrivalTime() { diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/depot/Depots.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/depot/Depots.java index 3b2152eec90..0d35c029215 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/depot/Depots.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/depot/Depots.java @@ -50,9 +50,9 @@ public static boolean isSwitchingFromStopToStay(DvrpVehicle vehicle) { if (!STAY.isBaseTypeOf(currentTask)) { return false; } - + // only if stay task is last task: with prebooking we may also idle during the day, but - // currently all the downstream relocation/charging logic assumes that we only stay at + // currently all the downstream relocation/charging logic assumes that we only stay at // the end of the schedule if (currentTask.getTaskIdx() < schedule.getTaskCount() - 1) { return false; @@ -64,13 +64,15 @@ public static boolean isSwitchingFromStopToStay(DvrpVehicle vehicle) { } public static Link findStraightLineNearestDepot(DvrpVehicle vehicle, Set links) { - Link currentLink = ((DrtStayTask)vehicle.getSchedule().getCurrentTask()).getLink(); + Link currentLink = ((DrtStayTask) vehicle.getSchedule().getCurrentTask()).getLink(); return links.contains(currentLink) ? - null /* already at a depot*/ : - links.stream() - .min(Comparator.comparing( - l -> DistanceUtils.calculateSquaredDistance(currentLink.getToNode().getCoord(), - l.getFromNode().getCoord()))) - .get(); + null /* already at a depot*/ : + links.stream().map(l -> new DepotCandidates(l, DistanceUtils.calculateSquaredDistance(currentLink.getToNode().getCoord(), + l.getFromNode().getCoord()))) + .min(Comparator.comparing(DepotCandidates::distance) + .thenComparing(h -> h.link.getId())) + .get().link(); } + + record DepotCandidates(Link link, double distance) {} } diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/passenger/AcceptedDrtRequest.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/passenger/AcceptedDrtRequest.java index 81dd831859a..d053f6e74b9 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/passenger/AcceptedDrtRequest.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/passenger/AcceptedDrtRequest.java @@ -103,6 +103,10 @@ public List> getPassengerIds() { return request.getPassengerIds(); } + public int getPassengerCount() { + return request.getPassengerCount(); + } + public String getMode() { return request.getMode(); } diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PassengerRequestBookedEvent.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PassengerRequestBookedEvent.java index e58f8835dfb..7d14a3650e6 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PassengerRequestBookedEvent.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PassengerRequestBookedEvent.java @@ -1,23 +1,21 @@ package org.matsim.contrib.drt.prebooking; -import java.util.List; -import java.util.Map; -import java.util.Objects; - import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.GenericEvent; import org.matsim.api.core.v01.population.Person; import org.matsim.contrib.dvrp.optimizer.Request; import org.matsim.contrib.dvrp.passenger.AbstractPassengerRequestEvent; +import java.util.*; + /** * @author Sebastian Hörl (sebhoerl), IRT SystemX */ public class PassengerRequestBookedEvent extends AbstractPassengerRequestEvent { public static final String EVENT_TYPE = "PassengerRequest booked"; - public PassengerRequestBookedEvent(double time, String mode, Id requestId, Id personId) { - super(time, mode, requestId, List.of(personId)); + public PassengerRequestBookedEvent(double time, String mode, Id requestId, List> personIds) { + super(time, mode, requestId, personIds); } @Override @@ -30,7 +28,8 @@ public static PassengerRequestBookedEvent convert(GenericEvent event) { double time = Double.parseDouble(attributes.get(ATTRIBUTE_TIME)); String mode = Objects.requireNonNull(attributes.get(ATTRIBUTE_MODE)); Id requestId = Id.create(attributes.get(ATTRIBUTE_REQUEST), Request.class); - Id personId = Id.createPersonId(attributes.get(ATTRIBUTE_PERSON)); - return new PassengerRequestBookedEvent(time, mode, requestId, personId); + String[] personIdsAttribute = attributes.get(ATTRIBUTE_PERSON).split(","); + List> personIds = Arrays.stream(personIdsAttribute).map(Id::createPersonId).toList(); + return new PassengerRequestBookedEvent(time, mode, requestId, personIds); } } diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingManager.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingManager.java index 1fc580715f4..ed79cd0bf9f 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingManager.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/PrebookingManager.java @@ -1,15 +1,7 @@ package org.matsim.contrib.drt.prebooking; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicInteger; - -import javax.annotation.Nullable; - +import com.google.common.base.Preconditions; +import com.google.common.base.Verify; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.IdMap; import org.matsim.api.core.v01.IdSet; @@ -25,14 +17,7 @@ import org.matsim.contrib.dvrp.fleet.DvrpVehicle; import org.matsim.contrib.dvrp.optimizer.Request; import org.matsim.contrib.dvrp.optimizer.VrpOptimizer; -import org.matsim.contrib.dvrp.passenger.AdvanceRequestProvider; -import org.matsim.contrib.dvrp.passenger.PassengerRequest; -import org.matsim.contrib.dvrp.passenger.PassengerRequestCreator; -import org.matsim.contrib.dvrp.passenger.PassengerRequestRejectedEvent; -import org.matsim.contrib.dvrp.passenger.PassengerRequestRejectedEventHandler; -import org.matsim.contrib.dvrp.passenger.PassengerRequestScheduledEvent; -import org.matsim.contrib.dvrp.passenger.PassengerRequestScheduledEventHandler; -import org.matsim.contrib.dvrp.passenger.PassengerRequestValidator; +import org.matsim.contrib.dvrp.passenger.*; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.mobsim.framework.MobsimAgent; import org.matsim.core.mobsim.framework.MobsimAgent.State; @@ -43,8 +28,10 @@ import org.matsim.core.mobsim.qsim.agents.WithinDayAgentUtils; import org.matsim.core.mobsim.qsim.interfaces.MobsimEngine; -import com.google.common.base.Preconditions; -import com.google.common.base.Verify; +import javax.annotation.Nullable; +import java.util.*; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; /** * This class manages prebooked requests. One instance of PrebookingManager @@ -140,6 +127,8 @@ public void handleEvent(PersonStuckEvent event) { private record RejectionItem(Id requestId, List> personIds, String cause) { } + public record PersonLeg(MobsimAgent agent, Leg leg){} + private final ConcurrentLinkedQueue rejections = new ConcurrentLinkedQueue<>(); private void processRejection(PassengerRequest request, String cause) { @@ -163,35 +152,47 @@ private void flushRejections(double now) { // collects new bookings that need to be submitted private final ConcurrentLinkedQueue bookingQueue = new ConcurrentLinkedQueue<>(); - public void prebook(MobsimAgent person, Leg leg, double earliestDepartureTime) { - Preconditions.checkArgument(leg.getMode().equals(mode), "Invalid mode for this prebooking manager"); - Preconditions.checkState(!person.getState().equals(State.ABORT), "Cannot prebook aborted agent"); + public void prebook(MobsimAgent agent, Leg leg, double earliestDepartureTime) { + prebook(List.of(new PersonLeg(agent, leg)), earliestDepartureTime); + } + + public void prebook(List personsLegs, double earliestDepartureTime) { + for (PersonLeg personLeg : personsLegs) { + Preconditions.checkArgument(personLeg.leg().getMode().equals(mode), "Invalid mode for this prebooking manager"); + Preconditions.checkState(!personLeg.agent().getState().equals(State.ABORT), "Cannot prebook aborted agent"); + } Id requestId = createRequestId(); double now = mobsimTimer.getTimeOfDay(); - eventsManager.processEvent(new PassengerRequestBookedEvent(now, mode, requestId, person.getId())); + List> personIds = personsLegs.stream().map(p -> p.agent().getId()).toList(); + eventsManager.processEvent(new PassengerRequestBookedEvent(now, mode, requestId, personIds)); - PassengerRequest request = requestCreator.createRequest(requestId, List.of(person.getId()), leg.getRoute(), - getLink(leg.getRoute().getStartLinkId()), getLink(leg.getRoute().getEndLinkId()), earliestDepartureTime, + Leg representativeLeg = personsLegs.get(0).leg(); + PassengerRequest request = requestCreator.createRequest(requestId, personIds, representativeLeg.getRoute(), + getLink(representativeLeg.getRoute().getStartLinkId()), getLink(representativeLeg.getRoute().getEndLinkId()), earliestDepartureTime, now); Set violations = requestValidator.validateRequest(request); - Plan plan = WithinDayAgentUtils.getModifiablePlan(person); - int currentLegIndex = WithinDayAgentUtils.getCurrentPlanElementIndex(person); - int prebookingLegIndex = plan.getPlanElements().indexOf(leg); + for (PersonLeg personLeg : personsLegs) { + Plan plan = WithinDayAgentUtils.getModifiablePlan(personLeg.agent()); + int currentLegIndex = WithinDayAgentUtils.getCurrentPlanElementIndex(personLeg.agent()); + int prebookingLegIndex = plan.getPlanElements().indexOf(personLeg.leg()); - if (prebookingLegIndex <= currentLegIndex) { - violations = new HashSet<>(violations); - violations.add("past leg"); // the leg for which the booking was made has already happened + if (prebookingLegIndex <= currentLegIndex) { + violations = new HashSet<>(violations); + violations.add("past leg"); // the leg for which the booking was made has already happened + } } if (!violations.isEmpty()) { String cause = String.join(", ", violations); processRejection(request, cause); } else { - leg.getAttributes().putAttribute(requestAttribute, request.getId().toString()); + for (PersonLeg personLeg : personsLegs) { + personLeg.leg().getAttributes().putAttribute(requestAttribute, request.getId().toString()); + } bookingQueue.add(request); } } 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 b3f6faa4bc7..badbb8624f5 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 @@ -1,5 +1,6 @@ package org.matsim.contrib.drt.prebooking; +import com.google.inject.Singleton; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.Population; import org.matsim.contrib.drt.optimizer.VehicleEntry; @@ -15,10 +16,7 @@ import org.matsim.contrib.drt.vrpagent.DrtActionCreator; import org.matsim.contrib.dvrp.fleet.DvrpVehicleLookup; import org.matsim.contrib.dvrp.optimizer.VrpOptimizer; -import org.matsim.contrib.dvrp.passenger.PassengerEngine; -import org.matsim.contrib.dvrp.passenger.PassengerHandler; -import org.matsim.contrib.dvrp.passenger.PassengerRequestCreator; -import org.matsim.contrib.dvrp.passenger.PassengerRequestValidator; +import org.matsim.contrib.dvrp.passenger.*; import org.matsim.contrib.dvrp.run.AbstractDvrpModeQSimModule; import org.matsim.contrib.dvrp.schedule.ScheduleTimingUpdater; import org.matsim.core.api.experimental.events.EventsManager; @@ -27,8 +25,6 @@ import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.router.util.TravelTime; -import com.google.inject.Singleton; - public class PrebookingModeQSimModule extends AbstractDvrpModeQSimModule { private final PrebookingParams prebookingParams; @@ -65,7 +61,7 @@ protected void configureQSim() { addModalQSimComponentBinding().to(modalKey(PrebookingManager.class)); bindModal(PrebookingQueue.class).toProvider(modalProvider(getter -> { - return new PrebookingQueue(getter.getModal(PrebookingManager.class)); + return new PrebookingQueue(getter.getModal(PrebookingManager.class), getter.getModal(PassengerGroupIdentifier.class)); })).in(Singleton.class); addModalQSimComponentBinding().to(modalKey(PrebookingQueue.class)); diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/logic/helpers/PrebookingQueue.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/logic/helpers/PrebookingQueue.java index ed04764c9b4..788a430c069 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/logic/helpers/PrebookingQueue.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/prebooking/logic/helpers/PrebookingQueue.java @@ -1,14 +1,16 @@ package org.matsim.contrib.drt.prebooking.logic.helpers; -import java.util.PriorityQueue; - +import com.google.common.base.Preconditions; +import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.population.Leg; import org.matsim.contrib.drt.prebooking.PrebookingManager; +import org.matsim.contrib.dvrp.passenger.PassengerGroupIdentifier; import org.matsim.core.mobsim.framework.MobsimAgent; +import org.matsim.core.mobsim.framework.MobsimPassengerAgent; import org.matsim.core.mobsim.framework.events.MobsimBeforeSimStepEvent; import org.matsim.core.mobsim.framework.listeners.MobsimBeforeSimStepListener; -import com.google.common.base.Preconditions; +import java.util.*; /** * This service helps to define a PrebookingLogic where at some point in time @@ -16,7 +18,7 @@ * request will happen at a specific time. Once we know that the request will be * sent, we can use the present class to put it in a queue, making sure the * request will be *booked* the the time we want. - * + * * @author Sebastian Hörl (sebhoerl), IRT SystemX */ public class PrebookingQueue implements MobsimBeforeSimStepListener { @@ -27,8 +29,11 @@ public class PrebookingQueue implements MobsimBeforeSimStepListener { private double currentTime = Double.NEGATIVE_INFINITY; - public PrebookingQueue(PrebookingManager prebookingManager) { + private final PassengerGroupIdentifier groupIdentifier; + + public PrebookingQueue(PrebookingManager prebookingManager, PassengerGroupIdentifier groupIdentifier) { this.prebookingManager = prebookingManager; + this.groupIdentifier = groupIdentifier; } @Override @@ -39,9 +44,19 @@ public void notifyMobsimBeforeSimStep(@SuppressWarnings("rawtypes") MobsimBefore private void performSubmissions(double time) { currentTime = time; + Map, List> groups = new LinkedHashMap<>(); while (!queue.isEmpty() && queue.peek().submissionTime <= time) { var item = queue.poll(); - prebookingManager.prebook(item.agent(), item.leg(), item.departuretime()); + Optional> groupId = groupIdentifier.getGroupId((MobsimPassengerAgent) item.agent); + if(groupId.isEmpty()) { + prebookingManager.prebook(item.agent(), item.leg(), item.departureTime()); + } else { + groups.computeIfAbsent(groupId.get(), k -> new ArrayList<>()).add(item); + } + } + for (List group : groups.values()) { + List personsLegs = group.stream().map(entry -> new PrebookingManager.PersonLeg(entry.agent, entry.leg)).toList(); + prebookingManager.prebook(personsLegs, group.get(0).departureTime); } } @@ -62,7 +77,7 @@ public void schedule(double submissionTime, MobsimAgent agent, Leg leg, double d } } - private record ScheduledSubmission(double submissionTime, MobsimAgent agent, Leg leg, double departuretime, + private record ScheduledSubmission(double submissionTime, MobsimAgent agent, Leg leg, double departureTime, int sequence) implements Comparable { @Override public int compareTo(ScheduledSubmission o) { diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtModeModule.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtModeModule.java index 677e5504c3c..a0cb1fc007c 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtModeModule.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/run/DrtModeModule.java @@ -20,18 +20,16 @@ package org.matsim.contrib.drt.run; +import com.google.inject.Key; +import com.google.inject.Singleton; +import com.google.inject.name.Names; import org.matsim.api.core.v01.network.Network; import org.matsim.contrib.drt.analysis.DrtEventSequenceCollector; import org.matsim.contrib.drt.fare.DrtFareHandler; import org.matsim.contrib.drt.optimizer.rebalancing.RebalancingModule; import org.matsim.contrib.drt.prebooking.analysis.PrebookingModeAnalysisModule; import org.matsim.contrib.drt.speedup.DrtSpeedUp; -import org.matsim.contrib.drt.stops.DefaultStopTimeCalculator; -import org.matsim.contrib.drt.stops.MinimumStopDurationAdapter; -import org.matsim.contrib.drt.stops.PassengerStopDurationProvider; -import org.matsim.contrib.drt.stops.PrebookingStopTimeCalculator; -import org.matsim.contrib.drt.stops.StaticPassengerStopDurationProvider; -import org.matsim.contrib.drt.stops.StopTimeCalculator; +import org.matsim.contrib.drt.stops.*; import org.matsim.contrib.dvrp.fleet.FleetModule; import org.matsim.contrib.dvrp.fleet.FleetSpecification; import org.matsim.contrib.dvrp.router.DvrpModeRoutingNetworkModule; @@ -44,10 +42,6 @@ import org.matsim.core.router.costcalculators.TravelDisutilityFactory; import org.matsim.core.router.util.TravelTime; -import com.google.inject.Key; -import com.google.inject.Singleton; -import com.google.inject.name.Names; - /** * @author michalm (Michal Maciejewski) */ @@ -87,15 +81,15 @@ public void install() { getter.getModal(DrtEventSequenceCollector.class)))).asEagerSingleton(); addControlerListenerBinding().to(modalKey(DrtSpeedUp.class)); }); - + bindModal(PassengerStopDurationProvider.class).toProvider(modalProvider(getter -> { return StaticPassengerStopDurationProvider.of(drtCfg.stopDuration, 0.0); })); - + bindModal(DefaultStopTimeCalculator.class).toProvider(modalProvider(getter -> { return new DefaultStopTimeCalculator(drtCfg.stopDuration); })).in(Singleton.class); - + if (drtCfg.getPrebookingParams().isEmpty()) { bindModal(StopTimeCalculator.class).toProvider(modalProvider(getter -> { return new DefaultStopTimeCalculator(drtCfg.stopDuration); @@ -105,7 +99,7 @@ public void install() { PassengerStopDurationProvider provider = getter.getModal(PassengerStopDurationProvider.class); return new MinimumStopDurationAdapter(new PrebookingStopTimeCalculator(provider), drtCfg.stopDuration); })); - + install(new PrebookingModeAnalysisModule(getMode())); } diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/sharingmetrics/SharingMetricsModule.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/sharingmetrics/SharingMetricsModule.java index 2ebe3777ac1..4e1c4c31b09 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/sharingmetrics/SharingMetricsModule.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/sharingmetrics/SharingMetricsModule.java @@ -21,7 +21,7 @@ public SharingMetricsModule(DrtConfigGroup drtConfigGroup) { @Override public void install() { bindModal(SharingMetricsTracker.class).toProvider(modalProvider(getter -> - new SharingMetricsTracker(personId -> true))).asEagerSingleton(); + new SharingMetricsTracker())).asEagerSingleton(); addEventHandlerBinding().to(modalKey(SharingMetricsTracker.class)); bindModal(SharingMetricsControlerListener.class).toProvider(modalProvider(getter -> new SharingMetricsControlerListener(getConfig(), drtConfigGroup, diff --git a/contribs/drt/src/main/java/org/matsim/contrib/drt/sharingmetrics/SharingMetricsTracker.java b/contribs/drt/src/main/java/org/matsim/contrib/drt/sharingmetrics/SharingMetricsTracker.java index f5393b29144..593361f0cdd 100644 --- a/contribs/drt/src/main/java/org/matsim/contrib/drt/sharingmetrics/SharingMetricsTracker.java +++ b/contribs/drt/src/main/java/org/matsim/contrib/drt/sharingmetrics/SharingMetricsTracker.java @@ -2,6 +2,8 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.population.Person; +import org.matsim.contrib.drt.passenger.events.DrtRequestSubmittedEvent; +import org.matsim.contrib.drt.passenger.events.DrtRequestSubmittedEventHandler; import org.matsim.contrib.dvrp.fleet.DvrpVehicle; import org.matsim.contrib.dvrp.optimizer.Request; import org.matsim.contrib.dvrp.passenger.PassengerDroppedOffEvent; @@ -16,9 +18,7 @@ /** * @author nkuehnel / MOIA */ -public class SharingMetricsTracker implements PassengerPickedUpEventHandler, PassengerDroppedOffEventHandler, MobsimBeforeCleanupListener { - - private final GroupPredicate groupPredicate; +public class SharingMetricsTracker implements DrtRequestSubmittedEventHandler, PassengerPickedUpEventHandler, PassengerDroppedOffEventHandler, MobsimBeforeCleanupListener { record Segment(double start, int occupancy) { } @@ -27,27 +27,34 @@ record Segment(double start, int occupancy) { private final Map, List> segments = new HashMap<>(); + private final Map, List>> knownGroups = new HashMap<>(); + private final Map, Double> sharingFactors = new HashMap<>(); private final Map, Boolean> poolingRate = new HashMap<>(); - public interface GroupPredicate { - boolean isGroupRepresentative(Id personId); - } - public SharingMetricsTracker(GroupPredicate groupPredicate) { - this.groupPredicate = groupPredicate; + public SharingMetricsTracker() { } + @Override + public void handleEvent(DrtRequestSubmittedEvent event) { + knownGroups.put(event.getRequestId(), new ArrayList<>(event.getPersonIds())); + } @Override public void handleEvent(PassengerDroppedOffEvent event) { - if (groupPredicate.isGroupRepresentative(event.getPersonId())) { + + List> passengers = knownGroups.get(event.getRequestId()); + passengers.remove(event.getPersonId()); + + if (passengers.isEmpty()) { + // all passengers of the group have been dropped off + knownGroups.remove(event.getRequestId()); List> occupancy = map.get(event.getVehicleId()); occupancy.remove(event.getRequestId()); occupancy.forEach(p -> segments.get(p).add(new Segment(event.getTime(), occupancy.size()))); - List finishedSegments = segments.remove(event.getRequestId()); double total = 0; @@ -82,9 +89,15 @@ public void handleEvent(PassengerDroppedOffEvent event) { @Override public void handleEvent(PassengerPickedUpEvent event) { - if (groupPredicate.isGroupRepresentative(event.getPersonId())) { - map.computeIfAbsent(event.getVehicleId(), vehicleId -> new ArrayList<>()); - List> occupancy = map.get(event.getVehicleId()); + List> occupancy = map.computeIfAbsent(event.getVehicleId(), vehicleId -> new ArrayList<>()); + if (occupancy.contains(event.getRequestId())) { + if (knownGroups.get(event.getRequestId()).size() > 1) { + //group request, skip for additional persons + return; + } else { + throw new RuntimeException("Single rider request picked up twice!"); + } + } else { occupancy.add(event.getRequestId()); occupancy.forEach( p -> segments.computeIfAbsent(p, requestId -> new ArrayList<>()).add(new Segment(event.getTime(), occupancy.size())) @@ -98,6 +111,7 @@ public void notifyMobsimBeforeCleanup(MobsimBeforeCleanupEvent e) { segments.clear(); poolingRate.clear(); sharingFactors.clear(); + knownGroups.clear(); } public Map, Double> getSharingFactors() { diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionGeneratorTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionGeneratorTest.java index 53c6aa2d5ae..5a44c12c118 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionGeneratorTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/optimizer/insertion/InsertionGeneratorTest.java @@ -20,14 +20,9 @@ package org.matsim.contrib.drt.optimizer.insertion; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import com.google.common.collect.Sets; +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; @@ -37,6 +32,7 @@ import org.matsim.contrib.drt.optimizer.insertion.InsertionDetourTimeCalculator.DropoffDetourInfo; import org.matsim.contrib.drt.optimizer.insertion.InsertionDetourTimeCalculator.PickupDetourInfo; import org.matsim.contrib.drt.optimizer.insertion.InsertionGenerator.Insertion; +import org.matsim.contrib.drt.passenger.AcceptedDrtRequest; import org.matsim.contrib.drt.passenger.DrtRequest; import org.matsim.contrib.drt.schedule.DefaultDrtStopTask; import org.matsim.contrib.drt.stops.DefaultStopTimeCalculator; @@ -46,8 +42,12 @@ import org.matsim.contrib.dvrp.fleet.ImmutableDvrpVehicleSpecification; import org.matsim.testcases.fakes.FakeLink; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; /** * @author Michal Maciejewski (michalm) @@ -444,6 +444,32 @@ void startEmpty_twoStops_groupExceedsCapacityAtFirstStop() { ); } + @Test + void testWaypointOccupancyChange() { + int occupancy = 0; + AcceptedDrtRequest acceptedReq5Pax = AcceptedDrtRequest.createFromOriginalRequest(drtRequest5Pax); + AcceptedDrtRequest acceptedReq2Pax = AcceptedDrtRequest.createFromOriginalRequest(drtRequest2Pax); + + Waypoint.Stop stop2 = stop(0, link("stop2"), occupancy); + //dropoff 5 pax + stop2.task.addDropoffRequest(acceptedReq5Pax); + occupancy -= stop2.getOccupancyChange(); + Assertions.assertEquals(5, occupancy); + + Waypoint.Stop stop1 = stop(0, link("stop1"), occupancy); + //dropoff 2 pax, pickup 5 + stop1.task.addDropoffRequest(acceptedReq2Pax); + stop1.task.addPickupRequest(acceptedReq5Pax); + occupancy -= stop1.getOccupancyChange(); + Assertions.assertEquals(2, occupancy); + + + Waypoint.Stop stop0 = stop(0, link("stop0"), occupancy); + stop0.task.addPickupRequest(acceptedReq2Pax); + occupancy -= stop0.getOccupancyChange(); + Assertions.assertEquals(0, occupancy); + } + private Link link(String id) { return new FakeLink(Id.createLinkId(id)); } diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/PrebookingGroupTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/PrebookingGroupTest.java new file mode 100644 index 00000000000..c609ec084f8 --- /dev/null +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/PrebookingGroupTest.java @@ -0,0 +1,74 @@ +package org.matsim.contrib.drt.prebooking; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.matsim.api.core.v01.Id; +import org.matsim.contrib.drt.prebooking.logic.AttributeBasedPrebookingLogic; +import org.matsim.contrib.drt.run.DrtConfigGroup; +import org.matsim.contrib.dvrp.passenger.PassengerGroupIdentifier; +import org.matsim.contrib.dvrp.run.AbstractDvrpModeQSimModule; +import org.matsim.core.controler.Controler; +import org.matsim.testcases.MatsimTestUtils; + +import java.util.Optional; + + +public class PrebookingGroupTest { + + @RegisterExtension + public MatsimTestUtils utils = new MatsimTestUtils(); + + + static PrebookingParams installPrebooking(Controler controller) { + return installPrebooking(controller, true); + } + + static PrebookingParams installPrebooking(Controler controller, boolean installLogic) { + DrtConfigGroup drtConfig = DrtConfigGroup.getSingleModeDrtConfig(controller.getConfig()); + drtConfig.addParameterSet(new PrebookingParams()); + + if (installLogic) { + AttributeBasedPrebookingLogic.install(controller, drtConfig); + } + controller.addOverridingQSimModule(new AbstractDvrpModeQSimModule(drtConfig.getMode()) { + @Override + protected void configureQSim() { + bindModal(PassengerGroupIdentifier.class).toInstance(agent -> Optional.of(Id.create("group", PassengerGroupIdentifier.PassengerGroup.class))); + } + }); + + return drtConfig.getPrebookingParams().get(); + } + + @Test + public void oneRequestArrivingLate() { + + // copy of prebooking test but with two persons in one request + PrebookingTestEnvironment environment = new PrebookingTestEnvironment(utils) // + .addVehicle("vehicleA", 1, 1) // + // 1800 indicated but only departing 2000 + .addRequest("personA", 0, 0, 5, 5, 2000.0, 0.0, 2000.0 - 200.0) // + .addRequest("personB", 0, 0, 5, 5, 2000.0, 0.0, 2000.0 - 200.0) // + .configure(600.0, 1.3, 600.0, 60.0) // + .endTime(10.0 * 3600.0); + + Controler controller = environment.build(); + installPrebooking(controller); + controller.run(); + + PrebookingTestEnvironment.RequestInfo requestInfoA = environment.getRequestInfo().get("personA"); + Assertions.assertEquals(0.0, requestInfoA.submissionTime, 1e-3); + Assertions.assertEquals(2060.0, requestInfoA.pickupTime, 1e-3); + Assertions.assertEquals(2271.0, requestInfoA.dropoffTime, 1e-3); + + PrebookingTestEnvironment.RequestInfo requestInfoB = environment.getRequestInfo().get("personB"); + Assertions.assertEquals(0.0, requestInfoB.submissionTime, 1e-3); + Assertions.assertEquals(2060.0, requestInfoB.pickupTime, 1e-3); + Assertions.assertEquals(2271.0, requestInfoB.dropoffTime, 1e-3); + + // assert both persons are part of same drt request + Assertions.assertEquals(requestInfoA.drtRequestId, requestInfoB.drtRequestId); + } +} + diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/PrebookingTestEnvironment.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/PrebookingTestEnvironment.java index 8e1f6394388..a80d8a42386 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/PrebookingTestEnvironment.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/prebooking/PrebookingTestEnvironment.java @@ -1,11 +1,5 @@ package org.matsim.contrib.drt.prebooking; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - import org.apache.commons.lang3.tuple.Pair; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; @@ -14,12 +8,7 @@ import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.network.NetworkFactory; import org.matsim.api.core.v01.network.Node; -import org.matsim.api.core.v01.population.Activity; -import org.matsim.api.core.v01.population.Leg; -import org.matsim.api.core.v01.population.Person; -import org.matsim.api.core.v01.population.Plan; -import org.matsim.api.core.v01.population.Population; -import org.matsim.api.core.v01.population.PopulationFactory; +import org.matsim.api.core.v01.population.*; import org.matsim.contrib.drt.optimizer.insertion.DrtInsertionSearchParams; import org.matsim.contrib.drt.optimizer.insertion.selective.SelectiveInsertionSearchParams; import org.matsim.contrib.drt.passenger.events.DrtRequestSubmittedEvent; @@ -35,12 +24,7 @@ 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.PassengerDroppedOffEvent; -import org.matsim.contrib.dvrp.passenger.PassengerDroppedOffEventHandler; -import org.matsim.contrib.dvrp.passenger.PassengerPickedUpEvent; -import org.matsim.contrib.dvrp.passenger.PassengerPickedUpEventHandler; -import org.matsim.contrib.dvrp.passenger.PassengerRequestRejectedEvent; -import org.matsim.contrib.dvrp.passenger.PassengerRequestRejectedEventHandler; +import org.matsim.contrib.dvrp.passenger.*; import org.matsim.contrib.dvrp.run.AbstractDvrpModeModule; import org.matsim.contrib.dvrp.run.DvrpConfigGroup; import org.matsim.contrib.dvrp.run.DvrpModule; @@ -61,6 +45,11 @@ import org.matsim.core.scenario.ScenarioUtils; import org.matsim.testcases.MatsimTestUtils; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + public class PrebookingTestEnvironment { private final MatsimTestUtils utils; @@ -361,6 +350,7 @@ public class RequestInfo { public double dropoffTime = Double.NaN; public List submissionTimes = new LinkedList<>(); + public Id drtRequestId = null; } private Map requestInfo = new HashMap<>(); @@ -382,17 +372,21 @@ private class RequestListener implements DrtRequestSubmittedEventHandler, Passen PassengerDroppedOffEventHandler, PassengerRequestRejectedEventHandler { @Override public void handleEvent(DrtRequestSubmittedEvent event) { - String ids = event.getPersonIds().stream().map(Object::toString).collect(Collectors.joining("-")); - requestInfo.computeIfAbsent(ids, id -> new RequestInfo()).submissionTime = event - .getTime(); - requestInfo.computeIfAbsent(ids, id -> new RequestInfo()).submissionTimes - .add(event.getTime()); - + for (Id personId : event.getPersonIds()) { + requestInfo.computeIfAbsent(personId.toString(), id -> new RequestInfo()).submissionTime = event + .getTime(); + requestInfo.computeIfAbsent(personId.toString(), id -> new RequestInfo()).drtRequestId = event + .getRequestId(); + requestInfo.computeIfAbsent(personId.toString(), id -> new RequestInfo()).submissionTimes + .add(event.getTime()); + } } @Override public void handleEvent(PassengerRequestRejectedEvent event) { - requestInfo.computeIfAbsent(event.getPersonIds().stream().map(Object::toString).collect(Collectors.joining("-")), id -> new RequestInfo()).rejected = true; + for (Id personId : event.getPersonIds()) { + requestInfo.computeIfAbsent(personId.toString(), id -> new RequestInfo()).rejected = true; + } } @Override diff --git a/contribs/drt/src/test/java/org/matsim/contrib/drt/sharingmetrics/SharingFactorTest.java b/contribs/drt/src/test/java/org/matsim/contrib/drt/sharingmetrics/SharingFactorTest.java index b731cedf080..7a7acba2809 100644 --- a/contribs/drt/src/test/java/org/matsim/contrib/drt/sharingmetrics/SharingFactorTest.java +++ b/contribs/drt/src/test/java/org/matsim/contrib/drt/sharingmetrics/SharingFactorTest.java @@ -3,7 +3,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.population.Person; +import org.matsim.contrib.drt.passenger.events.DrtRequestSubmittedEvent; import org.matsim.contrib.dvrp.fleet.DvrpVehicle; import org.matsim.contrib.dvrp.optimizer.Request; import org.matsim.contrib.dvrp.passenger.PassengerDroppedOffEvent; @@ -11,8 +11,7 @@ import org.matsim.core.events.ParallelEventsManager; import org.matsim.testcases.MatsimTestUtils; -import java.util.HashSet; -import java.util.Set; +import java.util.List; /** * @author nkuehnel / MOIA @@ -31,20 +30,8 @@ public void testDrtSharingFactorHandler() { var personId2 = Id.createPersonId("p2"); - Set> groupRepresentatives = new HashSet<>(); - - // two separate bookings - groupRepresentatives.add(personId1); - groupRepresentatives.add(personId2); - - ParallelEventsManager events = new ParallelEventsManager(false); - SharingMetricsTracker sharingFactorTracker = new SharingMetricsTracker(new SharingMetricsTracker.GroupPredicate() { - @Override - public boolean isGroupRepresentative(Id personId) { - return groupRepresentatives.contains(personId); - } - }); + SharingMetricsTracker sharingFactorTracker = new SharingMetricsTracker(); events.addHandler(sharingFactorTracker); events.initProcessing(); @@ -55,6 +42,7 @@ public boolean isGroupRepresentative(Id personId) { var requestId = Id.create(0, Request.class); Assertions.assertNull(sharingFactorTracker.getPoolingRates().get(requestId)); + events.processEvent(new DrtRequestSubmittedEvent(0.0, mode, requestId, List.of(personId1), null, null, 0, 0, 0, 0, 0)); events.processEvent(new PassengerPickedUpEvent(100.0, mode, requestId, personId1, vehicleId)); events.processEvent(new PassengerDroppedOffEvent(300.0, mode, requestId, personId1, vehicleId)); events.flush(); @@ -74,6 +62,8 @@ public boolean isGroupRepresentative(Id personId) { Assertions.assertNull(sharingFactorTracker.getPoolingRates().get(requestId1)); Assertions.assertNull(sharingFactorTracker.getPoolingRates().get(requestId2)); + events.processEvent(new DrtRequestSubmittedEvent(0.0, mode, requestId1, List.of(personId1), null, null, 0, 0, 0, 0, 0)); + events.processEvent(new DrtRequestSubmittedEvent(0.0, mode, requestId2, List.of(personId2), null, null, 0, 0, 0, 0, 0)); events.processEvent(new PassengerPickedUpEvent(100.0, mode, requestId1, personId1, vehicleId)); events.processEvent(new PassengerDroppedOffEvent(300.0, mode, requestId1, personId1, vehicleId)); events.processEvent(new PassengerPickedUpEvent(300.0, mode, requestId2, personId2, vehicleId)); @@ -101,6 +91,8 @@ public boolean isGroupRepresentative(Id personId) { Assertions.assertNull(sharingFactorTracker.getPoolingRates().get(requestId1)); Assertions.assertNull(sharingFactorTracker.getPoolingRates().get(requestId2)); + events.processEvent(new DrtRequestSubmittedEvent(0.0, mode, requestId1, List.of(personId1), null, null, 0, 0, 0, 0, 0)); + events.processEvent(new DrtRequestSubmittedEvent(0.0, mode, requestId2, List.of(personId2), null, null, 0, 0, 0, 0, 0)); events.processEvent(new PassengerPickedUpEvent(100.0, mode, requestId1, personId1, vehicleId)); events.processEvent(new PassengerPickedUpEvent(200.0, mode, requestId2, personId2, vehicleId)); events.processEvent(new PassengerDroppedOffEvent(300.0, mode, requestId1, personId1, vehicleId)); @@ -129,6 +121,9 @@ public boolean isGroupRepresentative(Id personId) { Assertions.assertNull(sharingFactorTracker.getPoolingRates().get(requestId1)); Assertions.assertNull(sharingFactorTracker.getPoolingRates().get(requestId2)); + events.processEvent(new DrtRequestSubmittedEvent(0.0, mode, requestId1, List.of(personId1), null, null, 0, 0, 0, 0, 0)); + events.processEvent(new DrtRequestSubmittedEvent(0.0, mode, requestId2, List.of(personId2), null, null, 0, 0, 0, 0, 0)); + events.processEvent(new PassengerPickedUpEvent(100.0, mode, requestId1, personId1, vehicleId)); events.processEvent(new PassengerPickedUpEvent(200.0, mode, requestId2, personId2, vehicleId)); events.processEvent(new PassengerDroppedOffEvent(300.0, mode, requestId2, personId2, vehicleId)); @@ -143,7 +138,7 @@ public boolean isGroupRepresentative(Id personId) { Assertions.assertNotNull(sharingFactorTracker.getPoolingRates().get(requestId2)); Assertions.assertNotNull(sharingFactorTracker.getSharingFactors().get(requestId2)); Assertions.assertTrue(sharingFactorTracker.getPoolingRates().get(requestId2)); - Assertions.assertEquals((100. ) / (50.), sharingFactorTracker.getSharingFactors().get(requestId2), MatsimTestUtils.EPSILON); + Assertions.assertEquals((100.) / (50.), sharingFactorTracker.getSharingFactors().get(requestId2), MatsimTestUtils.EPSILON); } //clean up @@ -157,6 +152,9 @@ public boolean isGroupRepresentative(Id personId) { Assertions.assertNull(sharingFactorTracker.getPoolingRates().get(requestId1)); Assertions.assertNull(sharingFactorTracker.getPoolingRates().get(requestId2)); + events.processEvent(new DrtRequestSubmittedEvent(0.0, mode, requestId1, List.of(personId1), null, null, 0, 0, 0, 0, 0)); + events.processEvent(new DrtRequestSubmittedEvent(0.0, mode, requestId2, List.of(personId2), null, null, 0, 0, 0, 0, 0)); + events.processEvent(new PassengerPickedUpEvent(100.0, mode, requestId1, personId1, vehicleId)); events.processEvent(new PassengerPickedUpEvent(100.0, mode, requestId2, personId2, vehicleId)); events.processEvent(new PassengerDroppedOffEvent(200.0, mode, requestId1, personId1, vehicleId)); @@ -179,27 +177,23 @@ public boolean isGroupRepresentative(Id personId) { sharingFactorTracker.notifyMobsimBeforeCleanup(null); { - // two persons part of a group, only person 1 is representative -> not pooled - groupRepresentatives.remove(personId2); + // two persons part of a group -> not pooled var requestId1 = Id.create(0, Request.class); - var requestId2 = Id.create(1, Request.class); Assertions.assertNull(sharingFactorTracker.getPoolingRates().get(requestId1)); - Assertions.assertNull(sharingFactorTracker.getPoolingRates().get(requestId2)); + + events.processEvent(new DrtRequestSubmittedEvent(0.0, mode, requestId1, List.of(personId1, personId2), null, null, 0, 0, 0, 0, 0)); events.processEvent(new PassengerPickedUpEvent(100.0, mode, requestId1, personId1, vehicleId)); - events.processEvent(new PassengerPickedUpEvent(100.0, mode, requestId2, personId2, vehicleId)); + events.processEvent(new PassengerPickedUpEvent(100.0, mode, requestId1, personId2, vehicleId)); events.processEvent(new PassengerDroppedOffEvent(200.0, mode, requestId1, personId1, vehicleId)); - events.processEvent(new PassengerDroppedOffEvent(200.0, mode, requestId2, personId2, vehicleId)); + events.processEvent(new PassengerDroppedOffEvent(200.0, mode, requestId1, personId2, vehicleId)); events.flush(); Assertions.assertNotNull(sharingFactorTracker.getPoolingRates().get(requestId1)); Assertions.assertNotNull(sharingFactorTracker.getSharingFactors().get(requestId1)); Assertions.assertFalse(sharingFactorTracker.getPoolingRates().get(requestId1)); Assertions.assertEquals(1., sharingFactorTracker.getSharingFactors().get(requestId1), MatsimTestUtils.EPSILON); - - Assertions.assertNull(sharingFactorTracker.getPoolingRates().get(requestId2)); - Assertions.assertNull(sharingFactorTracker.getSharingFactors().get(requestId2)); } } } diff --git a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/DefaultPassengerEngine.java b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/DefaultPassengerEngine.java index 6a19b93d470..7e11e5e8dd8 100644 --- a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/DefaultPassengerEngine.java +++ b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/DefaultPassengerEngine.java @@ -24,9 +24,11 @@ import com.google.common.base.Verify; import org.matsim.api.core.v01.Id; +import org.matsim.api.core.v01.Identifiable; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.Leg; +import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Route; import org.matsim.contrib.dvrp.optimizer.Request; import org.matsim.contrib.dvrp.optimizer.VrpOptimizer; @@ -73,8 +75,12 @@ public final class DefaultPassengerEngine implements PassengerEngine, PassengerR //accessed in doSimStep() and handleEvent() (potential data races) private final Queue rejectedRequestsEvents = new ConcurrentLinkedQueue<>(); + private final PassengerGroupIdentifier passengerGroupIdentifier; + private final Map, List> groupDepartureStage = new LinkedHashMap<>(); + + DefaultPassengerEngine(String mode, EventsManager eventsManager, MobsimTimer mobsimTimer, PassengerRequestCreator requestCreator, - VrpOptimizer optimizer, Network network, PassengerRequestValidator requestValidator, AdvanceRequestProvider advanceRequestProvider) { + VrpOptimizer optimizer, Network network, PassengerRequestValidator requestValidator, AdvanceRequestProvider advanceRequestProvider, PassengerGroupIdentifier passengerGroupIdentifier) { this.mode = mode; this.mobsimTimer = mobsimTimer; this.requestCreator = requestCreator; @@ -83,6 +89,7 @@ public final class DefaultPassengerEngine implements PassengerEngine, PassengerR this.requestValidator = requestValidator; this.eventsManager = eventsManager; this.advanceRequestProvider = advanceRequestProvider; + this.passengerGroupIdentifier = passengerGroupIdentifier; internalPassengerHandling = new InternalPassengerHandling(mode, eventsManager); } @@ -99,6 +106,9 @@ public void onPrepareSim() { @Override public void doSimStep(double time) { + + handleGroupDepartures(time); + // If prebooked requests are rejected (by the optimizer, through an // event) after submission, but before departure, the PassengerEngine does not // know this agent yet. Hence, we wait with setting the state to abort until the @@ -128,45 +138,81 @@ public void doSimStep(double time) { } } - @Override - public void afterSim() { - } + private void handleGroupDepartures(double now) { - @Override - public boolean handleDeparture(double now, MobsimAgent agent, Id fromLinkId) { - if (!agent.getMode().equals(mode)) { - return false; + groupDepartureStage.values().forEach(g -> g.sort(Comparator.comparing(Identifiable::getId))); + for (List group : groupDepartureStage.values()) { + handleDepartureImpl(now, group); } + groupDepartureStage.clear(); + } - MobsimPassengerAgent passenger = (MobsimPassengerAgent)agent; - internalInterface.registerAdditionalAgentOnLink(passenger); + private void handleDepartureImpl(double now, List group) { + List> groupIds = group.stream().map(Identifiable::getId).toList(); + + MobsimPassengerAgent representative = group.get(0); - Id toLinkId = passenger.getDestinationLinkId(); + Id fromLinkId = representative.getCurrentLinkId(); + Id toLinkId = representative.getDestinationLinkId(); + + Preconditions.checkArgument(group.stream().allMatch(a -> a.getCurrentLinkId().equals(fromLinkId))); + Preconditions.checkArgument(group.stream().allMatch(a -> a.getDestinationLinkId().equals(toLinkId))); // try to find a prebooked requests that is associated to this leg - Leg leg = (Leg)((PlanAgent)passenger).getCurrentPlanElement(); - PassengerRequest request = advanceRequestProvider.retrieveRequest(agent, leg); + Leg leg = (Leg)((PlanAgent)representative).getCurrentPlanElement(); + PassengerRequest request = advanceRequestProvider.retrieveRequest(representative, leg); if (request == null) { // immediate request - Route route = ((Leg)((PlanAgent)passenger).getCurrentPlanElement()).getRoute(); + Route route = leg.getRoute(); request = requestCreator.createRequest(internalPassengerHandling.createRequestId(), - List.of(passenger.getId()), route, getLink(fromLinkId), getLink(toLinkId), now, now); + groupIds, route, getLink(fromLinkId), getLink(toLinkId), now, now); // must come before validateAndSubmitRequest (to come before rejection event) - eventsManager.processEvent(new PassengerWaitingEvent(now, mode, request.getId(), List.of(passenger.getId()))); - activePassengers.put(request.getId(), List.of(passenger)); + eventsManager.processEvent(new PassengerWaitingEvent(now, mode, request.getId(), groupIds)); + activePassengers.put(request.getId(), group); - validateAndSubmitRequest(List.of(passenger), request, now); + validateAndSubmitRequest(group, request, now); } else { // advance request - eventsManager.processEvent(new PassengerWaitingEvent(now, mode, request.getId(), List.of(passenger.getId()))); - activePassengers.put(request.getId(), List.of(passenger)); + + Preconditions.checkArgument(request.getPassengerIds().size() == group.size()); + Preconditions.checkArgument(request.getPassengerIds().containsAll(groupIds)); + + for (MobsimPassengerAgent agent : group) { + eventsManager.processEvent(new PassengerWaitingEvent(now, mode, request.getId(), List.of(agent.getId()))); + } + + activePassengers.put(request.getId(), group); PassengerPickupActivity pickupActivity = waitingForPassenger.remove(request.getId()); if (pickupActivity != null) { // the vehicle is already waiting for the request, notify it - pickupActivity.notifyPassengersAreReadyForDeparture(List.of(passenger), now); + pickupActivity.notifyPassengersAreReadyForDeparture(group, now); } } + } + + @Override + public void afterSim() { + } + + @Override + public boolean handleDeparture(double now, MobsimAgent agent, Id fromLinkId) { + if (!agent.getMode().equals(mode)) { + return false; + } + + MobsimPassengerAgent passenger = (MobsimPassengerAgent)agent; + internalInterface.registerAdditionalAgentOnLink(passenger); + + Optional> groupId = passengerGroupIdentifier.getGroupId(passenger); + + if(groupId.isPresent()) { + groupDepartureStage.computeIfAbsent(groupId.get(), k -> new ArrayList<>()).add(passenger); + //terminate early as more group members may depart later + return true; + } + + handleDepartureImpl(now, List.of(passenger)); return true; } @@ -252,7 +298,7 @@ public static Provider createProvider(String mode) { public DefaultPassengerEngine get() { return new DefaultPassengerEngine(getMode(), eventsManager, mobsimTimer, getModalInstance(PassengerRequestCreator.class), getModalInstance(VrpOptimizer.class), getModalInstance(Network.class), getModalInstance(PassengerRequestValidator.class), - getModalInstance(AdvanceRequestProvider.class)); + getModalInstance(AdvanceRequestProvider.class), getModalInstance(PassengerGroupIdentifier.class)); } }; } diff --git a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/GroupPassengerEngine.java b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/GroupPassengerEngine.java deleted file mode 100644 index a5c2f9e9c84..00000000000 --- a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/GroupPassengerEngine.java +++ /dev/null @@ -1,231 +0,0 @@ -package org.matsim.contrib.dvrp.passenger; - -import com.google.common.base.Preconditions; -import com.google.common.base.Verify; -import jakarta.inject.Inject; -import jakarta.inject.Provider; -import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.Identifiable; -import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.network.Network; -import org.matsim.api.core.v01.population.Leg; -import org.matsim.api.core.v01.population.Route; -import org.matsim.contrib.dvrp.optimizer.Request; -import org.matsim.contrib.dvrp.optimizer.VrpOptimizer; -import org.matsim.contrib.dvrp.run.DvrpModes; -import org.matsim.core.api.experimental.events.EventsManager; -import org.matsim.core.gbl.Gbl; -import org.matsim.core.mobsim.framework.*; -import org.matsim.core.mobsim.qsim.InternalInterface; -import org.matsim.core.modal.ModalProviders; - -import java.util.*; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.stream.Collectors; - -public class GroupPassengerEngine implements PassengerEngine, PassengerRequestRejectedEventHandler { - - private final String mode; - private final MobsimTimer mobsimTimer; - - private final EventsManager eventsManager; - - private final PassengerRequestCreator requestCreator; - private final VrpOptimizer optimizer; - private final Network network; - private final PassengerRequestValidator requestValidator; - - private final InternalPassengerHandling internalPassengerHandling; - - private InternalInterface internalInterface; - - - //accessed in doSimStep() and handleDeparture() (no need to sync) - private final Map, List> activePassengers = new HashMap<>(); - - // holds vehicle stop activities for requests that have not arrived at departure point yet - private final Map, PassengerPickupActivity> waitingForPassenger = new HashMap<>(); - - //accessed in doSimStep() and handleEvent() (potential data races) - private final Queue rejectedRequestsEvents = new ConcurrentLinkedQueue<>(); - - private final Set currentDepartures = new LinkedHashSet<>(); - - private final PassengerGroupIdentifier groupIdentifier; - - GroupPassengerEngine(String mode, EventsManager eventsManager, MobsimTimer mobsimTimer, PassengerRequestCreator requestCreator, VrpOptimizer optimizer, Network network, PassengerRequestValidator requestValidator, PassengerGroupIdentifier groupIdentifier) { - this.mode = mode; - this.eventsManager = eventsManager; - this.mobsimTimer = mobsimTimer; - this.requestCreator = requestCreator; - this.optimizer = optimizer; - this.network = network; - this.requestValidator = requestValidator; - this.groupIdentifier = groupIdentifier; - - internalPassengerHandling = new InternalPassengerHandling(mode, eventsManager); - } - - @Override - public void setInternalInterface(InternalInterface internalInterface) { - this.internalInterface = internalInterface; - internalPassengerHandling.setInternalInterface(internalInterface); - } - - @Override - public void onPrepareSim() { - } - - @Override - public void doSimStep(double time) { - handleDepartures(time); - while (!rejectedRequestsEvents.isEmpty()) { - List passengers = activePassengers.remove(rejectedRequestsEvents.poll().getRequestId()); - //not much else can be done for immediate requests - //set the passenger agent to abort - the event will be thrown by the QSim - for (MobsimPassengerAgent passenger : passengers) { - passenger.setStateToAbort(mobsimTimer.getTimeOfDay()); - internalInterface.arrangeNextAgentState(passenger); - } - } - } - - @Override - public void afterSim() { - } - - @Override - public boolean handleDeparture(double now, MobsimAgent agent, Id fromLinkId) { - - if (!agent.getMode().equals(mode)) { - return false; - } - - MobsimPassengerAgent passenger = (MobsimPassengerAgent)agent; - internalInterface.registerAdditionalAgentOnLink(passenger); - currentDepartures.add(passenger); - return true; - } - - private void handleDepartures(double now) { - Map, List> agentGroups = - currentDepartures.stream().collect( - Collectors.groupingBy( - groupIdentifier, - Collectors.collectingAndThen(Collectors.toList(), list -> { - list.sort(Comparator.comparing(MobsimPassengerAgent::getId)); - return list; - }))); - - for (List group : agentGroups.values()) { - - Iterator iterator = group.iterator(); - MobsimAgent firstAgent = iterator.next(); - MobsimPassengerAgent passenger = (MobsimPassengerAgent) firstAgent; - - Id toLinkId = firstAgent.getDestinationLinkId(); - - while (iterator.hasNext()) { - MobsimAgent next = iterator.next(); - Gbl.assertIf(firstAgent.getCurrentLinkId().equals(next.getCurrentLinkId())); - Gbl.assertIf(toLinkId.equals(next.getDestinationLinkId())); - } - - Route route = ((Leg)((PlanAgent)passenger).getCurrentPlanElement()).getRoute(); - - PassengerRequest request = requestCreator.createRequest(internalPassengerHandling.createRequestId(), - group.stream().map(Identifiable::getId).toList(), route, - getLink(firstAgent.getCurrentLinkId()), getLink(toLinkId), - now, now); - - - // must come before validateAndSubmitRequest (to come before rejection event) - eventsManager.processEvent(new PassengerWaitingEvent(now, mode, request.getId(), group.stream().map(Identifiable::getId).toList())); - - validateAndSubmitRequest(group, request, mobsimTimer.getTimeOfDay()); - } - currentDepartures.clear(); - } - - private void validateAndSubmitRequest(List passengers, PassengerRequest request, double now) { - activePassengers.put(request.getId(), passengers); - if (internalPassengerHandling.validateRequest(request, requestValidator, now)) { - //need to synchronise to address cases where requestSubmitted() may: - // - be called from outside DepartureHandlers - // - interfere with VrpOptimizer.nextTask() - // - impact VrpAgentLogic.computeNextAction() - synchronized (optimizer) { - //optimizer can also reject request if cannot handle it - // (async operation, notification comes via the events channel) - optimizer.requestSubmitted(request); - } - } - } - - private Link getLink(Id linkId) { - return Preconditions.checkNotNull(network.getLinks().get(linkId), "Link id=%s does not exist in network for mode %s. Agent departs from a link that does not belong to that network?", linkId, mode); - } - - /** - * There are two ways of interacting with the PassengerEngine: - *

- * - (1) The stop activity tries to pick up a passenger and receives whether the - * pickup succeeded or not (see tryPickUpPassenger). In the classic - * implementation, the vehicle only calls tryPickUpPassenger at the time when it - * actually wants to pick up the person (at the end of the activity). It may - * happen that the person is not present yet. In that case, the pickup request - * is saved and notifyPassengerReady is called on the stop activity upen - * departure of the agent. - *

- * - (2) If pickup and dropoff times are handled more flexibly by the stop - * activity, it might want to detect whether an agent is ready to be picked up, - * then start an "interaction time" and only after perform the actual pickup. - * For that purpose, we have queryPickUpPassenger, which indicates whether the - * agent is already there, and, if not, makes sure that the stop activity is - * notified once the agent arrives for departure. - */ - @Override - public boolean notifyWaitForPassengers(PassengerPickupActivity pickupActivity, MobsimDriverAgent driver, Id requestId) { - - if (!activePassengers.containsKey(requestId)) { - waitingForPassenger.put(requestId, pickupActivity); - return false; - } - - return true; - } - - @Override - public boolean tryPickUpPassengers(PassengerPickupActivity pickupActivity, MobsimDriverAgent driver, Id requestId, double now) { - boolean pickedUp = internalPassengerHandling.tryPickUpPassengers(driver, activePassengers.get(requestId), requestId, now); - Verify.verify(pickedUp, "Not possible without prebooking"); - return pickedUp; - } - - @Override - public void dropOffPassengers(MobsimDriverAgent driver, Id requestId, double now) { - internalPassengerHandling.dropOffPassengers(driver, activePassengers.remove(requestId), requestId, now); - } - - @Override - public void handleEvent(PassengerRequestRejectedEvent event) { - if (event.getMode().equals(mode)) { - rejectedRequestsEvents.add(event); - } - } - - public static Provider createProvider(String mode) { - return new ModalProviders.AbstractProvider<>(mode, DvrpModes::mode) { - @Inject - private EventsManager eventsManager; - - @Inject - private MobsimTimer mobsimTimer; - - @Override - public GroupPassengerEngine get() { - return new GroupPassengerEngine(getMode(), eventsManager, mobsimTimer, getModalInstance(PassengerRequestCreator.class), getModalInstance(VrpOptimizer.class), getModalInstance(Network.class), getModalInstance(PassengerRequestValidator.class), getModalInstance(PassengerGroupIdentifier.class)); - } - }; - } -} diff --git a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/PassengerEngineQSimModule.java b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/PassengerEngineQSimModule.java index e9d806af179..25372c12000 100644 --- a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/PassengerEngineQSimModule.java +++ b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/PassengerEngineQSimModule.java @@ -4,13 +4,15 @@ import org.matsim.contrib.dvrp.run.AbstractDvrpModeQSimModule; +import java.util.Optional; + /** * dvrp needs {@link PassengerHandler} bound to something. It is first bound to a {@link PassengerEngine} so it can also do stuff on its own. Then, * {@link PassengerEngine} is bound to one of the existing implementations. */ public class PassengerEngineQSimModule extends AbstractDvrpModeQSimModule { public enum PassengerEngineType { - DEFAULT, WITH_PREBOOKING, TELEPORTING, WITH_GROUPS + DEFAULT, WITH_PREBOOKING, TELEPORTING } private final PassengerEngineType type; @@ -27,6 +29,8 @@ public PassengerEngineQSimModule(String mode, PassengerEngineType type) { @Override protected void configureQSim() { bindModal(PassengerHandler.class).to(modalKey(PassengerEngine.class)); + bindModal(PassengerGroupIdentifier.class).toInstance(agent -> Optional.empty()); + // (PassengerEngine is a more powerful interface.) addMobsimScopeEventHandlerBinding().to(modalKey(PassengerEngine.class)); @@ -44,10 +48,6 @@ protected void configureQSim() { addModalComponent( PassengerEngine.class, TeleportingPassengerEngine.createProvider( getMode() ) ); return; } - case WITH_GROUPS -> { - addModalComponent( PassengerEngine.class, GroupPassengerEngine.createProvider( getMode() ) ); - return; - } default -> throw new IllegalStateException( "Type: " + type + " is not supported" ); } } diff --git a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/PassengerGroupIdentifier.java b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/PassengerGroupIdentifier.java index 8dba2bdac52..0a644c87a72 100644 --- a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/PassengerGroupIdentifier.java +++ b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/PassengerGroupIdentifier.java @@ -3,19 +3,18 @@ import org.matsim.api.core.v01.Id; import org.matsim.core.mobsim.framework.MobsimPassengerAgent; -import java.util.function.Function; +import java.util.Optional; /** * Provides a method to identify the passenger group id of an agent. * @author nkuehnel / MOIA */ -public interface PassengerGroupIdentifier extends Function> { +public interface PassengerGroupIdentifier { class PassengerGroup { private PassengerGroup(){} } - @Override - Id apply(MobsimPassengerAgent agent); + Optional> getGroupId(MobsimPassengerAgent agent); } diff --git a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/PassengerRequestRejectedEvent.java b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/PassengerRequestRejectedEvent.java index 0d17138700d..13c131743db 100644 --- a/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/PassengerRequestRejectedEvent.java +++ b/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/passenger/PassengerRequestRejectedEvent.java @@ -70,7 +70,8 @@ public static PassengerRequestRejectedEvent convert(GenericEvent event) { List> personIds = new ArrayList<>(); for (String person : personIdsAttribute) { personIds.add(Id.create(person, Person.class)); - } String cause = Objects.requireNonNull(attributes.get(ATTRIBUTE_CAUSE)); + } + String cause = Objects.requireNonNull(attributes.get(ATTRIBUTE_CAUSE)); return new PassengerRequestRejectedEvent(time, mode, requestId, personIds, cause); } } diff --git a/contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/passenger/GroupPassengerEngineTest.java b/contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/passenger/PassengerGroupTest.java similarity index 93% rename from contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/passenger/GroupPassengerEngineTest.java rename to contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/passenger/PassengerGroupTest.java index 9630efb9374..61a9804b4bf 100644 --- a/contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/passenger/GroupPassengerEngineTest.java +++ b/contribs/dvrp/src/test/java/org/matsim/contrib/dvrp/passenger/PassengerGroupTest.java @@ -30,11 +30,15 @@ import org.matsim.vehicles.VehicleUtils; import java.util.List; +import java.util.Optional; import java.util.Set; import static org.matsim.contrib.dvrp.passenger.PassengerEngineTestFixture.*; -public class GroupPassengerEngineTest { +/** + * @author nkuehnel / MOIA + */ +public class PassengerGroupTest { private final PassengerEngineTestFixture fixture = new PassengerEngineTestFixture(); @@ -99,7 +103,7 @@ void test_group() { private QSim createQSim(PassengerRequestValidator requestValidator, Class optimizerClass) { return new QSimBuilder(fixture.config).useDefaults() .addOverridingModule(new MobsimScopeEventHandlingModule()) - .addQSimModule(new PassengerEngineQSimModule(MODE, PassengerEngineQSimModule.PassengerEngineType.WITH_GROUPS)) + .addQSimModule(new PassengerEngineQSimModule(MODE, PassengerEngineQSimModule.PassengerEngineType.DEFAULT)) .addQSimModule(new VrpAgentSourceQSimModule(MODE)) .addQSimModule(new AbstractDvrpModeQSimModule(MODE) { @Override @@ -111,6 +115,7 @@ protected void configureQSim() { bindModal(PassengerRequestCreator.class).to(OneTaxiRequest.OneTaxiRequestCreator.class) .asEagerSingleton(); bindModal(PassengerRequestValidator.class).toInstance(requestValidator); + bindModal(AdvanceRequestProvider.class).toInstance(AdvanceRequestProvider.NONE); //supply addQSimComponentBinding(DynActivityEngine.COMPONENT_NAME).to(DynActivityEngine.class); @@ -120,8 +125,13 @@ protected void configureQSim() { bindModal(VrpAgentLogic.DynActionCreator.class).to(OneTaxiActionCreator.class) .asEagerSingleton(); + } + }) + .addOverridingQSimModule(new AbstractDvrpModeQSimModule(MODE) { + @Override + protected void configureQSim() { //groups - bindModal(PassengerGroupIdentifier.class).toInstance(agent -> Id.create("group1", PassengerGroupIdentifier.PassengerGroup.class)); + bindModal(PassengerGroupIdentifier.class).toInstance(agent -> Optional.of(Id.create("group1", PassengerGroupIdentifier.PassengerGroup.class))); } }) .configureQSimComponents(components -> { diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/VehicleChargingHandler.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/VehicleChargingHandler.java index 6c8181d83d7..196e3fd1b52 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/VehicleChargingHandler.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/charging/VehicleChargingHandler.java @@ -53,6 +53,7 @@ import org.matsim.vehicles.Vehicle; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; /** * This is an events based approach to trigger vehicle charging. Vehicles will be charged as soon as a person begins a charging activity. @@ -71,7 +72,7 @@ public class VehicleChargingHandler private final Map, Id> lastVehicleUsed = new HashMap<>(); private final Map, Id> lastDriver = new HashMap<>(); private final Map, Id> vehiclesAtChargers = new HashMap<>(); - private final Set> agentsInChargerQueue = new HashSet<>(); + private final Set> agentsInChargerQueue = ConcurrentHashMap.newKeySet(); private final ChargingInfrastructure chargingInfrastructure; private final ElectricFleet electricFleet; diff --git a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/DriveDischargingHandler.java b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/DriveDischargingHandler.java index 53b29390fac..1f87d091b7b 100644 --- a/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/DriveDischargingHandler.java +++ b/contribs/ev/src/main/java/org/matsim/contrib/ev/discharging/DriveDischargingHandler.java @@ -19,12 +19,15 @@ package org.matsim.contrib.ev.discharging; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; import java.util.Map; +import java.util.Queue; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; 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.events.HasVehicleId; import org.matsim.api.core.v01.events.LinkLeaveEvent; import org.matsim.api.core.v01.events.VehicleEntersTrafficEvent; import org.matsim.api.core.v01.events.VehicleLeavesTrafficEvent; @@ -37,8 +40,8 @@ import org.matsim.contrib.ev.fleet.ElectricVehicle; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.events.MobsimScopeEventHandler; -import org.matsim.core.mobsim.framework.events.MobsimAfterSimStepEvent; -import org.matsim.core.mobsim.framework.listeners.MobsimAfterSimStepListener; +import org.matsim.core.mobsim.qsim.InternalInterface; +import org.matsim.core.mobsim.qsim.interfaces.MobsimEngine; import org.matsim.vehicles.Vehicle; import com.google.inject.Inject; @@ -49,8 +52,7 @@ * idle discharge process (see {@link IdleDischargingHandler}). */ public final class DriveDischargingHandler - implements LinkLeaveEventHandler, VehicleEntersTrafficEventHandler, VehicleLeavesTrafficEventHandler, MobsimScopeEventHandler, - MobsimAfterSimStepListener { + implements LinkLeaveEventHandler, VehicleEntersTrafficEventHandler, VehicleLeavesTrafficEventHandler, MobsimScopeEventHandler, MobsimEngine { private static class EvDrive { private final Id vehicleId; @@ -73,15 +75,15 @@ private boolean isOnFirstLink() { private final Map, ? extends ElectricVehicle> eVehicles; private final Map, EvDrive> evDrives; - private final List linkLeaveEvents = new ArrayList<>(); - private final List trafficLeaveEvents = new ArrayList<>(); + private final Queue linkLeaveEvents = new ConcurrentLinkedQueue<>(); + private final Queue trafficLeaveEvents = new ConcurrentLinkedQueue<>(); @Inject DriveDischargingHandler(ElectricFleet data, Network network, EventsManager eventsManager) { this.network = network; this.eventsManager = eventsManager; eVehicles = data.getElectricVehicles(); - evDrives = new HashMap<>(eVehicles.size() / 10); + evDrives = new ConcurrentHashMap<>(eVehicles.size() / 10); } @Override @@ -95,38 +97,62 @@ public void handleEvent(VehicleEntersTrafficEvent event) { @Override public void handleEvent(LinkLeaveEvent event) { - linkLeaveEvents.add(event); + if (evDrives.containsKey(event.getVehicleId())) {// handle only our EVs + linkLeaveEvents.add(event); + } } @Override public void handleEvent(VehicleLeavesTrafficEvent event) { - trafficLeaveEvents.add(event); + if (evDrives.containsKey(event.getVehicleId())) {// handle only our EVs + trafficLeaveEvents.add(event); + } + } + + @Override + public void onPrepareSim() { + } + + @Override + public void afterSim() { + // process remaining events + doSimStep(Double.POSITIVE_INFINITY); } @Override - public void notifyMobsimAfterSimStep(MobsimAfterSimStepEvent e) { + public void setInternalInterface(InternalInterface internalInterface) { + } + + @Override + public void doSimStep(double time) { + handleQueuedEvents(linkLeaveEvents, time, false); + handleQueuedEvents(trafficLeaveEvents, time, true); + } + + private void handleQueuedEvents(Queue queue, double time, boolean leftTraffic) { // We want to process events in the main thread (instead of the event handling threads). // This is to eliminate race conditions, where the battery is read/modified by many threads without proper synchronisation - for (var event : linkLeaveEvents) { - EvDrive evDrive = dischargeVehicle(event.getVehicleId(), event.getLinkId(), event.getTime()); - if (evDrive != null) { - evDrive.movedOverNodeTime = event.getTime(); + while (!queue.isEmpty()) { + var event = queue.peek(); + if (event.getTime() == time) { + // There is a potential race condition wrt processing events between doSimStep() and handleEvent(). + // To ensure a deterministic behaviour, we only process events from the previous time step. + break; } - } - linkLeaveEvents.clear(); - for (var event : trafficLeaveEvents) { - EvDrive evDrive = dischargeVehicle(event.getVehicleId(), event.getLinkId(), event.getTime()); - if (evDrive != null) { + var evDrive = dischargeVehicle(event.getVehicleId(), event.getLinkId(), event.getTime(), time); + if (leftTraffic) { evDrives.remove(evDrive.vehicleId); + } else { + evDrive.movedOverNodeTime = event.getTime(); } + queue.remove(); } - trafficLeaveEvents.clear(); } - private EvDrive dischargeVehicle(Id vehicleId, Id linkId, double eventTime) { + private EvDrive dischargeVehicle(Id vehicleId, Id linkId, double eventTime, double now) { EvDrive evDrive = evDrives.get(vehicleId); - if (evDrive != null && !evDrive.isOnFirstLink()) {// handle only our EVs, except for the first link + if (!evDrive.isOnFirstLink()) {// skip the first link Link link = network.getLinks().get(linkId); double tt = eventTime - evDrive.movedOverNodeTime; ElectricVehicle ev = evDrive.ev; @@ -135,8 +161,8 @@ private EvDrive dischargeVehicle(Id vehicleId, Id linkId, double //Energy consumption may be negative on links with negative slope ev.getBattery() .dischargeEnergy(energy, - missingEnergy -> eventsManager.processEvent(new MissingEnergyEvent(eventTime, ev.getId(), link.getId(), missingEnergy))); - eventsManager.processEvent(new DrivingEnergyConsumptionEvent(eventTime, vehicleId, linkId, energy, ev.getBattery().getCharge())); + missingEnergy -> eventsManager.processEvent(new MissingEnergyEvent(now, ev.getId(), link.getId(), missingEnergy))); + eventsManager.processEvent(new DrivingEnergyConsumptionEvent(now, vehicleId, linkId, energy, ev.getBattery().getCharge())); } return evDrive; } diff --git a/contribs/ev/test/input/org/matsim/contrib/ev/example/RunEvExampleTest/runTest/output_events.xml.gz b/contribs/ev/test/input/org/matsim/contrib/ev/example/RunEvExampleTest/runTest/output_events.xml.gz index 4e509e420bb..3b1fb60c3eb 100644 Binary files a/contribs/ev/test/input/org/matsim/contrib/ev/example/RunEvExampleTest/runTest/output_events.xml.gz and b/contribs/ev/test/input/org/matsim/contrib/ev/example/RunEvExampleTest/runTest/output_events.xml.gz differ diff --git a/contribs/ev/test/input/org/matsim/contrib/ev/example/RunEvExampleTest/runTestWithChargingDurationEnforcement/output_events.xml.gz b/contribs/ev/test/input/org/matsim/contrib/ev/example/RunEvExampleTest/runTestWithChargingDurationEnforcement/output_events.xml.gz index 45a604e9edb..8589f8c2b83 100644 Binary files a/contribs/ev/test/input/org/matsim/contrib/ev/example/RunEvExampleTest/runTestWithChargingDurationEnforcement/output_events.xml.gz and b/contribs/ev/test/input/org/matsim/contrib/ev/example/RunEvExampleTest/runTestWithChargingDurationEnforcement/output_events.xml.gz differ diff --git a/contribs/ev/test/input/org/matsim/contrib/ev/example/RunEvExampleWithLTHConsumptionModelTest/runTest/output_events.xml.gz b/contribs/ev/test/input/org/matsim/contrib/ev/example/RunEvExampleWithLTHConsumptionModelTest/runTest/output_events.xml.gz index a389b55a8e8..f93dab62299 100644 Binary files a/contribs/ev/test/input/org/matsim/contrib/ev/example/RunEvExampleWithLTHConsumptionModelTest/runTest/output_events.xml.gz and b/contribs/ev/test/input/org/matsim/contrib/ev/example/RunEvExampleWithLTHConsumptionModelTest/runTest/output_events.xml.gz differ diff --git a/contribs/freight/pom.xml b/contribs/freight/pom.xml index 498ee947063..3c805db83f3 100644 --- a/contribs/freight/pom.xml +++ b/contribs/freight/pom.xml @@ -44,6 +44,12 @@ com.graphhopper jsprit-analysis ${jsprit.version} + + + junit + junit + + 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 9514854743f..991ef3eb236 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 @@ -48,9 +48,6 @@ import java.util.Collection; import java.util.List; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*; public class MatsimTransformerTest { @@ -78,7 +75,7 @@ void whenTransforming_jSpritType2matsimType_withCaching_itIsNotCached() { .newInstance("myType").addCapacityDimension(0, 50).setCostPerDistance(10.0).setCostPerTransportTime(5.0) .setFixedCost(100.0).build(); VehicleType matsimType = MatsimJspritFactory.createMatsimVehicleType(jspritType); - assertThat(matsimType, is(not(MatsimJspritFactory.createMatsimVehicleType(jspritType)))); + assertNotEquals(matsimType, MatsimJspritFactory.createMatsimVehicleType(jspritType)); } @Test diff --git a/contribs/hybridsim/pom.xml b/contribs/hybridsim/pom.xml index 8954573f022..40d6ef82106 100644 --- a/contribs/hybridsim/pom.xml +++ b/contribs/hybridsim/pom.xml @@ -11,7 +11,7 @@ 3.25.1 - 1.60.0 + 1.60.1 diff --git a/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/FileUtils.java b/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/FileUtils.java index 52c6842b754..2e051b85d3b 100644 --- a/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/FileUtils.java +++ b/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/FileUtils.java @@ -27,9 +27,7 @@ static QuadTree readPtStops(String ptStopInputFile, final BoundingBox bb QuadTree qTree = new QuadTree(bb.getXMin(), bb.getYMin(), bb.getXMax(), bb.getYMax() ); - try { - BufferedReader bwPtStops = IOUtils.getBufferedReader(ptStopInputFile); - + try (BufferedReader bwPtStops = IOUtils.getBufferedReader(ptStopInputFile)) { String separator = ","; // read header @@ -63,9 +61,9 @@ else if(wrnCntParse == 20) // create pt stop coordinate Coord ptStopCoord = new Coord(Double.parseDouble(parts[xCoordIDX]), Double.parseDouble(parts[yCoordIDX])); - boolean isInBoundary = qTree.getMaxEasting() >= ptStopCoord.getX() && - qTree.getMinEasting() <= ptStopCoord.getX() && - qTree.getMaxNorthing() >= ptStopCoord.getY() && + boolean isInBoundary = qTree.getMaxEasting() >= ptStopCoord.getX() && + qTree.getMinEasting() <= ptStopCoord.getX() && + qTree.getMaxNorthing() >= ptStopCoord.getY() && qTree.getMinNorthing() <= ptStopCoord.getY(); if(!isInBoundary){ if(wrnCntSkip < 20) @@ -100,7 +98,7 @@ static void fillODMatrix(Matrix odMatrix, Map, PtStop> ptStopHashMap, int valueIDX = 2; // column index for travel time or distance value final double EMPTY_ENTRY = 999999.; // indicates that a value is not set (VISUM specific) - final String SEPARATOR = ";"; // + final String SEPARATOR = ";"; // String line = null; // line from input file String parts[] = null; // values accessible via array @@ -141,7 +139,7 @@ else if(wrnCntParam == 20) Id destinationPtStopID = Id.create(parts[destinationPtStopIDX], PtStop.class); // check if a pt stop with the given id exists - if( ptStopHashMap.containsKey(originPtStopID) && + if( ptStopHashMap.containsKey(originPtStopID) && ptStopHashMap.containsKey(destinationPtStopID)){ // add to od matrix @@ -152,7 +150,7 @@ else if(wrnCntParam == 20) // if(wrnCntId == 20){ // log.error( "Found " + wrnCntId + " warnings of type 'pt stop id not found'. There is probably something seriously wrong. Please check. Reasons for this error may be:"); // log.error( "The list of pt stops is incomplete or the stop ids of the VISUM files do not match the ids from the pt stop file."); - // } else + // } else if(! ptStopHashMap.containsKey(originPtStopID) && wrnCntId < 20) log.warn("Could not find an item in QuadTree (i.e. pt station has no coordinates) with pt stop id:" + originPtStopID); else if(! ptStopHashMap.containsKey(destinationPtStopID) && wrnCntId < 20) diff --git a/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/PtMatrix.java b/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/PtMatrix.java index 56d9a6dc6c4..1b838c97876 100644 --- a/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/PtMatrix.java +++ b/contribs/matrixbasedptrouter/src/main/java/org/matsim/contrib/matrixbasedptrouter/PtMatrix.java @@ -20,6 +20,7 @@ package org.matsim.contrib.matrixbasedptrouter; import java.io.BufferedReader; +import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; @@ -84,16 +85,19 @@ public static PtMatrix createPtMatrix(RoutingConfigGroup plansCalcRoute, Boundin String ptTravelTimeInputFile = ippcm.getPtTravelTimesInputFile(); String ptTravelDistanceInputFile = ippcm.getPtTravelDistancesInputFile(); - BufferedReader brTravelTimes = IOUtils.getBufferedReader(ptTravelTimeInputFile); - log.info("Creating travel time OD matrix from VISUM pt stop 2 pt stop travel times file: " + ptTravelTimeInputFile); - final Map, PtStop> ptStopsMap = PtMatrix.convertQuadTree2HashMap(ptStops); - FileUtils.fillODMatrix(originDestinationTravelTimeMatrix, ptStopsMap, brTravelTimes, true); - log.info("Done creating travel time OD matrix. " + originDestinationTravelTimeMatrix.toString()); - - log.info("Creating travel distance OD matrix from VISUM pt stop 2 pt stop travel distance file: " + ptTravelDistanceInputFile); - BufferedReader brTravelDistances = IOUtils.getBufferedReader(ptTravelDistanceInputFile); - FileUtils.fillODMatrix(originDestinationTravelDistanceMatrix, ptStopsMap, brTravelDistances, false); - log.info("Done creating travel distance OD matrix. " + originDestinationTravelDistanceMatrix.toString()); + try (BufferedReader brTravelTimes = IOUtils.getBufferedReader(ptTravelTimeInputFile); + BufferedReader brTravelDistances = IOUtils.getBufferedReader(ptTravelDistanceInputFile); + ) { + log.info("Creating travel time OD matrix from VISUM pt stop 2 pt stop travel times file: " + ptTravelTimeInputFile); + final Map, PtStop> ptStopsMap = PtMatrix.convertQuadTree2HashMap(ptStops); + FileUtils.fillODMatrix(originDestinationTravelTimeMatrix, ptStopsMap, brTravelTimes, true); + log.info("Done creating travel time OD matrix. " + originDestinationTravelTimeMatrix.toString()); + log.info("Creating travel distance OD matrix from VISUM pt stop 2 pt stop travel distance file: " + ptTravelDistanceInputFile); + FileUtils.fillODMatrix(originDestinationTravelDistanceMatrix, ptStopsMap, brTravelDistances, false); + log.info("Done creating travel distance OD matrix. " + originDestinationTravelDistanceMatrix.toString()); + } catch (IOException e) { + throw new RuntimeException(e); + } log.info("Done creating OD matrices with pt stop to pt stop travel times and distances."); diff --git a/contribs/matrixbasedptrouter/src/test/java/org/matsim/contrib/matrixbasedptrouter/PtMatrixTest.java b/contribs/matrixbasedptrouter/src/test/java/org/matsim/contrib/matrixbasedptrouter/PtMatrixTest.java index 2bbde2d9450..8c56b37927a 100644 --- a/contribs/matrixbasedptrouter/src/test/java/org/matsim/contrib/matrixbasedptrouter/PtMatrixTest.java +++ b/contribs/matrixbasedptrouter/src/test/java/org/matsim/contrib/matrixbasedptrouter/PtMatrixTest.java @@ -31,7 +31,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.TransportMode; diff --git a/contribs/otfvis/pom.xml b/contribs/otfvis/pom.xml index 100be456b06..82054bf73eb 100644 --- a/contribs/otfvis/pom.xml +++ b/contribs/otfvis/pom.xml @@ -143,7 +143,7 @@ org.jxmapviewer jxmapviewer2 - 2.6 + 2.8 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 b3300eda5b7..c3ba439a7c7 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 @@ -321,7 +321,7 @@ public final void loadSamplingPointsFromFile(String filename) throws IOException int idx = Integer.parseInt(parts[1]); double x = Double.parseDouble(parts[2]); double y = Double.parseDouble(parts[3]); - final int length = idx > maxIdx ? idx : maxIdx; + final int length = Math.max(idx, maxIdx); Coord[] coords = this.coordsPerZone.computeIfAbsent(zoneId, k -> new Coord[length + 1]); if (coords.length < (idx + 1)) { Coord[] tmp = new Coord[idx + 1]; @@ -453,10 +453,25 @@ public final void calculateAndWritePTMatrices(String networkFilename, double endTime, Config config, String outputPrefix, - BiPredicate trainDetector) throws IOException { + BiPredicate trainDetector, + PTSkimMatrices.CoordAggregator coordAggregator) throws IOException { var matrices = calculatePTMatrices(networkFilename, - transitScheduleFilename, startTime, endTime, config, trainDetector); + transitScheduleFilename, startTime, endTime, config, trainDetector, coordAggregator); + writePTMatricesAsCSV(matrices, outputPrefix); + } + public final void calculateAndWritePTMatrices(String networkFilename, + String transitScheduleFilename, + double startTime, + double endTime, + Config config, + String outputPrefix, + BiPredicate trainDetector + ) throws IOException { + + var matrices = calculatePTMatrices(networkFilename, + transitScheduleFilename, startTime, endTime, config, trainDetector, new PTSkimMatrices.CoordAggregator() { + }); writePTMatricesAsCSV(matrices, outputPrefix); } @@ -476,11 +491,12 @@ public final void writePTMatricesAsCSV(PTSkimMatrices.PtIndicators matri } public final PTSkimMatrices.PtIndicators calculatePTMatrices(String networkFilename, - String transitScheduleFilename, - double startTime, - double endTime, - Config config, - BiPredicate trainDetector) { + String transitScheduleFilename, + double startTime, + double endTime, + Config config, + BiPredicate trainDetector, + PTSkimMatrices.CoordAggregator coordAggregator) { Scenario scenario = ScenarioUtils.createScenario(config); log.info("loading schedule from " + transitScheduleFilename); new TransitScheduleReader(scenario).readFile(transitScheduleFilename); @@ -494,7 +510,7 @@ public final PTSkimMatrices.PtIndicators calculatePTMatrices(String netw log.info("calc PT matrices for " + Time.writeTime(startTime) + " - " + Time.writeTime(endTime)); PTSkimMatrices.PtIndicators matrices = PTSkimMatrices.calculateSkimMatrices( - raptorData, this.coordsPerZone, startTime, endTime, 120, raptorParameters, this.numberOfThreads, trainDetector); + raptorData, this.coordsPerZone, startTime, endTime, 120, raptorParameters, this.numberOfThreads, trainDetector, coordAggregator); return matrices; } @@ -511,15 +527,6 @@ private String findZone(Coord coord, SpatialIndex zonesQt, String zonesIdAttribu return null; } - private static class WeightedCoord { - - Coord coord; - double weight; - - private WeightedCoord(Coord coord, double weight) { - this.coord = coord; - this.weight = weight; - } - } + public record WeightedCoord(Coord coord, double weight){} } diff --git a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/PTSkimMatrices.java b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/PTSkimMatrices.java index 56121f8558a..f1255adf028 100644 --- a/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/PTSkimMatrices.java +++ b/contribs/sbb-extensions/src/main/java/ch/sbb/matsim/analysis/skims/PTSkimMatrices.java @@ -36,14 +36,10 @@ import org.matsim.pt.transitSchedule.api.TransitRoute; import org.matsim.pt.transitSchedule.api.TransitStopFacility; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.BiPredicate; +import java.util.stream.Collectors; /** * Calculates zone-to-zone matrices containing a number of performance indicators related to public transport. @@ -76,7 +72,7 @@ private PTSkimMatrices() { } public static PTSkimMatrices.PtIndicators calculateSkimMatrices(SwissRailRaptorData raptorData, Map coordsPerZone, double minDepartureTime, double maxDepartureTime, - double stepSize_seconds, RaptorParameters parameters, int numberOfThreads, BiPredicate trainDetector) { + double stepSize_seconds, RaptorParameters parameters, int numberOfThreads, BiPredicate trainDetector, CoordAggregator coordAggregator) { // prepare calculation Set zoneIds = coordsPerZone.keySet(); PtIndicators pti = new PtIndicators<>(zoneIds); @@ -89,7 +85,7 @@ public static PTSkimMatrices.PtIndicators calculateSkimMatrices(SwissRail Thread[] threads = new Thread[numberOfThreads]; for (int i = 0; i < numberOfThreads; i++) { SwissRailRaptor raptor = new SwissRailRaptor.Builder(raptorData, config).build(); - RowWorker worker = new RowWorker<>(originZones, zoneIds, coordsPerZone, pti, raptor, parameters, minDepartureTime, maxDepartureTime, stepSize_seconds, counter, trainDetector); + RowWorker worker = new RowWorker<>(originZones, zoneIds, coordsPerZone, pti, raptor, parameters, minDepartureTime, maxDepartureTime, stepSize_seconds, counter, trainDetector, coordAggregator); threads[i] = new Thread(worker, "PT-FrequencyMatrix-" + Time.writeTime(minDepartureTime) + "-" + Time.writeTime(maxDepartureTime) + "-" + i); threads[i].start(); } @@ -148,9 +144,10 @@ static class RowWorker implements Runnable { private final double stepSize; private final Counter counter; private final BiPredicate trainDetector; + private final CoordAggregator coordAggregator; - RowWorker(ConcurrentLinkedQueue originZones, Set destinationZones, Map coordsPerZone, PtIndicators pti, SwissRailRaptor raptor, RaptorParameters parameters, - double minDepartureTime, double maxDepartureTime, double stepSize, Counter counter, BiPredicate trainDetector) { + RowWorker(ConcurrentLinkedQueue originZones, Set destinationZones, Map coordsPerZone, PtIndicators pti, SwissRailRaptor raptor, RaptorParameters parameters, + double minDepartureTime, double maxDepartureTime, double stepSize, Counter counter, BiPredicate trainDetector, CoordAggregator coordAggregator) { this.originZones = originZones; this.destinationZones = destinationZones; this.coordsPerZone = coordsPerZone; @@ -162,6 +159,7 @@ static class RowWorker implements Runnable { this.stepSize = stepSize; this.counter = counter; this.trainDetector = trainDetector; + this.coordAggregator = coordAggregator; } private static Collection findStopCandidates(Coord coord, SwissRailRaptor raptor, RaptorParameters parameters) { @@ -185,14 +183,15 @@ public void run() { this.counter.incCounter(); Coord[] fromCoords = this.coordsPerZone.get(fromZoneId); if (fromCoords != null) { - for (Coord fromCoord : fromCoords) { - calcForRow(fromZoneId, fromCoord); + var weightedRelevantFromCoords = coordAggregator.aggregateCoords(fromCoords); + for (var fromCoord : weightedRelevantFromCoords) { + calcForRow(fromZoneId, fromCoord.coord(),fromCoord.weight()); } } } } - private void calcForRow(T fromZoneId, Coord fromCoord) { + private void calcForRow(T fromZoneId, Coord fromCoord, double fromCoordWeight) { double walkSpeed = this.parameters.getBeelineWalkSpeed(); Collection fromStops = findStopCandidates(fromCoord, this.raptor, this.parameters); @@ -216,13 +215,13 @@ private void calcForRow(T fromZoneId, Coord fromCoord) { Coord[] toCoords = this.coordsPerZone.get(toZoneId); if (toCoords != null) { for (Coord toCoord : toCoords) { - calcForOD(fromZoneId, toZoneId, toCoord, accessTimes, trees); + calcForOD(fromZoneId, toZoneId, toCoord, accessTimes, trees, (float) fromCoordWeight); } } } } - private void calcForOD(T fromZoneId, T toZoneId, Coord toCoord, Map, Double> accessTimes, List, TravelInfo>> trees) { + private void calcForOD(T fromZoneId, T toZoneId, Coord toCoord, Map, Double> accessTimes, List, TravelInfo>> trees, float fromCoordWeight) { double walkSpeed = this.parameters.getBeelineWalkSpeed(); Collection toStops = findStopCandidates(toCoord, this.raptor, this.parameters); @@ -297,15 +296,15 @@ private void calcForOD(T fromZoneId, T toZoneId, Coord toCoord, Map buildODConnections(List, TravelInfo>> trees, Map, Double> accessTimes, @@ -359,4 +358,10 @@ public static class PtIndicators { } } + public interface CoordAggregator{ + default List aggregateCoords(Coord[] coords){ + return Arrays.stream(coords).map(coord -> new CalculateSkimMatrices.WeightedCoord(coord,1.0)).collect(Collectors.toList()); + } + } + } diff --git a/contribs/taxi/test/input/org/matsim/contrib/etaxi/run/RunETaxiScenarioIT/testAssignment/output_events.xml.gz b/contribs/taxi/test/input/org/matsim/contrib/etaxi/run/RunETaxiScenarioIT/testAssignment/output_events.xml.gz index 88cd4466237..be4e7c20597 100644 Binary files a/contribs/taxi/test/input/org/matsim/contrib/etaxi/run/RunETaxiScenarioIT/testAssignment/output_events.xml.gz and b/contribs/taxi/test/input/org/matsim/contrib/etaxi/run/RunETaxiScenarioIT/testAssignment/output_events.xml.gz differ diff --git a/contribs/taxi/test/input/org/matsim/contrib/etaxi/run/RunETaxiScenarioIT/testOneTaxi/output_events.xml.gz b/contribs/taxi/test/input/org/matsim/contrib/etaxi/run/RunETaxiScenarioIT/testOneTaxi/output_events.xml.gz index 16c754539b8..41fd49194bf 100644 Binary files a/contribs/taxi/test/input/org/matsim/contrib/etaxi/run/RunETaxiScenarioIT/testOneTaxi/output_events.xml.gz and b/contribs/taxi/test/input/org/matsim/contrib/etaxi/run/RunETaxiScenarioIT/testOneTaxi/output_events.xml.gz differ diff --git a/contribs/taxi/test/input/org/matsim/contrib/etaxi/run/RunETaxiScenarioIT/testRuleBased/output_events.xml.gz b/contribs/taxi/test/input/org/matsim/contrib/etaxi/run/RunETaxiScenarioIT/testRuleBased/output_events.xml.gz index 88cd4466237..be4e7c20597 100644 Binary files a/contribs/taxi/test/input/org/matsim/contrib/etaxi/run/RunETaxiScenarioIT/testRuleBased/output_events.xml.gz and b/contribs/taxi/test/input/org/matsim/contrib/etaxi/run/RunETaxiScenarioIT/testRuleBased/output_events.xml.gz differ diff --git a/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/RunFreightAnalysisEventBased.java b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/RunFreightAnalysisEventBased.java index 1a60ed8b6a3..86249801bd0 100644 --- a/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/RunFreightAnalysisEventBased.java +++ b/contribs/vsp/src/main/java/org/matsim/freight/carriers/analysis/RunFreightAnalysisEventBased.java @@ -81,7 +81,7 @@ public void runAnalysis() throws IOException { //freight settings FreightCarriersConfigGroup freightCarriersConfigGroup = ConfigUtils.addOrGetModule( config, FreightCarriersConfigGroup.class ) ; freightCarriersConfigGroup.setCarriersFile( SIM_OUTPUT_PATH + "output_carriers.xml.gz"); - freightCarriersConfigGroup.setCarriersVehicleTypesFile(SIM_OUTPUT_PATH + "output_allVehicles.xml.gz"); + freightCarriersConfigGroup.setCarriersVehicleTypesFile(SIM_OUTPUT_PATH + "output_carriersVehicleTypes.xml.gz"); //Were to store the analysis output? String analysisOutputDirectory = ANALYSIS_OUTPUT_PATH; diff --git a/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/output_carriersVehicleTypes.xml.gz b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/output_carriersVehicleTypes.xml.gz new file mode 100644 index 00000000000..d584a182d65 Binary files /dev/null and b/contribs/vsp/test/input/org/matsim/freight/carriers/analysis/FreightAnalysisEventBasedTest/output_carriersVehicleTypes.xml.gz differ diff --git a/contribs/vsp/test/input/playground/vsp/ev/UrbanEVIT/run/output_events.xml.gz b/contribs/vsp/test/input/playground/vsp/ev/UrbanEVIT/run/output_events.xml.gz index e4bd42f3c0f..7c2e5641672 100644 Binary files a/contribs/vsp/test/input/playground/vsp/ev/UrbanEVIT/run/output_events.xml.gz and b/contribs/vsp/test/input/playground/vsp/ev/UrbanEVIT/run/output_events.xml.gz differ diff --git a/examples/scenarios/mielec/evehicles-multiModeEdrt.xml b/examples/scenarios/mielec/evehicles-multiModeEdrt.xml new file mode 100644 index 00000000000..cac643a64f7 --- /dev/null +++ b/examples/scenarios/mielec/evehicles-multiModeEdrt.xml @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + electricity + ["default"] + 20.0 + + + + + + + + + + + + + 0.8 + + + + + 0.7 + + + + + 0.775 + + + + + 0.675 + + + + + 0.75 + + + + + 0.65 + + + + + 0.725 + + + + + 0.625 + + + + + 0.7 + + + + + 0.6 + + + + + 0.8 + + + + + 0.7 + + + + + 0.775 + + + + + 0.675 + + + + + 0.75 + + + + + 0.65 + + + + + 0.725 + + + + + 0.625 + + + + + 0.7 + + + + + 0.6 + + + + + diff --git a/examples/scenarios/mielec/mielec_multiModeEdrt_config.xml b/examples/scenarios/mielec/mielec_multiModeEdrt_config.xml new file mode 100644 index 00000000000..aa5d99b31a2 --- /dev/null +++ b/examples/scenarios/mielec/mielec_multiModeEdrt_config.xml @@ -0,0 +1,115 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/scenarios/mielec/plans_only_multiModeEdrt.xml.gz b/examples/scenarios/mielec/plans_only_multiModeEdrt.xml.gz new file mode 100644 index 00000000000..ff94443fce7 Binary files /dev/null and b/examples/scenarios/mielec/plans_only_multiModeEdrt.xml.gz differ diff --git a/examples/scenarios/mielec/vehicles-10-cap-4_drt2.xml b/examples/scenarios/mielec/vehicles-10-cap-4_drt2.xml new file mode 100644 index 00000000000..ae24f59256b --- /dev/null +++ b/examples/scenarios/mielec/vehicles-10-cap-4_drt2.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/matsim/pom.xml b/matsim/pom.xml index 5ca0233cc32..dd83fd128b5 100644 --- a/matsim/pom.xml +++ b/matsim/pom.xml @@ -91,6 +91,7 @@ attach-sources + test-jar jar @@ -117,7 +118,7 @@ org.apache.maven.plugins maven-surefire-report-plugin - 3.2.3 + 3.2.5 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 2473517c9d1..3c8040a92fb 100644 --- a/matsim/src/main/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroup.java +++ b/matsim/src/main/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroup.java @@ -40,7 +40,6 @@ */ public class SwissRailRaptorConfigGroup extends ReflectiveConfigGroup { - private static final Logger log = LogManager.getLogger(SwissRailRaptorConfigGroup.class); public static final String GROUP = "swissRailRaptor"; private static final String PARAM_USE_RANGE_QUERY = "useRangeQuery"; @@ -81,6 +80,7 @@ public class SwissRailRaptorConfigGroup extends ReflectiveConfigGroup { private final Map rangeQuerySettingsPerSubpop = new HashMap<>(); private final Map routeSelectorPerSubpop = new HashMap<>(); private final List intermodalAccessEgressSettings = new ArrayList<>(); + private final List modeToModeTransferPenaltyParameterSets = new ArrayList<>(); private final Map modeMappingForPassengersByRouteMode = new HashMap<>(); @@ -243,19 +243,19 @@ public void setTransferPenaltyCostPerTravelTimeHour(double hourlyCost) { this.transferPenaltyHourlyCost = hourlyCost; } - @Override + + @Override public ConfigGroup createParameterSet(String type) { - if (RangeQuerySettingsParameterSet.TYPE.equals(type)) { - return new RangeQuerySettingsParameterSet(); - } else if (RouteSelectorParameterSet.TYPE.equals(type)) { - return new RouteSelectorParameterSet(); - } else if (IntermodalAccessEgressParameterSet.TYPE.equals(type)) { - return new IntermodalAccessEgressParameterSet(); - } else if (ModeMappingForPassengersParameterSet.TYPE.equals(type)) { - return new ModeMappingForPassengersParameterSet(); - } else { - throw new IllegalArgumentException("Unsupported parameterset-type: " + type); - } + return switch (type){ + case RangeQuerySettingsParameterSet.TYPE -> new RangeQuerySettingsParameterSet(); + case RouteSelectorParameterSet.TYPE -> new RouteSelectorParameterSet(); + case IntermodalAccessEgressParameterSet.TYPE -> new IntermodalAccessEgressParameterSet(); + case ModeMappingForPassengersParameterSet.TYPE -> new ModeMappingForPassengersParameterSet(); + case ModeToModeTransferPenalty.TYPE -> new ModeToModeTransferPenalty(); + default -> throw new IllegalArgumentException("Unsupported parameterset-type: " + type); + + }; + } @Override @@ -267,13 +267,25 @@ public void addParameterSet(ConfigGroup set) { } else if (set instanceof IntermodalAccessEgressParameterSet) { addIntermodalAccessEgress((IntermodalAccessEgressParameterSet) set); } else if (set instanceof ModeMappingForPassengersParameterSet) { - addModeMappingForPassengers((ModeMappingForPassengersParameterSet) set); + addModeMappingForPassengers((ModeMappingForPassengersParameterSet) set);} + else if (set instanceof ModeToModeTransferPenalty) { + addModeToModeTransferPenalty((ModeToModeTransferPenalty) set); } else { throw new IllegalArgumentException("Unsupported parameterset: " + set.getClass().getName()); } } - public void addRangeQuerySettings(RangeQuerySettingsParameterSet settings) { + public void addModeToModeTransferPenalty(ModeToModeTransferPenalty set) { + this.modeToModeTransferPenaltyParameterSets.add(set); + super.addParameterSet(set); + + } + + public List getModeToModeTransferPenaltyParameterSets() { + return modeToModeTransferPenaltyParameterSets; + } + + public void addRangeQuerySettings(RangeQuerySettingsParameterSet settings) { Set subpops = settings.getSubpopulations(); if (subpops.isEmpty()) { this.rangeQuerySettingsPerSubpop.put(null, settings); @@ -662,12 +674,39 @@ public void setPassengerMode(String passengerMode) { } } - @Override + public static class ModeToModeTransferPenalty extends ReflectiveConfigGroup{ + private static final String TYPE = "modeToModeTransferPenalty"; + @Parameter + @Comment("from Transfer PT Sub-Mode") + public String fromMode; + @Parameter + @Comment("to Transfer PT Sub-Mode") + public String toMode; + @Parameter + @Comment("Transfer Penalty per Transfer between modes") + public double transferPenalty = 0.0; + + public ModeToModeTransferPenalty() { + super(TYPE); + } + + public ModeToModeTransferPenalty(String fromMode, String toMode, double transferPenalty) { + super(TYPE); + this.fromMode = fromMode; + this.toMode = toMode; + this.transferPenalty = transferPenalty; + } + } + + + + @Override public Map getComments() { Map comments = super.getComments(); comments.put(PARAM_INTERMODAL_ACCESS_EGRESS_MODE_SELECTION, PARAM_INTERMODAL_ACCESS_EGRESS_MODE_SELECTION_DESC); comments.put(PARAM_USE_CAPACITY_CONSTRAINTS, PARAM_USE_CAPACITY_CONSTRAINTS_DESC); comments.put(PARAM_TRANSFER_WALK_MARGIN, PARAM_TRANSFER_WALK_MARGIN_DESC); + comments.put(PARAM_INTERMODAL_ACCESS_EGRESS_MODE_SELECTION,PARAM_INTERMODAL_ACCESS_EGRESS_MODE_SELECTION_DESC); return comments; } @@ -679,7 +718,7 @@ protected void checkConsistency(Config config) { Verify.verify(config.plans().getHandlingOfPlansWithoutRoutingMode().equals(HandlingOfPlansWithoutRoutingMode.reject), "Using intermodal access and egress in " + "combination with plans without a routing mode is not supported."); - Verify.verify(intermodalAccessEgressSettings.size() >= 1, "Using intermodal routing, but there are no access/egress " + Verify.verify(!intermodalAccessEgressSettings.isEmpty(), "Using intermodal routing, but there are no access/egress " + "modes defined. Add at least one parameterset with an access/egress mode and ensure " + "SwissRailRaptorConfigGroup is loaded correctly."); diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorTransferCostCalculator.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorTransferCostCalculator.java index 5522400f8cb..67216d31d3f 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorTransferCostCalculator.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/DefaultRaptorTransferCostCalculator.java @@ -26,13 +26,14 @@ */ public class DefaultRaptorTransferCostCalculator implements RaptorTransferCostCalculator { @Override - public double calcTransferCost(Supplier transfer, RaptorParameters raptorParams, int totalTravelTime, int transferCount, double existingTransferCosts, double currentTime) { + public double calcTransferCost(SwissRailRaptorCore.PathElement currentPE, Supplier transfer, RaptorStaticConfig staticConfig, RaptorParameters raptorParams, int totalTravelTime, int transferCount, double existingTransferCosts, double currentTime) { double transferCostBase = raptorParams.getTransferPenaltyFixCostPerTransfer(); + double transferCostModeToMode = staticConfig.isUseModeToModeTransferPenalty()?staticConfig.getModeToModeTransferPenalty(transfer.get().getFromTransitRoute().getTransportMode(),transfer.get().getToTransitRoute().getTransportMode()):0.0; double transferCostPerHour = raptorParams.getTransferPenaltyPerTravelTimeHour(); double transferCostMin = raptorParams.getTransferPenaltyMinimum(); double transferCostMax = raptorParams.getTransferPenaltyMaximum(); - return (calcSingleTransferCost(transferCostBase, transferCostPerHour, transferCostMin, transferCostMax, totalTravelTime) * transferCount) - existingTransferCosts; + return (calcSingleTransferCost(transferCostBase+transferCostModeToMode, transferCostPerHour, transferCostMin, transferCostMax, totalTravelTime) * transferCount) - existingTransferCosts; } private double calcSingleTransferCost(double costBase, double costPerHour, double costMin, double costMax, double travelTime) { 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 e80561feea5..20b94216349 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 @@ -20,6 +20,10 @@ package ch.sbb.matsim.routing.pt.raptor; import ch.sbb.matsim.config.SwissRailRaptorConfigGroup; +import org.matsim.api.core.v01.population.Person; +import org.matsim.facilities.Facility; +import org.matsim.pt.transitSchedule.api.TransitStopFacility; +import org.matsim.utils.objectattributes.attributable.Attributes; import java.util.HashMap; import java.util.Map; @@ -34,15 +38,17 @@ */ public class RaptorStaticConfig { - public enum RaptorOptimization { + + + public enum RaptorOptimization { /** * Use this option if you plan to calculate simple from-to routes - * (see {@link SwissRailRaptor#calcRoute(org.matsim.facilities.Facility, org.matsim.facilities.Facility, double, org.matsim.api.core.v01.population.Person)}). + * (see {@link SwissRailRaptor#calcRoute(Facility, Facility, double, double, double, Person, Attributes, RaptorRouteSelector)} */ OneToOneRouting, /** * Use this option if you plan to calculate one-to-all least-cost-path-trees - * (see {@link SwissRailRaptor#calcTree(org.matsim.pt.transitSchedule.api.TransitStopFacility, double, RaptorParameters)}). + * (see {@link SwissRailRaptor#calcTree(TransitStopFacility, double, RaptorParameters, Person)} ). */ OneToAllRouting } @@ -60,6 +66,7 @@ public enum RaptorOptimization { private boolean useModeMappingForPassengers = false; private final Map passengerModeMappings = new HashMap<>(); + private final Map> modeToModeTransferPenalties = new HashMap<>(); private boolean useCapacityConstraints = false; @@ -114,6 +121,20 @@ public boolean isUseModeMappingForPassengers() { public void setUseModeMappingForPassengers(boolean useModeMappingForPassengers) { this.useModeMappingForPassengers = useModeMappingForPassengers; } + public void addModeToModeTransferPenalty(String fromMode, String toMode, double transferPenalty) { + this.modeToModeTransferPenalties.computeIfAbsent(fromMode,s->new HashMap<>()).put(toMode,transferPenalty); + } + public double getModeToModeTransferPenalty(String fromMode, String toMode){ + var fromModeSet = this.modeToModeTransferPenalties.get(fromMode); + if (fromModeSet!=null){ + return fromModeSet.getOrDefault(toMode,0.0); + } + else return 0.0; + } + + public boolean isUseModeToModeTransferPenalty(){ + return !this.modeToModeTransferPenalties.isEmpty(); + } public boolean isUseCapacityConstraints() { return this.useCapacityConstraints; diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorTransferCostCalculator.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorTransferCostCalculator.java index 1a114db0a61..0f1b09148d1 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorTransferCostCalculator.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorTransferCostCalculator.java @@ -19,6 +19,7 @@ * *********************************************************************** */ package ch.sbb.matsim.routing.pt.raptor; + import java.util.function.Supplier; /** @@ -26,6 +27,6 @@ */ public interface RaptorTransferCostCalculator { - double calcTransferCost(Supplier transfer, RaptorParameters raptorParams, int totalTravelTime, int totalTransferCount, double existingTransferCosts, double currentTime); + double calcTransferCost(SwissRailRaptorCore.PathElement currentPE, Supplier transfer, RaptorStaticConfig staticConfig, RaptorParameters raptorParams, int totalTravelTime, int totalTransferCount, double existingTransferCosts, double currentTime); } diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorUtils.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorUtils.java index 2fae233bf34..f289b04e486 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorUtils.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/RaptorUtils.java @@ -70,6 +70,10 @@ public static RaptorStaticConfig createStaticConfig(Config config) { staticConfig.addModeMappingForPassengers(mapping.getRouteMode(), mapping.getPassengerMode()); } } + + for (SwissRailRaptorConfigGroup.ModeToModeTransferPenalty penalty : srrConfig.getModeToModeTransferPenaltyParameterSets()){ + staticConfig.addModeToModeTransferPenalty(penalty.fromMode,penalty.toMode,penalty.transferPenalty); + } staticConfig.setUseCapacityConstraints(srrConfig.isUseCapacityConstraints()); return staticConfig; 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 c0cfeb893bc..09cef257e09 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 @@ -637,7 +637,7 @@ private void exploreRoutes(RaptorParameters parameters, Person person) { int inVehicleTime = arrivalTime - currentAgentBoardingTime; double inVehicleCost = this.inVehicleCostCalculator.getInVehicleCost(inVehicleTime, marginalUtilityOfTravelTime_utl_s, person, currentVehicle, parameters, routeSegmentIterator); double arrivalTravelCost = currentTravelCostWhenBoarding + inVehicleCost; - double arrivalTransferCost = (boardingPE.firstDepartureTime != TIME_UNDEFINED) ? (currentTransferCostWhenBoarding + this.transferCostCalculator.calcTransferCost(transferProvider, parameters, arrivalTime - firstDepartureTime, boardingPE.transferCount, boardingPE.arrivalTransferCost, boardingPE.arrivalTime)) : 0; + double arrivalTransferCost = (boardingPE.firstDepartureTime != TIME_UNDEFINED) ? (currentTransferCostWhenBoarding + this.transferCostCalculator.calcTransferCost(boardingPE,transferProvider, data.config, parameters, arrivalTime - firstDepartureTime, boardingPE.transferCount, boardingPE.arrivalTransferCost, boardingPE.arrivalTime)) : 0; double previousArrivalCost = this.leastArrivalCostAtRouteStop[toRouteStopIndex]; double totalArrivalCost = arrivalTravelCost + arrivalTransferCost; if (totalArrivalCost <= previousArrivalCost) { @@ -758,7 +758,7 @@ private void handleTransfers(boolean strict, RaptorParameters raptorParams) { transferProvider.reset(transfer); int newArrivalTime = arrivalTime + transfer.transferTime; double newArrivalTravelCost = arrivalTravelCost - transfer.transferTime * margUtilityTransitWalk; - double newArrivalTransferCost = (fromPE.firstDepartureTime != TIME_UNDEFINED) ? (arrivalTransferCost + this.transferCostCalculator.calcTransferCost(transferProvider, raptorParams, newArrivalTime - fromPE.firstDepartureTime, fromPE.transferCount + 1, arrivalTransferCost, arrivalTime)) : 0; + double newArrivalTransferCost = (fromPE.firstDepartureTime != TIME_UNDEFINED) ? (arrivalTransferCost + this.transferCostCalculator.calcTransferCost(fromPE, transferProvider, data.config, raptorParams, newArrivalTime - fromPE.firstDepartureTime, fromPE.transferCount + 1, arrivalTransferCost, arrivalTime)) : 0; double newTotalArrivalCost = newArrivalTravelCost + newArrivalTransferCost; double prevLeastArrivalCost = this.leastArrivalCostAtRouteStop[toRouteStopIndex]; if (newTotalArrivalCost < prevLeastArrivalCost || (!strict && newTotalArrivalCost <= prevLeastArrivalCost)) { @@ -882,7 +882,7 @@ private static boolean isIntermodal(InitialStop initialStop) { return initialStop != null && initialStop.planElements != null; } - private static class PathElement { + static class PathElement { final PathElement comingFrom; final RRouteStop toRouteStop; final int firstDepartureTime; // the departure time at the start stop diff --git a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorRoutingModule.java b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorRoutingModule.java index 94c346b120b..3ebfeead059 100644 --- a/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorRoutingModule.java +++ b/matsim/src/main/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorRoutingModule.java @@ -29,13 +29,10 @@ import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Leg; -import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.PlanElement; import org.matsim.core.population.PopulationUtils; -import org.matsim.core.router.DefaultRoutingRequest; import org.matsim.core.router.RoutingModule; import org.matsim.core.router.RoutingRequest; -import org.matsim.facilities.Facility; import org.matsim.pt.routes.TransitPassengerRoute; import org.matsim.pt.transitSchedule.api.TransitSchedule; import org.matsim.pt.transitSchedule.api.TransitStopFacility; diff --git a/matsim/src/main/java/org/matsim/analysis/CalcLinkStats.java b/matsim/src/main/java/org/matsim/analysis/CalcLinkStats.java index f29a7203255..a317c02857c 100644 --- a/matsim/src/main/java/org/matsim/analysis/CalcLinkStats.java +++ b/matsim/src/main/java/org/matsim/analysis/CalcLinkStats.java @@ -160,9 +160,7 @@ public void reset() { } public void writeFile(final String filename) { - BufferedWriter out = null; - try { - out = IOUtils.getBufferedWriter(filename); + try (BufferedWriter out = IOUtils.getBufferedWriter(filename)) { // write header out.write("LINK\tORIG_ID\tFROM\tTO\tLENGTH\tFREESPEED\tCAPACITY"); @@ -238,16 +236,7 @@ public void writeFile(final String filename) { } } catch (IOException e) { - e.printStackTrace(); - } - finally { - if (out != null) { - try { - out.close(); - } catch (IOException e) { - log.warn("Could not close output-stream.", e); - } - } + log.error("could not write linkstats", e); } } @@ -255,9 +244,7 @@ public void readFile(final String filename) { // start with a clean, empty data structure reset(); - BufferedReader reader = null; - try { - reader = IOUtils.getBufferedReader(filename); + try (BufferedReader reader = IOUtils.getBufferedReader(filename)) { // read header String header = reader.readLine(); @@ -342,14 +329,7 @@ else if (parts.length == 153) { } } catch (IOException e) { - e.printStackTrace(); - } finally { - if (reader != null) { - try { reader.close(); } - catch (IOException e) { - log.warn("Could not close input-stream.", e); - } - } + log.error("could not read linkstats.", e); } } diff --git a/matsim/src/main/java/org/matsim/analysis/IterationTravelStatsControlerListener.java b/matsim/src/main/java/org/matsim/analysis/IterationTravelStatsControlerListener.java index 8055a2c04db..483f282480c 100644 --- a/matsim/src/main/java/org/matsim/analysis/IterationTravelStatsControlerListener.java +++ b/matsim/src/main/java/org/matsim/analysis/IterationTravelStatsControlerListener.java @@ -21,7 +21,6 @@ package org.matsim.analysis; -import org.matsim.api.core.v01.Scenario; import org.matsim.core.config.Config; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; diff --git a/matsim/src/main/java/org/matsim/analysis/LinkStatsModule.java b/matsim/src/main/java/org/matsim/analysis/LinkStatsModule.java index 8a87a1ad59b..dae75581cf2 100644 --- a/matsim/src/main/java/org/matsim/analysis/LinkStatsModule.java +++ b/matsim/src/main/java/org/matsim/analysis/LinkStatsModule.java @@ -22,14 +22,8 @@ package org.matsim.analysis; -import com.google.inject.Singleton; -import org.matsim.api.core.v01.Scenario; -import org.matsim.core.config.Config; import org.matsim.core.controler.AbstractModule; -import jakarta.inject.Inject; -import jakarta.inject.Provider; - public final class LinkStatsModule extends AbstractModule { @Override diff --git a/matsim/src/main/java/org/matsim/analysis/ModeStatsControlerListener.java b/matsim/src/main/java/org/matsim/analysis/ModeStatsControlerListener.java index dc351742a11..e2bad0763f6 100644 --- a/matsim/src/main/java/org/matsim/analysis/ModeStatsControlerListener.java +++ b/matsim/src/main/java/org/matsim/analysis/ModeStatsControlerListener.java @@ -20,9 +20,7 @@ package org.matsim.analysis; -import java.awt.*; import java.io.BufferedWriter; -import java.io.FileOutputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.util.*; @@ -33,10 +31,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.jfree.chart.ChartUtils; -import org.jfree.chart.JFreeChart; -import org.jfree.chart.plot.XYPlot; -import org.jfree.data.xy.XYDataset; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; diff --git a/matsim/src/main/java/org/matsim/analysis/PHbyModeCalculator.java b/matsim/src/main/java/org/matsim/analysis/PHbyModeCalculator.java index e572fbcc8a8..1a73c6d9a57 100644 --- a/matsim/src/main/java/org/matsim/analysis/PHbyModeCalculator.java +++ b/matsim/src/main/java/org/matsim/analysis/PHbyModeCalculator.java @@ -36,7 +36,6 @@ import org.jfree.chart.axis.CategoryLabelPositions; import org.matsim.api.core.v01.IdMap; import org.matsim.api.core.v01.population.*; -import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.config.groups.GlobalConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.router.StageActivityTypeIdentifier; diff --git a/matsim/src/main/java/org/matsim/analysis/PKMbyModeCalculator.java b/matsim/src/main/java/org/matsim/analysis/PKMbyModeCalculator.java index c9979b9ae4f..4745f6ba641 100644 --- a/matsim/src/main/java/org/matsim/analysis/PKMbyModeCalculator.java +++ b/matsim/src/main/java/org/matsim/analysis/PKMbyModeCalculator.java @@ -38,7 +38,6 @@ import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; -import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.config.groups.GlobalConfigGroup; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.utils.charts.StackedBarChart; diff --git a/matsim/src/main/java/org/matsim/analysis/ScoreStatsControlerListener.java b/matsim/src/main/java/org/matsim/analysis/ScoreStatsControlerListener.java index 8e82756527c..8ddacb1c45b 100644 --- a/matsim/src/main/java/org/matsim/analysis/ScoreStatsControlerListener.java +++ b/matsim/src/main/java/org/matsim/analysis/ScoreStatsControlerListener.java @@ -62,7 +62,7 @@ */ public class ScoreStatsControlerListener implements StartupListener, IterationEndsListener, ShutdownListener, ScoreStats { - public enum ScoreItem { worst, best, average, executed }; + public enum ScoreItem { worst, best, average, executed } private final Population population; private final OutputDirectoryHierarchy controllerIO; diff --git a/matsim/src/main/java/org/matsim/analysis/linkpaxvolumes/LinkPaxVolumesAnalysis.java b/matsim/src/main/java/org/matsim/analysis/linkpaxvolumes/LinkPaxVolumesAnalysis.java index acac9cf3ee9..fe0a1eb22c1 100644 --- a/matsim/src/main/java/org/matsim/analysis/linkpaxvolumes/LinkPaxVolumesAnalysis.java +++ b/matsim/src/main/java/org/matsim/analysis/linkpaxvolumes/LinkPaxVolumesAnalysis.java @@ -63,7 +63,7 @@ public final class LinkPaxVolumesAnalysis implements LinkEnterEventHandler, Vehi private final Vehicles vehicles; private final Vehicles transitVehicles; private final Id nullVehicleType = Id.create("nullVehicleType", VehicleType.class); - + // for multi-modal / multi vehicle type support final boolean observeNetworkModes; final boolean observePassengerModes; @@ -100,7 +100,7 @@ public LinkPaxVolumesAnalysis(Vehicles vehicles, Vehicles transitVehicles /* TOD this.vehicleType2timeOnNetwork = new IdMap<>(VehicleType.class); this.vehicleType2numberSeen = new IdMap<>(VehicleType.class); this.vehicleIdsSeen = new IdSet<>(Vehicle.class); - + this.observeNetworkModes = observeNetworkModes; if (this.observeNetworkModes) { this.linkVehicleVolumesPerNetworkMode = new IdMap<>(Link.class); @@ -187,7 +187,7 @@ public void handleEvent(final LinkEnterEvent event) { this.linkPaxVolumes.put(event.getLinkId(), passengerVolumesAll); } passengerVolumesAll[timeslot] += currentPaxAllPassengerModes; - + if (this.observeNetworkModes) { String mode = vehicleData.networkMode; @@ -302,7 +302,7 @@ private int getTimeSlotIndex(final double time) { int[] getVehicleVolumesForLink(final Id linkId) { return this.linkVehicleVolumes.get(linkId); } - + /** * @param linkId * @param networkMode @@ -313,7 +313,7 @@ int[] getVehicleVolumesForLinkPerNetworkMode(final Id linkId, String netwo if (observeNetworkModes) { Map modeVolumes = this.linkVehicleVolumesPerNetworkMode.get(linkId); if (modeVolumes != null) return modeVolumes.get(networkMode); - } + } return null; } @@ -404,10 +404,10 @@ int[] getPaxVolumesForLinkPerVehicleType(final Id linkId, Id int getVolumesArraySize() { return this.maxSlotIndex + 1; } - + /* * This procedure is only working if (hour % timeBinSize == 0) - * + * * Example: 15 minutes bins * ___________________ * | 0 | 1 | 2 | 3 | @@ -417,11 +417,11 @@ int getVolumesArraySize() { * | hour 0 | * |___________________| * 0 3600 - * + * * hour 0 = bins 0,1,2,3 * hour 1 = bins 4,5,6,7 * ... - * + * * getTimeSlotIndex = (int)time / this.timeBinSize => jumps at 3600.0! * Thus, starting time = (hour = 0) * 3600.0 */ @@ -457,17 +457,17 @@ Map, Integer> getVehicleType2numberSeen() { Map, Double> getVehicleType2timeOnNetwork() { return Collections.unmodifiableMap(vehicleType2timeOnNetwork); } - + /** * @return Set of Strings containing all modes for which counting-values are available. */ Set getNetworkModes() { Set modes = new TreeSet<>(); - + for (Map map : this.linkVehicleVolumesPerNetworkMode.values()) { modes.addAll(map.keySet()); } - + return modes; } @@ -496,7 +496,7 @@ IdSet getVehicleTypes() { return vehicleTypes; } - + /** * @return Set of Strings containing all link ids for which counting-values are available. */ @@ -515,7 +515,7 @@ public void reset(final int iteration) { this.person2passengerMode.clear(); this.vehiclesAboutToLeave.clear(); this.vehiclesData.clear(); - this.vehicleIdsSeen.clear();; + this.vehicleIdsSeen.clear(); this.vehicleType2numberSeen.clear(); this.vehicleType2timeOnNetwork.clear(); diff --git a/matsim/src/main/java/org/matsim/analysis/personMoney/PersonMoneyEventsAggregator.java b/matsim/src/main/java/org/matsim/analysis/personMoney/PersonMoneyEventsAggregator.java index 7b7d096e2b3..cdb0e41eab2 100644 --- a/matsim/src/main/java/org/matsim/analysis/personMoney/PersonMoneyEventsAggregator.java +++ b/matsim/src/main/java/org/matsim/analysis/personMoney/PersonMoneyEventsAggregator.java @@ -24,7 +24,6 @@ import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.events.PersonMoneyEvent; import org.matsim.api.core.v01.events.handler.PersonMoneyEventHandler; import org.matsim.core.config.groups.GlobalConfigGroup; diff --git a/matsim/src/main/java/org/matsim/analysis/personMoney/PersonMoneyEventsCollector.java b/matsim/src/main/java/org/matsim/analysis/personMoney/PersonMoneyEventsCollector.java index 5444e1ba783..4596c419c9a 100644 --- a/matsim/src/main/java/org/matsim/analysis/personMoney/PersonMoneyEventsCollector.java +++ b/matsim/src/main/java/org/matsim/analysis/personMoney/PersonMoneyEventsCollector.java @@ -24,7 +24,6 @@ import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.events.PersonMoneyEvent; import org.matsim.api.core.v01.events.handler.PersonMoneyEventHandler; import org.matsim.core.config.groups.GlobalConfigGroup; diff --git a/matsim/src/main/java/org/matsim/api/core/v01/TransportMode.java b/matsim/src/main/java/org/matsim/api/core/v01/TransportMode.java index aa0e7010eee..8b8c02b25d1 100644 --- a/matsim/src/main/java/org/matsim/api/core/v01/TransportMode.java +++ b/matsim/src/main/java/org/matsim/api/core/v01/TransportMode.java @@ -18,9 +18,6 @@ * * * *********************************************************************** */ -/** - * - */ package org.matsim.api.core.v01; /** diff --git a/matsim/src/main/java/org/matsim/api/core/v01/events/Event.java b/matsim/src/main/java/org/matsim/api/core/v01/events/Event.java index 6476397214c..09852740b7a 100644 --- a/matsim/src/main/java/org/matsim/api/core/v01/events/Event.java +++ b/matsim/src/main/java/org/matsim/api/core/v01/events/Event.java @@ -39,28 +39,28 @@ public Event(final double time) { } public Map getAttributes() { - Map attr = new LinkedHashMap(); + Map attr = new LinkedHashMap<>(); attr.put(ATTRIBUTE_TIME, Double.toString(this.time)); attr.put(ATTRIBUTE_TYPE, getEventType()); - if ( this instanceof HasPersonId && ((HasPersonId) this).getPersonId()!=null) { - attr.put( HasPersonId.ATTRIBUTE_PERSON, ((HasPersonId) this).getPersonId().toString() ) ; + if (this instanceof HasPersonId hasPersonId && hasPersonId.getPersonId() != null) { + attr.put(HasPersonId.ATTRIBUTE_PERSON, hasPersonId.getPersonId().toString()); // many derived types do this by themselves, for historical reasons. Since the information is put into a map, it still exists only once under that key. kai, // mar'19 } - if ( this instanceof HasFacilityId && ((HasFacilityId) this).getFacilityId()!=null ) { - attr.put( HasFacilityId.ATTRIBUTE_FACILITY, ((HasFacilityId) this).getFacilityId().toString() ); + if (this instanceof HasFacilityId hasFacilityId && hasFacilityId.getFacilityId() != null) { + attr.put(HasFacilityId.ATTRIBUTE_FACILITY, hasFacilityId.getFacilityId().toString()); } - if ( this instanceof HasLinkId && ((HasLinkId) this).getLinkId()!=null) { - attr.put( HasLinkId.ATTRIBUTE_LINK, ((HasLinkId) this).getLinkId().toString() ); + if (this instanceof HasLinkId hasLinkId && hasLinkId.getLinkId() != null) { + attr.put(HasLinkId.ATTRIBUTE_LINK, hasLinkId.getLinkId().toString()); } - if ( this instanceof BasicLocation && ((BasicLocation) this).getCoord()!=null ) { - if ( ((BasicLocation) this).getCoord()!=null ) { - attr.put( ATTRIBUTE_X, String.valueOf( ((BasicLocation) this).getCoord().getX() ) ) ; - attr.put( ATTRIBUTE_Y, String.valueOf( ((BasicLocation) this).getCoord().getY() ) ) ; + if (this instanceof BasicLocation basicLocation && basicLocation.getCoord() != null) { + if (((BasicLocation)this).getCoord() != null) { + attr.put(ATTRIBUTE_X, String.valueOf(basicLocation.getCoord().getX())); + attr.put(ATTRIBUTE_Y, String.valueOf(basicLocation.getCoord().getY())); } } - if ( this instanceof HasVehicleId && ((HasVehicleId) this).getVehicleId()!=null ) { - attr.put( HasVehicleId.ATTRIBUTE_VEHICLE, ((HasVehicleId) this).getVehicleId().toString() ); + if (this instanceof HasVehicleId hasVehicleId && hasVehicleId.getVehicleId() != null) { + attr.put(HasVehicleId.ATTRIBUTE_VEHICLE, hasVehicleId.getVehicleId().toString()); } return attr; } @@ -75,7 +75,7 @@ public final double getTime() { public void setTime(double time) { this.time = time; } - + public String toString() { Map attr = this.getAttributes() ; StringBuilder eventXML = new StringBuilder("\t vehicleId, final Id getDriverId() { throw new RuntimeException( LinkLeaveEvent.missingDriverIdMessage ) ; - } + } @Override public Id getLinkId() { return this.linkId; } - + public Id getVehicleId() { return vehicleId; } @Override public Map getAttributes() { - Map attr = super.getAttributes(); - attr.put(ATTRIBUTE_VEHICLE, this.vehicleId.toString()); - attr.put(ATTRIBUTE_LINK, this.linkId.toString()); - return attr; + Map atts = super.getAttributes(); + // linkId, vehicleId handled by superclass + return atts; } } diff --git a/matsim/src/main/java/org/matsim/api/core/v01/events/LinkLeaveEvent.java b/matsim/src/main/java/org/matsim/api/core/v01/events/LinkLeaveEvent.java index a2524206ece..06018363204 100644 --- a/matsim/src/main/java/org/matsim/api/core/v01/events/LinkLeaveEvent.java +++ b/matsim/src/main/java/org/matsim/api/core/v01/events/LinkLeaveEvent.java @@ -27,7 +27,7 @@ import java.util.Map; -public class LinkLeaveEvent extends Event implements HasLinkId, HasVehicleId{ +public class LinkLeaveEvent extends Event implements HasLinkId, HasVehicleId { public static final String EVENT_TYPE = "left link"; public static final String ATTRIBUTE_LINK = "link"; @@ -53,7 +53,7 @@ public String getEventType() { } /** - * Please use getVehicleId() instead. + * Please use getVehicleId() instead. * Vehicle-driver relations can be made by Wait2Link (now: VehicleEntersTraffic) and VehicleLeavesTraffic Events. */ @Deprecated @@ -69,12 +69,11 @@ public Id getLinkId() { public Id getVehicleId() { return vehicleId; } - + @Override public Map getAttributes() { - Map attr = super.getAttributes(); - attr.put(ATTRIBUTE_VEHICLE, this.vehicleId.toString()); - attr.put(ATTRIBUTE_LINK, this.linkId.toString()); - return attr; + Map atts = super.getAttributes(); + // linkId, vehicleId handled by superclass + return atts; } } diff --git a/matsim/src/main/java/org/matsim/api/core/v01/events/PersonArrivalEvent.java b/matsim/src/main/java/org/matsim/api/core/v01/events/PersonArrivalEvent.java index a6c49d62198..6e947aaff11 100644 --- a/matsim/src/main/java/org/matsim/api/core/v01/events/PersonArrivalEvent.java +++ b/matsim/src/main/java/org/matsim/api/core/v01/events/PersonArrivalEvent.java @@ -26,10 +26,10 @@ import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Person; -public class PersonArrivalEvent extends Event implements HasPersonId { +public class PersonArrivalEvent extends Event implements HasPersonId, HasLinkId { public static final String EVENT_TYPE = "arrival"; - + public static final String ATTRIBUTE_PERSON = "person"; public static final String ATTRIBUTE_LINK = "link"; public static final String ATTRIBUTE_LEGMODE = "legMode"; @@ -45,7 +45,7 @@ public PersonArrivalEvent(final double time, final Id agentId, final Id< this.legMode = legMode; this.personId = agentId; } - + public Id getPersonId() { return this.personId; } @@ -53,20 +53,19 @@ public Id getPersonId() { public Id getLinkId() { return this.linkId; } - + public String getLegMode() { return this.legMode; } - + public String getEventType() { return EVENT_TYPE; } - + @Override public Map getAttributes() { Map attr = super.getAttributes(); - attr.put(ATTRIBUTE_PERSON, this.personId.toString()); - attr.put(ATTRIBUTE_LINK, (this.linkId == null ? null : this.linkId.toString())); + // linkId, personId handled by superclass if (this.legMode != null) { attr.put(ATTRIBUTE_LEGMODE, this.legMode); } diff --git a/matsim/src/main/java/org/matsim/api/core/v01/events/PersonDepartureEvent.java b/matsim/src/main/java/org/matsim/api/core/v01/events/PersonDepartureEvent.java index 0dc5555778f..425d8ad4e78 100644 --- a/matsim/src/main/java/org/matsim/api/core/v01/events/PersonDepartureEvent.java +++ b/matsim/src/main/java/org/matsim/api/core/v01/events/PersonDepartureEvent.java @@ -26,7 +26,7 @@ import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Person; -public class PersonDepartureEvent extends Event implements HasPersonId { +public class PersonDepartureEvent extends Event implements HasPersonId, HasLinkId { public static final String EVENT_TYPE = "departure"; @@ -47,24 +47,24 @@ public PersonDepartureEvent(final double time, final Id agentId, final I this.personId = agentId; this.routingMode = routingMode; } - + @Override public Id getPersonId() { return this.personId; } - + public Id getLinkId() { return this.linkId; } - + public String getLegMode() { return this.legMode; } - + public String getRoutingMode() { return routingMode; } - + @Override public String getEventType() { return EVENT_TYPE; @@ -73,8 +73,7 @@ public String getEventType() { @Override public Map getAttributes() { Map attr = super.getAttributes(); - attr.put(ATTRIBUTE_PERSON, this.personId.toString()); - attr.put(ATTRIBUTE_LINK, (this.linkId == null ? null : this.linkId.toString())); + // linkId, personId handled by superclass if (this.legMode != null) { attr.put(ATTRIBUTE_LEGMODE, this.legMode); } diff --git a/matsim/src/main/java/org/matsim/api/core/v01/events/PersonEntersVehicleEvent.java b/matsim/src/main/java/org/matsim/api/core/v01/events/PersonEntersVehicleEvent.java index e862e1c8095..a3e051f44c4 100644 --- a/matsim/src/main/java/org/matsim/api/core/v01/events/PersonEntersVehicleEvent.java +++ b/matsim/src/main/java/org/matsim/api/core/v01/events/PersonEntersVehicleEvent.java @@ -29,7 +29,7 @@ /** * @author mrieser */ -public class PersonEntersVehicleEvent extends Event implements HasPersonId { +public class PersonEntersVehicleEvent extends Event implements HasPersonId, HasVehicleId { public static final String EVENT_TYPE = "PersonEntersVehicle"; public static final String ATTRIBUTE_PERSON = "person"; @@ -43,7 +43,7 @@ public PersonEntersVehicleEvent(final double time, final Id personId, fi this.personId = personId; this.vehicleId = vehicleId; } - + public Id getVehicleId() { return this.vehicleId; } @@ -55,8 +55,8 @@ public void setVehicleId(Id vehicleId) { @Override public Id getPersonId() { return this.personId; - } - + } + @Override public String getEventType() { return EVENT_TYPE; @@ -64,9 +64,8 @@ public String getEventType() { @Override public Map getAttributes() { - Map attrs = super.getAttributes(); - attrs.put(ATTRIBUTE_PERSON, this.personId.toString()); - attrs.put(ATTRIBUTE_VEHICLE, this.vehicleId.toString()); - return attrs; + Map atts = super.getAttributes(); + // personId, vehicleId handled by superclass + return atts; } } diff --git a/matsim/src/main/java/org/matsim/api/core/v01/events/PersonLeavesVehicleEvent.java b/matsim/src/main/java/org/matsim/api/core/v01/events/PersonLeavesVehicleEvent.java index c241f9753e3..27a3b5b2bdd 100644 --- a/matsim/src/main/java/org/matsim/api/core/v01/events/PersonLeavesVehicleEvent.java +++ b/matsim/src/main/java/org/matsim/api/core/v01/events/PersonLeavesVehicleEvent.java @@ -30,12 +30,12 @@ * * @author mrieser */ -public class PersonLeavesVehicleEvent extends Event implements HasPersonId { +public class PersonLeavesVehicleEvent extends Event implements HasPersonId, HasVehicleId { public static final String EVENT_TYPE = "PersonLeavesVehicle"; public static final String ATTRIBUTE_PERSON = "person"; public static final String ATTRIBUTE_VEHICLE = "vehicle"; - + private final Id personId; private Id vehicleId; @@ -44,12 +44,12 @@ public class PersonLeavesVehicleEvent extends Event implements HasPersonId { this.personId = personId; this.vehicleId = vehicleId; } - + @Override public Id getPersonId() { return this.personId; } - + public Id getVehicleId() { return this.vehicleId; } @@ -62,12 +62,11 @@ public void setVehicleId(Id vehicleId) { public String getEventType() { return EVENT_TYPE; } - + @Override public Map getAttributes() { Map attrs = super.getAttributes(); - attrs.put(ATTRIBUTE_PERSON, this.personId.toString()); - attrs.put(ATTRIBUTE_VEHICLE, this.vehicleId.toString()); + // personId, vehicleId handled by superclass return attrs; } } diff --git a/matsim/src/main/java/org/matsim/api/core/v01/events/PersonStuckEvent.java b/matsim/src/main/java/org/matsim/api/core/v01/events/PersonStuckEvent.java index 150495b08e9..b2439dd8b96 100644 --- a/matsim/src/main/java/org/matsim/api/core/v01/events/PersonStuckEvent.java +++ b/matsim/src/main/java/org/matsim/api/core/v01/events/PersonStuckEvent.java @@ -26,10 +26,10 @@ import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Person; -public class PersonStuckEvent extends Event implements HasPersonId { +public class PersonStuckEvent extends Event implements HasPersonId, HasLinkId { public static final String EVENT_TYPE = "stuckAndAbort"; - + public static final String ATTRIBUTE_LINK = "link"; public static final String ATTRIBUTE_LEGMODE = "legMode"; public static final String ATTRIBUTE_PERSON = "person"; @@ -44,11 +44,11 @@ public PersonStuckEvent(final double time, final Id agentId, final Id

  • getPersonId() { return this.personId; } - + public Id getLinkId() { return this.linkId; } @@ -56,22 +56,19 @@ public Id getLinkId() { public String getLegMode() { return this.legMode; } - + @Override public String getEventType() { return EVENT_TYPE; } - + @Override public Map getAttributes() { Map attr = super.getAttributes(); - if (this.linkId != null) { - attr.put(ATTRIBUTE_LINK, this.linkId.toString()); - } + // personId, linkId handled by superclass if (this.legMode != null) { attr.put(ATTRIBUTE_LEGMODE, this.legMode); } - attr.put(ATTRIBUTE_PERSON, this.personId.toString()); return attr; } } diff --git a/matsim/src/main/java/org/matsim/api/core/v01/events/VehicleAbortsEvent.java b/matsim/src/main/java/org/matsim/api/core/v01/events/VehicleAbortsEvent.java index 39e6782cace..a623a758bd0 100644 --- a/matsim/src/main/java/org/matsim/api/core/v01/events/VehicleAbortsEvent.java +++ b/matsim/src/main/java/org/matsim/api/core/v01/events/VehicleAbortsEvent.java @@ -26,10 +26,10 @@ import org.matsim.api.core.v01.network.Link; import org.matsim.vehicles.Vehicle; -public class VehicleAbortsEvent extends Event { +public class VehicleAbortsEvent extends Event implements HasLinkId, HasVehicleId { public static final String EVENT_TYPE = "vehicle aborts"; - + public static final String ATTRIBUTE_LINK = "link"; public static final String ATTRIBUTE_VEHICLE = "vehicle"; @@ -41,11 +41,11 @@ public VehicleAbortsEvent(final double time, final Id vehicleId, final this.vehicleId = vehicleId; this.linkId = linkId; } - + public Id getVehicleId() { return this.vehicleId; } - + public Id getLinkId() { return this.linkId; } @@ -54,12 +54,11 @@ public Id getLinkId() { public String getEventType() { return EVENT_TYPE; } - + @Override public Map getAttributes() { - Map attr = super.getAttributes(); - attr.put(ATTRIBUTE_LINK, this.linkId.toString()); - attr.put(ATTRIBUTE_VEHICLE, this.vehicleId.toString()); - return attr; + Map atts = super.getAttributes(); + // linkId, vehicleId handled by superclass + return atts; } -} \ No newline at end of file +} diff --git a/matsim/src/main/java/org/matsim/api/core/v01/events/VehicleEntersTrafficEvent.java b/matsim/src/main/java/org/matsim/api/core/v01/events/VehicleEntersTrafficEvent.java index cf467b6c3c2..2316507f115 100644 --- a/matsim/src/main/java/org/matsim/api/core/v01/events/VehicleEntersTrafficEvent.java +++ b/matsim/src/main/java/org/matsim/api/core/v01/events/VehicleEntersTrafficEvent.java @@ -27,7 +27,7 @@ import org.matsim.api.core.v01.population.Person; import org.matsim.vehicles.Vehicle; -public class VehicleEntersTrafficEvent extends Event implements HasPersonId, HasLinkId, HasVehicleId{ +public class VehicleEntersTrafficEvent extends Event implements HasPersonId, HasLinkId, HasVehicleId { public static final String EVENT_TYPE = "vehicle enters traffic"; public static final String ATTRIBUTE_NETWORKMODE = "networkMode"; @@ -39,7 +39,7 @@ public class VehicleEntersTrafficEvent extends Event implements HasPersonId, Has private final String networkMode; private final double relativePositionOnLink; - + public VehicleEntersTrafficEvent(final double time, final Id driverId, final Id linkId, Id vehicleId, String networkMode, double relativePositionOnLink) { super(time); this.driverId = driverId; @@ -48,42 +48,38 @@ public VehicleEntersTrafficEvent(final double time, final Id driverId, f this.networkMode = networkMode; this.relativePositionOnLink = relativePositionOnLink; } - + @Override public Id getPersonId() { return this.driverId; - } - + } + @Override public Id getLinkId() { return this.linkId; } - + public Id getVehicleId() { return vehicleId; } - + @Override public String getEventType() { return EVENT_TYPE; } - + public String getNetworkMode() { return networkMode; } - + public double getRelativePositionOnLink() { return relativePositionOnLink; } - + @Override public Map getAttributes() { Map attr = super.getAttributes(); -// attr.put(ATTRIBUTE_DRIVER, this.driverId.toString()); -// attr.put(ATTRIBUTE_LINK, (this.linkId == null ? null : this.linkId.toString())); -// if (this.vehicleId != null) { -// attr.put(ATTRIBUTE_VEHICLE, this.vehicleId.toString()); -// } + // personId, linkId, vehicleId handled by superclass if (this.networkMode != null) { attr.put(ATTRIBUTE_NETWORKMODE, networkMode); } diff --git a/matsim/src/main/java/org/matsim/api/core/v01/events/VehicleLeavesTrafficEvent.java b/matsim/src/main/java/org/matsim/api/core/v01/events/VehicleLeavesTrafficEvent.java index e39910597bb..600c499063d 100644 --- a/matsim/src/main/java/org/matsim/api/core/v01/events/VehicleLeavesTrafficEvent.java +++ b/matsim/src/main/java/org/matsim/api/core/v01/events/VehicleLeavesTrafficEvent.java @@ -27,7 +27,7 @@ import org.matsim.api.core.v01.population.Person; import org.matsim.vehicles.Vehicle; -public class VehicleLeavesTrafficEvent extends Event implements HasPersonId, HasLinkId { +public class VehicleLeavesTrafficEvent extends Event implements HasPersonId, HasLinkId, HasVehicleId { public static final String EVENT_TYPE = "vehicle leaves traffic"; public static final String ATTRIBUTE_VEHICLE = "vehicle"; @@ -53,30 +53,30 @@ public VehicleLeavesTrafficEvent(final double time, final Id driverId, f this.relativePositionOnLink = relativePositionOnLink; } - + @Override public Id getPersonId() { return this.driverId; - } - + } + @Override public Id getLinkId() { return this.linkId; } - + public Id getVehicleId() { return vehicleId; } - + @Override public String getEventType() { return EVENT_TYPE; } - + public String getNetworkMode() { return networkMode; } - + public double getRelativePositionOnLink() { return relativePositionOnLink; } @@ -84,16 +84,11 @@ public double getRelativePositionOnLink() { @Override public Map getAttributes() { Map attr = super.getAttributes(); - attr.put(ATTRIBUTE_DRIVER, this.driverId.toString()); - attr.put(ATTRIBUTE_LINK, (this.linkId == null ? null : this.linkId.toString())); - if (this.vehicleId != null) { - attr.put(ATTRIBUTE_VEHICLE, this.vehicleId.toString()); - } + // personId, linkId, vehicleId handled by superclass if (this.networkMode != null) { attr.put(ATTRIBUTE_NETWORKMODE, networkMode); } attr.put(ATTRIBUTE_POSITION, Double.toString(this.relativePositionOnLink)); - return attr; } } diff --git a/matsim/src/main/java/org/matsim/api/core/v01/events/handler/PersonScoreEventHandler.java b/matsim/src/main/java/org/matsim/api/core/v01/events/handler/PersonScoreEventHandler.java index 42cf6b3e64f..8a59d2a0164 100644 --- a/matsim/src/main/java/org/matsim/api/core/v01/events/handler/PersonScoreEventHandler.java +++ b/matsim/src/main/java/org/matsim/api/core/v01/events/handler/PersonScoreEventHandler.java @@ -18,7 +18,6 @@ package org.matsim.api.core.v01.events.handler; -import org.matsim.api.core.v01.events.PersonMoneyEvent; import org.matsim.api.core.v01.events.PersonScoreEvent; import org.matsim.core.events.handler.EventHandler; diff --git a/matsim/src/main/java/org/matsim/api/core/v01/network/NetworkFactory.java b/matsim/src/main/java/org/matsim/api/core/v01/network/NetworkFactory.java index 5a58eeb73e1..d38ecd1ec89 100644 --- a/matsim/src/main/java/org/matsim/api/core/v01/network/NetworkFactory.java +++ b/matsim/src/main/java/org/matsim/api/core/v01/network/NetworkFactory.java @@ -23,7 +23,6 @@ import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.core.api.internal.MatsimFactory; -import org.matsim.core.network.LinkFactory; /** * @author dgrether diff --git a/matsim/src/main/java/org/matsim/core/api/experimental/events/BoardingDeniedEvent.java b/matsim/src/main/java/org/matsim/core/api/experimental/events/BoardingDeniedEvent.java index 657c1a62169..c1d2616e23b 100644 --- a/matsim/src/main/java/org/matsim/core/api/experimental/events/BoardingDeniedEvent.java +++ b/matsim/src/main/java/org/matsim/core/api/experimental/events/BoardingDeniedEvent.java @@ -17,9 +17,6 @@ * * * *********************************************************************** */ -/** - * - */ package org.matsim.core.api.experimental.events; import java.util.Map; @@ -35,16 +32,16 @@ * @author nagel * */ -public final class BoardingDeniedEvent extends Event implements HasPersonId +public final class BoardingDeniedEvent extends Event implements HasPersonId { public static final String EVENT_TYPE="BoardingDeniedEvent"; - + public static final String ATTRIBUTE_PERSON_ID = "person"; public static final String ATTRIBUTE_VEHICLE_ID = "vehicle"; private Id personId; private Id vehicleId; - + public BoardingDeniedEvent(final double time, Id personId, Id vehicleId) { super(time); this.personId = personId; @@ -54,11 +51,11 @@ public BoardingDeniedEvent(final double time, Id personId, Id v public Id getPersonId() { return personId; } - + public Id getVehicleId() { return vehicleId; } - + @Override public Map getAttributes() { Map atts = super.getAttributes(); @@ -66,7 +63,7 @@ public Map getAttributes() { atts.put(ATTRIBUTE_VEHICLE_ID, this.vehicleId.toString()); return atts; } - + @Override public String getEventType() { return EVENT_TYPE; diff --git a/matsim/src/main/java/org/matsim/core/api/internal/MatsimParameters.java b/matsim/src/main/java/org/matsim/core/api/internal/MatsimParameters.java index 835a119c453..8fe2af2f13a 100644 --- a/matsim/src/main/java/org/matsim/core/api/internal/MatsimParameters.java +++ b/matsim/src/main/java/org/matsim/core/api/internal/MatsimParameters.java @@ -19,13 +19,10 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.api.internal; -/**Marker interface for classes that contain matsim parameters. - * +/**Marker interface for classes that contain matsim parameters. + * * @author nagel */ public interface MatsimParameters { diff --git a/matsim/src/main/java/org/matsim/core/config/ConfigAliases.java b/matsim/src/main/java/org/matsim/core/config/ConfigAliases.java index a95ce30372e..e8984a8d043 100644 --- a/matsim/src/main/java/org/matsim/core/config/ConfigAliases.java +++ b/matsim/src/main/java/org/matsim/core/config/ConfigAliases.java @@ -9,7 +9,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Stack; import java.util.stream.Collectors; public final class ConfigAliases { diff --git a/matsim/src/main/java/org/matsim/core/config/ConfigGroup.java b/matsim/src/main/java/org/matsim/core/config/ConfigGroup.java index 7f6922ab6c7..34fc8e1aa3f 100644 --- a/matsim/src/main/java/org/matsim/core/config/ConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/config/ConfigGroup.java @@ -20,7 +20,6 @@ package org.matsim.core.config; -import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Collection; @@ -97,7 +96,7 @@ protected void checkConsistency(Config config) { // material is known. Could put all of this in the "global" config consistency checker, but if it conceptually belongs into the // ConfigGroup, I think it is easier to have it more local. Wasn't a big problem, since this method is _only_ called from the global config // itself, which obviously can just pass on a "this" pointer. kai, jan'17) - + // default: just call this method on parameter sets for ( Collection sets : getParameterSets().values() ) { for ( ConfigGroup set : sets ) set.checkConsistency(config); @@ -189,12 +188,12 @@ public boolean removeParameterSet( final ConfigGroup set ) { * Can be extended if there are consistency checks to makes, * for instance if parameter sets of a given type should be * instances of a particular class. - * @param set + * @param set */ protected void checkParameterSet(final ConfigGroup set) { // empty for inheritance } - + /** * Useful for instance if default values are provided but should be cleared if * user provides values. @@ -213,9 +212,9 @@ public final Collection getParameterSets(final String typ public final Map> getParameterSets() { // TODO: immutabilize (including lists) // maybe done with what I did below? kai, sep'16 - + // return parameterSetsPerType; - + Map> parameterSetsPerType2 = new TreeMap<>() ; for ( Entry> entry : parameterSetsPerType.entrySet() ) { parameterSetsPerType2.put( entry.getKey(), Collections.unmodifiableCollection(entry.getValue()) ) ; @@ -232,11 +231,11 @@ public void setLocked() { this.locked = true ; for ( Collection parameterSets : this.parameterSetsPerType.values() ) { for ( ConfigGroup parameterSet : parameterSets ) { - parameterSet.setLocked(); + parameterSet.setLocked(); } } } - + public final void testForLocked() { if ( locked ) { throw new RuntimeException( "Too late to change this ...") ; diff --git a/matsim/src/main/java/org/matsim/core/config/ConfigReaderMatsimV2.java b/matsim/src/main/java/org/matsim/core/config/ConfigReaderMatsimV2.java index 02fcde5d57e..81f85f25664 100644 --- a/matsim/src/main/java/org/matsim/core/config/ConfigReaderMatsimV2.java +++ b/matsim/src/main/java/org/matsim/core/config/ConfigReaderMatsimV2.java @@ -27,18 +27,11 @@ import static org.matsim.core.config.ConfigV2XmlNames.VALUE; import java.util.ArrayDeque; -import java.util.ArrayList; import java.util.Deque; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; import java.util.Stack; -import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.checkerframework.checker.units.qual.C; import org.matsim.core.utils.io.MatsimXmlParser; import org.xml.sax.Attributes; diff --git a/matsim/src/main/java/org/matsim/core/config/ConfigWriterHandlerImplV2.java b/matsim/src/main/java/org/matsim/core/config/ConfigWriterHandlerImplV2.java index c511b1952da..a139ee48043 100644 --- a/matsim/src/main/java/org/matsim/core/config/ConfigWriterHandlerImplV2.java +++ b/matsim/src/main/java/org/matsim/core/config/ConfigWriterHandlerImplV2.java @@ -110,7 +110,7 @@ private Boolean processParameterSets(BufferedWriter writer, String indent, Strin Collection comparisonSets = new ArrayList<>() ; if ( comparisonModule != null ) { comparisonSets = comparisonModule.getParameterSets(entry.getKey()); - }; + } for ( ConfigGroup pSet : entry.getValue() ) { ConfigGroup comparisonPSet = null ; for ( ConfigGroup cg : comparisonSets ) { diff --git a/matsim/src/main/java/org/matsim/core/config/ReflectiveConfigGroup.java b/matsim/src/main/java/org/matsim/core/config/ReflectiveConfigGroup.java index 0cf673c78e4..3a00441d761 100644 --- a/matsim/src/main/java/org/matsim/core/config/ReflectiveConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/config/ReflectiveConfigGroup.java @@ -285,14 +285,29 @@ public final void addParam(final String param_name, final String value) { return; } - Preconditions.checkArgument(storeUnknownParameters, "Module %s of type %s doesn't accept unknown parameters." - + " Parameter %s is not part of the valid parameters: %s", getName(), getClass().getName(), param_name, - setters.keySet()); + this.handleAddUnknownParam(param_name, value); + } + + /** + * This method is designed to be overwritten if a config group wants to provide + * custom handling for unknown parameters, e.g. for improved backwards compatibility. + * For example: It allows to convert (old-named) parameter values to different units and + * store them with the new name (old parameter could be km/h, new parameter could be m/s). + * + * The default implementation in {@link ReflectiveConfigGroup} will either store the + * unknown parameter or throw an exception, depending on the value of {@link #storeUnknownParameters}. + * + * If the method is overwritten, it might make sense to also overwrite {@link #handleGetUnknownValue(String)}. + */ + public void handleAddUnknownParam(final String paramName, final String value) { + Preconditions.checkArgument(this.storeUnknownParameters, "Module %s of type %s doesn't accept unknown parameters." + + " Parameter %s is not part of the valid parameters: %s", getName(), getClass().getName(), paramName, + this.setters.keySet()); log.warn( - "Unknown parameter {} for group {}. Here are the valid parameter names: {}. Only the string value will be remembered.", - param_name, getName(), registeredParams); - super.addParam(param_name, value); + "Unknown parameter {} for group {}. Here are the valid parameter names: {}. Only the string value will be remembered.", + paramName, getName(), this.registeredParams); + super.addParam(paramName, value); } private void invokeSetter(final Method setter, final String value) { @@ -438,13 +453,22 @@ public final String getValue(final String param_name) { if (field != null) { return getParamField(field); } + return this.handleGetUnknownValue(param_name); + } - Preconditions.checkArgument(storeUnknownParameters, "Module %s of type %s doesn't store unknown parameters." - + " Parameter %s is not part of the valid parameters: %s", getName(), getClass().getName(), param_name, - registeredParams); + /** + * This method is designed to be overwritten if a config group wants to provide + * custom handling for unknown parameters, e.g. for improved backwards compatibility. + * + * Also see {@link #handleAddUnknownParam(String, String)} + */ + public String handleGetUnknownValue(final String paramName) { + Preconditions.checkArgument(this.storeUnknownParameters, "Module %s of type %s doesn't store unknown parameters." + + " Parameter %s is not part of the valid parameters: %s", getName(), getClass().getName(), paramName, + this.registeredParams); - log.warn("no getter found for param {}: trying parent method", param_name); - return super.getValue(param_name); + log.warn("no getter found for param {}: trying parent method", paramName); + return super.getValue(paramName); } private String invokeGetter(Method getter) { diff --git a/matsim/src/main/java/org/matsim/core/config/groups/FacilitiesConfigGroup.java b/matsim/src/main/java/org/matsim/core/config/groups/FacilitiesConfigGroup.java index 6824f510ffe..ce1dd8b5cd8 100644 --- a/matsim/src/main/java/org/matsim/core/config/groups/FacilitiesConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/config/groups/FacilitiesConfigGroup.java @@ -51,7 +51,8 @@ public final class FacilitiesConfigGroup extends ReflectiveConfigGroup { private static final String FACILITIES_SOURCE = "facilitiesSource"; public enum FacilitiesSource {none, fromFile, setInScenario, onePerActivityLinkInPlansFile, - onePerActivityLinkInPlansFileExceptWhenCoordinatesAreGiven, onePerActivityLocationInPlansFile}; + onePerActivityLinkInPlansFileExceptWhenCoordinatesAreGiven, onePerActivityLocationInPlansFile} + private FacilitiesSource facilitiesSource = FacilitiesSource.none; // private boolean addEmptyActivityOption = false; diff --git a/matsim/src/main/java/org/matsim/core/config/groups/ScoringConfigGroup.java b/matsim/src/main/java/org/matsim/core/config/groups/ScoringConfigGroup.java index 2f7955e23fc..b58d49c37c1 100644 --- a/matsim/src/main/java/org/matsim/core/config/groups/ScoringConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/config/groups/ScoringConfigGroup.java @@ -572,7 +572,7 @@ public void addActivityParams(final ActivityParams params) { public enum TypicalDurationScoreComputation { uniform, relative - }; + } /* parameter set handling */ @Override diff --git a/matsim/src/main/java/org/matsim/core/config/groups/TimeAllocationMutatorConfigGroup.java b/matsim/src/main/java/org/matsim/core/config/groups/TimeAllocationMutatorConfigGroup.java index 1a4b33e942e..c11569b9c9c 100644 --- a/matsim/src/main/java/org/matsim/core/config/groups/TimeAllocationMutatorConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/config/groups/TimeAllocationMutatorConfigGroup.java @@ -20,10 +20,8 @@ package org.matsim.core.config.groups; -import java.util.Collection; import java.util.Map; -import org.matsim.core.config.ConfigGroup; import org.matsim.core.config.ReflectiveConfigGroup; import org.matsim.core.utils.misc.Time; diff --git a/matsim/src/main/java/org/matsim/core/config/groups/TravelTimeCalculatorConfigGroup.java b/matsim/src/main/java/org/matsim/core/config/groups/TravelTimeCalculatorConfigGroup.java index c0302d24095..b24d37c05fd 100644 --- a/matsim/src/main/java/org/matsim/core/config/groups/TravelTimeCalculatorConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/config/groups/TravelTimeCalculatorConfigGroup.java @@ -19,11 +19,9 @@ * *********************************************************************** */ package org.matsim.core.config.groups; -import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; -import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/matsim/src/main/java/org/matsim/core/config/groups/VspExperimentalConfigGroup.java b/matsim/src/main/java/org/matsim/core/config/groups/VspExperimentalConfigGroup.java index 4930a793bd8..247e28b4a73 100644 --- a/matsim/src/main/java/org/matsim/core/config/groups/VspExperimentalConfigGroup.java +++ b/matsim/src/main/java/org/matsim/core/config/groups/VspExperimentalConfigGroup.java @@ -31,13 +31,13 @@ * @author nagel */ public final class VspExperimentalConfigGroup extends ReflectiveConfigGroup { - + @SuppressWarnings("unused") private final static Logger log = LogManager.getLogger(VspExperimentalConfigGroup.class); public static final String GROUP_NAME = "vspExperimental"; - + // --- @@ -57,7 +57,8 @@ public VspExperimentalConfigGroup() { // --- private static final String VSP_DEFAULTS_CHECKING_LEVEL = "vspDefaultsCheckingLevel" ; - public static enum VspDefaultsCheckingLevel { ignore, info, warn, abort } ; + public static enum VspDefaultsCheckingLevel { ignore, info, warn, abort } + private VspDefaultsCheckingLevel vspDefaultsCheckingLevel = VspDefaultsCheckingLevel.ignore ; @StringGetter(VSP_DEFAULTS_CHECKING_LEVEL) public VspDefaultsCheckingLevel getVspDefaultsCheckingLevel() { @@ -93,8 +94,8 @@ public void setGeneratingBoardingDeniedEvent(boolean isGeneratingBoardingDeniedE this.isGeneratingBoardingDeniedEvent = isGeneratingBoardingDeniedEvent; } // --- - private static final String ABLE_TO_OVERWRITE_PT_INTERACTION_PARAMS = "isAbleToOverwritePtInteractionParams" ; - private boolean isAbleToOverwritePtInteractionParams = false ; // default is that this NOT allowed. kai, nov'12 + private static final String ABLE_TO_OVERWRITE_PT_INTERACTION_PARAMS = "isAbleToOverwritePtInteractionParams" ; + private boolean isAbleToOverwritePtInteractionParams = false ; // default is that this NOT allowed. kai, nov'12 @StringGetter(ABLE_TO_OVERWRITE_PT_INTERACTION_PARAMS) public boolean isAbleToOverwritePtInteractionParams() { return isAbleToOverwritePtInteractionParams; @@ -105,7 +106,7 @@ public void setAbleToOverwritePtInteractionParams(boolean isAbleToOverwritePtInt this.isAbleToOverwritePtInteractionParams = isAbleToOverwritePtInteractionParams; } // --- - private static final String USING_OPPORTUNITY_COST_OF_TIME_FOR_LOCATION_CHOICE = "isUsingOpportunityCostOfTimeForLocationChoice" ; + private static final String USING_OPPORTUNITY_COST_OF_TIME_FOR_LOCATION_CHOICE = "isUsingOpportunityCostOfTimeForLocationChoice" ; private boolean isUsingOpportunityCostOfTimeForLocationChoice = true ; @StringGetter(USING_OPPORTUNITY_COST_OF_TIME_FOR_LOCATION_CHOICE) public boolean isUsingOpportunityCostOfTimeForLocationChoice() { @@ -117,7 +118,8 @@ public void setUsingOpportunityCostOfTimeForLocationChoice(boolean isUsingOpport this.isUsingOpportunityCostOfTimeForLocationChoice = isUsingOpportunityCostOfTimeForLocationChoice; } // --- - public enum CheckingOfMarginalUtilityOfTravellng { allZero, none }; + public enum CheckingOfMarginalUtilityOfTravellng { allZero, none } + private CheckingOfMarginalUtilityOfTravellng checkingOfMarginalUtilityOfTravellng = CheckingOfMarginalUtilityOfTravellng.allZero; public CheckingOfMarginalUtilityOfTravellng getCheckingOfMarginalUtilityOfTravellng(){ return checkingOfMarginalUtilityOfTravellng; @@ -146,7 +148,7 @@ public Map getComments() { for ( VspDefaultsCheckingLevel option : VspDefaultsCheckingLevel.values() ) { options.append(option + " | ") ; } - map.put( VSP_DEFAULTS_CHECKING_LEVEL, + map.put( VSP_DEFAULTS_CHECKING_LEVEL, "Options: | " + options + ". When violating VSP defaults, this results in " + "nothing, logfile infos, logfile warnings, or aborts. Members of VSP should use `abort' or talk to kai.") ; @@ -172,7 +174,7 @@ public void setWritingOutputEvents(boolean writingOutputEvents) { testForLocked() ; this.writingOutputEvents = writingOutputEvents; } - + @Override protected void checkConsistency(Config config) { } diff --git a/matsim/src/main/java/org/matsim/core/controler/ControlerDefaults.java b/matsim/src/main/java/org/matsim/core/controler/ControlerDefaults.java index 33bb9a9c3eb..a61d696bc02 100644 --- a/matsim/src/main/java/org/matsim/core/controler/ControlerDefaults.java +++ b/matsim/src/main/java/org/matsim/core/controler/ControlerDefaults.java @@ -28,21 +28,19 @@ /** * Intention of this class is to have the controler defaults clearly marked and visible. *

    - * The initial use case of this is that we want to deprecated the pattern of taking out a factory from the controler, wrapping something + * The initial use case of this is that we want to deprecated the pattern of taking out a factory from the controler, wrapping something * around it, and putting it back in, since such things may depend on the calling sequence and may thus be unstable. Users - * should then rather use the default factory (provided here) and wrap everything around it in a sequence they control themselves. + * should then rather use the default factory (provided here) and wrap everything around it in a sequence they control themselves. *

    * I just renamed this from ControlerUtils to ControlerDefaults since XxxUtils is for us, in many case, the outmost user interface, * and the material here IMO is not "outermost". kai, nov'13 - * + * * @author nagel * - */ -/** * @deprecated -- this pre-dates guice injection; one should rather use guice and {@link ControlerDefaultsModule}. kai, mar'20 */ public final class ControlerDefaults { - + private ControlerDefaults(){} // should not be instantiated /** diff --git a/matsim/src/main/java/org/matsim/core/controler/ControlerListenerManagerImpl.java b/matsim/src/main/java/org/matsim/core/controler/ControlerListenerManagerImpl.java index 1566d93be45..ade7fa81762 100644 --- a/matsim/src/main/java/org/matsim/core/controler/ControlerListenerManagerImpl.java +++ b/matsim/src/main/java/org/matsim/core/controler/ControlerListenerManagerImpl.java @@ -103,13 +103,13 @@ public void fireControlerStartupEvent() { StartupListener[] listener = this.coreListenerList.getListeners(StartupListener.class); Arrays.sort(listener, Comparator.comparingDouble(ControlerListener::priority).reversed()); for (StartupListener aListener : listener) { - log.info("calling notifyStartup on " + aListener.getClass().getName() + " with priority " + + aListener.priority()); + log.info("calling notifyStartup on " + aListener.getClass().getName() + " with priority " + aListener.priority()); aListener.notifyStartup(event); } listener = this.listenerList.getListeners(StartupListener.class); Arrays.sort(listener, Comparator.comparingDouble(ControlerListener::priority).reversed()); for (StartupListener aListener : listener) { - log.info("calling notifyStartup on " + aListener.getClass().getName() + " with priority " + + aListener.priority()); + log.info("calling notifyStartup on " + aListener.getClass().getName() + " with priority " + aListener.priority()); aListener.notifyStartup(event); } log.info("all ControlerStartupListeners called." ); @@ -125,14 +125,14 @@ public void fireControlerShutdownEvent(final boolean unexpected, int iteration) Arrays.sort(listener, Comparator.comparingDouble(ControlerListener::priority).reversed()); for (ShutdownListener aListener : listener) { - log.info("calling notifyShutdown on " + aListener.getClass().getName() + " with priority " + + aListener.priority()); + log.info("calling notifyShutdown on " + aListener.getClass().getName() + " with priority " + aListener.priority()); aListener.notifyShutdown(event); } listener = this.listenerList.getListeners(ShutdownListener.class); Arrays.sort(listener, Comparator.comparingDouble(ControlerListener::priority).reversed()); for (ShutdownListener aListener : listener) { - log.info("calling notifyShutdown on " + aListener.getClass().getName() + " with priority " + + aListener.priority()); + log.info("calling notifyShutdown on " + aListener.getClass().getName() + " with priority " + aListener.priority()); aListener.notifyShutdown(event); } log.info("all ControlerShutdownListeners called."); @@ -147,13 +147,13 @@ public void fireControlerIterationStartsEvent(final int iteration, boolean isLas IterationStartsListener[] listener = this.coreListenerList.getListeners(IterationStartsListener.class); Arrays.sort(listener, Comparator.comparingDouble(ControlerListener::priority).reversed()); for (IterationStartsListener aListener : listener) { - log.info("calling notifyIterationStarts on " + aListener.getClass().getName() + " with priority " + + aListener.priority()); + log.info("calling notifyIterationStarts on " + aListener.getClass().getName() + " with priority " + aListener.priority()); aListener.notifyIterationStarts(event); } listener = this.listenerList.getListeners(IterationStartsListener.class); Arrays.sort(listener, Comparator.comparingDouble(ControlerListener::priority).reversed()); for (IterationStartsListener aListener : listener) { - log.info("calling notifyIterationStarts on " + aListener.getClass().getName() + " with priority " + + aListener.priority()); + log.info("calling notifyIterationStarts on " + aListener.getClass().getName() + " with priority " + aListener.priority()); aListener.notifyIterationStarts(event); } log.info("[it." + iteration + "] all ControlerIterationStartsListeners called."); @@ -169,7 +169,7 @@ public void fireControlerIterationEndsEvent(final int iteration, boolean isLastI IterationEndsListener[] listener = this.coreListenerList.getListeners(IterationEndsListener.class); Arrays.sort(listener, Comparator.comparingDouble(ControlerListener::priority).reversed()); for (IterationEndsListener aListener : listener) { - log.info("calling notifyIterationEnds on " + aListener.getClass().getName() + " with priority " + + aListener.priority()); + log.info("calling notifyIterationEnds on " + aListener.getClass().getName() + " with priority " + aListener.priority()); aListener.notifyIterationEnds(event); } } @@ -177,7 +177,7 @@ public void fireControlerIterationEndsEvent(final int iteration, boolean isLastI IterationEndsListener[] listener = this.listenerList.getListeners(IterationEndsListener.class); Arrays.sort(listener, Comparator.comparingDouble(ControlerListener::priority).reversed()); for (IterationEndsListener aListener : listener) { - log.info("calling notifyIterationEnds on " + aListener.getClass().getName() + " with priority " + + aListener.priority()); + log.info("calling notifyIterationEnds on " + aListener.getClass().getName() + " with priority " + aListener.priority()); aListener.notifyIterationEnds(event); } } @@ -194,7 +194,7 @@ public void fireControlerScoringEvent(final int iteration, boolean isLastIterati ScoringListener[] listener = this.coreListenerList.getListeners(ScoringListener.class); Arrays.sort(listener, Comparator.comparingDouble(ControlerListener::priority).reversed()); for (ScoringListener aListener : listener) { - log.info("calling notifyScoring on " + aListener.getClass().getName() + " with priority " + + aListener.priority()); + log.info("calling notifyScoring on " + aListener.getClass().getName() + " with priority " + aListener.priority()); aListener.notifyScoring(event); } } @@ -202,7 +202,7 @@ public void fireControlerScoringEvent(final int iteration, boolean isLastIterati ScoringListener[] listener = this.listenerList.getListeners(ScoringListener.class); Arrays.sort(listener, Comparator.comparingDouble(ControlerListener::priority).reversed()); for (ScoringListener aListener : listener) { - log.info("calling notifyScoring on " + aListener.getClass().getName() + " with priority " + + aListener.priority()); + log.info("calling notifyScoring on " + aListener.getClass().getName() + " with priority " + aListener.priority()); aListener.notifyScoring(event); } } @@ -218,13 +218,13 @@ public void fireControlerReplanningEvent(final int iteration, boolean isLastIter ReplanningListener[] listener = this.coreListenerList.getListeners(ReplanningListener.class); Arrays.sort(listener, Comparator.comparingDouble(ControlerListener::priority).reversed()); for (ReplanningListener aListener : listener) { - log.info("calling notifyReplanning on " + aListener.getClass().getName() + " with priority " + + aListener.priority()); + log.info("calling notifyReplanning on " + aListener.getClass().getName() + " with priority " + aListener.priority()); aListener.notifyReplanning(event); } listener = this.listenerList.getListeners(ReplanningListener.class); Arrays.sort(listener, Comparator.comparingDouble(ControlerListener::priority).reversed()); for (ReplanningListener aListener : listener) { - log.info("calling notifyReplanning on " + aListener.getClass().getName() + " with priority " + + aListener.priority()); + log.info("calling notifyReplanning on " + aListener.getClass().getName() + " with priority " + aListener.priority()); aListener.notifyReplanning(event); } log.info("[it." + iteration + "] all ControlerReplanningListeners called."); @@ -239,13 +239,13 @@ public void fireControlerBeforeMobsimEvent(final int iteration, boolean isLastIt BeforeMobsimListener[] listener = this.coreListenerList.getListeners(BeforeMobsimListener.class); Arrays.sort(listener, Comparator.comparingDouble(ControlerListener::priority).reversed()); for (BeforeMobsimListener aListener : listener) { - log.info("calling notifyBeforeMobsim on " + aListener.getClass().getName() + " with priority " + + aListener.priority()); + log.info("calling notifyBeforeMobsim on " + aListener.getClass().getName() + " with priority " + aListener.priority()); aListener.notifyBeforeMobsim(event); } listener = this.listenerList.getListeners(BeforeMobsimListener.class); Arrays.sort(listener, Comparator.comparingDouble(ControlerListener::priority).reversed()); for (BeforeMobsimListener aListener : listener) { - log.info("calling notifyBeforeMobsim on " + aListener.getClass().getName() + " with priority " + + aListener.priority()); + log.info("calling notifyBeforeMobsim on " + aListener.getClass().getName() + " with priority " + aListener.priority()); aListener.notifyBeforeMobsim(event); } log.info("[it." + iteration + "] all ControlerBeforeMobsimListeners called."); @@ -260,13 +260,13 @@ public void fireControlerAfterMobsimEvent(final int iteration, boolean isLastIte AfterMobsimListener[] listener = this.coreListenerList.getListeners(AfterMobsimListener.class); Arrays.sort(listener, Comparator.comparingDouble(ControlerListener::priority).reversed()); for (AfterMobsimListener aListener : listener) { - log.info("calling notifyAfterMobsim on " + aListener.getClass().getName() + " with priority " + + aListener.priority()); + log.info("calling notifyAfterMobsim on " + aListener.getClass().getName() + " with priority " + aListener.priority()); aListener.notifyAfterMobsim(event); } listener = this.listenerList.getListeners(AfterMobsimListener.class); Arrays.sort(listener, Comparator.comparingDouble(ControlerListener::priority).reversed()); for (AfterMobsimListener aListener : listener) { - log.info("calling notifyAfterMobsim on " + aListener.getClass().getName() + " with priority " + + aListener.priority()); + log.info("calling notifyAfterMobsim on " + aListener.getClass().getName() + " with priority " + aListener.priority()); aListener.notifyAfterMobsim(event); } log.info("[it." + iteration + "] all ControlerAfterMobsimListeners called."); diff --git a/matsim/src/main/java/org/matsim/core/controler/ControlerUtils.java b/matsim/src/main/java/org/matsim/core/controler/ControlerUtils.java index 7fe67aa0a92..490076578e5 100644 --- a/matsim/src/main/java/org/matsim/core/controler/ControlerUtils.java +++ b/matsim/src/main/java/org/matsim/core/controler/ControlerUtils.java @@ -27,7 +27,6 @@ import org.matsim.core.config.Config; import org.matsim.core.config.ConfigWriter; import org.matsim.core.controler.corelisteners.ControlerDefaultCoreListenersModule; -import org.matsim.core.gbl.Gbl; import org.matsim.core.scenario.ScenarioByInstanceModule; /** @@ -78,7 +77,7 @@ private ControlerUtils() {} // namespace for static methods only should not be i public static final void checkConfigConsistencyAndWriteToLog(Config config, final String message) { log.info(message); - String newline = System.getProperty("line.separator");// use native line endings for logfile + String newline = System.lineSeparator();// use native line endings for logfile StringWriter writer = new StringWriter(); new ConfigWriter(config).writeStream(new PrintWriter(writer), newline); log.info(newline + newline + writer.getBuffer().toString()); diff --git a/matsim/src/main/java/org/matsim/core/controler/OutputDirectoryLogging.java b/matsim/src/main/java/org/matsim/core/controler/OutputDirectoryLogging.java index 7267f58c6a8..5850e378879 100644 --- a/matsim/src/main/java/org/matsim/core/controler/OutputDirectoryLogging.java +++ b/matsim/src/main/java/org/matsim/core/controler/OutputDirectoryLogging.java @@ -21,8 +21,8 @@ package org.matsim.core.controler; import java.io.IOException; +import java.nio.file.FileSystems; -import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; @@ -118,8 +118,8 @@ public static void initLoggingWithOutputDirectory(final String outputDirectory) ctx.getConfiguration().getRootLogger().removeAppender(collectLogMessagesAppender.getName()); ctx.updateLoggers(); } - String logfilename = outputDirectory + System.getProperty("file.separator") + LOGFILE; - String warnlogfilename = outputDirectory + System.getProperty("file.separator") + WARNLOGFILE; + String logfilename = outputDirectory + FileSystems.getDefault().getSeparator() + LOGFILE; + String warnlogfilename = outputDirectory + FileSystems.getDefault().getSeparator() + WARNLOGFILE; initLogging(logfilename, warnlogfilename); } diff --git a/matsim/src/main/java/org/matsim/core/controler/PrepareForMobsimImpl.java b/matsim/src/main/java/org/matsim/core/controler/PrepareForMobsimImpl.java index 40c1fa9f6d1..183961cd480 100644 --- a/matsim/src/main/java/org/matsim/core/controler/PrepareForMobsimImpl.java +++ b/matsim/src/main/java/org/matsim/core/controler/PrepareForMobsimImpl.java @@ -33,7 +33,6 @@ import org.matsim.core.population.algorithms.AbstractPersonAlgorithm; import org.matsim.core.population.algorithms.ParallelPersonAlgorithmUtils; import org.matsim.core.population.algorithms.PersonPrepareForSim; -import org.matsim.core.router.MainModeIdentifier; import org.matsim.core.router.PlanRouter; import org.matsim.core.router.TripRouter; import org.matsim.core.utils.timing.TimeInterpretation; diff --git a/matsim/src/main/java/org/matsim/core/controler/corelisteners/PlansReplanningImpl.java b/matsim/src/main/java/org/matsim/core/controler/corelisteners/PlansReplanningImpl.java index 733087d70df..e46158e6288 100644 --- a/matsim/src/main/java/org/matsim/core/controler/corelisteners/PlansReplanningImpl.java +++ b/matsim/src/main/java/org/matsim/core/controler/corelisteners/PlansReplanningImpl.java @@ -24,7 +24,6 @@ import org.matsim.core.controler.events.ReplanningEvent; import org.matsim.core.controler.listener.ReplanningListener; import org.matsim.core.replanning.ReplanningContext; -import org.matsim.core.replanning.ReplanningUtils; import org.matsim.core.replanning.StrategyManager; import org.matsim.core.replanning.conflicts.ConflictManager; diff --git a/matsim/src/main/java/org/matsim/core/events/EventsReaderTXT.java b/matsim/src/main/java/org/matsim/core/events/EventsReaderTXT.java index 12484fef7ee..a23f4db792a 100644 --- a/matsim/src/main/java/org/matsim/core/events/EventsReaderTXT.java +++ b/matsim/src/main/java/org/matsim/core/events/EventsReaderTXT.java @@ -31,7 +31,6 @@ import java.io.IOException; import static org.matsim.core.events.algorithms.EventWriterTXT.Number.*; -import static org.matsim.core.events.algorithms.EventWriterTXT.Number.ActivityEnd; /** * Created by laemmel on 16/11/15. diff --git a/matsim/src/main/java/org/matsim/core/events/algorithms/EventWriterJson.java b/matsim/src/main/java/org/matsim/core/events/algorithms/EventWriterJson.java index 85c26e35e00..c10087fd3ed 100644 --- a/matsim/src/main/java/org/matsim/core/events/algorithms/EventWriterJson.java +++ b/matsim/src/main/java/org/matsim/core/events/algorithms/EventWriterJson.java @@ -26,8 +26,8 @@ public EventWriterJson(File outfile) { this.out = IOUtils.getOutputStream(outfile.toURI().toURL(), false); this.jsonGenerator = new JsonFactory().createGenerator(this.out); this.jsonGenerator.setPrettyPrinter(new MinimalPrettyPrinter("\n")); - } catch (UncheckedIOException | IOException e) { - e.printStackTrace(); + } catch (IOException e) { + throw new UncheckedIOException(e); } } @@ -37,7 +37,7 @@ public EventWriterJson(OutputStream stream) { this.jsonGenerator = new JsonFactory().createGenerator(this.out); this.jsonGenerator.setPrettyPrinter(new MinimalPrettyPrinter("\n")); } catch (IOException e) { - e.printStackTrace(); + throw new UncheckedIOException(e); } } @@ -61,7 +61,7 @@ public void handleEvent(final Event event) { } this.jsonGenerator.writeEndObject(); } catch (IOException e) { - e.printStackTrace(); + throw new UncheckedIOException(e); } } diff --git a/matsim/src/main/java/org/matsim/core/events/algorithms/EventWriterTXT.java b/matsim/src/main/java/org/matsim/core/events/algorithms/EventWriterTXT.java index b198a660076..6230083b888 100644 --- a/matsim/src/main/java/org/matsim/core/events/algorithms/EventWriterTXT.java +++ b/matsim/src/main/java/org/matsim/core/events/algorithms/EventWriterTXT.java @@ -25,6 +25,8 @@ import java.util.HashMap; import java.util.Map; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.ActivityEndEvent; import org.matsim.api.core.v01.events.ActivityStartEvent; @@ -49,21 +51,23 @@ import org.matsim.core.utils.io.IOUtils; import org.matsim.vehicles.Vehicle; -public class EventWriterTXT implements EventWriter, ActivityEndEventHandler, ActivityStartEventHandler, PersonArrivalEventHandler, - PersonDepartureEventHandler, PersonStuckEventHandler, PersonMoneyEventHandler, +public class EventWriterTXT implements EventWriter, ActivityEndEventHandler, ActivityStartEventHandler, PersonArrivalEventHandler, + PersonDepartureEventHandler, PersonStuckEventHandler, PersonMoneyEventHandler, VehicleEntersTrafficEventHandler, LinkEnterEventHandler, LinkLeaveEventHandler { - + + private static final Logger LOG = LogManager.getLogger(EventWriterTXT.class); + /* Implement all the different event handlers by its own. Future event types will no longer be * suitable to be written to a TXT-format file, but will have additional attributes that need to be * stored in XML. Explicitly listing the event handlers makes sure only events are written to TXT that * can also correctly be read in again, and helps fix the test cases during introduction of the new, * additional events. */ - + private BufferedWriter out = null; private double lastTime = Double.NaN; private String timeString = null; - + private Map, Id> vehicleToDriverMap = new HashMap<>(); public EventWriterTXT(final String filename) { @@ -77,7 +81,7 @@ public void closeFile() { this.out.close(); this.out = null; } catch (IOException e) { - e.printStackTrace(); + LOG.error(e.getMessage(), e); } } } @@ -88,7 +92,7 @@ public void init(final String outfilename) { this.out.close(); this.out = null; } catch (IOException e) { - e.printStackTrace(); + LOG.error(e.getMessage(), e); } } try { @@ -102,7 +106,7 @@ public void init(final String outfilename) { eventsTxtFile += "DESCRIPTION\n"; this.out.write(eventsTxtFile); } catch (IOException e) { - e.printStackTrace(); + LOG.error(e.getMessage(), e); } } @@ -133,7 +137,7 @@ private void writeLine(final double time, final Id agentId, final Id\n"); } catch (IOException e) { - e.printStackTrace(); + LOG.error(e.getMessage(), e); } } diff --git a/matsim/src/main/java/org/matsim/core/events/handler/EventHandler.java b/matsim/src/main/java/org/matsim/core/events/handler/EventHandler.java index fe6c4395282..c0099d30344 100644 --- a/matsim/src/main/java/org/matsim/core/events/handler/EventHandler.java +++ b/matsim/src/main/java/org/matsim/core/events/handler/EventHandler.java @@ -20,13 +20,12 @@ package org.matsim.core.events.handler; -import org.matsim.api.core.v01.events.Event; import org.matsim.core.api.internal.MatsimExtensionPoint; /** * Examples:
      *
    • {@link tutorial.programming.example06EventsHandling.RunEventsHandlingExample} - *
    • {@link tutorial.programming.example06EventsHandling.RunEventsHandlingWithControlerExample} + *
    • {@link tutorial.programming.example06EventsHandling.RunEventsHandlingWithControlerExample} *
    • {@link tutorial.programming.example21tutorialTUBclass.events.RunEventsHandlingExample} *
    * @@ -35,12 +34,12 @@ *
  • This is deliberately without a handleEvent( Event ev ) so that derived interfaces and ultimately classes are not * forced to implement a handler that deals with all events. kai, with input from dominik, nov'11 * - * + * */ public interface EventHandler extends MatsimExtensionPoint { - /** Gives the event handler the possibility to clean up its internal state. + /** Gives the event handler the possibility to clean up its internal state. * Within a Controler-Simulation, this is called before the mobsim starts. - * + * * @param iteration the up-coming iteration from which up-coming events will be from. */ default void reset(int iteration) {} diff --git a/matsim/src/main/java/org/matsim/core/mobsim/jdeqsim/Road.java b/matsim/src/main/java/org/matsim/core/mobsim/jdeqsim/Road.java index e76863b4012..60395ba7868 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/jdeqsim/Road.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/jdeqsim/Road.java @@ -25,7 +25,6 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.core.network.NetworkUtils; -import org.matsim.core.utils.misc.Time; /** * The road is simulated as an active agent, moving arround vehicles. diff --git a/matsim/src/main/java/org/matsim/core/mobsim/jdeqsim/util/CppEventFileParser.java b/matsim/src/main/java/org/matsim/core/mobsim/jdeqsim/util/CppEventFileParser.java index 8060de84758..fa030fd3b3d 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/jdeqsim/util/CppEventFileParser.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/jdeqsim/util/CppEventFileParser.java @@ -1,24 +1,24 @@ - -/* *********************************************************************** * - * project: org.matsim.* - * CppEventFileParser.java - * * - * *********************************************************************** * - * * - * copyright : (C) 2019 by the members listed in the COPYING, * - * LICENSE and WARRANTY file. * - * email : info at matsim dot org * - * * - * *********************************************************************** * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * See also COPYING, LICENSE and WARRANTY file * - * * - * *********************************************************************** */ - + +/* *********************************************************************** * + * project: org.matsim.* + * CppEventFileParser.java + * * + * *********************************************************************** * + * * + * copyright : (C) 2019 by the members listed in the COPYING, * + * LICENSE and WARRANTY file. * + * email : info at matsim dot org * + * * + * *********************************************************************** * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * See also COPYING, LICENSE and WARRANTY file * + * * + * *********************************************************************** */ + package org.matsim.core.mobsim.jdeqsim.util; import java.io.BufferedReader; @@ -26,6 +26,8 @@ import java.util.ArrayList; import java.util.StringTokenizer; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.events.LinkEnterEvent; @@ -39,32 +41,17 @@ /** * This parser can read the event output files of the C++ DEQSim. - * + * * @author rashid_waraich */ public class CppEventFileParser { -// private static ArrayList eventLog = null; - - public static void main(final String[] args) { - String eventFileName = args[0]; - CppEventFileParser eventFileParser = new CppEventFileParser(); - eventFileParser.parse(eventFileName); - } - - public void parse(final String eventFileName) { -// CppEventFileParser.eventLog = CppEventFileParser.parseFile(eventFileName); - // for (int i = 0; i < eventLog.size(); i++) { - // eventLog.get(i).print(); - // } - } + private static final Logger LOG = LogManager.getLogger(CppEventFileParser.class); public static ArrayList parseFile(final String filePath) { int counter = 0; - ArrayList rows = new ArrayList(); - BufferedReader br = null; - try { - br = IOUtils.getBufferedReader(filePath); + ArrayList rows = new ArrayList<>(); + try (BufferedReader br = IOUtils.getBufferedReader(filePath)) { String line = null; StringTokenizer tokenizer = null; line = br.readLine(); @@ -118,15 +105,7 @@ public static ArrayList parseFile(final String filePath) { line = br.readLine(); } } catch (IOException ex) { - System.out.println(ex); - } finally { - try { - if (br != null) - br.close(); - } catch (IOException e) { - e.printStackTrace(); - } - + LOG.error("error reading events", ex); } return rows; diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/AgentTracker.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/AgentTracker.java index a431ccbe98b..126fdbcfd40 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/AgentTracker.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/AgentTracker.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.mobsim.qsim; import org.matsim.api.core.v01.Id; diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/HasAgentTracker.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/HasAgentTracker.java index 716ac1922a9..648639df00c 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/HasAgentTracker.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/HasAgentTracker.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.mobsim.qsim; /** diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/InternalInterface.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/InternalInterface.java index 1ac013da255..0b46df85cc9 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/InternalInterface.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/InternalInterface.java @@ -24,7 +24,6 @@ import org.matsim.api.core.v01.population.Person; import org.matsim.core.mobsim.framework.MobsimAgent; import org.matsim.core.mobsim.qsim.interfaces.DepartureHandler; -import org.matsim.core.mobsim.qsim.interfaces.Netsim; import java.util.List; @@ -33,7 +32,7 @@ *
  • The main functionality of this interface is arrangeNextAgentState. *
  • getMobsim is provided as a convenience. * - * + * * @author nagel * */ diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/PreplanningEngine.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/PreplanningEngine.java index cb85462403e..0f34e2d4a5b 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/PreplanningEngine.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/PreplanningEngine.java @@ -347,7 +347,6 @@ private void updateAgentPlan(MobsimAgent agent, TripInfo tripInfo) { double departureTime = tripInfo.getExpectedBoardingTime() - 900.; // always depart 15min before pickup List planElements = tripRouter.calcRoute(TransportMode.walk, fromFacility, toFacility, departureTime, null, inputTrip.getTripAttributes()); - ; // not sure if this works for walk, but it should ... result.addAll(planElements); diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/QSimModule.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/QSimModule.java index fd46dcdc95f..9332607428c 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/QSimModule.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/QSimModule.java @@ -28,22 +28,13 @@ import java.util.List; import java.util.Set; -import jakarta.inject.Inject; - -import org.matsim.core.config.Config; import org.matsim.core.controler.AbstractModule; import org.matsim.core.mobsim.framework.Mobsim; import org.matsim.core.mobsim.qsim.changeeventsengine.NetworkChangeEventsModule; import org.matsim.core.mobsim.qsim.components.QSimComponentsModule; import org.matsim.core.mobsim.qsim.messagequeueengine.MessageQueueModule; -import org.matsim.core.mobsim.qsim.pt.ComplexTransitStopHandlerFactory; -import org.matsim.core.mobsim.qsim.pt.SimpleTransitStopHandlerFactory; import org.matsim.core.mobsim.qsim.pt.TransitEngineModule; -import org.matsim.core.mobsim.qsim.pt.TransitStopHandlerFactory; -import org.matsim.core.mobsim.qsim.qnetsimengine.DefaultQNetworkFactory; -import org.matsim.core.mobsim.qsim.qnetsimengine.QLanesNetworkFactory; import org.matsim.core.mobsim.qsim.qnetsimengine.QNetsimEngineModule; -import org.matsim.core.mobsim.qsim.qnetsimengine.QNetworkFactory; import com.google.inject.Key; import com.google.inject.TypeLiteral; diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/TeleportationEngine.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/TeleportationEngine.java index 9b48bd08797..f92575675d1 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/TeleportationEngine.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/TeleportationEngine.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.mobsim.qsim; import org.matsim.core.mobsim.qsim.interfaces.DepartureHandler; diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/agents/DefaultAgentFactory.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/agents/DefaultAgentFactory.java index 596d0fca564..084b3defa24 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/agents/DefaultAgentFactory.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/agents/DefaultAgentFactory.java @@ -22,11 +22,8 @@ import org.matsim.api.core.v01.population.Person; import org.matsim.core.mobsim.framework.MobsimDriverAgent; import org.matsim.core.mobsim.qsim.interfaces.Netsim; -import org.matsim.core.population.PopulationUtils; import org.matsim.core.utils.timing.TimeInterpretation; -import java.sql.Time; - import jakarta.inject.Inject; /** diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/agents/HasModifiablePlan.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/agents/HasModifiablePlan.java index ba9061d703a..98f9857af21 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/agents/HasModifiablePlan.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/agents/HasModifiablePlan.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.mobsim.qsim.agents; import org.matsim.api.core.v01.population.Plan; @@ -33,11 +30,11 @@ public interface HasModifiablePlan { Plan getModifiablePlan(); - + void resetCaches() ; int getCurrentLinkIndex(); // not totally obvious that this should be _here_, but it really only makes sense together with the modifiable plan/within-da replanning // capability. Maybe should find a different name for the interface. kai, nov'17 - + } diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/agents/TransitAgentImpl.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/agents/TransitAgentImpl.java index 1128efd57f4..ceed5523234 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/agents/TransitAgentImpl.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/agents/TransitAgentImpl.java @@ -29,7 +29,6 @@ import org.matsim.core.mobsim.qsim.interfaces.MobsimVehicle; import org.matsim.core.mobsim.qsim.pt.PTPassengerAgent; import org.matsim.core.mobsim.qsim.pt.TransitVehicle; -import org.matsim.pt.config.TransitConfigGroup; import org.matsim.pt.config.TransitConfigGroup.BoardingAcceptance; import org.matsim.pt.routes.TransitPassengerRoute; import org.matsim.pt.transitSchedule.api.TransitLine; @@ -46,7 +45,7 @@ public final class TransitAgentImpl implements PTPassengerAgent { private BasicPlanAgentImpl basicAgentDelegate; private final BoardingAcceptance boardingAcceptance ; - + public TransitAgentImpl( BasicPlanAgentImpl basicAgent ) { this( basicAgent, BoardingAcceptance.checkLineAndStop ) ; } diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/interfaces/DepartureHandler.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/interfaces/DepartureHandler.java index 23f434726a0..c2a2e496858 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/interfaces/DepartureHandler.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/interfaces/DepartureHandler.java @@ -1,6 +1,6 @@ /* *********************************************************************** * * project: org.matsim.* - * + * * * * *********************************************************************** * * * @@ -22,14 +22,8 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; -import org.matsim.api.core.v01.population.Person; import org.matsim.core.mobsim.framework.MobsimAgent; import org.matsim.core.mobsim.qsim.components.QSimComponent; -import org.matsim.facilities.Facility; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; - -import java.util.List; -import java.util.Map; public interface DepartureHandler extends QSimComponent { diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/interfaces/TripInfo.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/interfaces/TripInfo.java index 3a29811cbc0..a17113df3ee 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/interfaces/TripInfo.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/interfaces/TripInfo.java @@ -24,7 +24,6 @@ import java.util.List; import java.util.Map; -import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Route; import org.matsim.core.mobsim.framework.MobsimPassengerAgent; import org.matsim.facilities.Facility; diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/PassengerAccessEgressImpl.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/PassengerAccessEgressImpl.java index 1cf6b2a41f4..2ae41ccb0ca 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/PassengerAccessEgressImpl.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/PassengerAccessEgressImpl.java @@ -24,8 +24,6 @@ import java.util.List; import java.util.Set; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.events.PersonEntersVehicleEvent; @@ -38,7 +36,6 @@ import org.matsim.core.mobsim.framework.MobsimDriverAgent; import org.matsim.core.mobsim.framework.PassengerAgent; import org.matsim.core.mobsim.qsim.InternalInterface; -import org.matsim.core.mobsim.qsim.agents.PersonDriverAgentImpl; import org.matsim.core.mobsim.qsim.interfaces.MobsimVehicle; import org.matsim.pt.transitSchedule.api.TransitLine; import org.matsim.pt.transitSchedule.api.TransitRoute; @@ -48,7 +45,7 @@ /** - * + * * @author dgrether * */ @@ -60,7 +57,7 @@ class PassengerAccessEgressImpl implements PassengerAccessEgress { private Set agentsDeniedToBoard = null; private Scenario scenario; private EventsManager eventsManager; - + PassengerAccessEgressImpl(InternalInterface internalInterface, TransitStopAgentTracker agentTracker, Scenario scenario, EventsManager eventsManager) { this.internalInterface = internalInterface; this.agentTracker = agentTracker; @@ -72,16 +69,16 @@ class PassengerAccessEgressImpl implements PassengerAccessEgress { this.agentsDeniedToBoard = new HashSet<>(); } } - + /** * @return should be 0.0 or 1.0, values greater than 1.0 may lead to buggy behavior, dependent on TransitStopHandler used */ - /*package*/ double calculateStopTimeAndTriggerBoarding(TransitRoute transitRoute, TransitLine transitLine, final TransitVehicle vehicle, + /*package*/ double calculateStopTimeAndTriggerBoarding(TransitRoute transitRoute, TransitLine transitLine, final TransitVehicle vehicle, final TransitStopFacility stop, List stopsToCome, final double now) { ArrayList passengersLeaving = findPassengersLeaving(vehicle, stop); int freeCapacity = vehicle.getPassengerCapacity() - vehicle.getPassengers().size() + passengersLeaving.size(); List passengersEntering = findPassengersEntering(transitRoute, transitLine, vehicle, stop, stopsToCome, freeCapacity, now); - + TransitStopHandler stopHandler = vehicle.getStopHandler(); double stopTime = stopHandler.handleTransitStop(stop, now, passengersLeaving, passengersEntering, this, vehicle); if (stopTime == 0.0){ // (de-)boarding is complete when the additional stopTime is 0.0 @@ -102,14 +99,14 @@ private void fireBoardingDeniedEvents(TransitVehicle vehicle, double now){ ) ; } } - - - private List findPassengersEntering(TransitRoute transitRoute, TransitLine transitLine, TransitVehicle vehicle, + + + private List findPassengersEntering(TransitRoute transitRoute, TransitLine transitLine, TransitVehicle vehicle, final TransitStopFacility stop, List stopsToCome, int freeCapacity, double now) { ArrayList passengersEntering = new ArrayList<>(); - + if (this.isGeneratingDeniedBoardingEvents) { - + for (PTPassengerAgent agent : this.agentTracker.getAgentsAtFacility(stop.getId())) { if (agent.getEnterTransitRoute(transitLine, transitRoute, stopsToCome, vehicle)) { if (freeCapacity >= 1) { @@ -122,7 +119,7 @@ private List findPassengersEntering(TransitRoute transitRoute, } } else { - + for (PTPassengerAgent agent : this.agentTracker.getAgentsAtFacility(stop.getId())) { if (freeCapacity == 0) { break; @@ -132,14 +129,14 @@ private List findPassengersEntering(TransitRoute transitRoute, freeCapacity--; } } - + } - + return passengersEntering; } - - - + + + private ArrayList findPassengersLeaving(TransitVehicle vehicle, final TransitStopFacility stop) { ArrayList passengersLeaving = new ArrayList<>(); @@ -150,7 +147,7 @@ private ArrayList findPassengersLeaving(TransitVehicle vehicle } return passengersLeaving; } - + @Override public boolean handlePassengerEntering(PTPassengerAgent passenger, MobsimVehicle vehicle, Id fromStopFacilityId, double time) { @@ -158,7 +155,7 @@ public boolean handlePassengerEntering(PTPassengerAgent passenger, MobsimVehicle if(handled){ this.agentTracker.removeAgentFromStop(passenger, fromStopFacilityId); MobsimAgent planAgent = (MobsimAgent) passenger; -// if (planAgent instanceof PersonDriverAgentImpl) { +// if (planAgent instanceof PersonDriverAgentImpl) { Id agentId = planAgent.getId(); Id linkId = planAgent.getCurrentLinkId(); this.internalInterface.unregisterAdditionalAgentOnLink(agentId, linkId) ; @@ -176,10 +173,10 @@ public boolean handlePassengerLeaving(PTPassengerAgent passenger, MobsimVehicle if(handled){ passenger.setVehicle(null); eventsManager.processEvent(new PersonLeavesVehicleEvent(time, passenger.getId(), vehicle.getVehicle().getId())); - + // from here on works only if PassengerAgent can be cast into MobsimAgent ... but this is how it was before. // kai, sep'12 - + MobsimAgent agent = (MobsimAgent) passenger ; agent.notifyArrivalOnLinkByNonNetworkMode(toLinkId); agent.endLegAndComputeNextState(time); diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/TransitEngineModule.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/TransitEngineModule.java index a6d75867864..9e3cf9f998e 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/TransitEngineModule.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/pt/TransitEngineModule.java @@ -21,13 +21,9 @@ package org.matsim.core.mobsim.qsim.pt; -import com.google.inject.Inject; -import com.google.inject.Provider; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.inject.multibindings.OptionalBinder; -import org.matsim.core.config.Config; -import org.matsim.core.gbl.Gbl; import org.matsim.core.mobsim.qsim.AbstractQSimModule; import org.matsim.core.mobsim.qsim.QSim; import org.matsim.pt.ReconstructingUmlaufBuilder; diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/AbstractQLink.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/AbstractQLink.java index f47d856ed5e..5e99245d126 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/AbstractQLink.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/AbstractQLink.java @@ -65,10 +65,10 @@ * */ abstract class AbstractQLink implements QLinkI { - // yy The way forward might be to separate the "service link/network" from the "movement link/network". The + // yy The way forward might be to separate the "service link/network" from the "movement link/network". The // service link would do things like park agents, accept additional agents on link, accept passengers or drivers waiting for // cars, etc. Both the thread-based parallelization and the visualization then would have to treat those service links - // separately, which feels fairly messy. Maybe better leave things as they are. kai, mar'16 + // separately, which feels fairly messy. Maybe better leave things as they are. kai, mar'16 public enum HandleTransitStopResult { continue_driving, rehandle, accepted @@ -109,7 +109,7 @@ public enum HandleTransitStopResult { private boolean active = false; private TransitQLink transitQLink; - + private final QNodeI toQNode ; private final NetsimEngineContext context; @@ -117,7 +117,7 @@ public enum HandleTransitStopResult { private final NetsimInternalInterface netsimEngine; private final LinkSpeedCalculator linkSpeedCalculator; private final VehicleHandler vehicleHandler; - + AbstractQLink(Link link, QNodeI toNode, NetsimEngineContext context, NetsimInternalInterface netsimEngine2, LinkSpeedCalculator linkSpeedCalculator, VehicleHandler vehicleHandler) { this.link = link ; this.toQNode = toNode ; @@ -132,7 +132,7 @@ public QNodeI getToNode() { return toQNode ; } - /** + /** * Links are active while (see checkForActivity()): () vehicles move on it; () vehicles wait to enter; () vehicles wait at the transit stop. * Once all of those have left the link, the link is no longer active. It then needs to be activated from the outside, which is done by * this method. @@ -147,7 +147,7 @@ private void activateLink() { // This is a bit involved since we do not want to ask the registry in every time step if the link is already active. } private static int wrnCnt = 0 ; - + public final void addParkedVehicle(MobsimVehicle vehicle, boolean isInitial) { QVehicle qveh = (QVehicle) vehicle; // cast ok: when it gets here, it needs to be a qvehicle to work. @@ -159,29 +159,29 @@ public final void addParkedVehicle(MobsimVehicle vehicle, boolean isInitial) { } } qveh.setCurrentLink(this.link); - + if (isInitial) { vehicleHandler.handleInitialVehicleArrival(qveh, link); } } - - @Override + + @Override public final void addParkedVehicle(MobsimVehicle vehicle) { addParkedVehicle(vehicle, true); } - + /* package */ final boolean letVehicleArrive(QVehicle qveh) { if (vehicleHandler.handleVehicleArrival(qveh, this.getLink())) { addParkedVehicle(qveh, false); - double now = context.getSimTimer().getTimeOfDay();; - context.getEventsManager().processEvent(new VehicleLeavesTrafficEvent(now , qveh.getDriver().getId(), + double now = context.getSimTimer().getTimeOfDay(); + context.getEventsManager().processEvent(new VehicleLeavesTrafficEvent(now , qveh.getDriver().getId(), this.link.getId(), qveh.getId(), qveh.getDriver().getMode(), 1.0 ) ) ; - + this.netsimEngine.letVehicleArrive(qveh); makeVehicleAvailableToNextDriver(qveh); return true; } - + return false; } @@ -238,7 +238,7 @@ public void clearVehicles() { context.getEventsManager().processEvent( new VehicleAbortsEvent(now, veh.getId(), veh.getCurrentLink().getId())); - + context.getEventsManager().processEvent( new PersonStuckEvent(now, veh.getDriver().getId(), veh.getCurrentLink().getId(), veh.getDriver().getMode())); context.getAgentCounter().incLost(); @@ -298,10 +298,10 @@ public void clearVehicles() { for (QVehicle veh : this.waitingList) { if (stuckAgents.contains(veh.getDriver().getId())) continue; else stuckAgents.add(veh.getDriver().getId()); - + this.context.getEventsManager().processEvent( new VehicleAbortsEvent(now, veh.getId(), veh.getCurrentLink().getId())); - + this.context.getEventsManager().processEvent( new PersonStuckEvent(now, veh.getDriver().getId(), veh.getCurrentLink().getId(), veh.getDriver().getMode())); this.context.getAgentCounter().incLost(); @@ -311,7 +311,7 @@ public void clearVehicles() { } void makeVehicleAvailableToNextDriver(QVehicle veh) { - + // this would (presumably) be the place where the "nature" of a vehicle could be changed (in the sense of PAVE), e.g. to // a freight vehicle, or to an autonomous vehicle that can be sent around the block or home. However, this would // necessitate some agent-like logic also for the vehicle: vehicle behavior given by driver as long as driver in @@ -365,7 +365,7 @@ void makeVehicleAvailableToNextDriver(QVehicle veh) { @Override public final void letVehicleDepart(QVehicle vehicle) { double now = context.getSimTimer().getTimeOfDay(); - + MobsimDriverAgent driver = vehicle.getDriver(); if (driver == null) throw new RuntimeException("Vehicle cannot depart without a driver!"); @@ -382,7 +382,7 @@ public final void letVehicleDepart(QVehicle vehicle) { @Override public final boolean insertPassengerIntoVehicle(MobsimAgent passenger, Id vehicleId) { double now = context.getSimTimer().getTimeOfDay(); - + QVehicle vehicle = this.getParkedVehicle(vehicleId); // if the vehicle is not parked at the link, mark the agent as passenger waiting for vehicle @@ -410,7 +410,7 @@ public final boolean insertPassengerIntoVehicle(MobsimAgent passenger, Id vehicleId) { // yyyy ?? does same as getParkedVehicle(...) ?? kai, mar'16 - + QVehicle ret = this.parkedVehicles.get(vehicleId); return ret; } @@ -502,81 +502,81 @@ TransitQLink getTransitQLink() { void setTransitQLink(TransitQLink transitQLink) { this.transitQLink = transitQLink; } - + /** * The idea here is to keep some control over what the implementations of QLaneI have access to. And maybe reduce * it over time, so that they become more encapsulated. kai, feb'18 */ public final class QLinkInternalInterface { - + public QNodeI getToNodeQ() { return AbstractQLink.this.toQNode ; } public Node getToNode() { return AbstractQLink.this.link.getToNode() ; } - + public double getFreespeed() { // yyyy does it make sense to provide the method without time? kai, feb'18 return AbstractQLink.this.link.getFreespeed() ; } - + public Id getId() { return AbstractQLink.this.link.getId() ; } - + public HandleTransitStopResult handleTransitStop(double now, QVehicle veh, TransitDriverAgent driver, Id linkId) { // yy now would not be needed as an argument. kai, feb'18 // yy linkId would not be needed as an argument. kai, feb'18 return AbstractQLink.this.transitQLink.handleTransitStop(now, veh, driver, linkId) ; } - + public void addParkedVehicle(QVehicle veh) { AbstractQLink.this.addParkedVehicle(veh); } - + public boolean letVehicleArrive(QVehicle veh) { return AbstractQLink.this.letVehicleArrive(veh); } - + public void makeVehicleAvailableToNextDriver(QVehicle veh) { AbstractQLink.this.makeVehicleAvailableToNextDriver(veh); } - + public void activateLink() { AbstractQLink.this.activateLink(); } - + public double getMaximumVelocityFromLinkSpeedCalculator(QVehicle veh, double now) { final LinkSpeedCalculator linkSpeedCalculator = AbstractQLink.this.linkSpeedCalculator; Gbl.assertNotNull(linkSpeedCalculator); return linkSpeedCalculator.getMaximumVelocity(veh, AbstractQLink.this.link, now) ; } - + public void setCurrentLinkToVehicle(QVehicle veh) { veh.setCurrentLink( AbstractQLink.this.link ); } - + public QLaneI getAcceptingQLane() { return AbstractQLink.this.getAcceptingQLane() ; } - + public List getOfferingQLanes() { return AbstractQLink.this.getOfferingQLanes() ; } - + public Node getFromNode() { return AbstractQLink.this.link.getFromNode() ; } - + public double getFreespeed(double now) { return AbstractQLink.this.link.getFreespeed(now) ; } - + public int getNumberOfLanesAsInt(double now) { return NetworkUtils.getNumberOfLanesAsInt(now,AbstractQLink.this.link) ; } - + public Link getLink() { return AbstractQLink.this.link; } diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/AbstractQNetsimEngine.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/AbstractQNetsimEngine.java index f52290c7472..296e0f26345 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/AbstractQNetsimEngine.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/AbstractQNetsimEngine.java @@ -32,7 +32,6 @@ import org.matsim.api.core.v01.events.PersonLeavesVehicleEvent; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Person; -import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.config.Config; import org.matsim.core.config.groups.QSimConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup.LinkDynamics; @@ -41,10 +40,8 @@ import org.matsim.core.gbl.Gbl; import org.matsim.core.mobsim.framework.MobsimAgent; import org.matsim.core.mobsim.framework.MobsimDriverAgent; -import org.matsim.core.mobsim.framework.MobsimTimer; import org.matsim.core.mobsim.qsim.InternalInterface; import org.matsim.core.mobsim.qsim.QSim; -import org.matsim.core.mobsim.qsim.interfaces.AgentCounter; import org.matsim.core.mobsim.qsim.interfaces.MobsimVehicle; import org.matsim.core.mobsim.qsim.interfaces.NetsimNetwork; import org.matsim.core.utils.misc.Time; @@ -91,7 +88,7 @@ abstract class AbstractQNetsimEngine impl private double infoTime = 0; private List engines; private InternalInterface internalInterface = null; - + AbstractQNetsimEngine(final QSim sim, QNetworkFactory netsimNetworkFactory) { this.qsim = sim; @@ -106,17 +103,17 @@ abstract class AbstractQNetsimEngine impl case wait: break; default: - throw new RuntimeException("Unknown vehicle behavior option."); + throw new RuntimeException("Unknown vehicle behavior option."); } dpHandler = new VehicularDepartureHandler(this, vehicleBehavior, qSimConfigGroup); - + if(qSimConfigGroup.getLinkDynamics().equals(LinkDynamics.SeepageQ)) { log.info("Seepage is allowed. Seep mode(s) is(are) " + qSimConfigGroup.getSeepModes() + "."); if(qSimConfigGroup.isSeepModeStorageFree()) { log.warn("Seep mode(s) " + qSimConfigGroup.getSeepModes() + " does not take storage space thus only considered for flow capacities."); } } - + if (netsimNetworkFactory != null){ qNetwork = new QNetwork( sim.getScenario().getNetwork(), netsimNetworkFactory ) ; } else { @@ -133,7 +130,7 @@ abstract class AbstractQNetsimEngine impl this.numOfThreads = sim.getScenario().getConfig().qsim().getNumberOfThreads(); } - + static AbstractAgentSnapshotInfoBuilder createAgentSnapshotInfoBuilder(Scenario scenario, SnapshotLinkWidthCalculator linkWidthCalculator) { final SnapshotStyle snapshotStyle = scenario.getConfig().qsim().getSnapshotStyle(); switch(snapshotStyle) { @@ -157,23 +154,23 @@ static AbstractAgentSnapshotInfoBuilder createAgentSnapshotInfoBuilder(Scenario @Override public final void onPrepareSim() { - this.infoTime = - Math.floor(internalInterface.getMobsim().getSimTimer().getSimStartTime() / INFO_PERIOD) * INFO_PERIOD; + this.infoTime = + Math.floor(internalInterface.getMobsim().getSimTimer().getSimStartTime() / INFO_PERIOD) * INFO_PERIOD; /* * infoTime may be < simStartTime, this ensures to print out the - * info at the very first timestep already + * info at the very first timestep already */ this.engines = initQSimEngineRunners(); assignNetElementActivators(); initMultiThreading(); } - - /** + + /** * do everything necessary to start the threads for {@link AbstractQNetsimEngineRunner} */ protected abstract void initMultiThreading(); - + @Override public final void afterSim() { @@ -198,26 +195,26 @@ public final void afterSim() { } } - /** + /** * do everything to finish multithreading {@link #afterSim()}, e.g. shut down a threadpool */ protected abstract void finishMultiThreading(); /** - * called during {@link #doSimStep(double)}. Should perform the - * simstep-logic in {@link AbstractQNetsimEngineRunner} provided by {@link #getQnetsimEngineRunner()} - * + * called during {@link #doSimStep(double)}. Should perform the + * simstep-logic in {@link AbstractQNetsimEngineRunner} provided by {@link #getQnetsimEngineRunner()} + * * @param time */ - protected abstract void run(double time); + protected abstract void run(double time); /** * create all necessary {@link AbstractQNetsimEngineRunner}. Will be called during {@link #onPrepareSim()}. - * + * * @return the list of {@link AbstractQNetsimEngineRunner} */ protected abstract List initQSimEngineRunners() ; - + /** * Implements one simulation step, called from simulation framework * @param time The current time in the simulation. @@ -225,11 +222,11 @@ public final void afterSim() { @Override public final void doSimStep(final double time) { run(time); - + this.printSimLog(time); } - + @Override public final void setInternalInterface( InternalInterface internalInterface) { this.internalInterface = internalInterface; @@ -288,7 +285,7 @@ public final Map, QVehicle> getVehicles() { } public final void registerAdditionalAgentOnLink(final MobsimAgent planAgent) { - Id linkId = planAgent.getCurrentLinkId(); + Id linkId = planAgent.getCurrentLinkId(); if (linkId != null) { // may be bushwacking QLinkI qLink = this.qNetwork.getNetsimLink(linkId ); if ( qLink==null ) { @@ -308,7 +305,7 @@ public final MobsimAgent unregisterAdditionalAgentOnLink(Id agentId, Id< public final void printEngineRunTimes() { if (!QSim.analyzeRunTimes) return; - + if (printRunTimesPerTimeStep) log.info("detailed QNetsimEngineRunner run times per time step:"); { StringBuffer sb = new StringBuffer(); @@ -412,7 +409,7 @@ private void assignNetElementActivators() { * step, the link should be activated. */ // this set is always empty... -// if (linksToActivateInitially.remove(qLink) +// if (linksToActivateInitially.remove(qLink) // || qsim.getScenario().getConfig().qsim().getSimStarttimeInterpretation()==StarttimeInterpretation.onlyUseStarttime) { // this.engines.get(i).registerLinkAsActive(qLink); // } @@ -435,7 +432,7 @@ private void assignNetElementActivators() { private final void arrangeNextAgentState(MobsimAgent pp) { internalInterface.arrangeNextAgentState(pp); } - + /** * @return the {@link AbstractQNetsimEngineRunner} created by {@link #initQSimEngineRunners()} */ diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/DefaultLinkSpeedCalculator.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/DefaultLinkSpeedCalculator.java index d25a6e3d806..09768849e7d 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/DefaultLinkSpeedCalculator.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/DefaultLinkSpeedCalculator.java @@ -26,8 +26,6 @@ import org.matsim.core.mobsim.qsim.AbstractQSimModule; import org.matsim.core.mobsim.qsim.qnetsimengine.QVehicle; import org.matsim.core.mobsim.qsim.qnetsimengine.linkspeedcalculator.LinkSpeedCalculator; -import org.matsim.core.mobsim.qsim.qnetsimengine.vehicle_handler.VehicleHandler; -import org.matsim.vehicles.Vehicle; import java.util.ArrayList; import java.util.Collection; @@ -35,7 +33,7 @@ /** * A simple link speed calculator taking the vehicle's max speed and the link's * free speed into account; - * + * * @author mrieser / Senozon AG */ public final class DefaultLinkSpeedCalculator implements LinkSpeedCalculator{ diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/DefaultTurnAcceptanceLogic.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/DefaultTurnAcceptanceLogic.java index 4b29de3e891..3a2cd5aa620 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/DefaultTurnAcceptanceLogic.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/DefaultTurnAcceptanceLogic.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.mobsim.qsim.qnetsimengine; import org.apache.logging.log4j.LogManager; @@ -31,15 +28,15 @@ /** * this class checks whether turning is physically possible, i.e. if the next link exists and if it is connected to the current link - * + * * @author kainagel * */ public final class DefaultTurnAcceptanceLogic implements TurnAcceptanceLogic { private static final Logger log = LogManager.getLogger( DefaultTurnAcceptanceLogic.class) ; - - @Override + /** We need qNetwork to get the next QLink, because the link lookup may lead to a NullPointer otherwise */ + @Override public AcceptTurn isAcceptingTurn(Link currentLink, QLaneI currentLane, Id nextLinkId, QVehicle veh, QNetwork qNetwork, double now){ if (nextLinkId == null) { log.error( "Agent has no or wrong route! agentId=" + veh.getDriver().getId() @@ -48,9 +45,9 @@ public AcceptTurn isAcceptingTurn(Link currentLink, QLaneI currentLane, Id return AcceptTurn.ABORT; } QLinkI nextQLink = qNetwork.getNetsimLinks().get(nextLinkId); - + if (nextQLink == null){ - log.warn("The link id " + nextLinkId + " is not available in the simulation network, but vehicle " + veh.getId() + + log.warn("The link id " + nextLinkId + " is not available in the simulation network, but vehicle " + veh.getId() + " plans to travel on that link from link " + veh.getCurrentLink().getId()); return AcceptTurn.ABORT ; } @@ -63,15 +60,15 @@ public AcceptTurn isAcceptingTurn(Link currentLink, QLaneI currentLane, Id // throw new RuntimeException( message ) ; //// log.warn(message ); //// return acceptTurn.ABORT ; -// // yyyy is rather nonsensical to get the mode from the driver, not from the vehicle. However, this seems to be +// // yyyy is rather nonsensical to get the mode from the driver, not from the vehicle. However, this seems to be // // how it currently works: network links are defined for modes, not for vehicle types. kai, may'16 // } - // currently does not work, see MATSIM-533 - - /* note: it cannot happen, that currentLane does not lead to nextLink (e.g. due to turn restrictions) because this is checked before: + // currently does not work, see MATSIM-533 + + /* note: it cannot happen, that currentLane does not lead to nextLink (e.g. due to turn restrictions) because this is checked before: * a vehicle only enters a lane when that lane leads to the next link. see QLinkLanesImpl.moveBufferToNextLane() and .chooseNextLane() * tthunig, oct'17 */ - + return AcceptTurn.GO ; } diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/NetsimEngine.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/NetsimEngine.java index ff3cea639b6..73fe544043c 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/NetsimEngine.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/NetsimEngine.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.mobsim.qsim.qnetsimengine; import org.matsim.api.core.v01.Id; diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/QNetworkFactory.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/QNetworkFactory.java index c89d210c956..2ac940aa59e 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/QNetworkFactory.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/QNetworkFactory.java @@ -25,7 +25,6 @@ import org.matsim.core.api.internal.MatsimFactory; import org.matsim.core.mobsim.framework.MobsimTimer; import org.matsim.core.mobsim.qsim.QSimModule; -import org.matsim.core.mobsim.qsim.components.QSimComponent; import org.matsim.core.mobsim.qsim.interfaces.AgentCounter; import org.matsim.core.mobsim.qsim.qnetsimengine.QNetsimEngineI.NetsimInternalInterface; diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/QNodeI.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/QNodeI.java index bf95d9cd560..ff24f7ab951 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/QNodeI.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/QNodeI.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.mobsim.qsim.qnetsimengine; import org.matsim.core.mobsim.qsim.interfaces.NetsimNode; diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/QueueAgentSnapshotInfoBuilder.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/QueueAgentSnapshotInfoBuilder.java index 74b817edd31..b36b175197e 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/QueueAgentSnapshotInfoBuilder.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/QueueAgentSnapshotInfoBuilder.java @@ -19,11 +19,9 @@ * *********************************************************************** */ package org.matsim.core.mobsim.qsim.qnetsimengine; -import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Scenario; -import org.matsim.vis.snapshotwriters.AgentSnapshotInfo; import org.matsim.vis.snapshotwriters.SnapshotLinkWidthCalculator; import org.matsim.vis.snapshotwriters.VisVehicle; diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/TurnAcceptanceLogic.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/TurnAcceptanceLogic.java index 36105c1f50d..3a1283aac97 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/TurnAcceptanceLogic.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/TurnAcceptanceLogic.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.mobsim.qsim.qnetsimengine; import org.matsim.api.core.v01.Id; @@ -32,7 +29,7 @@ * */ public interface TurnAcceptanceLogic { - + enum AcceptTurn { GO, WAIT, ABORT } AcceptTurn isAcceptingTurn(Link currentLink, QLaneI currentLane, Id nextLinkId, QVehicle veh, QNetwork qNetwork, double now); diff --git a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/VisUtils.java b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/VisUtils.java index b831768e3b3..f147ed922d7 100644 --- a/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/VisUtils.java +++ b/matsim/src/main/java/org/matsim/core/mobsim/qsim/qnetsimengine/VisUtils.java @@ -23,7 +23,6 @@ import org.matsim.api.core.v01.Identifiable; import org.matsim.api.core.v01.population.Person; -import org.matsim.core.mobsim.framework.PassengerAgent; /** * @author nagel diff --git a/matsim/src/main/java/org/matsim/core/network/NetworkUtils.java b/matsim/src/main/java/org/matsim/core/network/NetworkUtils.java index 493050fae3b..239f189da42 100644 --- a/matsim/src/main/java/org/matsim/core/network/NetworkUtils.java +++ b/matsim/src/main/java/org/matsim/core/network/NetworkUtils.java @@ -40,7 +40,6 @@ import org.matsim.core.gbl.Gbl; import org.matsim.core.network.algorithms.NetworkSimplifier; import org.matsim.core.network.io.MatsimNetworkReader; -import org.matsim.core.router.NetworkRoutingInclAccessEgressModule; import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.misc.OptionalTime; diff --git a/matsim/src/main/java/org/matsim/core/network/TimeDependentNetwork.java b/matsim/src/main/java/org/matsim/core/network/TimeDependentNetwork.java index b04dab32c5b..867a4428d58 100644 --- a/matsim/src/main/java/org/matsim/core/network/TimeDependentNetwork.java +++ b/matsim/src/main/java/org/matsim/core/network/TimeDependentNetwork.java @@ -18,7 +18,6 @@ * *********************************************************************** */ package org.matsim.core.network; -import java.util.Collection; import java.util.List; import java.util.Queue; diff --git a/matsim/src/main/java/org/matsim/core/network/ZZEverythingInPackageIsPackageOrFinal.java b/matsim/src/main/java/org/matsim/core/network/ZZEverythingInPackageIsPackageOrFinal.java index 8b69a46ccd1..fbb6f8abc55 100644 --- a/matsim/src/main/java/org/matsim/core/network/ZZEverythingInPackageIsPackageOrFinal.java +++ b/matsim/src/main/java/org/matsim/core/network/ZZEverythingInPackageIsPackageOrFinal.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.network; /** diff --git a/matsim/src/main/java/org/matsim/core/network/algorithms/NetworkMergeDoubleLinks.java b/matsim/src/main/java/org/matsim/core/network/algorithms/NetworkMergeDoubleLinks.java index caf7d6f89d6..6721473f993 100644 --- a/matsim/src/main/java/org/matsim/core/network/algorithms/NetworkMergeDoubleLinks.java +++ b/matsim/src/main/java/org/matsim/core/network/algorithms/NetworkMergeDoubleLinks.java @@ -27,7 +27,6 @@ import org.matsim.api.core.v01.network.Node; import org.matsim.core.api.internal.NetworkRunnable; import org.matsim.core.network.NetworkUtils; -import org.matsim.core.utils.misc.Time; import java.util.Iterator; @@ -40,7 +39,7 @@ public enum MergeType { ADDITIVE, /** max merge (max cap, max freespeed, max langes, max length */ MAXIMUM } - + public enum LogInfoLevel { /** do not print any info on merged links */ NOINFO, @@ -68,7 +67,7 @@ public NetworkMergeDoubleLinks() { public NetworkMergeDoubleLinks(final MergeType mergetype) { this(mergetype, LogInfoLevel.MAXIMUM); } - + public NetworkMergeDoubleLinks(final MergeType mergetype, final LogInfoLevel logInfoLevel) { this.mergetype = mergetype; this.logInfoLevel = logInfoLevel; @@ -84,7 +83,7 @@ private void mergeLink2IntoLink1(Link link1, Link link2, Network network) { if (logInfoLevel.equals(LogInfoLevel.MAXIMUM)) { log.info(" Link id=" + link2.getId() + " removed because of Link id=" + link1.getId()); } - + network.removeLink(link2.getId()); break; case ADDITIVE: diff --git a/matsim/src/main/java/org/matsim/core/network/algorithms/NetworkWriteAsTable.java b/matsim/src/main/java/org/matsim/core/network/algorithms/NetworkWriteAsTable.java index dcaa245a84b..8e9c8fb7596 100644 --- a/matsim/src/main/java/org/matsim/core/network/algorithms/NetworkWriteAsTable.java +++ b/matsim/src/main/java/org/matsim/core/network/algorithms/NetworkWriteAsTable.java @@ -33,7 +33,6 @@ import org.matsim.core.network.NetworkUtils; import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.core.utils.io.IOUtils; -import org.matsim.core.utils.misc.Time; public final class NetworkWriteAsTable implements NetworkRunnable { @@ -107,7 +106,7 @@ public void run(Network network) { offsetVector = CoordUtils.scalarMult(offset/CoordUtils.length(offsetVector),offsetVector); Coord fc = CoordUtils.plus(f.getCoord(),offsetVector); Coord tc = CoordUtils.plus(t.getCoord(),offsetVector); - + out_l.write(l.getId() + "\t" + fc.getX() + "\t" + fc.getY() + "\t"); out_l.write(tc.getX() + "\t" + tc.getY() + "\t" + l.getLength() + "\t"); out_l.write(l.getFreespeed()+"\t" diff --git a/matsim/src/main/java/org/matsim/core/network/algorithms/ZZEverythingInPackageIsPackageOrFinal.java b/matsim/src/main/java/org/matsim/core/network/algorithms/ZZEverythingInPackageIsPackageOrFinal.java index 0d13a1c8ed1..8972d110403 100644 --- a/matsim/src/main/java/org/matsim/core/network/algorithms/ZZEverythingInPackageIsPackageOrFinal.java +++ b/matsim/src/main/java/org/matsim/core/network/algorithms/ZZEverythingInPackageIsPackageOrFinal.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.network.algorithms; /** diff --git a/matsim/src/main/java/org/matsim/core/network/algorithms/intersectionSimplifier/DensityCluster.java b/matsim/src/main/java/org/matsim/core/network/algorithms/intersectionSimplifier/DensityCluster.java index 00d0881bf40..8cb61bc8a98 100644 --- a/matsim/src/main/java/org/matsim/core/network/algorithms/intersectionSimplifier/DensityCluster.java +++ b/matsim/src/main/java/org/matsim/core/network/algorithms/intersectionSimplifier/DensityCluster.java @@ -44,16 +44,16 @@ * This class implements the density-based clustering approach as published * by Zhou et al (2004). *
      - * ``The basic idea of DJ-DigicoreCluster is as follows. For each point, calculate its - * neighborhood: the neighborhood consists of points within distance + * ``The basic idea of DJ-DigicoreCluster is as follows. For each point, calculate its + * neighborhood: the neighborhood consists of points within distance * Eps, under condition that there are at least MinPts of them. If no * such neighborhood is found, the point is labeled noise; otherwise, the points are * created as a new DigicoreCluster if no neighbor is in an existing DigicoreCluster, or joined with * an existing DigicoreCluster if any neighbour is in an existing DigicoreCluster.'' *
    *

    Reference

    - * Zhou, C., Frankowski, D., Ludford, P.m Shekar, S. and Terveen, L. (2004). Discovering - * personal gazeteers: An interactive clustering approach. Proceedings of the 12th annual + * Zhou, C., Frankowski, D., Ludford, P.m Shekar, S. and Terveen, L. (2004). Discovering + * personal gazeteers: An interactive clustering approach. Proceedings of the 12th annual * ACM International workshop on Geographic Information Systems, p. 266-273. Washington, DC. *

    * @author jwjoubert @@ -68,17 +68,17 @@ public class DensityCluster { private final boolean silent; /** - * Creates a new instance of the density-based cluster with an empty list + * Creates a new instance of the density-based cluster with an empty list * of clusters. * @param radius the radius of the search circle within which other activity points * are searched. * @param minimumPoints the minimum number of points considered to constitute an * independent {@link Cluster}. - * @param pointsToCluster + * @param pointsToCluster */ public DensityCluster(List nodesToCluster, boolean silent){ this.inputPoints = nodesToCluster; - + /*TODO Remove later. */ int nullCounter = 0; for(Node node : inputPoints){ @@ -89,12 +89,12 @@ public DensityCluster(List nodesToCluster, boolean silent){ if(nullCounter > 0){ log.warn("In DJCluster: of the " + inputPoints.size() + " points, " + nullCounter + " were null."); } - + this.clusterList = new ArrayList(); this.silent = silent; } - + /** * Building an ArrayList of DigicoreClusters. The DJ-Clustering * procedure of Zhou et al (2004) is followed. If there are no points to cluster, a @@ -111,15 +111,15 @@ public void clusterInput(double radius, int minimumPoints){ int pointMultiplier = 1; int uPointCounter = 0; int cPointCounter = 0; - + /* - * Determine the extent of the QuadTree. + * Determine the extent of the QuadTree. */ double xMin = Double.POSITIVE_INFINITY; double yMin = Double.POSITIVE_INFINITY; double xMax = Double.NEGATIVE_INFINITY; double yMax = Double.NEGATIVE_INFINITY; - + for (Node node : this.inputPoints) { Coord c = node.getCoord(); /* TODO Remove if no NullPointerExceptions are thrown. */ @@ -129,13 +129,13 @@ public void clusterInput(double radius, int minimumPoints){ xMin = Math.min(xMin, c.getX()); yMin = Math.min(yMin, c.getY()); xMax = Math.max(xMax, c.getX()); - yMax = Math.max(yMax, c.getY()); + yMax = Math.max(yMax, c.getY()); } } /* * Build a new QuadTree, and place each point in the QuadTree as a ClusterActivity. * The geographic coordinates of each point is used as the keys in the QuadTree. - * Initially all ClusterPoints will have a NULL reference to its DigicoreCluster. An + * Initially all ClusterPoints will have a NULL reference to its DigicoreCluster. An * ArrayList of Points is also kept as iterator for unclustered points. */ if(!silent){ @@ -153,12 +153,12 @@ public void clusterInput(double radius, int minimumPoints){ if(!silent){ log.info("Done placing activities."); } - + int pointCounter = 0; while(pointCounter < listOfPoints.size()){ // Get next point. ClusterActivity p = listOfPoints.get(pointCounter); - + if(p.getCluster() == null){ // Compute the density-based neighbourhood, N(p), of the point p Collection neighbourhood = quadTree.getDisk(p.getCoord().getX(), p.getCoord().getY(), radius); @@ -176,18 +176,18 @@ public void clusterInput(double radius, int minimumPoints){ * FIXME Not quite true... it may be incorporated into * another cluster later! (JWJ - Mar '14) */ - + lostPoints.put(p.getId(), p); uPointCounter++; }else if(cN.size() > 0){ - /* + /* * Merge all the clusters. Use the DigicoreCluster with the smallest clusterId * value as the remaining DigicoreCluster. */ List localClusters = new ArrayList(); Cluster smallestCluster = cN.get(0).getCluster(); for(int i = 1; i < cN.size(); i++){ - if(Integer.parseInt(cN.get(i).getCluster().getId().toString()) < + if(Integer.parseInt(cN.get(i).getCluster().getId().toString()) < Integer.parseInt(smallestCluster.getId().toString()) ){ smallestCluster = cN.get(i).getCluster(); } @@ -204,15 +204,15 @@ public void clusterInput(double radius, int minimumPoints){ // Add the ClusterActivity to the new DigicoreCluster. smallestCluster.getPoints().add(thisClusterList.get(j)); // Remove the ClusterActivity from old DigicoreCluster. - /* + /* * 20091009 - I've commented this out... this seems - * both dangerous and unnecessary. + * both dangerous and unnecessary. */ // DigicoreCluster.getPoints().remove(thisClusterList.get(j)); } } } - + // Add unclustered points in the neighborhood. for (ClusterActivity cp : uN) { smallestCluster.getPoints().add(cp); @@ -227,7 +227,7 @@ public void clusterInput(double radius, int minimumPoints){ // Create new DigicoreCluster and add all the points. Cluster newCluster = new Cluster(Id.create(clusterIndex, Cluster.class)); clusterIndex++; - + for (ClusterActivity cp : uN) { cp.setCluster(newCluster); newCluster.getPoints().add(cp); @@ -236,7 +236,7 @@ public void clusterInput(double radius, int minimumPoints){ lostPoints.remove(cp.getId()); uPointCounter--; } - } + } } } pointCounter++; @@ -248,14 +248,14 @@ public void clusterInput(double radius, int minimumPoints){ } } } - - + + if(!silent){ - log.info(" Points clustered: " + pointCounter + " (Done)"); + log.info(" Points clustered: " + pointCounter + " (Done)"); int sum = cPointCounter + uPointCounter; - log.info("Sum should add up: " + cPointCounter + " (clustered) + " + log.info("Sum should add up: " + cPointCounter + " (clustered) + " + uPointCounter + " (unclustered) = " + sum); - + /* Code added for Joubert & Meintjes paper (2014). */ log.info("Unclustered points: "); for(ClusterActivity ca : lostPoints.values()){ @@ -264,8 +264,8 @@ public void clusterInput(double radius, int minimumPoints){ log.info("New way of unclustered points:"); log.info(" Number: " + lostPoints.size()); } - - /* + + /* * Build the DigicoreCluster list. Once built, I rename the clusterId field so as to * start at '0', and increment accordingly. This allows me to directly use * the clusterId field as 'row' and 'column' reference in the 2D matrices @@ -275,7 +275,7 @@ public void clusterInput(double radius, int minimumPoints){ log.info("Building the DigicoreCluster list (2 steps)"); } Map> clusterMap = new HashMap>(); - + if(!silent){ log.info("Step 1 of 2:"); log.info("Number of ClusterPoints to process: " + listOfPoints.size()); @@ -287,14 +287,14 @@ public void clusterInput(double radius, int minimumPoints){ if(theCluster != null){ // Removed 7/12/2011 (JWJ): Seems unnecessary computation. // theCluster.setCenterOfGravity(); - + if(!clusterMap.containsKey(theCluster)){ List newList = new ArrayList(); clusterMap.put(theCluster, newList); } clusterMap.get(theCluster).add(ca); } - + if(!silent){ if(++cpCounter == cpMultiplier){ log.info(" ClusterPoints processed: " + cpCounter + " (" + String.format("%3.2f", ((double)cpCounter/(double)listOfPoints.size())*100) + "%)"); @@ -305,7 +305,7 @@ public void clusterInput(double radius, int minimumPoints){ if(!silent){ log.info(" ClusterPoints processed: " + cpCounter + " (Done)"); } - + if(!silent){ log.info("Step 2 of 2:"); log.info("Number of clusters to process: " + clusterMap.keySet().size()); @@ -324,7 +324,7 @@ public void clusterInput(double radius, int minimumPoints){ } else if(!silent){ log.warn(" ... why do we HAVE a cluster with too few points?..."); } - + if(!silent){ if(++clusterCounter == clusterMultiplier){ log.info(" Clusters processed: " + clusterCounter + " (" + String.format("%3.2f", ((double)clusterCounter / (double)clusterMap.keySet().size())*100) + "%)"); @@ -337,11 +337,11 @@ public void clusterInput(double radius, int minimumPoints){ log.info("DigicoreCluster list built."); } } - - // lost list must be made up of clusters without Id. + + // lost list must be made up of clusters without Id. } - - + + /** * For each DigicoreCluster, this method writes out the DigicoreCluster id, the DigicoreCluster's center of * gravity (as a longitude and latitude value), and the order of the DigicoreCluster, i.e. @@ -355,24 +355,22 @@ public void clusterInput(double radius, int minimumPoints){ * 1,28.0114,31.3421,5
    * ... * - * + * * @param filename the absolute file path to where the DigicoreCluster information is written. */ public void writeClustersToFile(String filename){ - + int clusterCount = 0; int clusterMultiplier = 1; int totalClusters = clusterList.size(); if(!silent){ log.info("Writing a total of " + totalClusters + " to file."); } - - try { - BufferedWriter output = IOUtils.getBufferedWriter(filename); - try{ + + try (BufferedWriter output = IOUtils.getBufferedWriter(filename)) { output.write("ClusterId,Long,Lat,NumberOfActivities"); output.write("\n"); - + for (Cluster c : clusterList) { c.setCenterOfGravity(); Coord center = c.getCenterOfGravity(); @@ -384,7 +382,7 @@ public void writeClustersToFile(String filename){ output.write(delimiter); output.write(String.valueOf(c.getPoints().size())); output.write("\n"); - + clusterCount++; // Report progress if(!silent){ @@ -397,28 +395,25 @@ public void writeClustersToFile(String filename){ if(!silent){ log.info(" Clusters written: " + clusterCount + " (Done)" ); } - } finally{ - output.close(); - } } catch (IOException e) { - e.printStackTrace(); + log.error("Could not write cluster to file.", e); } } public List getClusterList() { return clusterList; } - - + + public QuadTree getClusteredPoints() { return quadTree; } - - + + public void setDelimiter(String delimiter) { this.delimiter = delimiter; } - + public Map,ClusterActivity> getLostPoints(){ return this.lostPoints; } diff --git a/matsim/src/main/java/org/matsim/core/network/algorithms/intersectionSimplifier/IntersectionSimplifier.java b/matsim/src/main/java/org/matsim/core/network/algorithms/intersectionSimplifier/IntersectionSimplifier.java index 9c81d5d0005..14e459f86da 100644 --- a/matsim/src/main/java/org/matsim/core/network/algorithms/intersectionSimplifier/IntersectionSimplifier.java +++ b/matsim/src/main/java/org/matsim/core/network/algorithms/intersectionSimplifier/IntersectionSimplifier.java @@ -18,9 +18,6 @@ * * * *********************************************************************** */ -/** - * - */ package org.matsim.core.network.algorithms.intersectionSimplifier; import java.util.ArrayList; @@ -39,7 +36,6 @@ import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.network.Node; -import org.matsim.core.config.groups.NetworkConfigGroup; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.algorithms.intersectionSimplifier.containers.Cluster; import org.matsim.core.network.algorithms.intersectionSimplifier.containers.ClusterActivity; @@ -47,7 +43,7 @@ /** * Class to simplify a given network's intersections. - * + * * @author jwjoubert */ public class IntersectionSimplifier { @@ -77,7 +73,7 @@ public Network simplify(Network network) { /* Get all the network's node coordinates that must be clustered. */ List nodes = new ArrayList<>(); for(Node node : network.getNodes().values()) { - /* Create new Node instances in order to assure that the original network can not be + /* Create new Node instances in order to assure that the original network can not be * changed by accident */ nodes.add(NetworkUtils.createNode(node.getId(), node.getCoord())); } @@ -91,16 +87,16 @@ public Network simplify(Network network) { /* Do the mapping of clustered points. */ List clusters = djc.getClusterList(); - /* Populate a QuadTree with all the clustered nodes, each with a + /* Populate a QuadTree with all the clustered nodes, each with a * reference to the cluster they belong to. */ LOG.info("Populating QuadTree with clustered points."); this.clusteredNodes = new QuadTree<>( - djc.getClusteredPoints().getMinEasting(), - djc.getClusteredPoints().getMinNorthing(), - djc.getClusteredPoints().getMaxEasting(), + djc.getClusteredPoints().getMinEasting(), + djc.getClusteredPoints().getMinNorthing(), + djc.getClusteredPoints().getMaxEasting(), djc.getClusteredPoints().getMaxNorthing()); for(Cluster cluster : clusters) { - /* Add up node ids of all nodes merged into this clustered node + /* Add up node ids of all nodes merged into this clustered node * and use it as id for the clustered node */ SortedSet nodeIdsInCluster = new TreeSet<>(); for (ClusterActivity nodeInCluster : cluster.getPoints()) { @@ -115,7 +111,7 @@ public Network simplify(Network network) { clusteredNodeName.append(nodeInCluster); } Id newId = Id.createNodeId(clusteredNodeName.toString()); - + Node newNode = network.getFactory().createNode(newId, cluster.getCenterOfGravity()); Set> includedNodes = new HashSet<>(); for(ClusterActivity clusterPoint : cluster.getPoints()) { @@ -129,7 +125,7 @@ public Network simplify(Network network) { /* Go through each network link, in given network, and evaluate it's nodes. */ for(Link link : network.getLinks().values()) { - + Node fromNode = NetworkUtils.createNode(link.getFromNode().getId(), link.getFromNode().getCoord()); Node fromCentroid = getClusteredNode(fromNode); @@ -138,22 +134,22 @@ public Network simplify(Network network) { Node newFromNode = fromCentroid != null ? fromCentroid : fromNode; Node newToNode = toCentroid != null ? toCentroid : toNode; - - /* FIXME currently the new link carries no additional information + + /* FIXME currently the new link carries no additional information * from the original network. */ Link newLink = NetworkUtils.createLink( - link.getId(), newFromNode, newToNode, newNetwork, + link.getId(), newFromNode, newToNode, newNetwork, link.getLength(), link.getFreespeed(), link.getCapacity(), link.getNumberOfLanes()); newLink.setAllowedModes(link.getAllowedModes()); - + if(newLink.getFromNode().getCoord().equals(newLink.getToNode().getCoord())) { /* If both link nodes are part of the same cluster, their node - * Coords will now be the same. The link can be completely ignored, + * Coords will now be the same. The link can be completely ignored, * so we do not need to process it here any further. */ } else { if(!newNetwork.getNodes().containsKey(newLink.getFromNode().getId())) { - /* FIXME currently the new node carries no additional + /* FIXME currently the new node carries no additional * information from the original network. */ NetworkUtils.createAndAddNode(newNetwork, newLink.getFromNode().getId(), newLink.getFromNode().getCoord()); } @@ -179,7 +175,7 @@ public Network simplify(Network network) { reportNetworkStatistics(newNetwork); return newNetwork; } - + /** * Look up the {@link Cluster} node of the provided {@link Node}. @@ -191,10 +187,10 @@ protected Node getClusteredNode(Node node) { Node n = mergedNodeId2clusterNode.get(node.getId()); return n; } - - + + /** - * Checking that clustering has been done, and then writes the clusters to + * Checking that clustering has been done, and then writes the clusters to * file using {@link DensityCluster#writeClustersToFile(String)}. * @param file */ @@ -209,7 +205,7 @@ public void writeClustersToFile(String file) { /** * Returns all the {@link Cluster}s. - * + * * @return */ public List getClusters() { @@ -221,7 +217,7 @@ public List getClusters() { } /** - * Provides basic statistics of a given {@link Network}. + * Provides basic statistics of a given {@link Network}. * @param network */ public static void reportNetworkStatistics(Network network) { diff --git a/matsim/src/main/java/org/matsim/core/network/algorithms/intersectionSimplifier/RunIntersectionSimplifier.java b/matsim/src/main/java/org/matsim/core/network/algorithms/intersectionSimplifier/RunIntersectionSimplifier.java index 58356243834..0a92819719f 100644 --- a/matsim/src/main/java/org/matsim/core/network/algorithms/intersectionSimplifier/RunIntersectionSimplifier.java +++ b/matsim/src/main/java/org/matsim/core/network/algorithms/intersectionSimplifier/RunIntersectionSimplifier.java @@ -18,9 +18,6 @@ * * * *********************************************************************** */ -/** - * - */ package org.matsim.core.network.algorithms.intersectionSimplifier; import org.apache.logging.log4j.LogManager; @@ -36,7 +33,7 @@ /** * Example to illustrate how the density-based algorithm is used to simplify a * network's intersections. - * + * * @author jwjoubert */ public class RunIntersectionSimplifier { @@ -48,24 +45,24 @@ public class RunIntersectionSimplifier { public static void main(String[] args) { run(args); } - + public static void run(String[] args) { String input = args[0]; String output = args[1]; - + Network network = NetworkUtils.createNetwork(); new MatsimNetworkReader(network).readFile(input); - + IntersectionSimplifier ns = new IntersectionSimplifier(30.0, 2); Network newNetwork = ns.simplify(network); NetworkCalcTopoType nct = new NetworkCalcTopoType(); nct.run(newNetwork); - + LOG.info("Simplifying the network..."); new NetworkSimplifier().run(newNetwork); LOG.info("Cleaning the network..."); new NetworkCleaner().run(newNetwork); - + IntersectionSimplifier.reportNetworkStatistics(newNetwork); new NetworkWriter(newNetwork).write(output); } diff --git a/matsim/src/main/java/org/matsim/core/network/filter/ZZEverythingInPackageIsPackageOrFinal.java b/matsim/src/main/java/org/matsim/core/network/filter/ZZEverythingInPackageIsPackageOrFinal.java index f8ca19aea46..bd8a2fdca89 100644 --- a/matsim/src/main/java/org/matsim/core/network/filter/ZZEverythingInPackageIsPackageOrFinal.java +++ b/matsim/src/main/java/org/matsim/core/network/filter/ZZEverythingInPackageIsPackageOrFinal.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.network.filter; /** diff --git a/matsim/src/main/java/org/matsim/core/network/io/ZZEverythingInPackageIsPackageOrFinal.java b/matsim/src/main/java/org/matsim/core/network/io/ZZEverythingInPackageIsPackageOrFinal.java index 2d4f9b174ea..2629d1a9d98 100644 --- a/matsim/src/main/java/org/matsim/core/network/io/ZZEverythingInPackageIsPackageOrFinal.java +++ b/matsim/src/main/java/org/matsim/core/network/io/ZZEverythingInPackageIsPackageOrFinal.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.network.io; /** diff --git a/matsim/src/main/java/org/matsim/core/population/PersonImpl.java b/matsim/src/main/java/org/matsim/core/population/PersonImpl.java index 01ee4263987..161ec544337 100644 --- a/matsim/src/main/java/org/matsim/core/population/PersonImpl.java +++ b/matsim/src/main/java/org/matsim/core/population/PersonImpl.java @@ -25,7 +25,6 @@ import java.util.Map; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Customizable; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.population.Person; @@ -96,7 +95,7 @@ public Id getId() { /* deliberately package */ void changeId(final Id newId) { // This is deliberately non-public and not on the interface, since the ID should not be changed after the - // person is inserted into the population map (since the ID is the map key). + // person is inserted into the population map (since the ID is the map key). // However, there are some situations where changing the ID makes sense while the person is outside // the population ... kai, jun'16 try { diff --git a/matsim/src/main/java/org/matsim/core/population/PersonUtils.java b/matsim/src/main/java/org/matsim/core/population/PersonUtils.java index 34a52e56bf3..9c64e247d87 100644 --- a/matsim/src/main/java/org/matsim/core/population/PersonUtils.java +++ b/matsim/src/main/java/org/matsim/core/population/PersonUtils.java @@ -91,7 +91,6 @@ public static Double getIncome(Person person) { return (Double) person.getAttributes().getAttribute(PERSONAL_INCOME_ATTRIBUTE_NAME); } - @SuppressWarnings("unchecked") /** * convenience method for often used demographic attribute * There is apparently no way to register a Map(String, Double) at ObjectAttributesConverter since all Maps default @@ -99,6 +98,7 @@ public static Double getIncome(Person person) { * scoring mode constants uses a Map(String, String). If this attribute is read often an alternative similar to * PersonVehicles can be considered. */ + @SuppressWarnings("unchecked") public static Map getModeConstants(Person person) { try { diff --git a/matsim/src/main/java/org/matsim/core/population/PlanImpl.java b/matsim/src/main/java/org/matsim/core/population/PlanImpl.java index 8477a25b7dc..8f2dc6b882a 100644 --- a/matsim/src/main/java/org/matsim/core/population/PlanImpl.java +++ b/matsim/src/main/java/org/matsim/core/population/PlanImpl.java @@ -28,7 +28,6 @@ import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Customizable; import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; @@ -42,7 +41,7 @@ /* deliberately package */ final class PlanImpl implements Plan { private Id id= null; - + private ArrayList actsLegs = new ArrayList<>(); private Double score = null; @@ -54,9 +53,9 @@ private final static Logger log = LogManager.getLogger(Plan.class); private Customizable customizableDelegate; - + private final Attributes attributes = new AttributesImpl(); - + @Override public final Attributes getAttributes() { return this.attributes; @@ -73,7 +72,7 @@ public final Attributes getAttributes() { // return a; // } - + ////////////////////////////////////////////////////////////////////// // create methods @@ -126,7 +125,7 @@ public String getType() { public void setType(final String type) { this.type = type; } - + @Override public Id getId() { if(this.id!=null) @@ -136,7 +135,7 @@ public Id getId() { return Id.create(this.getAttributes().getAttribute(PlanInheritanceModule.PLAN_ID).toString(),Plan.class); else return null; } - + } @Override @@ -144,7 +143,7 @@ public void setPlanId(Id planId) { this.getAttributes().putAttribute(PlanInheritanceModule.PLAN_ID, planId.toString()); this.id = planId; } - + @Override public int getIterationCreated() { return (int) this.getAttributes().getAttribute(PlanInheritanceModule.ITERATION_CREATED); @@ -212,7 +211,7 @@ public final Map getCustomAttributes() { // public final void setLocked() { // for ( PlanElement pe : this.actsLegs ) { // if ( pe instanceof ActivityImpl ) { -// ((ActivityImpl) pe).setLocked(); +// ((ActivityImpl) pe).setLocked(); // } else if ( pe instanceof LegImpl ) { // ((LegImpl) pe).setLocked() ; // } diff --git a/matsim/src/main/java/org/matsim/core/population/PopulationUtils.java b/matsim/src/main/java/org/matsim/core/population/PopulationUtils.java index b6f997cab25..574f2f76e93 100644 --- a/matsim/src/main/java/org/matsim/core/population/PopulationUtils.java +++ b/matsim/src/main/java/org/matsim/core/population/PopulationUtils.java @@ -381,7 +381,7 @@ public String getType() { public void setType(String type) { throw new UnsupportedOperationException(); } - + @Override public Id getId() { return this.delegate.getId(); @@ -391,7 +391,7 @@ public Id getId() { public void setPlanId(Id planId) { throw new UnsupportedOperationException(); } - + @Override public int getIterationCreated() { return this.delegate.getIterationCreated(); @@ -679,7 +679,6 @@ public static boolean equalPopulation(final Population s1, final Population s2) * * Otherwise, the Thread which is opened here may stay alive. */ - @SuppressWarnings("resource") private static InputStream openPopulationInputStream(final Population s1) { try { final PipedInputStream in = new PipedInputStream(); @@ -817,7 +816,7 @@ public static Activity createInteractionActivityFromCoordAndLinkId(String type, act.setLinkId(linkId); return act ; } - + public static Activity convertInteractionToStandardActivity(Activity activity) { if (activity instanceof InteractionActivity) { return createActivity(activity); diff --git a/matsim/src/main/java/org/matsim/core/population/ZZEverythingInPackageIsPackageOrFinal.java b/matsim/src/main/java/org/matsim/core/population/ZZEverythingInPackageIsPackageOrFinal.java index 8e516a3af20..3f4e8ca8e3b 100644 --- a/matsim/src/main/java/org/matsim/core/population/ZZEverythingInPackageIsPackageOrFinal.java +++ b/matsim/src/main/java/org/matsim/core/population/ZZEverythingInPackageIsPackageOrFinal.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.population; /** diff --git a/matsim/src/main/java/org/matsim/core/population/algorithms/ZZEverythingInPackageIsPackageFinalOrEmpty.java b/matsim/src/main/java/org/matsim/core/population/algorithms/ZZEverythingInPackageIsPackageFinalOrEmpty.java index cda266c018a..7b932b971b9 100644 --- a/matsim/src/main/java/org/matsim/core/population/algorithms/ZZEverythingInPackageIsPackageFinalOrEmpty.java +++ b/matsim/src/main/java/org/matsim/core/population/algorithms/ZZEverythingInPackageIsPackageFinalOrEmpty.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.population.algorithms; /** diff --git a/matsim/src/main/java/org/matsim/core/population/io/ParallelPopulationReaderMatsimV4.java b/matsim/src/main/java/org/matsim/core/population/io/ParallelPopulationReaderMatsimV4.java index 1ffbe805141..f0a6c117124 100644 --- a/matsim/src/main/java/org/matsim/core/population/io/ParallelPopulationReaderMatsimV4.java +++ b/matsim/src/main/java/org/matsim/core/population/io/ParallelPopulationReaderMatsimV4.java @@ -330,21 +330,21 @@ public abstract static class Tag { Stack context = null; // not used by the PopulationReader } - public final class StartTag extends Tag { + public static final class StartTag extends Tag { Attributes atts; } - public final class PersonTag extends Tag { + public static final class PersonTag extends Tag { Person person; } - public final class EndTag extends Tag { + public static final class EndTag extends Tag { String content; } /* * Marker Tag to inform the threads that no further data has to be parsed. */ - public final class EndProcessingTag extends Tag { + public static final class EndProcessingTag extends Tag { } } diff --git a/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandler.java b/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandler.java index d2d44ddc5bd..21bb0d3f7db 100644 --- a/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandler.java +++ b/matsim/src/main/java/org/matsim/core/population/io/PopulationWriterHandler.java @@ -25,7 +25,6 @@ import java.util.Map; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Population; import org.matsim.utils.objectattributes.AttributeConverter; @@ -42,7 +41,7 @@ public interface PopulationWriterHandler { void writePerson(final Person person, final BufferedWriter out) throws IOException; void endPlans(final BufferedWriter out) throws IOException; - + void writeSeparator(final BufferedWriter out) throws IOException; default void putAttributeConverters(Map, AttributeConverter> converters) { diff --git a/matsim/src/main/java/org/matsim/core/population/io/ZZEverythingInPackageIsPackageFinalOrEmpty.java b/matsim/src/main/java/org/matsim/core/population/io/ZZEverythingInPackageIsPackageFinalOrEmpty.java index 9b8ba3170f1..98f69b00bf3 100644 --- a/matsim/src/main/java/org/matsim/core/population/io/ZZEverythingInPackageIsPackageFinalOrEmpty.java +++ b/matsim/src/main/java/org/matsim/core/population/io/ZZEverythingInPackageIsPackageFinalOrEmpty.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.population.io; /** diff --git a/matsim/src/main/java/org/matsim/core/population/routes/RouteFactories.java b/matsim/src/main/java/org/matsim/core/population/routes/RouteFactories.java index c6c738d4b45..af019d61e77 100644 --- a/matsim/src/main/java/org/matsim/core/population/routes/RouteFactories.java +++ b/matsim/src/main/java/org/matsim/core/population/routes/RouteFactories.java @@ -25,7 +25,6 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Route; -import org.matsim.pt.routes.TransitPassengerRoute; import org.matsim.pt.routes.DefaultTransitPassengerRoute; import org.matsim.pt.routes.DefaultTransitPassengerRouteFactory; import org.matsim.pt.routes.ExperimentalTransitRoute; @@ -44,7 +43,7 @@ public RouteFactories() { this.setRouteFactory(ExperimentalTransitRoute.class, new ExperimentalTransitRouteFactory()); this.setRouteFactory(DefaultTransitPassengerRoute.class, new DefaultTransitPassengerRouteFactory()); } - + /** * @param routeClass the requested class of the route * @param startLinkId the link where the route starts diff --git a/matsim/src/main/java/org/matsim/core/population/routes/ZZEverythingInPackageIsPackageFinalOrEmpty.java b/matsim/src/main/java/org/matsim/core/population/routes/ZZEverythingInPackageIsPackageFinalOrEmpty.java index b2d752b84f0..edfa55df654 100644 --- a/matsim/src/main/java/org/matsim/core/population/routes/ZZEverythingInPackageIsPackageFinalOrEmpty.java +++ b/matsim/src/main/java/org/matsim/core/population/routes/ZZEverythingInPackageIsPackageFinalOrEmpty.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.population.routes; /** diff --git a/matsim/src/main/java/org/matsim/core/replanning/choosers/ForceInnovationStrategyChooser.java b/matsim/src/main/java/org/matsim/core/replanning/choosers/ForceInnovationStrategyChooser.java index 54d251a2004..193e36eda43 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/choosers/ForceInnovationStrategyChooser.java +++ b/matsim/src/main/java/org/matsim/core/replanning/choosers/ForceInnovationStrategyChooser.java @@ -80,7 +80,7 @@ public GenericPlanStrategy chooseStrategy(HasPlansAndId person, public enum Permute { yes, - no; + no } } diff --git a/matsim/src/main/java/org/matsim/core/replanning/inheritance/PlanInheritanceRecordReader.java b/matsim/src/main/java/org/matsim/core/replanning/inheritance/PlanInheritanceRecordReader.java index 8d83d6ef1de..5ab526fa020 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/inheritance/PlanInheritanceRecordReader.java +++ b/matsim/src/main/java/org/matsim/core/replanning/inheritance/PlanInheritanceRecordReader.java @@ -22,12 +22,10 @@ * * * *********************************************************************** */ -import java.io.BufferedWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -38,20 +36,20 @@ /** * Writes {@linkplain PlanInheritanceRecord} to file in a fixed column sequence. - * + * * @author alex94263 */ public class PlanInheritanceRecordReader { - - + + private final String DELIMITER = "\t"; private final BufferedReader reader; - + public PlanInheritanceRecordReader(String filename) { this.reader = IOUtils.getBufferedReader(filename); - - + + } public Map buildIdx(String[] header) { Map lookup = new HashMap(); @@ -76,21 +74,21 @@ public List read() { planInheritanceRecord.setIterationCreated(Integer.parseInt(line[lookUp.get(PlanInheritanceRecordWriter.ITERATION_CREATED)])); planInheritanceRecord.setIterationRemoved(Integer.parseInt(line[lookUp.get(PlanInheritanceRecordWriter.ITERATION_REMOVED)])); String iterationsSelected = line[lookUp.get(PlanInheritanceRecordWriter.ITERATIONS_SELECTED)]; - planInheritanceRecord.setIterationsSelected(Arrays.asList(iterationsSelected.substring(1, iterationsSelected.length()-1).split(", ")).stream() - .map(Integer::parseInt) + planInheritanceRecord.setIterationsSelected(Arrays.asList(iterationsSelected.substring(1, iterationsSelected.length()-1).split(", ")).stream() + .map(Integer::parseInt) .collect(Collectors.toList())); records.add(planInheritanceRecord); lineString = reader.readLine(); } return records; - + } catch (IOException e) { throw new RuntimeException("Could not read the plan inheritance records!", e); } - - - + + + } - + } diff --git a/matsim/src/main/java/org/matsim/core/replanning/modules/ChangeSingleLegMode.java b/matsim/src/main/java/org/matsim/core/replanning/modules/ChangeSingleLegMode.java index f1aa84ca1d5..64d161b14b6 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/modules/ChangeSingleLegMode.java +++ b/matsim/src/main/java/org/matsim/core/replanning/modules/ChangeSingleLegMode.java @@ -20,7 +20,6 @@ package org.matsim.core.replanning.modules; -import org.matsim.api.core.v01.TransportMode; import org.matsim.core.config.groups.ChangeModeConfigGroup; import org.matsim.core.config.groups.GlobalConfigGroup; import org.matsim.core.gbl.MatsimRandom; @@ -61,7 +60,7 @@ public ChangeSingleLegMode(final GlobalConfigGroup globalConfigGroup, ChangeMode this.allowSwitchFromListedModesOnly = true; } else this.allowSwitchFromListedModesOnly=false; } - + public ChangeSingleLegMode(final int nOfThreads, final String[] modes, final boolean ignoreCarAvailabilty) { super(nOfThreads); this.availableModes = modes.clone(); diff --git a/matsim/src/main/java/org/matsim/core/replanning/modules/ModeAndRouteConsistencyChecker.java b/matsim/src/main/java/org/matsim/core/replanning/modules/ModeAndRouteConsistencyChecker.java index 5459d30df9a..6d0d66cdf3f 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/modules/ModeAndRouteConsistencyChecker.java +++ b/matsim/src/main/java/org/matsim/core/replanning/modules/ModeAndRouteConsistencyChecker.java @@ -22,7 +22,6 @@ package org.matsim.core.replanning.modules; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Plan; @@ -33,7 +32,7 @@ public class ModeAndRouteConsistencyChecker implements PlanStrategyModule { @Override public void prepareReplanning(ReplanningContext replanningContext) { } - + @Override public void handlePlan(Plan plan) { for (Leg leg : TripStructureUtils.getLegs(plan)) { if (leg.getRoute() instanceof NetworkRoute) { @@ -50,6 +49,6 @@ public class ModeAndRouteConsistencyChecker implements PlanStrategyModule { } } } - + @Override public void finishReplanning() { } } diff --git a/matsim/src/main/java/org/matsim/core/replanning/selectors/ExpBetaPlanChanger.java b/matsim/src/main/java/org/matsim/core/replanning/selectors/ExpBetaPlanChanger.java index ad065206902..0cb91df7d16 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/selectors/ExpBetaPlanChanger.java +++ b/matsim/src/main/java/org/matsim/core/replanning/selectors/ExpBetaPlanChanger.java @@ -86,7 +86,7 @@ public T selectPlan(final HasPlansAndId person) { } return currentPlan; } - + // defending against NaN (which should not happen, but happens): if ( currentPlan.getScore().isNaN() ) { return otherPlan ; @@ -94,13 +94,13 @@ public T selectPlan(final HasPlansAndId person) { if ( otherPlan.getScore().isNaN() ) { return currentPlan ; } - + double currentScore = currentPlan.getScore(); double otherScore = otherPlan.getScore(); if ( betaWrnFlag ) { log.warn("Would make sense to revise this once more. See comments in code. kai, nov08") ; - /*** Gunnar says, rightly I think, that what is below hits the "0.01*weight > 1" threshold fairly quickly. + /* Gunnar says, rightly I think, that what is below hits the "0.01*weight > 1" threshold fairly quickly. * An alternative might be to divide by exp(0.5*beta*oS)+exp(0.5*beta*cS), or the max of these two numbers. But: * (1) someone would need to go through the theory to make sure that we remain within what we have said before * (convergence to logit and proba of jump between equal options = 0.01 diff --git a/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutator.java b/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutator.java index c1fbe50e538..15d12a2f679 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutator.java +++ b/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutator.java @@ -22,7 +22,6 @@ import jakarta.inject.Inject; import jakarta.inject.Provider; -import org.matsim.api.core.v01.population.Population; import org.matsim.core.config.groups.GlobalConfigGroup; import org.matsim.core.config.groups.PlansConfigGroup; import org.matsim.core.config.groups.TimeAllocationMutatorConfigGroup; diff --git a/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutatorReRoute.java b/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutatorReRoute.java index f430d0d3004..9b3b917f5dd 100644 --- a/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutatorReRoute.java +++ b/matsim/src/main/java/org/matsim/core/replanning/strategies/TimeAllocationMutatorReRoute.java @@ -19,7 +19,6 @@ * *********************************************************************** */ package org.matsim.core.replanning.strategies; -import org.matsim.api.core.v01.population.Population; import org.matsim.core.config.groups.GlobalConfigGroup; import org.matsim.core.config.groups.PlansConfigGroup; import org.matsim.core.config.groups.TimeAllocationMutatorConfigGroup; diff --git a/matsim/src/main/java/org/matsim/core/router/NetworkRoutingInclAccessEgressModule.java b/matsim/src/main/java/org/matsim/core/router/NetworkRoutingInclAccessEgressModule.java index 748b8c2e1d5..49da68730c1 100644 --- a/matsim/src/main/java/org/matsim/core/router/NetworkRoutingInclAccessEgressModule.java +++ b/matsim/src/main/java/org/matsim/core/router/NetworkRoutingInclAccessEgressModule.java @@ -329,7 +329,7 @@ private static void routeBushwhackingLeg(Person person, Leg leg, Coord fromCoord } else if ((tmp = paramsMap.get(TransportMode.walk)) != null) { params = tmp; } else { - log.fatal( "Teleportation (= mode routing) params neither defined for " + TransportMode.walk + " nor for " + TransportMode.non_network_walk + ". There are two cases:" ); ; + log.fatal( "Teleportation (= mode routing) params neither defined for " + TransportMode.walk + " nor for " + TransportMode.non_network_walk + ". There are two cases:" ); log.fatal( "(1) " + TransportMode.walk + " is teleported. Then you need to define the corresponding teleportation (= mode routing) params for " + TransportMode.walk + "." ); log.fatal( "(2) " + TransportMode.walk + " is routed on the network. Then you need to define the corresponding teleportation (= mode routing) params for " + TransportMode.non_network_walk + "."); diff --git a/matsim/src/main/java/org/matsim/core/router/NetworkRoutingModule.java b/matsim/src/main/java/org/matsim/core/router/NetworkRoutingModule.java index deaaf3fd87d..5380f45d47d 100644 --- a/matsim/src/main/java/org/matsim/core/router/NetworkRoutingModule.java +++ b/matsim/src/main/java/org/matsim/core/router/NetworkRoutingModule.java @@ -21,7 +21,6 @@ import java.util.Arrays; import java.util.List; -import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.network.Node; @@ -36,13 +35,11 @@ import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.router.util.LeastCostPathCalculator.Path; import org.matsim.facilities.Facility; -import org.matsim.vehicles.Vehicle; -import org.matsim.vehicles.VehicleUtils; /** * This wraps a "computer science" {@link LeastCostPathCalculator}, which routes from a node to another node, into something that * routes from a {@link Facility} to another {@link Facility}, as we need in MATSim. - * + * * @author thibautd */ public final class NetworkRoutingModule implements RoutingModule { @@ -63,7 +60,7 @@ public NetworkRoutingModule( final LeastCostPathCalculator routeAlgo) { Gbl.assertNotNull(network); // Gbl.assertIf( network.getLinks().size()>0 ) ; // otherwise network for mode probably not defined - // makes many tests fail. + // makes many tests fail. this.network = network; this.routeAlgo = routeAlgo; this.mode = mode; @@ -76,7 +73,7 @@ public List calcRoute(RoutingRequest request) { final Facility toFacility = request.getToFacility(); final double departureTime = request.getDepartureTime(); final Person person = request.getPerson(); - + Leg newLeg = this.populationFactory.createLeg( this.mode ); Gbl.assertNotNull(fromFacility); @@ -94,7 +91,7 @@ public List calcRoute(RoutingRequest request) { } Gbl.assertNotNull(fromLink); Gbl.assertNotNull(toLink); - + if (toLink != fromLink) { // (a "true" route) Node startNode = fromLink.getToNode(); // start at the end of the "current" link diff --git a/matsim/src/main/java/org/matsim/core/router/PlanRouter.java b/matsim/src/main/java/org/matsim/core/router/PlanRouter.java index 74d02707769..2e96a046a94 100644 --- a/matsim/src/main/java/org/matsim/core/router/PlanRouter.java +++ b/matsim/src/main/java/org/matsim/core/router/PlanRouter.java @@ -22,12 +22,10 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.PlanElement; -import org.matsim.core.config.Config; import org.matsim.core.population.algorithms.PersonAlgorithm; import org.matsim.core.population.algorithms.PlanAlgorithm; import org.matsim.core.population.routes.NetworkRoute; @@ -92,7 +90,7 @@ public void run(final Plan plan) { for (Trip oldTrip : trips) { final String routingMode = TripStructureUtils.identifyMainMode( oldTrip.getTripElements() ); timeTracker.addActivity(oldTrip.getOriginActivity()); - + if (log.isDebugEnabled()) log.debug("about to call TripRouter with routingMode=" + routingMode); final List newTripElements = tripRouter.calcRoute( // routingMode, // @@ -102,11 +100,11 @@ public void run(final Plan plan) { plan.getPerson(), // oldTrip.getTripAttributes() // ); - + putVehicleFromOldTripIntoNewTripIfMeaningful(oldTrip, newTripElements); TripRouter.insertTrip( plan, oldTrip.getOriginActivity(), newTripElements, oldTrip.getDestinationActivity()); - + timeTracker.addElements(newTripElements); } } diff --git a/matsim/src/main/java/org/matsim/core/router/TripRouter.java b/matsim/src/main/java/org/matsim/core/router/TripRouter.java index 47408aa9cb6..ac39295ebe8 100644 --- a/matsim/src/main/java/org/matsim/core/router/TripRouter.java +++ b/matsim/src/main/java/org/matsim/core/router/TripRouter.java @@ -40,12 +40,9 @@ import org.matsim.core.api.internal.MatsimExtensionPoint; import org.matsim.core.config.Config; import org.matsim.core.gbl.Gbl; -import org.matsim.core.population.PopulationUtils; import org.matsim.facilities.Facility; import org.matsim.utils.objectattributes.attributable.Attributes; -import com.google.common.base.Preconditions; - /** * Class acting as an intermediate between clients needing to * compute routes and all registered {@link RoutingModule}s. diff --git a/matsim/src/main/java/org/matsim/core/router/costcalculators/OnlyTimeDependentTravelDisutility.java b/matsim/src/main/java/org/matsim/core/router/costcalculators/OnlyTimeDependentTravelDisutility.java index eafed814d0e..9dd484608b6 100644 --- a/matsim/src/main/java/org/matsim/core/router/costcalculators/OnlyTimeDependentTravelDisutility.java +++ b/matsim/src/main/java/org/matsim/core/router/costcalculators/OnlyTimeDependentTravelDisutility.java @@ -27,18 +27,17 @@ import org.matsim.core.router.util.TravelDisutility; import org.matsim.core.router.util.TravelTime; import org.matsim.core.trafficmonitoring.FreeSpeedTravelTime; -import org.matsim.core.utils.misc.Time; import org.matsim.vehicles.Vehicle; /** * A Travel Cost Calculator that uses the travel times as travel disutility. - * + * * @author cdobler */ public class OnlyTimeDependentTravelDisutility implements TravelDisutility { private static final Logger log = LogManager.getLogger(OnlyTimeDependentTravelDisutility.class); - + protected final TravelTime travelTime; public OnlyTimeDependentTravelDisutility(final TravelTime travelTime) { @@ -49,7 +48,7 @@ public OnlyTimeDependentTravelDisutility(final TravelTime travelTime) { } @Override - public double getLinkTravelDisutility(final Link link, final double time, final Person person, final Vehicle vehicle) { + public double getLinkTravelDisutility(final Link link, final double time, final Person person, final Vehicle vehicle) { return this.travelTime.getLinkTravelTime(link, time, person, vehicle); } @@ -57,4 +56,4 @@ public double getLinkTravelDisutility(final Link link, final double time, final public double getLinkMinimumTravelDisutility(final Link link) { return link.getLength() / link.getFreespeed(); } -} \ No newline at end of file +} diff --git a/matsim/src/main/java/org/matsim/core/router/speedy/SpeedyALT.java b/matsim/src/main/java/org/matsim/core/router/speedy/SpeedyALT.java index fb2c56a7f35..47c2f16de86 100644 --- a/matsim/src/main/java/org/matsim/core/router/speedy/SpeedyALT.java +++ b/matsim/src/main/java/org/matsim/core/router/speedy/SpeedyALT.java @@ -1,6 +1,5 @@ package org.matsim.core.router.speedy; -import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.network.Link; diff --git a/matsim/src/main/java/org/matsim/core/router/util/TravelTimeUtils.java b/matsim/src/main/java/org/matsim/core/router/util/TravelTimeUtils.java index bfcf9870ec2..2d988456108 100644 --- a/matsim/src/main/java/org/matsim/core/router/util/TravelTimeUtils.java +++ b/matsim/src/main/java/org/matsim/core/router/util/TravelTimeUtils.java @@ -25,9 +25,9 @@ * */ public final class TravelTimeUtils { - - private TravelTimeUtils(){} ; // do not instantiate - + + private TravelTimeUtils(){} // do not instantiate + public static TravelTime createFreeSpeedTravelTime() { return new FreeSpeedTravelTime() ; } diff --git a/matsim/src/main/java/org/matsim/core/scenario/ZZEverythingInPackageIsPackageFinalOrEmpty.java b/matsim/src/main/java/org/matsim/core/scenario/ZZEverythingInPackageIsPackageFinalOrEmpty.java index 8786acc7ad3..ba7a93a5aef 100644 --- a/matsim/src/main/java/org/matsim/core/scenario/ZZEverythingInPackageIsPackageFinalOrEmpty.java +++ b/matsim/src/main/java/org/matsim/core/scenario/ZZEverythingInPackageIsPackageFinalOrEmpty.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.scenario; /** diff --git a/matsim/src/main/java/org/matsim/core/scoring/EventsToLegs.java b/matsim/src/main/java/org/matsim/core/scoring/EventsToLegs.java index 23e7c4dbc56..eeb8f641cd5 100644 --- a/matsim/src/main/java/org/matsim/core/scoring/EventsToLegs.java +++ b/matsim/src/main/java/org/matsim/core/scoring/EventsToLegs.java @@ -21,7 +21,6 @@ import com.google.inject.Inject; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.events.*; @@ -312,7 +311,7 @@ public void handleEvent(PersonArrivalEvent event) { final TransitStopFacility egressFacility = transitSchedule.getFacilities().get(lastFacilityId); assert egressFacility != null; - + DefaultTransitPassengerRoute passengerRoute = new DefaultTransitPassengerRoute(accessFacility, line, route, egressFacility); passengerRoute.setBoardingTime(pendingTransitTravel.boardingTime); passengerRoute.setTravelTime(travelTime); diff --git a/matsim/src/main/java/org/matsim/core/trafficmonitoring/FreeSpeedTravelTime.java b/matsim/src/main/java/org/matsim/core/trafficmonitoring/FreeSpeedTravelTime.java index a59b76ea5ab..731a32f42db 100644 --- a/matsim/src/main/java/org/matsim/core/trafficmonitoring/FreeSpeedTravelTime.java +++ b/matsim/src/main/java/org/matsim/core/trafficmonitoring/FreeSpeedTravelTime.java @@ -20,10 +20,8 @@ package org.matsim.core.trafficmonitoring; -import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Person; import org.matsim.core.router.util.TravelTime; diff --git a/matsim/src/main/java/org/matsim/core/trafficmonitoring/package-info.java b/matsim/src/main/java/org/matsim/core/trafficmonitoring/package-info.java index 268ae9d4fcf..6aaa66f69a8 100644 --- a/matsim/src/main/java/org/matsim/core/trafficmonitoring/package-info.java +++ b/matsim/src/main/java/org/matsim/core/trafficmonitoring/package-info.java @@ -19,9 +19,9 @@ * * * *********************************************************************** */ - package org.matsim.core.trafficmonitoring; /** * The material in this package is internal implementation, which may be changed. The only real public API is {@link org.matsim.core.trafficmonitoring.TravelTimeCalculator}. * Everything else, possibly with the exception of {@link org.matsim.core.trafficmonitoring.FreeSpeedTravelTime}, should not be considered public API, even when accessible. */ +package org.matsim.core.trafficmonitoring; diff --git a/matsim/src/main/java/org/matsim/core/utils/collections/ArrayMap.java b/matsim/src/main/java/org/matsim/core/utils/collections/ArrayMap.java index 24b371572bf..a892ae586c2 100644 --- a/matsim/src/main/java/org/matsim/core/utils/collections/ArrayMap.java +++ b/matsim/src/main/java/org/matsim/core/utils/collections/ArrayMap.java @@ -42,7 +42,6 @@ public class ArrayMap implements Map { private final static Object[] EMPTY = new Object[0]; - @SuppressWarnings("unchecked") private Object[] data = EMPTY; public ArrayMap() { @@ -198,7 +197,6 @@ public void putAll(final Map m) { m.forEach(this::put); } - @SuppressWarnings("unchecked") @Override public void clear() { this.data = EMPTY; diff --git a/matsim/src/main/java/org/matsim/core/utils/collections/IntArrayMap.java b/matsim/src/main/java/org/matsim/core/utils/collections/IntArrayMap.java index db0c3164a4f..51db4f77946 100644 --- a/matsim/src/main/java/org/matsim/core/utils/collections/IntArrayMap.java +++ b/matsim/src/main/java/org/matsim/core/utils/collections/IntArrayMap.java @@ -274,7 +274,6 @@ public Collection values() { return new ValuesView<>(this); } - @SuppressWarnings("unchecked") @Override public Set> entrySet() { return new EntrySetView<>(this); diff --git a/matsim/src/main/java/org/matsim/core/utils/collections/Tuple.java b/matsim/src/main/java/org/matsim/core/utils/collections/Tuple.java index 1774553a7ed..bda6d6299c2 100644 --- a/matsim/src/main/java/org/matsim/core/utils/collections/Tuple.java +++ b/matsim/src/main/java/org/matsim/core/utils/collections/Tuple.java @@ -69,7 +69,6 @@ public B getSecond() { /** * @see java.lang.Object#equals(java.lang.Object) */ - @SuppressWarnings("unchecked") @Override public boolean equals(final Object other) { if (!(other instanceof Tuple)) return false; diff --git a/matsim/src/main/java/org/matsim/core/utils/geometry/GeometryUtils.java b/matsim/src/main/java/org/matsim/core/utils/geometry/GeometryUtils.java index f8e01021ff8..8887bfe2e1c 100644 --- a/matsim/src/main/java/org/matsim/core/utils/geometry/GeometryUtils.java +++ b/matsim/src/main/java/org/matsim/core/utils/geometry/GeometryUtils.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.core.utils.geometry; import java.util.ArrayList; @@ -55,7 +52,7 @@ private GeometryUtils() {} // do not instantiate /** * Method to find all links in {@link Network} that intersect a given {@link Link}. Convenience method that * only uses MATSim objects. - * + * * @param link * @param network * @return @@ -67,24 +64,24 @@ public static List findIntersectingLinks( Link link, final Network network /** * Method to find all links in {@link Network} that intersect a given {@link LineString}. - * + * * @param lineString * @param network * @return - * + * * @see {@link GeometryUtilsTest#testIntersectingLinks()} */ public static List findIntersectingLinks(LineString lineString, final Network network) { // yy One could probably improve this method by using the (already existing) link quadtree to look only at // those links that are in the bounding box. kai, oct'17 - + // convert matsim links into geotools line strings: Map segments = new LinkedHashMap<>() ; for ( Link link : network.getLinks().values() ) { LineString theSegment = GeometryUtils.createGeotoolsLineString(link); segments.put( link, theSegment ) ; } - + // find the intersecting segments: List resultList = new ArrayList<>(); for ( Entry entry : segments.entrySet() ) { @@ -97,7 +94,7 @@ public static List findIntersectingLinks(LineString lineString, final Netw /** * Helper method for type conversion. - * + * * @param link * @return */ @@ -107,15 +104,15 @@ public static LineString createGeotoolsLineString(Link link) { LineString theSegment = new GeometryFactory().createLineString(new Coordinate[]{ fromCoord, toCoord }); return theSegment; } - + public static Point createGeotoolsPoint(Coord coord ) { Coordinate coordinate = MGC.coord2Coordinate(coord) ; Point point = new GeometryFactory().createPoint( coordinate ) ; return point ; } - + public static Polygon createGeotoolsPolygon(List coords ) { - + // better way to do this is welcome. kai, dec'17 double [] flatArray = new double[coords.size()*2] ; int ii=0 ; @@ -126,9 +123,9 @@ public static Polygon createGeotoolsPolygon(List coords ) { ii++ ; } return new GeometryBuilder().polygon( flatArray ) ; - + // the following yields some failing tests in the minibus contrib. ihab, feb'19 - + // Coordinate[] coordinates = new Coordinate[coords.size()] ; // int ii=0 ; // for ( Coord coord : coords ) { @@ -136,7 +133,7 @@ public static Polygon createGeotoolsPolygon(List coords ) { // ii++ ; // } // return new GeometryFactory().createPolygon(coordinates); - + } public static Point getRandomPointInFeature( Random rnd, SimpleFeature ft ) { diff --git a/matsim/src/main/java/org/matsim/core/utils/io/CollectLogMessagesAppender.java b/matsim/src/main/java/org/matsim/core/utils/io/CollectLogMessagesAppender.java index 6152b09fbf2..3399a3e65da 100644 --- a/matsim/src/main/java/org/matsim/core/utils/io/CollectLogMessagesAppender.java +++ b/matsim/src/main/java/org/matsim/core/utils/io/CollectLogMessagesAppender.java @@ -45,7 +45,6 @@ public CollectLogMessagesAppender() { Controler.DEFAULTLOG4JLAYOUT, false, new Property[0]); - this.logEvents = logEvents; } @Override diff --git a/matsim/src/main/java/org/matsim/core/utils/io/IOUtils.java b/matsim/src/main/java/org/matsim/core/utils/io/IOUtils.java index 9cc3cde191a..0b1cf1e93aa 100644 --- a/matsim/src/main/java/org/matsim/core/utils/io/IOUtils.java +++ b/matsim/src/main/java/org/matsim/core/utils/io/IOUtils.java @@ -341,7 +341,6 @@ public static BufferedReader getBufferedReader(URL url) throws UncheckedIOExcept * * @throws UncheckedIOException */ - @SuppressWarnings("resource") public static OutputStream getOutputStream(URL url, boolean append) throws UncheckedIOException { try { if (!url.getProtocol().equals("file")) { diff --git a/matsim/src/main/java/org/matsim/core/utils/io/MatsimFileTypeGuesser.java b/matsim/src/main/java/org/matsim/core/utils/io/MatsimFileTypeGuesser.java index f8869bbb6f6..8f855480dee 100644 --- a/matsim/src/main/java/org/matsim/core/utils/io/MatsimFileTypeGuesser.java +++ b/matsim/src/main/java/org/matsim/core/utils/io/MatsimFileTypeGuesser.java @@ -185,7 +185,7 @@ public XmlHandler() { @Override public InputSource resolveEntity(final String publicId, final String systemId) { - /** + /* * As the xml schema of interest may be derived from other schema instances we * are only interested in the first entity resolved. */ diff --git a/matsim/src/main/java/org/matsim/core/utils/io/tabularFileParser/TabularFileParserConfig.java b/matsim/src/main/java/org/matsim/core/utils/io/tabularFileParser/TabularFileParserConfig.java index 09e7e838755..f756cd8b2a6 100644 --- a/matsim/src/main/java/org/matsim/core/utils/io/tabularFileParser/TabularFileParserConfig.java +++ b/matsim/src/main/java/org/matsim/core/utils/io/tabularFileParser/TabularFileParserConfig.java @@ -22,6 +22,7 @@ import java.net.URL; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; /** * Configuration for a TabularFileParser. @@ -50,8 +51,8 @@ public class TabularFileParserConfig { private String commentRegex = null; private String delimiterRegex = null; - - private Charset charset = Charset.forName("UTF8"); + + private Charset charset = StandardCharsets.UTF_8; // -------------------- CONSTRUCTION -------------------- @@ -82,10 +83,10 @@ public void setFileName(String file) { public void setUrl(URL url) { this.url = url; } - + /** * Sets the charset for the file. Defaults to UTF-8 - * + * * @param charset the charset used to reade the file */ public void setCharset(Charset charset) { @@ -239,7 +240,7 @@ public String getCommentRegex() { public String getDelimiterRegex() { return delimiterRegex; } - + public Charset getCharset() { return this.charset; } diff --git a/matsim/src/main/java/org/matsim/core/utils/misc/ByteBufferUtils.java b/matsim/src/main/java/org/matsim/core/utils/misc/ByteBufferUtils.java index d003a97de3e..873aa73b814 100644 --- a/matsim/src/main/java/org/matsim/core/utils/misc/ByteBufferUtils.java +++ b/matsim/src/main/java/org/matsim/core/utils/misc/ByteBufferUtils.java @@ -23,7 +23,6 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; @@ -41,7 +40,7 @@ public class ByteBufferUtils { * Writes the given String to the ByteBuffer. First writes the length of the String as int, * then writes the single characters. The ByteBuffer's position is incremented according * to the length of the String. - * + * * @param buffer * @param string */ @@ -55,8 +54,8 @@ public static void putString(final ByteBuffer buffer, final String string) { /** * Reads a String from a ByteBuffer. Reads first an int for the length of the String, * and then the corresponding number of characters. Increments the position of the - * ByteBuffer according to the length of the String. - * + * ByteBuffer according to the length of the String. + * * @param buffer * @return the String at the buffer's current position */ @@ -73,7 +72,7 @@ public static String getString(final ByteBuffer buffer) { * Writes the given Serializable to the ByteBuffer. First writes the length of the Serializable as int, * then writes the single bytes of the serialized object. The ByteBuffer's position is incremented according * to the length of the Serializable. - * + * */ public static void putObject(final ByteBuffer buffer, Serializable o){ try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { @@ -87,13 +86,13 @@ public static void putObject(final ByteBuffer buffer, Serializable o){ } } catch (IOException e) { e.printStackTrace(); - } + } } /** * Reads a Object (Serializable) from a ByteBuffer. Reads first an int for the length of the Object, * and then the corresponding number of bytes. Increments the position of the - * ByteBuffer according to the length of the object's byte array. + * ByteBuffer according to the length of the object's byte array. */ public static Object getObject(ByteBuffer buffer) { int length = buffer.getInt(); @@ -101,18 +100,13 @@ public static Object getObject(ByteBuffer buffer) { for (int i = 0; i < length; i++) { bytes[i] = buffer.get(); } - ByteArrayInputStream bis = new ByteArrayInputStream(bytes); - Object o = null; - try (ObjectInputStream oin = new ObjectInputStream(bis)) { - o = oin.readObject(); - bis.close(); - oin.close(); - } catch (IOException e) { - e.printStackTrace(); - } catch (ClassNotFoundException e) { + try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); + ObjectInputStream oin = new ObjectInputStream(bis)) { + return oin.readObject(); + } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); + return null; } - return o; } } diff --git a/matsim/src/main/java/org/matsim/core/utils/misc/CRCChecksum.java b/matsim/src/main/java/org/matsim/core/utils/misc/CRCChecksum.java index dd4d5680618..9050a9eed79 100644 --- a/matsim/src/main/java/org/matsim/core/utils/misc/CRCChecksum.java +++ b/matsim/src/main/java/org/matsim/core/utils/misc/CRCChecksum.java @@ -55,14 +55,14 @@ private static long getCRCFromStream(final InputStream in) { /** * Calculates the checksum of the content of the given file. If the filename ends in ".gz", - * the file is assumed to be gzipped and the checksum over the uncompressed content + * the file is assumed to be gzipped and the checksum over the uncompressed content * will be calculated. If a file is not found at its expected place, it is searched via the class loader. *

    * Comments:
      *
    • Some version of this method, possibly the variant with the class loader, does some caching: If I replace * the original file in a test case, I need to restart eclipse before it works correctly. ??? kai, feb'14 *
    - * + * * @param filename * @return CRC32-Checksum of the file's content. */ @@ -96,7 +96,7 @@ public static long getCRCFromFile(final String filename) { if (filename.endsWith(".gz")) { log.info( "file ends in gz"); try ( InputStream stream = CRCChecksum.class.getClassLoader().getResourceAsStream(filename) ; - InputStream in = new GZIPInputStream(new BufferedInputStream(stream)); ) { + InputStream in = new GZIPInputStream(new BufferedInputStream(stream))) { long result = getCRCFromStream(in); in.close(); return result ; @@ -106,7 +106,7 @@ public static long getCRCFromFile(final String filename) { } else { // not work gz log.info( "file does not end in gz"); try ( InputStream stream = CRCChecksum.class.getClassLoader().getResourceAsStream(filename) ; - InputStream in = new BufferedInputStream(stream); ) { + InputStream in = new BufferedInputStream(stream)) { long result = getCRCFromStream(in); in.close(); return result ; diff --git a/matsim/src/main/java/org/matsim/core/utils/misc/ExeRunner.java b/matsim/src/main/java/org/matsim/core/utils/misc/ExeRunner.java index ceeac334ee8..8538f1328b4 100644 --- a/matsim/src/main/java/org/matsim/core/utils/misc/ExeRunner.java +++ b/matsim/src/main/java/org/matsim/core/utils/misc/ExeRunner.java @@ -81,7 +81,7 @@ public static int run(final String[] cmdArgs, final String stdoutFileName, final final ExternalExecutor myExecutor = new ExternalExecutor(cmdArgs, stdoutFileName, workingDirectory); return waitForFinish(myExecutor, timeout); } - + public static int waitForFinish(final ExternalExecutor myExecutor, final int timeout) { synchronized (myExecutor) { try { @@ -106,7 +106,7 @@ public static int waitForFinish(final ExternalExecutor myExecutor, final int tim log.info("ExeRunner.run() got interrupted while waiting for timeout", e); } } - + return myExecutor.erg; } @@ -136,7 +136,7 @@ public ExternalExecutor (final String cmd, final String stdoutFileName, final St this.stderrFileName = null; } } - + public ExternalExecutor (final String[] cmdArgs, final String stdoutFileName, final String workingDirectory) { this.cmdArgs = cmdArgs; this.cmd = null; @@ -152,7 +152,7 @@ public ExternalExecutor (final String[] cmdArgs, final String stdoutFileName, fi this.stderrFileName = null; } } - + public void killProcess() { if (this.p != null) { this.p.destroy(); @@ -175,10 +175,10 @@ public void run() { this.p = Runtime.getRuntime().exec(this.cmdArgs, null, new File(this.workingDirectory)); } } - + BufferedReader in = new BufferedReader(new InputStreamReader(this.p.getInputStream())); BufferedReader err = new BufferedReader(new InputStreamReader(this.p.getErrorStream())); - + BufferedWriter writerIn = null; StreamHandler outputHandler = null; if (this.stdoutFileName != null) { @@ -238,19 +238,19 @@ public void run() { writerErr.close(); } } catch (IOException e) { - e.printStackTrace(); + log.error("problem running exe", e); this.erg = -2; } } } - + static class BlackHoleStreamHandler extends Thread { private final BufferedReader in; - + public BlackHoleStreamHandler(final BufferedReader in) { this.in = in; } - + @Override public void run() { try { @@ -258,8 +258,7 @@ public void run() { while ((line = this.in.readLine()) != null) { } } catch (IOException e) { - log.info("StreamHandler got interrupted"); - e.printStackTrace(); + log.info("StreamHandler got interrupted", e); } } } @@ -291,10 +290,9 @@ public void run() { } this.out.flush(); } catch (IOException e) { - log.info("StreamHandler got interrupted"); - e.printStackTrace(); + log.info("StreamHandler got interrupted", e); } } } -} \ No newline at end of file +} diff --git a/matsim/src/main/java/org/matsim/counts/CountSimComparison.java b/matsim/src/main/java/org/matsim/counts/CountSimComparison.java index b1cc95398e1..c3a4007fff8 100644 --- a/matsim/src/main/java/org/matsim/counts/CountSimComparison.java +++ b/matsim/src/main/java/org/matsim/counts/CountSimComparison.java @@ -18,62 +18,61 @@ * * * *********************************************************************** */ -package org.matsim.counts; - +package org.matsim.counts; + import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.network.Link; - -/** - * Classes implementing this interface can be used to access the data - * needed to compare traffic counts and simulation traffic at a specific + +/** + * Classes implementing this interface can be used to access the data + * needed to compare traffic counts and simulation traffic at a specific * link for a one hour time step. - * - * @author dgrether - */ -public interface CountSimComparison { - - /** - * @return The Id of the link - */ - public Id getId(); + * + * @author dgrether + */ +public interface CountSimComparison { + + /** + * @return The Id of the link + */ + public Id getId(); /** - * + * * @return The Id of the count station */ public String getCsId(); - - /** - * The time at which the data was measured. - * @return A value in 1..24, 1 means 0 - 1 am, 2 means 1 - 2 am and so on - */ - public int getHour(); - - /** - * @return The real traffic amount - */ - public double getCountValue(); - - /** - * @return The traffic amount of the simulation - */ - public double getSimulationValue(); - - /** - * Calculates the relative error. - * @return the relative error - */ - public double calculateRelativeError(); + + /** + * The time at which the data was measured. + * @return A value in 1..24, 1 means 0 - 1 am, 2 means 1 - 2 am and so on + */ + public int getHour(); + + /** + * @return The real traffic amount + */ + public double getCountValue(); + + /** + * @return The traffic amount of the simulation + */ + public double getSimulationValue(); + + /** + * Calculates the relative error. + * @return the relative error + */ + public double calculateRelativeError(); /** * Calculates the normalized relative error. * @return the normalized relative error */ public double calculateNormalizedRelativeError(); - + /** * Calculates the GEH value * @return the GEH value */ - public double calculateGEHValue(); -} \ No newline at end of file + public double calculateGEHValue(); +} diff --git a/matsim/src/main/java/org/matsim/counts/algorithms/graphs/helper/OutputDelegate.java b/matsim/src/main/java/org/matsim/counts/algorithms/graphs/helper/OutputDelegate.java index dcefd8070ed..98e2b4b7156 100644 --- a/matsim/src/main/java/org/matsim/counts/algorithms/graphs/helper/OutputDelegate.java +++ b/matsim/src/main/java/org/matsim/counts/algorithms/graphs/helper/OutputDelegate.java @@ -74,19 +74,10 @@ public void outputHtml(){ } private void copyResourceToFile(final String resourceFilename, final String destinationFilename) throws IOException { - InputStream inStream = null; - OutputStream outStream = null; - try { - inStream = MatsimResource.getAsInputStream(resourceFilename); - outStream = new FileOutputStream(destinationFilename); + try (InputStream inStream = MatsimResource.getAsInputStream(resourceFilename); + FileOutputStream outStream = new FileOutputStream(destinationFilename) + ) { IOUtils.copyStream(inStream, outStream); - } finally { - if (inStream != null) { - inStream.close(); - } - if (outStream != null) { - outStream.close(); - } } } @@ -107,18 +98,16 @@ private void writeHtml(final CountsGraph cg, final String iter_path, boolean ind file2 = new File(iter_path+"/start.html"); } - PrintWriter writer = null; - try { + ; + try (PrintWriter writer = new PrintWriter(new BufferedOutputStream(new FileOutputStream(file2)))) { ChartRenderingInfo info=null; File file1; - if (!indexFile){ + if (!indexFile) { info = new ChartRenderingInfo(new StandardEntityCollection()); file1 = new File(iter_path+"/png/"+fileName+".png"); ChartUtils.saveChartAsPNG(file1, chart, width, height, info); } - writer = new PrintWriter(new BufferedOutputStream(new FileOutputStream(file2))); - writer.println(""); //writer.println(""); writer.println(""); @@ -200,10 +189,6 @@ private void writeHtml(final CountsGraph cg, final String iter_path, boolean ind } catch (IOException e) { System.out.println(e.toString()); - } finally { - if (writer != null) { - writer.close(); - } } } diff --git a/matsim/src/main/java/org/matsim/deprecated/scoring/functions/CharyparNagelLegScoring.java b/matsim/src/main/java/org/matsim/deprecated/scoring/functions/CharyparNagelLegScoring.java index fad91e945e1..7fe3c761df2 100644 --- a/matsim/src/main/java/org/matsim/deprecated/scoring/functions/CharyparNagelLegScoring.java +++ b/matsim/src/main/java/org/matsim/deprecated/scoring/functions/CharyparNagelLegScoring.java @@ -21,7 +21,6 @@ package org.matsim.deprecated.scoring.functions; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.events.ActivityEndEvent; import org.matsim.api.core.v01.events.Event; @@ -62,14 +61,14 @@ public class CharyparNagelLegScoring implements LegScoring, ArbitraryEventScorin private boolean nextStartPtLegIsFirstOfTrip = true ; private boolean currentLegIsPtLeg = false; private double lastActivityEndTime = Double.NaN; - + @Deprecated // this version should not be used any more. Instead the SumScoringFunction variant should be used. kai, aug'18 public CharyparNagelLegScoring(final ScoringParameters params, Network network) { this.params = params; this.network = network; this.reset(); } - + @Deprecated // this version should not be used any more. Instead the SumScoringFunction variant should be used. kai, aug'18 public CharyparNagelLegScoring(final ScoringParameters params, Network network, TransitSchedule transitSchedule) { this(params, network); @@ -112,10 +111,10 @@ public double getScore() { } private static int ccc=0 ; - + protected double calcLegScore(final double departureTime, final double arrivalTime, final Leg leg) { double tmpScore = 0.0; - double travelTime = arrivalTime - departureTime; // travel time in seconds + double travelTime = arrivalTime - departureTime; // travel time in seconds ModeUtilityParameters modeParams = this.params.modeParams.get(leg.getMode()); if (modeParams == null) { if (leg.getMode().equals(TransportMode.transit_walk)) { @@ -148,7 +147,7 @@ protected double calcLegScore(final double departureTime, final double arrivalTi // (yy NOTE: the constant is added for _every_ pt leg. This is not how such models are estimated. kai, nov'12) return tmpScore; } - + @Override public void handleEvent(Event event) { if ( event instanceof ActivityEndEvent ) { diff --git a/matsim/src/main/java/org/matsim/deprecated/scoring/functions/CharyparNagelMoneyScoring.java b/matsim/src/main/java/org/matsim/deprecated/scoring/functions/CharyparNagelMoneyScoring.java index 266f215df72..7153b336aa1 100644 --- a/matsim/src/main/java/org/matsim/deprecated/scoring/functions/CharyparNagelMoneyScoring.java +++ b/matsim/src/main/java/org/matsim/deprecated/scoring/functions/CharyparNagelMoneyScoring.java @@ -21,7 +21,6 @@ package org.matsim.deprecated.scoring.functions; import org.matsim.core.scoring.functions.ScoringParameters; -import org.matsim.deprecated.scoring.ScoringFunctionAccumulator.BasicScoring; import org.matsim.deprecated.scoring.ScoringFunctionAccumulator.MoneyScoring; /** @@ -38,13 +37,13 @@ public class CharyparNagelMoneyScoring implements MoneyScoring { private double score; private final double marginalUtilityOfMoney; - + @Deprecated // this version should not be used any more. Instead the SumScoringFunction variant should be used. kai, aug'18 public CharyparNagelMoneyScoring(final ScoringParameters params) { this.marginalUtilityOfMoney = params.marginalUtilityOfMoney; this.reset(); } - + @Deprecated // this version should not be used any more. Instead the SumScoringFunction variant should be used. kai, aug'18 public CharyparNagelMoneyScoring(final double marginalUtilityOfMoney) { this.marginalUtilityOfMoney = marginalUtilityOfMoney; diff --git a/matsim/src/main/java/org/matsim/facilities/ActivityFacilities.java b/matsim/src/main/java/org/matsim/facilities/ActivityFacilities.java index 6eda32abc85..728e5fd0f20 100644 --- a/matsim/src/main/java/org/matsim/facilities/ActivityFacilities.java +++ b/matsim/src/main/java/org/matsim/facilities/ActivityFacilities.java @@ -25,7 +25,6 @@ import org.matsim.api.core.v01.Id; import org.matsim.core.api.internal.MatsimToplevelContainer; import org.matsim.utils.objectattributes.FailingObjectAttributes; -import org.matsim.utils.objectattributes.ObjectAttributes; import org.matsim.utils.objectattributes.attributable.Attributable; /** @@ -38,7 +37,7 @@ public interface ActivityFacilities extends MatsimToplevelContainer, Attributabl public String getName(); public void setName(String name); - + @Override public ActivityFacilitiesFactory getFactory(); @@ -53,5 +52,5 @@ public interface ActivityFacilities extends MatsimToplevelContainer, Attributabl * so there seems to be a need for it... mrieser/jul13 */ public TreeMap, ActivityFacility> getFacilitiesForActivityType(final String actType); - + } diff --git a/matsim/src/main/java/org/matsim/facilities/FacilitiesFromPopulation.java b/matsim/src/main/java/org/matsim/facilities/FacilitiesFromPopulation.java index 62ba74d01d3..ef3eb8c677f 100644 --- a/matsim/src/main/java/org/matsim/facilities/FacilitiesFromPopulation.java +++ b/matsim/src/main/java/org/matsim/facilities/FacilitiesFromPopulation.java @@ -78,7 +78,7 @@ public FacilitiesFromPopulation(final ActivityFacilities facilities) { public FacilitiesFromPopulation( Scenario scenario ) { // "fat" constructor, to configure via config etc. this(scenario.getActivityFacilities()); - FacilitiesConfigGroup facilityConfigGroup = scenario.getConfig().facilities();; + FacilitiesConfigGroup facilityConfigGroup = scenario.getConfig().facilities(); this.idPrefix = facilityConfigGroup.getIdPrefix(); // this.removeLinksAndCoordinates = facilityConfigGroup.isRemovingLinksAndCoordinates(); this.removeLinksAndCoordinates = false ; diff --git a/matsim/src/main/java/org/matsim/facilities/FacilitiesReaderMatsimV1.java b/matsim/src/main/java/org/matsim/facilities/FacilitiesReaderMatsimV1.java index da95b2ea58f..986cc9978f7 100644 --- a/matsim/src/main/java/org/matsim/facilities/FacilitiesReaderMatsimV1.java +++ b/matsim/src/main/java/org/matsim/facilities/FacilitiesReaderMatsimV1.java @@ -38,8 +38,6 @@ import org.matsim.utils.objectattributes.attributable.AttributesXmlReaderDelegate; import org.xml.sax.Attributes; -import javax.xml.stream.events.DTD; - /** * A reader for facilities-files of MATSim according to facilities_v1.dtd. * diff --git a/matsim/src/main/java/org/matsim/facilities/FacilitiesWriterV1.java b/matsim/src/main/java/org/matsim/facilities/FacilitiesWriterV1.java index 8f902dfccbd..b312ad56cc6 100644 --- a/matsim/src/main/java/org/matsim/facilities/FacilitiesWriterV1.java +++ b/matsim/src/main/java/org/matsim/facilities/FacilitiesWriterV1.java @@ -31,6 +31,7 @@ import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; +import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -100,7 +101,7 @@ private void writeFacility(final ActivityFacilityImpl f) { this.endFacility(); this.writer.flush(); } catch (IOException e) { - e.printStackTrace(); + throw new UncheckedIOException(e); } } @@ -110,7 +111,7 @@ private void writeFinish() { this.writer.flush(); this.writer.close(); } catch (IOException e) { - e.printStackTrace(); + throw new UncheckedIOException(e); } } @@ -128,7 +129,7 @@ private void startFacilities(final ActivityFacilities facilities, final Buffered try { this.writer.write(NL); } catch (IOException e) { - e.printStackTrace(); + throw new UncheckedIOException(e); } } this.attributesWriter.writeAttributes("\t", out, facilities.getAttributes()); diff --git a/matsim/src/main/java/org/matsim/facilities/FacilitiesWriterV2.java b/matsim/src/main/java/org/matsim/facilities/FacilitiesWriterV2.java index 3eefd02431a..a740d2ae014 100644 --- a/matsim/src/main/java/org/matsim/facilities/FacilitiesWriterV2.java +++ b/matsim/src/main/java/org/matsim/facilities/FacilitiesWriterV2.java @@ -31,6 +31,7 @@ import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; +import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -100,7 +101,7 @@ private void writeFacility(final ActivityFacilityImpl f) { this.endFacility(); this.writer.flush(); } catch (IOException e) { - e.printStackTrace(); + throw new UncheckedIOException(e); } } @@ -110,7 +111,7 @@ private void writeFinish() { this.writer.flush(); this.writer.close(); } catch (IOException e) { - e.printStackTrace(); + throw new UncheckedIOException(e); } } @@ -128,7 +129,7 @@ private void startFacilities(final ActivityFacilities facilities, final Buffered try { this.writer.write(NL); } catch (IOException e) { - e.printStackTrace(); + throw new UncheckedIOException(e); } } this.attributesWriter.writeAttributes("\t", out, facilities.getAttributes()); diff --git a/matsim/src/main/java/org/matsim/facilities/Facility.java b/matsim/src/main/java/org/matsim/facilities/Facility.java index ca29bdf0f4e..e1b2f591f22 100644 --- a/matsim/src/main/java/org/matsim/facilities/Facility.java +++ b/matsim/src/main/java/org/matsim/facilities/Facility.java @@ -21,9 +21,7 @@ import org.matsim.api.core.v01.BasicLocation; import org.matsim.api.core.v01.Customizable; import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.Identifiable; import org.matsim.api.core.v01.network.Link; -import org.matsim.facilities.algorithms.FacilityAlgorithm; /** * A Facility is a (Basic)Location ("getCoord") that is connected to a Link ("getLinkId"). Since about 2018, it no longer implements Identifiable, since @@ -42,5 +40,5 @@ public interface Facility extends BasicLocation, Customizable { public static final String FACILITY_NO_LONGER_IDENTIFIABLE = "After refactoring, facility " + "does not longer automatically " + "implement Identifiable. Don't know what to do."; - + } diff --git a/matsim/src/main/java/org/matsim/facilities/algorithms/FacilitiesSummary.java b/matsim/src/main/java/org/matsim/facilities/algorithms/FacilitiesSummary.java index f5a840f76e3..4073373e61d 100644 --- a/matsim/src/main/java/org/matsim/facilities/algorithms/FacilitiesSummary.java +++ b/matsim/src/main/java/org/matsim/facilities/algorithms/FacilitiesSummary.java @@ -22,7 +22,6 @@ import java.util.Iterator; -import org.matsim.api.core.v01.Coord; import org.matsim.facilities.ActivityFacilities; import org.matsim.facilities.ActivityFacility; import org.matsim.facilities.ActivityOption; @@ -76,7 +75,7 @@ else if (a.getType().equals("leisure")) { } else { throw new RuntimeException("ERROR: in " + this.getClass().getName() + - " in run(Facilities facilities):" + + " in run(Facilities facilities):" + " do not know type = " + a.getType()); } } diff --git a/matsim/src/main/java/org/matsim/pt/analysis/TransitLoad.java b/matsim/src/main/java/org/matsim/pt/analysis/TransitLoad.java index 958d5d45ab1..45a76f13945 100644 --- a/matsim/src/main/java/org/matsim/pt/analysis/TransitLoad.java +++ b/matsim/src/main/java/org/matsim/pt/analysis/TransitLoad.java @@ -59,16 +59,16 @@ public class TransitLoad implements TransitDriverStartsEventHandler, VehicleArri public TransitLoad() { } - @Deprecated /** * Always returns first occurence of the TransitStopFacility in the route. - * + * * @param line * @param route * @param stopFacility * @param departure * @return */ + @Deprecated public int getLoadAtDeparture(final TransitLine line, final TransitRoute route, final TransitStopFacility stopFacility, final Departure departure) { for (int i = 0; i < route.getStops().size(); i++) { if (route.getStops().get(i).getStopFacility().getId().equals(stopFacility.getId())) { @@ -77,10 +77,10 @@ public int getLoadAtDeparture(final TransitLine line, final TransitRoute route, } return -1; } - + public int getLoadAtDeparture(final TransitLine line, final TransitRoute route, final int transitRouteStopIndex, final Departure departure) { int nOfPassengers = 0; - + /* * count how often a stop was visited while following the route in * route.getStops() to differentiate multiple servings of the same diff --git a/matsim/src/main/java/org/matsim/pt/router/TransitActsRemover.java b/matsim/src/main/java/org/matsim/pt/router/TransitActsRemover.java index 354c27d8ed6..c1a09d7e107 100644 --- a/matsim/src/main/java/org/matsim/pt/router/TransitActsRemover.java +++ b/matsim/src/main/java/org/matsim/pt/router/TransitActsRemover.java @@ -35,14 +35,12 @@ /** * Removes all transit activities (like "pt -interaction") as well as the legs * following those activities. In addition, all legs with mode "transit_walk" - * are set to mode "pt" to be routed again with the transit. - * + * are set to mode "pt" to be routed again with the transit. + * * @see PtConstants#TRANSIT_ACTIVITY_TYPE - * + * * @author mrieser - */ - -/** + * * @deprecated -- use {@link org.matsim.core.population.algorithms.TripsToLegsAlgorithm} instead to circumvene problems with different types of access / * egress legs and stage activities. */ 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 600d327a8f7..f8e5bf92d9f 100644 --- a/matsim/src/main/java/org/matsim/pt/transitSchedule/MinimalTransferTimesImpl.java +++ b/matsim/src/main/java/org/matsim/pt/transitSchedule/MinimalTransferTimesImpl.java @@ -35,7 +35,7 @@ */ class MinimalTransferTimesImpl implements MinimalTransferTimes { - private Map, Map, Double>> minimalTransferTimes = new ConcurrentHashMap<>(); + private final Map, Map, Double>> minimalTransferTimes = new ConcurrentHashMap<>(); @Override public double set(Id fromStop, Id toStop, double seconds) { @@ -59,15 +59,21 @@ public double get(Id fromStop, Id toSt public double get(Id fromStop, Id toStop, double defaultSeconds) { Map, Double> innerMap = this.minimalTransferTimes.get(fromStop); if (innerMap == null) { - return defaultSeconds; + return getInnerStopTransferTime(toStop,defaultSeconds); } Double value = innerMap.get(toStop); if (value == null) { - return defaultSeconds; + return Math.max(getInnerStopTransferTime(toStop,defaultSeconds),getInnerStopTransferTime(fromStop,defaultSeconds)); } return value; } + private double getInnerStopTransferTime(Id stopId, double defaultSeconds){ + Map, Double> innerMap = this.minimalTransferTimes.get(stopId); + return innerMap!=null?innerMap.getOrDefault(stopId,defaultSeconds):defaultSeconds; + + } + @Override public double remove(Id fromStop, Id toStop) { Map, Double> innerMap = this.minimalTransferTimes.get(fromStop); @@ -94,7 +100,7 @@ private static class MinimalTransferTimesIteratorImpl implements MinimalTransfe private double seconds = Double.NaN; private boolean hasElement = false; - private Iterator, Map, Double>>> outerIterator; + private final Iterator, Map, Double>>> outerIterator; private Iterator, Double>> innerIterator; MinimalTransferTimesIteratorImpl(Map, Map, Double>> values) { diff --git a/matsim/src/main/java/org/matsim/pt/transitSchedule/TransitScheduleUtils.java b/matsim/src/main/java/org/matsim/pt/transitSchedule/TransitScheduleUtils.java index e06377d0351..5d948a9d20e 100644 --- a/matsim/src/main/java/org/matsim/pt/transitSchedule/TransitScheduleUtils.java +++ b/matsim/src/main/java/org/matsim/pt/transitSchedule/TransitScheduleUtils.java @@ -23,7 +23,6 @@ import java.util.Collection; import org.matsim.core.utils.collections.QuadTree; -import org.matsim.pt.transitSchedule.api.TransitLine; import org.matsim.pt.transitSchedule.api.TransitSchedule; import org.matsim.pt.transitSchedule.api.TransitStopFacility; diff --git a/matsim/src/main/java/org/matsim/pt/transitSchedule/api/TransitSchedule.java b/matsim/src/main/java/org/matsim/pt/transitSchedule/api/TransitSchedule.java index a0690bc7e12..30096838c01 100644 --- a/matsim/src/main/java/org/matsim/pt/transitSchedule/api/TransitSchedule.java +++ b/matsim/src/main/java/org/matsim/pt/transitSchedule/api/TransitSchedule.java @@ -25,19 +25,18 @@ import org.matsim.api.core.v01.Id; import org.matsim.core.api.internal.MatsimToplevelContainer; import org.matsim.utils.objectattributes.FailingObjectAttributes; -import org.matsim.utils.objectattributes.ObjectAttributes; import org.matsim.utils.objectattributes.attributable.Attributable; /** * Stores a complete transit schedules with multiple lines, multiple routes per line, all the time data * and the infrastructure in form of stop facilities. - * + * * @author mrieser */ public interface TransitSchedule extends MatsimToplevelContainer, Attributable { void addTransitLine(final TransitLine line); - + /** * @param line the transit line to be removed * @return true if the transit line was successfully removed from the transit schedule. @@ -49,13 +48,13 @@ public interface TransitSchedule extends MatsimToplevelContainer, Attributable { Map, TransitLine> getTransitLines(); Map, TransitStopFacility> getFacilities(); - + /** * @param stop the stop facility to be removed * @return true if the transit stop facility was successfully removed from the transit schedule. */ boolean removeStopFacility(final TransitStopFacility stop); - + @Override TransitScheduleFactory getFactory(); @@ -66,4 +65,4 @@ public interface TransitSchedule extends MatsimToplevelContainer, Attributable { FailingObjectAttributes getTransitStopsAttributes(); MinimalTransferTimes getMinimalTransferTimes(); -} \ No newline at end of file +} diff --git a/matsim/src/main/java/org/matsim/pt/utils/CreateVehiclesForSchedule.java b/matsim/src/main/java/org/matsim/pt/utils/CreateVehiclesForSchedule.java index c778f2d175f..3adbd0b8407 100644 --- a/matsim/src/main/java/org/matsim/pt/utils/CreateVehiclesForSchedule.java +++ b/matsim/src/main/java/org/matsim/pt/utils/CreateVehiclesForSchedule.java @@ -26,7 +26,6 @@ import org.matsim.pt.transitSchedule.api.TransitRoute; import org.matsim.pt.transitSchedule.api.TransitSchedule; import org.matsim.vehicles.Vehicle; -import org.matsim.vehicles.VehicleCapacity; import org.matsim.vehicles.VehicleType; import org.matsim.vehicles.Vehicles; import org.matsim.vehicles.VehiclesFactory; diff --git a/matsim/src/main/java/org/matsim/pt/utils/TransitScheduleValidator.java b/matsim/src/main/java/org/matsim/pt/utils/TransitScheduleValidator.java index 2f3fc25bd47..cfd96dbe88f 100644 --- a/matsim/src/main/java/org/matsim/pt/utils/TransitScheduleValidator.java +++ b/matsim/src/main/java/org/matsim/pt/utils/TransitScheduleValidator.java @@ -50,7 +50,7 @@ /** * An abstract class offering a number of static methods to validate several aspects of transit schedules. - * + * * @author mrieser */ public abstract class TransitScheduleValidator { @@ -58,7 +58,7 @@ public abstract class TransitScheduleValidator { private TransitScheduleValidator() { // this class should not be instantiated } - + /** * Checks that the links specified for a network route really builds a complete route that can be driven along. * @@ -177,7 +177,7 @@ public static ValidationResult validateAllStopsExist(final TransitSchedule sched } return result; } - + public static ValidationResult validateOffsets(final TransitSchedule schedule) { ValidationResult result = new ValidationResult(); @@ -185,20 +185,20 @@ public static ValidationResult validateOffsets(final TransitSchedule schedule) { for (TransitRoute route : line.getRoutes().values()) { ArrayList stops = new ArrayList(route.getStops()); int stopCount = stops.size(); - + if (stopCount > 0) { TransitRouteStop stop = stops.get(0); if (stop.getDepartureOffset().isUndefined()) { result.addError("Transit line " + line.getId() + ", route " + route.getId() + ": The first stop does not contain any departure offset."); } - + for (int i = 1; i < stopCount - 1; i++) { stop = stops.get(i); if (stop.getDepartureOffset().isUndefined()) { result.addError("Transit line " + line.getId() + ", route " + route.getId() + ": Stop " + i + " does not contain any departure offset."); } } - + stop = stops.get(stopCount - 1); if (stop.getArrivalOffset().isUndefined()) { result.addError("Transit line " + line.getId() + ", route " + route.getId() + ": The last stop does not contain any arrival offset."); @@ -206,10 +206,10 @@ public static ValidationResult validateOffsets(final TransitSchedule schedule) { } else { result.addWarning("Transit line " + line.getId() + ", route " + route.getId() + ": The route has not stops assigned, looks suspicious."); } - + } } - + return result; } @@ -261,7 +261,7 @@ public static ValidationResult validateAll(final TransitSchedule schedule, final v.add(validateTransfers(schedule)); return v; } - + public static void printResult(final ValidationResult result) { if (result.isValid()) { System.out.println("Schedule appears valid!"); @@ -293,7 +293,7 @@ public static void main(String[] args) throws IOException, SAXException, ParserC System.err.println("Usage: TransitScheduleValidator transitSchedule.xml [network.xml]"); return; } - + MutableScenario s = (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig()); s.getConfig().transit().setUseTransit(true); TransitSchedule ts = s.getTransitSchedule(); @@ -311,11 +311,11 @@ public static void main(String[] args) throws IOException, SAXException, ParserC public static class ValidationResult { public enum Severity { - WARNING, ERROR; + WARNING, ERROR } public enum Type { - HAS_MISSING_STOP_FACILITY, HAS_NO_LINK_REF, ROUTE_HAS_UNREACHABLE_STOP, OTHER; + HAS_MISSING_STOP_FACILITY, HAS_NO_LINK_REF, ROUTE_HAS_UNREACHABLE_STOP, OTHER } public static class ValidationIssue { diff --git a/matsim/src/main/java/org/matsim/run/ConvertOldPlanCalcScoreConfigGroup.java b/matsim/src/main/java/org/matsim/run/ConvertOldPlanCalcScoreConfigGroup.java index 449636b7a06..2e8d26fe5de 100644 --- a/matsim/src/main/java/org/matsim/run/ConvertOldPlanCalcScoreConfigGroup.java +++ b/matsim/src/main/java/org/matsim/run/ConvertOldPlanCalcScoreConfigGroup.java @@ -548,7 +548,7 @@ public void addActivityParams(final ActivityParams params) { super.addParameterSet( params ); } - public static enum TypicalDurationScoreComputation { uniform, relative } ; + public static enum TypicalDurationScoreComputation { uniform, relative } /* complex classes */ public static class ActivityParams extends ReflectiveConfigGroup implements MatsimParameters { diff --git a/matsim/src/main/java/org/matsim/run/gui/ExeRunner.java b/matsim/src/main/java/org/matsim/run/gui/ExeRunner.java index ea7125f3226..8e2f94c3109 100644 --- a/matsim/src/main/java/org/matsim/run/gui/ExeRunner.java +++ b/matsim/src/main/java/org/matsim/run/gui/ExeRunner.java @@ -138,7 +138,7 @@ public void run() { log.info("got interrupted while waiting for errorHandler to die.", e); } } catch (IOException e) { - e.printStackTrace(); + log.error("problem running executable.", e); this.erg = -2; } } @@ -170,8 +170,7 @@ public void run() { } } } catch (IOException e) { - log.info("StreamHandler got interrupted"); - e.printStackTrace(); + log.info("StreamHandler got interrupted", e); } } } diff --git a/matsim/src/main/java/org/matsim/utils/eventsfilecomparison/Worker.java b/matsim/src/main/java/org/matsim/utils/eventsfilecomparison/Worker.java index 363b3a02aef..004a0a5e347 100644 --- a/matsim/src/main/java/org/matsim/utils/eventsfilecomparison/Worker.java +++ b/matsim/src/main/java/org/matsim/utils/eventsfilecomparison/Worker.java @@ -32,7 +32,6 @@ import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.events.Event; import org.matsim.core.api.experimental.events.EventsManager; -import org.matsim.core.events.EventsUtils; import org.matsim.core.events.MatsimEventsReader; import org.matsim.core.events.SingleHandlerEventsManager; import org.matsim.core.events.handler.BasicEventHandler; diff --git a/matsim/src/main/java/org/matsim/utils/objectattributes/ObjectAttributesXmlReader.java b/matsim/src/main/java/org/matsim/utils/objectattributes/ObjectAttributesXmlReader.java index 6a4b7b62e2a..222a0c3b303 100644 --- a/matsim/src/main/java/org/matsim/utils/objectattributes/ObjectAttributesXmlReader.java +++ b/matsim/src/main/java/org/matsim/utils/objectattributes/ObjectAttributesXmlReader.java @@ -25,22 +25,13 @@ import static org.matsim.utils.objectattributes.ObjectAttributesXmlWriter.TAG_ATTRIBUTE; import static org.matsim.utils.objectattributes.ObjectAttributesXmlWriter.TAG_OBJECT; -import java.util.HashMap; -import java.util.HashSet; import java.util.Map; -import java.util.Set; import java.util.Stack; import com.google.inject.Inject; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.core.utils.io.MatsimXmlParser; -import org.matsim.utils.objectattributes.attributeconverters.BooleanConverter; -import org.matsim.utils.objectattributes.attributeconverters.DoubleConverter; -import org.matsim.utils.objectattributes.attributeconverters.FloatConverter; -import org.matsim.utils.objectattributes.attributeconverters.IntegerConverter; -import org.matsim.utils.objectattributes.attributeconverters.LongConverter; -import org.matsim.utils.objectattributes.attributeconverters.StringConverter; import org.xml.sax.Attributes; import org.xml.sax.SAXException; diff --git a/matsim/src/main/java/org/matsim/utils/objectattributes/ObjectAttributesXmlWriter.java b/matsim/src/main/java/org/matsim/utils/objectattributes/ObjectAttributesXmlWriter.java index 8955547cdef..1d3a468f2ef 100644 --- a/matsim/src/main/java/org/matsim/utils/objectattributes/ObjectAttributesXmlWriter.java +++ b/matsim/src/main/java/org/matsim/utils/objectattributes/ObjectAttributesXmlWriter.java @@ -68,9 +68,7 @@ public void writeFile(final String filename) throws UncheckedIOException { xmlAttributes.clear(); // sort attributes by name Map objAttributes = new TreeMap(); - for (Map.Entry objAttribute : entry.getValue().entrySet()) { - objAttributes.put(objAttribute.getKey(), objAttribute.getValue()); - } + objAttributes.putAll(entry.getValue()); // write attributes for (Map.Entry objAttribute : objAttributes.entrySet()) { Class clazz = objAttribute.getValue().getClass(); diff --git a/matsim/src/main/java/org/matsim/utils/objectattributes/attributable/AttributesXmlReaderDelegate.java b/matsim/src/main/java/org/matsim/utils/objectattributes/attributable/AttributesXmlReaderDelegate.java index 328679b0e00..289946f1278 100644 --- a/matsim/src/main/java/org/matsim/utils/objectattributes/attributable/AttributesXmlReaderDelegate.java +++ b/matsim/src/main/java/org/matsim/utils/objectattributes/attributable/AttributesXmlReaderDelegate.java @@ -24,8 +24,6 @@ import java.util.Map; import java.util.Stack; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.matsim.core.gbl.Gbl; import org.matsim.utils.objectattributes.AttributeConverter; import org.matsim.utils.objectattributes.ObjectAttributesConverter; diff --git a/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/CoordArrayConverter.java b/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/CoordArrayConverter.java index 317a10de223..a38afa9a3a3 100644 --- a/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/CoordArrayConverter.java +++ b/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/CoordArrayConverter.java @@ -20,12 +20,9 @@ package org.matsim.utils.objectattributes.attributeconverters; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Coord; import org.matsim.utils.objectattributes.AttributeConverter; -import java.util.Locale; - public class CoordArrayConverter implements AttributeConverter { // [(X1;Y1),(X2;Y2),...,(Xn;Yn)] diff --git a/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/CoordConverter.java b/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/CoordConverter.java index 3326a4d924d..1cc9e40d77e 100644 --- a/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/CoordConverter.java +++ b/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/CoordConverter.java @@ -26,8 +26,6 @@ import org.matsim.api.core.v01.Coord; import org.matsim.utils.objectattributes.AttributeConverter; -import java.util.Locale; - public class CoordConverter implements AttributeConverter { private final Logger log = LogManager.getLogger(CoordConverter.class); @@ -46,7 +44,7 @@ public String convertToString(Object o) { return null; } Coord c = (Coord)o; - + return String.format("(%s;%s)", Double.toString(c.getX()), Double.toString(c.getY())); } diff --git a/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/DoubleArrayConverter.java b/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/DoubleArrayConverter.java index cae3244c0dc..26d47731341 100644 --- a/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/DoubleArrayConverter.java +++ b/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/DoubleArrayConverter.java @@ -22,7 +22,6 @@ */ import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.matsim.utils.objectattributes.AttributeConverter; public class DoubleArrayConverter implements AttributeConverter { diff --git a/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/StringCollectionConverter.java b/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/StringCollectionConverter.java index 6c6dc398c04..3d217087de5 100644 --- a/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/StringCollectionConverter.java +++ b/matsim/src/main/java/org/matsim/utils/objectattributes/attributeconverters/StringCollectionConverter.java @@ -8,7 +8,6 @@ import java.util.Collection; import java.util.Collections; -import java.util.Map; public class StringCollectionConverter implements AttributeConverter> { diff --git a/matsim/src/main/java/org/matsim/vehicles/Vehicles.java b/matsim/src/main/java/org/matsim/vehicles/Vehicles.java index 5515e969f61..4cd16be51e1 100644 --- a/matsim/src/main/java/org/matsim/vehicles/Vehicles.java +++ b/matsim/src/main/java/org/matsim/vehicles/Vehicles.java @@ -23,8 +23,6 @@ import org.matsim.api.core.v01.Id; import org.matsim.core.api.internal.MatsimToplevelContainer; -import org.matsim.utils.objectattributes.FailingObjectAttributes; -import org.matsim.utils.objectattributes.ObjectAttributes; /** diff --git a/matsim/src/main/java/org/matsim/vehicles/VehiclesFactory.java b/matsim/src/main/java/org/matsim/vehicles/VehiclesFactory.java index 0e97d7e49bb..4442578c906 100644 --- a/matsim/src/main/java/org/matsim/vehicles/VehiclesFactory.java +++ b/matsim/src/main/java/org/matsim/vehicles/VehiclesFactory.java @@ -21,7 +21,6 @@ import org.matsim.api.core.v01.Id; import org.matsim.core.api.internal.MatsimFactory; -import org.matsim.vehicles.EngineInformation.FuelType; public interface VehiclesFactory extends MatsimFactory { diff --git a/matsim/src/main/java/org/matsim/vis/snapshotwriters/SnapshotWriterManager.java b/matsim/src/main/java/org/matsim/vis/snapshotwriters/SnapshotWriterManager.java index b5c7325377a..29fd7b39621 100644 --- a/matsim/src/main/java/org/matsim/vis/snapshotwriters/SnapshotWriterManager.java +++ b/matsim/src/main/java/org/matsim/vis/snapshotwriters/SnapshotWriterManager.java @@ -20,7 +20,6 @@ package org.matsim.vis.snapshotwriters; -import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.network.Link; @@ -87,7 +86,7 @@ public void notifyMobsimAfterSimStep(MobsimAfterSimStepEvent e) { doSnapshot(time, (VisMobsim) e.getQueueSimulation()); } } - + private void doSnapshot(final double time, VisMobsim visMobsim) { if (!this.snapshotWriters.isEmpty()) { diff --git a/matsim/src/main/java/org/matsim/vis/snapshotwriters/TransimsSnapshotWriter.java b/matsim/src/main/java/org/matsim/vis/snapshotwriters/TransimsSnapshotWriter.java index c39a94a1ed5..eca46681519 100644 --- a/matsim/src/main/java/org/matsim/vis/snapshotwriters/TransimsSnapshotWriter.java +++ b/matsim/src/main/java/org/matsim/vis/snapshotwriters/TransimsSnapshotWriter.java @@ -34,8 +34,8 @@ public class TransimsSnapshotWriter implements SnapshotWriter { private BufferedWriter out = null; private double currentTime = -1; - - public static enum Labels { TIME, VEHICLE, EASTING, NORTHING, VELOCITY } ; + + public static enum Labels { TIME, VEHICLE, EASTING, NORTHING, VELOCITY } public TransimsSnapshotWriter(String filename) { try { diff --git a/matsim/src/main/java/org/matsim/vis/snapshotwriters/TransimsSnapshotWriterFactory.java b/matsim/src/main/java/org/matsim/vis/snapshotwriters/TransimsSnapshotWriterFactory.java index f9ba42b2b42..aef0e84558c 100644 --- a/matsim/src/main/java/org/matsim/vis/snapshotwriters/TransimsSnapshotWriterFactory.java +++ b/matsim/src/main/java/org/matsim/vis/snapshotwriters/TransimsSnapshotWriterFactory.java @@ -21,11 +21,9 @@ package org.matsim.vis.snapshotwriters; import com.google.inject.Inject; -import org.matsim.core.controler.ControlerI; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.replanning.ReplanningContext; -import jakarta.inject.Named; import jakarta.inject.Provider; class TransimsSnapshotWriterFactory implements Provider { diff --git a/matsim/src/main/java/org/matsim/vis/snapshotwriters/VisMobsim.java b/matsim/src/main/java/org/matsim/vis/snapshotwriters/VisMobsim.java index df481b86d5f..705841598b9 100644 --- a/matsim/src/main/java/org/matsim/vis/snapshotwriters/VisMobsim.java +++ b/matsim/src/main/java/org/matsim/vis/snapshotwriters/VisMobsim.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.vis.snapshotwriters; @@ -48,8 +45,8 @@ public interface VisMobsim extends ObservableMobsim { * since java does not have multi-maps. Which means that we come back to the question of what should be in here and what not. * For that reason, it is just a Collection.
  • * kai, aug'10 - * - * changed to Map for that works better with queries in OTFVis + * + * changed to Map for that works better with queries in OTFVis */ Map, MobsimAgent> getAgents(); diff --git a/matsim/src/main/java/org/matsim/vis/snapshotwriters/VisVehicle.java b/matsim/src/main/java/org/matsim/vis/snapshotwriters/VisVehicle.java index e67ab9ffe47..6a0f0ca3ff7 100644 --- a/matsim/src/main/java/org/matsim/vis/snapshotwriters/VisVehicle.java +++ b/matsim/src/main/java/org/matsim/vis/snapshotwriters/VisVehicle.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.vis.snapshotwriters; import org.matsim.api.core.v01.Identifiable; @@ -33,14 +30,14 @@ * */ public interface VisVehicle extends Identifiable { - + /** * @return the Vehicle that this simulation vehicle represents */ Vehicle getVehicle(); MobsimDriverAgent getDriver() ; - + double getSizeInEquivalents() ; } diff --git a/matsim/src/main/java/org/matsim/visum/VisumNetworkReader.java b/matsim/src/main/java/org/matsim/visum/VisumNetworkReader.java index 866ff295215..932602bf943 100644 --- a/matsim/src/main/java/org/matsim/visum/VisumNetworkReader.java +++ b/matsim/src/main/java/org/matsim/visum/VisumNetworkReader.java @@ -24,6 +24,7 @@ import java.io.IOException; import java.io.UncheckedIOException; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -155,7 +156,7 @@ public VisumNetworkReader(final VisumNetwork network) { } public void read(final String filename) throws UncheckedIOException { - BufferedReader reader = IOUtils.getBufferedReader(IOUtils.getFileUrl(filename), Charset.forName("ISO-8859-1")); + BufferedReader reader = IOUtils.getBufferedReader(IOUtils.getFileUrl(filename), StandardCharsets.ISO_8859_1); try { String line = reader.readLine(); diff --git a/matsim/src/main/java/org/matsim/withinday/controller/WithinDayConfigGroup.java b/matsim/src/main/java/org/matsim/withinday/controller/WithinDayConfigGroup.java index ca457ce5138..d83807df143 100644 --- a/matsim/src/main/java/org/matsim/withinday/controller/WithinDayConfigGroup.java +++ b/matsim/src/main/java/org/matsim/withinday/controller/WithinDayConfigGroup.java @@ -19,9 +19,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.withinday.controller; import java.util.Map; @@ -38,23 +35,23 @@ public final class WithinDayConfigGroup extends ReflectiveConfigGroup { public WithinDayConfigGroup() { super(GROUP_NAME); } - - // --- + // --- + // --- + + // yyyy I cannot say yet if this should restrict to "TravelTimePrediction". Probably yes. Needs to be decided before escalated to xml config. kai, may'17 + + public enum ShortTermPredictionMethod { currentSpeeds } - // yyyy I cannot say yet if this should restrict to "TravelTimePrediction". Probably yes. Needs to be decided before escalated to xml config. kai, may'17 - - public enum ShortTermPredictionMethod { currentSpeeds } - ShortTermPredictionMethod predictionMethod = ShortTermPredictionMethod.currentSpeeds ; // I think this is what the original code does: use "current" travel times (whatever that means; I still need to find out). kai, may'17 - + @SuppressWarnings("unused") private static final String SHORT_TERM_PREDICTION_METHOD_CMT="method to predict travel times for the future" ; /** * {@value #SHORT_TERM_PREDICTION_METHOD_CMT} - * + * * @return the predictionMethod */ public ShortTermPredictionMethod getPredictionMethod() { @@ -62,7 +59,7 @@ public ShortTermPredictionMethod getPredictionMethod() { } /** * {@value #SHORT_TERM_PREDICTION_METHOD_CMT} - * + * * @param predictionMethod the predictionMethod to set */ public void setPredictionMethod(ShortTermPredictionMethod predictionMethod) { @@ -71,7 +68,7 @@ public void setPredictionMethod(ShortTermPredictionMethod predictionMethod) { // --- // --- - + @Override public Map getComments() { Map comments = super.getComments(); return comments ; diff --git a/matsim/src/main/java/org/matsim/withinday/mobsim/MobsimDataProvider.java b/matsim/src/main/java/org/matsim/withinday/mobsim/MobsimDataProvider.java index 41949ff0a3b..c9e1bbe13c6 100644 --- a/matsim/src/main/java/org/matsim/withinday/mobsim/MobsimDataProvider.java +++ b/matsim/src/main/java/org/matsim/withinday/mobsim/MobsimDataProvider.java @@ -29,14 +29,11 @@ import org.matsim.core.mobsim.framework.listeners.MobsimInitializedListener; import org.matsim.core.mobsim.qsim.QSim; import org.matsim.core.mobsim.qsim.interfaces.MobsimVehicle; -import org.matsim.core.mobsim.qsim.interfaces.NetsimLink; -import org.matsim.core.mobsim.qsim.interfaces.NetsimNetwork; import org.matsim.vehicles.Vehicle; import jakarta.inject.Inject; import jakarta.inject.Singleton; import java.util.Collection; -import java.util.HashMap; import java.util.Map; /** diff --git a/matsim/src/main/java/org/matsim/withinday/replanning/identifiers/filter/ActivityStartingFilter.java b/matsim/src/main/java/org/matsim/withinday/replanning/identifiers/filter/ActivityStartingFilter.java index f24a68f5e7a..5bac65010c6 100644 --- a/matsim/src/main/java/org/matsim/withinday/replanning/identifiers/filter/ActivityStartingFilter.java +++ b/matsim/src/main/java/org/matsim/withinday/replanning/identifiers/filter/ActivityStartingFilter.java @@ -25,7 +25,6 @@ import java.util.Set; import org.matsim.api.core.v01.Id; -import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Person; import org.matsim.core.mobsim.framework.DriverAgent; import org.matsim.core.mobsim.framework.MobsimAgent; @@ -34,35 +33,35 @@ /** * Remove all agents from the set that are going to start an activity on * their current link. - * + * * @author cdobler */ public class ActivityStartingFilter implements AgentFilter { private final Map, MobsimAgent> agents; - + // use the factory /*package*/ ActivityStartingFilter(Map, MobsimAgent> agents) { this.agents = agents; } - + @Override public void applyAgentFilter(Set> set, double time) { Iterator> iter = set.iterator(); - + while (iter.hasNext()) { Id id = iter.next(); - + if (!this.applyAgentFilter(id, time)) iter.remove(); } } - + @Override public boolean applyAgentFilter(Id id, double time) { MobsimAgent agent = this.agents.get(id); // check whether the agent is performing a leg if (!(agent.getState() == MobsimAgent.State.LEG)) return false; - + /* * Check whether the agent ends its leg on the current link. If * yes, remove the agent from the set. @@ -71,8 +70,8 @@ public boolean applyAgentFilter(Id id, double time) { // Id nextLinkId = driver.chooseNextLinkId(); // if (nextLinkId == null) return false; if ( driver.isWantingToArriveOnCurrentLink() ) return false ; - + return true; } - + } diff --git a/matsim/src/main/java/org/matsim/withinday/replanning/replanners/InitialReplanner.java b/matsim/src/main/java/org/matsim/withinday/replanning/replanners/InitialReplanner.java index d38a43e36d6..436d7984a94 100644 --- a/matsim/src/main/java/org/matsim/withinday/replanning/replanners/InitialReplanner.java +++ b/matsim/src/main/java/org/matsim/withinday/replanning/replanners/InitialReplanner.java @@ -24,7 +24,6 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.core.mobsim.framework.MobsimAgent; import org.matsim.core.mobsim.qsim.ActivityEndRescheduler; -import org.matsim.core.mobsim.qsim.InternalInterface; import org.matsim.core.mobsim.qsim.agents.WithinDayAgentUtils; import org.matsim.core.router.PlanRouter; import org.matsim.withinday.replanning.replanners.interfaces.WithinDayInitialReplanner; @@ -38,7 +37,7 @@ public class InitialReplanner extends WithinDayInitialReplanner { private final PlanRouter planRouter; - + /*package*/ InitialReplanner(Id id, Scenario scenario, ActivityEndRescheduler internalInterface, PlanRouter planRouter) { super(id, scenario, internalInterface); this.planRouter = planRouter; @@ -46,8 +45,8 @@ public class InitialReplanner extends WithinDayInitialReplanner { @Override public boolean doReplanning(MobsimAgent withinDayAgent) { - + this.planRouter.run(WithinDayAgentUtils.getModifiablePlan(withinDayAgent)); return true; } -} \ No newline at end of file +} diff --git a/matsim/src/main/java/org/matsim/withinday/replanning/replanners/interfaces/WithinDayDuringLegReplanner.java b/matsim/src/main/java/org/matsim/withinday/replanning/replanners/interfaces/WithinDayDuringLegReplanner.java index 412083a499e..cc7b05d154e 100644 --- a/matsim/src/main/java/org/matsim/withinday/replanning/replanners/interfaces/WithinDayDuringLegReplanner.java +++ b/matsim/src/main/java/org/matsim/withinday/replanning/replanners/interfaces/WithinDayDuringLegReplanner.java @@ -23,7 +23,6 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; import org.matsim.core.mobsim.qsim.ActivityEndRescheduler; -import org.matsim.core.mobsim.qsim.InternalInterface; import org.matsim.withinday.replanning.identifiers.interfaces.DuringLegAgentSelector; /* @@ -34,5 +33,5 @@ public abstract class WithinDayDuringLegReplanner extends WithinDayReplanner id, Scenario scenario, ActivityEndRescheduler internalInterface) { super(id, scenario, internalInterface); } - + } diff --git a/matsim/src/main/java/org/matsim/withinday/replanning/replanners/interfaces/WithinDayInitialReplanner.java b/matsim/src/main/java/org/matsim/withinday/replanning/replanners/interfaces/WithinDayInitialReplanner.java index b74cd76df48..e35f078b7e0 100644 --- a/matsim/src/main/java/org/matsim/withinday/replanning/replanners/interfaces/WithinDayInitialReplanner.java +++ b/matsim/src/main/java/org/matsim/withinday/replanning/replanners/interfaces/WithinDayInitialReplanner.java @@ -23,7 +23,6 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; import org.matsim.core.mobsim.qsim.ActivityEndRescheduler; -import org.matsim.core.mobsim.qsim.InternalInterface; import org.matsim.withinday.replanning.identifiers.interfaces.InitialIdentifier; /* @@ -34,5 +33,5 @@ public abstract class WithinDayInitialReplanner extends WithinDayReplanner id, Scenario scenario, ActivityEndRescheduler internalInterface) { super(id, scenario, internalInterface); } - + } diff --git a/matsim/src/main/java/org/matsim/withinday/replanning/replanners/interfaces/WithinDayReplannerFactory.java b/matsim/src/main/java/org/matsim/withinday/replanning/replanners/interfaces/WithinDayReplannerFactory.java index ca049e10d23..1ddd01f5a39 100644 --- a/matsim/src/main/java/org/matsim/withinday/replanning/replanners/interfaces/WithinDayReplannerFactory.java +++ b/matsim/src/main/java/org/matsim/withinday/replanning/replanners/interfaces/WithinDayReplannerFactory.java @@ -26,7 +26,6 @@ import org.matsim.api.core.v01.Id; import org.matsim.core.mobsim.qsim.ActivityEndReschedulerProvider; -import org.matsim.withinday.mobsim.WithinDayEngine; import org.matsim.withinday.replanning.identifiers.interfaces.AgentSelector; import org.matsim.withinday.replanning.replanners.tools.ReplanningIdGenerator; @@ -35,30 +34,30 @@ public abstract class WithinDayReplannerFactory { private final ActivityEndReschedulerProvider withinDayEngine; private Id id; private Set identifiers = new HashSet(); - + public WithinDayReplannerFactory(ActivityEndReschedulerProvider withinDayEngine) { this.withinDayEngine = withinDayEngine; this.id = ReplanningIdGenerator.getNextId(); } - + public abstract WithinDayReplanner createReplanner(); - + public final ActivityEndReschedulerProvider getWithinDayEngine() { return this.withinDayEngine; } - + public final Id getId() { return this.id; } - + public final boolean addIdentifier(T identifier) { return this.identifiers.add(identifier); } - + public final boolean removeIdentifier(T identifier) { return this.identifiers.remove(identifier); } - + public final Set getIdentifers() { return Collections.unmodifiableSet(identifiers); } diff --git a/matsim/src/main/java/org/matsim/withinday/utils/EditPlans.java b/matsim/src/main/java/org/matsim/withinday/utils/EditPlans.java index 9ffc19497e6..329f9283f5e 100644 --- a/matsim/src/main/java/org/matsim/withinday/utils/EditPlans.java +++ b/matsim/src/main/java/org/matsim/withinday/utils/EditPlans.java @@ -69,21 +69,21 @@ public boolean addActivityAtEnd(MobsimAgent agent, Activity activity, String rou Plan plan = WithinDayAgentUtils.getModifiablePlan(agent); List planElements = plan.getPlanElements(); - + boolean retVal1 = false; - + if (isAtRealActivity(agent)) { retVal1 = planElements.add(pf.createLeg(routingMode)); } - + final boolean retVal = planElements.add(activity); // (need the terminating activity in order to find the current trip. kai, nov'17) - + if (!isAtRealActivity(agent)) { retVal1 = editTrips.replanCurrentTrip(agent,mobsim.getSimTimer().getTimeOfDay(),routingMode); } - - + + WithinDayAgentUtils.resetCaches(agent); this.mobsim.rescheduleActivityEnd(agent); return (retVal1 && retVal); @@ -105,7 +105,7 @@ public PlanElement removeActivity(MobsimAgent agent, int index, String mode) { throw new ReplanningException("mode not given and mode before removed activity != mode after removed activity; don't know which mode to use") ; } } - PlanElement pe = planElements.remove(index) ; + PlanElement pe = planElements.remove(index) ; if ( checkIfTripHasAlreadyStarted( agent, tripBefore.getTripElements() ) ) { editTrips.replanCurrentTrip(agent, mobsim.getSimTimer().getTimeOfDay() , mode); } else { @@ -128,8 +128,8 @@ public final Activity replaceActivity(MobsimAgent agent, int index, Activity new Plan plan = WithinDayAgentUtils.getModifiablePlan(agent) ; WithinDayAgentUtils.printPlan(plan) ; System.err.println("here330"); - - + + List planElements = plan.getPlanElements() ; // make sure we have indeed an activity position: @@ -207,13 +207,13 @@ public void insertActivity(MobsimAgent agent, int index, Activity activity, Stri if ( actAfter != null ) { EditTrips.insertEmptyTrip(plan, activity, actAfter, downstreamMode, pf ) ; } - } + } WithinDayAgentUtils.resetCaches(agent); this.mobsim.rescheduleActivityEnd(agent); } - + // === convenience methods: === - /** + /** * Convenience method, clarifying that this can be called without giving the mode. */ public PlanElement removeActivity(MobsimAgent agent, int index) { @@ -268,7 +268,7 @@ private static void checkIfSameMode(String upstreamMode, final String currentMod public static Activity findRealActAfter(MobsimAgent agent, int index) { Plan plan = WithinDayAgentUtils.getModifiablePlan(agent) ; List planElements = plan.getPlanElements() ; - return (Activity) planElements.get( findIndexOfRealActAfter(agent, index) ) ; + return (Activity) planElements.get( findIndexOfRealActAfter(agent, index) ) ; } public static int findIndexOfRealActAfter(MobsimAgent agent, int index) { Plan plan = WithinDayAgentUtils.getModifiablePlan(agent) ; @@ -310,7 +310,7 @@ public static Activity findRealActBefore(MobsimAgent agent, int index) { // } // return hereFacility; // } - + public void rescheduleActivityEnd(MobsimAgent agent) { // this is mostly for retrofitting existing code. but maybe also useful by itself this.mobsim.rescheduleActivityEnd(agent); @@ -326,7 +326,7 @@ public boolean isAtRealActivity(MobsimAgent agent) { public boolean isRealActivity(PlanElement pe) { return pe instanceof Activity && ! ( StageActivityTypeIdentifier.isStageActivity( ((Activity)pe).getType() ) ); } - + public String getModeOfCurrentOrNextTrip(MobsimAgent agent) { Trip trip ; if ( isAtRealActivity( agent ) ) { @@ -348,9 +348,9 @@ public void rescheduleCurrentActivityEndtime(MobsimAgent agent, double newEndTim Integer index = WithinDayAgentUtils.getCurrentPlanElementIndex(agent) ; this.rescheduleActivityEndtime(agent, index, newEndTime); } - + public Activity createFinalActivity(String type, Id newLinkId) { - Activity newAct = this.pf.createActivityFromLinkId(type, newLinkId);; + Activity newAct = this.pf.createActivityFromLinkId(type, newLinkId); newAct.setEndTime( Double.POSITIVE_INFINITY ) ; return newAct ; } diff --git a/matsim/src/main/java/org/matsim/withinday/utils/EditRoutes.java b/matsim/src/main/java/org/matsim/withinday/utils/EditRoutes.java index bb94f567102..39ee1239053 100644 --- a/matsim/src/main/java/org/matsim/withinday/utils/EditRoutes.java +++ b/matsim/src/main/java/org/matsim/withinday/utils/EditRoutes.java @@ -55,12 +55,12 @@ * */ public final class EditRoutes { - // I think that this class is now for the time being (nov'17) roughly ok: The pure replanning calls just find a possibly + // I think that this class is now for the time being (nov'17) roughly ok: The pure replanning calls just find a possibly // different path to the same destination, which is ok. The relocate calls are marked as "deprecated" to discourage use, // but they are still ok if the user knows what she/he is doing; evidently, with access/egress routing, they will lead to // disconnected trips. kai, nov'17 - - + + /* * Design thoughts while adding access/egress walk legs to car trips: * . Matsim has a computer science router (LeastCostPathCalculator, from node to node) and a behavioral router (RoutingModule, from @@ -69,12 +69,12 @@ public final class EditRoutes { * . So it seems that for replanCurrentRoute, the computer science router makes more sense. * . This is, however, not true for all the relocate calls, since they also need to reroute the egress leg. * yyyy So, in short: all the relocate methods need to be adapted. For "future", this is easy. For "current", the splicing needs to be re-done. kai, dec'15 - * - * Hm, next thought: It is not fully clear how relocateXxx has worked in the past, since also there the succeeding activity would + * + * Hm, next thought: It is not fully clear how relocateXxx has worked in the past, since also there the succeeding activity would * have needed adaptation. So in the end the method should just do what it promises (i.e. modify a single leg), and not * think too much about its context. (In the end, will presumably retrofit the mobsim in a way that it is able to process also the * old car trips.) - */ + */ private static final Logger log = LogManager.getLogger(EditRoutes.class); @@ -103,11 +103,11 @@ public EditRoutes( Network network, LeastCostPathCalculator pathCalculator, Popu /** * Re-locates a future route. The route is given by its leg. It just replaces the route for the given leg, without looking after * overall plan consistency. - * + * * @return true when replacing the route worked, false when something went wrong - * + * */ - @Deprecated // not consistent with access/egress approach; can only be used if you know exactly what you are doing. + @Deprecated // not consistent with access/egress approach; can only be used if you know exactly what you are doing. // Maybe replanXxx (which does not have these problems) is already sufficient? Otherwise use EditTrips or EditPlans. kai, nov'17 public boolean relocateFutureLegRoute(Leg leg, Id fromLinkId, Id toLinkId, Person person ) { @@ -127,7 +127,7 @@ public boolean relocateFutureLegRoute(Leg leg, Id fromLinkId, Id toL route.setTravelCost(path.travelCost); route.setDistance(RouteUtils.calcDistance(route,1.,1., this.network)); leg.setRoute(route); - + return true; } @@ -144,16 +144,16 @@ public final void replanCurrentLeg( MobsimAgent agent, double now ) { /** * Re-locates a future route. The route is given by its leg. - * + * * @return true when replacing the route worked, false when something went wrong - * + * * @deprecated switch this to relocateFutureTrip, since with egress legs relocating the destination of a single leg leads to disconnected trips. kai, dec'15 */ - @Deprecated // not consistent with access/egress approach; can only be used if you know exactly what you are doing. + @Deprecated // not consistent with access/egress approach; can only be used if you know exactly what you are doing. // Maybe replanXxx is already sufficient? Otherwise use EditTrips or EditPlans. kai, nov'17 public static boolean relocateFutureLegRoute(Leg leg, Id fromLinkId, Id toLinkId, Person person, Network network, TripRouter tripRouter, Activity fromActivity) { // TripRouter variant; everything else uses the PathCalculator - + Link fromLink = network.getLinks().get(fromLinkId); Link toLink = network.getLinks().get(toLinkId); @@ -165,7 +165,7 @@ public static boolean relocateFutureLegRoute(Leg leg, Id fromLinkId, Id
  • fromLinkId, Id
  • fromLinkId, Id
  • toLinkId, double time ) { @@ -262,17 +262,17 @@ public boolean relocateCurrentLegRoute(Leg leg, Person person, int currentLinkIn Vehicle vehicle = null ; Path path = this.pathCalculator.calcLeastCostPath(startLink.getToNode(), endLink.getFromNode(), time, person, vehicle) ; - + spliceNewPathIntoOldRoute(currentLinkIndex, toLinkId, oldRoute, NetworkUtils.getLinkIds(path.links), currentLinkId) ; return true; } - + static void spliceNewPathIntoOldRoute(int currentLinkIndex, Id toLinkId, NetworkRoute oldRoute, List> newLinksIds, Id currentLinkId) { - List> oldLinkIds = oldRoute.getLinkIds();; + List> oldLinkIds = oldRoute.getLinkIds(); List> resultingLinkIds = new ArrayList<>(); - + // REMEMBER: the "currentLinkIndex" does not point to the current position, but one beyond. Probably // because there is a starting link, which is not part of getLinkIds(). @@ -295,7 +295,7 @@ static void spliceNewPathIntoOldRoute(int currentLinkIndex, Id toLinkId, N // (this happens if the agent is still on the departure link: that is not part of getLinkIds(). Otherwise: ) resultingLinkIds.add(currentLinkId); } - + // Merge old and new Route. /* * Edit cdobler 25.5.2010 @@ -312,9 +312,9 @@ static void spliceNewPathIntoOldRoute(int currentLinkIndex, Id toLinkId, N ) { resultingLinkIds.remove( resultingLinkIds.size()-1 ); } - + resultingLinkIds.addAll( newLinksIds ) ; - + StringBuilder strb = new StringBuilder() ; for ( int ii= Math.max(0,currentLinkIndex-2) ; ii < Math.min( resultingLinkIds.size(), currentLinkIndex+3) ; ii++ ) { strb.append("-") ; @@ -322,7 +322,7 @@ static void spliceNewPathIntoOldRoute(int currentLinkIndex, Id toLinkId, N strb.append("-") ; } log.info( "linkIds at join: " + strb ) ; - + // Overwrite old Route oldRoute.setLinkIds(oldRoute.getStartLinkId(), resultingLinkIds, toLinkId ); } @@ -373,14 +373,14 @@ public boolean replanCurrentLegRoute(Leg leg, Person person, int currentLinkInd return false; } // (cannot move the above test down into relocateCurrentLegRoute, since it also hedges against route==null. kai, nov'17) - + return relocateCurrentLegRoute(leg, person, currentLinkIndex, route.getEndLinkId(), time ); } - + public final LeastCostPathCalculator getPathCalculator() { return pathCalculator; } - + // ######################################################################################### // helper methods below diff --git a/matsim/src/main/java/org/matsim/withinday/utils/EditTrips.java b/matsim/src/main/java/org/matsim/withinday/utils/EditTrips.java index 36f4776cbee..db8f3521cfc 100644 --- a/matsim/src/main/java/org/matsim/withinday/utils/EditTrips.java +++ b/matsim/src/main/java/org/matsim/withinday/utils/EditTrips.java @@ -18,9 +18,6 @@ * * * *********************************************************************** */ - /** - * - */ package org.matsim.withinday.utils; import java.util.ArrayList; @@ -79,7 +76,7 @@ * At some places the code now sets a travel time which is not really correct because the real value is hard to obtain. * Still a defined value at least keeps the simulation running. This should be fixed with look-ups in the transit * schedule when exactly the agent arrives at the next stop and can disembark. vsp-gleich nov'21 - * + * * @author kainagel */ public final class EditTrips { @@ -110,7 +107,7 @@ public EditTrips( TripRouter tripRouter, Scenario scenario, InternalInterface in } } } - + this.tripRouter = tripRouter; this.scenario = scenario; this.pf = scenario.getPopulation().getFactory() ; @@ -149,7 +146,7 @@ public final boolean replanCurrentTrip(MobsimAgent agent, double now, String rou // I will treat this here in the way that it will make the trip consistent with the activities. So if the activity in the // plan has changed, the trip will go to a new location. - + // what matters is the external interface, which is the method call. Everything below is internal so it does not matter so much. Trip trip = findCurrentTrip( agent ) ; @@ -192,11 +189,11 @@ private void replanCurrentTripFromLeg(Activity newAct, final PlanElement current private void replanCurrentLegWithNetworkRoute(Activity newAct, String mainMode, Leg currentLeg, double now, MobsimAgent agent, Attributes routingAttributes) { log.debug("entering replanCurrentLegWithNetworkRoute for agent" + agent.getId()) ; - + Plan plan = WithinDayAgentUtils.getModifiablePlan(agent) ; List planElements = plan.getPlanElements() ; Person person = plan.getPerson() ; - + // (1) get new trip from current position to new activity: Link currentLink = scenario.getNetwork().getLinks().get( agent.getCurrentLinkId() ) ; Facility currentLocationFacility = FacilitiesUtils.wrapLink( currentLink ) ; @@ -285,7 +282,7 @@ private void replanCurrentLegWithTransitRoute(Activity newAct, String routingMod log.debug( "agent with ID=" + agent.getId() + " is waiting at a stop=" + currentOrNextStop ) ; newTripElements = newTripToNewActivity(currentOrNextStop, newAct, routingMode, now, person, routingAttributes ); Gbl.assertIf( newTripElements.get(0) instanceof Leg ); // that is what TripRouter should do. kai, jul'19 - + wantsToLeaveStop = true ; if (newTripElements.size() >= 2) { // check if the agent has a useless teleport leg from a transit stop to the very same stop @@ -312,7 +309,7 @@ private void replanCurrentLegWithTransitRoute(Activity newAct, String routingMod } } } - + // in all other cases leave the stop if (wantsToLeaveStop) { // The agent will not board any bus at the transit stop and will walk away or @@ -334,8 +331,8 @@ private void replanCurrentLegWithTransitRoute(Activity newAct, String routingMod * already departed and cannot be reached by the agent even though the agent is currently located on that very same * bus (which the router does not know :-( ) * We have no router or schedule data in "real time", i.e. considering delays, so lets assume that all pt departures - * are punctual. If we would route from the current time (= "now") instead, it is unclear how long it will take to - * arrive at the next stop and we risk that the agent misses the bus he is already riding on. - gl jul'19 + * are punctual. If we would route from the current time (= "now") instead, it is unclear how long it will take to + * arrive at the next stop and we risk that the agent misses the bus he is already riding on. - gl jul'19 */ double reRoutingTime; if (driver instanceof TransitDriverAgentImpl) { // this is ugly, but there seems to be no other way to find out the scheduled arrival time. Maybe add to interface? @@ -349,7 +346,7 @@ private void replanCurrentLegWithTransitRoute(Activity newAct, String routingMod log.debug( "agent with ID=" + agent.getId() + " is re-routed from next stop " + currentOrNextStop.getId() + " scheduled arrival at " + reRoutingTime); newTripElements = newTripToNewActivity(currentOrNextStop, newAct, routingMode, reRoutingTime, person, routingAttributes ); // yyyy as discussed elswhere, would make more sense to compute this once arrived at that stop. - + boolean agentStaysOnSameVehicle = false; if (newTripElements.size() >= 2) { // check if the agent has a useless teleport leg from a transit stop to the very same stop @@ -394,7 +391,7 @@ private void replanCurrentLegWithTransitRoute(Activity newAct, String routingMod } } } - + // in all other cases disembark at next stop if (!agentStaysOnSameVehicle) { newTripElements = defaultMergeOldAndNewCurrentPtLeg(currentLeg, newTripElements, agent, currentOrNextStop, oldPtRoute); @@ -504,14 +501,14 @@ private void replanCurrentLegWithGenericRoute(Activity newAct, String routingMod * before the activity and assumes instead that the agent starts the activity at the time passed as parameter and * calculates a suitable activity end time based on that start time. This is not useful here :-( * The end time of the previous activity is not updated when the agent departs for the leg. - * Leg departure time exists as variable but is -Infinity.... + * Leg departure time exists as variable but is -Infinity.... * So we have no clear and reliable information when the agent will finish its teleport leg. * Do some estimation and hope for a TODO better solution in the future :-( - * - gl jul'19 + * - gl jul'19 */ // double departureTime = PopulationUtils.decideOnActivityEndTime( nextAct, now, scenario.getConfig() ); Activity previousActivity = (Activity) plan.getPlanElements().get(currPosPlanElements - 1); - // We don't know where the agent is located on its teleport leg and when it will arrive. Let's assume the agent is + // We don't know where the agent is located on its teleport leg and when it will arrive. Let's assume the agent is // located half way between origin and destination of the teleport leg. double travelTime = timeInterpretation.decideOnLegTravelTime(currentLeg).seconds(); @@ -569,7 +566,7 @@ private void replanCurrentTripFromStageActivity(Trip trip, int tripElementsIndex String mainMode, double now, MobsimAgent agent) { log.debug("entering replanCurrentTripFromStageActivity for agent" + agent.getId()) ; - + Plan plan = WithinDayAgentUtils.getModifiablePlan(agent) ; List planElements = plan.getPlanElements() ; Person person = plan.getPerson() ; @@ -632,15 +629,15 @@ private static void replaceRemainderOfCurrentRoute(Leg currentLeg, List> newLinksIds = newNWRoute.getLinkIds().subList(0,newNWRoute.getLinkIds().size()) ; EditRoutes.spliceNewPathIntoOldRoute(currentRouteLinkIdIndex, newNWRoute.getEndLinkId(), oldNWRoute, newLinksIds, agent.getCurrentLinkId()) ; - + // for (int ii = currentRouteLinkIdIndex; ii defaultMergeOldAndNewCurrentPtLeg(Leg currentLeg, List // from that transit stop location to that very same transit stop. if (newCurrentLeg.getRoute() instanceof TransitPassengerRoute) { throw new RuntimeException(Gbl.NOT_IMPLEMENTED); - } + } // prune remaining route from current route: DefaultTransitPassengerRoute route = new DefaultTransitPassengerRoute( // @@ -714,7 +711,7 @@ private boolean transitRouteLaterStopsAt(Id lineId, Id replanFutureTrip(Trip trip, Plan plan, String routingMode, @@ -733,7 +730,7 @@ public static List replanFutureTrip(Trip trip, Plan plan, return PopulationUtils.createActivity((Activity) p); } else return p; }) - .collect(Collectors.toList());; + .collect(Collectors.toList()); TripRouter.insertTrip(plan, trip.getOriginActivity(), newTrip, trip.getDestinationActivity()); diff --git a/matsim/src/test/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroupTest.java b/matsim/src/test/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroupTest.java index d206be9f32b..277bb6f2dc6 100644 --- a/matsim/src/test/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroupTest.java +++ b/matsim/src/test/java/ch/sbb/matsim/config/SwissRailRaptorConfigGroupTest.java @@ -23,7 +23,6 @@ import ch.sbb.matsim.config.SwissRailRaptorConfigGroup.ModeMappingForPassengersParameterSet; import ch.sbb.matsim.config.SwissRailRaptorConfigGroup.RangeQuerySettingsParameterSet; import ch.sbb.matsim.config.SwissRailRaptorConfigGroup.RouteSelectorParameterSet; -import ch.sbb.matsim.routing.pt.raptor.RaptorStopFinder.Direction; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Assertions; @@ -33,6 +32,7 @@ import org.matsim.core.config.ConfigReader; import org.matsim.core.config.ConfigUtils; import org.matsim.core.config.ConfigWriter; +import org.matsim.testcases.MatsimTestUtils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -261,6 +261,25 @@ void testConfigIO_modeMappings() { Assertions.assertNull(config2.getModeMappingForPassengersParameterSet("road")); Assertions.assertNull(config2.getModeMappingForPassengersParameterSet("ship")); } + @Test + void testConfigIO_ModeToModePenalties() { + SwissRailRaptorConfigGroup config1 = new SwissRailRaptorConfigGroup(); + + { // prepare config1 + config1.setUseModeMappingForPassengers(true); + SwissRailRaptorConfigGroup.ModeToModeTransferPenalty penalty = new SwissRailRaptorConfigGroup.ModeToModeTransferPenalty(TransportMode.airplane,TransportMode.ship,100); + config1.addParameterSet(penalty); + } + + SwissRailRaptorConfigGroup config2 = writeRead(config1); + + // do checks + + SwissRailRaptorConfigGroup.ModeToModeTransferPenalty penalty = config2.getModeToModeTransferPenaltyParameterSets().get(0); + Assertions.assertEquals(penalty.transferPenalty,100.0, MatsimTestUtils.EPSILON); + Assertions.assertEquals(penalty.fromMode,TransportMode.airplane); + Assertions.assertEquals(penalty.toMode,TransportMode.ship); + } private SwissRailRaptorConfigGroup writeRead(SwissRailRaptorConfigGroup config) { Config fullConfig1 = ConfigUtils.createConfig(config); diff --git a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorTest.java b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorTest.java index 559a2970bf2..98431e35cc7 100644 --- a/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorTest.java +++ b/matsim/src/test/java/ch/sbb/matsim/routing/pt/raptor/SwissRailRaptorTest.java @@ -36,8 +36,8 @@ import org.matsim.api.core.v01.population.PlanElement; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.config.groups.ScoringConfigGroup.ModeParams; import org.matsim.core.config.groups.RoutingConfigGroup; +import org.matsim.core.config.groups.ScoringConfigGroup.ModeParams; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.population.routes.RouteUtils; import org.matsim.core.router.DefaultRoutingModules; @@ -53,13 +53,7 @@ import org.matsim.pt.router.TransitRouter; import org.matsim.pt.routes.TransitPassengerRoute; import org.matsim.pt.transitSchedule.TransitScheduleUtils; -import org.matsim.pt.transitSchedule.api.Departure; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitRoute; -import org.matsim.pt.transitSchedule.api.TransitRouteStop; -import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.pt.transitSchedule.api.TransitScheduleFactory; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; +import org.matsim.pt.transitSchedule.api.*; import org.matsim.testcases.MatsimTestUtils; import org.matsim.utils.objectattributes.attributable.AttributesImpl; @@ -68,8 +62,7 @@ import java.util.List; import java.util.function.Supplier; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * Most of these tests were copied from org.matsim.pt.router.TransitRouterImplTest @@ -343,6 +336,25 @@ void testLineChange() { CoordUtils.calcEuclideanDistance(f.schedule.getFacilities().get(Id.create("19", TransitStopFacility.class)).getCoord(), toCoord) / raptorParams.getBeelineWalkSpeed(); assertEquals(Math.ceil(expectedTravelTime), actualTravelTime, MatsimTestUtils.EPSILON); } + @Test + void testLineChangeWithDifferentUtils() { + Fixture f = new Fixture(); + f.init(); + f.blueLine.getRoutes().values().forEach(transitRoute -> transitRoute.setTransportMode(TransportMode.ship)); + SwissRailRaptorConfigGroup swissRailRaptorConfigGroup = ConfigUtils.addOrGetModule(f.config, SwissRailRaptorConfigGroup.class); + SwissRailRaptorConfigGroup.ModeToModeTransferPenalty trainToShip = new SwissRailRaptorConfigGroup.ModeToModeTransferPenalty("train",TransportMode.ship,1000000.0); + SwissRailRaptorConfigGroup.ModeToModeTransferPenalty shipToTrain = new SwissRailRaptorConfigGroup.ModeToModeTransferPenalty(TransportMode.ship,"train",1000000.0); + swissRailRaptorConfigGroup.addModeToModeTransferPenalty(trainToShip); + swissRailRaptorConfigGroup.addModeToModeTransferPenalty(shipToTrain); + swissRailRaptorConfigGroup.setTransferWalkMargin(0); + RaptorParameters raptorParams = RaptorUtils.createParameters(f.config); + TransitRouter router = createTransitRouter(f.schedule, f.config, f.network); + Coord fromCoord = new Coord(3800, 5100); + Coord toCoord = new Coord(16100, 10050); + List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(fromCoord), new FakeFacility(toCoord), 6.0*3600, null)); + //changing from train to ship is so expensive that direct walk is cheaper + assertNull(legs); + } @Test void testFasterAlternative() { @@ -481,7 +493,7 @@ void testCoordFarAway() { Fixture f = new Fixture(); f.init(); TransitRouter router = createTransitRouter(f.schedule, f.config, f.network); - double x = +42000; + double x = 42000; double x1 = -2000; List legs = router.calcRoute(DefaultRoutingRequest.withoutAttributes(new FakeFacility(new Coord(x1, 0)), new FakeFacility(new Coord(x, 0)), 5.5*3600, null)); // should map to stops A and I assertEquals(3, legs.size()); @@ -868,9 +880,8 @@ void testCustomTransferCostCalculator() { int[] transferCount = new int[] { 0 }; SwissRailRaptorData data = SwissRailRaptorData.create(f.schedule, null, RaptorUtils.createStaticConfig(f.config), f.scenario.getNetwork(), null); - SwissRailRaptor router = new Builder(data, f.config).with(new RaptorTransferCostCalculator() { - @Override - public double calcTransferCost(Supplier transfer, RaptorParameters raptorParams, int totalTravelTime, int totalTransferCount, double existingTransferCosts, double now) { + SwissRailRaptor router = new Builder(data, f.config).with((RaptorTransferCostCalculator) (currentPE, transfer, staticConfig, raptorParams, totalTravelTime, totalTransferCount, existingTransferCosts, currentTime) -> { + transferCount[0]++; Transfer t = transfer.get(); @@ -882,7 +893,7 @@ public double calcTransferCost(Supplier transfer, RaptorParameters rap assertEquals(Id.create("2to3", TransitRoute.class), t.getToTransitRoute().getId()); return 0.5; - } + }).build(); Coord fromCoord = f.fromFacility.getCoord(); diff --git a/matsim/src/test/java/org/matsim/analysis/IterationTravelStatsControlerListenerTest.java b/matsim/src/test/java/org/matsim/analysis/IterationTravelStatsControlerListenerTest.java index 1757e6a3f99..e4c49caed4b 100644 --- a/matsim/src/test/java/org/matsim/analysis/IterationTravelStatsControlerListenerTest.java +++ b/matsim/src/test/java/org/matsim/analysis/IterationTravelStatsControlerListenerTest.java @@ -81,13 +81,13 @@ void testIterationTravelStatsControlerListener() { Scenario scenario = ScenarioUtils.createScenario(config); - Person person1 = PopulationUtils.getFactory().createPerson(Id.create("1", Person.class));; + Person person1 = PopulationUtils.getFactory().createPerson(Id.create("1", Person.class)); person1.addPlan(plan1); - Person person2 = PopulationUtils.getFactory().createPerson(Id.create("2", Person.class));; + Person person2 = PopulationUtils.getFactory().createPerson(Id.create("2", Person.class)); person2.addPlan(plan2); - Person person3 = PopulationUtils.getFactory().createPerson(Id.create("3", Person.class));; + Person person3 = PopulationUtils.getFactory().createPerson(Id.create("3", Person.class)); person3.addPlan(plan3); - Person person4 = PopulationUtils.getFactory().createPerson(Id.create("4", Person.class));; + Person person4 = PopulationUtils.getFactory().createPerson(Id.create("4", Person.class)); person4.addPlan(plan4); scenario.getPopulation().addPerson(person1); diff --git a/matsim/src/test/java/org/matsim/analysis/ScoreStatsControlerListenerTest.java b/matsim/src/test/java/org/matsim/analysis/ScoreStatsControlerListenerTest.java index 2bc0864ed85..42d172b17eb 100644 --- a/matsim/src/test/java/org/matsim/analysis/ScoreStatsControlerListenerTest.java +++ b/matsim/src/test/java/org/matsim/analysis/ScoreStatsControlerListenerTest.java @@ -18,7 +18,6 @@ import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; import org.matsim.api.core.v01.population.Route; -import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.config.groups.ControllerConfigGroup; import org.matsim.core.config.groups.ControllerConfigGroup.CompressionType; diff --git a/matsim/src/test/java/org/matsim/api/core/v01/AutoResetIdCaches.java b/matsim/src/test/java/org/matsim/api/core/v01/AutoResetIdCaches.java index 8d992aaa110..fb89677e985 100644 --- a/matsim/src/test/java/org/matsim/api/core/v01/AutoResetIdCaches.java +++ b/matsim/src/test/java/org/matsim/api/core/v01/AutoResetIdCaches.java @@ -23,7 +23,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.extension.ExtensionContext; -import org.junit.jupiter.api.extension.TestInstancePostProcessor; import org.junit.jupiter.api.extension.TestWatcher; import java.util.Optional; diff --git a/matsim/src/test/java/org/matsim/api/core/v01/IdAnnotationsTest.java b/matsim/src/test/java/org/matsim/api/core/v01/IdAnnotationsTest.java index ac679f3d593..032eab0f7bd 100644 --- a/matsim/src/test/java/org/matsim/api/core/v01/IdAnnotationsTest.java +++ b/matsim/src/test/java/org/matsim/api/core/v01/IdAnnotationsTest.java @@ -81,7 +81,7 @@ private static record RecordWithIds( @JsonId Id personId, @JsonId Id linkId, @JsonId Id nodeId) { - }; + } @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) private static class ClassWithIds { @@ -117,6 +117,6 @@ public boolean equals(Object o) { return false; } - }; + } } diff --git a/matsim/src/test/java/org/matsim/core/config/ReflectiveConfigGroupTest.java b/matsim/src/test/java/org/matsim/core/config/ReflectiveConfigGroupTest.java index bee35515f5c..17b8278da9e 100644 --- a/matsim/src/test/java/org/matsim/core/config/ReflectiveConfigGroupTest.java +++ b/matsim/src/test/java/org/matsim/core/config/ReflectiveConfigGroupTest.java @@ -34,7 +34,6 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; -import org.junit.jupiter.api.extension.RegisterExtension; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; @@ -409,7 +408,7 @@ public String getStuff() { } private enum MyEnum { - VALUE1, VALUE2; + VALUE1, VALUE2 } /** diff --git a/matsim/src/test/java/org/matsim/core/controler/ControlerIT.java b/matsim/src/test/java/org/matsim/core/controler/ControlerIT.java index ff8e7c8ca99..2a735f508af 100644 --- a/matsim/src/test/java/org/matsim/core/controler/ControlerIT.java +++ b/matsim/src/test/java/org/matsim/core/controler/ControlerIT.java @@ -26,8 +26,6 @@ import java.io.File; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; import java.util.Collections; import java.util.EnumSet; @@ -895,7 +893,7 @@ void testOneSnapshotWriterInConfig() { config.controller().setWriteEventsInterval(0); config.controller().setWritePlansInterval(0); config.qsim().setSnapshotPeriod(10); - config.qsim().setSnapshotStyle(SnapshotStyle.equiDist) ;; + config.qsim().setSnapshotStyle(SnapshotStyle.equiDist) ; final Controler controler = new Controler(config); controler.getConfig().controller().setCreateGraphs(false); @@ -915,7 +913,7 @@ void testTransimsSnapshotWriterOnQSim() { config.controller().setSnapshotFormat( Collections.singletonList( SnapshotFormat.transims ) ); config.controller().setOutputDirectory( utils.getOutputDirectory() ); config.qsim().setSnapshotPeriod(600); - config.qsim().setSnapshotStyle( SnapshotStyle.equiDist ) ;; + config.qsim().setSnapshotStyle( SnapshotStyle.equiDist ) ; final Controler controler = new Controler(config); controler.getConfig().controller().setCreateGraphs(false); diff --git a/matsim/src/test/java/org/matsim/core/controler/PrepareForSimImplTest.java b/matsim/src/test/java/org/matsim/core/controler/PrepareForSimImplTest.java index 424631dd064..af9ec71a41b 100644 --- a/matsim/src/test/java/org/matsim/core/controler/PrepareForSimImplTest.java +++ b/matsim/src/test/java/org/matsim/core/controler/PrepareForSimImplTest.java @@ -822,7 +822,7 @@ public TripRouter get() { } } - private class DummyRoutingModule implements RoutingModule { + private static class DummyRoutingModule implements RoutingModule { @Override public List calcRoute(RoutingRequest request) { return Collections.singletonList(PopulationUtils.createLeg("dummyMode")); diff --git a/matsim/src/test/java/org/matsim/core/events/EventsManagerImplTest.java b/matsim/src/test/java/org/matsim/core/events/EventsManagerImplTest.java index 157a0c73db1..daa35adbc68 100644 --- a/matsim/src/test/java/org/matsim/core/events/EventsManagerImplTest.java +++ b/matsim/src/test/java/org/matsim/core/events/EventsManagerImplTest.java @@ -104,6 +104,7 @@ public void reset(final int iteration) { @Override public void handleEvent(final MyEvent e) { this.counter++; + //noinspection divzero int i = 1 / 0; // produce ArithmeticException System.out.println(i); } diff --git a/matsim/src/test/java/org/matsim/core/mobsim/hermes/HermesTransitTest.java b/matsim/src/test/java/org/matsim/core/mobsim/hermes/HermesTransitTest.java index 5fba7f1c420..7a73ef5fe1c 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/hermes/HermesTransitTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/hermes/HermesTransitTest.java @@ -2,9 +2,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; @@ -55,8 +53,6 @@ import org.matsim.vehicles.Vehicles; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; import java.util.Collections; import java.util.List; diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/AbstractQSimModuleTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/AbstractQSimModuleTest.java index fbec8a33e7f..e4112813bae 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/AbstractQSimModuleTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/AbstractQSimModuleTest.java @@ -131,7 +131,7 @@ void testOverrideAgentFactoryTwice() { Assertions.assertTrue(value2.get() > 0); } - private class TestQSimModule extends AbstractQSimModule { + private static class TestQSimModule extends AbstractQSimModule { private final AtomicLong value; public TestQSimModule(AtomicLong value) { diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/FlowStorageSpillbackTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/FlowStorageSpillbackTest.java index a46bea6bb90..dbf47866033 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/FlowStorageSpillbackTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/FlowStorageSpillbackTest.java @@ -17,15 +17,11 @@ * * * *********************************************************************** */ -/** - * - */ package org.matsim.core.mobsim.qsim; import java.util.*; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/NetsimRoutingConsistencyTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/NetsimRoutingConsistencyTest.java index 1253b79ec74..cbdde36ca58 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/NetsimRoutingConsistencyTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/NetsimRoutingConsistencyTest.java @@ -294,7 +294,7 @@ public void install() { Assertions.assertEquals(adjustedRoutingTravelTime, 202.0, 1e-3); } - class DepartureArrivalListener implements PersonDepartureEventHandler, PersonArrivalEventHandler { + static class DepartureArrivalListener implements PersonDepartureEventHandler, PersonArrivalEventHandler { public double departureTime = Double.NaN; public double arrivalTime = Double.NaN; diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/NodeTransitionTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/NodeTransitionTest.java index b57ed217c3e..b37c5f2a32d 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/NodeTransitionTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/NodeTransitionTest.java @@ -18,8 +18,6 @@ * *********************************************************************** */ package org.matsim.core.mobsim.qsim; -import java.util.Arrays; -import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -27,9 +25,7 @@ import java.util.TreeMap; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; @@ -739,7 +735,7 @@ private static void fillPopulationWithOneCommodity(Population population, double } - private final class ThroughputAnalyzer implements LinkLeaveEventHandler { + private static final class ThroughputAnalyzer implements LinkLeaveEventHandler { private final List> linksOfInterest; private Map, Map> absoluteThroughputPerTimeStep_veh = new HashMap<>(); diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/VehicleSourceTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/VehicleSourceTest.java index ac787bb7de9..9460bd95d03 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/VehicleSourceTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/VehicleSourceTest.java @@ -19,7 +19,6 @@ package org.matsim.core.mobsim.qsim; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -104,7 +103,9 @@ void main(VehiclesSource vehiclesSource, boolean usingPersonIdForMissingVehicleI config.qsim().setVehiclesSource(vehiclesSource ); config.qsim().setUsePersonIdForMissingVehicleId(usingPersonIdForMissingVehicleId ); - config.controller().setOutputDirectory(helper.getOutputDirectory()); + config.controller() + .setOutputDirectory( + helper.getOutputDirectory(vehiclesSource.name() + "_" + usingPersonIdForMissingVehicleId + "_" + providingVehiclesInPerson)); config.controller().setLastIteration(0); config.controller().setWriteEventsInterval(1); config.controller().setCreateGraphs(false); diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/changeeventsengine/NetworkChangeEventsEngineTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/changeeventsengine/NetworkChangeEventsEngineTest.java index 1cb8f2e7000..9735f60a0be 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/changeeventsengine/NetworkChangeEventsEngineTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/changeeventsengine/NetworkChangeEventsEngineTest.java @@ -40,7 +40,6 @@ import org.matsim.core.mobsim.qsim.QSim; import org.matsim.core.mobsim.qsim.QSimBuilder; import org.matsim.core.mobsim.qsim.interfaces.DepartureHandler; -import org.matsim.core.mobsim.qsim.interfaces.Netsim; import org.matsim.core.network.NetworkChangeEvent; import org.matsim.core.scenario.ScenarioUtils; diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/DeparturesOnSameLinkSameTimeTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/DeparturesOnSameLinkSameTimeTest.java index e26d72120ad..bc69576a7f2 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/DeparturesOnSameLinkSameTimeTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/DeparturesOnSameLinkSameTimeTest.java @@ -132,7 +132,7 @@ public void handleEvent(LinkLeaveEvent event) { *

    o-----o------o * */ - private class PseudoInputs { + private static class PseudoInputs { Scenario scenario; Config config; diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/FlowCapacityVariationTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/FlowCapacityVariationTest.java index 66f3d0000b6..d94ce42724a 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/FlowCapacityVariationTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/FlowCapacityVariationTest.java @@ -19,7 +19,6 @@ package org.matsim.core.mobsim.qsim.qnetsimengine; 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.matsim.api.core.v01.Coord; @@ -69,7 +68,7 @@ void twoCarsLeavingTimes() { void twoMotorbikesTravelTime(){ /* linkCapacity higher than 1PCU/sec*/ vehiclesLeavingSameTime("motorbike",3601); - + /*link capacuty higher than 1motorbike/sec = 0.25PCU/sec */ vehiclesLeavingSameTime("motorbike",1800); } @@ -78,11 +77,11 @@ void twoMotorbikesTravelTime(){ void twoBikesTravelTime(){ /* linkCapacity higher than 1PCU/sec */ vehiclesLeavingSameTime(TransportMode.bike,3601); - + /* link capacuty higher than 1motorbike/sec = 0.25PCU/sec */ vehiclesLeavingSameTime(TransportMode.bike,1800); } - + private void vehiclesLeavingSameTime(String travelMode, double linkCapacity){ PseudoInputs net = new PseudoInputs(travelMode); net.createNetwork(linkCapacity); @@ -102,16 +101,16 @@ private void vehiclesLeavingSameTime(String travelMode, double linkCapacity){ Map, double[]> times1 = vehicleLinkTravelTimes.get(Id.create("1", Vehicle.class)); Map, double[]> times2 = vehicleLinkTravelTimes.get(Id.create("2", Vehicle.class)); - int linkEnterTime1 = (int)times1.get(Id.create("2", Link.class))[0]; + int linkEnterTime1 = (int)times1.get(Id.create("2", Link.class))[0]; int linkEnterTime2 = (int)times2.get(Id.create("2", Link.class))[0]; - int linkLeaveTime1 = (int)times1.get(Id.create("2", Link.class))[1]; + int linkLeaveTime1 = (int)times1.get(Id.create("2", Link.class))[1]; int linkLeaveTime2 = (int)times2.get(Id.create("2", Link.class))[1]; Assertions.assertEquals(0, linkEnterTime1-linkEnterTime2, travelMode+ " entered at different time"); Assertions.assertEquals(0, linkLeaveTime1-linkLeaveTime2, travelMode +" entered at same time but not leaving the link at the same time."); } - + private static final class PseudoInputs{ final Config config; @@ -126,7 +125,7 @@ private static final class PseudoInputs{ public PseudoInputs(String travelMode){ this.travelMode = travelMode; - + scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()); config = scenario.getConfig(); config.qsim().setMainModes(Arrays.asList(travelMode)); @@ -157,10 +156,10 @@ private void createNetwork(double linkCapacity){ link3 = NetworkUtils.createAndAddLink(network, Id.create("3", Link.class), fromNode2, toNode2, 1000, 25, 7200, 1, null, "22"); } - + private void createPopulation(){ - // Vehicles info + // Vehicles info // scenario.getConfig().qsim().setUseDefaultVehicles(false); scenario.getConfig().qsim().setVehiclesSource( VehiclesSource.fromVehiclesData ) ; diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/FlowEfficiencyCalculatorTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/FlowEfficiencyCalculatorTest.java index 714d3e0452b..2d373a8e2b1 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/FlowEfficiencyCalculatorTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/FlowEfficiencyCalculatorTest.java @@ -104,7 +104,7 @@ QNetworkFactory provideQNetworkFactory(EventsManager eventsManager, Scenario sce return arrivalHandler.latestArrivalTime; } - private class CustomFlowEfficiencyCalculator implements FlowEfficiencyCalculator { + private static class CustomFlowEfficiencyCalculator implements FlowEfficiencyCalculator { private final double factor; public CustomFlowEfficiencyCalculator(double factor) { @@ -117,7 +117,7 @@ public double calculateFlowEfficiency(QVehicle qVehicle, QVehicle previousVehicl } } - private class LatestArrivalHandler implements PersonArrivalEventHandler { + private static class LatestArrivalHandler implements PersonArrivalEventHandler { Double latestArrivalTime = null; @Override diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/JavaRoundingErrorInQsimTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/JavaRoundingErrorInQsimTest.java index e7342fff755..ca771b4156c 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/JavaRoundingErrorInQsimTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/JavaRoundingErrorInQsimTest.java @@ -23,7 +23,6 @@ import java.util.List; import java.util.Map; 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.matsim.api.core.v01.Coord; @@ -42,7 +41,6 @@ import org.matsim.core.config.ConfigUtils; import org.matsim.core.controler.PrepareForSimUtils; import org.matsim.core.events.EventsUtils; -import org.matsim.core.mobsim.qsim.QSim; import org.matsim.core.mobsim.qsim.QSimBuilder; import org.matsim.core.network.NetworkUtils; import org.matsim.core.population.routes.LinkNetworkRouteFactory; @@ -58,7 +56,7 @@ * In such scenarios, flowCapacityFraction is accumulated in every second and that's where * problem starts. For e.g. 0.2+0.1 = 0.30000000004 also 0.6+0.1=0.79999999999999999 * See, nice article http://floating-point-gui.de/basic/ - * + * * See small numerical test also * @author amit */ @@ -70,11 +68,11 @@ void printDecimalSum(){ double a = 0.1; double sum =0; double counter = 0; - + for(int i=0; i<10;i++){ sum += a; counter++; - System.out.println("Sum at counter "+counter+" is "+sum); + System.out.println("Sum at counter "+counter+" is "+sum); } } @@ -99,7 +97,7 @@ void testToCheckTravelTime() { //agent 2 is departed first so will have free speed time = 1000/25 +1 = 41 sec Assertions.assertEquals( 41.0 , vehicleLinkTravelTime.get(Id.createVehicleId(2)) , MatsimTestUtils.EPSILON, "Wrong travel time for on link 2 for vehicle 2"); - // agent 1 should have 1000/25 +1 + 10 = 51 but, it may be 52 sec sometimes due to rounding errors in java. Rounding errors is eliminated at the moment if accumulating flow to zero instead of one. + // agent 1 should have 1000/25 +1 + 10 = 51 but, it may be 52 sec sometimes due to rounding errors in java. Rounding errors is eliminated at the moment if accumulating flow to zero instead of one. Assertions.assertEquals( 51.0 , vehicleLinkTravelTime.get(Id.createVehicleId(1)) , MatsimTestUtils.EPSILON, "Wrong travel time for on link 2 for vehicle 1"); LogManager.getLogger(JavaRoundingErrorInQsimTest.class).warn("Although the test is passing instead of failing for vehicle 1. This is done intentionally in order to keep this in mind for future."); } @@ -162,10 +160,10 @@ private void createNetwork(double linkCapacity){ link1 = NetworkUtils.createAndAddLink(network,Id.create("1", Link.class), fromNode, toNode, (double) 1000, (double) 25, (double) 7200, (double) 1, null, "22"); final Node fromNode1 = node2; final Node toNode1 = node3; - final double capacity = linkCapacity; + final double capacity = linkCapacity; link2 = NetworkUtils.createAndAddLink(network,Id.create("2", Link.class), fromNode1, toNode1, (double) 1000, (double) 25, capacity, (double) 1, null, "22"); final Node fromNode2 = node3; - final Node toNode2 = node4; + final Node toNode2 = node4; link3 = NetworkUtils.createAndAddLink(network,Id.create("3", Link.class), fromNode2, toNode2, (double) 1000, (double) 25, (double) 7200, (double) 1, null, "22"); } diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/PassingTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/PassingTest.java index 111b37cc82c..a145ecf6c39 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/PassingTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/PassingTest.java @@ -44,7 +44,6 @@ import org.matsim.core.controler.listener.IterationEndsListener; import org.matsim.core.controler.listener.StartupListener; import org.matsim.core.events.EventsUtils; -import org.matsim.core.mobsim.qsim.QSim; import org.matsim.core.mobsim.qsim.QSimBuilder; import org.matsim.core.network.NetworkUtils; import org.matsim.core.population.routes.LinkNetworkRouteFactory; @@ -125,7 +124,7 @@ void test4PassingInFreeFlowState(){ } - private class TravelTimeControlerListener implements StartupListener, IterationEndsListener { + private static class TravelTimeControlerListener implements StartupListener, IterationEndsListener { Map, Map, Double>> vehicleLinkTravelTimes = new HashMap<>(); VehicleLinkTravelTimeEventHandler hand; diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/QLinkTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/QLinkTest.java index ff153e4a86f..394ef272b28 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/QLinkTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/QLinkTest.java @@ -22,13 +22,10 @@ import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/SeepageTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/SeepageTest.java index 89e0f598b0a..c562b59987b 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/SeepageTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/SeepageTest.java @@ -21,7 +21,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.ValueSource; import org.matsim.api.core.v01.Coord; diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/SimulatedLaneFlowCapacityTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/SimulatedLaneFlowCapacityTest.java index 8fc3a972827..018ef7c995f 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/SimulatedLaneFlowCapacityTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/SimulatedLaneFlowCapacityTest.java @@ -340,7 +340,7 @@ void testCapacityWithThreeLanes() { * * @author tthunig */ - class SimulatedCapacityHandler implements LinkLeaveEventHandler, LaneLeaveEventHandler{ + static class SimulatedCapacityHandler implements LinkLeaveEventHandler, LaneLeaveEventHandler{ private double linkCapacity; private Map, Double> laneCapacities = new HashMap<>(); diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/VehVsLinkSpeedTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/VehVsLinkSpeedTest.java index 10ec18198e2..820914fc323 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/VehVsLinkSpeedTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/VehVsLinkSpeedTest.java @@ -21,7 +21,6 @@ import java.util.*; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.matsim.api.core.v01.Coord; @@ -42,7 +41,6 @@ import org.matsim.core.config.groups.QSimConfigGroup; import org.matsim.core.controler.PrepareForSimUtils; import org.matsim.core.events.EventsUtils; -import org.matsim.core.mobsim.qsim.QSim; import org.matsim.core.mobsim.qsim.QSimBuilder; import org.matsim.core.network.NetworkUtils; import org.matsim.core.population.routes.LinkNetworkRouteFactory; diff --git a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/VehicleHandlerTest.java b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/VehicleHandlerTest.java index 7a9d4e656ad..292ae461e58 100644 --- a/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/VehicleHandlerTest.java +++ b/matsim/src/test/java/org/matsim/core/mobsim/qsim/qnetsimengine/VehicleHandlerTest.java @@ -126,12 +126,12 @@ QNetworkFactory provideQNetworkFactory(EventsManager eventsManager, Scenario sce return result; } - private class Result { + private static class Result { double latestArrivalTime; long initialCount; } - private class BlockingVehicleHandler implements VehicleHandler { + private static class BlockingVehicleHandler implements VehicleHandler { private final long capacity; long initialCount = 0; @@ -171,7 +171,7 @@ public void handleInitialVehicleArrival(QVehicle vehicle, Link link) { } } - private class LatestArrivalHandler implements PersonArrivalEventHandler { + private static class LatestArrivalHandler implements PersonArrivalEventHandler { Double latestArrivalTime = null; @Override diff --git a/matsim/src/test/java/org/matsim/core/network/DisallowedNextLinksTest.java b/matsim/src/test/java/org/matsim/core/network/DisallowedNextLinksTest.java index d3b5c37d7fe..48c0bbfe824 100644 --- a/matsim/src/test/java/org/matsim/core/network/DisallowedNextLinksTest.java +++ b/matsim/src/test/java/org/matsim/core/network/DisallowedNextLinksTest.java @@ -2,14 +2,12 @@ import java.io.File; import java.io.IOException; -import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; diff --git a/matsim/src/test/java/org/matsim/core/network/NetworkChangeEventsParserWriterTest.java b/matsim/src/test/java/org/matsim/core/network/NetworkChangeEventsParserWriterTest.java index 1824d8ee25e..a78c2e0d851 100644 --- a/matsim/src/test/java/org/matsim/core/network/NetworkChangeEventsParserWriterTest.java +++ b/matsim/src/test/java/org/matsim/core/network/NetworkChangeEventsParserWriterTest.java @@ -27,7 +27,6 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; -import org.matsim.api.core.v01.network.NetworkFactory; import org.matsim.api.core.v01.network.Node; import org.matsim.core.network.io.NetworkChangeEventsParser; import org.matsim.core.network.io.NetworkChangeEventsWriter; diff --git a/matsim/src/test/java/org/matsim/core/network/algorithms/MultimodalNetworkCleanerTest.java b/matsim/src/test/java/org/matsim/core/network/algorithms/MultimodalNetworkCleanerTest.java index 2665b2d4096..4ba316aa1ee 100644 --- a/matsim/src/test/java/org/matsim/core/network/algorithms/MultimodalNetworkCleanerTest.java +++ b/matsim/src/test/java/org/matsim/core/network/algorithms/MultimodalNetworkCleanerTest.java @@ -130,8 +130,8 @@ void testRun_singleMode_singleSink() { Network network = f.scenario.getNetwork(); Node node1 = network.getNodes().get(f.nodeIds[1]); Node node3 = network.getNodes().get(f.nodeIds[3]); - Node node10 = network.getFactory().createNode(f.nodeIds[10], new Coord((double) 0, (double) 200)); - Node node11 = network.getFactory().createNode(f.nodeIds[11], new Coord((double) 200, (double) 200)); + Node node10 = network.getFactory().createNode(f.nodeIds[10], new Coord(0, 200)); + Node node11 = network.getFactory().createNode(f.nodeIds[11], new Coord(200, 200)); network.addNode(node10); network.addNode(node11); network.addLink(network.getFactory().createLink(f.linkIds[10], node1, node10)); @@ -226,8 +226,8 @@ void testRun_singleMode_doubleSink() { Node node1 = network.getNodes().get(f.nodeIds[1]); Node node2 = network.getNodes().get(f.nodeIds[2]); Node node3 = network.getNodes().get(f.nodeIds[3]); - Node node10 = network.getFactory().createNode(f.nodeIds[10], new Coord((double) 0, (double) 200)); - Node node11 = network.getFactory().createNode(f.nodeIds[11], new Coord((double) 200, (double) 200)); + Node node10 = network.getFactory().createNode(f.nodeIds[10], new Coord(0, 200)); + Node node11 = network.getFactory().createNode(f.nodeIds[11], new Coord(200, 200)); network.addNode(node10); network.addNode(node11); network.addLink(network.getFactory().createLink(f.linkIds[10], node1, node10)); @@ -282,8 +282,8 @@ void testRun_singleMode_singleSource() { Network network = f.scenario.getNetwork(); Node node1 = network.getNodes().get(f.nodeIds[1]); Node node3 = network.getNodes().get(f.nodeIds[3]); - Node node10 = network.getFactory().createNode(f.nodeIds[10], new Coord((double) 0, (double) 200)); - Node node11 = network.getFactory().createNode(f.nodeIds[11], new Coord((double) 200, (double) 200)); + Node node10 = network.getFactory().createNode(f.nodeIds[10], new Coord(0, 200)); + Node node11 = network.getFactory().createNode(f.nodeIds[11], new Coord(200, 200)); network.addNode(node10); network.addNode(node11); network.addLink(network.getFactory().createLink(f.linkIds[10], node10, node1)); @@ -333,7 +333,7 @@ void testRun_singleMode_singleSource() { void testRemoveNodesWithoutLinks() { Fixture f = new Fixture(); Network network = f.scenario.getNetwork(); - network.addNode(network.getFactory().createNode(f.nodeIds[10], new Coord((double) 300, (double) 300))); + network.addNode(network.getFactory().createNode(f.nodeIds[10], new Coord(300, 300))); MultimodalNetworkCleaner cleaner = new MultimodalNetworkCleaner(network); Assertions.assertEquals(8, network.getLinks().size(), "wrong number of links."); Assertions.assertEquals(7, network.getNodes().size(), "wrong number of nodes."); @@ -356,8 +356,8 @@ void testRun_singleMode_doubleSource() { Node node1 = network.getNodes().get(f.nodeIds[1]); Node node2 = network.getNodes().get(f.nodeIds[2]); Node node3 = network.getNodes().get(f.nodeIds[3]); - Node node10 = network.getFactory().createNode(f.nodeIds[10], new Coord((double) 0, (double) 200)); - Node node11 = network.getFactory().createNode(f.nodeIds[11], new Coord((double) 200, (double) 200)); + Node node10 = network.getFactory().createNode(f.nodeIds[10], new Coord(0, 200)); + Node node11 = network.getFactory().createNode(f.nodeIds[11], new Coord(200, 200)); network.addNode(node10); network.addNode(node11); network.addLink(network.getFactory().createLink(f.linkIds[10], node10, node1)); @@ -436,7 +436,7 @@ void testRun_multipleModes_doubleSink() { Node node2 = network.getNodes().get(f.nodeIds[2]); Node node3 = network.getNodes().get(f.nodeIds[3]); - Node node10 = network.getFactory().createNode(f.nodeIds[10], new Coord((double) 200, (double) 200)); + Node node10 = network.getFactory().createNode(f.nodeIds[10], new Coord(200, 200)); network.addNode(node10); network.addLink(network.getFactory().createLink(f.linkIds[18], node2, node10)); network.addLink(network.getFactory().createLink(f.linkIds[19], node3, node10)); @@ -470,7 +470,7 @@ void testRun_multipleModes_doubleSource() { Node node2 = network.getNodes().get(f.nodeIds[2]); Node node3 = network.getNodes().get(f.nodeIds[3]); - Node node10 = network.getFactory().createNode(f.nodeIds[10], new Coord((double) 200, (double) 200)); + Node node10 = network.getFactory().createNode(f.nodeIds[10], new Coord(200, 200)); network.addNode(node10); network.addLink(network.getFactory().createLink(f.linkIds[18], node10, node2)); network.addLink(network.getFactory().createLink(f.linkIds[19], node10, node3)); @@ -549,8 +549,8 @@ void testRun_singleLinkNetwork() { Id id2 = Id.create(2, Node.class); Id linkId1 = Id.create(1, Link.class); - Node node1 = factory.createNode(id1, new Coord((double) 0, (double) 100)); - Node node2 = factory.createNode(id2, new Coord((double) 100, (double) 100)); + Node node1 = factory.createNode(id1, new Coord(0, 100)); + Node node2 = factory.createNode(id2, new Coord(100, 100)); network.addNode(node1); network.addNode(node2); network.addLink(factory.createLink(linkId1, node1, node2)); @@ -582,7 +582,7 @@ void testRun_withConnectivity_connectedSource() { NetworkFactory nf = network.getFactory(); Node node4 = network.getNodes().get(f.nodeIds[4]); Node node5 = network.getNodes().get(f.nodeIds[5]); - Node node7 = nf.createNode(f.nodeIds[7], new Coord((double) 600, (double) 100)); + Node node7 = nf.createNode(f.nodeIds[7], new Coord(600, 100)); network.addNode(node7); network.addLink(nf.createLink(f.linkIds[10], node4, node7)); network.addLink(nf.createLink(f.linkIds[11], node7, node5)); @@ -602,7 +602,7 @@ void testRun_withConnectivity_connectedSink() { NetworkFactory nf = network.getFactory(); Node node4 = network.getNodes().get(f.nodeIds[4]); Node node5 = network.getNodes().get(f.nodeIds[5]); - Node node7 = nf.createNode(f.nodeIds[7], new Coord((double) 600, (double) 100)); + Node node7 = nf.createNode(f.nodeIds[7], new Coord(600, 100)); network.addNode(node7); network.addLink(nf.createLink(f.linkIds[10], node4, node7)); network.addLink(nf.createLink(f.linkIds[11], node7, node5)); @@ -622,7 +622,7 @@ void testRun_withConnectivity_unconnectedSource() { NetworkFactory nf = network.getFactory(); Node node4 = network.getNodes().get(f.nodeIds[4]); Node node5 = network.getNodes().get(f.nodeIds[5]); - Node node7 = nf.createNode(f.nodeIds[7], new Coord((double) 600, (double) 100)); + Node node7 = nf.createNode(f.nodeIds[7], new Coord(600, 100)); network.addNode(node7); network.addLink(nf.createLink(f.linkIds[10], node4, node7)); network.addLink(nf.createLink(f.linkIds[11], node7, node5)); @@ -643,7 +643,7 @@ void testRun_withConnectivity_unconnectedSink() { NetworkFactory nf = network.getFactory(); Node node4 = network.getNodes().get(f.nodeIds[4]); Node node5 = network.getNodes().get(f.nodeIds[5]); - Node node7 = nf.createNode(f.nodeIds[7], new Coord((double) 600, (double) 100)); + Node node7 = nf.createNode(f.nodeIds[7], new Coord(600, 100)); network.addNode(node7); network.addLink(nf.createLink(f.linkIds[10], node4, node7)); network.addLink(nf.createLink(f.linkIds[11], node7, node5)); @@ -662,16 +662,16 @@ void testRun_withConnectivity_unconnectedLink() { MultimodalFixture2 f = new MultimodalFixture2(); Network network = f.scenario.getNetwork(); NetworkFactory nf = network.getFactory(); - Node node7 = nf.createNode(f.nodeIds[7], new Coord((double) 600, (double) 100)); - Node node8 = nf.createNode(f.nodeIds[8], new Coord((double) 600, (double) 000)); + Node node7 = nf.createNode(f.nodeIds[7], new Coord(600, 100)); + Node node8 = nf.createNode(f.nodeIds[8], new Coord(600, 0)); network.addNode(node7); network.addNode(node8); network.addLink(nf.createLink(f.linkIds[10], node7, node8)); network.addLink(nf.createLink(f.linkIds[11], node8, node7)); network.getLinks().get(f.linkIds[10]).setAllowedModes(f.modesW); network.getLinks().get(f.linkIds[11]).setAllowedModes(f.modesW); - Node node9 = nf.createNode(f.nodeIds[9], new Coord((double) 700, (double) 100)); - Node node10 = nf.createNode(f.nodeIds[10], new Coord((double) 700, (double) 000)); + Node node9 = nf.createNode(f.nodeIds[9], new Coord(700, 100)); + Node node10 = nf.createNode(f.nodeIds[10], new Coord(700, 0)); network.addNode(node9); network.addNode(node10); network.addLink(nf.createLink(f.linkIds[12], node9, node10)); @@ -729,12 +729,12 @@ private static class Fixture { Network network = this.scenario.getNetwork(); NetworkFactory factory = network.getFactory(); - Node node1 = factory.createNode(this.nodeIds[1], new Coord((double) 0, (double) 100)); - Node node2 = factory.createNode(this.nodeIds[2], new Coord((double) 100, (double) 100)); - Node node3 = factory.createNode(this.nodeIds[3], new Coord((double) 200, (double) 100)); - Node node4 = factory.createNode(this.nodeIds[4], new Coord((double) 0, (double) 100)); - Node node5 = factory.createNode(this.nodeIds[5], new Coord((double) 100, (double) 0)); - Node node6 = factory.createNode(this.nodeIds[6], new Coord((double) 200, (double) 0)); + Node node1 = factory.createNode(this.nodeIds[1], new Coord(0, 100)); + Node node2 = factory.createNode(this.nodeIds[2], new Coord(100, 100)); + Node node3 = factory.createNode(this.nodeIds[3], new Coord(200, 100)); + Node node4 = factory.createNode(this.nodeIds[4], new Coord(0, 100)); + Node node5 = factory.createNode(this.nodeIds[5], new Coord(100, 0)); + Node node6 = factory.createNode(this.nodeIds[6], new Coord(200, 0)); network.addNode(node1); network.addNode(node2); network.addNode(node3); @@ -797,11 +797,11 @@ private static class MultimodeFixture extends Fixture { Node node4 = network.getNodes().get(this.nodeIds[4]); Node node6 = network.getNodes().get(this.nodeIds[6]); double y2 = -100; - Node node7 = factory.createNode(this.nodeIds[7], new Coord((double) 0, y2)); + Node node7 = factory.createNode(this.nodeIds[7], new Coord(0, y2)); double y1 = -100; - Node node8 = factory.createNode(this.nodeIds[8], new Coord((double) 100, y1)); + Node node8 = factory.createNode(this.nodeIds[8], new Coord(100, y1)); double y = -100; - Node node9 = factory.createNode(this.nodeIds[9], new Coord((double) 200, y)); + Node node9 = factory.createNode(this.nodeIds[9], new Coord(200, y)); network.addNode(node7); network.addNode(node8); network.addNode(node9); @@ -858,12 +858,12 @@ private static class MultimodalFixture2 { Network network = this.scenario.getNetwork(); NetworkFactory factory = network.getFactory(); - Node node1 = factory.createNode(this.nodeIds[1], new Coord((double) 0, (double) 100)); - Node node2 = factory.createNode(this.nodeIds[2], new Coord((double) 100, (double) 100)); - Node node3 = factory.createNode(this.nodeIds[3], new Coord((double) 0, (double) 0)); - Node node4 = factory.createNode(this.nodeIds[4], new Coord((double) 400, (double) 100)); - Node node5 = factory.createNode(this.nodeIds[5], new Coord((double) 400, (double) 0)); - Node node6 = factory.createNode(this.nodeIds[6], new Coord((double) 300, (double) 0)); + Node node1 = factory.createNode(this.nodeIds[1], new Coord(0, 100)); + Node node2 = factory.createNode(this.nodeIds[2], new Coord(100, 100)); + Node node3 = factory.createNode(this.nodeIds[3], new Coord(0, 0)); + Node node4 = factory.createNode(this.nodeIds[4], new Coord(400, 100)); + Node node5 = factory.createNode(this.nodeIds[5], new Coord(400, 0)); + Node node6 = factory.createNode(this.nodeIds[6], new Coord(300, 0)); network.addNode(node1); network.addNode(node2); network.addNode(node3); diff --git a/matsim/src/test/java/org/matsim/core/network/algorithms/TransportModeNetworkFilterTest.java b/matsim/src/test/java/org/matsim/core/network/algorithms/TransportModeNetworkFilterTest.java index a62e147d2f1..bd159f2cf7f 100644 --- a/matsim/src/test/java/org/matsim/core/network/algorithms/TransportModeNetworkFilterTest.java +++ b/matsim/src/test/java/org/matsim/core/network/algorithms/TransportModeNetworkFilterTest.java @@ -35,7 +35,6 @@ import org.matsim.api.core.v01.network.Node; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.mobsim.qsim.interfaces.TimeVariantLink; import org.matsim.core.network.NetworkChangeEvent; import org.matsim.core.network.NetworkChangeEvent.ChangeType; import org.matsim.core.network.NetworkChangeEvent.ChangeValue; @@ -274,12 +273,12 @@ void testFilter_NoCommonModes() { /** * Tests the algorithm for the case the network contains direct loops, i.e. * links with the same from and to node. - * + * * Issue #178 - http://sourceforge.net/apps/trac/matsim/ticket/178 - * - * The problem seems only to happen when the loop link is (accidentally / randomly) + * + * The problem seems only to happen when the loop link is (accidentally / randomly) * chosen as start link for the algorithm, as otherwise the node already exists. - * Thus cannot extend existing Fixture to test this, but have to create test + * Thus cannot extend existing Fixture to test this, but have to create test * scenario from scratch. */ @Test @@ -293,9 +292,9 @@ void testFilter_SingleMode_loop() { Link link1 = factory.createLink(Id.create(1, Link.class), node1, node1); link1.setAllowedModes(createHashSet(TransportMode.car)); network.addLink(link1); - + TransportModeNetworkFilter filter = new TransportModeNetworkFilter(network); - + Network subNetwork = ScenarioUtils.createScenario(ConfigUtils.createConfig()).getNetwork(); filter.filter(subNetwork, createHashSet(TransportMode.car)); Assertions.assertEquals(1, subNetwork.getNodes().size(), "wrong number of nodes."); @@ -310,28 +309,28 @@ void testFilter_SingleMode_loop() { void testFilter_timeVariant() { Config config = ConfigUtils.createConfig(); config.network().setTimeVariantNetwork(true); - + Network sourceNetwork = NetworkUtils.createNetwork(config); Node node1 = sourceNetwork.getFactory().createNode(Id.createNodeId("1"), new Coord(0.0, 0.0)); Node node2 = sourceNetwork.getFactory().createNode(Id.createNodeId("2"), new Coord(0.0, 0.0)); sourceNetwork.addNode(node1); sourceNetwork.addNode(node2); - + Link sourceLink = sourceNetwork.getFactory().createLink(Id.createLinkId("link"), node1, node2); sourceLink.setFreespeed(50.0); sourceLink.setAllowedModes(Collections.singleton("car")); sourceNetwork.addLink(sourceLink); - + NetworkChangeEvent changeEvent = new NetworkChangeEvent(120.0); changeEvent.setFreespeedChange(new ChangeValue(ChangeType.FACTOR, 2.0)); changeEvent.addLink(sourceLink); ((TimeDependentNetwork) sourceNetwork).addNetworkChangeEvent(changeEvent); - + Assertions.assertEquals(50.0, sourceLink.getFreespeed(), 1e-3); Assertions.assertEquals(50.0, sourceLink.getFreespeed(0.0), 1e-3); Assertions.assertEquals(100.0, sourceLink.getFreespeed(120.0), 1e-3); - - + + Network targetNetwork = NetworkUtils.createNetwork(config); new TransportModeNetworkFilter(sourceNetwork).filter(targetNetwork, Collections.singleton("car")); Link targetLink = targetNetwork.getLinks().get(sourceLink.getId()); diff --git a/matsim/src/test/java/org/matsim/core/population/PopulationUtilsTest.java b/matsim/src/test/java/org/matsim/core/population/PopulationUtilsTest.java index 44520f6f8d0..fb1332c9636 100644 --- a/matsim/src/test/java/org/matsim/core/population/PopulationUtilsTest.java +++ b/matsim/src/test/java/org/matsim/core/population/PopulationUtilsTest.java @@ -25,13 +25,10 @@ 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.population.*; import org.matsim.core.config.ConfigUtils; -import org.matsim.core.population.io.PopulationReader; -import org.matsim.core.scenario.ScenarioUtils; - /** +/** * @author thibautd */ public class PopulationUtilsTest { diff --git a/matsim/src/test/java/org/matsim/core/population/io/PopulationReprojectionIOIT.java b/matsim/src/test/java/org/matsim/core/population/io/PopulationReprojectionIOIT.java index 6a2da5d5506..28ce85fc83b 100644 --- a/matsim/src/test/java/org/matsim/core/population/io/PopulationReprojectionIOIT.java +++ b/matsim/src/test/java/org/matsim/core/population/io/PopulationReprojectionIOIT.java @@ -204,7 +204,7 @@ void testWithControlerAndAttributes() { Assertions.assertNotEquals( transformation.transform(o.getCoord()), - r, + r.getCoord(), "No coordinates transform performed!"); } } @@ -313,7 +313,7 @@ void testWithControlerAndConfigParameters() { Assertions.assertNotEquals( transformation.transform(o.getCoord()), - r, + r.getCoord(), "No coordinates transform performed!"); } } diff --git a/matsim/src/test/java/org/matsim/core/replanning/conflicts/ReplanningWithConflictsTest.java b/matsim/src/test/java/org/matsim/core/replanning/conflicts/ReplanningWithConflictsTest.java index 81b9522bb1b..a230136537f 100644 --- a/matsim/src/test/java/org/matsim/core/replanning/conflicts/ReplanningWithConflictsTest.java +++ b/matsim/src/test/java/org/matsim/core/replanning/conflicts/ReplanningWithConflictsTest.java @@ -221,7 +221,7 @@ public String getName() { assertEquals(60, counter.unrestricted); } - private class LegCounter implements PersonDepartureEventHandler { + private static class LegCounter implements PersonDepartureEventHandler { int restricted; int unrestricted; diff --git a/matsim/src/test/java/org/matsim/core/replanning/strategies/DeterministicMultithreadedReplanningIT.java b/matsim/src/test/java/org/matsim/core/replanning/strategies/DeterministicMultithreadedReplanningIT.java index 898ccfd8b2e..09f6550063b 100644 --- a/matsim/src/test/java/org/matsim/core/replanning/strategies/DeterministicMultithreadedReplanningIT.java +++ b/matsim/src/test/java/org/matsim/core/replanning/strategies/DeterministicMultithreadedReplanningIT.java @@ -292,12 +292,7 @@ public void install() { bind(StrategyManager.class).toProvider(new com.google.inject.Provider() { @Override public StrategyManager get() { - return new Provider() { - @Override - public StrategyManager get() { - return myLoadStrategyManager(); - } - }.get(); + return myLoadStrategyManager(); } }).in(Singleton.class); } diff --git a/matsim/src/test/java/org/matsim/core/replanning/strategies/InnovationSwitchOffTest.java b/matsim/src/test/java/org/matsim/core/replanning/strategies/InnovationSwitchOffTest.java index f62b40c44e2..7038474ef48 100644 --- a/matsim/src/test/java/org/matsim/core/replanning/strategies/InnovationSwitchOffTest.java +++ b/matsim/src/test/java/org/matsim/core/replanning/strategies/InnovationSwitchOffTest.java @@ -17,9 +17,6 @@ * * * *********************************************************************** */ -/** - * - */ package org.matsim.core.replanning.strategies; import com.google.inject.*; diff --git a/matsim/src/test/java/org/matsim/core/router/TripStructureUtilsSubtoursTest.java b/matsim/src/test/java/org/matsim/core/router/TripStructureUtilsSubtoursTest.java index 7dae5a07ce9..f0febfca7f6 100644 --- a/matsim/src/test/java/org/matsim/core/router/TripStructureUtilsSubtoursTest.java +++ b/matsim/src/test/java/org/matsim/core/router/TripStructureUtilsSubtoursTest.java @@ -29,7 +29,6 @@ import java.util.HashSet; import java.util.List; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.matsim.api.core.v01.Id; diff --git a/matsim/src/test/java/org/matsim/core/scenario/ScenarioImplTest.java b/matsim/src/test/java/org/matsim/core/scenario/ScenarioImplTest.java index 741fbf70dca..c485812927c 100644 --- a/matsim/src/test/java/org/matsim/core/scenario/ScenarioImplTest.java +++ b/matsim/src/test/java/org/matsim/core/scenario/ScenarioImplTest.java @@ -22,9 +22,6 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.matsim.core.config.ConfigUtils; -import org.matsim.households.Households; -import org.matsim.pt.transitSchedule.api.TransitSchedule; -import org.matsim.vehicles.Vehicles; /** * @author thibautd diff --git a/matsim/src/test/java/org/matsim/core/scenario/ScenarioLoaderImplTest.java b/matsim/src/test/java/org/matsim/core/scenario/ScenarioLoaderImplTest.java index a26eaacb88f..b4171981f1b 100644 --- a/matsim/src/test/java/org/matsim/core/scenario/ScenarioLoaderImplTest.java +++ b/matsim/src/test/java/org/matsim/core/scenario/ScenarioLoaderImplTest.java @@ -36,9 +36,6 @@ import org.matsim.facilities.FacilitiesUtils; import org.matsim.households.Household; import org.matsim.households.HouseholdUtils; -import org.matsim.pt.transitSchedule.TransitScheduleUtils; -import org.matsim.pt.transitSchedule.api.TransitLine; -import org.matsim.pt.transitSchedule.api.TransitStopFacility; import org.matsim.testcases.MatsimTestUtils; /** diff --git a/matsim/src/test/java/org/matsim/core/scoring/EventsToScoreTest.java b/matsim/src/test/java/org/matsim/core/scoring/EventsToScoreTest.java index 4d0bbb8f127..d7390a8bf70 100644 --- a/matsim/src/test/java/org/matsim/core/scoring/EventsToScoreTest.java +++ b/matsim/src/test/java/org/matsim/core/scoring/EventsToScoreTest.java @@ -92,7 +92,7 @@ void testMsaAveraging() { for (int mockIteration = config.controller().getFirstIteration(); mockIteration <= config.controller().getLastIteration() ; mockIteration++ ) { - e2s.beginIteration(mockIteration, false); ; + e2s.beginIteration(mockIteration, false); events.initProcessing(); // generating a money event with amount mockIteration-98 (i.e. 1, 2, 3, 4): diff --git a/matsim/src/test/java/org/matsim/core/scoring/ScoringFunctionsForPopulationStressIT.java b/matsim/src/test/java/org/matsim/core/scoring/ScoringFunctionsForPopulationStressIT.java index 5d1b6ebe200..2482b858c2e 100644 --- a/matsim/src/test/java/org/matsim/core/scoring/ScoringFunctionsForPopulationStressIT.java +++ b/matsim/src/test/java/org/matsim/core/scoring/ScoringFunctionsForPopulationStressIT.java @@ -80,7 +80,7 @@ void exceptionInScoringFunctionPropagates() { }); } - private class ThrowingScoringFunctionFactory implements ScoringFunctionFactory { + private static class ThrowingScoringFunctionFactory implements ScoringFunctionFactory { @Override public ScoringFunction createNewScoringFunction(Person person) { return new ScoringFunction() { diff --git a/matsim/src/test/java/org/matsim/core/scoring/ScoringFunctionsForPopulationTest.java b/matsim/src/test/java/org/matsim/core/scoring/ScoringFunctionsForPopulationTest.java index cecacd2f17d..8fcaad45248 100644 --- a/matsim/src/test/java/org/matsim/core/scoring/ScoringFunctionsForPopulationTest.java +++ b/matsim/src/test/java/org/matsim/core/scoring/ScoringFunctionsForPopulationTest.java @@ -29,7 +29,6 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.events.ActivityStartEvent; import org.matsim.api.core.v01.events.Event; -import org.matsim.api.core.v01.events.PersonMoneyEvent; import org.matsim.api.core.v01.events.PersonScoreEvent; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Leg; @@ -184,4 +183,4 @@ public void handleEvent(Event event) { } } -} \ No newline at end of file +} diff --git a/matsim/src/test/java/org/matsim/core/trafficmonitoring/TravelTimeCalculatorTest.java b/matsim/src/test/java/org/matsim/core/trafficmonitoring/TravelTimeCalculatorTest.java index 87495bae909..3a8e904f1d2 100644 --- a/matsim/src/test/java/org/matsim/core/trafficmonitoring/TravelTimeCalculatorTest.java +++ b/matsim/src/test/java/org/matsim/core/trafficmonitoring/TravelTimeCalculatorTest.java @@ -161,19 +161,10 @@ private static void doTravelTimeCalculatorTest( final MutableScenario scenario, Link link10 = network.getLinks().get(Id.create("10", Link.class)); if (generateNewData) { - BufferedWriter outfile = null; - try { - outfile = new BufferedWriter(new FileWriter(compareFile)); + try (BufferedWriter outfile = new BufferedWriter(new FileWriter(compareFile))) { for (int i = 0; i < numberOfTimeSlotsToTest; i++) { double ttime = ttcalc.getLinkTravelTimes().getLinkTravelTime(link10, i*timeBinSize, null, null); - outfile.write(Double.toString(ttime) + "\n"); - } - } - finally { - if (outfile != null) { - try { - outfile.close(); - } catch (IOException ignored) {} + outfile.write(ttime + "\n"); } } fail("A new file containg data for comparison was created. No comparison was made."); diff --git a/matsim/src/test/java/org/matsim/core/utils/io/IOUtilsTest.java b/matsim/src/test/java/org/matsim/core/utils/io/IOUtilsTest.java index 5f7394b5b5a..562ebad16d0 100644 --- a/matsim/src/test/java/org/matsim/core/utils/io/IOUtilsTest.java +++ b/matsim/src/test/java/org/matsim/core/utils/io/IOUtilsTest.java @@ -33,6 +33,7 @@ import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.file.Paths; /** @@ -100,7 +101,7 @@ void testGetBufferedReader_encodingMacRoman() throws IOException { @Test void testGetBufferedReader_encodingIsoLatin1() throws IOException { URL url = IOUtils.resolveFileOrResource(this.utils.getClassInputDirectory() + "textsample_IsoLatin1.txt"); - BufferedReader reader = IOUtils.getBufferedReader(url, Charset.forName("ISO-8859-1")); + BufferedReader reader = IOUtils.getBufferedReader(url, StandardCharsets.ISO_8859_1); String line = reader.readLine(); Assertions.assertNotNull(line); Assertions.assertEquals("äöüÉç", line); @@ -131,7 +132,7 @@ void testGetBufferedWriter_encodingMacRoman() throws IOException { void testGetBufferedWriter_encodingIsoLatin1() throws IOException { String filename = this.utils.getOutputDirectory() + "textsample_IsoLatin1.txt"; URL url = IOUtils.getFileUrl(filename); - BufferedWriter writer = IOUtils.getBufferedWriter(url, Charset.forName("ISO-8859-1"), false); + BufferedWriter writer = IOUtils.getBufferedWriter(url, StandardCharsets.ISO_8859_1, false); writer.write("äöüÉç"); writer.close(); long crc1 = CRCChecksum.getCRCFromFile(this.utils.getClassInputDirectory() + "textsample_IsoLatin1.txt"); diff --git a/matsim/src/test/java/org/matsim/core/utils/io/MatsimXmlParserTest.java b/matsim/src/test/java/org/matsim/core/utils/io/MatsimXmlParserTest.java index 4c300c39c09..97533595a98 100644 --- a/matsim/src/test/java/org/matsim/core/utils/io/MatsimXmlParserTest.java +++ b/matsim/src/test/java/org/matsim/core/utils/io/MatsimXmlParserTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; import org.xml.sax.Attributes; import org.xml.sax.SAXParseException; diff --git a/matsim/src/test/java/org/matsim/core/utils/misc/ConfigUtilsTest.java b/matsim/src/test/java/org/matsim/core/utils/misc/ConfigUtilsTest.java index c2bf6888369..173090066bc 100644 --- a/matsim/src/test/java/org/matsim/core/utils/misc/ConfigUtilsTest.java +++ b/matsim/src/test/java/org/matsim/core/utils/misc/ConfigUtilsTest.java @@ -32,7 +32,6 @@ import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; import org.matsim.testcases.MatsimTestUtils; -import static org.hamcrest.CoreMatchers.*; /** * @author mrieser diff --git a/matsim/src/test/java/org/matsim/core/utils/misc/RouteUtilsTest.java b/matsim/src/test/java/org/matsim/core/utils/misc/RouteUtilsTest.java index 8aa058cdf5d..2f5e1662efe 100644 --- a/matsim/src/test/java/org/matsim/core/utils/misc/RouteUtilsTest.java +++ b/matsim/src/test/java/org/matsim/core/utils/misc/RouteUtilsTest.java @@ -34,7 +34,6 @@ import org.matsim.api.core.v01.network.Node; import org.matsim.core.config.ConfigUtils; import org.matsim.core.population.routes.NetworkRoute; -import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.population.routes.RouteUtils; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.testcases.MatsimTestUtils; @@ -50,7 +49,7 @@ void testCalculateCoverage() { f.network.getLinks().get(f.linkIds[3]).setLength(400.0); f.network.getLinks().get(f.linkIds[4]).setLength(500.0); f.network.getLinks().get(f.linkIds[5]).setLength(600.0); - + NetworkRoute route, route2, route3 ; { Link startLink = f.network.getLinks().get(f.linkIds[0]); @@ -77,11 +76,11 @@ void testCalculateCoverage() { route3 = RouteUtils.createLinkNetworkRouteImpl(startLink.getId(), endLink.getId()); route3.setLinkIds(startLink.getId(), linkIds, endLink.getId()); } - + Assertions.assertEquals( 1. , RouteUtils.calculateCoverage( route, route2, f.network ), 0.0001 ); Assertions.assertEquals( (200.+400.+500.)/(200.+300.+400.+500.) , RouteUtils.calculateCoverage( route, route3, f.network ), 0.0001 ); Assertions.assertEquals( 1. , RouteUtils.calculateCoverage( route3, route, f.network ), 0.0001 ); - + } @Test diff --git a/matsim/src/test/java/org/matsim/counts/CountsV2Test.java b/matsim/src/test/java/org/matsim/counts/CountsV2Test.java index d8aacb1146a..6df02642e69 100644 --- a/matsim/src/test/java/org/matsim/counts/CountsV2Test.java +++ b/matsim/src/test/java/org/matsim/counts/CountsV2Test.java @@ -21,7 +21,6 @@ import java.util.SplittableRandom; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatNoException; import static org.junit.jupiter.api.Assertions.assertThrows; public class CountsV2Test { diff --git a/matsim/src/test/java/org/matsim/examples/EquilTest.java b/matsim/src/test/java/org/matsim/examples/EquilTest.java index 30b722f1065..96794010292 100644 --- a/matsim/src/test/java/org/matsim/examples/EquilTest.java +++ b/matsim/src/test/java/org/matsim/examples/EquilTest.java @@ -20,13 +20,9 @@ package org.matsim.examples; -import java.util.Arrays; -import java.util.Collection; - 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.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; diff --git a/matsim/src/test/java/org/matsim/examples/simple/PtScoringTest.java b/matsim/src/test/java/org/matsim/examples/simple/PtScoringTest.java index bf0fda1ee5c..8954e969fe7 100644 --- a/matsim/src/test/java/org/matsim/examples/simple/PtScoringTest.java +++ b/matsim/src/test/java/org/matsim/examples/simple/PtScoringTest.java @@ -22,7 +22,6 @@ import java.util.List; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; @@ -40,7 +39,6 @@ import org.matsim.core.scoring.functions.ActivityUtilityParameters; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; -import org.matsim.pt.config.TransitConfigGroup.TransitRoutingAlgorithmType; import org.matsim.testcases.MatsimTestUtils; import org.matsim.testcases.utils.EventsCollector; diff --git a/matsim/src/test/java/org/matsim/facilities/ActivityFacilitiesSourceTest.java b/matsim/src/test/java/org/matsim/facilities/ActivityFacilitiesSourceTest.java index de9dddfc5d5..aaf7a4416aa 100644 --- a/matsim/src/test/java/org/matsim/facilities/ActivityFacilitiesSourceTest.java +++ b/matsim/src/test/java/org/matsim/facilities/ActivityFacilitiesSourceTest.java @@ -20,7 +20,6 @@ package org.matsim.facilities; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -44,8 +43,6 @@ import org.matsim.testcases.MatsimTestUtils; import java.io.File; -import java.util.Arrays; -import java.util.Collection; import java.util.stream.Stream; /** diff --git a/matsim/src/test/java/org/matsim/households/HouseholdAttributeConversionTest.java b/matsim/src/test/java/org/matsim/households/HouseholdAttributeConversionTest.java index 6f8dbc7bbf3..4851818c2d5 100644 --- a/matsim/src/test/java/org/matsim/households/HouseholdAttributeConversionTest.java +++ b/matsim/src/test/java/org/matsim/households/HouseholdAttributeConversionTest.java @@ -30,9 +30,6 @@ import org.matsim.api.core.v01.Scenario; import org.matsim.core.config.ConfigUtils; import org.matsim.core.scenario.ScenarioUtils; -import org.matsim.core.utils.io.IOUtils; -import org.matsim.facilities.FacilitiesWriter; -import org.matsim.facilities.MatsimFacilitiesReader; import org.matsim.testcases.MatsimTestUtils; import org.matsim.utils.objectattributes.AttributeConverter; diff --git a/matsim/src/test/java/org/matsim/integration/invertednetworks/InvertedNetworkRoutingTestFixture.java b/matsim/src/test/java/org/matsim/integration/invertednetworks/InvertedNetworkRoutingTestFixture.java index 039fb91947f..e63fb5115fa 100644 --- a/matsim/src/test/java/org/matsim/integration/invertednetworks/InvertedNetworkRoutingTestFixture.java +++ b/matsim/src/test/java/org/matsim/integration/invertednetworks/InvertedNetworkRoutingTestFixture.java @@ -160,7 +160,7 @@ private void createNetwork() { network.addNode(n); n = f.createNode(Id.create(6, Node.class), new Coord((double) 0, (double) 600)); network.addNode(n); - l = f.createLink(Id.create(01, Link.class), network.getNodes().get(Id.create(0, Node.class)), network.getNodes().get(Id.create(1, Node.class))); + l = f.createLink(Id.create(1, Link.class), network.getNodes().get(Id.create(0, Node.class)), network.getNodes().get(Id.create(1, Node.class))); l.setLength(300.0); l.setFreespeed(10.0); l.setCapacity(3600.0); diff --git a/matsim/src/test/java/org/matsim/modules/ScoreStatsModuleTest.java b/matsim/src/test/java/org/matsim/modules/ScoreStatsModuleTest.java index a128a9ff6ea..5735acd4d8f 100644 --- a/matsim/src/test/java/org/matsim/modules/ScoreStatsModuleTest.java +++ b/matsim/src/test/java/org/matsim/modules/ScoreStatsModuleTest.java @@ -22,14 +22,11 @@ package org.matsim.modules; -import java.util.Arrays; -import java.util.Collection; import java.util.Map; import java.util.stream.Stream; import jakarta.inject.Inject; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; diff --git a/matsim/src/test/java/org/matsim/other/DownloadAndReadXmlTest.java b/matsim/src/test/java/org/matsim/other/DownloadAndReadXmlTest.java index 8b523e2ba36..ee5ffed39d0 100644 --- a/matsim/src/test/java/org/matsim/other/DownloadAndReadXmlTest.java +++ b/matsim/src/test/java/org/matsim/other/DownloadAndReadXmlTest.java @@ -19,7 +19,6 @@ package org.matsim.other; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -43,10 +42,10 @@ public class DownloadAndReadXmlTest { @RegisterExtension private MatsimTestUtils utils = new MatsimTestUtils(); @Disabled - @Test /** + /** * Http downloads from the SVN server will be forbidden soon, according to jwilk. */ - final void testHttpFromSvn() { + @Test final void testHttpFromSvn() { Config config = ConfigUtils.createConfig(); System.out.println(utils.getInputDirectory() + "../../"); diff --git a/matsim/src/test/java/org/matsim/population/algorithms/ChooseRandomLegModeForSubtourDiffModesTest.java b/matsim/src/test/java/org/matsim/population/algorithms/ChooseRandomLegModeForSubtourDiffModesTest.java index 6246fb409a6..55daf0abbec 100644 --- a/matsim/src/test/java/org/matsim/population/algorithms/ChooseRandomLegModeForSubtourDiffModesTest.java +++ b/matsim/src/test/java/org/matsim/population/algorithms/ChooseRandomLegModeForSubtourDiffModesTest.java @@ -25,7 +25,6 @@ import java.util.List; import java.util.Random; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.matsim.api.core.v01.Id; diff --git a/matsim/src/test/java/org/matsim/population/algorithms/ChooseRandomLegModeForSubtourTest.java b/matsim/src/test/java/org/matsim/population/algorithms/ChooseRandomLegModeForSubtourTest.java index 394fe8398fe..93986fe0404 100644 --- a/matsim/src/test/java/org/matsim/population/algorithms/ChooseRandomLegModeForSubtourTest.java +++ b/matsim/src/test/java/org/matsim/population/algorithms/ChooseRandomLegModeForSubtourTest.java @@ -30,7 +30,6 @@ import java.util.List; import java.util.Random; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; diff --git a/matsim/src/test/java/org/matsim/population/algorithms/ChooseRandomSingleLegModeTest.java b/matsim/src/test/java/org/matsim/population/algorithms/ChooseRandomSingleLegModeTest.java index 331a2fc5de3..e61bfce7509 100644 --- a/matsim/src/test/java/org/matsim/population/algorithms/ChooseRandomSingleLegModeTest.java +++ b/matsim/src/test/java/org/matsim/population/algorithms/ChooseRandomSingleLegModeTest.java @@ -30,7 +30,6 @@ import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.population.Leg; -import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.core.gbl.MatsimRandom; diff --git a/matsim/src/test/java/org/matsim/population/algorithms/ParallelPersonAlgorithmRunnerTest.java b/matsim/src/test/java/org/matsim/population/algorithms/ParallelPersonAlgorithmRunnerTest.java index 5090918a377..558e67ec6b0 100644 --- a/matsim/src/test/java/org/matsim/population/algorithms/ParallelPersonAlgorithmRunnerTest.java +++ b/matsim/src/test/java/org/matsim/population/algorithms/ParallelPersonAlgorithmRunnerTest.java @@ -23,7 +23,6 @@ import java.util.ArrayList; 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.matsim.api.core.v01.Id; diff --git a/matsim/src/test/java/org/matsim/population/algorithms/PersonPrepareForSimTest.java b/matsim/src/test/java/org/matsim/population/algorithms/PersonPrepareForSimTest.java index c5bfec0e2b7..baec9afc911 100644 --- a/matsim/src/test/java/org/matsim/population/algorithms/PersonPrepareForSimTest.java +++ b/matsim/src/test/java/org/matsim/population/algorithms/PersonPrepareForSimTest.java @@ -22,7 +22,6 @@ import java.util.HashSet; import java.util.Set; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.matsim.api.core.v01.Coord; diff --git a/matsim/src/test/java/org/matsim/pt/transitSchedule/MinimalTransferTimesImplTest.java b/matsim/src/test/java/org/matsim/pt/transitSchedule/MinimalTransferTimesImplTest.java index 4c6c8c0a8fc..dc182804e07 100644 --- a/matsim/src/test/java/org/matsim/pt/transitSchedule/MinimalTransferTimesImplTest.java +++ b/matsim/src/test/java/org/matsim/pt/transitSchedule/MinimalTransferTimesImplTest.java @@ -32,11 +32,10 @@ */ public class MinimalTransferTimesImplTest { - private Id stopId1 = Id.create(1, TransitStopFacility.class); - private Id stopId2 = Id.create(2, TransitStopFacility.class); - private Id stopId3 = Id.create(3, TransitStopFacility.class); - private Id stopId4 = Id.create(4, TransitStopFacility.class); - private Id stopId5 = Id.create(5, TransitStopFacility.class); + private final Id stopId1 = Id.create(1, TransitStopFacility.class); + private final Id stopId2 = Id.create(2, TransitStopFacility.class); + private final Id stopId3 = Id.create(3, TransitStopFacility.class); + private final Id stopId4 = Id.create(4, TransitStopFacility.class); @Test void testSetGet() { @@ -55,6 +54,19 @@ void testSetGet() { Assertions.assertEquals(Double.NaN, mtt.get(this.stopId1, this.stopId4), 0.0); } + @Test + void testGetNonSetConnection() { + MinimalTransferTimes mtt = new MinimalTransferTimesImpl(); + mtt.set(this.stopId1, this.stopId1, 300.0); + mtt.set(this.stopId3, this.stopId3, 240.0); + + Assertions.assertEquals(300.0, mtt.get(this.stopId1, this.stopId1), 0.0); + Assertions.assertEquals(240.0, mtt.get(this.stopId3, this.stopId3), 0.0); + + Assertions.assertEquals(300.0, mtt.get(this.stopId1, this.stopId3), 0.0); + + } + @Test void testGetWithDefault() { MinimalTransferTimes mtt = new MinimalTransferTimesImpl(); @@ -259,4 +271,4 @@ void testIterator_withRemove() { iter = mtt.iterator(); Assertions.assertFalse(iter.hasNext()); } -} \ No newline at end of file +} diff --git a/matsim/src/test/java/org/matsim/pt/transitSchedule/TransitScheduleIOTest.java b/matsim/src/test/java/org/matsim/pt/transitSchedule/TransitScheduleIOTest.java index 8b4f9688a6d..87995007deb 100644 --- a/matsim/src/test/java/org/matsim/pt/transitSchedule/TransitScheduleIOTest.java +++ b/matsim/src/test/java/org/matsim/pt/transitSchedule/TransitScheduleIOTest.java @@ -68,7 +68,6 @@ void testWriteRead_V2() { schedule.getMinimalTransferTimes().set(stop1.getId(), stop2.getId(), 300.0); schedule.getMinimalTransferTimes().set(stop2.getId(), stop1.getId(), 360.0); -; TransitLine line1 = f.createTransitLine(Id.create("blue", TransitLine.class)); line1.getAttributes().putAttribute("color", "like the sky"); line1.getAttributes().putAttribute("operator", "higher being"); diff --git a/matsim/src/test/java/org/matsim/pt/transitSchedule/TransitScheduleReprojectionIOTest.java b/matsim/src/test/java/org/matsim/pt/transitSchedule/TransitScheduleReprojectionIOTest.java index 4be9bbe91fb..9cf7abf7f5e 100644 --- a/matsim/src/test/java/org/matsim/pt/transitSchedule/TransitScheduleReprojectionIOTest.java +++ b/matsim/src/test/java/org/matsim/pt/transitSchedule/TransitScheduleReprojectionIOTest.java @@ -39,7 +39,6 @@ import org.matsim.core.utils.geometry.transformations.TransformationFactory; import org.matsim.core.utils.io.IOUtils; import org.matsim.examples.ExamplesUtils; -import org.matsim.pt.config.TransitConfigGroup.TransitRoutingAlgorithmType; import org.matsim.pt.transitSchedule.api.TransitSchedule; import org.matsim.pt.transitSchedule.api.TransitScheduleReader; import org.matsim.pt.transitSchedule.api.TransitScheduleWriter; diff --git a/matsim/src/test/java/org/matsim/testcases/MatsimTestUtils.java b/matsim/src/test/java/org/matsim/testcases/MatsimTestUtils.java index 8b34bea7c10..87696593899 100644 --- a/matsim/src/test/java/org/matsim/testcases/MatsimTestUtils.java +++ b/matsim/src/test/java/org/matsim/testcases/MatsimTestUtils.java @@ -41,8 +41,6 @@ import java.net.MalformedURLException; import java.net.URL; import java.util.Objects; -import java.util.regex.Matcher; -import java.util.regex.Pattern; /** * Some helper methods for writing JUnit 5 tests in MATSim. @@ -80,13 +78,6 @@ public final class MatsimTestUtils implements BeforeEachCallback, AfterEachCallb private Class testClass = null; private String testMethodName = null; - private String testParameterSetIndex = null; - - //captures the method name (group 1) and optionally the index of the parameter set (group 2; only if the test is parametrised) - //The matching may fail if the parameter set name does not start with {index} (at least one digit is required at the beginning) - private static final Pattern METHOD_PARAMETERS_WITH_INDEX_PATTERN = Pattern.compile( - "([\\S]*)(?:\\[(\\d+)[\\s\\S]*\\])?"); - public MatsimTestUtils() { MatsimRandom.reset(); @@ -95,13 +86,7 @@ public MatsimTestUtils() { @Override public void beforeEach(ExtensionContext extensionContext) { this.testClass = extensionContext.getTestClass().orElseThrow(); - - Matcher matcher = METHOD_PARAMETERS_WITH_INDEX_PATTERN.matcher(extensionContext.getTestMethod().orElseThrow().getName()); - if (!matcher.matches()) { - throw new RuntimeException("The name of the test parameter set must start with {index}"); - } - this.testMethodName = matcher.group(1); - this.testParameterSetIndex = matcher.group(2); // null for non-parametrised tests + this.testMethodName = extensionContext.getRequiredTestMethod().getName(); } @Override @@ -232,10 +217,12 @@ private void createOutputDirectory() { * @return path to the output directory for this test */ public String getOutputDirectory() { + return getOutputDirectory(""); + } + + public String getOutputDirectory(String subDir) { if (this.outputDirectory == null) { - String subDirectoryForParametrisedTests = testParameterSetIndex == null ? "" : testParameterSetIndex + "/"; - this.outputDirectory = "test/output/" + this.testClass.getCanonicalName().replace('.', '/') + "/" + getMethodName()+ "/" - + subDirectoryForParametrisedTests; + this.outputDirectory = "test/output/" + this.testClass.getCanonicalName().replace('.', '/') + "/" + getMethodName()+ "/" + subDir; } createOutputDirectory(); return this.outputDirectory; diff --git a/matsim/src/test/java/org/matsim/testcases/fakes/FakeLink.java b/matsim/src/test/java/org/matsim/testcases/fakes/FakeLink.java index 24928f85cef..5e83743fbf3 100644 --- a/matsim/src/test/java/org/matsim/testcases/fakes/FakeLink.java +++ b/matsim/src/test/java/org/matsim/testcases/fakes/FakeLink.java @@ -28,7 +28,6 @@ import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Node; -import org.matsim.core.utils.misc.Time; import org.matsim.utils.objectattributes.attributable.Attributes; /** diff --git a/matsim/src/test/java/org/matsim/utils/objectattributes/attributeconverters/StringCollectionConverterTest.java b/matsim/src/test/java/org/matsim/utils/objectattributes/attributeconverters/StringCollectionConverterTest.java index bdaa3ee6977..21556113b88 100644 --- a/matsim/src/test/java/org/matsim/utils/objectattributes/attributeconverters/StringCollectionConverterTest.java +++ b/matsim/src/test/java/org/matsim/utils/objectattributes/attributeconverters/StringCollectionConverterTest.java @@ -1,7 +1,6 @@ package org.matsim.utils.objectattributes.attributeconverters; import java.util.Collection; -import java.util.Map; import org.junit.jupiter.api.Test; @@ -19,4 +18,4 @@ void test() { assertEquals(expectedString, serializedString); } -} \ No newline at end of file +} diff --git a/matsim/src/test/java/org/matsim/vehicles/VehicleReaderV2Test.java b/matsim/src/test/java/org/matsim/vehicles/VehicleReaderV2Test.java index 30547c26436..22b4d78b3c4 100644 --- a/matsim/src/test/java/org/matsim/vehicles/VehicleReaderV2Test.java +++ b/matsim/src/test/java/org/matsim/vehicles/VehicleReaderV2Test.java @@ -116,7 +116,6 @@ void test_VehicleTypeValuesAreReadCorrectly_normalCar() { assertNotNull(vehTypeNormalCar.getEngineInformation()); EngineInformation engineInformation = vehTypeNormalCar.getEngineInformation(); - ; assertEquals("pass. car", VehicleUtils.getHbefaVehicleCategory(engineInformation)); assertEquals("petrol", VehicleUtils.getHbefaTechnology(engineInformation)); assertEquals("< 1,4L", VehicleUtils.getHbefaSizeClass(engineInformation)); diff --git a/matsim/src/test/java/org/matsim/vehicles/VehicleWriterV2Test.java b/matsim/src/test/java/org/matsim/vehicles/VehicleWriterV2Test.java index 1bd89738340..2cc85902283 100644 --- a/matsim/src/test/java/org/matsim/vehicles/VehicleWriterV2Test.java +++ b/matsim/src/test/java/org/matsim/vehicles/VehicleWriterV2Test.java @@ -111,7 +111,6 @@ void test_VehicleTypeValuesAreReadCorrectly_normalCar() { assertNotNull(vehTypeNormalCar.getEngineInformation()); EngineInformation engineInformation = vehTypeNormalCar.getEngineInformation(); - ; assertEquals("pass. car", VehicleUtils.getHbefaVehicleCategory(engineInformation)); assertEquals("petrol", VehicleUtils.getHbefaTechnology(engineInformation)); assertEquals("< 1,4L", VehicleUtils.getHbefaSizeClass(engineInformation)); diff --git a/pom.xml b/pom.xml index a31598d97b7..eb2534176cc 100644 --- a/pom.xml +++ b/pom.xml @@ -30,12 +30,12 @@ 17 - 2.22.0 + 2.22.1 29.2 0.49.2 1.19.0 7.0.0 - 2.16.0 + 2.16.1 2.5.0 5.10.1 @@ -103,7 +103,7 @@ com.google.guava guava - 32.1.3-jre + 33.0.0-jre org.apache.commons @@ -195,7 +195,7 @@ com.google.errorprone error_prone_annotations - 2.23.0 + 2.24.1 @@ -232,7 +232,7 @@ org.slf4j slf4j-api - 2.0.9 + 2.0.11 @@ -286,7 +286,7 @@ org.checkerframework checker-qual - 3.41.0 + 3.42.0 @@ -304,7 +304,7 @@ org.assertj assertj-core - 3.24.2 + 3.25.1 test @@ -342,7 +342,7 @@ net.bytebuddy byte-buddy - 1.14.10 + 1.14.11 test @@ -354,7 +354,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.11.0 + 3.12.1 org.apache.maven.plugins @@ -400,12 +400,12 @@ org.apache.maven.plugins maven-surefire-plugin - 3.2.3 + 3.2.5 org.apache.maven.plugins maven-failsafe-plugin - 3.2.3 + 3.2.5 org.apache.maven.plugins